Ir para o conteúdo

tempest_fastapi_sdk.ui.css

CSS tipado: stylesheets, design tokens e a rota que os serve.

« Web, UI e utilitários


Rule dataclass

Rule(
    selector: str,
    style: Any | None = None,
    layout: Layout | None = None,
    declarations: Mapping[str, str] = dict(),
)

One CSS rule: a selector and the declarations it applies.

Attributes:

Name Type Description
selector str

Any CSS selector — ".card", ".card:hover", "form .field > label".

style Any | None

A tempest_core Style whose set fields become declarations.

layout Layout | None

Treat the rule as a flex container of that direction, adding display: flex and flex-direction the way Column / Row do.

declarations Mapping[str, str]

Raw CSS declarations, emitted after the style ones and therefore winning on conflicts.

to_css

to_css(*, indent: str = '') -> str

Render the rule as CSS.

Parameters:

Name Type Description Default
indent str

Indentation prepended to every line, used when the rule sits inside an at-rule block.

''

Returns:

Name Type Description
str str

The rule as selector { ... }, or an empty string

str

when it carries no declaration at all.

class_names

class_names() -> set[str]

Return the class names mentioned in the selector.

Returns:

Type Description
set[str]

set[str]: Every .name found in the selector, without the

set[str]

dot. Empty for element- or attribute-only selectors.

Media dataclass

Media(query: str, rules: Sequence[Rule] = ())

A group of rules wrapped in an at-rule (usually a media query).

Attributes:

Name Type Description
query str

The at-rule condition, without @media — "(min-width: 768px)".

rules Sequence[Rule]

The rules the condition guards.

min_width classmethod

min_width(pixels: float, rules: Sequence[Rule]) -> Media

Build a mobile-first min-width query.

Parameters:

Name Type Description Default
pixels float

The lower bound, in CSS pixels.

required
rules Sequence[Rule]

Rules applied at or above the bound.

required

Returns:

Name Type Description
Media Media

The wrapped rule group.

max_width classmethod

max_width(pixels: float, rules: Sequence[Rule]) -> Media

Build a max-width query.

Parameters:

Name Type Description Default
pixels float

The upper bound, in CSS pixels.

required
rules Sequence[Rule]

Rules applied at or below the bound.

required

Returns:

Name Type Description
Media Media

The wrapped rule group.

dark classmethod

dark(rules: Sequence[Rule]) -> Media

Build a prefers-color-scheme: dark query.

Parameters:

Name Type Description Default
rules Sequence[Rule]

Rules applied in dark mode.

required

Returns:

Name Type Description
Media Media

The wrapped rule group.

reduced_motion classmethod

reduced_motion(rules: Sequence[Rule]) -> Media

Build a prefers-reduced-motion: reduce query.

Parameters:

Name Type Description Default
rules Sequence[Rule]

Rules applied when the reader asked for less motion.

required

Returns:

Name Type Description
Media Media

The wrapped rule group.

to_css

to_css() -> str

Render the at-rule and everything it guards.

Returns:

Name Type Description
str str

@media (…) { … }, or an empty string when no nested

str

rule produced a declaration.

class_names

class_names() -> set[str]

Return the class names mentioned by the nested rules.

Returns:

Type Description
set[str]

set[str]: The union of every nested rule's class names.

StyleSheet dataclass

StyleSheet(
    rules: Sequence[Rule | Media] = (),
    theme: Any | None = None,
    reset: bool = True,
    extra_css: str = "",
)

A whole stylesheet, written in typed Python.

Attributes:

Name Type Description
rules Sequence[Rule | Media]

The rules, in cascade order.

theme ThemeTokens | None

Design tokens emitted as custom properties before every rule. None emits no token block.

reset bool

Whether to prepend the minimal base reset (box-sizing, zeroed body margin, the body font family, block media, inherited control fonts).

extra_css str

Raw CSS appended at the end, for the rare thing no rule expresses (@font-face, keyframes).

to_css

to_css() -> str

Render the whole sheet.

Returns:

Name Type Description
str str

Reset (when enabled), token block (when a theme is set),

str

every rule in order, then extra_css. Blocks are separated

str

by a blank line; empty blocks are dropped.

class_names

class_names() -> frozenset[str]

Return every class name the sheet defines.

Returns:

Type Description
frozenset[str]

frozenset[str]: The union of the class names of all rules,

frozenset[str]

used by :meth:cls to reject typos.

cls

cls(*names: str) -> dict[str, str]

Build a class attribute, rejecting names the sheet lacks.

