Recursive AI

Events and focus

All onehtml docs

How OneHtml dispatches DOM events and moves focus over live documents (MutableDocument) and over host objects that are not nodes. Behaviour here is normative for ports. Spec references: DOM Standard 2.2 "Interface Event", 2.4 "Interface EventTarget" and 2.7 "Interface EventTarget" (listeners), 2.9 "Dispatching events", 4.2.2 "Slots", 4.3.1 (notify mutation observers), 4.8 "Interface ShadowRoot" (retarget); HTML Standard 4.10 (forms, activation), 4.11.1 (details), 6.6 "Focus", 8.1.8.1 "Event handlers".

Not here: hit testing, the UI Events input state machine and default actions (the renderer's), custom element reactions, and MutationObserver itself (mutation-observer.md).

1. Targets and events

  • An EventTargetRef is a node of a MutableDocument or a HostEventTarget (a window, an abort signal, a message port). One dispatcher serves both. A host target's parent comes from its GetTheParent(event) override (default none), which may return another host target.
  • The document node's parent is MutableDocument.EventWindow, a host target, unless the event type is load (DOM 2.9, a document's get the parent) or no window is set.
  • DomEvent is an ordinary object the caller owns. Reset(type, bubbles, cancelable, composed) re-initializes it (DOM "initialize": clears stop and canceled flags, target, related target, IsTrusted, TimeStamp and a subclass payload) and allocates nothing. HostData carries the host's wrapper. Subclasses carry typed UI Events payloads: UiEvent, MouseEvent (an activation event when its type is click), PointerEvent, WheelEvent, KeyboardEvent, FocusEvent, CompositionEvent, InputEvent, TouchEvent, DragEvent, CustomEvent, SubmitEvent.
  • The library reads no clock and decides no trust: the host sets IsTrusted and TimeStamp before dispatch. Reset clears both.
  • Dispatch throws DomException (InvalidStateError) when the event is already being dispatched or was never initialized. InitEvent does nothing while dispatching.

2. Listeners

  • Listeners are kept per document, indexed by node slot; a node with none costs nothing, and a reused slot starts empty. A listener is (type, callback, capture, once, passive, key). The duplicate check and removal use the key (the callback unless the caller passes one: a script runtime passes its callback object).
  • ListenerOptions.Passive null means the DOM default: true for touchstart, touchmove, wheel and mousewheel on a global host target, a document, a document element or the first body.
  • ListenerOptions.Signal is a CancellationToken: canceled before add means not added, canceled later removes the listener. ListenerToken.Remove() removes one listener.
  • Event handlers (SetEventHandler) follow HTML 8.1.8.1: the first non-null value registers one listener at the end of the list, later values replace its callback where it stands, null removes it (a later set goes to the end).
  • Dispatch walks the entries present when it started and skips those removed since (the DOM clone and removed flag, without the copy). A once listener is removed before it is called.
  • A listener exception goes to EventHostHooks.ReportException (default: ignored) and dispatch continues. A trusted event whose type is animationend, animationiteration, animationstart or transitionend and found no listener is tried again under the webkit name (DOM 2.9 invoke).

3. Dispatch and paths

EventDispatcher.Dispatch follows DOM 2.9 as written, with these notes:

  • The path is built before any listener runs and lives in the event; listeners may mutate the tree, commit and dispatch other events. The nodes part is built by one generic routine shared with the snapshot helpers (ShadowDom.ComposedPath), so a renderer and a runtime agree on paths.
  • Get the parent (DOM 2.5): a slottable assigned to a slot has that slot as its parent (named or manual assignment, MutableDocument slot columns); a shadow root's parent is its host, or none when the event is not composed and the root is the root of the event's target.
  • Retargeting (DOM 4.8) is used for the related target and for every touch target, once per path item. Retargeting a node against a host target climbs out of every shadow tree.
  • The dispatch is skipped (nothing is called) when the retargeted related target is the target and the original related target is not.
  • ComposedPath follows the DOM steps with hidden subtree levels, so a closed root's contents are hidden from outside listeners. It is empty outside dispatch. The span form returns the path length and writes at most into.Length entries.
  • After dispatch, Target and RelatedTarget keep the values the last listener saw, and are cleared when that last visible item was in a shadow tree (DOM 2.9 clearTargets). When nothing was called because the dispatch was skipped, RelatedTarget is cleared if it is inside a shadow tree. Touch targets of a TouchEvent are mutated in place during dispatch and left as the last listener saw them (cleared on clearTargets).
  • NonPassiveListenerInvoked reports that a non-passive listener ran; HasNonPassiveListeners(target, event) answers before dispatch for wheel and touch events.
  • No-listener fast path: EventDispatcher.HasListeners(target, type) is a dictionary lookup per document plus the window chain, allocates nothing, and is conservative (true when any node of the document has a listener of the type). A caller that gets false need not build an event. A dispatch with a reused event and listeners allocates nothing in steady state (measured, EventAllocationTests).

4. Activation

