registry

Defining hyperelements and collecting their styles and behaviors

AnswerUI provides built-in components through its shared stylesheet and JavaScript assets. Python constructors render their marked HTML. This registry holds application CSS and event handlers, attaches custom rules to constructors, and assembles those additions for each page. Built-in CSS remains in the shared assets instead of being copied into registry entries.

from fasthtml.common import Label, Input, Button, to_xml
from fastcore.test import *

Rules

Both styling and behavior pair a CSS selector with an action: CSS declarations for styling, or an event name and JavaScript handler for behavior. A Rule stores both CSS text and behavior records under a cascade layer because each page loads one combined stylesheet and one combined script.

The layer list is fixed and ordered. For normal declarations, each layer overrides earlier layers regardless of specificity. You can restyle a built-in component from the app layer without changing its definition. Component and base CSS do not use !important because !important reverses cascade-layer order (only the hidden-state classes in utilities use it).

Behaviors are passed as a dict from (selector, event) keys to JavaScript handler bodies. Each handler runs with el bound to the matched element and e to the event. For an event that doesn't bubble, such as toggle, add a truthy third item to the key to attach the handler in the capture phase. When a rule has a root selector sel, _behaviors replaces each & in its behavior selectors with :is(sel) (raising ValueError if sel is missing).

A rule's key is a name, or owner.name when the rule belongs to a hyperelement. Rule checks the layer, expands the behaviors, and derives owner and name from the key. For a variant rule, the variant attribute is stored in variant:


Rule

def Rule(
    key, # Registry key: a name, or `owner.name` for a hyperelement's rule
    css:str='', # Complete CSS, or a no-argument function returning it
    *, on=None, # Mapping of (selector, event[, capture]) to JavaScript handler bodies
    sel=None, # Root selector substituted for `&` in behaviors
    layer:str='app', # One of LAYERS
    doc:str='', # Description of the rule
    variant=None, # Attribute selecting a declared variant
):

A named CSS and behavior definition in a cascade layer

Registry.rule takes CSS first and an optional name second. Without a name, it hashes the CSS, selector, expanded behaviors and layer into a deterministic key. Identical registrations share one entry, including behavior-only rules. Pass an explicit name when css is callable, or when later edits should replace the previous rule rather than add another. A component's rule uses owner.name as its key.

Rules are stored in Registry.rules. Registering an existing key updates that Rule object in place, preserving both existing references and its position in the stylesheet. Registering or removing a rule increments version, which Registry.assets checks before rebuilding the stylesheet and script. Each entry of layers is a live RuleView of the rules in that layer:


Registry

def Registry():

Named rules and hyperelements, from which a page's stylesheet and script are built


RuleView

def RuleView(
    registry, *, layer=None, owner=None
):

A live, read-only view of one layer or one hyperelement's rules

The simplest rule is bare CSS with no constructor, such as a centered page column. Its layer defaults to app. Registering the same name again returns the existing entry:

page_css = 'main { max-width: 65ch; margin-inline: auto; padding: 1rem; }'
page_rule = reg.rule(page_css, 'app-page', doc='A centered single-column page.')
test_eq(page_rule.css, page_css)
test_is(reg.rule(page_css, 'app-page', doc='A centered single-column page.'), page_rule)
page_rule
app-page [app]: A centered single-column page.

A standalone behavior works the same way. Here we add a select-all attribute that selects an input's text on focus. Passing sel='input[select-all]' sets the root selector that & expands to in the handler key. The rule stores the expanded behavior record:

select_all = reg.rule(name='select-all', sel='input[select-all]', on={('&', 'focusin'): r"el.select()"},
    doc='Select the input text when it receives focus.')
select_all.on
[{'sel': ':is(input[select-all])',
  'ev': 'focusin',
  'js': 'el.select()',
  'cap': False}]
with expect_fail(ValueError): reg.rule('a { color: teal; }', layer='appp')
with expect_fail(ValueError): reg.rule(name='paste', on={('&', 'click'): ''})

Displaying reg lists each rule that belongs to no component, such as app-page and select-all:

reg

Registry(2 rules, 0 elements)

Layers:

  • reset: 0 rules
  • tokens: 0 rules
  • base: 0 rules
  • layout: 0 rules
  • components: 0 rules
  • app: 2 rules
  • utilities: 0 rules

Elements: none

