behaviors
Delegated event-handler runtime (Registry.build_js) and browser.js DOM hookup for AnswerUI's built-in interactions across htmx swaps.
answerui.behaviors generates the delegated event script (Registry.build_js) for handlers registered in Registry and defines browser.js to wire up AnswerUI's shared browser modules.
Application handlers are stored in Registry as records containing a selector, an event name, a capture flag, and a JavaScript handler body. The generated script installs one document listener per event and capture phase, then matches the nearest ancestor for each rule's selector when an event fires. Elements inserted by htmx work without attaching extra listeners. Built-in interactive controllers with local state are mounted through a MutationObserver in browser.js and disposed when their elements are removed from the document.
from answerui.registry import reg, hypelt
from fastcore.test import *
The runtime
_runtime is the entire client script. build_js embeds rules as an array of objects. Each object has sel (selector), evs (DOM event names), cap (capture boolean), init (boolean), and fn (handler). The script groups these objects by event name and capture phase, then installs one document listener per group regardless of how many rules share it. When an event fires on an Element target, that listener calls closest(r.sel) for each rule in the group and runs r.fn(el, e) on any match. Because delegation uses the DOM e.target, init runs on newly swapped elements while HTMX 4 dispatches swap events on the triggering element (with e.detail.ctx.target holding the swap target).
An init rule runs when matching elements enter the document. When rules includes any init rule, the script registers a callback with htmx.onLoad. htmx calls that callback with document.body on initial load and with the root element of each swapped fragment. The callback checks root itself (root.matches) and its descendants (root.querySelectorAll). Checking ancestors instead would re-run init handlers on outer elements already in the page. Each init call passes a synthetic new Event('init') that is never dispatched. Load htmx before this script whenever you register init rules. FastHTML's default headers and demo both include htmx first.
The script executes once per document. FastHTML sends page headers only with full pages, never with htmx fragment responses. When htmx swaps a full page, it discards the incoming <head>.
Each handler is an async function. If one throws, the returned promise is rejected without stopping other handlers registered for the same event. Capture-phase listening (cap=True) is opt-in for non-bubbling events such as toggle and scroll. A regenerated script takes effect cleanly only in a fresh page or preview. Injecting a second copy into the same document attaches duplicate listeners alongside the existing ones.
Entries
_entry formats each behavior record as one object literal in rules. AnswerUI defines two special event names. init runs when an element enters the document. cleanup runs before an element is removed by htmx. Every other name is a DOM event. A leading : expands to htmx: (for example, ':after-request' becomes 'htmx:after-request').
HTMX 4 dispatches events under two naming conventions: default colon-separated names such as htmx:after:swap, and FastHTML's metaCharacter='-' form where every colon becomes a hyphen (htmx-after-swap). _event normalizes either spelling (or a leading : shorthand like ':after-swap') to htmx: followed by the hyphenated name, and _spellings expands it back into both HTMX 4 DOM event names. The script registers listeners for both because only one fires on a given page.
init and cleanup are handled separately. Because init is not a DOM event, _spellings('init') returns [] and the script invokes init handlers through htmx.onLoad. For cleanup, _spellings returns _cleanup (htmx:before:cleanup and htmx-before-cleanup), which fires for elements initialised by htmx (elements with hx- attributes). Each distinct handler body becomes one async function taking (el, e), declared before rules and referenced by name in each entry:
_event normalizes every htmx event spelling to the same canonical name. _spellings returns the DOM event names registered for it:
for ev in [':after-swap', 'htmx:after:swap', 'htmx-after-swap']: test_eq(_event(ev), 'htmx:after-swap')
_spellings('htmx:after-swap')
['htmx:after:swap', 'htmx-after-swap']
Building the script
A behavior is identified by (selector, canonical_event, capture), using _event to canonicalize the event name. Declaring the same identity again replaces the earlier handler. Only the last declaration in registry order appears in the script. Because re-registering a rule preserves its original position in self.rules, re-running a component definition cannot overwrite an application rule registered later. Replacing a handler also keeps the identity's original position in the output dict to preserve execution order. Because Registry compares selector strings literally without parsing CSS, two distinct selectors matching the same element are separate behaviors. Both handlers run.
behaviors returns the effective handler for each identity along with its declaring rule key. build_js deduplicates identical handler bodies and assembles the script:
Registry.build_js
def build_js():
The behavior script: one function per distinct handler, one entry per effective behavior
Registry.behaviors
def behaviors():
The effective behavior per (selector, event, capture): the last declared in registry order, with the key of the rule that declared it
This example defines a NoticeBox component with two behaviors: an init handler that removes the element after an autodismiss delay, and a click handler on [dismiss]. Because htmx calls htmx.onLoad only for the initial page and newly swapped fragments, swapping content inside an existing notice-box does not restart its timer:
NoticeBox = hypelt('NoticeBox', layer='components', doc='A notice that dismisses itself.', on={
('&[autodismiss]', 'init'): r"await new Promise(r => setTimeout(r, +el.getAttribute('autodismiss'))); el.remove()",
('& [dismiss]', 'click'): r"el.closest('notice-box').remove()"})
print('\n'.join(l for l in reg.build_js().splitlines() if 'notice-box' in l))
async function f1(el, e) { el.closest('notice-box').remove() }
const rules = [{sel: ":is(notice-box)[autodismiss]", evs: [], cap: false, init: true, fn: f0},
{sel: ":is(notice-box) [dismiss]", evs: ["click"], cap: false, init: false, fn: f1}];
The init entry has init: true and evs: [] because htmx.onLoad invokes it instead of a document listener. The click entry has init: false. build_js emits the handler functions and rules array. At page load, the script groups those entries into document listeners.
You can register the same handler body for multiple events in one rule. Here a form is marked dirty on input and on change (a <select> fires only change). Registering the input handler again in an anonymous rule keeps the change handler in place because anonymous rule keys include their behaviors. build_js declares the shared handler function once and references it from both entries:
_dirty = r"el.toggleAttribute('dirty', [...el.elements].some(c => c.value !== c.defaultValue))"
reg.rule(name='dirty', sel='form', on={('&', 'input'): _dirty, ('&', 'change'): _dirty})
reg.rule(sel='form', on={('&', 'input'): _dirty})
s = reg.build_js()
test_eq(s.count(_dirty), 1)
test_eq(s.count('":is(form)"'), 2)
To require confirmation before dismissing a notice, register the same selector and event on NoticeBox. Just as in the component definition, & expands to :is(notice-box). Because the behavior identity matches, the confirmation handler replaces the original. Each effective behavior's rule field holds the key of the rule that supplied its active handler:
NoticeBox.rule('confirm-dismiss', on={('& [dismiss]', 'click'): r"if (confirm('Dismiss this notice?')) el.closest('notice-box').remove()"})
{k: b['rule'] for k,b in reg.behaviors().items()}
{(':is(notice-box)[autodismiss]', 'init', False): 'NoticeBox.base',
(':is(notice-box) [dismiss]', 'click', False): 'NoticeBox.confirm-dismiss',
(':is(form)', 'input', False): '858472c34654',
(':is(form)', 'change', False): 'dirty'}
The generated script contains only the confirmation click handler for [dismiss]. NoticeBox.behaviors still lists both declarations made on the component. reg.behaviors returns only the effective handlers emitted to the script:
s = reg.build_js()
test_eq(s.count('":is(notice-box) [dismiss]"'), 1)
assert 'confirm(' in s
NoticeBox.behaviors
[{'sel': ':is(notice-box)[autodismiss]',
'ev': 'init',
'js': "await new Promise(r => setTimeout(r, +el.getAttribute('autodismiss'))); el.remove()",
'cap': False},
{'sel': ':is(notice-box) [dismiss]',
'ev': 'click',
'js': "el.closest('notice-box').remove()",
'cap': False},
{'sel': ':is(notice-box) [dismiss]',
'ev': 'click',
'js': "if (confirm('Dismiss this notice?')) el.closest('notice-box').remove()",
'cap': False}]
Re-registering the component's definition does not displace the application's override:
NoticeBox = hypelt('NoticeBox', layer='components', doc='A notice that dismisses itself.', on={
('&[autodismiss]', 'init'): r"await new Promise(r => setTimeout(r, +el.getAttribute('autodismiss'))); el.remove()",
('& [dismiss]', 'click'): r"el.closest('notice-box').remove()"})
test_eq(reg.behaviors()[(':is(notice-box) [dismiss]', 'click', False)]['rule'], 'NoticeBox.confirm-dismiss')
[k for k in reg.behaviors() if k[1]=='init']
[(':is(notice-box)[autodismiss]', 'init', False)]
Built-in browser behavior
browser.js connects AnswerUI's shared JavaScript modules (floating.js, interactions.js, fit.js, and copy.js) to server-rendered HTML, including fragments inserted by htmx. Native controls, CSS tooltips, and static surfaces require no JavaScript.
Form helpers attach document-level input, change, reset, focusout, and capture-phase invalid listeners:
enable(form)togglesdisabledon eachbutton[enable]from its space-separated tokens (changedfor modified form values,validfor constraint validity).range(input)sets--ui-range-filloninput[range]frommin,max, andvalue.- Changing
input[reveals]setshiddenon the element whoseidmatches the attribute value. validity(control, event)writes nativevalidationMessagetext into asmall[validation][ui-tone="danger"]child of[field], links it viaaria-describedby, suppresses the browser popup, and focuses the first invalid control on submit.
Document-level action handlers cover common UI events:
- Clicking
button[dismiss]removes the closest[alert]or[toast]. - Clicking
button[copy]orbutton[copyfor]copies text withcopyText, settingcopied(andaria-label="Copied"if anaria-labelexists) for 1500 ms. - Clicking
button[commandfor]falls back toshowModal()forcommand="show-modal"andclose()forcommand="close"whencommandForElementis unavailable. - On
animationend,browser.jsremoves[toast]elements whenui-toast-lifetimefinishes. - On HTMX 4 settle events (
htmx:after:settle,htmx-after-settle),browser.jscallsshowModal()on a closeddialog[dialog]when non-empty content is swapped into a descendant inside it (including via<hx-partial>).
Stateful controllers are tracked in a WeakMap and managed by a MutationObserver on document.body. On initial load and for every added subtree, mount handles:
[popup][popover]and[popovertarget]: attachesmountPopover(andmountHoverPopoverwhen[hovercard]is present), readingdata-side,data-align, anddata-side-offset(default6).[tabs]with[role=tablist]: attachesmountTabsusingdata-activation-mode.[toolbar][role=toolbar]: attachesmountToolbar.[navbar]: attachesmountNavbarwhen bothnavand[navbar-toggle]are present or[navbar-sticky]is set.[toaster]: opens the popover withshowPopover()when not already open.input[range]andbutton[enable]: runs their initial state updates.
Removing a disconnected element calls its disposer and clears any pending copy timer. Moving an element within the document keeps isConnected true and preserves its mounted controller.
_forms = r'''
import {mountPopover} from './floating.js';
import {mountTabs, mountToolbar, mountHoverPopover} from './interactions.js';
import {mountNavbar} from './fit.js';
import {copyText} from './copy.js';
function enable(form) {
if (!form) return;
const changed = [...form.elements].some(control => control.matches('input:not([type=hidden], [type=submit], [type=button], [type=reset]), select, textarea') &&
(control.type === 'checkbox' || control.type === 'radio' ? control.checked !== control.defaultChecked :
control.tagName === 'SELECT' ? [...control.options].some(option => option.selected !== option.defaultSelected) : control.value !== control.defaultValue));
const valid = [...form.elements].every(control => control.validity.valid);
for (const button of form.querySelectorAll('button[enable]'))
button.disabled = !button.getAttribute('enable').split(' ').every(want => want === 'changed' ? changed : want === 'valid' ? valid : true);
}
function range(input) {
const low = input.min === '' ? 0 : +input.min, high = input.max === '' ? 100 : +input.max;
input.style.setProperty('--ui-range-fill', `${high > low ? (input.value - low) / (high - low) * 100 : 0}%`);
}
function validity(control, event) {
const field = control.closest('[field]');
if (!field) return;
let message = field.querySelector(':scope > small[validation]');
const ids = (control.getAttribute('aria-describedby') || '').split(' ').filter(id => id && id !== message?.id);
const show = event.type === 'invalid' || (event.type === 'focusout' ? control.matches(':user-invalid') : message && !control.validity.valid);
if (show) {
if (!message) {
message = document.createElement('small');
message.setAttribute('validation', '');
message.setAttribute('ui-tone', 'danger');
message.id = `validation-${Math.random().toString(36).slice(2, 10)}`;
field.append(message);
}
message.textContent = control.validationMessage;
ids.push(message.id);
} else message?.remove();
if (ids.length) control.setAttribute('aria-describedby', ids.join(' '));
else control.removeAttribute('aria-describedby');
if (event.type === 'invalid') {
event.preventDefault();
if ([...(control.form?.elements ?? [control])].find(item => !item.validity.valid) === control) control.focus();
}
}
function changed(event) {
const control = event.target;
if (!(control instanceof Element)) return;
if (control.form?.querySelector('button[enable]')) enable(control.form);
if (control.matches('input[range]')) range(control);
if (control.matches('input[reveals]')) document.getElementById(control.getAttribute('reveals')).hidden = !control.checked;
if (control.matches('input, select, textarea')) {
validity(control, event);
for (const message of control.form?.querySelectorAll('small[validation]') ?? []) if (!message.closest('[field]')) message.remove();
}
}
document.addEventListener('input', changed);
document.addEventListener('change', changed);
document.addEventListener('reset', event => setTimeout(() => {
enable(event.target);
for (const input of event.target.querySelectorAll('input[range]')) range(input);
}));
for (const type of ['focusout', 'invalid']) document.addEventListener(type, event => {
if (event.target.matches('input, select, textarea')) validity(event.target, event);
}, {capture: type === 'invalid'});
'''
_actions = r'''
document.addEventListener('click', async event => {
const button = event.target.closest('button');
if (!button) return;
if (button.hasAttribute('dismiss')) button.closest('[alert], [toast]')?.remove();
if (button.matches('[copy], [copyfor]')) {
const target = document.getElementById(button.getAttribute('copyfor'));
const text = button.hasAttribute('copy') ? button.getAttribute('copy') : target?.matches('input, textarea, select') ? target.value : target?.textContent;
if (text == null) return;
await copyText(text);
if (!button.isConnected) return;
button._label ??= button.getAttribute('aria-label') ?? '';
button.toggleAttribute('copied', true);
if (button._label) button.setAttribute('aria-label', 'Copied');
clearTimeout(button._copied);
button._copied = setTimeout(() => {
button.removeAttribute('copied');
if (button._label) button.setAttribute('aria-label', button._label);
}, 1500);
}
if (button.hasAttribute('commandfor') && !('commandForElement' in button)) {
const target = document.getElementById(button.getAttribute('commandfor')), command = button.getAttribute('command');
if (command === 'show-modal') target.showModal();
else if (command === 'close') target.close();
}
});
document.addEventListener('animationend', event => {
if (event.animationName === 'ui-toast-lifetime' && event.target.matches('[toast]')) event.target.remove();
});
for (const type of ['htmx:after:settle', 'htmx-after-settle']) document.addEventListener(type, event => {
const target = event.target, dialog = target?.closest?.('dialog[dialog]');
if (dialog?.isConnected && target !== dialog && !dialog.open && event.detail?.newContent?.some(n => n.childNodes?.length || n.textContent?.trim())) dialog.showModal();
});
'''
_mounts = r'''
const mounted = new WeakMap();
const tabs = '[tabs], [tabs] [role=tablist]';
const navbar = '[navbar], [navbar] > [navbar-row], [navbar-row] > nav, [navbar-row] > [navbar-toggle]';
const selector = `${tabs}, ${navbar}, [popup][popover], [popovertarget], [toolbar][role=toolbar], [toaster], input[range], button[enable], [copy], [copyfor]`;
function own(elements, dispose) {
const stop = () => { dispose(); for (const element of elements) mounted.delete(element); };
for (const element of elements) mounted.set(element, stop);
}
function mount(element) {
if (mounted.has(element)) return;
if (element.matches('[popovertarget]')) {
const panel = element.popoverTargetElement;
if (panel?.matches('[popup]')) mount(panel);
} else if (element.matches('[popup][popover]')) {
const trigger = document.querySelector(`[popovertarget="${CSS.escape(element.id)}"]`);
if (!trigger) return;
const stop = mountPopover(trigger, element, {side: element.dataset.side, align: element.dataset.align, sideOffset: +(element.dataset.sideOffset ?? 6)});
const hover = element.hasAttribute('hovercard') ? mountHoverPopover(trigger, element) : undefined;
own([element, trigger], () => { hover?.(); stop(); });
} else if (element.matches(tabs)) {
const root = element.closest('[tabs]'), list = root?.querySelector('[role=tablist]');
if (list && !mounted.has(root)) own([root, list], mountTabs(root, {activationMode: root.dataset.activationMode}).dispose);
} else if (element.matches('[toolbar][role=toolbar]')) own([element], mountToolbar(element));
else if (element.matches(navbar)) {
const root = element.closest('[navbar]'), row = root?.querySelector(':scope > [navbar-row]');
const nav = row?.querySelector(':scope > nav'), toggle = row?.querySelector(':scope > [navbar-toggle]');
if (nav && toggle || root?.hasAttribute('navbar-sticky')) {
mounted.get(root)?.();
own([root, row, nav, toggle].filter(Boolean), mountNavbar(root).dispose);
}
} else if (element.matches('[toaster]')) { if (!element.matches(':popover-open')) element.showPopover(); }
else if (element.matches('input[range]')) range(element);
else if (element.matches('button[enable]')) enable(element.form);
}
function cleanup(element) {
mounted.get(element)?.();
mounted.delete(element);
clearTimeout(element._copied);
}
function visit(root, action, match = selector) {
if (!(root instanceof Element)) return;
if (root.matches(match)) action(root);
root.querySelectorAll(match).forEach(action);
}
visit(document.body, mount);
new MutationObserver(records => {
for (const record of records) for (const node of record.removedNodes) if (!node.isConnected) visit(node, cleanup, '*');
for (const record of records) for (const node of record.addedNodes) if (node.isConnected) visit(node, mount);
}).observe(document.body, {childList: true, subtree: true});
'''