Themes¶
Palettes, fonts and role styles; see the Themes guide. svg.Theme and
svg.themes are also available at the top level; every registry works like svg.Registry.
Themes: palettes, fonts and role styles that documents apply as CSS classes.
A Theme is immutable. Elements opt in with element.as_role("box"); a document writes one
<style> rule per role it uses, so the SVG stays portable and can be restyled by swapping the sheet.
Built-in themes are light (the default), dark, paper, print, mono, noir, brutalist,
dracula, alucard, one-dark and one-light.
- class Fonts(family: Family = 'Helvetica, Arial, sans-serif', monospace: Family = 'Consolas, Menlo, monospace', sizes: Mapping[str, float]=<factory>, weights: Mapping[str, int]=<factory>)[source]¶
Bases:
objectFont families, named sizes (user units) and named weights.
- Parameters:
family (str or Typeface, optional) – CSS
font-familyof ordinary text, or aTypeface(registered for rendering, embeddable withDocument.embed_fonts). Defaults to a sans-serif stack.monospace (str or Typeface, optional) – CSS
font-familyof code, or a typeface. Defaults to a monospace stack.sizes (mapping of str to float, optional) – Named font sizes such as
"text"and"title". Defaults to text 14, title 24, subtitle 18 and caption 11.weights (mapping of str to int, optional) – Named weights such as
"regular"and"bold". Defaults to 400 and 700.
See also
ThemeUses these values in its text roles.
Examples
>>> from svgwriter.model.theme import Fonts >>> fonts = Fonts().replace(sizes={"title": 30}) >>> fonts.sizes["title"], fonts.sizes["text"] (30, 14.0) >>> fonts.lookup("weights.bold") 700
- family: Family = 'Helvetica, Arial, sans-serif'¶
- monospace: Family = 'Consolas, Menlo, monospace'¶
- replace(*, family: Family | None = None, monospace: Family | None = None, sizes: Mapping[str, float] | None = None, weights: Mapping[str, int] | None = None) Fonts[source]¶
A copy with some values replaced;
sizesandweightsmerge by name.- Parameters:
family (str or Typeface, optional) – New families. Defaults to None, which keeps the current ones.
monospace (str or Typeface, optional) – New families. Defaults to None, which keeps the current ones.
sizes (mapping, optional) – Entries to replace or add. Defaults to None.
weights (mapping, optional) – Entries to replace or add. Defaults to None.
- Returns:
Fonts – The merged fonts.
Examples
>>> from svgwriter.model.theme import Fonts >>> Fonts().replace(family="Georgia, serif").family 'Georgia, serif'
- lookup(path: str) str | float | int[source]¶
The value at a dotted path:
family,monospace,sizes.<name>orweights.<name>.- Parameters:
path (str) – The path below
fonts.- Returns:
str or float or int – The value.
- Raises:
ThemeError – If the path names nothing.
Examples
>>> from svgwriter.model.theme import Fonts >>> Fonts().lookup("sizes.caption") 11.0
- to_dict() dict[str, object][source]¶
The fonts as plain data, as written to theme files.
- Returns:
dict –
family,monospace,sizesandweights; a typeface loaded from files is written as the list of its files.
Examples
>>> from svgwriter.model.theme import Fonts >>> sorted(Fonts().to_dict()) ['family', 'monospace', 'sizes', 'weights']
- class Palette(sources: Mapping[str, Color | str | Sequence[float] | Callable[[Palette], Color | str | Sequence[float]]])[source]¶
-
Immutable color roles, resolved once from literals, references, expressions and functions.
- Parameters:
sources (mapping of str to color or str or callable) – Each role’s source: a color (
"#0f766e","navy", aColor), a reference to another role written"{palette.name}", an expression marked with a leading=such as"=lighten({palette.primary}, 0.2)"(see the Themes guide), or a function that receives this palette and returns a color (lambda p: p.foreground.mix(p.background, 0.3)).- Raises:
ThemeError – If a reference names a missing role, references form a cycle or nest too deeply, an expression is malformed, or a value is not a color.
See also
ThemeCombines a palette with fonts and role styles.
Notes
Sources are kept, so
replace()derives again: replacingforegroundalso changes every role computed from it. Roles read as attributes (palette.primary) or keys.Examples
>>> from svgwriter.model.theme import Palette >>> p = Palette({"ink": "#000000", "paper": "white", "line": lambda p: p.ink.mix(p.paper, 0.5)}) >>> p.line.hex '#808080' >>> p.replace(ink="#ff0000").line.hex '#ff8080' >>> Palette({"ink": "navy", "label": "=readable({palette.ink})"}).label.hex '#ffffff'
- property sources: Mapping[str, Color | str | Sequence[float] | Callable[[Palette], Color | str | Sequence[float]]]¶
literals, references and functions.
Examples
>>> from svgwriter.model.theme import Palette >>> Palette({"a": "red", "b": "{palette.a}"}).sources["b"] '{palette.a}'
- Type:
Each role’s source as given
- replace(**sources: Color | str | Sequence[float] | Callable[[Palette], Color | str | Sequence[float]]) Palette[source]¶
A new palette with some sources replaced or added; derived roles follow.
- Parameters:
**sources (color or str or callable) – The roles to replace or add, by name.
- Returns:
Palette – The merged palette.
Examples
>>> from svgwriter.model.theme import Palette >>> Palette({"a": "red", "b": "{palette.a}"}).replace(a="blue").b.hex '#0000ff'
- class Theme(name: str, palette: Palette | Mapping[str, PaletteSource], fonts: Fonts | None = None, roles: Mapping[str, RoleSource] | None = None)[source]¶
Bases:
ThemeFilesColors, fonts and the styles of named roles, applied to documents as CSS classes.
- Parameters:
name (str) – A short name, used by
get()once registered and written to theme files.palette (Palette or mapping) – Color roles (see
Palette).border,mutedandshadoware derived fromforegroundandbackground, andon_primaryfromprimary, unless given.fonts (Fonts, optional) – Families, sizes and weights. Defaults to
Fonts().roles (mapping of str to style or callable, optional) – Extra or replaced role styles, merged over the standard roles. Each is a mapping of CSS properties (values may be literals,
"{palette.name}"/"{fonts.sizes.name}"references, expressions such as"={fonts.sizes.text} * 1.5"or functions of the theme) or a function of the theme returning one. Defaults to None.
- Raises:
ThemeError – If a role name is invalid or anything cannot be resolved.
See also
svgwriter.DocumentTakes
theme=; elements opt in withas_role.
Notes
A theme never changes.
replace()builds variants, andwith theme:makes it the default for documents created in the block (a context variable, so threads and tasks stay separate). Outside any block the default is the registered"light"theme.Examples
>>> import svgwriter as svg >>> dark = svg.themes.get("dark") >>> dark.style("box")["fill"].hex '#1f2937' >>> brand = dark.replace(name="brand", palette={"primary": "#ff6600"}) >>> brand.style("shape")["fill"].hex '#ff6600' >>> with brand: ... svg.Document(10, 10).theme.name 'brand'
- property extends: str | None¶
The registered theme this one is a variant of, or None; files write it as
extends.Examples
>>> import svgwriter as svg >>> svg.themes.get("dark").replace(name="night").extends 'dark' >>> svg.themes.get("dark").extends is None True
- property roles: Mapping[str, Style | Mapping[str, object] | str | Callable[[Theme], Style | Mapping[str, object] | str]]¶
Every role’s source, standard roles included, as given.
- style(role: str) Style[source]¶
The resolved style of role (a copy).
- Parameters:
role (str) – The role name, such as
"box"or"arrow.head".- Returns:
Style – CSS declarations with colors resolved.
- Raises:
ThemeError – If the theme has no such role.
Examples
>>> import svgwriter as svg >>> str(svg.themes.get("light").style("line")) 'fill:none;stroke:#0f766e;stroke-width:2px'
- static class_name(role: str) str[source]¶
The CSS class that marks elements of role:
role-plus the name with dots as dashes.- Parameters:
role (str) – The role name.
- Returns:
str – The class name.
Examples
>>> import svgwriter as svg >>> svg.Theme.class_name("arrow.head") 'role-arrow-head'
- css(roles: Iterable[str] | None = None) StyleSheet[source]¶
A style sheet with one
.role-<name>rule per role.- Parameters:
roles (iterable of str, optional) – The roles to include, in theme order. Defaults to None, which includes every role.
- Returns:
StyleSheet – The rules.
- Raises:
ThemeError – If a requested role is not in the theme.
Examples
>>> import svgwriter as svg >>> svg.themes.get("mono").css(["dot"]).css() '.role-dot { fill:#000000;stroke:#000000;stroke-width:1px }'
- attributes(role: str) dict[str, str][source]¶
The geometry a role sets as attributes (
rx,ry,r); SVG 1.1 CSS cannot style them.- Parameters:
role (str) – The role name.
- Returns:
dict of str to str – Attribute names and values; empty when the role sets no geometry.
- Raises:
ThemeError – If the theme has no such role.
Examples
>>> import svgwriter as svg >>> svg.themes.get("light").replace(roles={"card": {"rx": "6"}}).attributes("card") {'rx': '6'}
- replace(*, name: str | None = None, palette: Mapping[str, PaletteSource] | None = None, fonts: Fonts | Mapping[str, Any] | None = None, roles: Mapping[str, RoleSource] | None = None) Theme[source]¶
A variant: palette entries, font values and role properties merge into this theme’s.
A variant of a registered theme extends it; a variant of anything else keeps what that theme extends and the file it was read from, so
save()writes only what changed.- Parameters:
name (str, optional) – The variant’s name. Defaults to None, which keeps this name.
palette (mapping, optional) – Palette sources to replace or add; derived roles follow. Defaults to None.
fonts (Fonts or mapping, optional) – A whole
Fonts, or keywords ofFonts.replace(). Defaults to None.roles (mapping, optional) – Role sources; a mapping merges property by property into the existing role, a function replaces it. Defaults to None.
- Returns:
Theme – The new theme.
Examples
>>> import svgwriter as svg >>> light = svg.themes.get("light") >>> bold = light.replace(roles={"line": {"stroke-width": 4}}, fonts={"sizes": {"text": 16}}) >>> str(bold.style("line")), bold.fonts.sizes["text"] ('fill:none;stroke:#0f766e;stroke-width:4px', 16)
- static current() Theme[source]¶
The theme in effect: the innermost
with theme:block, else"light".- Returns:
Theme – The theme new documents use.
Examples
>>> import svgwriter as svg >>> svg.Theme.current().name 'light' >>> with svg.themes.get("dark"): ... svg.Theme.current().name 'dark'
The theme <style> sheet of a tree: the roles it uses and the sheet written while it is output.
- applied(theme: Theme, root: Element) Generator[None, None, None][source]¶
Hold the theme sheet in root for the duration of the block.
The sheet is a
<style id="svgwriter-theme">with rules for the roles in use. An existing one (from a parsed file) has its text replaced; otherwise one is inserted at the top. The tree is restored on exit. Nothing is written when no role is used and no sheet exists.Examples
>>> import svgwriter as svg >>> from svgwriter.model.theme.sheet import applied >>> root = svg.Svg(svg.circle(0, 0, 1).as_role("dot")) >>> with applied(svg.themes.get("mono"), root): ... root[0].css '.role-dot { fill:#000000;stroke:#000000;stroke-width:1px }' >>> len(root) 1
- role_rules(theme: Theme) dict[str, list[Rule]][source]¶
The theme’s role styles as parsed style rules, by the class name each one matches.
A document attaches them to its root, so styles looked up before output (layout measuring text,
computed) see the theme the output will write.- Parameters:
theme (Theme) – The theme.
- Returns:
dict of str to list of Rule – The rules of each
role-class.
Examples
>>> import svgwriter as svg >>> from svgwriter.model.theme.sheet import role_rules >>> role_rules(svg.themes.get("mono"))["role-dot"][0].declarations[0] ('fill', '#000000', False)
- sheet_theme(root: Element) Theme | None[source]¶
The theme that wrote the theme sheet of a parsed tree, so reopening a file keeps its look.
A registered theme that writes exactly that sheet is returned; otherwise the current theme with the sheet’s role styles, named
"document".- Parameters:
root (Element) – The root
<svg>.- Returns:
Theme or None – The theme, or None when the tree has no theme sheet.
Examples
>>> import svgwriter as svg >>> from svgwriter.model.theme.sheet import sheet_theme >>> doc = svg.Document(10, 10, theme="dark") >>> _ = doc.circle(5, 5, 2).as_role("dot") >>> sheet_theme(svg.parse(doc.to_string())).name 'dark' >>> sheet_theme(svg.Svg()) is None True
- used_roles(theme: Theme, root: Element) list[str][source]¶
The roles of theme that elements under root carry, in theme order.
- Parameters:
- Returns:
list of str – Role names.
- Raises:
ThemeError – If an element carries a
role-class that the theme does not define.
Examples
>>> import svgwriter as svg >>> from svgwriter.model.theme.sheet import used_roles >>> g = svg.group(svg.circle(0, 0, 1).as_role("dot"), svg.rect(0, 0, 1, 1).as_role("box")) >>> used_roles(svg.themes.get("light"), g) ['box', 'dot']