Skip to content

Theme

The palette the workbench paints plotly, pyvista, xterm and Monaco with, the colormap catalogue its pickers offer, and the render settings every 3D view draws with.

femforge_workbench.theme

The palette read from the dist's theme.json, painting plotly, pyvista, xterm and Monaco in the stylesheet's colours.

Classes:

  • Token –

    The stylesheet tokens the palette reads.

  • Section –

    The sections of theme.json.

  • Font –

    The font stacks theme.json names.

  • Tokens –

    What theme.json carries: the colours, the metrics in CSS pixels and the font stacks.

  • Metrics –

    The type sizes and chrome heights of the stylesheet, in CSS pixels.

  • Tones –

    The interaction colours derived from a palette, as hex.

  • Palette –

    The colours the panels share, read from the tokens.

Functions:

  • rgb –

    The channels of a CSS colour written as a hex triplet, rgb()/rgba(), or white/black.

  • hex_color –

    The colour as an upper-case hex triplet, the form pyvista takes.

  • mix –

    The hex colour fraction of the way from onto to color.

  • luminance –

    The perceived brightness of a colour on the 0-255 scale.

  • rotate_hue –

    The colour with its hue rotated by a fraction of the wheel, as a hex triplet.

  • template_json –

    A registered plotly template (the default when unnamed) as plain JSON.

  • section –

    The nested object under key, empty when absent.

  • text –

    The string under key, else the fallback.

  • load_tokens –

    The tokens of the built dist; a missing dist names the build command.

Token

Bases: StrEnum

The stylesheet tokens the palette reads.

Section

Bases: StrEnum

The sections of theme.json.

Font

Bases: StrEnum

The font stacks theme.json names.

Tokens dataclass

Tokens(colors: Mapping[str, str], metrics: Mapping[str, float], fonts: Mapping[str, str])

What theme.json carries: the colours, the metrics in CSS pixels and the font stacks.

Methods:

  • from_json –

    Reads the tokens from theme.json's document.

from_json classmethod

from_json(document: Mapping[str, object]) -> Tokens

Reads the tokens from theme.json's document.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
@classmethod
def from_json(cls, document: Mapping[str, object]) -> "Tokens":
    """Reads the tokens from theme.json's document."""
    colors = {name: str(value) for name, value in section(document, Section.COLORS).items()}
    metrics = {name: float(cast("float", value)) for name, value in section(document, Section.METRICS).items()}
    fonts = {name: str(value) for name, value in section(document, Section.FONTS).items()}

    return cls(colors=colors, metrics=metrics, fonts=fonts)

Metrics dataclass

Metrics(size_body: float, size_label: float, bar_height: float, tab_height: float, space: float, row_height: float)

The type sizes and chrome heights of the stylesheet, in CSS pixels.

Methods:

  • from_tokens –

    Reads the metrics from the tokens, which name each field in kebab case.

from_tokens classmethod

from_tokens(tokens: Tokens) -> Metrics

Reads the metrics from the tokens, which name each field in kebab case.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
@classmethod
def from_tokens(cls, tokens: Tokens) -> "Metrics":
    """Reads the metrics from the tokens, which name each field in kebab case."""
    return cls(**{field.name: tokens.metrics[field.name.replace("_", "-")] for field in fields(cls)})

Tones dataclass

Tones(raised: str, on_accent: str)

The interaction colours derived from a palette, as hex.

Palette dataclass

Palette(paper: str, plot: str, text: str, grid: str, accent: str, muted: str, chart: tuple[str, ...], metrics: Metrics, font: str, mono: str)

The colours the panels share, read from the tokens.

Methods:

  • from_tokens –

    The palette of the tokens.

  • load –

    The dist's palette.

  • with_accent –

    The dist's palette with an accent of the caller's own.

  • colorway –

    The chart colours, then hues rotated evenly from the accent for the rest.

  • tones –

    The derived interaction colours: a raised surface and text that reads on the accent.

  • plotly_template –

    The base template, plotly_dark by default, repainted in this palette, at the label size, with the top margin a titleless figure needs.

  • install –

    Registers this palette's plotly template as the default, so every figure built afterwards is painted in it.

  • xterm_theme –

    The xterm ITheme colours.

from_tokens classmethod

from_tokens(tokens: Tokens) -> Palette

