hdrs

Inline or content-hashed page headers and footers for the registry's stylesheet, scripts, and icon spritesheet.

For inline assets, pass reg.hdrs() and reg.ftrs() to FastHTML or fast_app. The headers include the shared foundation stylesheet, registered application rules, the delegated event script, and the shared browser helpers. The footer includes the fastlucide icon spritesheet. FastHTML renders the registry's current rules on each response, including rules registered after app creation. To serve cached local asset URLs instead, call reg.serve(app). It mounts the asset routes and appends the headers and footers to app.

from fasthtml.common import *
from answerui.registry import reg, hypelt
from fastcore.test import *
from fastlucide.icons import Check
from tempfile import TemporaryDirectory

assets caches the compiled stylesheet and script because building the stylesheet walks every rule. The registry increments version on each change. assets rebuilds only when version differs from its cached build:


Registry.assets

def assets():

The stylesheet and script, keyed by extension, built once per registry version

assets returns the same build until a rule changes:

r = Registry()
built = r.assets()
test_is(r.assets(), built)
r.rule('main { max-width: 65ch; }', 'page')
assert r.assets() is not built
assert 'max-width: 65ch' in r.assets()['css']
list(built)
['css', 'js']

FastHTML calls __ft__ on each object that defines it. _Lazy uses that hook to render the registry's current CSS and event script on each response. For inline pages and notebook previews, _inline_browser rewrites browser.js so its imports of floating.js, interactions.js, fit.js, and copy.js use base64 data: URLs rather than relative paths. On served pages, the browser loads those same files over HTTP. If your app uses its own Registry, pass its hdrs() instead of reg.hdrs().


Registry.hdrs

def hdrs():

Inline foundation, application rules and browser behavior, rendered from this registry per response

To see that the headers are lazy, build them first and define a component afterwards. Rendering the stylesheet header then includes the component's CSS.

hdrs = reg.hdrs()
LateCard = hypelt('LateCard', css='display: block; color: teal;', layer='components',
    on={('&', 'click'): r"el.remove()"}, doc='Defined after the app; click to remove.')