DOM 2.9 activation: for a click MouseEvent the activation target is the target if it has activation behaviour, else the first item of the path with it that sees the event (an item with a null shadow-adjusted target only when the event bubbles). Legacy-pre-activation runs before the path is walked, canceled-activation after a canceled dispatch, activation behaviour after an uncanceled one.

OneHtml owns the parts that only change DOM state. Checkedness and selectedness are kept on the node with their dirty flag, apart from the checked and selected attributes (mutable-document.md section 15), so toggling is not an attribute edit and shows in no change set. A disabled form control has no activation behaviour at all:

ElementBehaviour
input checkboxpre-activation toggles checkedness and sets the dirty flag; canceled restores both; activation fires input (bubbles, composed) and change (bubbles) when connected
input radiopre-activation checks it and unchecks its group (same form owner, tree and non-empty name); canceled restores this radio and the previously checked one; activation as for checkbox
labelcalls FocusLabeledControl, then forwards a synthetic untrusted click to its enabled control (for, else first labelable descendant) unless the click came from the control or interactive content inside the label
summarythe first summary of a details toggles its open attribute (the toggle event is the host's task)
submit and reset buttons (input, button)resolve the form owner (form attribute, else nearest ancestor), ask BeforeSubmit, fire a cancelable submit (SubmitEvent) or reset event, then reset the controls' state (reset) and call the host

Trust. Events the user agent makes by itself are trusted: slotchange (DOM 4.2.2.5 "signal a slot change", fired at the notify step), and the focus events of the focus update steps. The events an activation fires take IsTrusted from the click that activated the element: input and change of a checkbox or radio, submit of a submit button and reset of a reset button are trusted after a host-dispatched pointer or keyboard click (the host sets IsTrusted on it, as everywhere) and untrusted after Click() or a script's DispatchEvent. The label's forwarded click is the standard's synthetic click and is always untrusted, so the input and change it causes are too, whatever the first click was. Disabled controls, summary (no event; toggle is the host's task) and registered ActivationBehaviors fire nothing here. The DOM Standard's "fire an event" makes the events it creates trusted whoever calls it, so a strict reading would also make the click() case trusted and leaves open whether script input may be told from user input; OneHtml follows the activating click so that a host can tell them apart.

Host callbacks (EventHostHooks): FollowHyperlink (a, area with href), BeforeSubmit, SubmitForm, ResetForm, FocusLabeledControl, FocusChanged. Anything else (select popups, caret placement, custom controls) is a host-registered ActivationBehavior per element (SetActivationBehavior), run after the built-in behaviour. A disabled form control ignores submit, reset and button activation; node.Click() does nothing on a disabled control, while dispatchEvent of a click reaches it (HTML 4.10.18.5 limits real clicks and click() only).

MutableDocument.EraseAllEventListeners(includeWindow) is HTML 8.4.3 "erase all event listeners and handlers" for a document: listeners and handlers of the document and every shadow-including descendant (not template contents or detached nodes), and of EventWindow when asked. DocumentOpenHost.EraseEventListeners calls it with the window included, in step 9 and 10 order before the children are replaced; a host with a different window overrides that method.

5. slotchange

MutableDocument.NotifyMutationObservers takes the signalled slots, notifies observers, then fires slotchange (bubbles, not composed, not cancelable) at each slot still alive that has a listener, then calls MutationHooks.SlotChangeSteps (DOM 4.3.1 steps 3, 4, 6). Slot signalling itself is in the mutable shadow layer (shadow-dom.md).