The palette of the tokens.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
@classmethod
def from_tokens(cls, tokens: Tokens) -> "Palette":
    """The palette of the tokens."""
    colors = tokens.colors

    return cls(
        paper=colors[Token.BACKGROUND],
        plot=colors[Token.CARD],
        text=colors[Token.FOREGROUND],
        grid=colors[Token.BORDER],
        accent=colors[Token.PRIMARY],
        muted=colors[Token.MUTED_FOREGROUND],
        chart=tuple(colors[token] for token in CHART_TOKENS),
        metrics=Metrics.from_tokens(tokens),
        font=tokens.fonts[Font.SANS],
        mono=tokens.fonts[Font.MONO],
    )

load classmethod

load() -> Palette

The dist's palette.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
@classmethod
def load(cls) -> "Palette":
    """The dist's palette."""
    return cls.from_tokens(load_tokens())

with_accent classmethod

with_accent(accent: str) -> Palette

The dist's palette with an accent of the caller's own.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
@classmethod
def with_accent(cls, accent: str) -> "Palette":
    """The dist's palette with an accent of the caller's own."""
    return replace(cls.load(), accent=accent)

colorway

colorway(count: int = 6) -> list[str]

The chart colours, then hues rotated evenly from the accent for the rest.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def colorway(self, count: int = 6) -> list[str]:
    """The chart colours, then hues rotated evenly from the accent for the rest."""
    listed = list(self.chart[:count])
    extra = count - len(listed)

    return [*listed, *(rotate_hue(self.accent, (i + 1) / (extra + 1)) for i in range(extra))]

tones

tones() -> Tones

The derived interaction colours: a raised surface and text that reads on the accent.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def tones(self) -> Tones:
    """The derived interaction colours: a raised surface and text that reads on the accent."""
    on_accent = self.paper if luminance(self.accent) >= DARK_BELOW else self.text

    return Tones(raised=mix(self.text, self.paper, 0.12), on_accent=hex_color(on_accent))

plotly_template

plotly_template(base: str | None = None) -> Json

The base template, plotly_dark by default, repainted in this palette, at the label size, with the top margin a titleless figure needs.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def plotly_template(self, base: str | None = None) -> Json:
    """The base template, plotly_dark by default, repainted in this palette, at the label size, with the top margin a titleless figure needs."""
    template = template_json(base or "plotly_dark")
    layout = section(template, "layout")
    axis_paint = {"gridcolor": self.grid, "zerolinecolor": self.grid, "linecolor": self.grid}
    repainted: Json = {
        **layout,
        "paper_bgcolor": self.paper,
        "plot_bgcolor": self.plot,
        "font": {**section(layout, "font"), "color": self.text, "family": self.font, "size": self.metrics.size_label},
        "colorway": self.colorway(),
        "margin": {**section(layout, "margin"), "t": TITLELESS_TOP_MARGIN},
        "xaxis": {**section(layout, "xaxis"), **axis_paint},
        "yaxis": {**section(layout, "yaxis"), **axis_paint},
    }

    return {**template, "layout": repainted}

install

install() -> None

Registers this palette's plotly template as the default, so every figure built afterwards is painted in it.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def install(self) -> None:
    """Registers this palette's plotly template as the default, so every figure built afterwards is painted in it."""
    pio.templates[TEMPLATE] = self.plotly_template()  # pyright: ignore[reportUnknownMemberType]  # plotly's template registry ships no stub
    pio.templates.default = TEMPLATE  # pyright: ignore[reportUnknownMemberType]

xterm_theme

xterm_theme() -> dict[str, str]

The xterm ITheme colours.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def xterm_theme(self) -> dict[str, str]:
    """The xterm ITheme colours."""
    return {"background": self.paper, "foreground": self.text, "cursor": self.accent, "selectionBackground": self.tones().raised}

rgb

rgb(color: str) -> tuple[int, int, int]

The channels of a CSS colour written as a hex triplet, rgb()/rgba(), or white/black.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def rgb(color: str) -> tuple[int, int, int]:
    """The channels of a CSS colour written as a hex triplet, rgb()/rgba(), or white/black."""
    color = color.strip().lower()
    if color in NAMED_COLORS:
        return NAMED_COLORS[color]

    if color.startswith("#"):
        digits = color[1:]
        if len(digits) == 3:
            digits = "".join(ch * 2 for ch in digits)

        return int(digits[0:2], 16), int(digits[2:4], 16), int(digits[4:6], 16)

    numbers: list[str] = re.findall(r"[\d.]+", color)
    r, g, b = (int(float(n)) for n in numbers[:3])

    return r, g, b

hex_color

hex_color(color: str) -> str

The colour as an upper-case hex triplet, the form pyvista takes.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def hex_color(color: str) -> str:
    """The colour as an upper-case hex triplet, the form pyvista takes."""
    red, green, blue = rgb(color)

    return f"#{red:02X}{green:02X}{blue:02X}"