Same output as the module-level :func:cls, with a lookup against the sheet so a typo fails loudly at render time instead of silently producing an unstyled element.

Parameters:

Name Type Description Default
*names str

Class names to apply, without the leading dot.

()

Returns:

Type Description
dict[str, str]

dict[str, str]: {"class": "card card--wide"}.

Raises:

Type Description
KeyError

When a name is not defined by any rule in the sheet.

merge

merge(other: StyleSheet) -> StyleSheet

Concatenate two sheets into one.

The receiver's rules come first, so other wins on equal specificity — the normal cascade. The receiver's theme and reset settings are kept unless it has none.

Parameters:

Name Type Description Default
other StyleSheet

The sheet appended after this one.

required

Returns:

Name Type Description
StyleSheet StyleSheet

A new sheet holding both rule lists.

etag

etag() -> str

Return a strong ETag for the rendered sheet.

Returns:

Name Type Description
str str

A quoted SHA-256 prefix of the CSS, stable for identical

str

content so a conditional request can answer 304.

version

version() -> str

Return a short content version of the rendered sheet.

Derived from the same SHA-256 as :meth:etag, so it depends on the CSS text alone: two processes rendering the same rules get the same value, and changing any declaration changes it.

Returns:

Name Type Description
str str

The first 12 hex characters of the digest.

url

url(path: str = '/static/app.css') -> str

Return the content-versioned URL pages should link.

Pass the same path given to :func:~tempest_fastapi_sdk.ui.css.make_css_router. The router answers a request carrying the current version with a year-long immutable cache policy, and a changed sheet yields a URL the browser has never cached — so a deploy never leaves new HTML on top of an old stylesheet.

Compute it once, next to the sheet, at import time: every call renders the whole sheet to hash it.

Parameters:

Name Type Description Default
path str

Absolute route path the sheet is served from.

'/static/app.css'

Returns:

Name Type Description
str str

"/static/app.css?v=<version>".

Raises:

Type Description
ValueError

When path does not start with "/" or already carries a query string.

Example
from tempest_fastapi_sdk.ui import app_stylesheet
from tempest_fastapi_sdk.ui.css import StyleSheet

STYLESHEET: StyleSheet = app_stylesheet()
CSS_URL: str = STYLESHEET.url("/static/app.css")

cls

cls(*names: str) -> dict[str, str]

Build the class attribute mapping for a widget.

Widgets take an open attrs mapping; this turns a list of class names into exactly the {"class": "..."} entry you would have written, with the names joined and blanks dropped.

Parameters:

Name Type Description Default
*names str

Class names to apply, without the leading dot.

()

Returns:

Type Description
dict[str, str]

dict[str, str]: {"class": "card card--wide"}. Empty when no

dict[str, str]

non-blank name is given, so it is safe to splat unconditionally.

Example
from tempest_core import Column, Text

from tempest_fastapi_sdk.ui.css import cls

Column(tag="section", attrs=cls("card"), children=[Text(content="hi")])

ThemeTokens dataclass

ThemeTokens(
    token_set: Any = None,
    prefix: str = _DEFAULT_PREFIX,
    dark_mode: bool = True,
    font_family_body: str = SYSTEM_FONT_STACK,
    _resolved: list[Any] = list(),
)

Design tokens rendered as CSS custom properties.

Attributes:

Name Type Description
token_set Any

The tempest_core TokenSet to emit. Defaults to :func:tempest_core.default_tokens, resolved lazily on first use so importing this module never requires the [ssr] extra.

prefix str

Custom-property prefix, without dashes. "t" yields --t-color-primary.

dark_mode bool

Whether to emit the dark colour scheme blocks.

font_family_body str

Value of --<prefix>-font-family-body, the face the reset applies to body. Defaults to :data:~tempest_fastapi_sdk.ui.css.SYSTEM_FONT_STACK. tempest_core's token set carries sizes and weights but no family, so the family lives here.

var

var(group: str, name: str) -> str

Return a var(...) reference to one token.

Parameters:

Name Type Description Default
group str

Token group (color, space, radius, font-family, font-size, line-height, font-weight, letter-spacing, duration, easing).

required
name str

Token name within the group (primary, md, body_medium).

required

Returns:

Name Type Description
str str

var(--t-color-primary).

color

color(role: str) -> str

Return a var(...) reference to a colour role.

Parameters:

Name Type Description Default
role str

A colour role of the scheme (primary, on_surface, error_container, …).

required

Returns:

Name Type Description
str str

var(--t-color-primary).

space

space(name: str) -> str

Return a var(...) reference to a spacing step.