6. Focus

  • Focusable area (HTML 6.6.2): Focus.IsFocusableByMarkup and the snapshot twin. An element with a valid tabindex, a/area with href, button, select, textarea, iframe, a non-hidden input, the first summary of a details, or an editing host; not disabled; not a shadow host whose root delegates focus. Rendering is the host's: override EventHostHooks.IsFocusable (and IsInert) or pass a predicate to the snapshot functions.
  • Focus delegate (6.6.4): Focus.FocusDelegate and ShadowDom.FocusDelegate. For a host whose root delegates focus: the first descendant of the root with an autofocus attribute that is a focusable area (or delegates), else the first focusable descendant in tree order, through nested delegating hosts. A nested delegation is bounded to 128 levels, never by recursion on input depth. For FocusTrigger.Click an autofocus candidate must be focusable itself.
  • Sequential order (6.6.5): Focus.SequentialOrder and ShadowDom.SequentialFocusOrder build the flattened tabindex-ordered scope of a document. Scope owners are the document, shadow hosts and slots; each element belongs to the scope of its focus navigation owner (a light child of a host: its assigned slot, unassigned: none; a child of a shadow root: the host). Positive tabindex ascending first, then tabindex 0 or none in tree order; negative tabindex leaves the element (and a scope owner's contents) out. A scope owner that is not itself focusable is replaced by its scope, a focusable one is followed by it. A slot's fallback content is the slot's own scope while the slot has no assigned nodes (HTML 6.6.2 says an element's owner is its parent's owner, which would put fallback content in the enclosing scope; the WPT pages focus-navigation-slot-fallback* and focus-with-negative-index order it as the slot's scope, as Chrome does), and is left out of the order while the slot has assigned nodes. Only a slot inside a shadow tree has fallback content.
  • Showing popovers (6.6.2 "focus navigation owner"). A popover that is showing (FormStateKind.PopoverOpen set by the host; on a snapshot, the FormStateOverrides passed to the SequentialFocusOrder / NextSequentialFocus overloads that take one) is in the scope of its invoker instead of its place in the tree, so its focusable contents follow the invoker directly and Tab then goes on to what follows the invoker. The invoker is taken as the first button (or input of type button, submit, reset or image) in tree order, in the popover's own tree, whose popovertarget names the popover's id, that is not inside the popover and does not have popovertargetaction=hide; the library has no record of which control actually opened it. A popover with no such invoker, or that is not showing, stays in tree order.
  • Sequential navigation search (6.6.5): Focus.NextSequential and ShadowDom.NextSequentialFocus give the element Tab or Shift+Tab reaches from a start element. A start in the order moves to its neighbour. A start outside it (negative tabindex, or inside a scope whose owner was left out) is placed by tree order among its scope's items, then, when its scope has nothing further, the same is done for the owner (host or slot) in the owner's scope; the first or last focusable area of the item found is the answer. This is what Chrome does from the end of a shadow tree (focus goes on to what follows the host) and not the spec's flat "DOM" selection, which would pick k1 rather than k0 in focus-with-negative-index.
  • Focus update steps: Focus.FocusElement (resolves a delegating host, keeps a focused descendant of the host), Unfocus, Update. The sequence is blur, focusout at the old element, the focused element changes, then focus, focusin at the new one: FocusEvent, trusted, composed, not cancelable, blur/focus not bubbling. The related target is the other element; the dispatcher retargets it per path item. No event is made when nobody listens. Focus.ActiveElement(scope) retargets the focused element against a document or shadow root.

7. Measured

Indicative, Debug build, one core: wrapping a parsed 6,000-node document in a MutableDocument copies the node columns, about 1 ms; WorkingSnapshot.ToMutable allocates nothing and is O(1).

8. Deviations, decisions and limits

  • Form state is attributes (above); the indeterminate state and the toggle event are not modelled.
  • A host chain is limited to 1,024 targets, a node path to 1,048,576 items (DomException LimitExceeded), focus delegation to 128 levels.
  • Skipped dispatch (a node target whose related target retargets to it, DOM 2.9 first if): nothing is called, Target stays null, a related target inside a shadow tree is cleared, and Dispatch still returns !DefaultPrevented. WPT relatedTarget.window.js disagrees with itself here: its "Retarget a shadow-tree relatedTarget" test expects the target and the host back, and "Reset targets on early return" expects both null for the same input. A black-box probe in Chrome 149 and in Chromium 157 (a closed-shadow host dispatching a FocusEvent whose related target is its own shadow root) gives target null, related target unchanged and dispatchEvent returning true, so Chrome passes neither; this library follows DOM 2.9 and clears targets. A second assertion on that page (a click at a node whose related target is a shadow root should have its target and related target null in the activation behaviour) is also not followed: the related target retargets to the host, outside any shadow tree, so DOM 2.9's clearTargets does not apply.
  • Not translated, with reasons. From dom/events/ at the pinned commit:
    • realm and script semantics (the script runtime wraps these over the dispatcher): EventListener-handleEvent*, EventListener-incumbent-global*, EventListener-invoke-legacy, EventListener-addEventListener.sub.window.js, Event-dispatch-throwing-multiple-globals, Event-timestamp-cross-realm-getter, Event-subclasses-constructors, Event-constructors dictionary coercion, EventTarget-this-of-listener, EventTarget-add-listener-platform-object, EventTarget-constructible, EventTarget-window-constructor, KeyEvent-initKeyEvent, event-global*, Body-FrameSet-Event-Handlers, event-src-element-nullable;
    • clocks and browsing contexts (the host's): Event-timestamp-high-resolution*, Event-timestamp-safe-resolution, event-listener-not-fully-active*, focus-event-document-move, pointer-event-document-move;
    • hit testing, real clicks, animations and rendering (onerender): Event-dispatch-on-disabled-elements (its real click, transition and animation parts; the dispatch parts are translated), event-disabled-dynamic, click-on-absolute-pseudo, element-click, mouse-event-retarget, no-focus-events-at-clicking-editable-content-in-link, keypress-dispatch-crash, Event-dispatch-click.tentative, handler-count.
    • Everything else under dom/events/ that asserts DOM-level behaviour is covered by EventDispatchTests, ActivationPageTests and ShadowEventTests.
  • Shadow DOM events (18) and focus (63): each row of docs/wpt-shadow-dom.md says in the inventory's note column which test translates it or why it belongs to the renderer or the scoped cascade. Pages with a regular format run from the vendored files (WptFocusNavigationTests, WptEventLogPageTests, ShadowEventTests.Event_path_expectations_of_the_pages); the rest are written out in WptFocusBehaviourTests, ShadowEventPageTests, BehaviourTests.