mix

mix(color: str, onto: str, fraction: float) -> str

The hex colour fraction of the way from onto to color.

Parameters:

  • color (str) –

    The colour at a fraction of 1.

  • onto (str) –

    The colour at a fraction of 0.

  • fraction (float) –

    How far from onto toward color, from 0 to 1.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def mix(color: str, onto: str, fraction: float) -> str:
    """The hex colour `fraction` of the way from `onto` to `color`.

    Args:
        color: The colour at a fraction of 1.
        onto: The colour at a fraction of 0.
        fraction: How far from `onto` toward `color`, from 0 to 1.
    """
    channels = [round(a * fraction + b * (1 - fraction)) for a, b in zip(rgb(color), rgb(onto), strict=True)]

    return "#" + "".join(f"{channel:02X}" for channel in channels)

luminance

luminance(color: str) -> float

The perceived brightness of a colour on the 0-255 scale.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def luminance(color: str) -> float:
    """The perceived brightness of a colour on the 0-255 scale."""
    r, g, b = rgb(color)

    return 0.299 * r + 0.587 * g + 0.114 * b

rotate_hue

rotate_hue(color: str, turns: float) -> str

The colour with its hue rotated by a fraction of the wheel, as a hex triplet.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def rotate_hue(color: str, turns: float) -> str:
    """The colour with its hue rotated by a fraction of the wheel, as a hex triplet."""
    r, g, b = rgb(color)
    hue, lightness, saturation = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)
    r, g, b = colorsys.hls_to_rgb((hue + turns) % 1, lightness, saturation)

    return f"#{round(r * 255):02X}{round(g * 255):02X}{round(b * 255):02X}"

template_json

template_json(name: str | None = None) -> Json

A registered plotly template (the default when unnamed) as plain JSON.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def template_json(name: str | None = None) -> Json:
    """A registered plotly template (the default when unnamed) as plain JSON."""
    key = name or str(pio.templates.default)  # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType]  # plotly's template registry ships no stub

    return cast("Json", pio.templates[key].to_plotly_json())  # pyright: ignore[reportUnknownMemberType]

section

section(source: Mapping[str, object], key: str) -> Json

The nested object under key, empty when absent.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def section(source: Mapping[str, object], key: str) -> Json:
    """The nested object under `key`, empty when absent."""
    value = source.get(key)
    if not isinstance(value, Mapping):
        return {}

    return dict(cast("Mapping[str, object]", value))

text

text(source: Mapping[str, object], key: str, fallback: str) -> str

The string under key, else the fallback.

Parameters:

  • source (Mapping[str, object]) –

    The JSON object to read.

  • key (str) –

    The key to read.

  • fallback (str) –

    The string returned when the value is missing or not a string.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
def text(source: Mapping[str, object], key: str, fallback: str) -> str:
    """The string under `key`, else the fallback.

    Args:
        source: The JSON object to read.
        key: The key to read.
        fallback: The string returned when the value is missing or not a string.
    """
    value = source.get(key)
    if not isinstance(value, str):
        return fallback

    return value

load_tokens cached

load_tokens() -> Tokens

The tokens of the built dist; a missing dist names the build command.

Source code in packages/femforge-workbench/src/femforge_workbench/theme.py
@cache
def load_tokens() -> Tokens:
    """The tokens of the built dist; a missing dist names the build command."""
    path = SERVE_DIR / THEME_FILE
    if not path.exists():
        raise FileNotFoundError(f"{path} is missing: {BUILD_HINT}")

    return Tokens.from_json(cast("Mapping[str, object]", json.loads(path.read_text(encoding="utf-8"))))

femforge_workbench.colormaps

The colormap catalogue the field viewer's pickers offer, by type, with the favorites listed first.

Classes:

  • ColormapType –

    Enumeration of colormap types.

  • Colormap –

    One catalogue entry: its type, the name pyvista resolves and the sentence-case label the pickers show.

Attributes:

  • FAVORITES (tuple[str, ...]) –

    Suggested starting maps, listed first in the colormap pickers.

FAVORITES module-attribute

FAVORITES: tuple[str, ...] = ('viridis', 'haline', 'batlow', 'inferno', 'Black-Body Radiation', 'coolwarm', 'vik', 'Fast', 'turbo')

Suggested starting maps, listed first in the colormap pickers.

ColormapType

Bases: Enum

Enumeration of colormap types.

Colormap

Bases: NamedTuple

One catalogue entry: its type, the name pyvista resolves and the sentence-case label the pickers show.

femforge_workbench.render