Parameters:

Name Type Description Default
name str

Spacing step (none, xs, sm, md, lg, xl, xxl).

required

Returns:

Name Type Description
str str

var(--t-space-md).

radius

radius(name: str) -> str

Return a var(...) reference to a shape radius.

Parameters:

Name Type Description Default
name str

Shape step (none, xs, sm, md, lg, xl, full).

required

Returns:

Name Type Description
str str

var(--t-radius-md).

font_size

font_size(name: str) -> str

Return a var(...) reference to a typography size.

Parameters:

Name Type Description Default
name str

Typography token (body_medium, headline_large, label_small, …).

required

Returns:

Name Type Description
str str

var(--t-font-size-body-medium).

font_family

font_family(name: str = 'body') -> str

Return a var(...) reference to a font family.

Parameters:

Name Type Description Default
name str

Family token. Only body is emitted.

'body'

Returns:

Name Type Description
str str

var(--t-font-family-body).

breakpoint

breakpoint(name: str) -> float

Return a breakpoint width in pixels.

Breakpoints are returned as numbers rather than custom properties: CSS media queries cannot read var().

Parameters:

Name Type Description Default
name str

Breakpoint name (sm, md, lg, xl).

required

Returns:

Name Type Description
float float

The breakpoint width in pixels.

Raises:

Type Description
KeyError

When the breakpoint name is unknown.

to_css

to_css() -> str

Render every token as CSS custom properties.

Returns:

Name Type Description
str str

A :root block with the light scheme and the scalar

str

scales, followed (when dark_mode is on) by the dark

str

scheme under prefers-color-scheme and under

str

[data-theme="dark"].

make_css_router

make_css_router(
    sheet: StyleSheet,
    *,
    path: str = "/static/app.css",
    cache_control: str = _DEFAULT_CACHE_CONTROL,
    versioned_cache_control: str = _DEFAULT_VERSIONED_CACHE_CONTROL,
) -> APIRouter

Build a router serving one stylesheet at a fixed path.

The CSS is rendered eagerly, at router-construction time, so no request pays the cost of walking the rules. Link pages at sheet.url(path) — the content-versioned URL — so the browser keeps the sheet cached and fetches a new one exactly when a deploy changes it.

Parameters:

Name Type Description Default
sheet StyleSheet

The sheet to serve.

required
path str

Absolute route path, including the leading slash. Pass the same value to :meth:StyleSheet.url and hand the result to :func:tempest_fastapi_sdk.ssr.html_response through its stylesheets argument.

'/static/app.css'
cache_control str

Cache-Control of a request without the current version (the bare path, or a stale ?v=). Defaults to no-cache.

_DEFAULT_CACHE_CONTROL
versioned_cache_control str

Cache-Control of a request whose ?v= matches :meth:StyleSheet.version. Defaults to public, max-age=31536000, immutable.

_DEFAULT_VERSIONED_CACHE_CONTROL

Returns:

Name Type Description
APIRouter APIRouter

A router exposing GET {path}, answering 304

APIRouter

when the request's If-None-Match matches the sheet's ETag.

Raises:

Type Description
ValueError

When path does not start with "/".

Example
from fastapi import FastAPI

from tempest_fastapi_sdk.ui.css import Rule, StyleSheet, make_css_router

app: FastAPI = FastAPI()
sheet: StyleSheet = StyleSheet(
    rules=[Rule(".card", declarations={"padding": "16px"})],
)
CSS_URL: str = sheet.url("/static/app.css")
app.include_router(make_css_router(sheet, path="/static/app.css"))

css_response

css_response(
    sheet: StyleSheet,
    *,
    cache_control: str = _DEFAULT_CACHE_CONTROL,
    status_code: int = 200,
) -> Response

Render a stylesheet into a text/css response.

Parameters:

Name Type Description Default
sheet StyleSheet

The sheet to render.

required
cache_control str

Value of the Cache-Control header. Defaults to no-cache (revalidate through the ETag before each use).

_DEFAULT_CACHE_CONTROL
status_code int

HTTP status code. Defaults to 200.

200

Returns:

Name Type Description
Response Response

The rendered CSS with an ETag derived from its

Response

content and the given cache policy.

stylesheet_links(*hrefs: str) -> str

Build the <link rel="stylesheet"> tags for a document head.

Parameters:

Name Type Description Default
*hrefs str

Stylesheet URLs, in load order.

()

Returns:

Name Type Description
str str

The concatenated link tags, with " escaped in each URL

str

so a crafted path cannot break out of the attribute.