css = to_xml(hdrs[0])
print(css[css.index('/* LateCard.base */'):][:60])
/* LateCard.base */
late-card {
display: block; color: teal;

Redefining the component changes the next render. There is no rebuild step and nothing to invalidate:

LateCard = hypelt('LateCard', css='display: block; color: navy;', layer='components', doc='Defined after the app.')
css = to_xml(hdrs[0])
assert 'navy' in css and 'teal' not in css

Each icon references a symbol in fastlucide's spritesheet. Importing an icon from fastlucide.icons adds its symbol to spritesheet. Because spritesheet is an <svg> element, it belongs in <body> rather than <head>. ftrs returns (spritesheet,) for FastHTML to render at the end of <body>. Because spritesheet already defines __ft__ for per-page rendering, ftrs returns it directly without a _Lazy wrapper:


Registry.ftrs

def ftrs():

Footers for fast_app(ftrs=...): fastlucide's sprite sheet, with every icon that any module has imported

A whole page

FastHTML's test Client fetches a page without starting a server. In the response, <head> contains htmx, the AnswerUI stylesheet, the event script, and the inline browser.js module. The spritesheet appears at the end of <body>, after the icon that references it.

app = FastHTML(hdrs=reg.hdrs(), ftrs=reg.ftrs())
rt = app.route

@rt
def index(): return Titled('Hello', LateCard(Check(), 'Defined after the app.'))

page = Client(app).get('/').text
assert page.index('<symbol id="lc-check"') > page.index('late-card')
print(re.sub(r'(?s)(<(style|script)\b[^>]*>).*?(?=</\2>)', r'\1…', page))
<!doctype html>
<html>
  <head>
    <title>Hello</title>
    <link rel="canonical" href="https://testserver/">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <meta name="htmx-config" content='{"metaCharacter": "-", "defaultTimeout": 0, "noSwap": [204, 304, "4xx", "5xx"]}'>
<script src="https://cdn.jsdelivr.net/npm/htmx.org@4.0.2/dist/htmx.min.js">…</script><script src="https://cdn.jsdelivr.net/gh/answerdotai/fasthtml-js@1.0.13/fasthtml.js">…</script><script src="https://cdn.jsdelivr.net/gh/answerdotai/surreal@main/surreal.js">…</script><script src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js">…</script>    <style>…</style>
<script>…</script><script type="module">…</script>  </head>
  <body>
<main class="container">      <h1>Hello</h1>
<late-card><svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 24 24" height="24px" width="24px" class="lucide-icon "><use href="#lc-check"></use></svg>Defined after the app.</late-card></main>    <style>…</style>
<svg xmlns="http://www.w3.org/2000/svg" style="display: none"><defs><symbol id="lc-check"><path d="M20 6 9 17l-5-5"></path></symbol></defs></svg>  </body>
</html>

With fast_app, pass pico=False to disable Pico CSS:

app, rt = fast_app(hdrs=reg.hdrs(), ftrs=reg.ftrs(), pico=False)
@rt
def index(): return Titled('Hello', LateCard('Defined after the app.'))

assert 'pico' not in (r:= Client(app).get('/').text)
assert 'late-card' in r

Serving the assets

Call reg.serve(app) instead of passing reg.hdrs() and reg.ftrs() to serve cached assets from local URLs under path (default /answerui). serve mounts content-hashed routes for the stylesheet and event script with Cache-Control: public, max-age=31536000, immutable. Each registry version is built once. The asset handler continues to serve the original bytes for earlier hashed URLs and returns 404 for unknown names. Because the handler builds the current version on demand, a separate worker process can serve the current assets without rendering a page first.

serve also mounts the packaged asset tree (browser.js, its helper modules, optional fonts.css, and font files) under a URL prefix hashed from the whole tree. Relative module imports and font URLs resolve under that prefix. serve appends the headers to app.hdrs and spritesheet to app.ftrs. It also returns the header tuple in case you assemble <head> manually.


Registry.serve

def serve(
    app, # The FastHTML app to mount the route on and add the headers to
    path:str='/answerui', # URL prefix the assets are served under
):

Serve content-hashed assets, adding their headers and the icon sprite sheet to app; returns the headers

app, worker = FastHTML(), FastHTML()
rt = app.route
for a in (app, worker): reg.serve(a)

@rt
def index(): return Titled('Hello', LateCard('Defined after the app.'))

page = Client(app).get('/').text
href = re.search(r'href="(/answerui/[^"]+\.css)"', page)[1]
asset = Client(worker).get(href)
test_eq(asset.headers['cache-control'], 'public, max-age=31536000, immutable')
assert 'navy' in asset.text
href
'/answerui/09d29de4622c.css'

After a registry change, the next page links to a new hashed URL. Requesting the previous URL still returns the earlier build. Requesting an unknown URL returns 404:

LateCard = hypelt('LateCard', css='display: block; color: teal;', layer='components', doc='Defined after the app.')
href2 = re.search(r'href="(/answerui/[^"]+\.css)"', Client(app).get('/').text)[1]
assert href2 != href
assert 'navy' in Client(app).get(href).text
assert 'teal' in Client(app).get(href2).text
test_eq(Client(app).get('/answerui/000000000000.css').status_code, 404)

CSS rules sometimes reference external files, such as a font or logo. Register a file with reg.file(name, path, url) and use the returned URL in your rule. serve mounts the file at a content-hashed URL under path and rewrites the public URL in the stylesheet and script. Without serve, the browser fetches the file from the public URL.

r, tmp = Registry(), TemporaryDirectory()
logo = Path(tmp.name)/'logo.svg'
logo.write_text('<svg xmlns="http://www.w3.org/2000/svg"/>')
url = r.file('logo.svg', logo, 'https://example.com/logo.svg')
r.rule(f"header {{ background: url('{url}'); }}", 'brand')
assert url in r.build_css()

The stylesheet's hashed URL is computed from its rewritten content, including each local file URL. Another worker process can serve the app's copy of the file without rendering a page first:

app, worker = FastHTML(), FastHTML()
for a in (app, worker): r.serve(a)

@app.get('/')
def index(): return Titled('Hello')

cli = Client(app)
css_href = re.search(r'href="(/answerui/[^"]+\.css)"', cli.get('/').text)[1]
css = cli.get(css_href).text
test_eq(css_href, f'/answerui/{_hash(css)}.css')
assert url not in css
served_logo = re.search(r"url\('(/answerui/\w+-logo\.svg)'\)", css)[1]
test_eq(Client(worker).get(served_logo).text, logo.read_text())
served_logo
'/answerui/900fbe934249-logo.svg'