The render settings every 3D view shares, persisted once per user across workbenches.

Classes:

  • Antialias –

    How a renderer smooths the edges it draws.

  • Lighting –

    The lights a renderer places.

  • Projection –

    How the camera projects the scene.

  • ToneMapping –

    How the stream maps the rendered light onto the screen's range.

  • RenderSettings –

    How every 3D view draws: its antialiasing per renderer, its lights, shading, camera, tone mapping and lines.

  • RenderVar –

    The shell's state variables of the render settings, one per field, named PREFIX and the field; a slider's holds its one thumb in a list.

Functions:

  • limits –

    The lowest and highest value a slider's setting validates.

  • render_state –

    The state variables showing settings.

  • settings_from_state –

    The settings the state variables show; None when they do not validate.

  • load_render –

    The user's saved render settings; the defaults when none are saved or the saved ones no longer validate.

  • save_render –

    Saves the user's render settings for every workbench.

Attributes:

SHARED module-attribute

SHARED = '_shared'

The workbench name of the documents every workbench of a user reads.

RENDER_KEY module-attribute

RENDER_KEY = 'render'

The persisted document of the render settings.

PREFIX module-attribute

PREFIX = 'render_'

What every render setting's state variable starts with, before its field name.

CLIENT_ANTIALIAS module-attribute

CLIENT_ANTIALIAS: tuple[Antialias, ...] = (Antialias.OFF, Antialias.FXAA, Antialias.SSAA)

What the mirror can draw: VTK.wasm ignores the window's multisamples.

SERVER_ANTIALIAS module-attribute

SERVER_ANTIALIAS: tuple[Antialias, ...] = tuple(Antialias)

What the stream can draw.

SLIDERS module-attribute

SLIDERS: tuple[RenderVar, ...] = tuple(var for var in RenderVar if RenderSettings.model_fields[var.field].annotation is float)

The settings a slider sets, which apply on its release.

CHOICES module-attribute

CHOICES: tuple[RenderVar, ...] = tuple(var for var in RenderVar if var not in SLIDERS)

The settings a toggle or a switch sets, which apply at once.

Antialias

Bases: StrEnum

How a renderer smooths the edges it draws.

Lighting

Bases: StrEnum

The lights a renderer places.

Projection

Bases: StrEnum

How the camera projects the scene.

ToneMapping

Bases: StrEnum

How the stream maps the rendered light onto the screen's range.

RenderSettings pydantic-model

Bases: BaseModel

How every 3D view draws: its antialiasing per renderer, its lights, shading, camera, tone mapping and lines.

Config:

  • frozen: True
  • use_attribute_docstrings: True

Fields:

Validators:

client_antialias pydantic-field

client_antialias: Antialias = Antialias.FXAA

The mirror's antialiasing, one of CLIENT_ANTIALIAS.

server_antialias pydantic-field

server_antialias: Antialias = Antialias.MSAA

The stream's antialiasing.

lighting pydantic-field

lighting: Lighting = Lighting.LIGHT_KIT

The lights every view places.

brightness pydantic-field

brightness: float = 1.0

[-]: The intensity of every light, relative to the preset's own.

ambient pydantic-field

ambient: float = 0.0

[-]: The share of a surface's color shown without light.

specular pydantic-field

specular: float = PLAIN_SPECULAR

[-]: The highlight strength of a body in a plain color.

smooth_shading pydantic-field

smooth_shading: bool = True

Shade curved faces evenly; off shades every facet flat.

split_angle pydantic-field

split_angle: float = 30.0

[deg]: The dihedral angle above which a smooth surface keeps its edge sharp.

projection pydantic-field

projection: Projection = Projection.ORTHOGRAPHIC

How the camera projects the scene.

view_angle pydantic-field

view_angle: float = 30.0

[deg]: The perspective camera's vertical field of view.

tone_mapping pydantic-field

tone_mapping: ToneMapping = ToneMapping.OFF

The stream's tone mapping; the mirror has none.

exposure pydantic-field

exposure: float = 1.0

[-]: The light the tone mapping takes in, relative to the rendered.

outline_width pydantic-field

outline_width: float = 2.0

[px]: The width of the feature-edge outline in CSS pixels.

feature_angle pydantic-field

feature_angle: float = 30.0

[deg]: The dihedral angle above which a surface edge counts as a feature edge.

highlight_width pydantic-field

highlight_width: float = 2.0

[px]: The width of a hover outline in CSS pixels; a selection draws wider in proportion.

line_width pydantic-field

line_width: float = 1.0

[px]: The width of a field line in CSS pixels.