Rules of no element:

  • app-page (app): A centered single-column page.
  • select-all (app): Select the input text when it receives focus.

Building the stylesheet

build_css starts with the shared styles.css, whose opening @layer statement declares the layer order. Registered rules follow as one @layer block per layer in registration order, each preceded by a comment naming its key. Application rules default to app, after the built-in components layer. For CSS that depends on later registrations, pass a zero-argument callable that build_css evaluates during assembly.


Registry.build_css

def build_css():

The shared foundation followed by registered CSS in cascade-layer order

reg.layers['app']
app-page [app]: A centered single-column page.
select-all [app] input[select-all]: Select the input text when it receives focus.

Hyperelements

A component pairs a constructor (a standard FastTag or a Python function combining multiple tags) with registered rules. Calling a Hyperelement invokes that constructor. Its sel attribute holds the root selector. Its rules attribute is a live RuleView of the component's rules:


Hyperelement

def Hyperelement(
    registry, name, fn, sel, doc:str='', generated:bool=False
):

A callable constructor linked to its registered rules and behaviors

Use Hyperelement.rule to add CSS nested under the root selector, or Hyperelement.variant to add an attribute variant nested under :is(sel)[name]. Both register their rule with the hyperelement as its owner. Calling variant also stores the attribute name on the rule (base is reserved for the constructor's own rule):


Hyperelement.variant

def variant(
    name, # Attribute selecting the variant; also its local rule name
    css:str='', # CSS declarations and nested rules, scoped to the variant
    *, on=None, # Mapping of (selector, event[, capture]) to handler bodies; `&` is the variant selector
    layer:str='app', # One of LAYERS
    doc:str='', # Description shown with the variant
):

Declare an attribute variant without changing the constructor


Hyperelement.rule

def rule(
    name, # Local rule name; registering it again replaces that rule
    css:str='', # CSS declarations and nested rules, scoped to the root selector
    *, on=None, # Mapping of (selector, event[, capture]) to handler bodies; `&` is the root selector
    layer:str='app', # One of LAYERS
    doc:str='', # Description of the customization
):

Register CSS and behaviors scoped to this hyperelement

hypelt registers a component from a FastHTML tag name or a handwritten constructor and nests css under its root selector as the base rule, just like Hyperelement.rule. Write declarations for the root, nested selectors for children, and & for states or pseudo-elements on the root. Pass a callable with no parameters when css depends on later registrations. Put global rules such as @keyframes in reg.rule, which accepts complete CSS without wrapping and uses its sel parameter for behaviors only. The module-level hypelt is bound to reg:


Registry.hypelt

def hypelt(
    name=None, # FastHTML tag name or a constructor; omit to use as a decorator
    *, sel=None, # Root selector; required for a handwritten constructor
    css:str='', # CSS declarations and nested rules, or a no-argument function returning them
    on=None, # Mapping of (selector, event[, capture]) to JavaScript handler bodies
    layer:str='app', # One of LAYERS; built-ins use components, layout, or base
    doc=None, # Description; defaults to a handwritten constructor's docstring
):

Register a constructor and its base rule, returning a callable hyperelement

As an example component, let's build a dismissible notice box with a close button. Because HTML has no built-in notice element, we use the custom tag notice-box. Clicking any child with the dismiss attribute removes the notice:

notice_css = r"""
display: block;
padding: .75rem 1rem;
background: #f4f4f6;
border: 1px solid #ccc;
border-radius: 8px;
"""
NoticeBox = hypelt('NoticeBox', css=notice_css, on={('& [dismiss]', 'click'): r"el.closest('notice-box').remove()"},
    layer='components', doc='A dismissible notice.')
to_xml(NoticeBox('Changes saved.', Button('Dismiss', dismiss=True)))
'<notice-box>Changes saved.<button dismiss>Dismiss</button></notice-box>'

For a string name such as 'NoticeBox', hypelt looks up the constructor on fasthtml.components and calls it with no arguments to get the root selector (notice-box). NoticeBox.rules and reg.rules hold the same Rule object:

test_eq(NoticeBox().tag, NoticeBox.sel)
assert NoticeBox.rules['base'] is reg.rules['NoticeBox.base']
assert NoticeBox.rules['base'].compiled_css.startswith('notice-box {')
NoticeBox

NoticeBox(*children, **attrs)

A dismissible notice.

Root selector: notice-box.

Rules:

  • base (components)

The second case is a handwritten constructor, such as a labelled field that wraps an input inside its label to associate them without an id. Because Field requires a label argument, hypelt can't call it with no arguments to infer a root selector. Instead we mark the label with a field attribute and pass sel='label[field]' using the decorator form:

field_css = r"""
display: grid;
gap: .5rem;
"""

@hypelt(sel='label[field]', css=field_css)
def Field(label, **attrs):
    "A labelled input"
    return Label(label, Input(**attrs), field=True)

to_xml(Field('Email', name='email', type='email'))
'<label field>Email  <input name="email" type="email">\n</label>'

Customization

There are two ways to change a component's styling or behavior. To override a component without altering its base rule, register separate rules in the app layer. To redefine it, call hypelt again with the same name to replace its constructor and base rule in place.

Overrides

Say a developer wants rounder notices in their application. NoticeBox.rule registers a named rule in the app layer by default, where it overrides the component's CSS in the components layer:

NoticeBox.rule('corners', 'border-radius: 1rem;', doc='Rounder notices in this application.')
NoticeBox.corners [app] notice-box: Rounder notices in this application.

To select a style with an attribute, declare it with variant. Its description then appears in the hyperelement's documentation while the existing constructor accepts the attribute:

NoticeBox.variant('quiet', 'background: transparent; border-color: transparent;', doc='An unfilled notice without a visible border.')
NoticeBox.quiet [app] :is(notice-box)[quiet]: An unfilled notice without a visible border.
test_eq(list(NoticeBox.variants), ['quiet'])
to_xml(NoticeBox('Saved quietly.', quiet=True))
'<notice-box quiet>Saved quietly.</notice-box>'

To change a component only within part of a page, register an application rule scoped to that container. Here reg.rule registers editor-notices to square the corners of every notice-box inside an [editor] element, with an explicit name for later replacement. Because this rule is not registered on NoticeBox, it leaves the component's definition untouched and appears in reg.layers['app'] rather than NoticeBox.rules:

reg.rule('[editor] notice-box { border-radius: 0; }', 'editor-notices', doc='Square notices inside the editor.')
reg.layers['app']
app-page [app]: A centered single-column page.
select-all [app] input[select-all]: Select the input text when it receives focus.
Field.base [app] label[field]: A labelled input
NoticeBox.corners [app] notice-box: Rounder notices in this application.
NoticeBox.quiet [app] :is(notice-box)[quiet]: An unfilled notice without a visible border.
editor-notices [app]: Square notices inside the editor.

Redefinitions

Calling hypelt again with the same name updates the hyperelement's constructor and base rule in place, preserving existing references, application rules, and declared variants. Omitted css or on arguments are cleared rather than merged because the new call replaces the entire base rule. hypelt raises ValueError if sel changes because existing rules and variants are nested under the original root selector. Omitting on here makes NoticeBox persistent:

original, base = NoticeBox, NoticeBox.rules['base']
NoticeBox = hypelt('NoticeBox', css=lambda: notice_css.replace('8px', '12px'), layer='components', doc='A persistent notice.')
test_is(NoticeBox, original)
test_is(NoticeBox.rules['base'], base)
assert '12px' in base.compiled_css
assert 'corners' in NoticeBox.rules and 'quiet' in NoticeBox.variants
with expect_fail(ValueError): hypelt('NoticeBox', sel='notice-box[persistent]', css=notice_css, layer='components')
NoticeBox

NoticeBox(*children, **attrs)

A persistent notice.

Root selector: notice-box.

Declared variants:

  • quiet: An unfilled notice without a visible border.

Rules:

  • base (components)
  • corners (app): Rounder notices in this application.

The base rule now has no behaviors. To remove the application override, pass its full key to reg.remove. A layer view taken earlier no longer lists it:

test_eq(NoticeBox.behaviors, [])
app_rules = reg.layers['app']
v = reg.version
reg.remove('NoticeBox.corners')
NoticeBox.corners [app] notice-box: Rounder notices in this application.
assert 'NoticeBox.corners' not in app_rules
test_eq(reg.version, v+1)
app_rules
app-page [app]: A centered single-column page.
select-all [app] input[select-all]: Select the input text when it receives focus.
Field.base [app] label[field]: A labelled input
NoticeBox.quiet [app] :is(notice-box)[quiet]: An unfilled notice without a visible border.
editor-notices [app]: Square notices inside the editor.