drawable pydantic-validator

drawable(value: Antialias) -> Antialias

Rejects an antialiasing the mirror cannot draw.

Source code in packages/femforge-workbench/src/femforge_workbench/render.py
@field_validator("client_antialias")
@classmethod
def drawable(cls, value: Antialias) -> Antialias:
    """Rejects an antialiasing the mirror cannot draw."""
    if value not in CLIENT_ANTIALIAS:
        raise ValueError(f"the mirror cannot draw {value}")

    return value

edges

edges() -> EdgeStyle

The outline and line widths and the feature angle as the scenes take them.

Source code in packages/femforge-workbench/src/femforge_workbench/render.py
def edges(self) -> EdgeStyle:
    """The outline and line widths and the feature angle as the scenes take them."""
    return EdgeStyle(width=self.outline_width, feature_angle=self.feature_angle, highlight_width=self.highlight_width, line_width=self.line_width)

shading

shading() -> Shading

The surface shading as the scenes take it.

Source code in packages/femforge-workbench/src/femforge_workbench/render.py
def shading(self) -> Shading:
    """The surface shading as the scenes take it."""
    return Shading(smooth=self.smooth_shading, split_angle=self.split_angle, ambient=self.ambient, specular=self.specular)

RenderVar

Bases: StrEnum

The shell's state variables of the render settings, one per field, named PREFIX and the field; a slider's holds its one thumb in a list.

Attributes:

  • field (str) –

    The settings field the variable shows.

field property

field: str

The settings field the variable shows.

limits

limits(var: RenderVar) -> tuple[float, float]

The lowest and highest value a slider's setting validates.

Source code in packages/femforge-workbench/src/femforge_workbench/render.py
def limits(var: RenderVar) -> tuple[float, float]:
    """The lowest and highest value a slider's setting validates."""
    metadata = cast("list[object]", RenderSettings.model_fields[var.field].metadata)
    low = next(float(cast("float", bound.ge)) for bound in metadata if isinstance(bound, Ge))
    high = next(float(cast("float", bound.le)) for bound in metadata if isinstance(bound, Le))

    return low, high

render_state

render_state(settings: RenderSettings) -> dict[str, object]

The state variables showing settings.

Source code in packages/femforge-workbench/src/femforge_workbench/render.py
def render_state(settings: RenderSettings) -> dict[str, object]:
    """The state variables showing ``settings``."""
    values = settings.model_dump(mode="json")

    return {var: [values[var.field]] if var in SLIDERS else values[var.field] for var in RenderVar}

settings_from_state

settings_from_state(state: Mapping[str, object]) -> RenderSettings | None

The settings the state variables show; None when they do not validate.

Source code in packages/femforge-workbench/src/femforge_workbench/render.py
def settings_from_state(state: Mapping[str, object]) -> RenderSettings | None:
    """The settings the state variables show; None when they do not validate."""

    def thumb(var: RenderVar) -> object:
        value = state.get(var)
        if isinstance(value, list):
            thumbs = cast("list[object]", value)

            return thumbs[0] if thumbs else None

        return value

    try:
        return RenderSettings.model_validate({var.field: thumb(var) for var in RenderVar})
    except ValidationError:
        return None

load_render

load_render(store: UiStateStore, user: str) -> RenderSettings

The user's saved render settings; the defaults when none are saved or the saved ones no longer validate.

Source code in packages/femforge-workbench/src/femforge_workbench/render.py
def load_render(store: UiStateStore, user: str) -> RenderSettings:
    """The user's saved render settings; the defaults when none are saved or the saved ones no longer validate."""
    saved = store.load((user, SHARED), RENDER_KEY)
    if saved is None:
        return RenderSettings()

    try:
        return RenderSettings.model_validate(saved)
    except ValidationError:
        log.bind(user=user).warning("Saved render settings are invalid; using the defaults.")

        return RenderSettings()

save_render

save_render(store: UiStateStore, user: str, settings: RenderSettings) -> None

Saves the user's render settings for every workbench.

Parameters:

  • store (UiStateStore) –

    The store the shell persists its UI state in.

  • user (str) –

    The user the settings belong to.

  • settings (RenderSettings) –

    The settings to save.

Source code in packages/femforge-workbench/src/femforge_workbench/render.py
def save_render(store: UiStateStore, user: str, settings: RenderSettings) -> None:
    """Saves the user's render settings for every workbench.

    Args:
        store: The store the shell persists its UI state in.
        user: The user the settings belong to.
        settings: The settings to save.
    """
    store.save((user, SHARED), RENDER_KEY, settings.model_dump(mode="json"))