stimeo-ui 0.18.0 → 0.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -2
- package/dist/cable/index.d.ts +2 -1
- package/dist/controllers/command_palette_controller.js +1 -0
- package/dist/controllers/command_palette_controller.js.map +1 -1
- package/dist/controllers/dismissible_controller.js +2 -0
- package/dist/controllers/dismissible_controller.js.map +1 -1
- package/dist/controllers/editable_controller.js +1 -0
- package/dist/controllers/editable_controller.js.map +1 -1
- package/dist/controllers/form_field_controller.d.ts +2 -1
- package/dist/controllers/input_mask_controller.d.ts +2 -1
- package/dist/controllers/input_mask_controller.js +23 -0
- package/dist/controllers/input_mask_controller.js.map +1 -1
- package/dist/controllers/multi_select_controller.d.ts +2 -1
- package/dist/controllers/multi_select_controller.js +21 -1
- package/dist/controllers/multi_select_controller.js.map +1 -1
- package/dist/controllers/pointer_drag_controller.d.ts +1 -0
- package/dist/controllers/pointer_drag_controller.js +6 -1
- package/dist/controllers/pointer_drag_controller.js.map +1 -1
- package/dist/controllers/popover_controller.d.ts +6 -2
- package/dist/controllers/popover_controller.js +9 -0
- package/dist/controllers/popover_controller.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +63 -2
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.d.ts +10 -1
- package/dist/inspector/cli.js +5 -0
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.d.ts +1 -1
- package/dist/inspector/cli_bin.js +9 -0
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/manifest.json +2 -2
- package/dist/positioning/index.d.ts +2 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/state_reason.ts","../../src/utils/action_source.ts","../../src/utils/template.ts","../../src/utils/announce.ts","../../src/utils/shared_registry.ts","../../src/utils/aria_ids.ts","../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/utils/attribute_write.ts","../../src/utils/attribute_lease.ts","../../src/utils/element_part.ts","../../src/utils/roving_tabindex.ts","../../src/utils/chip_row.ts","../../src/utils/composition_tracker.ts","../../src/utils/field_mirror.ts","../../src/utils/listener_set.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/morph_render_watcher.ts","../../src/utils/move_counter.ts","../../src/utils/number_bounds.ts","../../src/utils/coerce.ts","../../src/utils/number_value.ts","../../src/utils/option_scroll.ts","../../src/utils/state_regions.ts","../../src/utils/focus_candidate.ts","../../src/utils/query_open_descendants.ts","../../src/utils/tabindex_loan.ts","../../src/utils/target_selector.ts","../../src/utils/template_row.ts","../../src/controllers/multi_select_controller.ts"],"names":["registry","entry","button","holdsFocus","above","name"],"mappings":";;AA0CA,IAAM,YAAA,uBAAmB,GAAA,CAAI,CAAC,QAAQ,OAAA,EAAS,SAAA,EAAW,UAAU,CAAC,CAAA;AAGrE,IAAM,cAAA,uBAAqB,GAAA,CAAI,CAAC,cAAc,YAAA,EAAc,cAAA,EAAgB,cAAc,CAAC,CAAA;AA0BpF,SAAS,eAAe,KAAA,EAA4D;AACzF,EAAA,IAAI,CAAC,OAAO,OAAO,KAAA;AACnB,EAAA,IAAI,YAAA,CAAa,GAAA,CAAI,KAAA,CAAM,IAAI,GAAG,OAAO,OAAA;AACzC,EAAA,IAAI,cAAA,CAAe,GAAA,CAAI,KAAA,CAAM,IAAI,GAAG,OAAO,SAAA;AAC3C,EAAA,OAAO,MAAA;AACT;;ACxDO,SAAS,aAAa,MAAA,EAA4C;AACvE,EAAA,IAAI,kBAAkB,WAAA,EAAa;AACjC,IAAA,OAAO,EAAE,OAAO,IAAA,EAAM,IAAA,EAAM,QAAQ,MAAA,EAAQ,MAAA,EAAQ,QAAQ,KAAA,EAAM;AAAA,EACpE;AACA,EAAA,MAAM,QAAQ,MAAA,IAAU,IAAA;AACxB,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,IAAA,EAAM,KAAA,EAAO,aA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CAAO,CAAC,WAAW,MAAA,CAAO,YAAA,CAAa,eAAe,CAAA,KAAM,MAAM,CAAA;AAAA,EAC9F;AAAA,EAGA,IAAI,OAAA,GAAoB;AACtB,IAAA,OAAO,IAAA,CAAK,iBAAiB,GAAA,CAAI,CAAC,WAAW,IAAA,CAAK,YAAA,CAAa,MAAM,CAAC,CAAA;AAAA,EACxE;AAAA,EAMA,IAAI,eAAA,GAA0B;AAC5B,IAAA,IAAI,IAAA,CAAK,QAAA,IAAY,CAAA,EAAG,OAAO,CAAA;AAC/B,IAAA,OAAO,KAAK,GAAA,CAAI,CAAA,EAAG,KAAK,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAC,CAAA;AAAA,EAC9C;AAAA,EAGA,SAAA,CAAU,MAAmB,IAAA,EAAqB;AAChD,IAAA,IAAA,CAAK,WAAA,CAAY,KAAA,CAAM,IAAA,EAAM,IAAA,GAAO,OAAO,EAAE,CAAA;AAAA,EAC/C;AAAA,EAGA,IAAI,SAAA,GAAqB;AACvB,IAAA,OAAO,CAAC,IAAA,CAAK,aAAA,IAAiB,IAAA,CAAK,WAAW,MAAA,KAAW,KAAA;AAAA,EAC3D;AAAA,EAEA,IAAI,QAAA,GAAmB;AACrB,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,MACnB,IAAA;AAAA,MACA,KAAA;AAAA,MACA,IAAA,CAAK,QAAA;AAAA,MACL,sBAAA,CAAsB,OAAO,GAAA,CAAI,OAAA;AAAA,MACjC,uBAAsB,gBAAA,CAAiB;AAAA,KACzC;AAAA,EACF;AACF","file":"multi_select_controller.js","sourcesContent":["/**\n * Why a component's public state moved, carried as `detail.reason`\n * on the state event that reports the move.\n *\n * The attribute a component publishes (`aria-expanded`, `hidden`, `data-state`)\n * only says *what* the state is now. A subscriber that mirrors the state\n * elsewhere, or reports it, needs *why*: closing on `Escape` and closing because\n * the consumer called the action are the same attribute write and different\n * events to the page around it.\n *\n * `\"api\"` is the one every subscriber has to look at. A close the consumer asked\n * for arrives back at their own listener, so a listener that closes something\n * else on `close` loops unless it ignores its own calls.\n *\n * | Reason | The state moved because |\n * | --- | --- |\n * | `\"user\"` | a control of this component was operated |\n * | `\"select\"` | an item inside it was activated |\n * | `\"escape\"` | `Escape` was pressed and this layer owned it |\n * | `\"outside\"` | a pointer landed outside it, or on its backdrop |\n * | `\"focus\"` | focus entered or left it |\n * | `\"pointer\"` | the pointer entered or left it |\n * | `\"scroll\"` | a tracked scroll container scrolled |\n * | `\"api\"` | a public action was called with no DOM event |\n * | `\"timeout\"` | an automatic timer advanced or dismissed the state |\n * | `\"limit\"` | a capacity limit dismissed an item |\n * | `\"media\"` | an operating-system media preference changed |\n */\nexport type StateReason =\n | \"user\"\n | \"select\"\n | \"escape\"\n | \"outside\"\n | \"focus\"\n | \"pointer\"\n | \"scroll\"\n | \"api\"\n | \"timeout\"\n | \"limit\"\n | \"media\";\n\n/** Focus modality: the events a focus move delivers to an action. */\nconst FOCUS_EVENTS = new Set([\"blur\", \"focus\", \"focusin\", \"focusout\"]);\n\n/** Pointer modality: the crossing events an action is bound to for hover. */\nconst POINTER_EVENTS = new Set([\"mouseenter\", \"mouseleave\", \"pointerenter\", \"pointerleave\"]);\n\n/**\n * Reads the interaction behind a **public action** from the DOM event it was\n * handed.\n *\n * Stimulus always passes the event to an action it invoked from `data-action`,\n * and a consumer calling the method themselves passes nothing — which is what\n * separates `\"api\"` from the rest.\n *\n * Only an action entry may resolve a reason this way. Inside the component the\n * event type no longer identifies the interaction: one `click` is the trigger\n * being pressed, the page outside being pressed, and an item being activated,\n * and those paths pass their own reason instead.\n *\n * @param event - The event the action received, if any.\n * @returns `\"api\"` with no event, else the modality the event type names, else\n * `\"user\"`.\n *\n * @example\n * ```ts\n * toggle(event?: Event): void {\n * this.#apply(!this.#isOpen, stateReasonFor(event));\n * }\n * ```\n */\nexport function stateReasonFor(event?: Event | null): \"user\" | \"focus\" | \"pointer\" | \"api\" {\n if (!event) return \"api\";\n if (FOCUS_EVENTS.has(event.type)) return \"focus\";\n if (POINTER_EVENTS.has(event.type)) return \"pointer\";\n return \"user\";\n}\n","import { stateReasonFor } from \"./state_reason\";\n\n/** The DOM binding and origin of a public action, or its explicit API element. */\nexport interface ActionSource {\n readonly event: Event | null;\n readonly host: Element | null;\n readonly origin: Element | null;\n readonly reason: ReturnType<typeof stateReasonFor>;\n}\n\n/**\n * Normalizes an action's DOM event or explicit element without choosing an owned target.\n *\n * Event hosts and origins stay separate so consumers can yield to nested controls.\n * An explicit element supplies both, with no DOM event and an `\"api\"` reason.\n * Consumers resolve current targets and enforce their own scope and interaction rules.\n *\n * @param source - The DOM event, explicit element, or absent optional argument.\n * @returns The source elements, original event and public interaction reason.\n */\nexport function actionSource(source?: Event | HTMLElement): ActionSource {\n if (source instanceof HTMLElement) {\n return { event: null, host: source, origin: source, reason: \"api\" };\n }\n const event = source ?? null;\n return {\n event,\n host: event?.currentTarget instanceof Element ? event.currentTarget : null,\n origin: event?.target instanceof Element ? event.target : null,\n reason: stateReasonFor(event),\n };\n}\n","/**\n * Fills `{name}` placeholders in a localized template from the own entries of `values`.\n *\n * Announcement and value-text templates share this one substitution, so a consumer writes\n * `\"{percent}% complete\"` in one attribute and gets the same rules everywhere. A\n * placeholder with no matching entry is left as authored rather than blanked, which\n * keeps a typo visible instead of silently swallowing the word.\n * Every occurrence is filled in one pass. Inserted strings stay literal, including\n * replacement-pattern characters and text that resembles another placeholder.\n */\nexport function fillTemplate(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, name: string) => {\n const replacement = Object.hasOwn(values, name) ? values[name] : undefined;\n return replacement === undefined ? match : String(replacement);\n });\n}\n","export { fillTemplate } from \"./template\";\n\n/**\n * Sends one message to the page's shared `stimeo--announcer`.\n *\n * A message that has to reach assistive tech is not put into a live region created\n * or un-hidden along with it: a region only announces what changes *after* assistive\n * tech already knows about it, which such a region cannot satisfy. The announcer has\n * to be in the page before any message is handed to it — one sent while no announcer\n * is listening is not read — so state changes reach it as an event and it does the\n * reading.\n *\n * The event goes to `window` because the announcer is usually a sibling high in the\n * document rather than an ancestor of the component dispatching it.\n *\n * Wording comes from the consumer — this helper adds no text of its own — so an\n * empty message is silently dropped and nothing is announced.\n *\n * @example\n * ```ts\n * announce(this.announceTextValue, { assertive: false });\n * ```\n */\nexport function announce(message: string, options: { assertive?: boolean } = {}): void {\n const text = message.trim();\n if (text.length === 0) return;\n window.dispatchEvent(\n new CustomEvent(\"stimeo--announcer:announce\", {\n detail: { message: text, assertive: options.assertive === true },\n }),\n );\n}\n","/**\n * One registry per page for every copy of the library.\n *\n * Each `stimeo-ui/controllers/*` file, and each opt-in entry, is built on its own and carries\n * its own copy of every utility it uses, so a page that imports controllers one by one, or one\n * of them next to the barrel, evaluates a utility several times. A registry that coordinates\n * instances of different controllers — the stacks of leased values, the loans of a\n * `tabindex`, the Escape layers, the focus traps — must not be split by that: a dialog inside\n * a drawer, or a character counter and a form field on one input, coordinate whichever files\n * they came from. So such a registry lives once on `globalThis`, under a `Symbol.for` key the\n * copies agree on, and the first copy to ask for it creates it.\n *\n * The key names the registry and the version of its shape\n * (`stimeo-ui.<utility>.registry.v<n>`). Copies whose registries have the same shape share\n * one; a release that changes the shape changes the version, so a copy of another release\n * keeps a registry of its own instead of reading entries it does not understand — the two\n * then coordinate within each release only. An entry another copy put in a registry is read\n * through its fields alone, never through `#private` members, which belong to the class of\n * the copy that created it.\n */\n\n/**\n * The registry stored under `key`, created by `create` on first use.\n *\n * @param key - `stimeo-ui.<utility>.registry.v<n>`: the version is that of the shape `create`\n * returns.\n * @param create - Builds the empty registry.\n */\nexport function sharedRegistry<T extends object>(key: string, create: () => T): T {\n const symbol = Symbol.for(key);\n const scope = globalThis as unknown as Record<symbol, T | undefined>;\n const existing = scope[symbol];\n if (existing !== undefined) return existing;\n const registry = create();\n Object.defineProperty(globalThis, symbol, { value: registry });\n return registry;\n}\n","import { sharedRegistry } from \"./shared_registry\";\n\n/**\n * Minimal id primitives for wiring ARIA relationships.\n *\n * Accessible relationships such as `aria-describedby`, `aria-errormessage`,\n * `aria-labelledby`, and `aria-activedescendant` reference their targets by DOM\n * `id`. When a controller must establish such a relationship but the consumer's\n * markup left the target without an `id`, it needs to mint one that is stable for\n * the page's lifetime and guaranteed not to collide with another generated id.\n *\n * These helpers own *only* id generation/assignment. The linking policy (which\n * attribute, what order, when to add or remove it) stays in each controller —\n * this deliberately avoids a premature generic \"ARIA linker\" abstraction.\n */\n\n/**\n * Monotonic counter backing {@link uniqueId}, shared by every entry copy so generated\n * ids are distinct even before their elements enter the document.\n */\nconst ids = sharedRegistry(\"stimeo-ui.aria-ids.registry.v1\", () => ({ counter: 0 }));\n\n/**\n * Returns a unique, DOM-id-safe string of the form `` `${prefix}-${n}` `` where\n * `n` increases on each call.\n *\n * The counter alone guarantees uniqueness against other *generated* ids, but a\n * consumer-authored element could already own `` `${prefix}-${n}` ``. When a\n * `document` is available the candidate is therefore advanced until no element\n * with that id exists, so a generated id never collides with author markup\n * either — the minimal \"id registry\" guarantee these helpers exist to provide.\n *\n * @param prefix - Leading segment of the id (e.g. a controller's identifier).\n * Defaults to `\"stimeo\"`.\n */\nexport function uniqueId(prefix = \"stimeo\"): string {\n let candidate: string;\n do {\n ids.counter += 1;\n candidate = `${prefix}-${ids.counter}`;\n } while (typeof document !== \"undefined\" && document.getElementById(candidate) !== null);\n return candidate;\n}\n\n/**\n * Returns `element`'s existing `id`, or assigns it a freshly generated\n * {@link uniqueId} (with the given `prefix`) and returns that. Idempotent: an\n * element that already has an id keeps it, so consumer-authored ids are never\n * overwritten.\n *\n * @param element - The element to read or stamp an `id` onto.\n * @param prefix - Prefix forwarded to {@link uniqueId} when one must be generated.\n * @returns The element's id (existing or newly assigned).\n */\nexport function ensureId(element: Element, prefix = \"stimeo\"): string {\n if (element.id) return element.id;\n const id = uniqueId(prefix);\n element.id = id;\n return id;\n}\n","/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/**\n * The element whose writing direction orders a grid's columns: the nearest\n * `<table>` holding `grid` inside `root`, else `grid` itself. Table columns follow\n * the table's direction, so a direction declared only on a row group such as\n * `<tbody>` does not reorder them and must not reverse the arrows either.\n */\nexport function gridDirectionElement(grid: Element, root: Element): Element {\n const table = grid.closest(\"table\");\n return table !== null && root.contains(table) ? table : grid;\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — for example `Alt+Down`/`Alt+Up`, which the APG Combobox\n * pattern makes optional and `stimeo--combobox` implements.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n\n/**\n * True when a press carries Alt, Control, Meta, or Shift, regardless of its key.\n *\n * This predicate reports modifier presence only; key ownership stays with the\n * caller. Check the widget's implemented key/modifier bindings and their state\n * conditions before using this result to yield a chord. An unimplemented chord\n * must not fall through to the bare-key behavior.\n *\n * Dedicated bindings, such as a grid's Control+Home/End navigation, belong in\n * the caller. Unlike {@link isReservedArrowChord}, this function examines every\n * key and has no arrow-specific reservation or `allow` list.\n *\n * @example\n * ```ts\n * // A Home/End handler with no modifier bindings yields every modified press.\n * case \"Home\":\n * case \"End\":\n * if (hasModifierChord(event)) return;\n * ```\n */\nexport function hasModifierChord(event: KeyboardEvent): boolean {\n return event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;\n}\n","/**\n * Reflects a serialized attribute value only when the current value differs.\n *\n * A same-value `setAttribute` still queues a mutation record for every observer, so an\n * unchanged value writes nothing.\n *\n * @param element - The element whose attribute is reflected.\n * @param name - The attribute name, using the non-namespaced DOM API.\n * @param value - The serialized value, or null to remove the attribute.\n * @param beforeWrite - Called only for a change, before the DOM mutation, so the\n * caller can record ownership or identify its own observer records.\n * @returns Whether an attribute was written or removed.\n */\nexport function setAttributeIfChanged(\n element: Element,\n name: string,\n value: string | null,\n beforeWrite?: () => void,\n): boolean {\n if (element.getAttribute(name) === value) return false;\n beforeWrite?.();\n if (value === null) element.removeAttribute(name);\n else element.setAttribute(name, value);\n return true;\n}\n","import { setAttributeIfChanged } from \"./attribute_write\";\nimport { sharedRegistry } from \"./shared_registry\";\n\n/** What a lease's record says: the author's value, its last write, the leases beneath. */\ninterface AttributeLeaseRecord {\n readonly original: string | null;\n readonly written: string | null;\n /** Whether it hands back what the lease right beneath it wrote last. */\n readonly linked: boolean;\n /** The records of the other owners' leases beneath it, nearest first. */\n readonly beneath: readonly string[];\n}\n\n/** One lease's hold on one element's attribute, in the stack every lease of it shares. */\ninterface AttributeHold {\n /** The lease holding it; `null` for a hold read from a copy's record until its lease takes it. */\n lease: object | null;\n readonly record: string;\n written: string | null;\n /** What it hands back with nothing beneath it: the author's value. */\n readonly original: string | null;\n /** Whether it hands back what the hold beneath it wrote last instead. */\n linked: boolean;\n}\n\n/** The holds on each element by attribute, and every lease's record name by attribute. */\ninterface AttributeLeaseRegistry {\n readonly stacks: WeakMap<Element, Map<string, AttributeHold[]>>;\n readonly names: Map<string, Set<string>>;\n}\n\n/** Holds and record names coordinate across separately built package entries. */\nconst registry = sharedRegistry(\n \"stimeo-ui.attribute-lease.registry.v1\",\n (): AttributeLeaseRegistry => ({ stacks: new WeakMap(), names: new Map() }),\n);\n\n/** Whether a parsed record entry is an attribute value: a string, or `null` for absence. */\nfunction isAttributeValue(value: unknown): value is string | null {\n return value === null || typeof value === \"string\";\n}\n\n/**\n * Reads the record a lease left on `element`: the author's value, the value the lease wrote\n * last, whether it hands back the value beneath it (`false` before the names when it does not)\n * and the records beneath it. `undefined` when the record is missing or holds anything else.\n */\nfunction readLeaseRecord(element: Element, record: string): AttributeLeaseRecord | undefined {\n try {\n const parsed: unknown = JSON.parse(element.getAttribute(record) ?? \"null\");\n if (!Array.isArray(parsed)) return undefined;\n const [original, written, ...rest] = parsed as unknown[];\n const linked = rest[0] !== false;\n const beneath = linked ? rest : rest.slice(1);\n if (!beneath.every((under): under is string => typeof under === \"string\")) return undefined;\n return isAttributeValue(original) && isAttributeValue(written)\n ? { original, written, linked, beneath }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The element's stack, seeded from complete ownership records once. */\nfunction attributeStack(element: Element, attribute: string): AttributeHold[] {\n const byAttribute = registry.stacks.get(element) ?? new Map<string, AttributeHold[]>();\n registry.stacks.set(element, byAttribute);\n const known = byAttribute.get(attribute);\n if (known) return known;\n const found: (AttributeLeaseRecord & { readonly record: string })[] = [];\n for (const record of registry.names.get(attribute) ?? []) {\n const read = readLeaseRecord(element, record);\n if (read) found.push({ ...read, record });\n }\n const depth = ({ beneath }: (typeof found)[number]) =>\n beneath.filter((name) => found.some((other) => other.record === name)).length;\n const stack = found\n .sort((one, other) => depth(one) - depth(other))\n .map(({ record, written, original, linked }, index) => ({\n lease: null,\n record,\n written,\n original,\n linked: linked && index > 0,\n }));\n byAttribute.set(attribute, stack);\n return stack;\n}\n\n/** The lease's live hold or the unclaimed hold described by its owner's record. */\nfunction findHold(\n stack: readonly AttributeHold[],\n lease: object,\n record: string,\n): AttributeHold | undefined {\n return (\n stack.find((held) => held.lease === lease) ??\n stack.find((held) => held.lease === null && held.record === record)\n );\n}\n\n/**\n * Inspects a derived writer's continuation without acquiring or returning a hold.\n * A covered hold may update beneath its cover. Without a hold, the expected authored\n * value is compared with the original beneath any temporary cover. The original\n * distinguishes an absent attribute from an empty one.\n */\nexport function readAttributeLease(\n element: Element,\n attribute: string,\n owner: string,\n lease: object,\n expected: string | null,\n): { readonly allowed: boolean; readonly original: string | null } {\n const stack = attributeStack(element, attribute);\n const hold = findHold(stack, lease, `data-${owner}-${attribute}-lease`);\n const current = element.getAttribute(attribute);\n const covering = [...stack].reverse().find((other) => other.written === current);\n const original = (hold ?? covering)?.original;\n const authored = original === undefined ? current : original;\n return {\n original: authored,\n allowed: hold\n ? current === hold.written ||\n stack.slice(stack.indexOf(hold) + 1).some((above) => above.written === current)\n : authored === expected,\n };\n}\n\n/**\n * The value `element`'s author wrote for `attribute`, as the record a lease of any owner leaves\n * on the element carries it; `undefined` while no lease leaves one, as when nothing has moved\n * the attribute off the author's value. A field a reveal turned from `password` into `text`\n * still reads `\"password\"` here.\n */\nexport function leasedAuthorValue(element: Element, attribute: string): string | null | undefined {\n const suffix = `-${attribute}-lease`;\n for (const name of element.getAttributeNames()) {\n if (!name.startsWith(\"data-\") || !name.endsWith(suffix)) continue;\n const record = readLeaseRecord(element, name);\n if (record) return record.original;\n }\n return undefined;\n}\n\n/**\n * Temporarily controls one attribute across a changing set of elements.\n *\n * The first write remembers the authored value, including the distinction between\n * an absent attribute and an authored empty string. Returning a lease restores that\n * value only while the attribute still matches the controller's last write. If a\n * consumer changed it in the meantime, the consumer owns the new value and teardown\n * leaves it alone.\n *\n * A `null` write deliberately removes the attribute while retaining the lease. This\n * is useful for derived ARIA whose valid absence is itself controller state, such as\n * an unbounded `aria-valuemin` or a blank spinbutton's `aria-valuenow`.\n *\n * **Every lease of an attribute shares one stack of holds per element**, whatever its owner\n * and whichever file of the package constructed it (the stacks are one per page): the holds\n * sit in the order their leases first wrote the element, each with the value it wrote last.\n * The element's value is the highest hold's that carries it, and the page's when none does.\n * A write reaches the element unless a hold above the writer carries the element's value: the\n * top hold always shows its writes, a hold beneath it shows nothing while a hold above keeps\n * its value on the element, and once the page has put a value there that no hold carries, the\n * next write of any hold replaces it. A return gives a value back only from the hold the\n * element's value is: the value the hold beneath it wrote last, or the author's once nothing\n * is beneath it; any other return only leaves the stack, and the page's value stays. Holds\n * that wrote the same value are told apart by the stack, never by the value: the higher one\n * keeps it. A first write over a top hold whose value the page has replaced takes the\n * element's value as the author's. Two instances of one controller on one element — an\n * element outside their scope — stack the same way.\n *\n * A **base lease** (`{ base: true }`) holds the element's own state rather than a value over\n * it — a form field's ARIA on its control is one — so its first write goes to the bottom of\n * the stack, beneath the leases of other owners already there: a temporary value another\n * owner leased stays shown and returns to the base lease's latest value.\n *\n * **The stack travels with the element.** While a hold shows a value other than the author's,\n * lies on another hold or is covered by one, the element carries its owner's record\n * `data-<owner>-<attribute>-lease`: JSON of the author's value and the value the hold wrote\n * last (each a string, or `null` for an absent attribute), `false` where the hold hands back\n * the author's value rather than the latest value of the hold beneath it, and the records of\n * every hold beneath it, nearest first. Returning the last lease of an owner removes its\n * record. A copy of the element — a page Turbo restores from its cache is one — therefore\n * carries the stack, and the first lease to touch the copy reads it back under the record\n * names of the leases constructed so far, which include every lease that wrote a record the\n * cache holds, and orders the holds by the records each one lists beneath it. Each lease takes\n * the hold its owner's record describes over in place. Complete records for distinct owners\n * preserve their order across a copy. The records describe holds by owner, not by instance:\n * one owner holding the element more than once leaves only its topmost hold's record, which\n * the first of its leases to write or return on the copy takes. Lower holds of that owner and\n * their positions are absent; mutually listed owners cannot express their full live order.\n * A hold that showed the author's value alone carries no record and is taken by its first\n * write on the copy. Missing or unreadable records also leave their holds unknown, so copying\n * the DOM does not promise identical decisions for every live stack. Without a record it can\n * read, a new stack takes the current value as the author's. A Turbo morph removes records\n * absent from the server HTML; existing holds remain in memory until their leases return.\n *\n * The lease has no lifecycle of its own, so it never subscribes to document events,\n * and nothing rewinds a live page before Turbo caches it: `turbo:before-cache` also\n * fires on pages that stay.\n */\nexport class AttributeLease<T extends Element = Element> {\n readonly #attribute: string;\n readonly #record: string;\n readonly #base: boolean;\n readonly #preserveAuthor: boolean;\n readonly #held = new Set<T>();\n\n /**\n * @param attribute - The attribute whose temporary values this lease owns.\n * @param owner - Names the record on the element; the controller's identifier.\n * @param options - `base`: written beneath the other owners' leases;\n * `preserveAuthor`: a new base hold keeps a current value that no hold carries as authored.\n */\n constructor(\n attribute: string,\n owner: string,\n options: { readonly base?: boolean; readonly preserveAuthor?: boolean } = {},\n ) {\n this.#attribute = attribute;\n this.#record = `data-${owner}-${attribute}-lease`;\n this.#base = options.base === true;\n this.#preserveAuthor = options.preserveAuthor === true;\n const names = registry.names;\n names.set(attribute, (names.get(attribute) ?? new Set<string>()).add(this.#record));\n }\n\n /** Writes or removes the leased attribute while preserving its authored value. */\n write(element: T, value: string | null): void {\n const stack = attributeStack(element, this.#attribute);\n const hold = this.#take(stack) ?? this.#acquire(element, stack);\n this.#held.add(element);\n const shows = !this.#covered(element, stack, hold);\n hold.written = value;\n this.#mark(element, stack);\n if (shows) this.#reflect(element, value);\n }\n\n /**\n * Returns one lease, also on a restored copy, to the value the hold beneath it wrote last or\n * the author's, without overwriting a value a consumer wrote since. Says whether there was a\n * lease to return: a hold this lease has, or the hold a copy's record describes while no live\n * lease of the owner has taken it — a copy of a page an earlier connection wrote carries one.\n */\n return(element: T): boolean {\n const held = this.#held.delete(element);\n const known = registry.stacks.get(element)?.has(this.#attribute);\n const stack =\n held || known || element.hasAttribute(this.#record)\n ? attributeStack(element, this.#attribute)\n : [];\n const hold = this.#take(stack);\n if (!hold) return false;\n const carries = element.getAttribute(this.#attribute) === hold.written;\n const owns = carries && !this.#covered(element, stack, hold);\n const index = stack.indexOf(hold);\n stack.splice(index, 1);\n const above = stack[index];\n if (above) above.linked &&= hold.linked;\n this.#mark(element, stack);\n if (!owns) return true;\n const below = hold.linked ? stack[index - 1] : undefined;\n this.#reflect(element, below ? below.written : hold.original);\n return true;\n }\n\n /** Returns every lease it holds, with the same ownership check as {@link return}. */\n returnAll(): void {\n for (const element of Array.from(this.#held)) this.return(element);\n }\n\n /** Its hold in `stack`, taking over one read from its record. */\n #take(stack: AttributeHold[]): AttributeHold | undefined {\n const hold = findHold(stack, this, this.#record);\n if (hold) hold.lease = this;\n return hold;\n }\n\n /** A new hold: on top, over the top hold while the element shows it; a base one at the bottom. */\n #acquire(element: T, stack: AttributeHold[]): AttributeHold {\n const current = element.getAttribute(this.#attribute);\n const top = stack.at(-1);\n const bottom = stack[0];\n const over = top?.written === current ? top : undefined;\n const from = this.#base\n ? this.#preserveAuthor && !stack.some((held) => held.written === current)\n ? undefined\n : bottom\n : over;\n const hold: AttributeHold = {\n lease: this,\n record: this.#record,\n written: current,\n original: from ? from.original : current,\n linked: !this.#base && over !== undefined,\n };\n if (this.#base && bottom) {\n bottom.linked = true;\n stack.unshift(hold);\n } else stack.push(hold);\n return hold;\n }\n\n /** Whether a hold above `hold` carries the element's value, which is then that hold's. */\n #covered(element: T, stack: readonly AttributeHold[], hold: AttributeHold): boolean {\n const current = element.getAttribute(this.#attribute);\n return stack.slice(stack.indexOf(hold) + 1).some((above) => above.written === current);\n }\n\n /** Leaves each owner's record of its topmost hold, or none where nothing needs one. */\n #mark(element: T, stack: readonly AttributeHold[]): void {\n const records = new Map<string, string | null>([[this.#record, null]]);\n stack.forEach((hold, index) => {\n const names = stack.slice(0, index).map((under) => under.record);\n const beneath = [...new Set(names.reverse())].filter((name) => name !== hold.record);\n const marker = hold.linked || beneath.length === 0 ? [] : [false];\n records.set(\n hold.record,\n hold.written === hold.original && beneath.length === 0 && index === stack.length - 1\n ? null\n : JSON.stringify([hold.original, hold.written, ...marker, ...beneath]),\n );\n });\n for (const [name, recorded] of records) {\n setAttributeIfChanged(element, name, recorded);\n }\n }\n\n /** Reflects only a real value transition, avoiding self-triggered mutation work. */\n #reflect(element: T, value: string | null): void {\n setAttributeIfChanged(element, this.#attribute, value);\n }\n}\n","/**\n * The element a selector names within `root`, which may be `root` itself.\n *\n * A target declaration is a space-separated token list, so one element can name\n * several at once: a row built from a `<template>` is its own row target, its own\n * label, and its own button where the author writes it that way. `querySelector`\n * never returns its receiver, so resolving a part with it alone reaches nothing on\n * such a row and leaves it rendered but inert.\n *\n * The selector is composed by the caller, so a tag name written into it still\n * narrows the match — a row that is not a `<button>` does not answer for one.\n *\n * @example\n * ```ts\n * const button = matchingPart<HTMLButtonElement>(row, `button${selector(\"remove\")}`);\n * ```\n */\nexport function matchingPart<E extends HTMLElement = HTMLElement>(\n root: HTMLElement,\n selector: string,\n): E | null {\n return root.matches(selector) ? (root as unknown as E) : root.querySelector<E>(selector);\n}\n\n/**\n * Writes `text` as the label of `slot`, keeping the elements nested inside it.\n *\n * A row that names itself its own label holds the rest of the row inside the\n * element the text goes into — the remove button among them. Replacing the whole\n * subtree takes those with it and leaves a chip that is rendered but has nothing to\n * press, so only the slot's own text moves: the first text node carries the value\n * and the rest go, which puts the label where the template left room for it. A slot\n * holding nothing but text is written whole, which is the ordinary row.\n */\nexport function writeLabel(slot: HTMLElement, text: string): void {\n if (slot.childElementCount === 0) {\n slot.textContent = text;\n return;\n }\n let first: ChildNode | null = null;\n for (const node of Array.from(slot.childNodes)) {\n if (node.nodeType !== Node.TEXT_NODE) continue;\n if (first) node.remove();\n else first = node;\n }\n if (first) first.nodeValue = text;\n else slot.prepend(text);\n}\n\n/**\n * Reads back the label {@link writeLabel} wrote, without what sits beside it.\n *\n * The same row that holds the remove button inside its label slot returns that\n * button's glyph from `textContent`, which is enough to make a comparison\n * against the authored label never match — so every pass rewrites a label that\n * did not change — and to put the glyph into an announcement. Only the slot's\n * own text nodes carry the label, which on the ordinary row — a slot holding\n * nothing but text — is the whole of it.\n */\nexport function readLabel(slot: HTMLElement | null): string {\n if (!slot) return \"\";\n let text = \"\";\n for (const node of Array.from(slot.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) text += node.nodeValue ?? \"\";\n }\n return text.trim();\n}\n","/**\n * Low-level roving-tabindex primitive shared by composite-widget controllers.\n *\n * The APG roving-tabindex pattern keeps a composite widget a single Tab stop:\n * exactly one item is in the Tab sequence (`tabindex=\"0\"`) while the rest are\n * removed from it (`tabindex=\"-1\"`), and the arrow keys move both DOM focus and\n * that single tabbable position together. {@link RovingTabindex} owns *only* that\n * mechanical bookkeeping — \"which one item is tabbable, and move focus there\".\n *\n * It is intentionally **policy-free**. Orientation, wrapping vs. clamping,\n * selection-follows-focus, typeahead, and `Home`/`End` semantics differ per APG\n * pattern (Radio Group, Toolbar, Tabs, …); folding them into one helper would\n * flatten those widgets to a lowest common denominator and lose each pattern's\n * correctness. Those decisions therefore stay in each controller, which calls\n * {@link RovingTabindex.setActive} with an index it computed itself (optionally\n * via the pure {@link rovingMove} helper).\n *\n * @remarks\n * Items are read lazily through a getter so a controller can add or remove\n * targets (Stimulus re-scans the DOM) without re-wiring this helper. A caller\n * that already captured one event-scoped snapshot may pass it to\n * {@link RovingTabindex.setActive}, avoiding a second live-target scan while\n * preserving one coherent collection for the whole operation.\n */\nexport class RovingTabindex {\n /** Returns the current ordered item elements; called on every operation. */\n readonly #getItems: () => HTMLElement[];\n\n /**\n * @param getItems - Returns the current ordered item elements. Called on every\n * operation so the live target list is always used.\n */\n constructor(getItems: () => HTMLElement[]) {\n this.#getItems = getItems;\n }\n\n /** Index of the currently tabbable item (`tabindex=\"0\"`), or `-1` if none. */\n get activeIndex(): number {\n return this.#getItems().findIndex((item) => item.tabIndex === 0);\n }\n\n /**\n * Makes exactly the item at `index` tabbable (`tabindex=\"0\"`) and removes every\n * other item from the Tab sequence (`tabindex=\"-1\"`). An out-of-range `index`\n * (e.g. `-1`) leaves all items at `-1`, which a controller can use to express\n * \"nothing is currently tabbable\".\n *\n * @param index - Position of the item to make tabbable.\n * @param options - Pass `{ focus: true }` to also move DOM focus to that item,\n * and `items` to reuse an event-scoped collection snapshot.\n */\n setActive(\n index: number,\n options: { focus?: boolean; items?: readonly HTMLElement[] } = {},\n ): void {\n const { focus = false } = options;\n const items = options.items ?? this.#getItems();\n items.forEach((item, i) => {\n item.tabIndex = i === index ? 0 : -1;\n });\n if (focus) items[index]?.focus();\n }\n}\n\n/** Edge behavior for {@link rovingMove}: cycle past the ends, or stop at them. */\nexport type RovingWrap = \"wrap\" | \"clamp\";\n\n/**\n * Pure helper that resolves the target index for a one-step directional move.\n *\n * Keyboard/orientation mapping stays in the caller: it decides that a key means\n * `delta` `+1` (next) or `-1` (previous) and whether the widget should `\"wrap\"`\n * (Radio Group, Toolbar) or `\"clamp\"` at the ends.\n *\n * @param current - The index focus is moving from.\n * @param length - Number of items in the set.\n * @param delta - `+1` to move to the next item, `-1` for the previous.\n * @param wrap - `\"wrap\"` cycles around the ends; `\"clamp\"` stops at them.\n * @returns The resolved index, or `-1` when there are no items.\n */\nexport function rovingMove(\n current: number,\n length: number,\n delta: number,\n wrap: RovingWrap,\n): number {\n if (length === 0) return -1;\n const next = current + delta;\n if (wrap === \"wrap\") return (next + length) % length;\n return Math.min(length - 1, Math.max(0, next));\n}\n","import { isReservedArrowChord, logicalArrowKey } from \"./arrow_step\";\nimport { matchingPart } from \"./element_part\";\nimport { RovingTabindex } from \"./roving_tabindex\";\n\n/** Consumer-owned behavior that differs between removable-chip widgets. */\nexport interface ChipRowOptions {\n /** Returns the current container whose direction defines logical previous/next. */\n readonly getDirectionElement: () => HTMLElement;\n /** Returns the current chip elements in navigation order. */\n readonly getItems: () => readonly HTMLElement[];\n /** Resolves the one remove button owned by a chip. Defaults to its first button. */\n readonly getButton?: (item: HTMLElement) => HTMLButtonElement | null;\n /** Removes the chip currently occupying `index`. */\n readonly onRemove: (index: number) => void;\n /** Receives focus when navigation moves past the logical end of the row. */\n readonly focusAfterEnd: () => void;\n}\n\n/**\n * Delegated interaction and roving-tabindex mechanics for a row of removable chips.\n *\n * The selection model stays in the consuming controller: this helper knows only\n * how to resolve one consumer-declared remove button per chip, move between those\n * buttons, delegate click/delete requests by index, and bind those listeners to\n * a replaceable row target. Restricting the button set to the declared chip items\n * deliberately excludes sibling controls such as an authored \"Clear all\" button.\n */\nexport class ChipRow {\n readonly #getDirectionElement: () => HTMLElement;\n readonly #getItems: () => readonly HTMLElement[];\n readonly #getButton: (item: HTMLElement) => HTMLButtonElement | null;\n readonly #onRemove: (index: number) => void;\n readonly #focusAfterEnd: () => void;\n readonly #roving = new RovingTabindex(() => this.buttons);\n #container: HTMLElement | null = null;\n\n constructor(options: ChipRowOptions) {\n this.#getDirectionElement = options.getDirectionElement;\n this.#getItems = options.getItems;\n this.#getButton =\n options.getButton ?? ((item) => matchingPart<HTMLButtonElement>(item, \"button\"));\n this.#onRemove = options.onRemove;\n this.#focusAfterEnd = options.focusAfterEnd;\n }\n\n /**\n * Binds delegation to `container`; any row currently bound is released first.\n * Idempotent for the same node, so target callbacks may call it freely.\n */\n connect(container: HTMLElement): void {\n if (this.#container === container) return;\n this.disconnect();\n this.#container = container;\n container.addEventListener(\"click\", this.#onClick);\n container.addEventListener(\"keydown\", this.#onKeydown);\n }\n\n /**\n * Releases the current row. When `container` is supplied, a stale disconnect\n * callback cannot tear listeners off a newer replacement target.\n */\n disconnect(container?: HTMLElement): void {\n const current = this.#container;\n if (!current || (container !== undefined && current !== container)) return;\n current.removeEventListener(\"click\", this.#onClick);\n current.removeEventListener(\"keydown\", this.#onKeydown);\n this.#container = null;\n }\n\n /** Current remove buttons, at most one consumer-resolved button per chip item. */\n get buttons(): HTMLButtonElement[] {\n return this.#entries.map(({ button }) => button);\n }\n\n /** Number of currently navigable remove buttons. */\n get length(): number {\n return this.buttons.length;\n }\n\n /** Declared-item index of the last navigable chip, or `-1` for an empty row. */\n get lastIndex(): number {\n return this.#entries.at(-1)?.itemIndex ?? -1;\n }\n\n /** Keeps exactly one button tabbable, preferring the first authored Tab stop. */\n ensureTabStop(): void {\n const buttons = this.#entries.map(({ button }) => button);\n const active = buttons.findIndex((button) => button.tabIndex === 0);\n const count = buttons.filter((button) => button.tabIndex === 0).length;\n if (buttons.length > 0 && count !== 1) {\n this.#roving.setActive(active === -1 ? 0 : active, { items: buttons });\n }\n }\n\n /** Focuses the last chip, returning false for an empty row. */\n focusLast(): boolean {\n const buttons = this.#entries.map(({ button }) => button);\n const last = buttons.length - 1;\n if (last < 0) return false;\n this.#roving.setActive(last, { focus: true, items: buttons });\n return true;\n }\n\n /**\n * Focuses the chip that followed a removed index, or the new last chip.\n * Returns false when removal emptied the row so the consumer can rescue focus.\n */\n focusAfterRemoval(index: number): boolean {\n const entries = this.#entries;\n if (entries.length === 0) return false;\n const following = entries.findIndex((entry) => entry.itemIndex >= index);\n this.#roving.setActive(following === -1 ? entries.length - 1 : following, {\n focus: true,\n items: entries.map(({ button }) => button),\n });\n return true;\n }\n\n /** Current remove-button entries, retaining each button's declared item index. */\n get #entries(): Array<{ button: HTMLButtonElement; itemIndex: number }> {\n return this.#getItems().flatMap((item, itemIndex) => {\n const button = this.#getButton(item);\n return button ? [{ button, itemIndex }] : [];\n });\n }\n\n /** Resolves a delegated event to the remove button owned by a declared chip. */\n #entry(event: Event): {\n button: HTMLButtonElement;\n buttonIndex: number;\n buttons: HTMLButtonElement[];\n itemIndex: number;\n } | null {\n const target = event.target;\n if (!(target instanceof Element)) return null;\n const button = target.closest<HTMLButtonElement>(\"button\");\n const entries = this.#entries;\n const buttonIndex = entries.findIndex((entry) => entry.button === button);\n if (buttonIndex === -1) return null;\n const entry = entries[buttonIndex] as { button: HTMLButtonElement; itemIndex: number };\n return { ...entry, buttonIndex, buttons: entries.map(({ button }) => button) };\n }\n\n /** Delegates removal clicks without waiting for Stimulus to wire a new chip. */\n readonly #onClick = (event: MouseEvent): void => {\n const entry = this.#entry(event);\n if (!entry) return;\n this.#onRemove(entry.itemIndex);\n };\n\n /** Applies the shared logical-arrow and removal policy within the chip row. */\n readonly #onKeydown = (event: KeyboardEvent): void => {\n if (event.defaultPrevented || isReservedArrowChord(event)) return;\n const entry = this.#entry(event);\n if (!entry) return;\n const buttons = entry.buttons;\n const index = entry.buttonIndex;\n\n switch (logicalArrowKey(event.key, this.#getDirectionElement())) {\n case \"ArrowLeft\":\n if (index > 0) {\n event.preventDefault();\n this.#roving.setActive(index - 1, { focus: true, items: buttons });\n }\n break;\n case \"ArrowRight\":\n event.preventDefault();\n if (index < buttons.length - 1) {\n this.#roving.setActive(index + 1, { focus: true, items: buttons });\n } else {\n this.#focusAfterEnd();\n }\n break;\n case \"Delete\":\n case \"Backspace\":\n event.preventDefault();\n this.#onRemove(entry.itemIndex);\n break;\n default:\n break;\n }\n };\n}\n","/** Minimal event shape carrying the platform's per-event composition signal. */\nexport interface CompositionSignal {\n readonly isComposing?: boolean;\n}\n\n/** Minimal `input` shape needed to tell a composition echo from a fresh edit. */\nexport interface ConfirmedInputSignal {\n readonly target: EventTarget | null;\n readonly inputType?: string;\n}\n\n/**\n * The `inputType` values an engine reports on an `input` that belongs to a\n * composition rather than to an edit the user just made.\n */\nconst COMPOSITION_INPUT_TYPES = new Set([\n \"insertCompositionText\",\n \"insertFromComposition\",\n \"deleteCompositionText\",\n \"deleteByComposition\",\n]);\n\n/** Whether a platform input kind belongs to composition rather than ordinary editing. */\nexport function isCompositionInputType(inputType: string | undefined): boolean {\n return inputType !== undefined && COMPOSITION_INPUT_TYPES.has(inputType);\n}\n\n/** The cancelable notice Turbo dispatches before a morph writes one attribute. */\nconst BEFORE_MORPH_ATTRIBUTE = \"turbo:before-morph-attribute\";\n\n/** Hooks that keep component-specific work outside {@link CompositionTracker}. */\nexport interface CompositionTrackerOptions {\n /** Runs after lifecycle state is set for a `compositionstart` event. */\n readonly onStart?: (event: Event) => void;\n /** Runs after lifecycle state is cleared for a `compositionend` event. */\n readonly onEnd?: (event: Event) => void;\n /**\n * Runs once lifecycle state is cleared for a composition that ended without\n * `compositionend`, with the `element` it ran in. Nothing was confirmed: the\n * element holds what a write left (`inPlace` false), or still holds the text the\n * composition left, which the engine stopped composing (`inPlace` true) — text\n * typed against whatever the page declared while it ran.\n *\n * A hook applies the work the composition held back — and only that — at once,\n * keeping the caret where it was. The event that showed the end is then handled as\n * it would be with no composition: the text the element holds is read by whatever\n * reads it next, as the user's edit if an edit reads it. A consumer whose contract\n * judges what an interrupted conversion leaves may also settle that text here, as\n * `stimeo--otp` returns a residual its `pattern` rejects to the prior character: it reports\n * that as a reconciliation, never as the user's edit, and keeps the selection.\n *\n * When the tracker sees the end in an event it hears — a key, an edit, a focus\n * change, the next `compositionstart` — the hook runs there, in the capture phase,\n * ahead of that event's own handlers and of the edit it announces, whoever\n * dispatched it. When a question ({@link CompositionTracker.isComposing},\n * {@link CompositionTracker.composingElement}) or a Turbo morph's notice for one\n * attribute shows the end, the hook runs in a microtask after them, never inside\n * its caller or a half-applied morph, unless an event the tracker hears comes\n * first. On `compositionstart` it runs after the new composition is set and before\n * `onStart`: {@link CompositionTracker.isComposing} is true again, so work held for\n * the old composition stays held for the new.\n */\n readonly onAbandon?: (element: EventTarget, inPlace: boolean) => void;\n}\n\n/** One composition in progress. */\ninterface Composition {\n /** The observed target the composition was heard on. */\n readonly target: EventTarget;\n /** The element composing: the observed field itself, or a field inside an observed ancestor. */\n readonly element: EventTarget;\n /** The value the composition last left in the element; `undefined` for an element with none. */\n text: unknown;\n}\n\n/**\n * The element's live value; `undefined` for an element without one, which a write never\n * changes.\n */\nconst textOf = (element: EventTarget): unknown => (element as { value?: unknown }).value;\n\n/** Whether `element` is the focused element of the document or shadow root it is in. */\nconst holdsFocus = (element: EventTarget): boolean =>\n element instanceof Node &&\n (element.getRootNode() as Partial<DocumentOrShadowRoot>).activeElement === element;\n\n/**\n * Owns IME composition listeners and transient state for one or more event targets.\n *\n * Some browsers omit `KeyboardEvent.isComposing` on the keydown that confirms a\n * conversion. Tracking `compositionstart` through `compositionend` supplies the\n * missing lifecycle signal without relying on deprecated numeric key codes.\n * Component policy stays with the consumer: filtering, validation, and submission\n * belong in the optional {@link CompositionTrackerOptions.onEnd} callback.\n *\n * The tracker also owns the other half of that lifecycle: **the `input` some\n * engines send after `compositionend` to echo the text just confirmed.** A\n * consumer that ran `onEnd` and then handled the echo would commit the same\n * confirmation twice, so {@link CompositionTracker.consumesConfirmedInput} tells\n * the echo apart and the consumer returns early on it.\n *\n * **What the echo is not, is the harder half.** Not every engine sends one —\n * Chromium ends a confirmation at `compositionend` with no `input` after it — so\n * a window that waits for the echo and only closes on the next key would swallow\n * the first edit that arrives without one: dictation, autofill, a drop,\n * `insertText`. Two things keep that from happening. The window closes on the\n * next anything — a key, a new composition, any `input`, losing the field — and\n * an `input` that reports an `inputType` outside {@link COMPOSITION_INPUT_TYPES}\n * is an edit, so it is never folded. Only an engine that reports no `inputType`\n * at all is left relying on the window alone.\n *\n * **A composition can also end without `compositionend`.** Chromium drops the\n * conversion silently when something other than the IME writes a different value\n * into its field — a Turbo morph, a form reset, a script — and when the field\n * moves or leaves the page, leaving the text it composed. The tracker reads the end\n * from what the engine and the field still say:\n *\n * - **The field holds other text than the composition left.** The IME's edits, and\n * the user's own between them, arrive as an `input` the engine dispatched\n * (`isTrusted`) or one that reports the composition, and the tracker takes the\n * field's text from those. A write by anything else changes the text with no such\n * `input` — at most a synthetic one — so the composition is over, ended with\n * {@link CompositionTrackerOptions.onAbandon}, before anyone acts on the field.\n * Writing the same text keeps the conversion, and the match.\n * - **The engine edits outside a composition.** A `beforeinput` reporting\n * `isComposing: false` with an `inputType` outside {@link COMPOSITION_INPUT_TYPES}\n * is an edit the engine no longer counts as composition — unless the `keydown`\n * right before it reported `isComposing: true`: a key the IME lets through, such\n * as Backspace, edits the field while the conversion goes on. This is what shows\n * a composition that ended with its text in place. Only one field composes at a\n * time, so such an edit on any observed target ends the composition held, with\n * `onAbandon`. A `keydown` can hold this back but never starts it: the keydown\n * that confirms a conversion may carry no `isComposing`, and dictation and\n * autofill edit with no key at all.\n * - **The field stays where it was heard.** A field the consumer observes itself is\n * the consumer's to release when it moves or leaves, which reads what it holds;\n * one that keeps focus through the move keeps composing\n * ({@link CompositionTracker.disconnect}). A field inside an observed ancestor\n * that leaves the ancestor, or loses focus within its document, ends its\n * composition quietly; one that stays the document's active element — the window\n * lost focus — keeps composing.\n * - **No other field composes**: a `compositionstart` ends any composition the\n * tracker still holds, with `onAbandon`, before the new one starts.\n *\n * The tracker checks this before it answers {@link CompositionTracker.isComposing}\n * or {@link CompositionTracker.composingElement}, and at every key, edit, blur,\n * `compositionstart` and morph it hears — keys, edits and blurs in the capture\n * phase, ahead of the consumer's own handlers. While\n * a composition is live, a Turbo morph leaves its field's value alone: Idiomorph\n * asks through `turbo:before-morph-attribute` before it writes `value`, as an\n * attribute or as the live text, and the tracker cancels that one notice for the\n * element composing, so the morph keeps the conversion, as it keeps focus. Every\n * other attribute, and every other element, still morphs.\n *\n * A consumer that observes several fields tells the conversion's own events from\n * edits in the other fields with {@link CompositionTracker.owns}, which holds even\n * while the tracker keeps a composition whose end no event has shown yet.\n *\n * @example\n * ```ts\n * #composition = new CompositionTracker({ onEnd: () => this.filter() });\n *\n * connect(): void {\n * this.#composition.observe(this.inputTarget);\n * }\n *\n * disconnect(): void {\n * this.#composition.disconnect();\n * }\n *\n * onInput(event: InputEvent): void {\n * if (this.#composition.consumesConfirmedInput(event)) return;\n * if (this.#composition.isComposing(event)) return;\n * }\n *\n * onKeydown(event: KeyboardEvent): void {\n * if (this.#composition.isComposing(event)) return;\n * }\n * ```\n */\nexport class CompositionTracker {\n readonly #observedTargets = new Set<EventTarget>();\n /** The composition in progress, if any: only one field composes at a time. */\n #composition: Composition | null = null;\n readonly #onStart: ((event: Event) => void) | undefined;\n readonly #onEnd: ((event: Event) => void) | undefined;\n readonly #onAbandon: ((element: EventTarget, inPlace: boolean) => void) | undefined;\n /** The field whose confirming `input` is still owed, while the window is open. */\n #confirmedTarget: EventTarget | null = null;\n /**\n * Whether the last `keydown` reported a composition, until the `beforeinput`\n * after it: the edit that key announces lands inside the composition.\n */\n #keyComposing = false;\n /** Whether the consumer is connected: from `observe()` until `disconnect()`. */\n #connected = false;\n /** A composition that ended without `compositionend` and whose `onAbandon` has not run yet. */\n #abandoned: { readonly element: EventTarget; readonly inPlace: boolean } | null = null;\n\n constructor(options: CompositionTrackerOptions = {}) {\n this.#onStart = options.onStart;\n this.#onEnd = options.onEnd;\n this.#onAbandon = options.onAbandon;\n }\n\n /**\n * Starts lifecycle tracking for `target`; repeated calls are idempotent. The\n * targets one tracker observes do not contain one another: a composition event\n * reaching two of them would be counted as two.\n */\n observe(target: EventTarget): void {\n this.#connected = true;\n if (this.#observedTargets.has(target)) return;\n target.addEventListener(\"compositionstart\", this.#handleStart);\n target.addEventListener(\"compositionend\", this.#handleEnd);\n target.addEventListener(\"keydown\", this.#handleKeydown, true);\n target.addEventListener(\"beforeinput\", this.#handleBeforeInput, true);\n target.addEventListener(\"input\", this.#handleInput, true);\n target.addEventListener(\"blur\", this.#handleBlur, true);\n target.addEventListener(BEFORE_MORPH_ATTRIBUTE, this.#handleBeforeMorphAttribute);\n this.#observedTargets.add(target);\n }\n\n /**\n * Stops tracking one target. A composition it held ends quietly, unless its element\n * still holds focus — see {@link CompositionTracker.disconnect}.\n */\n unobserve(target: EventTarget): void {\n if (!this.#observedTargets.delete(target)) return;\n this.#release(target);\n if (this.#composition?.target === target) this.#letGo();\n if (this.#confirmedTarget === target) this.#confirmedTarget = null;\n }\n\n /**\n * Releases every listener and clears state so reconnect starts cleanly.\n *\n * A composition whose element still holds focus is the exception. A move that\n * keeps focus — `moveBefore`, which Turbo's morph uses where the browser provides\n * it — can leave the conversion running, and Stimulus releases the moved target, or\n * the controller around it, and observes it again within the one mutation batch. So\n * the composition waits for its target to be observed again before the turn ends,\n * and goes on; otherwise it ends then — quietly once disconnected, and with\n * {@link CompositionTrackerOptions.onAbandon} for a consumer that only let that one\n * target go. A move without `moveBefore`, or a removal, takes focus away.\n */\n disconnect(): void {\n this.#connected = false;\n for (const target of this.#observedTargets) this.#release(target);\n this.#observedTargets.clear();\n this.#letGo();\n this.#confirmedTarget = null;\n this.#keyComposing = false;\n this.#abandoned = null;\n }\n\n /**\n * True when a composition is live or the current event reports one. A\n * composition that ended without `compositionend` ends here first.\n */\n isComposing(event?: CompositionSignal): boolean {\n this.#settle();\n return event?.isComposing === true || this.#composition !== null;\n }\n\n /**\n * The element a live composition is running in, or `null`. A composition that\n * ended without `compositionend` ends here first.\n */\n composingElement(): EventTarget | null {\n this.#settle();\n return this.#composition?.element ?? null;\n }\n\n /**\n * Whether `event` belongs to a composition: it reports one, or it is in the element a\n * live composition runs in. An event in another element — a key there, or a script's\n * write reported with a bare `input` — is an edit outside the composition, even while\n * the tracker holds one whose end it has not seen: only one element composes at a\n * time, and the IME edits nothing else. The composition held stays, since such an\n * event does not show its end. A consumer that observes several fields asks this of\n * each event; {@link CompositionTracker.isComposing} asks of the targets as a whole.\n * A composition that ended without `compositionend` ends here first.\n */\n owns(event: CompositionSignal & { readonly target: EventTarget | null }): boolean {\n const element = this.composingElement();\n return event.isComposing === true || (element !== null && element === event.target);\n }\n\n /**\n * Whether `event` is the `input` echoing the composition just confirmed.\n *\n * Asking closes the window either way, so one confirmation is folded at most\n * once and a consumer asks once per `input`.\n */\n consumesConfirmedInput(event: ConfirmedInputSignal): boolean {\n const confirmed = this.#confirmedTarget;\n this.#confirmedTarget = null;\n if (confirmed === null || confirmed !== event.target) return false;\n // An engine that reports no kind at all leaves `inputType` empty, and the\n // window is then the only signal there is.\n const inputType = event.inputType;\n return !inputType || isCompositionInputType(inputType);\n }\n\n /** Removes every listener {@link CompositionTracker.observe} added to `target`. */\n #release(target: EventTarget): void {\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n target.removeEventListener(\"keydown\", this.#handleKeydown, true);\n target.removeEventListener(\"beforeinput\", this.#handleBeforeInput, true);\n target.removeEventListener(\"input\", this.#handleInput, true);\n target.removeEventListener(\"blur\", this.#handleBlur, true);\n target.removeEventListener(BEFORE_MORPH_ATTRIBUTE, this.#handleBeforeMorphAttribute);\n }\n\n /**\n * Lets go of the composition held once its target is no longer observed: it is over\n * unless its element kept focus and its target is observed again this turn.\n */\n #letGo(): void {\n const composition = this.#composition;\n if (composition === null) return;\n if (!holdsFocus(composition.element)) {\n this.#composition = null;\n return;\n }\n queueMicrotask(() => {\n if (this.#composition !== composition || this.#observedTargets.has(composition.target)) {\n return;\n }\n this.#composition = null;\n if (!this.#connected) return;\n this.#abandoned = { element: composition.element, inPlace: true };\n this.#runAbandon();\n });\n }\n\n /**\n * Ends the composition held if its field left the observed target, taking the\n * composition's text along, or holds text a write left.\n */\n #settle(): void {\n const composition = this.#composition;\n if (composition === null) return;\n const { target, element, text } = composition;\n if (target instanceof Node && element instanceof Node && !target.contains(element)) {\n this.#composition = null;\n } else if (textOf(element) !== text) {\n this.#abandon(false);\n }\n }\n\n /**\n * Ends the composition held, unconfirmed. Its `onAbandon` runs in a microtask,\n * unless an event the tracker hears runs it first.\n */\n #abandon(inPlace: boolean): void {\n this.#owe(inPlace);\n this.#composition = null;\n queueMicrotask(this.#runAbandon);\n }\n\n /** Records the `onAbandon` the composition held owes. */\n #owe(inPlace: boolean): void {\n const composition = this.#composition;\n if (composition !== null) this.#abandoned = { element: composition.element, inPlace };\n }\n\n /** Runs the `onAbandon` an ended composition owes, once. */\n readonly #runAbandon = (): void => {\n const abandoned = this.#abandoned;\n if (abandoned === null) return;\n this.#abandoned = null;\n this.#onAbandon?.(abandoned.element, abandoned.inPlace);\n };\n\n /** A composition starting while one is held ends the held one, unconfirmed. */\n readonly #handleStart = (event: Event): void => {\n this.#confirmedTarget = null;\n this.#settle();\n this.#owe(true);\n // A listener runs while the event is dispatched, so both targets are set.\n const target = event.currentTarget as EventTarget;\n const element = event.target as EventTarget;\n this.#composition = { target, element, text: textOf(element) };\n this.#runAbandon();\n this.#onStart?.(event);\n };\n\n readonly #handleEnd = (event: Event): void => {\n this.#runAbandon();\n if (this.#composition?.target === event.currentTarget) this.#composition = null;\n this.#confirmedTarget = event.target;\n this.#onEnd?.(event);\n };\n\n /**\n * A key on an observed field opens an edit of its own, so no echo is owed; it\n * also says whether the edit it announces lands inside a composition.\n */\n readonly #handleKeydown = (event: Event): void => {\n this.#settle();\n this.#runAbandon();\n this.#confirmedTarget = null;\n this.#keyComposing = (event as KeyboardEvent).isComposing === true;\n };\n\n /** An edit is about to land: a composition the engine no longer runs ends first. */\n readonly #handleBeforeInput = (event: Event): void => {\n const keyComposing = this.#keyComposing;\n this.#keyComposing = false;\n this.#settle();\n const { isComposing, inputType } = event as InputEvent;\n if (\n this.#composition !== null &&\n !keyComposing &&\n !isComposing &&\n inputType &&\n !isCompositionInputType(inputType)\n ) {\n this.#abandon(true);\n }\n this.#runAbandon();\n };\n\n /**\n * Takes the composing field's text from an `input` the engine dispatched or one\n * that reports the composition; any other `input` follows a write the\n * composition did not make.\n */\n readonly #handleInput = (event: Event): void => {\n const composition = this.#composition;\n const { isTrusted, isComposing, inputType } = event as InputEvent;\n if (\n composition !== null &&\n event.target === composition.element &&\n (isTrusted || isComposing || isCompositionInputType(inputType))\n ) {\n composition.text = textOf(composition.element);\n } else {\n this.#settle();\n }\n this.#runAbandon();\n };\n\n /**\n * Checks the composition as a field loses focus, ahead of the consumer's own blur\n * handlers. A field inside an observed ancestor that loses focus within its\n * document keeps its text and composes no more.\n */\n readonly #handleBlur = (event: Event): void => {\n this.#settle();\n this.#runAbandon();\n const composition = this.#composition;\n if (composition === null || composition.target === composition.element) return;\n const { element } = composition;\n if (!(element instanceof Node) || event.target !== element) return;\n const root = element.getRootNode() as Document | ShadowRoot;\n if (root.activeElement !== element) this.#composition = null;\n };\n\n /** Keeps a Turbo morph from writing the value of the element composing. */\n readonly #handleBeforeMorphAttribute = (event: Event): void => {\n this.#settle();\n const composition = this.#composition;\n if (composition?.target !== event.currentTarget || event.target !== composition.element) return;\n const detail: { readonly attributeName?: unknown } | null = (event as CustomEvent).detail;\n if (detail?.attributeName === \"value\") event.preventDefault();\n };\n}\n","/**\n * The hidden form fields a widget keeps in step with the state it owns.\n *\n * A widget whose value lives in ARIA attributes submits nothing on its own, so\n * it mirrors that value into `<input type=\"hidden\">` — one field for a single\n * value, a container of generated fields for a set. The mirror is one-way: the\n * widget's own state stays the source of truth and the field is what the form\n * reads.\n *\n * The write and the report are separate calls because they answer to different\n * rules. A mirror is refreshed on connect, after a morph, and whenever the\n * widget repairs itself — none of which a form should treat as an edit. Only\n * the user's own commit reports one, which is why {@link commitField} is never\n * folded into the writes.\n */\n\n/** How a widget's generated fields identify themselves to the form. */\nexport interface GeneratedFieldOptions {\n /** The `name` every generated input submits under. */\n readonly name: string;\n /** The `form` id, for a widget that sits outside the form it submits to. */\n readonly form?: string;\n}\n\n/**\n * Mirrors one value into a hidden field.\n *\n * @returns Whether the field's value moved.\n *\n * @example\n * ```ts\n * if (writeField(this.fieldTarget, String(value)) && userDriven) {\n * commitField(this.fieldTarget);\n * }\n * ```\n */\nexport function writeField(field: HTMLInputElement, value: string): boolean {\n if (field.value === value) return false;\n field.value = value;\n return true;\n}\n\n/**\n * Mirrors a set of values into `container` as generated hidden fields, in the\n * order given.\n *\n * A container that already submits exactly this set is left untouched, children\n * and all — the mirror is refreshed far more often than it moves (every connect,\n * morph and repair), and a rebuild that changes nothing is still a DOM mutation\n * a consumer's observer and a `:empty` rule can see.\n *\n * @returns Whether the submitted set moved — its values, their order, the\n * `name`, or the `form`.\n */\nexport function writeFields(\n container: HTMLElement,\n values: readonly string[],\n { name, form = \"\" }: GeneratedFieldOptions,\n): boolean {\n const current = [...container.children];\n const submits =\n current.length === values.length &&\n current.every(\n (child, index) =>\n child instanceof HTMLInputElement &&\n child.type === \"hidden\" &&\n child.value === values[index] &&\n child.name === name &&\n (child.getAttribute(\"form\") ?? \"\") === form,\n );\n if (submits) return false;\n\n container.replaceChildren(\n ...values.map((value) => {\n const input = document.createElement(\"input\");\n input.type = \"hidden\";\n input.name = name;\n input.value = value;\n if (form !== \"\") input.setAttribute(\"form\", form);\n return input;\n }),\n );\n return true;\n}\n\n/**\n * Reports a committed value from `target` the way a native form control does:\n * one bubbling, non-cancelable `change`.\n *\n * Call it only for a move the user made. Form-level behaviors listen for this —\n * validation re-checks, auto-submit — and a mirror refreshed by a morph or a\n * repair is not something the user submitted.\n *\n * `target` is the element that carries the value: the hidden field for a single\n * mirrored value, the container for a generated set (whose own inputs are\n * replaced on every write), or a widget's own native control where that is what\n * the form reads.\n */\nexport function commitField(target: HTMLElement): void {\n target.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n","/** What {@link ListenerSet.add} passes on besides the signal it supplies itself. */\nexport type ListenerOptions = Omit<AddEventListenerOptions, \"signal\">;\n\n/**\n * The event map a target's own `addEventListener` types its handlers with: the\n * window's, a document's, an HTML or SVG element's, any other element's, or a\n * media query list's. Other targets name none.\n */\ntype EventMapOf<T extends EventTarget> = T extends Window\n ? WindowEventMap\n : T extends Document\n ? DocumentEventMap\n : T extends HTMLElement\n ? HTMLElementEventMap\n : T extends SVGElement\n ? SVGElementEventMap\n : T extends Element\n ? ElementEventMap\n : T extends MediaQueryList\n ? MediaQueryListEventMap\n : Record<never, never>;\n\n/**\n * Owns every listener a controller attaches for one connected lifetime and\n * releases them together, so an event name is spelled once and the release\n * cannot drift from the registration.\n *\n * Detaching by hand repeats three things at the release site — the type, the\n * handler reference and the capture flag — and any one of them drifting leaves\n * a listener alive on an element the controller no longer drives. Aborting the\n * signal a registration was created with releases it whatever it was made of,\n * so the release site names nothing.\n *\n * One set per lifetime, held as a field and never rebuilt.\n * {@link ListenerSet.dispose} is the only thing that closes a generation, and it opens\n * the next one in the same step, so the lifecycle hooks can call `add` and\n * `dispose` in any order any number of times, and no `add` ever meets an\n * already aborted signal — a DOM that registers a listener on such a signal\n * would keep it forever. Rebuilding the set instead would leak:\n * `addEventListener` matches an existing registration on target, type, callback\n * and capture alone, so re-adding the same handler while the first registration\n * is live is discarded, and that live registration keeps the signal it was\n * attached with — a set built by a second `connect()` can never release what it\n * appears to own.\n *\n * Scope is the registration only. Timers, observers, leases and the order they\n * are unwound in stay with the controller, which places `dispose()` in its\n * cleanup sequence. A receiver that changes at runtime (a\n * swapped target) is rebound by calling `dispose()` and then `add()` again from\n * the rebind, not by a second set.\n *\n * A lifetime shorter than the connection — while a Value holds, until a first\n * load, while a subscription is open — gets a set of its own, which the end of\n * that lifetime disposes. A controller therefore holds one set per lifetime: the\n * connection's, and one for each swapped receiver or shorter span.\n *\n * The set must own every registration of a tuple it holds: a listener the same\n * target already carries for the same type, callback and capture flag keeps the\n * right to remove it, and this set's `add` for that tuple is discarded. A\n * subscription shared between instances behind a participant count, listeners of\n * several elements that come and go one at a time, and those one gesture holds\n * keep their own pair of calls or a signal of their own.\n *\n * @example\n * ```ts\n * readonly #listeners = new ListenerSet();\n *\n * connect(): void {\n * this.#listeners.add(this.element, \"submit\", this.#onNativeSubmit, { capture: true });\n * this.#listeners.add(this.element, \"turbo:submit-start\", this.#onSubmitStart);\n * this.#listeners.add(this.element, \"turbo:submit-end\", this.#onSubmitEnd);\n * }\n *\n * disconnect(): void {\n * this.#listeners.dispose();\n * }\n * ```\n */\nexport class ListenerSet {\n /** The generation every `add` joins until the next `dispose()`. */\n #abort = new AbortController();\n\n /**\n * Attaches `handler` to the open generation, exactly as the caller spelled it.\n *\n * The set supplies the signal, so `options` carries everything else the DOM\n * accepts — `capture` included. A removal by hand would have to repeat that\n * flag; aborting the signal releases the listener without it.\n *\n * A `type` the target's own event map names types `handler` with that event,\n * as the target's `addEventListener` does, so a handler written for a\n * `KeyboardEvent` is passed as it is; any other `type` takes an\n * `EventListener`.\n */\n add<T extends EventTarget, K extends keyof EventMapOf<T> & string>(\n target: T,\n type: K,\n handler: (event: EventMapOf<T>[K]) => void,\n options?: ListenerOptions,\n ): void;\n add(target: EventTarget, type: string, handler: EventListener, options?: ListenerOptions): void;\n add(target: EventTarget, type: string, handler: EventListener, options?: ListenerOptions): void {\n target.addEventListener(type, handler, { ...options, signal: this.#abort.signal });\n }\n\n /**\n * Releases every listener of the open generation, synchronously, and opens the\n * next one. Idempotent, and safe before anything has been added.\n */\n dispose(): void {\n this.#abort.abort();\n this.#abort = new AbortController();\n }\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Whether a requested pass has yet to run. */\n get pending(): boolean {\n return this.#queued;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","import { ListenerSet } from \"./listener_set\";\nimport { MicrotaskCoalescer } from \"./microtask_coalescer\";\n\n/**\n * Coalesces retained-element morphs and explicit lifecycle requests into one pass.\n *\n * Observe the controller's element after its initial state is settled. Morphs on\n * that element and bubbling morphs on its descendants share the same microtask\n * as {@link schedule}. The callback repairs derived output; the controller owns\n * any logical transition reporting. {@link disconnect} releases the listener and\n * cancels pending work, including work from an earlier connected lifetime.\n */\nexport class MorphRenderWatcher {\n readonly #listeners = new ListenerSet();\n readonly #pass: MicrotaskCoalescer;\n #element: Element | null = null;\n readonly #onMorph = (): void => this.#pass.schedule();\n\n /** @param run - the single pass that repairs the settled controller's output. */\n constructor(run: () => void) {\n this.#pass = new MicrotaskCoalescer(run);\n }\n\n /** Opens observation; observing the same element again preserves queued work. */\n observe(element: Element): void {\n if (this.#element === element) return;\n this.disconnect();\n this.#element = element;\n this.#pass.activate();\n this.#listeners.add(element, \"turbo:morph-element\", this.#onMorph);\n }\n\n /** Requests one pass; requests outside an observed lifetime are ignored. */\n schedule(): void {\n this.#pass.schedule();\n }\n\n /** Whether a pass requested by a morph or {@link schedule} has yet to run. */\n get pending(): boolean {\n return this.#pass.pending;\n }\n\n /** Releases observation and pending work synchronously; safe to repeat. */\n disconnect(): void {\n this.#listeners.dispose();\n this.#pass.cancel();\n this.#element = null;\n }\n}\n","/**\n * Identifies the latest reported state transition of one owner.\n *\n * Record a transition after its state is written and before invoking external\n * code. Check the returned token before each later report: a synchronous\n * transition made by a listener supersedes reports that have not been sent.\n * Reading state or committing an unchanged state must not advance the counter.\n * Reports stay in the caller so their ordering remains explicit.\n */\nexport class MoveCounter {\n #sequence = 0;\n\n /** Records a state transition and returns its report token. */\n record(): number {\n this.#sequence += 1;\n return this.#sequence;\n }\n\n /** Whether no later state transition has superseded this report token. */\n isLatest(token: number): boolean {\n return token === this.#sequence;\n }\n}\n","import { MAX_TIMER_DELAY_MS } from \"./timer_bounds\";\n\n/** Semantic constraints on an already decoded number, independent of the DOM. */\nexport interface NumberBounds {\n /** Finite numbers are required, including when this field is omitted. */\n readonly finite?: true;\n /** Inclusive lower endpoint. */\n readonly min?: number;\n /** Inclusive upper endpoint. */\n readonly max?: number;\n /** Exclusive lower endpoint. */\n readonly exclusiveMin?: number;\n /** Require a number without a fractional part. */\n readonly integer?: boolean;\n /** Exact decoded numbers accepted by a discrete contract. */\n readonly allowedValues?: readonly number[];\n /** JSON-safe exceptions to finite-number checking for unbounded endpoints. */\n readonly allowInfinity?: \"negative\" | \"positive\" | \"both\";\n}\n\n/** One constraint for each Number Value, including shorthand declarations. */\nexport type NumberValueConstraints<Values> = {\n readonly [Key in keyof Values as Values[Key] extends\n | NumberConstructor\n | { type: NumberConstructor }\n ? Key\n : never]: NumberBounds;\n};\n\n/** Reusable semantic domains; fractional inputs remain fractional unless excluded. */\nexport const NUMBER_BOUNDS = {\n finite: { finite: true },\n nonNegative: { finite: true, min: 0 },\n positive: { finite: true, exclusiveMin: 0 },\n nonNegativeInteger: { finite: true, min: 0, integer: true },\n positiveInteger: { finite: true, exclusiveMin: 0, integer: true },\n lowerBound: { finite: true, allowInfinity: \"negative\" },\n upperBound: { finite: true, allowInfinity: \"positive\" },\n timer: { finite: true, min: 0, max: MAX_TIMER_DELAY_MS },\n positiveTimer: { finite: true, exclusiveMin: 0, max: MAX_TIMER_DELAY_MS },\n} as const satisfies Record<string, NumberBounds>;\n\n/**\n * Checks all declared bounds without rounding, clamping, or coercing the input.\n * Infinity exceptions relax only finite checking; every other bound still applies.\n */\nexport function matchesNumberBounds(value: number, bounds: NumberBounds): boolean {\n if (!Number.isFinite(value)) {\n const direction = value === Infinity ? \"positive\" : value === -Infinity ? \"negative\" : null;\n if (direction === null) return false;\n if (bounds.allowInfinity !== \"both\" && bounds.allowInfinity !== direction) return false;\n }\n if (bounds.min !== undefined && value < bounds.min) return false;\n if (bounds.max !== undefined && value > bounds.max) return false;\n if (bounds.exclusiveMin !== undefined && value <= bounds.exclusiveMin) return false;\n if (bounds.integer && !Number.isInteger(value)) return false;\n if (bounds.allowedValues !== undefined && !bounds.allowedValues.includes(value)) return false;\n return true;\n}\n\n/** Decodes a Number Value literal; action params use their own JSON decoder. */\nexport function decodeNumberValue(raw: string): number {\n return Number(raw.replace(/_/g, \"\"));\n}\n","/**\n * Numeric coercion for controllers that accept a number through a Value, an action\n * param, or an event detail.\n *\n * Stimulus decodes action params as JSON when possible and leaves other text\n * untouched. CustomEvent detail can also supply a number or numeric string.\n * The reader accepts those two types while rejecting blank and non-finite input.\n */\n\nimport { matchesNumberBounds, type NumberBounds } from \"./number_bounds\";\n\n/** Numeric update input, accepting decoded action params before CustomEvent detail. */\nexport type NumericValueEvent = Event & {\n params?: { amount?: unknown };\n detail?: { value?: unknown };\n};\n\n/** Reads the nullish action-param/detail precedence without falling back from invalid input. */\nexport function eventNumber(event: NumericValueEvent): number | null {\n return toFiniteNumber(event.params?.amount ?? event.detail?.value);\n}\n\n/**\n * Reads a finite number or nonblank numeric string; other input returns `null`.\n * Blank strings cannot silently reset a value to zero.\n */\nexport function toFiniteNumber(raw: unknown): number | null {\n if (typeof raw !== \"number\" && typeof raw !== \"string\") return null;\n if (typeof raw === \"string\" && raw.trim().length === 0) return null;\n const value = Number(raw);\n return Number.isFinite(value) ? value : null;\n}\n\n/**\n * Returns an accepted decoded Number Value or the caller's fallback unchanged.\n * The caller owns the fallback contract; this reader does not parse or write a Value.\n */\nexport function readNumber(raw: number, fallback: number, bounds: NumberBounds): number {\n return matchesNumberBounds(raw, bounds) ? raw : fallback;\n}\n","import { readNumber } from \"./coerce\";\nimport { matchesNumberBounds, type NumberBounds } from \"./number_bounds\";\n\n/** The instance identity carried by a Number Value read. */\nexport interface NumberValueOwner {\n readonly identifier: string;\n readonly element: Element;\n}\n\n/** Reads current declarations at the point of use without rewriting their attributes. */\nexport class NumberValueReader {\n /** The last rejected literal per Value; no history grows for an unchanged instance. */\n readonly #lastRejected = new Map<string, string>();\n\n /** Resolves the declared number using its own fallback and shared class contract. */\n read(\n owner: NumberValueOwner,\n name: string,\n raw: number,\n fallback: number,\n bounds: NumberBounds,\n ): number {\n const resolved = readNumber(raw, fallback, bounds);\n if (matchesNumberBounds(raw, bounds)) {\n this.#lastRejected.delete(name);\n return resolved;\n }\n const attribute = `data-${owner.identifier}-${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}-value`;\n const literal = owner.element.getAttribute(attribute);\n if (literal === null) {\n this.#lastRejected.delete(name);\n return resolved;\n }\n if (this.#lastRejected.get(name) !== literal) {\n this.#lastRejected.set(name, literal);\n console.warn(\n `Stimeo UI: \"${owner.identifier}\" has an invalid number Value \"${name}\" declaration ${JSON.stringify(literal)}; using ${fallback}.`,\n );\n }\n return resolved;\n }\n}\n","/**\n * Scroll-follow for virtually-focused listbox options.\n *\n * Listbox-style widgets that track their active option with\n * `aria-activedescendant` keep DOM focus on the input/trigger, so the\n * browser's native \"scroll the focused element into view\" never runs — in a\n * scrollable list (`max-height` + `overflow`) the active option can walk right\n * out of sight on ArrowDown/ArrowUp. This helper keeps it visible.\n *\n * It adjusts the LIST's own `scrollTop` only — deliberately not\n * `scrollIntoView({ block: \"nearest\" })`, which may also scroll ancestor\n * scrolling boxes (the page) when a floating popup pokes past a viewport\n * edge, desyncing anchored/marker-composed placements. (Command-palette uses\n * `scrollIntoView` because its page is scroll-locked behind the modal;\n * page-floating popups must use this helper instead.)\n */\n\n/**\n * Scrolls `option` into view within `list` by minimally adjusting\n * `list.scrollTop`. No-ops when the list does not actually scroll. Never\n * touches any other scrolling box.\n *\n * @param list - The scrollable listbox container.\n * @param option - The (virtually focused) option to keep visible.\n */\nexport function scrollOptionIntoView(list: HTMLElement, option: HTMLElement): void {\n if (list.scrollHeight <= list.clientHeight) return;\n const listRect = list.getBoundingClientRect();\n const optionRect = option.getBoundingClientRect();\n if (optionRect.top < listRect.top) {\n list.scrollTop -= listRect.top - optionRect.top;\n } else if (optionRect.bottom > listRect.bottom) {\n list.scrollTop += optionRect.bottom - listRect.bottom;\n }\n}\n","import { setAttributeIfChanged } from \"./attribute_write\";\nimport { sharedRegistry } from \"./shared_registry\";\n\n/** What a consumer declares once about the regions one boolean state reveals. */\nexport interface StateRegionsOptions {\n /** Returns the declared regions shown while the state holds. */\n readonly whenTrue: () => readonly HTMLElement[];\n /**\n * Returns the declared regions shown while the state does not hold. Omitted by a\n * state whose other side has nothing of its own to show.\n */\n readonly whenFalse?: () => readonly HTMLElement[];\n}\n\n/** One instance's hold on one region's `hidden`, in the stack every instance shares. */\ninterface RegionHold {\n /** The instance holding it; `null` for a hold read from a copy's record until it is taken. */\n instance: object | null;\n readonly record: string;\n /** What the author wrote: the `hidden` it hands back with nothing beneath it. */\n readonly authored: string | null;\n /** Whether the visibility it wrote last hides the region. */\n written: boolean;\n /** Whether it hands back what the hold beneath it wrote last instead. */\n linked: boolean;\n}\n\n/** What an instance's record on a region says. */\ninterface RegionRecord {\n readonly authored: string | null;\n readonly written: boolean;\n readonly linked: boolean;\n /** The records of the other owners' holds beneath it, nearest first. */\n readonly beneath: readonly string[];\n}\n\n/** The holds on each region and every instance's record name. */\ninterface StateRegionsRegistry {\n readonly stacks: WeakMap<HTMLElement, RegionHold[]>;\n readonly names: Set<string>;\n}\n\n/**\n * Owns `hidden` on the regions a boolean state reveals.\n *\n * A region is a **declared** target, so the consumer decides whether one exists at\n * all; where it does, which side is shown is a pure function of the state and the\n * controller writes it unconditionally. An authored `hidden` is therefore not read\n * back — the first reflection after a connection settles it, and a restored DOM\n * cannot leave a region contradicting the state it belongs to.\n *\n * The regions arrive as the caller's own target arrays, which Stimulus has already\n * scoped to this instance: a nested controller registered under the same identifier\n * keeps its own regions. `host` narrows that set further, to the regions inside one\n * trigger or item, so a widget with several of them reflects each independently.\n *\n * **Two sides are a pair.** Where the state has a `whenFalse` side and only one half\n * sits inside `host`, the half that is there is left in view: hiding it would take\n * the only label with it, and the static check names the missing one instead. What\n * the author wrote on a lone half is theirs and stays — only a half this instance\n * took out of view is given back, which is what a pair losing one side at runtime\n * leaves behind.\n *\n * `hidden` moves only where it changes, and the record below only where what it says changes:\n * a transition costs a consumer watching its own subtree for attribute mutations two of them on\n * each region it moves — `hidden` and the record — and a reflection that moves nothing costs\n * none. A write that moves no `hidden` — the page moved the region first, or another\n * instance's hold lies above this one — changes only the record.\n *\n * **Every instance shares one stack of holds per region**, whatever its owner and whichever\n * file of the package constructed it (the stacks are one per page): the holds sit in the order\n * their instances first wrote the region, each with the visibility it wrote last. The region's\n * visibility is the highest hold's that carries it, and the page's when none does. A write\n * moves `hidden` unless a hold above the writer carries the region's visibility, so the top\n * hold always shows its writes and the page's visibility gives way to the next write of any\n * hold. A release gives a visibility back only from the hold the region's visibility is: the\n * one the hold beneath it wrote last, or the author's `hidden` once nothing is beneath it; any\n * other release only leaves the stack. Holds that wrote the same visibility are told apart by\n * the stack: the higher one keeps it. A first write over a top hold whose visibility the page\n * has replaced takes the region's `hidden` as the author's. Two instances of one owner on one\n * region stack the same way.\n *\n * **The stack travels with the region.** While the region carries anything but what the author\n * wrote under its top hold, or a hold lies on another hold or is covered by one, the region\n * carries that hold's owner's record `data-<owner>-hidden-region`: JSON of what the author\n * wrote (a string, or `null` for an absent attribute), whether the visibility written last\n * hides the region, `false` where the hold hands back the author's `hidden` rather than the\n * latest visibility of the hold beneath it, and the records of every hold beneath it, nearest\n * first; the last release of an owner removes it. A copy of the region — a page Turbo restores\n * from its cache — therefore carries the stack, read back under the record names of the\n * instances constructed so far and ordered by the records each hold lists beneath it, and an\n * instance that reflects, gives back or releases the copy takes the hold its owner's record\n * describes over in place. Complete records for distinct owners preserve their order across\n * a copy, including release without a new reflection. Records describe owners, not instances:\n * one owner holding the region more than once leaves only its topmost hold's record, which\n * the first of its instances to write or release on the copy takes. Its lower holds and\n * positions are absent; mutually listed owners cannot express their full live order. A hold\n * that showed the author's `hidden` alone carries no record and is taken by its first write\n * on the copy. Missing or unreadable records also leave their holds unknown, so copying the\n * DOM does not promise identical decisions for every live stack. A new stack with no readable\n * record takes the current value as the author's; a morph can remove records while existing\n * holds remain in memory until released.\n *\n * @example\n * ```ts\n * readonly #labels = new StateRegions(\n * {\n * whenTrue: () => this.expandedLabelTargets,\n * whenFalse: () => this.collapsedLabelTargets,\n * },\n * this.identifier,\n * );\n *\n * #reflect(): void {\n * this.#labels.reflect(this.triggerTarget, this.#expanded);\n * }\n * ```\n */\nexport class StateRegions {\n /** The holds on each region, bottom first, and the record names; one per page. */\n static readonly #registry = sharedRegistry(\n \"stimeo-ui.state-regions.registry.v1\",\n (): StateRegionsRegistry => ({ stacks: new WeakMap(), names: new Set() }),\n );\n readonly #whenTrue: () => readonly HTMLElement[];\n readonly #whenFalse: (() => readonly HTMLElement[]) | null;\n readonly #record: string;\n\n /**\n * @param options - The declared regions of each side.\n * @param owner - Names the record on a region; the controller's identifier.\n */\n constructor(options: StateRegionsOptions, owner: string) {\n this.#whenTrue = options.whenTrue;\n this.#whenFalse = options.whenFalse ?? null;\n this.#record = `data-${owner}-hidden-region`;\n StateRegions.#registry.names.add(this.#record);\n }\n\n /** Shows the regions inside `host` that belong to `isTrue` and hides the others. */\n reflect(host: Element, isTrue: boolean): void {\n const shown = this.#inside(host, this.#whenTrue());\n if (!this.#whenFalse) {\n for (const region of shown) this.#write(region, !isTrue);\n return;\n }\n const hiddenSide = this.#inside(host, this.#whenFalse());\n if (shown.length === 0 || hiddenSide.length === 0) {\n for (const region of shown) this.#give(region);\n for (const region of hiddenSide) this.#give(region);\n return;\n }\n for (const region of shown) this.#write(region, !isTrue);\n for (const region of hiddenSide) this.#write(region, isTrue);\n }\n\n /**\n * Restores the regions this instance wrote inside `host` to what the hold beneath it wrote last\n * or the authored `hidden`, unless changed since; found by scan, as the declared lists stop\n * resolving with targets.\n */\n release(host: Element): void {\n for (const region of [host, ...host.querySelectorAll(\"*\")]) {\n if (!(region instanceof HTMLElement)) continue;\n const stack = this.#held(region);\n const hold = stack && this.#take(stack);\n if (!stack || !hold) continue;\n const owns = region.hidden === hold.written && !this.#covered(region, stack, hold);\n const index = stack.indexOf(hold);\n stack.splice(index, 1);\n const above = stack[index];\n if (above) above.linked &&= hold.linked;\n if (owns) {\n const below = hold.linked ? stack[index - 1] : undefined;\n if (below) {\n if (region.hidden !== below.written) region.hidden = below.written;\n } else {\n setAttributeIfChanged(region, \"hidden\", hold.authored);\n }\n }\n this.#mark(region, stack);\n }\n }\n\n /** Writes `hidden` where it moves, unless a hold above this one carries the region's. */\n #write(region: HTMLElement, hidden: boolean): void {\n const stack = this.#stack(region);\n const hold = this.#take(stack) ?? this.#acquire(region, stack);\n const shows = !this.#covered(region, stack, hold);\n hold.written = hidden;\n if (shows && region.hidden !== hidden) region.hidden = hidden;\n this.#mark(region, stack);\n }\n\n /** Returns a region this instance hid; one it never hid keeps what it carries. */\n #give(region: HTMLElement): void {\n const stack = this.#held(region);\n if (stack && this.#take(stack)?.written) this.#write(region, false);\n }\n\n /** The region's stack, while it has one or carries this owner's record. */\n #held(region: HTMLElement): RegionHold[] | undefined {\n return StateRegions.#registry.stacks.has(region) || region.hasAttribute(this.#record)\n ? this.#stack(region)\n : undefined;\n }\n\n /** The region's stack, read from its records the first time. */\n #stack(region: HTMLElement): RegionHold[] {\n const stacks = StateRegions.#registry.stacks;\n const stack = stacks.get(region) ?? this.#seed(region);\n stacks.set(region, stack);\n return stack;\n }\n\n /** The holds a copy's records describe, each above every hold its record lists beneath. */\n #seed(region: HTMLElement): RegionHold[] {\n const found: (RegionRecord & { readonly record: string })[] = [];\n for (const record of StateRegions.#registry.names) {\n const read = this.#recorded(region, record);\n if (read) found.push({ ...read, record });\n }\n const depth = ({ beneath }: (typeof found)[number]) =>\n beneath.filter((name) => found.some((other) => other.record === name)).length;\n return found\n .sort((one, other) => depth(one) - depth(other))\n .map(({ record, authored, written, linked }, index) => ({\n instance: null,\n record,\n authored,\n written,\n linked: linked && index > 0,\n }));\n }\n\n /** Its hold in `stack`, taking over one read from its record. */\n #take(stack: RegionHold[]): RegionHold | undefined {\n const hold =\n stack.find((held) => held.instance === this) ??\n stack.find((held) => held.instance === null && held.record === this.#record);\n if (hold) hold.instance = this;\n return hold;\n }\n\n /** Whether a hold above `hold` carries the region's visibility, then that hold's. */\n #covered(region: HTMLElement, stack: readonly RegionHold[], hold: RegionHold): boolean {\n return stack.slice(stack.indexOf(hold) + 1).some((above) => above.written === region.hidden);\n }\n\n /** A new hold on top, over the top hold while the region shows what it wrote. */\n #acquire(region: HTMLElement, stack: RegionHold[]): RegionHold {\n const top = stack.at(-1);\n const over = top && region.hidden === top.written ? top : undefined;\n const hold: RegionHold = {\n instance: this,\n record: this.#record,\n authored: over ? over.authored : region.getAttribute(\"hidden\"),\n written: false,\n linked: over !== undefined,\n };\n stack.push(hold);\n return hold;\n }\n\n /** Leaves each owner's record of its topmost hold, or none where nothing needs one. */\n #mark(region: HTMLElement, stack: readonly RegionHold[]): void {\n const records = new Map<string, string | null>([[this.#record, null]]);\n stack.forEach((hold, index) => {\n const names = stack.slice(0, index).map((under) => under.record);\n const beneath = [...new Set(names.reverse())].filter((name) => name !== hold.record);\n const marker = hold.linked || beneath.length === 0 ? [] : [false];\n records.set(\n hold.record,\n region.getAttribute(\"hidden\") === hold.authored &&\n beneath.length === 0 &&\n index === stack.length - 1\n ? null\n : JSON.stringify([hold.authored, hold.written, ...marker, ...beneath]),\n );\n });\n for (const [name, recorded] of records) {\n setAttributeIfChanged(region, name, recorded);\n }\n }\n\n /**\n * The author's `hidden`, the visibility written last, whether it hands back the visibility\n * beneath it (`false` before the names when it does not) and the records beneath that the\n * record `name` on `region` holds.\n */\n #recorded(region: HTMLElement, name: string): RegionRecord | null {\n try {\n const parsed: unknown = JSON.parse(region.getAttribute(name) ?? \"null\");\n if (!Array.isArray(parsed)) return null;\n const [authored, written, ...rest] = parsed as unknown[];\n if (authored !== null && typeof authored !== \"string\") return null;\n const linked = rest[0] !== false;\n const beneath = linked ? rest : rest.slice(1);\n if (!beneath.every((under): under is string => typeof under === \"string\")) return null;\n return typeof written === \"boolean\" ? { authored, written, linked, beneath } : null;\n } catch {\n return null;\n }\n }\n\n /** The declared regions that sit within `host`, which may be the host itself. */\n #inside(host: Element, regions: readonly HTMLElement[]): HTMLElement[] {\n return regions.filter((region) => host.contains(region));\n }\n}\n","/**\n * Whether a disabled `<fieldset>` ancestor actually reaches `control`.\n *\n * HTML exempts the contents of a fieldset's **first direct-child `<legend>`**, and\n * the exemption is per fieldset — a control legal in one legend can still be\n * disabled by a second, outer fieldset, so the walk continues upward.\n *\n * Exported on its own for callers that need the disabled-inheritance rule without\n * the rest of {@link canTakeFocus} — a control's availability check, or a `hidden`\n * walk bounded at a widget root, which is a different rule to compose with.\n */\nexport function inheritsFieldsetDisabled(control: HTMLElement): boolean {\n let fieldset: Element | null = control.closest(\"fieldset[disabled]\");\n while (fieldset) {\n const legend = Array.from(fieldset.children).find((child) => child.tagName === \"LEGEND\");\n if (!legend?.contains(control)) return true;\n fieldset = fieldset.parentElement?.closest(\"fieldset[disabled]\") ?? null;\n }\n return false;\n}\n\n/**\n * Whether the engine reports `element` assigned to no slot of the open shadow root its parent\n * hosts: such an element is not in the flat tree, so it and what it holds are rendered nowhere\n * and cannot take focus.\n */\nfunction unslotted(element: Element): boolean {\n return element.assignedSlot === null && element.parentElement?.shadowRoot != null;\n}\n\n/**\n * The parent of `element` in the flat tree: the slot it is assigned to, its parent element,\n * or the host of the shadow root it is a child of; `null` at the top of the document or of a\n * detached tree, and for an element the engine assigns to no slot of the open shadow root its\n * parent hosts, which is outside the flat tree. A closed shadow root does not report its slots,\n * so an element assigned to one climbs to the host.\n */\nexport function flatTreeParent(element: Element): Element | null {\n if (unslotted(element)) return null;\n const parent = element.assignedSlot ?? element.parentNode;\n if (parent instanceof ShadowRoot) return parent.host;\n return parent instanceof Element ? parent : null;\n}\n\n/** Whether `element` is `ancestor` or one of its descendants in the flat tree. */\nexport function flatTreeContains(ancestor: Element, element: Element | null): boolean {\n for (let node = element; node; node = flatTreeParent(node)) {\n if (node === ancestor) return true;\n }\n return false;\n}\n\n/** The nearest of `element` and its flat-tree ancestors that matches `selector`, or `null`. */\nexport function closestInFlatTree(element: Element, selector: string): Element | null {\n for (let node: Element | null = element; node; node = flatTreeParent(node)) {\n if (node.matches(selector)) return node;\n }\n return null;\n}\n\n/**\n * The children of `element` in the flat tree: its open shadow root's children, a slot's\n * assigned elements (its own children when nothing is assigned to it), or its children.\n */\nexport function flatTreeChildren(element: Element): Element[] {\n return ownedScope(element) ?? Array.from(element.children);\n}\n\n/**\n * Whether an element can actually take focus, checked **before** `focus()` runs.\n *\n * A controller that must move focus off a control it is about to disable or hide\n * picks a destination and calls `focus()` on it. If that destination cannot take\n * focus, the call **fails silently**: `hidden` and natively `disabled` elements\n * swallow it, so the caret stays in the subtree that is disappearing and lands on\n * `<body>` a frame later — the exact outcome the rescue exists to prevent, minus\n * any signal that it happened.\n *\n * Testing after the fact is the obvious alternative and is deliberately not the\n * rule. Reading `document.activeElement` back only works in a real browser, and\n * looping over candidates that way performs a real focus move per failure —\n * observable to assistive technology. Checking first costs nothing and catches\n * the cases that actually occur.\n *\n * **`aria-disabled` is not disqualifying.** It is the attribute an author uses\n * for a control that must stay *discoverable*, and the roving contract keeps\n * such items reachable. Only the conditions that make the platform refuse\n * focus are checked: `hidden` / `inert` on the element or a flat-tree ancestor\n * (the host of an open shadow root it sits in, the slot it is assigned to), the\n * element or an ancestor left out of the flat tree (one the engine assigns to no\n * slot of the open shadow root its parent hosts), `input[type=\"hidden\"]`, the\n * native `disabled` property, and `disabled` inherited from an ancestor\n * `fieldset`. CSS-only invisibility is handled by {@link isRenderedForFocus}\n * when a consumer needs sequential-focus semantics.\n *\n * Reading `:disabled` instead of walking the fieldset chain would be shorter, but\n * that pseudo-class is not evaluated consistently outside real browsers and this\n * has to be right headlessly too. happy-dom in particular focuses a `<button>`\n * inside a disabled fieldset where a real engine refuses, so the inheritance is\n * spelled out rather than delegated.\n *\n * What a consumer does when nothing survives is its own call: some fall back to\n * their landmark, while a widget whose caret already sits somewhere legitimate\n * refuses the move outright rather than relocating it.\n *\n * @example\n * ```ts\n * const target = candidates.find(canTakeFocus);\n * if (target) target.focus();\n * else {\n * this.#tabindex.lend(this.element); // nothing left: fall back to the landmark\n * this.element.focus();\n * }\n * ```\n *\n * @param element - the candidate destination\n */\nexport function canTakeFocus(element: HTMLElement): boolean {\n for (let node: Element | null = element; node; node = flatTreeParent(node)) {\n if (unslotted(node) || node.matches(\"[hidden], [inert]\")) return false;\n }\n if (element instanceof HTMLInputElement && element.type === \"hidden\") return false;\n if (!(\"disabled\" in element)) return true;\n if ((element as HTMLElement & { disabled: boolean }).disabled) return false;\n return !inheritsFieldsetDisabled(element);\n}\n\n/** Elements whose semantics or authored attributes can place them in sequential focus order. */\nexport const TAB_STOP_CANDIDATE_SELECTOR = [\n \"a[href]\",\n \"area[href]\",\n \"button\",\n \"input\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"iframe\",\n \"audio[controls]\",\n \"video[controls]\",\n \"[tabindex]\",\n \"[contenteditable]\",\n].join(\",\");\n\n/** Optional browser visibility API used to exclude CSS-hidden candidates. */\ninterface VisibilityCheckable {\n checkVisibility?: (options?: { visibilityProperty?: boolean }) => boolean;\n}\n\n/** Whether CSS visibility allows an otherwise eligible element to participate in focus order. */\nexport function isRenderedForFocus(element: HTMLElement): boolean {\n const check = (element as HTMLElement & VisibilityCheckable).checkVisibility;\n return typeof check === \"function\" ? check.call(element, { visibilityProperty: true }) : true;\n}\n\n/** Parses an authored `tabindex`; invalid syntax has no explicit focus-order meaning. */\nfunction authoredTabindex(element: Element): number | null {\n const value = element.getAttribute(\"tabindex\");\n if (value === null || !/^[+-]?\\d+$/.test(value.trim())) return null;\n return Number(value);\n}\n\n/** Whether the element's native semantics place it in sequential focus order. */\nfunction hasNativeTabStop(element: HTMLElement): boolean {\n if (element instanceof HTMLAnchorElement || element instanceof HTMLAreaElement) {\n return element.hasAttribute(\"href\");\n }\n if (\n element instanceof HTMLButtonElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement\n ) {\n return true;\n }\n if (element instanceof HTMLInputElement) return element.type !== \"hidden\";\n if (element instanceof HTMLIFrameElement) return true;\n if (element.tagName === \"AUDIO\" || element.tagName === \"VIDEO\") {\n return element.hasAttribute(\"controls\");\n }\n if (element instanceof HTMLElement && element.tagName === \"SUMMARY\") {\n const details = element.parentElement;\n return (\n details instanceof HTMLDetailsElement &&\n Array.from(details.children).find((child) => child.tagName === \"SUMMARY\") === element\n );\n }\n return false;\n}\n\n/** Whether an explicit `contenteditable` value creates an editable tab stop. */\nfunction hasEditableTabStop(element: HTMLElement): boolean {\n const value = element.getAttribute(\"contenteditable\")?.toLowerCase();\n return value === \"\" || value === \"true\" || value === \"plaintext-only\";\n}\n\n/**\n * Whether an element is a usable sequential Tab stop right now.\n *\n * Native semantics, authored `tabindex`, editable hosts, inherited disabled state,\n * HTML `hidden`/`inert`, and CSS visibility are evaluated together. `aria-disabled`\n * remains focusable because it communicates unavailability without removing the\n * control from discovery order.\n */\nexport function isTabStop(element: HTMLElement): boolean {\n if (!canTakeFocus(element) || !isRenderedForFocus(element)) return false;\n\n const tabindex = authoredTabindex(element);\n if (tabindex !== null) return tabindex >= 0;\n return hasNativeTabStop(element) || hasEditableTabStop(element);\n}\n\n/** Returns every usable sequential Tab stop below `root` in document order. */\nexport function tabStopsWithin(root: ParentNode): HTMLElement[] {\n return Array.from(root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)).filter(\n isTabStop,\n );\n}\n\n/** Returns the first usable sequential Tab stop below `root`, if one exists. */\nexport function firstTabStop(root: ParentNode): HTMLElement | null {\n for (const candidate of root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)) {\n if (isTabStop(candidate)) return candidate;\n }\n return null;\n}\n\n/** Whether `root` contains at least one usable sequential Tab stop. */\nexport function hasTabStop(root: ParentNode): boolean {\n return firstTabStop(root) !== null;\n}\n\n/** An element sequential focus navigation can stop on. */\nexport type TabStopElement = HTMLElement | SVGElement;\n\n/** Whether the element is a radio button. */\nfunction isRadio(element: Element | null): element is HTMLInputElement {\n return element instanceof HTMLInputElement && element.type === \"radio\";\n}\n\n/**\n * Whether two radios form one group: the same non-empty `name`, the same form owner and\n * the same tree. A radio without a name is a group of its own.\n */\nfunction sameRadioGroup(a: HTMLInputElement, b: HTMLInputElement): boolean {\n return (\n a.name !== \"\" && a.name === b.name && a.form === b.form && a.getRootNode() === b.getRootNode()\n );\n}\n\n/**\n * Whether the element is part of editable content: the nearest ancestor that sets a valid\n * `contenteditable` decides. `false` ends the editable region (a non-editable island\n * inside an editor); an invalid value inherits from further up.\n */\nfunction isInEditableContent(element: Element): boolean {\n for (let node = element.parentElement; node; node = node.parentElement) {\n if (node.getAttribute(\"contenteditable\")?.toLowerCase() === \"false\") return false;\n if (hasEditableTabStop(node)) return true;\n }\n return false;\n}\n\n/** The XLink namespace, where an SVG link may carry its `href`. */\nconst XLINK_NAMESPACE = \"http://www.w3.org/1999/xlink\";\n\n/** Whether the element is an SVG link: an SVG `a` with `href` or `xlink:href`. */\nfunction isSvgLink(element: Element): boolean {\n return (\n element instanceof SVGElement &&\n element.localName === \"a\" &&\n (element.hasAttribute(\"href\") || element.hasAttributeNS(XLINK_NAMESPACE, \"href\"))\n );\n}\n\n/**\n * Whether an image-map area has a rendered image: an `img` in the area's tree whose\n * `usemap` names the area's map (by `name`, or by `id` without one) and that is rendered.\n * The area has no box of its own for {@link isRenderedForFocus} to check.\n */\nfunction hasRenderedImage(area: HTMLAreaElement): boolean {\n const map = area.closest(\"map\");\n const key = map?.name || map?.id;\n if (!map || !key) return false;\n const root = map.getRootNode() as Document | ShadowRoot;\n return Array.from(root.querySelectorAll<HTMLElement>(\"img[usemap]\")).some(\n (image) => image.getAttribute(\"usemap\") === `#${key}` && isRenderedForFocus(image),\n );\n}\n\n/** Whether the element can take focus and has no negative `tabindex`. */\nfunction isFocusableInOrder(element: TabStopElement): boolean {\n const tabindex = authoredTabindex(element);\n return (tabindex === null || tabindex >= 0) && canTakeFocus(element as HTMLElement);\n}\n\n/**\n * The engine's verdict for the stops {@link isTabStop} does not judge the way sequential\n * navigation does, or `null` for every other element: an image-map area with an `href` or\n * its own `tabindex` stops while an image that uses its map is rendered; an object stops\n * while it holds a nested document, as an iframe does; an SVG link stops while it is\n * rendered. Each also needs to take focus and not be taken out of the order with a\n * negative `tabindex`.\n */\nfunction extraStop(element: TabStopElement): boolean | null {\n if (element instanceof HTMLAreaElement) {\n const focusable = element.hasAttribute(\"href\") || authoredTabindex(element) !== null;\n return focusable && isFocusableInOrder(element) && hasRenderedImage(element);\n }\n if (element instanceof HTMLObjectElement) {\n return (\n isFocusableInOrder(element) && isRenderedForFocus(element) && element.contentWindow !== null\n );\n }\n if (isSvgLink(element))\n return isFocusableInOrder(element) && isRenderedForFocus(element as HTMLElement);\n return null;\n}\n\n/**\n * Whether sequential navigation stops on the element: a usable Tab stop\n * ({@link isTabStop}), or one of the stops `extraStop` judges, except a link inside\n * editable content without a `tabindex` of its own, which the engine leaves to editing.\n * Other controls inside an editing host, and the host itself, stay stops.\n */\nfunction isSequentialStop(element: TabStopElement): boolean {\n const stop =\n extraStop(element) ??\n (element.matches(TAB_STOP_CANDIDATE_SELECTOR) && isTabStop(element as HTMLElement));\n if (!stop) return false;\n const link =\n element instanceof HTMLAnchorElement ||\n element instanceof HTMLAreaElement ||\n isSvgLink(element);\n return !(link && authoredTabindex(element) === null && isInEditableContent(element));\n}\n\n/**\n * The elements of the focus navigation scope `element` owns: its open shadow root's\n * children, or a slot's assigned elements (its fallback content when nothing is\n * assigned). `null` when it owns no scope. A closed shadow root cannot be read, so its\n * host owns none.\n */\nfunction ownedScope(element: Element): Element[] | null {\n if (element.shadowRoot) return Array.from(element.shadowRoot.children);\n if (element instanceof HTMLSlotElement) {\n const assigned = element.assignedElements();\n return assigned.length > 0 ? assigned : Array.from(element.children);\n }\n return null;\n}\n\n/** One member of a focus navigation scope: its tabindex and the stops it contributes. */\ninterface ScopeEntry {\n readonly tabindex: number;\n readonly stops: TabStopElement[];\n}\n\n/** What a walk of the order records besides the order itself. */\ninterface OrderWalk {\n /** The element a move starts from. */\n readonly from: Element | null;\n /** Every stop, in flat-tree order. */\n readonly tree: TabStopElement[];\n /**\n * How many entries of {@link OrderWalk.tree} come before `from`; `-1` until the walk\n * meets it.\n */\n fromAt: number;\n}\n\n/**\n * Orders one focus navigation scope the way HTML's sequential navigation does: members\n * with a positive `tabindex` first, ascending, ties in tree order, then the rest in tree\n * order. A member that owns a scope (a shadow host, a slot) is followed by that scope's\n * own order; one taken out of the order with a negative `tabindex` takes its scope with it.\n */\nfunction orderScope(elements: Element[], walk: OrderWalk): TabStopElement[] {\n const entries: ScopeEntry[] = [];\n const visit = (element: Element): void => {\n if (element === walk.from) walk.fromAt = walk.tree.length;\n const tabindex = authoredTabindex(element) ?? 0;\n const stop =\n (element instanceof HTMLElement || element instanceof SVGElement) && isSequentialStop(element)\n ? element\n : null;\n if (stop) walk.tree.push(stop);\n const owned = ownedScope(element);\n if (owned) {\n if (tabindex >= 0) {\n entries.push({ tabindex, stops: [...(stop ? [stop] : []), ...orderScope(owned, walk)] });\n }\n return;\n }\n if (stop) entries.push({ tabindex, stops: [stop] });\n for (const child of Array.from(element.children)) visit(child);\n };\n for (const element of elements) visit(element);\n const positive = entries.filter((entry) => entry.tabindex > 0);\n positive.sort((a, b) => a.tabindex - b.tabindex);\n const rest = entries.filter((entry) => entry.tabindex === 0);\n return [...positive, ...rest].flatMap((entry) => entry.stops);\n}\n\n/**\n * Whether a candidate passes the radio-group rule the engine applies: a checked radio\n * among the stops always does; an unchecked one only as the first radio of a group with\n * no checked stop, and not while focus is on a radio of that group. `tree` is the walk's\n * stops in flat-tree order, so a group is counted within the walked root only.\n */\nfunction passesRadioRule(\n element: TabStopElement,\n tree: TabStopElement[],\n focusedRadio: HTMLInputElement | null,\n): boolean {\n if (!isRadio(element) || element.checked) return true;\n const group = tree.filter(\n (stop): stop is HTMLInputElement =>\n stop === element || (isRadio(stop) && sameRadioGroup(stop, element)),\n );\n if (group.some((radio) => radio.checked)) return false;\n if (group[0] !== element) return false;\n return focusedRadio === null || !sameRadioGroup(focusedRadio, element);\n}\n\n/**\n * The index in `order` a move from the walk's `from` visits first. A start the walk did\n * not meet is outside: the move enters at the first stop, or the last going backward. A\n * start that is a stop moves one place along the order. Any other start (the root, an\n * element with a negative `tabindex`) moves to the nearest stop after it in tree order,\n * or before it going backward, and wraps when there is none.\n */\nfunction startIndex(\n order: TabStopElement[],\n walk: OrderWalk,\n backward: boolean,\n isStop: (element: TabStopElement) => boolean,\n): number {\n if (walk.fromAt < 0) return backward ? order.length - 1 : 0;\n const at = order.indexOf(walk.from as TabStopElement);\n if (at >= 0) return backward ? at - 1 : at + 1;\n const neighbour = backward\n ? walk.tree.slice(0, walk.fromAt).reverse().find(isStop)\n : walk.tree.slice(walk.fromAt).find(isStop);\n if (neighbour) return order.indexOf(neighbour);\n return backward ? order.length - 1 : 0;\n}\n\n/**\n * The stops below `root` in the order a sequential move from `from` visits them: the\n * next stop first (the previous one when `backward`), wrapping at the ends, with `from`\n * itself left out. Without a `from` — or with one outside `root` — the list starts at the\n * first stop, or at the last one when `backward`.\n *\n * The order is HTML's sequential navigation order within `root`: positive `tabindex`\n * first, ascending, then `tabindex=\"0\"` and native stops in tree order. Open shadow roots\n * are walked in flat-tree order, slots expanded, each scope ordered on its own; a closed\n * shadow root is not read. A radio group, counted within `root`, stops once: on its\n * checked radio when that radio can take focus, even with focus elsewhere in the group,\n * and otherwise on its first radio that can, unless focus is already in the group.\n * A link inside editable content without its own `tabindex` is not a stop. Every stop\n * also passes its applicable focusability and rendering checks.\n *\n * @param root - The element whose descendants are ordered; it is not a stop itself.\n * @param from - Where the move starts, usually {@link deepActiveElement}.\n * @param backward - Whether the move goes backward (`Shift+Tab`).\n */\nexport function sequentialTabStops(\n root: Element,\n from: Element | null = null,\n backward = false,\n): TabStopElement[] {\n const walk: OrderWalk = { from, tree: [], fromAt: from === root ? 0 : -1 };\n const order = orderScope(ownedScope(root) ?? Array.from(root.children), walk);\n const focusedRadio = walk.fromAt >= 0 && isRadio(from) ? from : null;\n const isStop = (element: TabStopElement): boolean =>\n passesRadioRule(element, walk.tree, focusedRadio);\n const start = startIndex(order, walk, backward, isStop);\n const visited = backward\n ? [...order.slice(0, start + 1).reverse(), ...order.slice(start + 1).reverse()]\n : [...order.slice(start), ...order.slice(0, start)];\n return visited.filter((element) => element !== from && isStop(element));\n}\n\n/**\n * The element that holds focus in `ownerDocument`, looking through open shadow roots:\n * `document.activeElement` stops at a shadow host. A closed shadow root cannot be read,\n * so focus inside one reads as its host.\n */\nexport function deepActiveElement(ownerDocument: Document): Element | null {\n let active = ownerDocument.activeElement;\n while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;\n return active;\n}\n","/** Queries physical descendants and nested open shadow trees, including `root`'s own. */\nexport function queryOpenDescendants<T extends Element = Element>(\n root: ParentNode,\n selector: string,\n): T[] {\n const matches: T[] = [];\n const roots: ParentNode[] = [root];\n for (const scope of roots) {\n matches.push(...scope.querySelectorAll<T>(selector));\n if (scope.nodeType === Node.ELEMENT_NODE) {\n const shadow = (scope as Element).shadowRoot;\n if (shadow) roots.push(shadow);\n }\n for (const element of scope.querySelectorAll(\"*\")) {\n if (element.shadowRoot) roots.push(element.shadowRoot);\n }\n }\n return matches;\n}\n","import { setAttributeIfChanged } from \"./attribute_write\";\nimport { deepActiveElement } from \"./focus_candidate\";\nimport { queryOpenDescendants } from \"./query_open_descendants\";\nimport { sharedRegistry } from \"./shared_registry\";\n\n/** One loan's hold on one element's `tabindex`, in the stack every loan of it shares. */\ninterface LoanHold {\n /** The loan holding it; `null` for a loan read from a copy's record until a loan takes it. */\n loan: object | null;\n readonly record: string;\n readonly value: string;\n /** Whether it hands back the value of the hold beneath it; otherwise no `tabindex`. */\n linked: boolean;\n}\n\n/** The loans on each element, bottom first, and every loan's record name. */\ninterface TabindexLoanRegistry {\n readonly stacks: WeakMap<HTMLElement, LoanHold[]>;\n readonly names: Set<string>;\n}\n\n/** Focus can be retargeted to a shadow host rather than exposed on the document. */\nfunction holdsFocus(element: HTMLElement): boolean {\n return element.matches(\":focus\") || deepActiveElement(element.ownerDocument) === element;\n}\n\n/**\n * Shared bookkeeping for a `tabindex` a controller lends an element temporarily.\n *\n * A controller that must move focus somewhere the author never made focusable\n * (a landmark root, a scroll destination) reaches for the same trick: add a\n * `tabindex` just-in-time and hand it back once it is no longer needed. The\n * borrow is the easy half; the return is what the two conditions below are for.\n *\n * **Returning needs two conditions, not one.** Owning the borrow is not enough:\n * the attribute must also still hold the value this instance wrote. A consumer\n * that changed it afterwards — `tabindex=\"0\"` to make the root its own Tab stop\n * — owns it now, and removing it there silently discards authored markup. The\n * bookkeeping is dropped when returned. With `preserveFocus`, a focused element\n * still showing this loan keeps its hold and record until a later return can finish.\n *\n * **Never borrow over a value no loan holds.** An element whose `tabindex` no loan\n * holds — the author's, or one the page wrote over the loans — is the author's to\n * control, so there is nothing to lend and nothing to return.\n *\n * **Every loan of an element shares one stack of loans**, whatever its owner and\n * whichever file of the package constructed it (the stacks are one per page). A loan\n * lends over the loans that hold the element while its `tabindex` is theirs — sharing\n * their value, or covering it with its own — and lends again where the page removed\n * the `tabindex`. The `tabindex` is the highest loan's that lends its value: returning\n * that loan gives the element the value of the loan beneath it, or no `tabindex`, and\n * any other return only leaves the stack. So two loans of one value — every focus trap\n * lends its container under one owner — keep it until the last of them returns, and a\n * loan lent after the page removed an earlier one's `tabindex` keeps it when the\n * earlier one returns.\n *\n * **A loan is recorded on the element.** Lending writes\n * `data-<owner>-tabindex-loan` holding the value the owner's topmost loan lends next\n * to the `tabindex`, and the owner's last loan to end removes it. A copy of the\n * element — a page Turbo restores from its cache is one — so tells its owners' loans\n * from an authored `tabindex`: `lend()` takes over a loan its owner recorded, and\n * `reclaim()` gives back one no loan has taken over; the `tabindex` goes with the last\n * of them. A copy keeps no order of its loans beyond putting those of the value it\n * carries on top. Without a record a `tabindex` is the author's. Nothing returns a\n * live loan before Turbo caches the page: `turbo:before-cache` also fires on pages\n * that stay, and the loan is still in use there.\n *\n * The registry is keyed by element, so a controller borrowing on a single\n * element (`this.element`) and one borrowing across a changing set of targets\n * use the same API — the single-element case is a set of one. It holds no\n * opinion about *when* to borrow or where focus goes next; that stays in the\n * controller.\n *\n * **The API is deliberately small.** Each consumer entry includes its own copy\n * of the class, so unused methods still increase its runtime output.\n *\n * @example\n * ```ts\n * readonly #tabindex = new TabindexLoan(\"-1\", this.identifier);\n *\n * connect() {\n * this.#tabindex.reclaim(this.element);\n * }\n *\n * #rescueFocus() {\n * this.#tabindex.lend(this.element);\n * this.element.focus();\n * }\n *\n * disconnect() {\n * this.#tabindex.returnAll();\n * }\n * ```\n */\nexport class TabindexLoan<T extends HTMLElement = HTMLElement> {\n /** The loans on each element and the record names, one per page. */\n static readonly #registry = sharedRegistry(\n \"stimeo-ui.tabindex-loan.registry.v1\",\n (): TabindexLoanRegistry => ({ stacks: new WeakMap(), names: new Set() }),\n );\n readonly #value: string;\n readonly #record: string;\n readonly #preserveFocus: boolean;\n readonly #lent = new Set<T>();\n\n /**\n * @param value - the `tabindex` to lend. `\"-1\"` is programmatically focusable but\n * not a Tab stop; `\"0\"` is a real Tab stop, which a scroll region with no\n * focusable content of its own needs.\n * @param owner - Names the record on the element; the controller's identifier.\n * @param options - `preserveFocus`: keep a shown loan while its element holds focus.\n */\n constructor(value: string, owner: string, options: { readonly preserveFocus?: boolean } = {}) {\n this.#value = value;\n this.#record = `data-${owner}-tabindex-loan`;\n this.#preserveFocus = options.preserveFocus === true;\n TabindexLoan.#registry.names.add(this.#record);\n }\n\n /**\n * Lends `element` the value over the loans holding its `tabindex`, or where the page removed\n * it; a `tabindex` no loan holds is left alone, and a loan recorded on a copy taken over.\n * `onlyIfUnfocusable` starts no new loan on an element that carries any `tabindex` or is\n * natively focusable (a `tabIndex` of `0` or more).\n */\n lend(element: T, options: { readonly onlyIfUnfocusable?: boolean } = {}): void {\n const stack = this.#stack(element);\n const current = element.getAttribute(\"tabindex\");\n const held =\n stack.find((hold) => hold.loan === this) ??\n stack.find(\n (hold) => hold.loan === null && hold.record === this.#record && hold.value === this.#value,\n );\n const linked = stack.at(-1)?.value === current;\n if (!held && options.onlyIfUnfocusable && (current !== null || element.tabIndex >= 0)) return;\n if (!held && current !== null && !linked) return;\n this.#lent.add(element);\n if (held) held.loan = this;\n else stack.push({ loan: this, record: this.#record, value: this.#value, linked });\n this.#mark(element, stack);\n if (current === null || (!held && current !== this.#value)) {\n element.setAttribute(\"tabindex\", this.#value);\n }\n }\n\n /** Returns one live or restored loan, retaining a focus-protected hold for a later return. */\n return(element: T): boolean {\n const stack = this.#stack(element);\n const hold =\n stack.find((held) => held.loan === this) ??\n stack.find(\n (held) => held.loan === null && held.record === this.#record && held.value === this.#value,\n );\n if (!hold) return false;\n if (!this.#release(element, stack, hold, this.#preserveFocus)) {\n hold.loan = this;\n this.#lent.add(element);\n return false;\n }\n this.#lent.delete(element);\n return true;\n }\n\n /** Returns every loan, retaining focus-protected ones even outside the current target set. */\n returnAll(): void {\n for (const element of Array.from(this.#lent)) this.return(element);\n }\n\n /**\n * Gives back a loan its owner recorded on a restored copy that no loan has taken over, unless\n * the record holds another value or the element holds focus.\n */\n reclaim(element: HTMLElement): void {\n if (element.getAttribute(this.#record) !== this.#value) return;\n const stack = this.#stack(element);\n const hold = stack.find((held) => held.loan === null && held.record === this.#record);\n if (hold && !holdsFocus(element)) this.#release(element, stack, hold);\n }\n\n /** Gives back, as {@link reclaim} does, every loan of its owner recorded inside `root`. */\n reclaimWithin(root: ParentNode): void {\n for (const element of queryOpenDescendants<HTMLElement>(root, `[${this.#record}]`)) {\n this.reclaim(element);\n }\n }\n\n /** The element's loans, read from its records the first time. */\n #stack(element: HTMLElement): LoanHold[] {\n const stacks = TabindexLoan.#registry.stacks;\n const stack = stacks.get(element) ?? this.#seed(element);\n stacks.set(element, stack);\n return stack;\n }\n\n /** The loans a copy's records describe, those of the value it carries on top. */\n #seed(element: HTMLElement): LoanHold[] {\n const current = element.getAttribute(\"tabindex\");\n const holds: LoanHold[] = [];\n for (const record of TabindexLoan.#registry.names) {\n const value = element.getAttribute(record);\n if (value !== null) holds.push({ loan: null, record, value, linked: true });\n }\n holds.sort((one, other) => Number(one.value === current) - Number(other.value === current));\n for (const [index, hold] of holds.entries()) hold.linked = index > 0;\n return holds;\n }\n\n /** Takes `hold` off, handing the value it shows to the loan beneath. */\n #release(\n element: HTMLElement,\n stack: LoanHold[],\n hold: LoanHold,\n preserveFocus = false,\n ): boolean {\n const current = element.getAttribute(\"tabindex\");\n const index = stack.indexOf(hold);\n const owns =\n current === hold.value && !stack.slice(index + 1).some((above) => above.value === current);\n if (owns && preserveFocus && holdsFocus(element)) return false;\n stack.splice(index, 1);\n const above = stack[index];\n if (above) above.linked &&= hold.linked;\n this.#mark(element, stack);\n if (!owns) return true;\n const below = hold.linked ? stack[index - 1] : undefined;\n if (!below) element.removeAttribute(\"tabindex\");\n else if (below.value !== current) element.setAttribute(\"tabindex\", below.value);\n return true;\n }\n\n /** Leaves each owner's record of the value its topmost loan lends. */\n #mark(element: HTMLElement, stack: readonly LoanHold[]): void {\n const records = new Map<string, string | null>([[this.#record, null]]);\n for (const hold of stack) records.set(hold.record, hold.value);\n for (const [name, recorded] of records) {\n setAttributeIfChanged(element, name, recorded);\n }\n }\n}\n","/**\n * The attribute selector for one declared target, in a controller's own namespace.\n *\n * Stimulus reads `data-<identifier>-target` as a **space-separated token list**, so a\n * single element can carry several target names at once. Matching the attribute value\n * whole would reach only the elements that declare exactly one name, which is why the\n * name is paired with `~=`.\n *\n * `identifier` is the name the controller is registered under, so the selector reaches\n * the markup that registration renders rather than one fixed spelling.\n */\nexport function targetSelector(identifier: string, name: string): string {\n return `[data-${identifier}-target~=\"${name}\"]`;\n}\n","import { fillTemplate } from \"./announce\";\nimport { matchingPart } from \"./element_part\";\nimport { targetSelector } from \"./target_selector\";\n\n/**\n * Clones the first element of a `<template>`, and nothing else.\n *\n * A template is authored across lines, so its content holds whitespace text nodes\n * around that element — and a second element, where one is written. Cloning the\n * element on its own makes it the whole unit the caller appends, so the same node\n * a later `remove()` takes back is everything that went in, and the parent's child\n * list stays equal to its element list.\n *\n * `null` when the content has no element at all.\n */\nexport function cloneTemplateRoot(template: HTMLTemplateElement): HTMLElement | null {\n const root = template.content.firstElementChild;\n return root instanceof HTMLElement ? (root.cloneNode(true) as HTMLElement) : null;\n}\n\n/** What a consumer declares once about the rows it builds from a `<template>`. */\nexport interface TemplateRowOptions<R extends string, O extends string> {\n /** The controller identifier the row's parts are declared against. */\n readonly identifier: string;\n /** Target name the row itself carries. */\n readonly root: string;\n /** Target names the row must contain; the first one missing is the one reported. */\n readonly required: readonly R[];\n /** Target names the row may contain; a missing one resolves to `null`. */\n readonly optional?: readonly O[];\n /** Target name of the `<button>` whose authored `aria-label` names the row. */\n readonly button: string;\n /** What the widget did not do, e.g. `\"added no tag\"`. */\n readonly outcome: string;\n /** What the author wrote it in, e.g. `\"chip template\"`. */\n readonly noun: string;\n}\n\n/** One row: the element to append, the parts inside it, and its named button. */\nexport interface TemplateRowParts<R extends string, O extends string> {\n readonly root: HTMLElement;\n readonly slots: Readonly<Record<R, HTMLElement> & Record<O, HTMLElement | null>>;\n readonly button: HTMLButtonElement;\n}\n\n/**\n * Builds one row from an authored `<template>`, naming an unusable one once per connection.\n *\n * **The row is the template's only element, and it carries\n * {@link TemplateRowOptions.root} itself.** Cloning it alone ({@link cloneTemplateRoot})\n * makes what the caller appends exactly what a later `remove()` takes back; a row\n * wrapped in another element, or standing beside a second one, would leave that\n * other element behind on every removal — or never be rendered at all — so such a\n * template is refused rather than half-built.\n *\n * Parts resolve through the caller's own namespace, derived from the identifier\n * the controller is registered under, so a registration under any name reaches\n * the attributes that registration renders.\n *\n * A template that cannot produce a row yields `null` and changes nothing: what a\n * refused row means for the selection, the field, or the announcement stays with\n * the caller. The diagnostic names what is wrong — the element count, or the first\n * missing part — because the only other symptom is a widget that silently adds\n * nothing, and the causes a static check cannot see — a server-rendered template,\n * a name that renders empty from a missing translation — would have no diagnostic\n * anywhere. It is written once per connection, so one authoring mistake cannot\n * flood the console.\n *\n * @example\n * ```ts\n * readonly #rows = new TemplateRow({\n * identifier: this.identifier,\n * root: \"tag\",\n * required: [\"label\"],\n * button: \"remove\",\n * outcome: \"added no tag\",\n * noun: \"chip template\",\n * });\n *\n * connect(): void {\n * this.#rows.connect();\n * }\n * ```\n */\nexport class TemplateRow<R extends string, O extends string = never> {\n readonly #options: TemplateRowOptions<R, O>;\n #warned = false;\n\n constructor(options: TemplateRowOptions<R, O>) {\n this.#options = options;\n }\n\n /** The attribute selector for one declared part, in this controller's namespace. */\n selector(name: string): string {\n return targetSelector(this.#options.identifier, name);\n }\n\n /** Re-arms the once-per-connection diagnostic. */\n connect(): void {\n this.#warned = false;\n }\n\n /**\n * Names one missing part on the console, at most once per connection, and\n * returns `null` so a caller can hand it straight back.\n */\n report(missing: string): null {\n return this.#say(`lacks ${missing}`);\n }\n\n /** Writes one diagnostic per connection, saying what the template got wrong. */\n #say(problem: string): null {\n if (this.#warned) return null;\n this.#warned = true;\n const { identifier, outcome, noun } = this.#options;\n console.warn(`Stimeo UI: \"${identifier}\" ${outcome} because its ${noun} ${problem}.`);\n return null;\n }\n\n /**\n * Clones the row and resolves its parts, or names what the template got wrong\n * and returns `null`. `values` fills the button's authored `aria-label`.\n */\n instantiate(\n template: HTMLTemplateElement,\n values: Record<string, string | number>,\n ): TemplateRowParts<R, O> | null {\n const { root: rootName, required, optional, button: buttonName } = this.#options;\n const root = cloneTemplateRoot(template);\n if (!root?.matches(this.selector(rootName))) {\n return this.report(`${this.#article(rootName)} \"${rootName}\" root`);\n }\n // One element, and it is the row: anything beside it would be left behind by\n // a removal that takes the row back, which is the accumulation this contract\n // exists to stop. The row here is the one that was asked for, so the count is\n // what the diagnostic names — a missing part would point at the wrong element.\n const count = template.content.children.length;\n if (count !== 1) {\n return this.#say(`holds ${count} elements, and the row has to be its only one`);\n }\n // Required parts are resolved before they are written, so the declared shape\n // holds for every row returned at all — a missing one leaves through `report`\n // instead. The accumulator is keyed loosely because that ordering is what\n // makes the narrower return type true, and no index signature can say so.\n const slots: Record<string, HTMLElement | null> = {};\n for (const name of required) {\n const part = this.#resolve(root, name);\n if (!part) return this.report(`${this.#article(name)} \"${name}\" target`);\n slots[name] = part;\n }\n for (const name of optional ?? []) slots[name] = this.#resolve(root, name);\n const named = this.#resolve(root, buttonName);\n if (!(named instanceof HTMLButtonElement)) {\n return this.report(`${this.#article(buttonName)} \"${buttonName}\" target <button>`);\n }\n const button = named;\n const name = button.getAttribute(\"aria-label\")?.trim() ?? \"\";\n if (name === \"\") return this.report(`a non-empty aria-label on its \"${buttonName}\" target`);\n button.setAttribute(\"aria-label\", fillTemplate(name, values));\n return { root, slots, button } as TemplateRowParts<R, O>;\n }\n\n /** The row may be its own part; otherwise the first descendant carrying the target. */\n #resolve(root: HTMLElement, name: string): HTMLElement | null {\n return matchingPart(root, this.selector(name));\n }\n\n #article(name: string): string {\n return /^[aeiou]/i.test(name) ? \"an\" : \"a\";\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { actionSource } from \"../utils/action_source\";\nimport { announce, fillTemplate } from \"../utils/announce\";\nimport { ensureId } from \"../utils/aria_ids\";\nimport { hasModifierChord, isReservedArrowChord, logicalArrowKey } from \"../utils/arrow_step\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { setAttributeIfChanged } from \"../utils/attribute_write\";\nimport { ChipRow } from \"../utils/chip_row\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\nimport { matchingPart, readLabel, writeLabel } from \"../utils/element_part\";\nimport { commitField, writeFields } from \"../utils/field_mirror\";\nimport { ListenerSet } from \"../utils/listener_set\";\nimport { MorphRenderWatcher } from \"../utils/morph_render_watcher\";\nimport { MoveCounter } from \"../utils/move_counter\";\nimport { NUMBER_BOUNDS, type NumberValueConstraints } from \"../utils/number_bounds\";\nimport { NumberValueReader } from \"../utils/number_value\";\nimport { scrollOptionIntoView } from \"../utils/option_scroll\";\nimport type { StateReason } from \"../utils/state_reason\";\nimport { StateRegions } from \"../utils/state_regions\";\nimport { TabindexLoan } from \"../utils/tabindex_loan\";\nimport { targetSelector } from \"../utils/target_selector\";\nimport { TemplateRow } from \"../utils/template_row\";\n\n/**\n * Headless, accessible multi-select combobox with chips.\n *\n * Selection fields, chips and keyboard stops are settled before notification.\n * Confirmations compare with the last published selection; synchronous replacement\n * selections suppress the older notifications and announcements still pending.\n *\n * Markup contract (identifier: `stimeo--multi-select`):\n * <div data-controller=\"stimeo--multi-select\"\n * data-stimeo--multi-select-announce-text-value=\"{label} selected; {count} total\"\n * data-stimeo--multi-select-announce-removed-text-value=\"{label} removed; {count} total\">\n * <ul data-stimeo--multi-select-target=\"tags\" aria-label=\"Selected\"></ul>\n * <input type=\"text\" role=\"combobox\" aria-expanded=\"false\"\n * aria-autocomplete=\"list\" aria-controls=\"ms-list\"\n * data-stimeo--multi-select-target=\"input\"\n * data-action=\"input->stimeo--multi-select#filter\n * keydown->stimeo--multi-select#onKeydown\n * focus->stimeo--multi-select#open\" />\n * <ul id=\"ms-list\" role=\"listbox\" aria-multiselectable=\"true\" hidden\n * data-stimeo--multi-select-target=\"list\">\n * <li id=\"ms-opt-1\" role=\"option\" aria-selected=\"false\" data-value=\"apple\"\n * data-stimeo--multi-select-target=\"option\"\n * data-action=\"click->stimeo--multi-select#toggleOption\">Apple</li>\n * </ul>\n * <!-- Optional: the message shown while the open list has no match. -->\n * <p data-stimeo--multi-select-target=\"empty\" hidden>No fruits match</p>\n * <!-- Optional: submit the selection as name=\"fruits[]\" hidden inputs. -->\n * <div data-stimeo--multi-select-target=\"fields\"></div>\n * <template data-stimeo--multi-select-target=\"tagTemplate\">\n * <li data-stimeo--multi-select-target=\"tag\">\n * <span data-stimeo--multi-select-target=\"label\"></span>\n * <button type=\"button\" tabindex=\"-1\" aria-label=\"Remove {label}\"\n * data-stimeo--multi-select-target=\"remove\">×</button>\n * </li>\n * </template>\n * </div>\n *\n * Implements the WAI-ARIA APG **Combobox** pattern in its list-autocomplete,\n * multi-select form. Focus stays on the input; the active option is tracked with\n * `aria-activedescendant` and selection with `aria-selected`. Selected options are\n * mirrored as removable chips. For single selection use `stimeo--listbox` or\n * `stimeo--combobox`; for free-text tags use `stimeo--tags-input`.\n *\n * Behavior provided:\n * - Typing filters options by substring and opens the list; `ArrowDown`/`ArrowUp`\n * (wrapping), `Home`/`End` move the active option; `Enter` toggles it (the list\n * stays open); `Escape`/`Tab`/outside click close.\n * - Toggling syncs `aria-selected`, expands the author-localized remove-button\n * name from the chip template, adds/removes the chip, sends localized text to\n * the shared announcer, and dispatches\n * `stimeo--multi-select:change` with `values`; filtering dispatches\n * `stimeo--multi-select:filter` for async candidates. Option churn or a lowered\n * `max` that moves the selection without a user edit is reported as\n * `stimeo--multi-select:reconcile`, carrying the same `values` detail.\n * - The chips are one roving Tab stop: `ArrowLeft`/`ArrowRight` move between them,\n * `Delete`/`Backspace` remove the focused chip, and `Backspace` on an empty\n * input removes the last and keeps input focus; removal from a chip re-homes\n * focus to a neighbor or the input.\n * The current `tags` container defines horizontal direction for the chips and input boundary.\n * - An open list with nothing left to offer is reported on the root as\n * `data-stimeo--multi-select-empty`, and any declared `empty` region is shown\n * for exactly that state and hidden for its opposite, whatever the markup\n * authored: this controller owns the region's `hidden` and writes it at every\n * reflection of the state, including the one a region gets as it connects.\n * - `max` is a permanent selection invariant across initial markup, interaction,\n * runtime options, and runtime cap changes (`0` = unlimited).\n * - With a `fields` target the selected values are mirrored into named hidden\n * inputs (default name `options[]`), so the selection submits with a normal\n * form and no consumer JS — parity with `stimeo--tags-input`. An optional\n * `form` value sets the hidden inputs' `form` attribute, associating them with a\n * `<form>` by id even when the picker lives outside it. Without a `fields`\n * target the hidden inputs are simply not written. A selection the controller\n * changes — a user's choice or a `toggleOption()` call — emits a native bubbling\n * `change` from the container, the way a form control does, so\n * `stimeo--auto-submit` and form-level validation hear it; the rebuilds that\n * follow connect, a replacement container, option churn, or a `name` / `form`\n * change stay silent.\n * `change` dispatches `{ values: string[], reason: StateReason }`;\n * `reconcile` carries `{ values }`. `filter` dispatches `{ query: string }`.\n */\nexport class MultiSelectController extends Controller<HTMLElement> {\n /** Numeric read boundaries share one reader for this controller instance. */\n readonly #numbers = new NumberValueReader();\n\n /** Identifies the latest published state transition. */\n readonly #moves = new MoveCounter();\n\n static override targets = [\n \"input\",\n \"list\",\n \"option\",\n \"tags\",\n \"tag\",\n \"tagTemplate\",\n \"label\",\n \"remove\",\n \"fields\",\n \"empty\",\n ];\n static override values = {\n max: { type: Number, default: 0 },\n name: { type: String, default: \"options[]\" },\n form: { type: String, default: \"\" },\n announceText: { type: String, default: \"\" },\n announceRemovedText: { type: String, default: \"\" },\n };\n\n static valueConstraints = {\n max: NUMBER_BOUNDS.finite,\n } satisfies NumberValueConstraints<typeof MultiSelectController.values>;\n static actions = [\"close\", \"filter\", \"onKeydown\", \"open\", \"toggleOption\"] as const;\n static events = [\"change\", \"filter\", \"reconcile\"] as const;\n\n declare readonly inputTarget: HTMLInputElement;\n declare readonly inputTargets: HTMLInputElement[];\n declare readonly listTarget: HTMLElement;\n declare readonly listTargets: HTMLElement[];\n declare readonly optionTargets: HTMLElement[];\n declare readonly emptyTargets: HTMLElement[];\n declare readonly tagsTarget: HTMLElement;\n declare readonly tagTargets: HTMLElement[];\n declare readonly tagTemplateTarget: HTMLTemplateElement;\n declare readonly labelTargets: HTMLElement[];\n declare readonly removeTargets: HTMLButtonElement[];\n declare readonly fieldsTarget: HTMLElement;\n declare readonly hasListTarget: boolean;\n declare readonly hasInputTarget: boolean;\n declare readonly hasTagsTarget: boolean;\n declare readonly hasTagTemplateTarget: boolean;\n declare readonly hasFieldsTarget: boolean;\n\n declare maxValue: number;\n declare nameValue: string;\n declare formValue: string;\n declare readonly hasFormValue: boolean;\n declare announceTextValue: string;\n declare announceRemovedTextValue: string;\n\n /** Stable id of the active option; the current target is resolved from the DOM. */\n #activeOptionId: string | null = null;\n /** Whether the root borrowed a tab stop to catch focus, so teardown can undo it. */\n readonly #tabindex = new TabindexLoan(\"-1\", this.identifier);\n /** Last reconciled selection, used to distinguish state changes from derived-DOM repair. */\n #selectionValues: string[] = [];\n /** Whether initial normalization finished, so a fields callback cannot mirror stale state. */\n #connected = false;\n /** Owns `hidden` on the regions declared for the empty-result state. */\n readonly #emptyRegion = new StateRegions({ whenTrue: () => this.emptyTargets }, this.identifier);\n /** Borrows `hidden` on the list, to give back when an element stops being the list. */\n readonly #listHidden = new AttributeLease<HTMLElement>(\"hidden\", this.identifier);\n /** Borrows `aria-expanded` on the input, to give back when an element stops being the input. */\n readonly #expanded = new AttributeLease<HTMLElement>(\"aria-expanded\", this.identifier);\n /** Borrows `aria-activedescendant` on the input, for the same return. */\n readonly #activeDescendant = new AttributeLease<HTMLElement>(\n \"aria-activedescendant\",\n this.identifier,\n );\n /** Whether this widget holds the list open; a list that takes over is shown to match. */\n #open = false;\n /** The list the open state was last applied to; `null` once it stops being the list. */\n #openList: HTMLElement | null = null;\n /** Collapses one batch of target callbacks into a single final-DOM reconciliation. */\n readonly #reconcile = new MorphRenderWatcher(() => this.#reconcileOptions());\n /** Owns IME lifecycle state; confirmed text emits one filter result. */\n readonly #composition = new CompositionTracker({\n // Apply the confirmed query even in browsers that omit a final input event;\n // where one follows, the tracker folds it so consumers receive one filter\n // event for the confirmed text, not two.\n onEnd: () => this.filter(),\n });\n /** Builds one chip from the authored template and owns its diagnostic. */\n readonly #rows = new TemplateRow({\n identifier: this.identifier,\n root: \"tag\",\n required: [\"label\"],\n button: \"remove\",\n outcome: \"changed no selection\",\n noun: \"chip template\",\n });\n /** Shared delegated interaction for the replaceable row of removable chips. */\n readonly #chipRow = new ChipRow({\n getDirectionElement: () => this.#chipDirectionElement,\n getItems: () => this.tagTargets,\n getButton: (tag) =>\n matchingPart<HTMLButtonElement>(tag, `button${this.#rows.selector(\"remove\")}`),\n onRemove: (index) => this.#removeTagAt(index),\n focusAfterEnd: () => this.#focusInput(),\n });\n\n /** The listeners of one connection, released together on `disconnect()`. */\n readonly #listeners = new ListenerSet();\n\n /** Starts closed, syncs chips for any pre-selected options, and listens out. */\n override connect(): void {\n this.#tabindex.reclaim(this.element);\n this.#rows.connect();\n // A fresh connection has no prior selection to preserve: deterministic DOM\n // order decides which authored selections survive a finite max.\n this.#normalizeSelection([]);\n this.close();\n if (this.hasTagsTarget) {\n this.#chipRow.connect(this.tagsTarget);\n this.#rebuildTags();\n }\n this.#selectionValues = this.#values;\n // Seed the hidden fields from any pre-selected options so the form submits\n // the initial selection without an interaction.\n this.#syncFields();\n this.#listeners.add(document, \"click\", this.#onOutsideClick, { capture: true });\n this.#connected = true;\n this.#reconcile.observe(this.element);\n }\n\n /**\n * Derives the chips from the selected options, idempotently: a Turbo Drive cache\n * restore or morph can re-connect with chips already in the DOM, so they are\n * cleared before deriving afresh to avoid duplicates.\n */\n #rebuildTags(): void {\n if (!this.hasTagsTarget || !this.hasTagTemplateTarget) return;\n const chips: HTMLElement[] = [];\n for (const option of this.#selectedOptions) {\n const chip = this.#buildTag(option);\n if (!chip) return;\n chips.push(chip);\n }\n for (const tag of this.tagTargets) tag.remove();\n this.tagsTarget.append(...chips);\n this.#chipRow.ensureTabStop();\n }\n\n /** Tears down document and chip listeners on disconnect (Turbo included). */\n override disconnect(): void {\n this.#connected = false;\n this.#reconcile.disconnect();\n this.#composition.disconnect();\n this.#chipRow.disconnect();\n this.#listeners.dispose();\n this.#releaseTabindex();\n }\n\n /** Reconciles active state after an option target is added at runtime. */\n optionTargetConnected(): void {\n this.#scheduleOptionReconcile();\n }\n\n /** Cleans a removed target and reconciles active state against the surviving DOM. */\n optionTargetDisconnected(option: HTMLElement): void {\n // `#setActive` can only scan current targets; clean the old node explicitly in\n // case a Turbo morph reuses it elsewhere.\n option.removeAttribute(\"data-active\");\n this.#scheduleOptionReconcile();\n }\n\n /** Settles a region inserted after connect on the side of the current state. */\n emptyTargetConnected(): void {\n if (this.#connected) this.#reflectEmpty();\n }\n\n /** Rebinds delegated chip interaction when Turbo replaces the tags container. */\n tagsTargetConnected(tags: HTMLElement): void {\n this.#chipRow.connect(tags);\n this.#scheduleOptionReconcile();\n }\n\n /** Releases only the row that actually disconnected, never a newer replacement. */\n tagsTargetDisconnected(tags: HTMLElement): void {\n this.#chipRow.disconnect(tags);\n this.#scheduleOptionReconcile();\n }\n\n /** Seeds a fields target inserted after connect from the current selection. */\n fieldsTargetConnected(): void {\n if (this.#connected) this.#syncFields();\n }\n\n /** Seeds the fields target that stays when an earlier one leaves, in the next reconcile. */\n fieldsTargetDisconnected(): void {\n this.#scheduleOptionReconcile();\n }\n\n /** Brings the list that is first to the open state, then reconciles options. */\n listTargetConnected(_list: HTMLElement): void {\n if (!this.#connected) return;\n this.#reconcileOpenState();\n this.#scheduleOptionReconcile();\n }\n\n /**\n * Gives a list that no longer resolves as one back its `hidden` — after `disconnect()`\n * too, since dropping the identifier leaves the element on the page — and, while\n * connected, brings the list that stays to the open state. A departing list the state\n * was applied to, found hidden while open, was closed by the page; that is read before\n * its own `hidden` comes back.\n */\n listTargetDisconnected(list: HTMLElement): void {\n if (!this.listTargets.includes(list)) {\n if (list === this.#openList) {\n this.#adoptPageClose();\n this.#openList = null;\n }\n this.#listHidden.return(list);\n }\n if (!this.#connected) return;\n this.#reconcileOpenState();\n this.#scheduleOptionReconcile();\n }\n\n /** Reconciles a runtime max change, including dropping any newly invalid overflow. */\n maxValueChanged(): void {\n this.#scheduleOptionReconcile();\n }\n\n /** Rebuilds submitted fields when their public name changes at runtime. */\n nameValueChanged(): void {\n this.#scheduleOptionReconcile();\n }\n\n /** Rebuilds submitted fields when their associated form changes at runtime. */\n formValueChanged(): void {\n this.#scheduleOptionReconcile();\n }\n\n /** Schedules one reconciliation after all callbacks in the mutation batch. */\n #scheduleOptionReconcile(): void {\n this.#reconcile.schedule();\n }\n\n /**\n * Keeps a surviving/same-id active target, otherwise falls back to the first\n * visible one — and brings the derived state back in line with the new option set.\n *\n * The baseline pass fills in any missing `aria-selected`, and the chips and\n * hidden fields are re-derived from it, because the options are the truth source\n * for the selection. The chips are rebuilt **only when the selected value set\n * actually moved**: the rebuild removes and recreates every chip, so running it\n * for an unrelated option would drop focus from a chip's remove button to\n * `<body>`, losing the keyboard user's place for something that did not concern\n * them.\n *\n * @stimeoRenderRoot\n */\n #reconcileOptions(): void {\n const visible = this.#visibleOptions;\n const active = this.#activeOption;\n const next = this.#isClosed ? null : active && !active.hidden ? active : (visible[0] ?? null);\n this.#setActive(next);\n this.#reflectEmpty();\n\n const previous = this.#selectionValues;\n const previousLabels = new Map(\n this.tagTargets.map((tag) => [\n tag.dataset.value ?? \"\",\n readLabel(matchingPart(tag, this.#rows.selector(\"label\"))),\n ]),\n );\n // Prefer the interaction order represented by live chips. A tags target can\n // be replaced with an empty container, so the last reconciled option set is\n // the fallback that prevents a derived-DOM repair from evicting user choices.\n const priority = [\n ...new Set([...this.tagTargets.map((tag) => tag.dataset.value ?? \"\"), ...previous]),\n ];\n this.#normalizeSelection(priority);\n const selected = this.#selectedOptions;\n // Compared as a set, not a sequence: the chips are in selection order while\n // the options are in DOM order, so an index-wise comparison reports a change\n // for every selection the user made out of DOM order and rebuilds forever.\n const nextValues = selected.map((option) => this.#optionValue(option)).sort();\n const tagValues = this.tagTargets.map((tag) => tag.dataset.value ?? \"\").sort();\n const unchanged =\n nextValues.length === tagValues.length &&\n nextValues.every((value, index) => value === tagValues[index]);\n if (unchanged) this.#refreshTagLabels(selected);\n else this.#rebuildTags();\n this.#syncFields();\n\n const values = this.#values;\n const changed = !this.#sameSelection(previous, values);\n this.#selectionValues = values;\n if (!changed) return;\n const token = this.#moves.record();\n\n const options = new Map(selected.map((option) => [this.#optionValue(option), option]));\n for (const value of previous) {\n if (!this.#moves.isLatest(token)) return;\n if (!values.includes(value)) {\n this.#announceTransition(false, previousLabels.get(value) || value, value, values.length);\n }\n }\n for (const value of values) {\n if (!this.#moves.isLatest(token)) return;\n if (previous.includes(value)) continue;\n // `values` is derived from `selected`, so this lookup is total.\n const option = options.get(value) as HTMLElement;\n this.#announceTransition(true, this.#optionLabel(option), value, values.length);\n }\n // Runtime option churn and the `max` cap move the selection by this\n // controller's rules, so the repair is reported apart from `change`, which\n // stays reserved for the user's own add and remove.\n if (!this.#moves.isLatest(token)) return;\n this.dispatch(\"reconcile\", { detail: { values } });\n }\n\n /**\n * Gives every option an explicit `aria-selected` and enforces the current cap.\n * Priority preserves existing chip order at runtime; a fresh connection passes\n * no priority, so deterministic option DOM order chooses the initial survivors.\n */\n #normalizeSelection(priority: readonly string[]): void {\n const selected = this.optionTargets.filter(\n (option) => option.getAttribute(\"aria-selected\") === \"true\",\n );\n const limit = this.#selectionLimit;\n const kept = new Set<HTMLElement>();\n\n if (limit === 0) {\n for (const option of selected) kept.add(option);\n } else {\n for (const value of priority) {\n if (kept.size >= limit) break;\n const option = selected.find(\n (candidate) => !kept.has(candidate) && this.#optionValue(candidate) === value,\n );\n if (option) kept.add(option);\n }\n for (const option of selected) {\n if (kept.size >= limit) break;\n kept.add(option);\n }\n }\n\n for (const option of this.optionTargets) {\n option.setAttribute(\"aria-selected\", String(kept.has(option)));\n }\n }\n\n /**\n * Tracks an input added initially or after connect, and makes it describe the\n * widget that is actually on screen: a swapped-in input arrives with the\n * authored ARIA of a fresh node while this controller still holds the popup\n * state, and the open path cannot repair that (it seeds an active option only\n * when there is none), so a live list would go unannounced.\n */\n inputTargetConnected(input: HTMLInputElement): void {\n this.#composition.observe(input);\n this.#describeInput(input);\n }\n\n /**\n * Removes the departing input's composition listeners and gives an input that no\n * longer resolves as one back its `aria-expanded` and `aria-activedescendant`, after\n * `disconnect()` too. While connected, it describes the widget to the input that\n * stays, which the popup state may have moved past while both were present.\n */\n inputTargetDisconnected(input: HTMLInputElement): void {\n this.#composition.unobserve(input);\n if (!this.inputTargets.includes(input)) {\n this.#expanded.return(input);\n this.#activeDescendant.return(input);\n }\n if (this.#connected && this.hasInputTarget) this.#describeInput(this.inputTarget);\n }\n\n /** Writes the popup state and the active option onto `input`. */\n #describeInput(input: HTMLInputElement): void {\n this.#expanded.write(input, String(!this.#isClosed));\n const active = this.#activeOption;\n this.#activeDescendant.write(input, active ? ensureId(active, \"stimeo-ms-opt\") : null);\n }\n\n /**\n * Brings the list and the input that are first to one open state. A list that takes\n * over from the one the state was applied to is shown or hidden to match it; the list\n * it was applied to, found hidden while open, was closed by the page. The input's\n * `aria-expanded` then follows the list. With no list left, nothing is written.\n */\n #reconcileOpenState(): void {\n if (!this.hasListTarget) return;\n this.#adoptPageClose();\n const list = this.listTarget;\n if (list !== this.#openList) {\n this.#showList(list, this.#open);\n this.#openList = list;\n }\n if (this.hasInputTarget) this.#expanded.write(this.inputTarget, String(!list.hidden));\n }\n\n /** Treats the widget as closed when the list the open state was applied to is hidden. */\n #adoptPageClose(): void {\n if (this.#openList?.hidden) this.#open = false;\n }\n\n /** Filters confirmed input text, opens, and re-seeds the active option. */\n filter(event?: InputEvent): void {\n if (!this.hasInputTarget) return;\n if (event && this.#composition.consumesConfirmedInput(event)) return;\n if (this.#composition.isComposing(event)) return;\n const query = this.inputTarget.value.trim().toLowerCase();\n for (const option of this.optionTargets) {\n const label = (option.textContent ?? \"\").trim().toLowerCase();\n option.hidden = query !== \"\" && !label.includes(query);\n }\n this.open();\n const visible = this.#visibleOptions;\n this.#setActive(visible[0] ?? null);\n this.dispatch(\"filter\", { detail: { query } });\n }\n\n /**\n * Opens the list and activates the first visible option when none is active.\n *\n * Needs the input, which owns `aria-expanded` and `aria-activedescendant`: a\n * list shown without one is a popup no assistive technology is told about. So\n * opening is skipped entirely, where {@link MultiSelectController.close | close}\n * still closes.\n */\n open(): void {\n if (!this.hasListTarget || !this.hasInputTarget) {\n this.#reflectEmpty();\n return;\n }\n this.#showList(this.listTarget, true);\n this.#open = true;\n this.#openList = this.listTarget;\n this.#expanded.write(this.inputTarget, \"true\");\n if (!this.#activeOption) this.#setActive(this.#visibleOptions[0] ?? null);\n this.#reflectEmpty();\n }\n\n /**\n * Closes the list and clears the active option.\n *\n * Survives a missing input in both directions. `connect()` calls this before it\n * builds the chips, so dereferencing the input here would throw before the chips,\n * the roving seed, the chip listeners, the hidden fields and the outside-click\n * listener — and Stimulus keeps the controller alive after that throw, so none of\n * them would ever run and the selection would silently stop submitting. An input\n * removed while the list is open must still let it come down *and* forget its\n * active option, so only the `aria-expanded` write is guarded.\n */\n close(): void {\n this.#open = false;\n if (this.hasListTarget) {\n this.#showList(this.listTarget, false);\n this.#openList = this.listTarget;\n }\n this.#setActive(null);\n if (this.hasInputTarget) this.#expanded.write(this.inputTarget, \"false\");\n this.#reflectEmpty();\n }\n\n /** Routes input keyboard interaction per the multi-select combobox model. */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key must not ALSO open the\n // list or move the active option — composition depends on this yield.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n if ((event.key === \"Home\" || event.key === \"End\") && hasModifierChord(event)) return;\n if (!this.hasInputTarget) return;\n // Ignore keys fired during IME composition: the `Enter` that confirms a\n // candidate (and arrows that move within it) must not select an option or\n // navigate the chip list. Controller-owned lifecycle state covers confirming\n // events that omit the standard per-event signal.\n if (this.#composition.isComposing(event)) return;\n // Target callbacks are MutationObserver-driven. Resolve a replacement now, or\n // clear a removed id now, so a synchronously dispatched key cannot commit a\n // detached node before the callback gets its turn.\n this.#reconcileActiveForInteraction();\n // The tags container defines the same logical boundary as its chip buttons.\n switch (logicalArrowKey(event.key, this.#chipDirectionElement)) {\n case \"ArrowDown\":\n event.preventDefault();\n if (this.#isClosed) this.open();\n else this.#moveActive(1);\n break;\n case \"ArrowUp\":\n event.preventDefault();\n if (this.#isClosed) this.open();\n else this.#moveActive(-1);\n break;\n case \"Home\":\n if (!this.#isClosed) {\n event.preventDefault();\n this.#setActive(this.#visibleOptions[0] ?? null);\n }\n break;\n case \"End\": {\n if (!this.#isClosed) {\n event.preventDefault();\n const visible = this.#visibleOptions;\n this.#setActive(visible[visible.length - 1] ?? null);\n }\n break;\n }\n case \"Enter\": {\n const active = this.#activeOption;\n if (!this.#isClosed && active) {\n event.preventDefault();\n this.#toggleSelection(active);\n }\n break;\n }\n case \"Escape\":\n // A press an inner handler already owned is yielded at the top of this\n // handler. Escape is consumed only while the list is open: with it closed\n // the press stays free for the shared resolver, so an enclosing dialog\n // still closes from a focused input.\n if (this.#isClosed) break;\n event.preventDefault();\n this.close();\n break;\n case \"Backspace\":\n if (this.inputTarget.value === \"\") {\n const last = this.#chipRow.lastIndex;\n if (last >= 0) {\n event.preventDefault();\n this.#removeTagAt(last, \"input\");\n }\n }\n break;\n case \"ArrowLeft\":\n if (this.inputTarget.value === \"\" && this.#chipRow.length > 0) {\n event.preventDefault();\n this.#chipRow.focusLast();\n }\n break;\n case \"Tab\":\n this.close();\n break;\n default:\n break;\n }\n }\n\n /**\n * Toggles an owned option or descendant. For action events, focus is\n * re-homed to the input afterwards: options are non-focusable, so the click blurs\n * the input to `body` — and with the list deliberately staying open, every\n * keyboard affordance (Escape, arrows, typing) is bound to the input and would\n * otherwise go dead until the user clicks back in (\"focus stays on the input\").\n */\n toggleOption(source: Event | HTMLElement): void {\n const { event, host, origin, reason } = actionSource(source);\n if (origin && origin.closest(`[data-controller~=\"${this.identifier}\"]`) !== this.element)\n return;\n const option = host?.closest<HTMLElement>(targetSelector(this.identifier, \"option\"));\n if (!option || !this.optionTargets.includes(option)) return;\n const focus = event !== null || this.element.contains(document.activeElement);\n if (!this.#toggleSelection(option, reason)) return;\n if (focus && (event !== null || this.element.contains(document.activeElement)))\n this.#focusInput();\n }\n\n /** Current tags container, or the root while the target is absent. */\n get #chipDirectionElement(): HTMLElement {\n return this.hasTagsTarget ? this.tagsTarget : this.element;\n }\n\n /**\n * Re-homes focus to the input, or leaves it where it is when there is none.\n *\n * All three callers run *after* an option or a chip already took focus, and all\n * three are reachable without an input — options and chips carry their own\n * `data-action`. Throwing here would leave the chip removed but focus stranded\n * on a detached button.\n */\n #focusInput(): void {\n if (this.hasInputTarget) this.inputTarget.focus();\n }\n\n /**\n * Re-homes focus after the last chip was removed: to the input, else the root.\n *\n * Unlike the other {@link #focusInput} callers, the element that held focus has\n * just left the DOM, so \"leave it alone\" is not an option — the browser already\n * dropped it to `<body>`. The root borrows a `tabindex=\"-1\"` just-in-time (not a\n * Tab stop, returned on teardown or reclaimed on restoration). Focus that landed\n * on a real element is left alone, so a chip removed out of band never steals it.\n */\n #focusAfterLastTag(): void {\n if (this.hasInputTarget) {\n this.inputTarget.focus();\n return;\n }\n const doc = this.element.ownerDocument;\n const active = doc.activeElement;\n // Anything else still holding focus keeps it; only `<body>`, the root element\n // and a detached node mean the browser had nowhere to put it.\n if (active && active !== doc.body && active !== doc.documentElement && active.isConnected) {\n return;\n }\n this.#tabindex.lend(this.element);\n this.element.focus();\n }\n\n /**\n * Returns the borrowed tab stop. Owning the borrow is not enough — the value\n * has to still be the one this instance wrote, since a consumer that changed it\n * afterwards owns it now.\n */\n #releaseTabindex(): void {\n this.#tabindex.returnAll();\n }\n\n /** Moves the active option by `delta` among visible options, wrapping. */\n #moveActive(delta: number): void {\n const visible = this.#visibleOptions;\n const active = this.#activeOption;\n // `null` is the deliberate \"not found\" sentinel; Array#indexOf accepts it\n // at runtime and returns -1, although this array's static item type excludes it.\n const current = visible.indexOf(active as HTMLElement);\n const candidate = current === -1 ? (delta > 0 ? 0 : visible.length - 1) : current + delta;\n const next = (candidate + visible.length) % visible.length;\n this.#setActive(visible[next] ?? null);\n }\n\n /** Selects/deselects `option`, honoring `max`, and syncs chip + announcement. */\n #toggleSelection(option: HTMLElement, reason: StateReason = \"user\"): boolean {\n const selected = option.getAttribute(\"aria-selected\") === \"true\";\n const limit = this.#selectionLimit;\n if (!selected && limit > 0 && this.#selectedOptions.length >= limit) {\n return true;\n }\n if (selected) {\n option.setAttribute(\"aria-selected\", \"false\");\n this.#removeTagFor(option);\n } else {\n // Chips are a display affordance here, not the value model: the selection\n // lives on `aria-selected` and the hidden fields, so a field authored\n // without a chip template still selects. An authored template that cannot\n // be completed is the opposite case — leaving a selection whose chip is\n // missing would be the half-applied state, so that one aborts instead.\n if (this.hasTagTemplateTarget && !this.#appendTag(option)) return true;\n option.setAttribute(\"aria-selected\", \"true\");\n }\n this.#refreshRoving();\n return this.#publishSelection(\n !selected,\n this.#optionLabel(option),\n this.#optionValue(option),\n reason,\n );\n }\n\n /**\n * Re-reads each chip's label from its option, in place.\n *\n * The value order alone does not say the chips are still correct: a server can\n * re-render the same candidate with a new label (\"Apple\" → \"Green Apple\"), and\n * the chip text and its `Remove {label}` name are both derived from the option.\n * Updating them here keeps the rebuild — which would drop focus — for the case\n * that actually needs it, a changed selection.\n */\n #refreshTagLabels(selected: readonly HTMLElement[]): void {\n // Paired by value rather than by position: the chips are in selection order\n // and the options in DOM order, so the two lists hold the same values in\n // different places and an index-wise pairing would relabel the wrong chip.\n const options = new Map(selected.map((option) => [this.#optionValue(option), option]));\n for (const tag of this.tagTargets) {\n // The caller established equal selected/tag value sets before refreshing.\n const option = options.get(tag.dataset.value ?? \"\") as HTMLElement;\n const text = this.#optionLabel(option);\n const label = matchingPart(tag, this.#rows.selector(\"label\"));\n const button = matchingPart<HTMLButtonElement>(tag, `button${this.#rows.selector(\"remove\")}`);\n const name = this.#removeName(text, this.#optionValue(option));\n // Relabelling is one transaction, like building the chip is. Writing the\n // visible text without its accessible name would leave the button naming\n // a value the chip no longer shows, so a name this template cannot produce\n // holds the old text in place too.\n if (!label || !button || !name) continue;\n if (readLabel(label) !== text) writeLabel(label, text);\n setAttributeIfChanged(button, \"aria-label\", name);\n }\n }\n\n /** Builds one chip from the template for `option`. */\n #appendTag(option: HTMLElement): boolean {\n if (!this.hasTagsTarget) {\n this.#rows.report('a \"tags\" target to append the chip to');\n return false;\n }\n const chip = this.#buildTag(option);\n if (!chip) return false;\n this.tagsTarget.appendChild(chip);\n return true;\n }\n\n /**\n * Builds one fully named chip without mutating the live tag row, or `null`\n * when the authored template cannot produce one — in which case the selection\n * stays untouched and the row names the missing part once per connection.\n * Both callers establish the template first: a field authored without\n * `tagTemplate` renders no chips at all — a supported configuration — and\n * never reaches here.\n */\n #buildTag(option: HTMLElement): HTMLElement | null {\n const text = this.#optionLabel(option);\n const value = this.#optionValue(option);\n const row = this.#rows.instantiate(this.tagTemplateTarget, { label: text, value });\n if (!row) return null;\n row.root.dataset.value = value;\n writeLabel(row.slots.label, text);\n // Chip buttons are a single Tab stop the roving helper hands out.\n row.button.tabIndex = -1;\n return row.root;\n }\n\n /** Expands the current template's localized remove-button name. */\n #removeName(label: string, value: string): string | null {\n if (!this.hasTagTemplateTarget) return null;\n const template = this.tagTemplateTarget.content\n .querySelector<HTMLButtonElement>(`button${this.#rows.selector(\"remove\")}`)\n ?.getAttribute(\"aria-label\")\n ?.trim();\n return template ? fillTemplate(template, { label, value }) : null;\n }\n\n /** Removes the chip mirroring `option`, if present. */\n #removeTagFor(option: HTMLElement): void {\n const value = this.#optionValue(option);\n const tag = this.tagTargets.find((candidate) => candidate.dataset.value === value);\n tag?.remove();\n }\n\n /** Removes chip `index` and deselects its option, re-homing focus. */\n #removeTagAt(index: number, focus: \"neighbor\" | \"input\" = \"neighbor\"): void {\n const tag = this.tagTargets[index];\n if (!tag) return;\n const value = tag.dataset.value ?? \"\";\n // Match by the option's stable value, which falls back to its label when no\n // data-value is present, so a label-keyed chip still finds its option.\n const option = this.optionTargets.find((candidate) => this.#optionValue(candidate) === value);\n if (option) option.setAttribute(\"aria-selected\", \"false\");\n tag.remove();\n // Prefer the option's display label for the announcement (e.g. \"Apple\"),\n // which can differ from its data-value (e.g. \"apple\").\n this.#refreshRoving();\n if (!this.#publishSelection(false, option ? this.#optionLabel(option) : value, value)) return;\n\n if (focus === \"input\") {\n this.#focusInput();\n return;\n }\n if (!this.#chipRow.focusAfterRemoval(index)) this.#focusAfterLastTag();\n }\n\n /**\n * Marks `option` active via `data-active` and the input's\n * `aria-activedescendant` (the attribute is removed, not emptied, when null).\n *\n * The state half runs even with no input, so a `close()` that cannot touch ARIA\n * still clears it: {@link MultiSelectController.open | open} seeds an active\n * option only when there is none, so a stale one makes the next open skip the\n * seeding and a replacement input gets no `aria-activedescendant` at all.\n */\n #setActive(option: HTMLElement | null): void {\n const activeId = option ? ensureId(option, \"stimeo-ms-opt\") : null;\n this.#activeOptionId = activeId;\n for (const candidate of this.optionTargets) {\n candidate.toggleAttribute(\"data-active\", candidate === option);\n }\n // Virtual focus never triggers the browser's native focus-scrolling, so a\n // scrollable list must follow the active option itself (list-only scroll).\n if (option && this.hasListTarget) scrollOptionIntoView(this.listTarget, option);\n if (this.hasInputTarget) this.#activeDescendant.write(this.inputTarget, activeId);\n }\n\n /** Repairs only active identity before a key; the fallback waits for the target callback. */\n #reconcileActiveForInteraction(): void {\n const activeId = this.#activeOptionId;\n if (activeId === null) return;\n const resolved = this.#activeOption;\n const active = resolved && !resolved.hidden ? resolved : null;\n const marked = this.optionTargets.filter((candidate) => candidate.hasAttribute(\"data-active\"));\n // The only caller returns before reaching here when the input is absent.\n const idref = this.inputTarget.getAttribute(\"aria-activedescendant\");\n if (!active || marked.length !== 1 || marked[0] !== active || idref !== activeId) {\n this.#setActive(active);\n }\n }\n\n /**\n * Reflects whether the open list currently has no visible option targets, on\n * the root's state attribute and on the regions declared for that state.\n */\n #reflectEmpty(): void {\n const empty = !this.#isClosed && this.#visibleOptions.length === 0;\n this.element.toggleAttribute(`data-${this.identifier}-empty`, empty);\n this.#emptyRegion.reflect(this.element, empty);\n }\n\n /**\n * Mirrors the selected values into named hidden inputs under the `fields`\n * target so the selection submits with a normal form (parity with tags-input).\n * No-ops without a `fields` target. When the\n * `form` value is set, each input gets a matching `form` attribute so the picker\n * can submit with a `<form>` it lives outside of.\n */\n #syncFields(): boolean {\n if (!this.hasFieldsTarget) return false;\n const options = { name: this.nameValue, form: this.formValue };\n return writeFields(this.fieldsTarget, this.#values, options);\n }\n\n /** Settles the selection before its field, announcement and custom reports. */\n #publishSelection(\n selected: boolean,\n label: string,\n value: string,\n reason: StateReason = \"user\",\n ): boolean {\n const values = this.#values;\n const changed = !this.#sameSelection(this.#selectionValues, values);\n const fieldChanged = this.#syncFields();\n this.#selectionValues = values;\n if (!changed) return true;\n const token = this.#moves.record();\n if (fieldChanged) commitField(this.fieldsTarget);\n if (!this.#moves.isLatest(token)) return false;\n this.#announceTransition(selected, label, value, values.length);\n if (!this.#moves.isLatest(token)) return false;\n this.dispatch(\"change\", { detail: { values, reason } });\n return this.#moves.isLatest(token);\n }\n\n /** Keeps exactly one chip remove button tabbable after the set changes. */\n #refreshRoving(): void {\n this.#chipRow.ensureTabStop();\n }\n\n /**\n * Sends one localized selection transition through the page's shared announcer.\n *\n * @stimeoRuntimeOnly The texts word the one announcement of this change.\n */\n #announceTransition(selected: boolean, label: string, value: string, count: number): void {\n const template = selected ? this.announceTextValue : this.announceRemovedTextValue;\n announce(fillTemplate(template, { label, value, count }));\n }\n\n /** Whether two arrays represent the same selection set, independent of DOM order. */\n #sameSelection(left: readonly string[], right: readonly string[]): boolean {\n if (left.length !== right.length) return false;\n const a = [...left].sort();\n const b = [...right].sort();\n return a.every((value, index) => value === b[index]);\n }\n\n /** Closes the list on a click outside the controller element. */\n readonly #onOutsideClick = (event: MouseEvent): void => {\n if (!this.#isClosed && !this.element.contains(event.target as Node)) this.close();\n };\n\n /** Trimmed visible label of an option. */\n #optionLabel(option: HTMLElement): string {\n return (option.textContent ?? \"\").trim();\n }\n\n /** An option's stable value: its `data-value`, else its display label. */\n #optionValue(option: HTMLElement): string {\n return option.dataset.value ?? this.#optionLabel(option);\n }\n\n /** Options not hidden by the current filter. */\n get #visibleOptions(): HTMLElement[] {\n return this.optionTargets.filter((option) => !option.hidden);\n }\n\n /** Current active target resolved by stable id, never a detached node reference. */\n get #activeOption(): HTMLElement | null {\n return this.optionTargets.find((option) => option.id === this.#activeOptionId) ?? null;\n }\n\n /** Options currently selected. */\n get #selectedOptions(): HTMLElement[] {\n return this.optionTargets.filter((option) => option.getAttribute(\"aria-selected\") === \"true\");\n }\n\n /** Selected values in option order. */\n get #values(): string[] {\n return this.#selectedOptions.map((option) => this.#optionValue(option));\n }\n\n /**\n * Normalized cardinality cap: zero and below are unlimited; a positive value floors,\n * never below 1.\n */\n get #selectionLimit(): number {\n if (this.#safeMax <= 0) return 0;\n return Math.max(1, Math.floor(this.#safeMax));\n }\n\n /** Shows or hides `list` through the lease, so a departed list gets its authored value back. */\n #showList(list: HTMLElement, open: boolean): void {\n this.#listHidden.write(list, open ? null : \"\");\n }\n\n /** Whether the list is currently hidden. */\n get #isClosed(): boolean {\n return !this.hasListTarget || this.listTarget.hidden !== false;\n }\n /** Current `max` declaration resolved against its numeric contract. */\n get #safeMax(): number {\n return this.#numbers.read(\n this,\n \"max\",\n this.maxValue,\n MultiSelectController.values.max.default,\n MultiSelectController.valueConstraints.max,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/state_reason.ts","../../src/utils/action_source.ts","../../src/utils/template.ts","../../src/utils/announce.ts","../../src/utils/shared_registry.ts","../../src/utils/aria_ids.ts","../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/utils/attribute_write.ts","../../src/utils/attribute_lease.ts","../../src/utils/element_part.ts","../../src/utils/roving_tabindex.ts","../../src/utils/chip_row.ts","../../src/utils/composition_tracker.ts","../../src/utils/field_mirror.ts","../../src/utils/listener_set.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/morph_render_watcher.ts","../../src/utils/move_counter.ts","../../src/utils/number_bounds.ts","../../src/utils/coerce.ts","../../src/utils/number_value.ts","../../src/utils/option_scroll.ts","../../src/utils/state_regions.ts","../../src/utils/focus_candidate.ts","../../src/utils/query_open_descendants.ts","../../src/utils/tabindex_loan.ts","../../src/utils/target_selector.ts","../../src/utils/template_row.ts","../../src/controllers/multi_select_controller.ts"],"names":["registry","entry","button","holdsFocus","above","name"],"mappings":";;AA0CA,IAAM,YAAA,uBAAmB,GAAA,CAAI,CAAC,QAAQ,OAAA,EAAS,SAAA,EAAW,UAAU,CAAC,CAAA;AAGrE,IAAM,cAAA,uBAAqB,GAAA,CAAI,CAAC,cAAc,YAAA,EAAc,cAAA,EAAgB,cAAc,CAAC,CAAA;AA0BpF,SAAS,eAAe,KAAA,EAA4D;AACzF,EAAA,IAAI,CAAC,OAAO,OAAO,KAAA;AACnB,EAAA,IAAI,YAAA,CAAa,GAAA,CAAI,KAAA,CAAM,IAAI,GAAG,OAAO,OAAA;AACzC,EAAA,IAAI,cAAA,CAAe,GAAA,CAAI,KAAA,CAAM,IAAI,GAAG,OAAO,SAAA;AAC3C,EAAA,OAAO,MAAA;AACT;;ACxDO,SAAS,aAAa,MAAA,EAA4C;AACvE,EAAA,IAAI,kBAAkB,WAAA,EAAa;AACjC,IAAA,OAAO,EAAE,OAAO,IAAA,EAAM,IAAA,EAAM,QAAQ,MAAA,EAAQ,MAAA,EAAQ,QAAQ,KAAA,EAAM;AAAA,EACpE;AACA,EAAA,MAAM,QAAQ,MAAA,IAAU,IAAA;AACxB,EAAA,O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CAAK,cAAc,MAAA,CAAO,CAAC,WAAW,MAAA,CAAO,YAAA,CAAa,eAAe,CAAA,KAAM,MAAM,CAAA;AAAA,EAC9F;AAAA,EAGA,IAAI,OAAA,GAAoB;AACtB,IAAA,OAAO,IAAA,CAAK,iBAAiB,GAAA,CAAI,CAAC,WAAW,IAAA,CAAK,YAAA,CAAa,MAAM,CAAC,CAAA;AAAA,EACxE;AAAA,EAMA,IAAI,eAAA,GAA0B;AAC5B,IAAA,IAAI,IAAA,CAAK,QAAA,IAAY,CAAA,EAAG,OAAO,CAAA;AAC/B,IAAA,OAAO,KAAK,GAAA,CAAI,CAAA,EAAG,KAAK,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAC,CAAA;AAAA,EAC9C;AAAA,EAGA,SAAA,CAAU,MAAmB,IAAA,EAAqB;AAChD,IAAA,IAAA,CAAK,WAAA,CAAY,KAAA,CAAM,IAAA,EAAM,IAAA,GAAO,OAAO,EAAE,CAAA;AAAA,EAC/C;AAAA,EAGA,IAAI,SAAA,GAAqB;AACvB,IAAA,OAAO,CAAC,IAAA,CAAK,aAAA,IAAiB,IAAA,CAAK,WAAW,MAAA,KAAW,KAAA;AAAA,EAC3D;AAAA,EAEA,IAAI,QAAA,GAAmB;AACrB,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,MACnB,IAAA;AAAA,MACA,KAAA;AAAA,MACA,IAAA,CAAK,QAAA;AAAA,MACL,sBAAA,CAAsB,OAAO,GAAA,CAAI,OAAA;AAAA,MACjC,uBAAsB,gBAAA,CAAiB;AAAA,KACzC;AAAA,EACF;AACF","file":"multi_select_controller.js","sourcesContent":["/**\n * Why a component's public state moved, carried as `detail.reason`\n * on the state event that reports the move.\n *\n * The attribute a component publishes (`aria-expanded`, `hidden`, `data-state`)\n * only says *what* the state is now. A subscriber that mirrors the state\n * elsewhere, or reports it, needs *why*: closing on `Escape` and closing because\n * the consumer called the action are the same attribute write and different\n * events to the page around it.\n *\n * `\"api\"` is the one every subscriber has to look at. A close the consumer asked\n * for arrives back at their own listener, so a listener that closes something\n * else on `close` loops unless it ignores its own calls.\n *\n * | Reason | The state moved because |\n * | --- | --- |\n * | `\"user\"` | a control of this component was operated |\n * | `\"select\"` | an item inside it was activated |\n * | `\"escape\"` | `Escape` was pressed and this layer owned it |\n * | `\"outside\"` | a pointer landed outside it, or on its backdrop |\n * | `\"focus\"` | focus entered or left it |\n * | `\"pointer\"` | the pointer entered or left it |\n * | `\"scroll\"` | a tracked scroll container scrolled |\n * | `\"api\"` | a public action was called with no DOM event |\n * | `\"timeout\"` | an automatic timer advanced or dismissed the state |\n * | `\"limit\"` | a capacity limit dismissed an item |\n * | `\"media\"` | an operating-system media preference changed |\n */\nexport type StateReason =\n | \"user\"\n | \"select\"\n | \"escape\"\n | \"outside\"\n | \"focus\"\n | \"pointer\"\n | \"scroll\"\n | \"api\"\n | \"timeout\"\n | \"limit\"\n | \"media\";\n\n/** Focus modality: the events a focus move delivers to an action. */\nconst FOCUS_EVENTS = new Set([\"blur\", \"focus\", \"focusin\", \"focusout\"]);\n\n/** Pointer modality: the crossing events an action is bound to for hover. */\nconst POINTER_EVENTS = new Set([\"mouseenter\", \"mouseleave\", \"pointerenter\", \"pointerleave\"]);\n\n/**\n * Reads the interaction behind a **public action** from the DOM event it was\n * handed.\n *\n * Stimulus always passes the event to an action it invoked from `data-action`,\n * and a consumer calling the method themselves passes nothing — which is what\n * separates `\"api\"` from the rest.\n *\n * Only an action entry may resolve a reason this way. Inside the component the\n * event type no longer identifies the interaction: one `click` is the trigger\n * being pressed, the page outside being pressed, and an item being activated,\n * and those paths pass their own reason instead.\n *\n * @param event - The event the action received, if any.\n * @returns `\"api\"` with no event, else the modality the event type names, else\n * `\"user\"`.\n *\n * @example\n * ```ts\n * toggle(event?: Event): void {\n * this.#apply(!this.#isOpen, stateReasonFor(event));\n * }\n * ```\n */\nexport function stateReasonFor(event?: Event | null): \"user\" | \"focus\" | \"pointer\" | \"api\" {\n if (!event) return \"api\";\n if (FOCUS_EVENTS.has(event.type)) return \"focus\";\n if (POINTER_EVENTS.has(event.type)) return \"pointer\";\n return \"user\";\n}\n","import { stateReasonFor } from \"./state_reason\";\n\n/** The DOM binding and origin of a public action, or its explicit API element. */\nexport interface ActionSource {\n readonly event: Event | null;\n readonly host: Element | null;\n readonly origin: Element | null;\n readonly reason: ReturnType<typeof stateReasonFor>;\n}\n\n/**\n * Normalizes an action's DOM event or explicit element without choosing an owned target.\n *\n * Event hosts and origins stay separate so consumers can yield to nested controls.\n * An explicit element supplies both, with no DOM event and an `\"api\"` reason.\n * Consumers resolve current targets and enforce their own scope and interaction rules.\n *\n * @param source - The DOM event, explicit element, or absent optional argument.\n * @returns The source elements, original event and public interaction reason.\n */\nexport function actionSource(source?: Event | HTMLElement): ActionSource {\n if (source instanceof HTMLElement) {\n return { event: null, host: source, origin: source, reason: \"api\" };\n }\n const event = source ?? null;\n return {\n event,\n host: event?.currentTarget instanceof Element ? event.currentTarget : null,\n origin: event?.target instanceof Element ? event.target : null,\n reason: stateReasonFor(event),\n };\n}\n","/**\n * Fills `{name}` placeholders in a localized template from the own entries of `values`.\n *\n * Announcement and value-text templates share this one substitution, so a consumer writes\n * `\"{percent}% complete\"` in one attribute and gets the same rules everywhere. A\n * placeholder with no matching entry is left as authored rather than blanked, which\n * keeps a typo visible instead of silently swallowing the word.\n * Every occurrence is filled in one pass. Inserted strings stay literal, including\n * replacement-pattern characters and text that resembles another placeholder.\n */\nexport function fillTemplate(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, name: string) => {\n const replacement = Object.hasOwn(values, name) ? values[name] : undefined;\n return replacement === undefined ? match : String(replacement);\n });\n}\n","export { fillTemplate } from \"./template\";\n\n/**\n * Sends one message to the page's shared `stimeo--announcer`.\n *\n * A message that has to reach assistive tech is not put into a live region created\n * or un-hidden along with it: a region only announces what changes *after* assistive\n * tech already knows about it, which such a region cannot satisfy. The announcer has\n * to be in the page before any message is handed to it — one sent while no announcer\n * is listening is not read — so state changes reach it as an event and it does the\n * reading.\n *\n * The event goes to `window` because the announcer is usually a sibling high in the\n * document rather than an ancestor of the component dispatching it.\n *\n * Wording comes from the consumer — this helper adds no text of its own — so an\n * empty message is silently dropped and nothing is announced.\n *\n * @example\n * ```ts\n * announce(this.announceTextValue, { assertive: false });\n * ```\n */\nexport function announce(message: string, options: { assertive?: boolean } = {}): void {\n const text = message.trim();\n if (text.length === 0) return;\n window.dispatchEvent(\n new CustomEvent(\"stimeo--announcer:announce\", {\n detail: { message: text, assertive: options.assertive === true },\n }),\n );\n}\n","/**\n * One registry per page for every copy of the library.\n *\n * Each `stimeo-ui/controllers/*` file, and each opt-in entry, is built on its own and carries\n * its own copy of every utility it uses, so a page that imports controllers one by one, or one\n * of them next to the barrel, evaluates a utility several times. A registry that coordinates\n * instances of different controllers — the stacks of leased values, the loans of a\n * `tabindex`, the Escape layers, the focus traps — must not be split by that: a dialog inside\n * a drawer, or a character counter and a form field on one input, coordinate whichever files\n * they came from. So such a registry lives once on `globalThis`, under a `Symbol.for` key the\n * copies agree on, and the first copy to ask for it creates it.\n *\n * The key names the registry and the version of its shape\n * (`stimeo-ui.<utility>.registry.v<n>`). Copies whose registries have the same shape share\n * one; a release that changes the shape changes the version, so a copy of another release\n * keeps a registry of its own instead of reading entries it does not understand — the two\n * then coordinate within each release only. An entry another copy put in a registry is read\n * through its fields alone, never through `#private` members, which belong to the class of\n * the copy that created it.\n */\n\n/**\n * The registry stored under `key`, created by `create` on first use.\n *\n * @param key - `stimeo-ui.<utility>.registry.v<n>`: the version is that of the shape `create`\n * returns.\n * @param create - Builds the empty registry.\n */\nexport function sharedRegistry<T extends object>(key: string, create: () => T): T {\n const symbol = Symbol.for(key);\n const scope = globalThis as unknown as Record<symbol, T | undefined>;\n const existing = scope[symbol];\n if (existing !== undefined) return existing;\n const registry = create();\n Object.defineProperty(globalThis, symbol, { value: registry });\n return registry;\n}\n","import { sharedRegistry } from \"./shared_registry\";\n\n/**\n * Minimal id primitives for wiring ARIA relationships.\n *\n * Accessible relationships such as `aria-describedby`, `aria-errormessage`,\n * `aria-labelledby`, and `aria-activedescendant` reference their targets by DOM\n * `id`. When a controller must establish such a relationship but the consumer's\n * markup left the target without an `id`, it needs to mint one that is stable for\n * the page's lifetime and guaranteed not to collide with another generated id.\n *\n * These helpers own *only* id generation/assignment. The linking policy (which\n * attribute, what order, when to add or remove it) stays in each controller —\n * this deliberately avoids a premature generic \"ARIA linker\" abstraction.\n */\n\n/**\n * Monotonic counter backing {@link uniqueId}, shared by every entry copy so generated\n * ids are distinct even before their elements enter the document.\n */\nconst ids = sharedRegistry(\"stimeo-ui.aria-ids.registry.v1\", () => ({ counter: 0 }));\n\n/**\n * Returns a unique, DOM-id-safe string of the form `` `${prefix}-${n}` `` where\n * `n` increases on each call.\n *\n * The counter alone guarantees uniqueness against other *generated* ids, but a\n * consumer-authored element could already own `` `${prefix}-${n}` ``. When a\n * `document` is available the candidate is therefore advanced until no element\n * with that id exists, so a generated id never collides with author markup\n * either — the minimal \"id registry\" guarantee these helpers exist to provide.\n *\n * @param prefix - Leading segment of the id (e.g. a controller's identifier).\n * Defaults to `\"stimeo\"`.\n */\nexport function uniqueId(prefix = \"stimeo\"): string {\n let candidate: string;\n do {\n ids.counter += 1;\n candidate = `${prefix}-${ids.counter}`;\n } while (typeof document !== \"undefined\" && document.getElementById(candidate) !== null);\n return candidate;\n}\n\n/**\n * Returns `element`'s existing `id`, or assigns it a freshly generated\n * {@link uniqueId} (with the given `prefix`) and returns that. Idempotent: an\n * element that already has an id keeps it, so consumer-authored ids are never\n * overwritten.\n *\n * @param element - The element to read or stamp an `id` onto.\n * @param prefix - Prefix forwarded to {@link uniqueId} when one must be generated.\n * @returns The element's id (existing or newly assigned).\n */\nexport function ensureId(element: Element, prefix = \"stimeo\"): string {\n if (element.id) return element.id;\n const id = uniqueId(prefix);\n element.id = id;\n return id;\n}\n","/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/**\n * The element whose writing direction orders a grid's columns: the nearest\n * `<table>` holding `grid` inside `root`, else `grid` itself. Table columns follow\n * the table's direction, so a direction declared only on a row group such as\n * `<tbody>` does not reorder them and must not reverse the arrows either.\n */\nexport function gridDirectionElement(grid: Element, root: Element): Element {\n const table = grid.closest(\"table\");\n return table !== null && root.contains(table) ? table : grid;\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — for example `Alt+Down`/`Alt+Up`, which the APG Combobox\n * pattern makes optional and `stimeo--combobox` implements.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n\n/**\n * True when a press carries Alt, Control, Meta, or Shift, regardless of its key.\n *\n * This predicate reports modifier presence only; key ownership stays with the\n * caller. Check the widget's implemented key/modifier bindings and their state\n * conditions before using this result to yield a chord. An unimplemented chord\n * must not fall through to the bare-key behavior.\n *\n * Dedicated bindings, such as a grid's Control+Home/End navigation, belong in\n * the caller. Unlike {@link isReservedArrowChord}, this function examines every\n * key and has no arrow-specific reservation or `allow` list.\n *\n * @example\n * ```ts\n * // A Home/End handler with no modifier bindings yields every modified press.\n * case \"Home\":\n * case \"End\":\n * if (hasModifierChord(event)) return;\n * ```\n */\nexport function hasModifierChord(event: KeyboardEvent): boolean {\n return event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;\n}\n","/**\n * Reflects a serialized attribute value only when the current value differs.\n *\n * A same-value `setAttribute` still queues a mutation record for every observer, so an\n * unchanged value writes nothing.\n *\n * @param element - The element whose attribute is reflected.\n * @param name - The attribute name, using the non-namespaced DOM API.\n * @param value - The serialized value, or null to remove the attribute.\n * @param beforeWrite - Called only for a change, before the DOM mutation, so the\n * caller can record ownership or identify its own observer records.\n * @returns Whether an attribute was written or removed.\n */\nexport function setAttributeIfChanged(\n element: Element,\n name: string,\n value: string | null,\n beforeWrite?: () => void,\n): boolean {\n if (element.getAttribute(name) === value) return false;\n beforeWrite?.();\n if (value === null) element.removeAttribute(name);\n else element.setAttribute(name, value);\n return true;\n}\n","import { setAttributeIfChanged } from \"./attribute_write\";\nimport { sharedRegistry } from \"./shared_registry\";\n\n/** What a lease's record says: the author's value, its last write, the leases beneath. */\ninterface AttributeLeaseRecord {\n readonly original: string | null;\n readonly written: string | null;\n /** Whether it hands back what the lease right beneath it wrote last. */\n readonly linked: boolean;\n /** The records of the other owners' leases beneath it, nearest first. */\n readonly beneath: readonly string[];\n}\n\n/** One lease's hold on one element's attribute, in the stack every lease of it shares. */\ninterface AttributeHold {\n /** The lease holding it; `null` for a hold read from a copy's record until its lease takes it. */\n lease: object | null;\n readonly record: string;\n written: string | null;\n /** What it hands back with nothing beneath it: the author's value. */\n readonly original: string | null;\n /** Whether it hands back what the hold beneath it wrote last instead. */\n linked: boolean;\n}\n\n/** The holds on each element by attribute, and every lease's record name by attribute. */\ninterface AttributeLeaseRegistry {\n readonly stacks: WeakMap<Element, Map<string, AttributeHold[]>>;\n readonly names: Map<string, Set<string>>;\n}\n\n/** Holds and record names coordinate across separately built package entries. */\nconst registry = sharedRegistry(\n \"stimeo-ui.attribute-lease.registry.v1\",\n (): AttributeLeaseRegistry => ({ stacks: new WeakMap(), names: new Map() }),\n);\n\n/** Whether a parsed record entry is an attribute value: a string, or `null` for absence. */\nfunction isAttributeValue(value: unknown): value is string | null {\n return value === null || typeof value === \"string\";\n}\n\n/**\n * Reads the record a lease left on `element`: the author's value, the value the lease wrote\n * last, whether it hands back the value beneath it (`false` before the names when it does not)\n * and the records beneath it. `undefined` when the record is missing or holds anything else.\n */\nfunction readLeaseRecord(element: Element, record: string): AttributeLeaseRecord | undefined {\n try {\n const parsed: unknown = JSON.parse(element.getAttribute(record) ?? \"null\");\n if (!Array.isArray(parsed)) return undefined;\n const [original, written, ...rest] = parsed as unknown[];\n const linked = rest[0] !== false;\n const beneath = linked ? rest : rest.slice(1);\n if (!beneath.every((under): under is string => typeof under === \"string\")) return undefined;\n return isAttributeValue(original) && isAttributeValue(written)\n ? { original, written, linked, beneath }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The element's stack, seeded from complete ownership records once. */\nfunction attributeStack(element: Element, attribute: string): AttributeHold[] {\n const byAttribute = registry.stacks.get(element) ?? new Map<string, AttributeHold[]>();\n registry.stacks.set(element, byAttribute);\n const known = byAttribute.get(attribute);\n if (known) return known;\n const found: (AttributeLeaseRecord & { readonly record: string })[] = [];\n for (const record of registry.names.get(attribute) ?? []) {\n const read = readLeaseRecord(element, record);\n if (read) found.push({ ...read, record });\n }\n const depth = ({ beneath }: (typeof found)[number]) =>\n beneath.filter((name) => found.some((other) => other.record === name)).length;\n const stack = found\n .sort((one, other) => depth(one) - depth(other))\n .map(({ record, written, original, linked }, index) => ({\n lease: null,\n record,\n written,\n original,\n linked: linked && index > 0,\n }));\n byAttribute.set(attribute, stack);\n return stack;\n}\n\n/** The lease's live hold or the unclaimed hold described by its owner's record. */\nfunction findHold(\n stack: readonly AttributeHold[],\n lease: object,\n record: string,\n): AttributeHold | undefined {\n return (\n stack.find((held) => held.lease === lease) ??\n stack.find((held) => held.lease === null && held.record === record)\n );\n}\n\n/**\n * Inspects a derived writer's continuation without acquiring or returning a hold.\n * A covered hold may update beneath its cover. Without a hold, the expected authored\n * value is compared with the original beneath any temporary cover. The original\n * distinguishes an absent attribute from an empty one.\n */\nexport function readAttributeLease(\n element: Element,\n attribute: string,\n owner: string,\n lease: object,\n expected: string | null,\n): { readonly allowed: boolean; readonly original: string | null } {\n const stack = attributeStack(element, attribute);\n const hold = findHold(stack, lease, `data-${owner}-${attribute}-lease`);\n const current = element.getAttribute(attribute);\n const covering = [...stack].reverse().find((other) => other.written === current);\n const original = (hold ?? covering)?.original;\n const authored = original === undefined ? current : original;\n return {\n original: authored,\n allowed: hold\n ? current === hold.written ||\n stack.slice(stack.indexOf(hold) + 1).some((above) => above.written === current)\n : authored === expected,\n };\n}\n\n/**\n * The value `element`'s author wrote for `attribute`, as the record a lease of any owner leaves\n * on the element carries it; `undefined` while no lease leaves one, as when nothing has moved\n * the attribute off the author's value. A field a reveal turned from `password` into `text`\n * still reads `\"password\"` here.\n */\nexport function leasedAuthorValue(element: Element, attribute: string): string | null | undefined {\n const suffix = `-${attribute}-lease`;\n for (const name of element.getAttributeNames()) {\n if (!name.startsWith(\"data-\") || !name.endsWith(suffix)) continue;\n const record = readLeaseRecord(element, name);\n if (record) return record.original;\n }\n return undefined;\n}\n\n/**\n * Temporarily controls one attribute across a changing set of elements.\n *\n * The first write remembers the authored value, including the distinction between\n * an absent attribute and an authored empty string. Returning a lease restores that\n * value only while the attribute still matches the controller's last write. If a\n * consumer changed it in the meantime, the consumer owns the new value and teardown\n * leaves it alone.\n *\n * A `null` write deliberately removes the attribute while retaining the lease. This\n * is useful for derived ARIA whose valid absence is itself controller state, such as\n * an unbounded `aria-valuemin` or a blank spinbutton's `aria-valuenow`.\n *\n * **Every lease of an attribute shares one stack of holds per element**, whatever its owner\n * and whichever file of the package constructed it (the stacks are one per page): the holds\n * sit in the order their leases first wrote the element, each with the value it wrote last.\n * The element's value is the highest hold's that carries it, and the page's when none does.\n * A write reaches the element unless a hold above the writer carries the element's value: the\n * top hold always shows its writes, a hold beneath it shows nothing while a hold above keeps\n * its value on the element, and once the page has put a value there that no hold carries, the\n * next write of any hold replaces it. A return gives a value back only from the hold the\n * element's value is: the value the hold beneath it wrote last, or the author's once nothing\n * is beneath it; any other return only leaves the stack, and the page's value stays. Holds\n * that wrote the same value are told apart by the stack, never by the value: the higher one\n * keeps it. A first write over a top hold whose value the page has replaced takes the\n * element's value as the author's. Two instances of one controller on one element — an\n * element outside their scope — stack the same way.\n *\n * A **base lease** (`{ base: true }`) holds the element's own state rather than a value over\n * it — a form field's ARIA on its control is one — so its first write goes to the bottom of\n * the stack, beneath the leases of other owners already there: a temporary value another\n * owner leased stays shown and returns to the base lease's latest value.\n *\n * **The stack travels with the element.** While a hold shows a value other than the author's,\n * lies on another hold or is covered by one, the element carries its owner's record\n * `data-<owner>-<attribute>-lease`: JSON of the author's value and the value the hold wrote\n * last (each a string, or `null` for an absent attribute), `false` where the hold hands back\n * the author's value rather than the latest value of the hold beneath it, and the records of\n * every hold beneath it, nearest first. Returning the last lease of an owner removes its\n * record. A copy of the element — a page Turbo restores from its cache is one — therefore\n * carries the stack, and the first lease to touch the copy reads it back under the record\n * names of the leases constructed so far, which include every lease that wrote a record the\n * cache holds, and orders the holds by the records each one lists beneath it. Each lease takes\n * the hold its owner's record describes over in place. Complete records for distinct owners\n * preserve their order across a copy. The records describe holds by owner, not by instance:\n * one owner holding the element more than once leaves only its topmost hold's record, which\n * the first of its leases to write or return on the copy takes. Lower holds of that owner and\n * their positions are absent; mutually listed owners cannot express their full live order.\n * A hold that showed the author's value alone carries no record and is taken by its first\n * write on the copy. Missing or unreadable records also leave their holds unknown, so copying\n * the DOM does not promise identical decisions for every live stack. Without a record it can\n * read, a new stack takes the current value as the author's. A Turbo morph removes records\n * absent from the server HTML; existing holds remain in memory until their leases return.\n *\n * The lease has no lifecycle of its own, so it never subscribes to document events,\n * and nothing rewinds a live page before Turbo caches it: `turbo:before-cache` also\n * fires on pages that stay.\n */\nexport class AttributeLease<T extends Element = Element> {\n readonly #attribute: string;\n readonly #record: string;\n readonly #base: boolean;\n readonly #preserveAuthor: boolean;\n readonly #held = new Set<T>();\n\n /**\n * @param attribute - The attribute whose temporary values this lease owns.\n * @param owner - Names the record on the element; the controller's identifier.\n * @param options - `base`: written beneath the other owners' leases;\n * `preserveAuthor`: a new base hold keeps a current value that no hold carries as authored.\n */\n constructor(\n attribute: string,\n owner: string,\n options: { readonly base?: boolean; readonly preserveAuthor?: boolean } = {},\n ) {\n this.#attribute = attribute;\n this.#record = `data-${owner}-${attribute}-lease`;\n this.#base = options.base === true;\n this.#preserveAuthor = options.preserveAuthor === true;\n const names = registry.names;\n names.set(attribute, (names.get(attribute) ?? new Set<string>()).add(this.#record));\n }\n\n /** Writes or removes the leased attribute while preserving its authored value. */\n write(element: T, value: string | null): void {\n const stack = attributeStack(element, this.#attribute);\n const hold = this.#take(stack) ?? this.#acquire(element, stack);\n this.#held.add(element);\n const shows = !this.#covered(element, stack, hold);\n hold.written = value;\n this.#mark(element, stack);\n if (shows) this.#reflect(element, value);\n }\n\n /**\n * Returns one lease, also on a restored copy, to the value the hold beneath it wrote last or\n * the author's, without overwriting a value a consumer wrote since. Says whether there was a\n * lease to return: a hold this lease has, or the hold a copy's record describes while no live\n * lease of the owner has taken it — a copy of a page an earlier connection wrote carries one.\n */\n return(element: T): boolean {\n const held = this.#held.delete(element);\n const known = registry.stacks.get(element)?.has(this.#attribute);\n const stack =\n held || known || element.hasAttribute(this.#record)\n ? attributeStack(element, this.#attribute)\n : [];\n const hold = this.#take(stack);\n if (!hold) return false;\n const carries = element.getAttribute(this.#attribute) === hold.written;\n const owns = carries && !this.#covered(element, stack, hold);\n const index = stack.indexOf(hold);\n stack.splice(index, 1);\n const above = stack[index];\n if (above) above.linked &&= hold.linked;\n this.#mark(element, stack);\n if (!owns) return true;\n const below = hold.linked ? stack[index - 1] : undefined;\n this.#reflect(element, below ? below.written : hold.original);\n return true;\n }\n\n /** Returns every lease it holds, with the same ownership check as {@link return}. */\n returnAll(): void {\n for (const element of Array.from(this.#held)) this.return(element);\n }\n\n /** Its hold in `stack`, taking over one read from its record. */\n #take(stack: AttributeHold[]): AttributeHold | undefined {\n const hold = findHold(stack, this, this.#record);\n if (hold) hold.lease = this;\n return hold;\n }\n\n /** A new hold: on top, over the top hold while the element shows it; a base one at the bottom. */\n #acquire(element: T, stack: AttributeHold[]): AttributeHold {\n const current = element.getAttribute(this.#attribute);\n const top = stack.at(-1);\n const bottom = stack[0];\n const over = top?.written === current ? top : undefined;\n const from = this.#base\n ? this.#preserveAuthor && !stack.some((held) => held.written === current)\n ? undefined\n : bottom\n : over;\n const hold: AttributeHold = {\n lease: this,\n record: this.#record,\n written: current,\n original: from ? from.original : current,\n linked: !this.#base && over !== undefined,\n };\n if (this.#base && bottom) {\n bottom.linked = true;\n stack.unshift(hold);\n } else stack.push(hold);\n return hold;\n }\n\n /** Whether a hold above `hold` carries the element's value, which is then that hold's. */\n #covered(element: T, stack: readonly AttributeHold[], hold: AttributeHold): boolean {\n const current = element.getAttribute(this.#attribute);\n return stack.slice(stack.indexOf(hold) + 1).some((above) => above.written === current);\n }\n\n /** Leaves each owner's record of its topmost hold, or none where nothing needs one. */\n #mark(element: T, stack: readonly AttributeHold[]): void {\n const records = new Map<string, string | null>([[this.#record, null]]);\n stack.forEach((hold, index) => {\n const names = stack.slice(0, index).map((under) => under.record);\n const beneath = [...new Set(names.reverse())].filter((name) => name !== hold.record);\n const marker = hold.linked || beneath.length === 0 ? [] : [false];\n records.set(\n hold.record,\n hold.written === hold.original && beneath.length === 0 && index === stack.length - 1\n ? null\n : JSON.stringify([hold.original, hold.written, ...marker, ...beneath]),\n );\n });\n for (const [name, recorded] of records) {\n setAttributeIfChanged(element, name, recorded);\n }\n }\n\n /** Reflects only a real value transition, avoiding self-triggered mutation work. */\n #reflect(element: T, value: string | null): void {\n setAttributeIfChanged(element, this.#attribute, value);\n }\n}\n","/**\n * The element a selector names within `root`, which may be `root` itself.\n *\n * A target declaration is a space-separated token list, so one element can name\n * several at once: a row built from a `<template>` is its own row target, its own\n * label, and its own button where the author writes it that way. `querySelector`\n * never returns its receiver, so resolving a part with it alone reaches nothing on\n * such a row and leaves it rendered but inert.\n *\n * The selector is composed by the caller, so a tag name written into it still\n * narrows the match — a row that is not a `<button>` does not answer for one.\n *\n * @example\n * ```ts\n * const button = matchingPart<HTMLButtonElement>(row, `button${selector(\"remove\")}`);\n * ```\n */\nexport function matchingPart<E extends HTMLElement = HTMLElement>(\n root: HTMLElement,\n selector: string,\n): E | null {\n return root.matches(selector) ? (root as unknown as E) : root.querySelector<E>(selector);\n}\n\n/**\n * Writes `text` as the label of `slot`, keeping the elements nested inside it.\n *\n * A row that names itself its own label holds the rest of the row inside the\n * element the text goes into — the remove button among them. Replacing the whole\n * subtree takes those with it and leaves a chip that is rendered but has nothing to\n * press, so only the slot's own text moves: the first text node carries the value\n * and the rest go, which puts the label where the template left room for it. A slot\n * holding nothing but text is written whole, which is the ordinary row.\n */\nexport function writeLabel(slot: HTMLElement, text: string): void {\n if (slot.childElementCount === 0) {\n slot.textContent = text;\n return;\n }\n let first: ChildNode | null = null;\n for (const node of Array.from(slot.childNodes)) {\n if (node.nodeType !== Node.TEXT_NODE) continue;\n if (first) node.remove();\n else first = node;\n }\n if (first) first.nodeValue = text;\n else slot.prepend(text);\n}\n\n/**\n * Reads back the label {@link writeLabel} wrote, without what sits beside it.\n *\n * The same row that holds the remove button inside its label slot returns that\n * button's glyph from `textContent`, which is enough to make a comparison\n * against the authored label never match — so every pass rewrites a label that\n * did not change — and to put the glyph into an announcement. Only the slot's\n * own text nodes carry the label, which on the ordinary row — a slot holding\n * nothing but text — is the whole of it.\n */\nexport function readLabel(slot: HTMLElement | null): string {\n if (!slot) return \"\";\n let text = \"\";\n for (const node of Array.from(slot.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) text += node.nodeValue ?? \"\";\n }\n return text.trim();\n}\n","/**\n * Low-level roving-tabindex primitive shared by composite-widget controllers.\n *\n * The APG roving-tabindex pattern keeps a composite widget a single Tab stop:\n * exactly one item is in the Tab sequence (`tabindex=\"0\"`) while the rest are\n * removed from it (`tabindex=\"-1\"`), and the arrow keys move both DOM focus and\n * that single tabbable position together. {@link RovingTabindex} owns *only* that\n * mechanical bookkeeping — \"which one item is tabbable, and move focus there\".\n *\n * It is intentionally **policy-free**. Orientation, wrapping vs. clamping,\n * selection-follows-focus, typeahead, and `Home`/`End` semantics differ per APG\n * pattern (Radio Group, Toolbar, Tabs, …); folding them into one helper would\n * flatten those widgets to a lowest common denominator and lose each pattern's\n * correctness. Those decisions therefore stay in each controller, which calls\n * {@link RovingTabindex.setActive} with an index it computed itself (optionally\n * via the pure {@link rovingMove} helper).\n *\n * @remarks\n * Items are read lazily through a getter so a controller can add or remove\n * targets (Stimulus re-scans the DOM) without re-wiring this helper. A caller\n * that already captured one event-scoped snapshot may pass it to\n * {@link RovingTabindex.setActive}, avoiding a second live-target scan while\n * preserving one coherent collection for the whole operation.\n */\nexport class RovingTabindex {\n /** Returns the current ordered item elements; called on every operation. */\n readonly #getItems: () => HTMLElement[];\n\n /**\n * @param getItems - Returns the current ordered item elements. Called on every\n * operation so the live target list is always used.\n */\n constructor(getItems: () => HTMLElement[]) {\n this.#getItems = getItems;\n }\n\n /** Index of the currently tabbable item (`tabindex=\"0\"`), or `-1` if none. */\n get activeIndex(): number {\n return this.#getItems().findIndex((item) => item.tabIndex === 0);\n }\n\n /**\n * Makes exactly the item at `index` tabbable (`tabindex=\"0\"`) and removes every\n * other item from the Tab sequence (`tabindex=\"-1\"`). An out-of-range `index`\n * (e.g. `-1`) leaves all items at `-1`, which a controller can use to express\n * \"nothing is currently tabbable\".\n *\n * @param index - Position of the item to make tabbable.\n * @param options - Pass `{ focus: true }` to also move DOM focus to that item,\n * and `items` to reuse an event-scoped collection snapshot.\n */\n setActive(\n index: number,\n options: { focus?: boolean; items?: readonly HTMLElement[] } = {},\n ): void {\n const { focus = false } = options;\n const items = options.items ?? this.#getItems();\n items.forEach((item, i) => {\n item.tabIndex = i === index ? 0 : -1;\n });\n if (focus) items[index]?.focus();\n }\n}\n\n/** Edge behavior for {@link rovingMove}: cycle past the ends, or stop at them. */\nexport type RovingWrap = \"wrap\" | \"clamp\";\n\n/**\n * Pure helper that resolves the target index for a one-step directional move.\n *\n * Keyboard/orientation mapping stays in the caller: it decides that a key means\n * `delta` `+1` (next) or `-1` (previous) and whether the widget should `\"wrap\"`\n * (Radio Group, Toolbar) or `\"clamp\"` at the ends.\n *\n * @param current - The index focus is moving from.\n * @param length - Number of items in the set.\n * @param delta - `+1` to move to the next item, `-1` for the previous.\n * @param wrap - `\"wrap\"` cycles around the ends; `\"clamp\"` stops at them.\n * @returns The resolved index, or `-1` when there are no items.\n */\nexport function rovingMove(\n current: number,\n length: number,\n delta: number,\n wrap: RovingWrap,\n): number {\n if (length === 0) return -1;\n const next = current + delta;\n if (wrap === \"wrap\") return (next + length) % length;\n return Math.min(length - 1, Math.max(0, next));\n}\n","import { isReservedArrowChord, logicalArrowKey } from \"./arrow_step\";\nimport { matchingPart } from \"./element_part\";\nimport { RovingTabindex } from \"./roving_tabindex\";\n\n/** Consumer-owned behavior that differs between removable-chip widgets. */\nexport interface ChipRowOptions {\n /** Returns the current container whose direction defines logical previous/next. */\n readonly getDirectionElement: () => HTMLElement;\n /** Returns the current chip elements in navigation order. */\n readonly getItems: () => readonly HTMLElement[];\n /** Resolves the one remove button owned by a chip. Defaults to its first button. */\n readonly getButton?: (item: HTMLElement) => HTMLButtonElement | null;\n /** Removes the chip currently occupying `index`. */\n readonly onRemove: (index: number) => void;\n /** Receives focus when navigation moves past the logical end of the row. */\n readonly focusAfterEnd: () => void;\n}\n\n/**\n * Delegated interaction and roving-tabindex mechanics for a row of removable chips.\n *\n * The selection model stays in the consuming controller: this helper knows only\n * how to resolve one consumer-declared remove button per chip, move between those\n * buttons, delegate click/delete requests by index, and bind those listeners to\n * a replaceable row target. Restricting the button set to the declared chip items\n * deliberately excludes sibling controls such as an authored \"Clear all\" button.\n */\nexport class ChipRow {\n readonly #getDirectionElement: () => HTMLElement;\n readonly #getItems: () => readonly HTMLElement[];\n readonly #getButton: (item: HTMLElement) => HTMLButtonElement | null;\n readonly #onRemove: (index: number) => void;\n readonly #focusAfterEnd: () => void;\n readonly #roving = new RovingTabindex(() => this.buttons);\n #container: HTMLElement | null = null;\n\n constructor(options: ChipRowOptions) {\n this.#getDirectionElement = options.getDirectionElement;\n this.#getItems = options.getItems;\n this.#getButton =\n options.getButton ?? ((item) => matchingPart<HTMLButtonElement>(item, \"button\"));\n this.#onRemove = options.onRemove;\n this.#focusAfterEnd = options.focusAfterEnd;\n }\n\n /**\n * Binds delegation to `container`; any row currently bound is released first.\n * Idempotent for the same node, so target callbacks may call it freely.\n */\n connect(container: HTMLElement): void {\n if (this.#container === container) return;\n this.disconnect();\n this.#container = container;\n container.addEventListener(\"click\", this.#onClick);\n container.addEventListener(\"keydown\", this.#onKeydown);\n }\n\n /**\n * Releases the current row. When `container` is supplied, a stale disconnect\n * callback cannot tear listeners off a newer replacement target.\n */\n disconnect(container?: HTMLElement): void {\n const current = this.#container;\n if (!current || (container !== undefined && current !== container)) return;\n current.removeEventListener(\"click\", this.#onClick);\n current.removeEventListener(\"keydown\", this.#onKeydown);\n this.#container = null;\n }\n\n /** Current remove buttons, at most one consumer-resolved button per chip item. */\n get buttons(): HTMLButtonElement[] {\n return this.#entries.map(({ button }) => button);\n }\n\n /** Number of currently navigable remove buttons. */\n get length(): number {\n return this.buttons.length;\n }\n\n /** Declared-item index of the last navigable chip, or `-1` for an empty row. */\n get lastIndex(): number {\n return this.#entries.at(-1)?.itemIndex ?? -1;\n }\n\n /** Keeps exactly one button tabbable, preferring the first authored Tab stop. */\n ensureTabStop(): void {\n const buttons = this.#entries.map(({ button }) => button);\n const active = buttons.findIndex((button) => button.tabIndex === 0);\n const count = buttons.filter((button) => button.tabIndex === 0).length;\n if (buttons.length > 0 && count !== 1) {\n this.#roving.setActive(active === -1 ? 0 : active, { items: buttons });\n }\n }\n\n /** Focuses the last chip, returning false for an empty row. */\n focusLast(): boolean {\n const buttons = this.#entries.map(({ button }) => button);\n const last = buttons.length - 1;\n if (last < 0) return false;\n this.#roving.setActive(last, { focus: true, items: buttons });\n return true;\n }\n\n /**\n * Focuses the chip that followed a removed index, or the new last chip.\n * Returns false when removal emptied the row so the consumer can rescue focus.\n */\n focusAfterRemoval(index: number): boolean {\n const entries = this.#entries;\n if (entries.length === 0) return false;\n const following = entries.findIndex((entry) => entry.itemIndex >= index);\n this.#roving.setActive(following === -1 ? entries.length - 1 : following, {\n focus: true,\n items: entries.map(({ button }) => button),\n });\n return true;\n }\n\n /** Current remove-button entries, retaining each button's declared item index. */\n get #entries(): Array<{ button: HTMLButtonElement; itemIndex: number }> {\n return this.#getItems().flatMap((item, itemIndex) => {\n const button = this.#getButton(item);\n return button ? [{ button, itemIndex }] : [];\n });\n }\n\n /** Resolves a delegated event to the remove button owned by a declared chip. */\n #entry(event: Event): {\n button: HTMLButtonElement;\n buttonIndex: number;\n buttons: HTMLButtonElement[];\n itemIndex: number;\n } | null {\n const target = event.target;\n if (!(target instanceof Element)) return null;\n const button = target.closest<HTMLButtonElement>(\"button\");\n const entries = this.#entries;\n const buttonIndex = entries.findIndex((entry) => entry.button === button);\n if (buttonIndex === -1) return null;\n const entry = entries[buttonIndex] as { button: HTMLButtonElement; itemIndex: number };\n return { ...entry, buttonIndex, buttons: entries.map(({ button }) => button) };\n }\n\n /** Delegates removal clicks without waiting for Stimulus to wire a new chip. */\n readonly #onClick = (event: MouseEvent): void => {\n const entry = this.#entry(event);\n if (!entry) return;\n this.#onRemove(entry.itemIndex);\n };\n\n /** Applies the shared logical-arrow and removal policy within the chip row. */\n readonly #onKeydown = (event: KeyboardEvent): void => {\n if (event.defaultPrevented || isReservedArrowChord(event)) return;\n const entry = this.#entry(event);\n if (!entry) return;\n const buttons = entry.buttons;\n const index = entry.buttonIndex;\n\n switch (logicalArrowKey(event.key, this.#getDirectionElement())) {\n case \"ArrowLeft\":\n if (index > 0) {\n event.preventDefault();\n this.#roving.setActive(index - 1, { focus: true, items: buttons });\n }\n break;\n case \"ArrowRight\":\n event.preventDefault();\n if (index < buttons.length - 1) {\n this.#roving.setActive(index + 1, { focus: true, items: buttons });\n } else {\n this.#focusAfterEnd();\n }\n break;\n case \"Delete\":\n case \"Backspace\":\n event.preventDefault();\n this.#onRemove(entry.itemIndex);\n break;\n default:\n break;\n }\n };\n}\n","/** Minimal event shape carrying the platform's per-event composition signal. */\nexport interface CompositionSignal {\n readonly isComposing?: boolean;\n}\n\n/** Minimal `input` shape needed to tell a composition echo from a fresh edit. */\nexport interface ConfirmedInputSignal {\n readonly target: EventTarget | null;\n readonly inputType?: string;\n}\n\n/**\n * The `inputType` values an engine reports on an `input` that belongs to a\n * composition rather than to an edit the user just made.\n */\nconst COMPOSITION_INPUT_TYPES = new Set([\n \"insertCompositionText\",\n \"insertFromComposition\",\n \"deleteCompositionText\",\n \"deleteByComposition\",\n]);\n\n/** Whether a platform input kind belongs to composition rather than ordinary editing. */\nexport function isCompositionInputType(inputType: string | undefined): boolean {\n return inputType !== undefined && COMPOSITION_INPUT_TYPES.has(inputType);\n}\n\n/** The cancelable notice Turbo dispatches before a morph writes one attribute. */\nconst BEFORE_MORPH_ATTRIBUTE = \"turbo:before-morph-attribute\";\n\n/** Hooks that keep component-specific work outside {@link CompositionTracker}. */\nexport interface CompositionTrackerOptions {\n /** Runs after lifecycle state is set for a `compositionstart` event. */\n readonly onStart?: (event: Event) => void;\n /** Runs after lifecycle state is cleared for a `compositionend` event. */\n readonly onEnd?: (event: Event) => void;\n /**\n * Runs once lifecycle state is cleared for a composition that ended without\n * `compositionend`, with the `element` it ran in. Nothing was confirmed: the\n * element holds what a write left (`inPlace` false), or still holds the text the\n * composition left, which the engine stopped composing (`inPlace` true) — text\n * typed against whatever the page declared while it ran.\n *\n * A hook applies the work the composition held back — and only that — at once,\n * keeping the caret where it was. The event that showed the end is then handled as\n * it would be with no composition: the text the element holds is read by whatever\n * reads it next, as the user's edit if an edit reads it. A consumer whose contract\n * judges what an interrupted conversion leaves may also settle that text here, as\n * `stimeo--otp` returns a residual its `pattern` rejects to the prior character: it reports\n * that as a reconciliation, never as the user's edit, and keeps the selection.\n *\n * When the tracker sees the end in an event it hears — a key, an edit, a focus\n * change, the next `compositionstart` — the hook runs there, in the capture phase,\n * ahead of that event's own handlers and of the edit it announces, whoever\n * dispatched it. When a question ({@link CompositionTracker.isComposing},\n * {@link CompositionTracker.composingElement}) or a Turbo morph's notice for one\n * attribute shows the end, the hook runs in a microtask after them, never inside\n * its caller or a half-applied morph, unless an event the tracker hears comes\n * first. On `compositionstart` it runs after the new composition is set and before\n * `onStart`: {@link CompositionTracker.isComposing} is true again, so work held for\n * the old composition stays held for the new.\n */\n readonly onAbandon?: (element: EventTarget, inPlace: boolean) => void;\n}\n\n/** One composition in progress. */\ninterface Composition {\n /** The observed target the composition was heard on. */\n readonly target: EventTarget;\n /** The element composing: the observed field itself, or a field inside an observed ancestor. */\n readonly element: EventTarget;\n /** The value the composition last left in the element; `undefined` for an element with none. */\n text: unknown;\n}\n\n/**\n * The element's live value; `undefined` for an element without one, which a write never\n * changes.\n */\nconst textOf = (element: EventTarget): unknown => (element as { value?: unknown }).value;\n\n/** Whether `element` is the focused element of the document or shadow root it is in. */\nconst holdsFocus = (element: EventTarget): boolean =>\n element instanceof Node &&\n (element.getRootNode() as Partial<DocumentOrShadowRoot>).activeElement === element;\n\n/**\n * Owns IME composition listeners and transient state for one or more event targets.\n *\n * Some browsers omit `KeyboardEvent.isComposing` on the keydown that confirms a\n * conversion. Tracking `compositionstart` through `compositionend` supplies the\n * missing lifecycle signal without relying on deprecated numeric key codes.\n * Component policy stays with the consumer: filtering, validation, and submission\n * belong in the optional {@link CompositionTrackerOptions.onEnd} callback.\n *\n * The tracker also owns the other half of that lifecycle: **the `input` some\n * engines send after `compositionend` to echo the text just confirmed.** A\n * consumer that ran `onEnd` and then handled the echo would commit the same\n * confirmation twice, so {@link CompositionTracker.consumesConfirmedInput} tells\n * the echo apart and the consumer returns early on it.\n *\n * **What the echo is not, is the harder half.** Not every engine sends one —\n * Chromium ends a confirmation at `compositionend` with no `input` after it — so\n * a window that waits for the echo and only closes on the next key would swallow\n * the first edit that arrives without one: dictation, autofill, a drop,\n * `insertText`. Two things keep that from happening. The window closes on the\n * next anything — a key, a new composition, any `input`, losing the field — and\n * an `input` that reports an `inputType` outside {@link COMPOSITION_INPUT_TYPES}\n * is an edit, so it is never folded. Only an engine that reports no `inputType`\n * at all is left relying on the window alone.\n *\n * **A composition can also end without `compositionend`.** Chromium drops the\n * conversion silently when something other than the IME writes a different value\n * into its field — a Turbo morph, a form reset, a script — and when the field\n * moves or leaves the page, leaving the text it composed. The tracker reads the end\n * from what the engine and the field still say:\n *\n * - **The field holds other text than the composition left.** The IME's edits, and\n * the user's own between them, arrive as an `input` the engine dispatched\n * (`isTrusted`) or one that reports the composition, and the tracker takes the\n * field's text from those. A write by anything else changes the text with no such\n * `input` — at most a synthetic one — so the composition is over, ended with\n * {@link CompositionTrackerOptions.onAbandon}, before anyone acts on the field.\n * Writing the same text keeps the conversion, and the match.\n * - **The engine edits outside a composition.** A `beforeinput` reporting\n * `isComposing: false` with an `inputType` outside {@link COMPOSITION_INPUT_TYPES}\n * is an edit the engine no longer counts as composition — unless the `keydown`\n * right before it reported `isComposing: true`: a key the IME lets through, such\n * as Backspace, edits the field while the conversion goes on. This is what shows\n * a composition that ended with its text in place. Only one field composes at a\n * time, so such an edit on any observed target ends the composition held, with\n * `onAbandon`. A `keydown` can hold this back but never starts it: the keydown\n * that confirms a conversion may carry no `isComposing`, and dictation and\n * autofill edit with no key at all.\n * - **The field stays where it was heard.** A field the consumer observes itself is\n * the consumer's to release when it moves or leaves, which reads what it holds;\n * one that keeps focus through the move keeps composing\n * ({@link CompositionTracker.disconnect}). A field inside an observed ancestor\n * that leaves the ancestor, or loses focus within its document, ends its\n * composition quietly; one that stays the document's active element — the window\n * lost focus — keeps composing.\n * - **No other field composes**: a `compositionstart` ends any composition the\n * tracker still holds, with `onAbandon`, before the new one starts.\n *\n * The tracker checks this before it answers {@link CompositionTracker.isComposing}\n * or {@link CompositionTracker.composingElement}, and at every key, edit, blur,\n * `compositionstart` and morph it hears — keys, edits and blurs in the capture\n * phase, ahead of the consumer's own handlers. While\n * a composition is live, a Turbo morph leaves its field's value alone: Idiomorph\n * asks through `turbo:before-morph-attribute` before it writes `value`, as an\n * attribute or as the live text, and the tracker cancels that one notice for the\n * element composing, so the morph keeps the conversion, as it keeps focus. Every\n * other attribute, and every other element, still morphs.\n *\n * A consumer that observes several fields tells the conversion's own events from\n * edits in the other fields with {@link CompositionTracker.owns}, which holds even\n * while the tracker keeps a composition whose end no event has shown yet.\n *\n * @example\n * ```ts\n * #composition = new CompositionTracker({ onEnd: () => this.filter() });\n *\n * connect(): void {\n * this.#composition.observe(this.inputTarget);\n * }\n *\n * disconnect(): void {\n * this.#composition.disconnect();\n * }\n *\n * onInput(event: InputEvent): void {\n * if (this.#composition.consumesConfirmedInput(event)) return;\n * if (this.#composition.isComposing(event)) return;\n * }\n *\n * onKeydown(event: KeyboardEvent): void {\n * if (this.#composition.isComposing(event)) return;\n * }\n * ```\n */\nexport class CompositionTracker {\n readonly #observedTargets = new Set<EventTarget>();\n /** The composition in progress, if any: only one field composes at a time. */\n #composition: Composition | null = null;\n readonly #onStart: ((event: Event) => void) | undefined;\n readonly #onEnd: ((event: Event) => void) | undefined;\n readonly #onAbandon: ((element: EventTarget, inPlace: boolean) => void) | undefined;\n /** The field whose confirming `input` is still owed, while the window is open. */\n #confirmedTarget: EventTarget | null = null;\n /**\n * Whether the last `keydown` reported a composition, until the `beforeinput`\n * after it: the edit that key announces lands inside the composition.\n */\n #keyComposing = false;\n /** Whether the consumer is connected: from `observe()` until `disconnect()`. */\n #connected = false;\n /** A composition that ended without `compositionend` and whose `onAbandon` has not run yet. */\n #abandoned: { readonly element: EventTarget; readonly inPlace: boolean } | null = null;\n\n constructor(options: CompositionTrackerOptions = {}) {\n this.#onStart = options.onStart;\n this.#onEnd = options.onEnd;\n this.#onAbandon = options.onAbandon;\n }\n\n /**\n * Starts lifecycle tracking for `target`; repeated calls are idempotent. The\n * targets one tracker observes do not contain one another: a composition event\n * reaching two of them would be counted as two.\n */\n observe(target: EventTarget): void {\n this.#connected = true;\n if (this.#observedTargets.has(target)) return;\n target.addEventListener(\"compositionstart\", this.#handleStart);\n target.addEventListener(\"compositionend\", this.#handleEnd);\n target.addEventListener(\"keydown\", this.#handleKeydown, true);\n target.addEventListener(\"beforeinput\", this.#handleBeforeInput, true);\n target.addEventListener(\"input\", this.#handleInput, true);\n target.addEventListener(\"blur\", this.#handleBlur, true);\n target.addEventListener(BEFORE_MORPH_ATTRIBUTE, this.#handleBeforeMorphAttribute);\n this.#observedTargets.add(target);\n }\n\n /**\n * Stops tracking one target. A composition it held ends quietly, unless its element\n * still holds focus — see {@link CompositionTracker.disconnect}.\n */\n unobserve(target: EventTarget): void {\n if (!this.#observedTargets.delete(target)) return;\n this.#release(target);\n if (this.#composition?.target === target) this.#letGo();\n if (this.#confirmedTarget === target) this.#confirmedTarget = null;\n }\n\n /**\n * Releases every listener and clears state so reconnect starts cleanly.\n *\n * A composition whose element still holds focus is the exception. A move that\n * keeps focus — `moveBefore`, which Turbo's morph uses where the browser provides\n * it — can leave the conversion running, and Stimulus releases the moved target, or\n * the controller around it, and observes it again within the one mutation batch. So\n * the composition waits for its target to be observed again before the turn ends,\n * and goes on; otherwise it ends then — quietly once disconnected, and with\n * {@link CompositionTrackerOptions.onAbandon} for a consumer that only let that one\n * target go. A move without `moveBefore`, or a removal, takes focus away.\n */\n disconnect(): void {\n this.#connected = false;\n for (const target of this.#observedTargets) this.#release(target);\n this.#observedTargets.clear();\n this.#letGo();\n this.#confirmedTarget = null;\n this.#keyComposing = false;\n this.#abandoned = null;\n }\n\n /**\n * True when a composition is live or the current event reports one. A\n * composition that ended without `compositionend` ends here first.\n */\n isComposing(event?: CompositionSignal): boolean {\n this.#settle();\n return event?.isComposing === true || this.#composition !== null;\n }\n\n /**\n * The element a live composition is running in, or `null`. A composition that\n * ended without `compositionend` ends here first.\n */\n composingElement(): EventTarget | null {\n this.#settle();\n return this.#composition?.element ?? null;\n }\n\n /**\n * Whether `event` belongs to a composition: it reports one, or it is in the element a\n * live composition runs in. An event in another element — a key there, or a script's\n * write reported with a bare `input` — is an edit outside the composition, even while\n * the tracker holds one whose end it has not seen: only one element composes at a\n * time, and the IME edits nothing else. The composition held stays, since such an\n * event does not show its end. A consumer that observes several fields asks this of\n * each event; {@link CompositionTracker.isComposing} asks of the targets as a whole.\n * A composition that ended without `compositionend` ends here first.\n */\n owns(event: CompositionSignal & { readonly target: EventTarget | null }): boolean {\n const element = this.composingElement();\n return event.isComposing === true || (element !== null && element === event.target);\n }\n\n /**\n * Whether `event` is the `input` echoing the composition just confirmed.\n *\n * Asking closes the window either way, so one confirmation is folded at most\n * once and a consumer asks once per `input`.\n */\n consumesConfirmedInput(event: ConfirmedInputSignal): boolean {\n const confirmed = this.#confirmedTarget;\n this.#confirmedTarget = null;\n if (confirmed === null || confirmed !== event.target) return false;\n // An engine that reports no kind at all leaves `inputType` empty, and the\n // window is then the only signal there is.\n const inputType = event.inputType;\n return !inputType || isCompositionInputType(inputType);\n }\n\n /** Removes every listener {@link CompositionTracker.observe} added to `target`. */\n #release(target: EventTarget): void {\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n target.removeEventListener(\"keydown\", this.#handleKeydown, true);\n target.removeEventListener(\"beforeinput\", this.#handleBeforeInput, true);\n target.removeEventListener(\"input\", this.#handleInput, true);\n target.removeEventListener(\"blur\", this.#handleBlur, true);\n target.removeEventListener(BEFORE_MORPH_ATTRIBUTE, this.#handleBeforeMorphAttribute);\n }\n\n /**\n * Lets go of the composition held once its target is no longer observed: it is over\n * unless its element kept focus and its target is observed again this turn.\n */\n #letGo(): void {\n const composition = this.#composition;\n if (composition === null) return;\n if (!holdsFocus(composition.element)) {\n this.#composition = null;\n return;\n }\n queueMicrotask(() => {\n if (this.#composition !== composition || this.#observedTargets.has(composition.target)) {\n return;\n }\n this.#composition = null;\n if (!this.#connected) return;\n this.#abandoned = { element: composition.element, inPlace: true };\n this.#runAbandon();\n });\n }\n\n /**\n * Ends the composition held if its field left the observed target, taking the\n * composition's text along, or holds text a write left.\n */\n #settle(): void {\n const composition = this.#composition;\n if (composition === null) return;\n const { target, element, text } = composition;\n if (target instanceof Node && element instanceof Node && !target.contains(element)) {\n this.#composition = null;\n } else if (textOf(element) !== text) {\n this.#abandon(false);\n }\n }\n\n /**\n * Ends the composition held, unconfirmed. Its `onAbandon` runs in a microtask,\n * unless an event the tracker hears runs it first.\n */\n #abandon(inPlace: boolean): void {\n this.#owe(inPlace);\n this.#composition = null;\n queueMicrotask(this.#runAbandon);\n }\n\n /** Records the `onAbandon` the composition held owes. */\n #owe(inPlace: boolean): void {\n const composition = this.#composition;\n if (composition !== null) this.#abandoned = { element: composition.element, inPlace };\n }\n\n /** Runs the `onAbandon` an ended composition owes, once. */\n readonly #runAbandon = (): void => {\n const abandoned = this.#abandoned;\n if (abandoned === null) return;\n this.#abandoned = null;\n this.#onAbandon?.(abandoned.element, abandoned.inPlace);\n };\n\n /** A composition starting while one is held ends the held one, unconfirmed. */\n readonly #handleStart = (event: Event): void => {\n this.#confirmedTarget = null;\n this.#settle();\n this.#owe(true);\n // A listener runs while the event is dispatched, so both targets are set.\n const target = event.currentTarget as EventTarget;\n const element = event.target as EventTarget;\n this.#composition = { target, element, text: textOf(element) };\n this.#runAbandon();\n this.#onStart?.(event);\n };\n\n readonly #handleEnd = (event: Event): void => {\n this.#runAbandon();\n if (this.#composition?.target === event.currentTarget) this.#composition = null;\n this.#confirmedTarget = event.target;\n this.#onEnd?.(event);\n };\n\n /**\n * A key on an observed field opens an edit of its own, so no echo is owed; it\n * also says whether the edit it announces lands inside a composition.\n */\n readonly #handleKeydown = (event: Event): void => {\n this.#settle();\n this.#runAbandon();\n this.#confirmedTarget = null;\n this.#keyComposing = (event as KeyboardEvent).isComposing === true;\n };\n\n /** An edit is about to land: a composition the engine no longer runs ends first. */\n readonly #handleBeforeInput = (event: Event): void => {\n const keyComposing = this.#keyComposing;\n this.#keyComposing = false;\n this.#settle();\n const { isComposing, inputType } = event as InputEvent;\n if (\n this.#composition !== null &&\n !keyComposing &&\n !isComposing &&\n inputType &&\n !isCompositionInputType(inputType)\n ) {\n this.#abandon(true);\n }\n this.#runAbandon();\n };\n\n /**\n * Takes the composing field's text from an `input` the engine dispatched or one\n * that reports the composition; any other `input` follows a write the\n * composition did not make.\n */\n readonly #handleInput = (event: Event): void => {\n const composition = this.#composition;\n const { isTrusted, isComposing, inputType } = event as InputEvent;\n if (\n composition !== null &&\n event.target === composition.element &&\n (isTrusted || isComposing || isCompositionInputType(inputType))\n ) {\n composition.text = textOf(composition.element);\n } else {\n this.#settle();\n }\n this.#runAbandon();\n };\n\n /**\n * Checks the composition as a field loses focus, ahead of the consumer's own blur\n * handlers. A field inside an observed ancestor that loses focus within its\n * document keeps its text and composes no more.\n */\n readonly #handleBlur = (event: Event): void => {\n this.#settle();\n this.#runAbandon();\n const composition = this.#composition;\n if (composition === null || composition.target === composition.element) return;\n const { element } = composition;\n if (!(element instanceof Node) || event.target !== element) return;\n const root = element.getRootNode() as Document | ShadowRoot;\n if (root.activeElement !== element) this.#composition = null;\n };\n\n /** Keeps a Turbo morph from writing the value of the element composing. */\n readonly #handleBeforeMorphAttribute = (event: Event): void => {\n this.#settle();\n const composition = this.#composition;\n if (composition?.target !== event.currentTarget || event.target !== composition.element) return;\n const detail: { readonly attributeName?: unknown } | null = (event as CustomEvent).detail;\n if (detail?.attributeName === \"value\") event.preventDefault();\n };\n}\n","/**\n * The hidden form fields a widget keeps in step with the state it owns.\n *\n * A widget whose value lives in ARIA attributes submits nothing on its own, so\n * it mirrors that value into `<input type=\"hidden\">` — one field for a single\n * value, a container of generated fields for a set. The mirror is one-way: the\n * widget's own state stays the source of truth and the field is what the form\n * reads.\n *\n * The write and the report are separate calls because they answer to different\n * rules. A mirror is refreshed on connect, after a morph, and whenever the\n * widget repairs itself — none of which a form should treat as an edit. Only\n * the user's own commit reports one, which is why {@link commitField} is never\n * folded into the writes.\n */\n\n/** How a widget's generated fields identify themselves to the form. */\nexport interface GeneratedFieldOptions {\n /** The `name` every generated input submits under. */\n readonly name: string;\n /** The `form` id, for a widget that sits outside the form it submits to. */\n readonly form?: string;\n}\n\n/**\n * Mirrors one value into a hidden field.\n *\n * @returns Whether the field's value moved.\n *\n * @example\n * ```ts\n * if (writeField(this.fieldTarget, String(value)) && userDriven) {\n * commitField(this.fieldTarget);\n * }\n * ```\n */\nexport function writeField(field: HTMLInputElement, value: string): boolean {\n if (field.value === value) return false;\n field.value = value;\n return true;\n}\n\n/**\n * Mirrors a set of values into `container` as generated hidden fields, in the\n * order given.\n *\n * A container that already submits exactly this set is left untouched, children\n * and all — the mirror is refreshed far more often than it moves (every connect,\n * morph and repair), and a rebuild that changes nothing is still a DOM mutation\n * a consumer's observer and a `:empty` rule can see.\n *\n * @returns Whether the submitted set moved — its values, their order, the\n * `name`, or the `form`.\n */\nexport function writeFields(\n container: HTMLElement,\n values: readonly string[],\n { name, form = \"\" }: GeneratedFieldOptions,\n): boolean {\n const current = [...container.children];\n const submits =\n current.length === values.length &&\n current.every(\n (child, index) =>\n child instanceof HTMLInputElement &&\n child.type === \"hidden\" &&\n child.value === values[index] &&\n child.name === name &&\n (child.getAttribute(\"form\") ?? \"\") === form,\n );\n if (submits) return false;\n\n container.replaceChildren(\n ...values.map((value) => {\n const input = document.createElement(\"input\");\n input.type = \"hidden\";\n input.name = name;\n input.value = value;\n if (form !== \"\") input.setAttribute(\"form\", form);\n return input;\n }),\n );\n return true;\n}\n\n/**\n * Reports a committed value from `target` the way a native form control does:\n * one bubbling, non-cancelable `change`.\n *\n * Call it only for a move the user made. Form-level behaviors listen for this —\n * validation re-checks, auto-submit — and a mirror refreshed by a morph or a\n * repair is not something the user submitted.\n *\n * `target` is the element that carries the value: the hidden field for a single\n * mirrored value, the container for a generated set (whose own inputs are\n * replaced on every write), or a widget's own native control where that is what\n * the form reads.\n */\nexport function commitField(target: HTMLElement): void {\n target.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n","/** What {@link ListenerSet.add} passes on besides the signal it supplies itself. */\nexport type ListenerOptions = Omit<AddEventListenerOptions, \"signal\">;\n\n/**\n * The event map a target's own `addEventListener` types its handlers with: the\n * window's, a document's, an HTML or SVG element's, any other element's, or a\n * media query list's. Other targets name none.\n */\ntype EventMapOf<T extends EventTarget> = T extends Window\n ? WindowEventMap\n : T extends Document\n ? DocumentEventMap\n : T extends HTMLElement\n ? HTMLElementEventMap\n : T extends SVGElement\n ? SVGElementEventMap\n : T extends Element\n ? ElementEventMap\n : T extends MediaQueryList\n ? MediaQueryListEventMap\n : Record<never, never>;\n\n/**\n * Owns every listener a controller attaches for one connected lifetime and\n * releases them together, so an event name is spelled once and the release\n * cannot drift from the registration.\n *\n * Detaching by hand repeats three things at the release site — the type, the\n * handler reference and the capture flag — and any one of them drifting leaves\n * a listener alive on an element the controller no longer drives. Aborting the\n * signal a registration was created with releases it whatever it was made of,\n * so the release site names nothing.\n *\n * One set per lifetime, held as a field and never rebuilt.\n * {@link ListenerSet.dispose} is the only thing that closes a generation, and it opens\n * the next one in the same step, so the lifecycle hooks can call `add` and\n * `dispose` in any order any number of times, and no `add` ever meets an\n * already aborted signal — a DOM that registers a listener on such a signal\n * would keep it forever. Rebuilding the set instead would leak:\n * `addEventListener` matches an existing registration on target, type, callback\n * and capture alone, so re-adding the same handler while the first registration\n * is live is discarded, and that live registration keeps the signal it was\n * attached with — a set built by a second `connect()` can never release what it\n * appears to own.\n *\n * Scope is the registration only. Timers, observers, leases and the order they\n * are unwound in stay with the controller, which places `dispose()` in its\n * cleanup sequence. A receiver that changes at runtime (a\n * swapped target) is rebound by calling `dispose()` and then `add()` again from\n * the rebind, not by a second set.\n *\n * A lifetime shorter than the connection — while a Value holds, until a first\n * load, while a subscription is open — gets a set of its own, which the end of\n * that lifetime disposes. A controller therefore holds one set per lifetime: the\n * connection's, and one for each swapped receiver or shorter span.\n *\n * The set must own every registration of a tuple it holds: a listener the same\n * target already carries for the same type, callback and capture flag keeps the\n * right to remove it, and this set's `add` for that tuple is discarded. A\n * subscription shared between instances behind a participant count, listeners of\n * several elements that come and go one at a time, and those one gesture holds\n * keep their own pair of calls or a signal of their own.\n *\n * @example\n * ```ts\n * readonly #listeners = new ListenerSet();\n *\n * connect(): void {\n * this.#listeners.add(this.element, \"submit\", this.#onNativeSubmit, { capture: true });\n * this.#listeners.add(this.element, \"turbo:submit-start\", this.#onSubmitStart);\n * this.#listeners.add(this.element, \"turbo:submit-end\", this.#onSubmitEnd);\n * }\n *\n * disconnect(): void {\n * this.#listeners.dispose();\n * }\n * ```\n */\nexport class ListenerSet {\n /** The generation every `add` joins until the next `dispose()`. */\n #abort = new AbortController();\n\n /**\n * Attaches `handler` to the open generation, exactly as the caller spelled it.\n *\n * The set supplies the signal, so `options` carries everything else the DOM\n * accepts — `capture` included. A removal by hand would have to repeat that\n * flag; aborting the signal releases the listener without it.\n *\n * A `type` the target's own event map names types `handler` with that event,\n * as the target's `addEventListener` does, so a handler written for a\n * `KeyboardEvent` is passed as it is; any other `type` takes an\n * `EventListener`.\n */\n add<T extends EventTarget, K extends keyof EventMapOf<T> & string>(\n target: T,\n type: K,\n handler: (event: EventMapOf<T>[K]) => void,\n options?: ListenerOptions,\n ): void;\n add(target: EventTarget, type: string, handler: EventListener, options?: ListenerOptions): void;\n add(target: EventTarget, type: string, handler: EventListener, options?: ListenerOptions): void {\n target.addEventListener(type, handler, { ...options, signal: this.#abort.signal });\n }\n\n /**\n * Releases every listener of the open generation, synchronously, and opens the\n * next one. Idempotent, and safe before anything has been added.\n */\n dispose(): void {\n this.#abort.abort();\n this.#abort = new AbortController();\n }\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Whether a requested pass has yet to run. */\n get pending(): boolean {\n return this.#queued;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","import { ListenerSet } from \"./listener_set\";\nimport { MicrotaskCoalescer } from \"./microtask_coalescer\";\n\n/**\n * Coalesces retained-element morphs and explicit lifecycle requests into one pass.\n *\n * Observe the controller's element after its initial state is settled. Morphs on\n * that element and bubbling morphs on its descendants share the same microtask\n * as {@link schedule}. The callback repairs derived output; the controller owns\n * any logical transition reporting. {@link disconnect} releases the listener and\n * cancels pending work, including work from an earlier connected lifetime.\n */\nexport class MorphRenderWatcher {\n readonly #listeners = new ListenerSet();\n readonly #pass: MicrotaskCoalescer;\n #element: Element | null = null;\n readonly #onMorph = (): void => this.#pass.schedule();\n\n /** @param run - the single pass that repairs the settled controller's output. */\n constructor(run: () => void) {\n this.#pass = new MicrotaskCoalescer(run);\n }\n\n /** Opens observation; observing the same element again preserves queued work. */\n observe(element: Element): void {\n if (this.#element === element) return;\n this.disconnect();\n this.#element = element;\n this.#pass.activate();\n this.#listeners.add(element, \"turbo:morph-element\", this.#onMorph);\n }\n\n /** Requests one pass; requests outside an observed lifetime are ignored. */\n schedule(): void {\n this.#pass.schedule();\n }\n\n /** Whether a pass requested by a morph or {@link schedule} has yet to run. */\n get pending(): boolean {\n return this.#pass.pending;\n }\n\n /** Releases observation and pending work synchronously; safe to repeat. */\n disconnect(): void {\n this.#listeners.dispose();\n this.#pass.cancel();\n this.#element = null;\n }\n}\n","/**\n * Identifies the latest reported state transition of one owner.\n *\n * Record a transition after its state is written and before invoking external\n * code. Check the returned token before each later report: a synchronous\n * transition made by a listener supersedes reports that have not been sent.\n * Reading state or committing an unchanged state must not advance the counter.\n * Reports stay in the caller so their ordering remains explicit.\n */\nexport class MoveCounter {\n #sequence = 0;\n\n /** Records a state transition and returns its report token. */\n record(): number {\n this.#sequence += 1;\n return this.#sequence;\n }\n\n /** Whether no later state transition has superseded this report token. */\n isLatest(token: number): boolean {\n return token === this.#sequence;\n }\n}\n","import { MAX_TIMER_DELAY_MS } from \"./timer_bounds\";\n\n/** Semantic constraints on an already decoded number, independent of the DOM. */\nexport interface NumberBounds {\n /** Finite numbers are required, including when this field is omitted. */\n readonly finite?: true;\n /** Inclusive lower endpoint. */\n readonly min?: number;\n /** Inclusive upper endpoint. */\n readonly max?: number;\n /** Exclusive lower endpoint. */\n readonly exclusiveMin?: number;\n /** Require a number without a fractional part. */\n readonly integer?: boolean;\n /** Exact decoded numbers accepted by a discrete contract. */\n readonly allowedValues?: readonly number[];\n /** JSON-safe exceptions to finite-number checking for unbounded endpoints. */\n readonly allowInfinity?: \"negative\" | \"positive\" | \"both\";\n}\n\n/** One constraint for each Number Value, including shorthand declarations. */\nexport type NumberValueConstraints<Values> = {\n readonly [Key in keyof Values as Values[Key] extends\n | NumberConstructor\n | { type: NumberConstructor }\n ? Key\n : never]: NumberBounds;\n};\n\n/** Reusable semantic domains; fractional inputs remain fractional unless excluded. */\nexport const NUMBER_BOUNDS = {\n finite: { finite: true },\n nonNegative: { finite: true, min: 0 },\n positive: { finite: true, exclusiveMin: 0 },\n nonNegativeInteger: { finite: true, min: 0, integer: true },\n positiveInteger: { finite: true, exclusiveMin: 0, integer: true },\n lowerBound: { finite: true, allowInfinity: \"negative\" },\n upperBound: { finite: true, allowInfinity: \"positive\" },\n timer: { finite: true, min: 0, max: MAX_TIMER_DELAY_MS },\n positiveTimer: { finite: true, exclusiveMin: 0, max: MAX_TIMER_DELAY_MS },\n} as const satisfies Record<string, NumberBounds>;\n\n/**\n * Checks all declared bounds without rounding, clamping, or coercing the input.\n * Infinity exceptions relax only finite checking; every other bound still applies.\n */\nexport function matchesNumberBounds(value: number, bounds: NumberBounds): boolean {\n if (!Number.isFinite(value)) {\n const direction = value === Infinity ? \"positive\" : value === -Infinity ? \"negative\" : null;\n if (direction === null) return false;\n if (bounds.allowInfinity !== \"both\" && bounds.allowInfinity !== direction) return false;\n }\n if (bounds.min !== undefined && value < bounds.min) return false;\n if (bounds.max !== undefined && value > bounds.max) return false;\n if (bounds.exclusiveMin !== undefined && value <= bounds.exclusiveMin) return false;\n if (bounds.integer && !Number.isInteger(value)) return false;\n if (bounds.allowedValues !== undefined && !bounds.allowedValues.includes(value)) return false;\n return true;\n}\n\n/** Decodes a Number Value literal; action params use their own JSON decoder. */\nexport function decodeNumberValue(raw: string): number {\n return Number(raw.replace(/_/g, \"\"));\n}\n","/**\n * Numeric coercion for controllers that accept a number through a Value, an action\n * param, or an event detail.\n *\n * Stimulus decodes action params as JSON when possible and leaves other text\n * untouched. CustomEvent detail can also supply a number or numeric string.\n * The reader accepts those two types while rejecting blank and non-finite input.\n */\n\nimport { matchesNumberBounds, type NumberBounds } from \"./number_bounds\";\n\n/** Numeric update input, accepting decoded action params before CustomEvent detail. */\nexport type NumericValueEvent = Event & {\n params?: { amount?: unknown };\n detail?: { value?: unknown };\n};\n\n/** Reads the nullish action-param/detail precedence without falling back from invalid input. */\nexport function eventNumber(event: NumericValueEvent): number | null {\n return toFiniteNumber(event.params?.amount ?? event.detail?.value);\n}\n\n/**\n * Reads a finite number or nonblank numeric string; other input returns `null`.\n * Blank strings cannot silently reset a value to zero.\n */\nexport function toFiniteNumber(raw: unknown): number | null {\n if (typeof raw !== \"number\" && typeof raw !== \"string\") return null;\n if (typeof raw === \"string\" && raw.trim().length === 0) return null;\n const value = Number(raw);\n return Number.isFinite(value) ? value : null;\n}\n\n/**\n * Returns an accepted decoded Number Value or the caller's fallback unchanged.\n * The caller owns the fallback contract; this reader does not parse or write a Value.\n */\nexport function readNumber(raw: number, fallback: number, bounds: NumberBounds): number {\n return matchesNumberBounds(raw, bounds) ? raw : fallback;\n}\n","import { readNumber } from \"./coerce\";\nimport { matchesNumberBounds, type NumberBounds } from \"./number_bounds\";\n\n/** The instance identity carried by a Number Value read. */\nexport interface NumberValueOwner {\n readonly identifier: string;\n readonly element: Element;\n}\n\n/** Reads current declarations at the point of use without rewriting their attributes. */\nexport class NumberValueReader {\n /** The last rejected literal per Value; no history grows for an unchanged instance. */\n readonly #lastRejected = new Map<string, string>();\n\n /** Resolves the declared number using its own fallback and shared class contract. */\n read(\n owner: NumberValueOwner,\n name: string,\n raw: number,\n fallback: number,\n bounds: NumberBounds,\n ): number {\n const resolved = readNumber(raw, fallback, bounds);\n if (matchesNumberBounds(raw, bounds)) {\n this.#lastRejected.delete(name);\n return resolved;\n }\n const attribute = `data-${owner.identifier}-${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}-value`;\n const literal = owner.element.getAttribute(attribute);\n if (literal === null) {\n this.#lastRejected.delete(name);\n return resolved;\n }\n if (this.#lastRejected.get(name) !== literal) {\n this.#lastRejected.set(name, literal);\n console.warn(\n `Stimeo UI: \"${owner.identifier}\" has an invalid number Value \"${name}\" declaration ${JSON.stringify(literal)}; using ${fallback}.`,\n );\n }\n return resolved;\n }\n}\n","/**\n * Scroll-follow for virtually-focused listbox options.\n *\n * Listbox-style widgets that track their active option with\n * `aria-activedescendant` keep DOM focus on the input/trigger, so the\n * browser's native \"scroll the focused element into view\" never runs — in a\n * scrollable list (`max-height` + `overflow`) the active option can walk right\n * out of sight on ArrowDown/ArrowUp. This helper keeps it visible.\n *\n * It adjusts the LIST's own `scrollTop` only — deliberately not\n * `scrollIntoView({ block: \"nearest\" })`, which may also scroll ancestor\n * scrolling boxes (the page) when a floating popup pokes past a viewport\n * edge, desyncing anchored/marker-composed placements. (Command-palette uses\n * `scrollIntoView` because its page is scroll-locked behind the modal;\n * page-floating popups must use this helper instead.)\n */\n\n/**\n * Scrolls `option` into view within `list` by minimally adjusting\n * `list.scrollTop`. No-ops when the list does not actually scroll. Never\n * touches any other scrolling box.\n *\n * @param list - The scrollable listbox container.\n * @param option - The (virtually focused) option to keep visible.\n */\nexport function scrollOptionIntoView(list: HTMLElement, option: HTMLElement): void {\n if (list.scrollHeight <= list.clientHeight) return;\n const listRect = list.getBoundingClientRect();\n const optionRect = option.getBoundingClientRect();\n if (optionRect.top < listRect.top) {\n list.scrollTop -= listRect.top - optionRect.top;\n } else if (optionRect.bottom > listRect.bottom) {\n list.scrollTop += optionRect.bottom - listRect.bottom;\n }\n}\n","import { setAttributeIfChanged } from \"./attribute_write\";\nimport { sharedRegistry } from \"./shared_registry\";\n\n/** What a consumer declares once about the regions one boolean state reveals. */\nexport interface StateRegionsOptions {\n /** Returns the declared regions shown while the state holds. */\n readonly whenTrue: () => readonly HTMLElement[];\n /**\n * Returns the declared regions shown while the state does not hold. Omitted by a\n * state whose other side has nothing of its own to show.\n */\n readonly whenFalse?: () => readonly HTMLElement[];\n}\n\n/** One instance's hold on one region's `hidden`, in the stack every instance shares. */\ninterface RegionHold {\n /** The instance holding it; `null` for a hold read from a copy's record until it is taken. */\n instance: object | null;\n readonly record: string;\n /** What the author wrote: the `hidden` it hands back with nothing beneath it. */\n readonly authored: string | null;\n /** Whether the visibility it wrote last hides the region. */\n written: boolean;\n /** Whether it hands back what the hold beneath it wrote last instead. */\n linked: boolean;\n}\n\n/** What an instance's record on a region says. */\ninterface RegionRecord {\n readonly authored: string | null;\n readonly written: boolean;\n readonly linked: boolean;\n /** The records of the other owners' holds beneath it, nearest first. */\n readonly beneath: readonly string[];\n}\n\n/** The holds on each region and every instance's record name. */\ninterface StateRegionsRegistry {\n readonly stacks: WeakMap<HTMLElement, RegionHold[]>;\n readonly names: Set<string>;\n}\n\n/**\n * Owns `hidden` on the regions a boolean state reveals.\n *\n * A region is a **declared** target, so the consumer decides whether one exists at\n * all; where it does, which side is shown is a pure function of the state and the\n * controller writes it unconditionally. An authored `hidden` is therefore not read\n * back — the first reflection after a connection settles it, and a restored DOM\n * cannot leave a region contradicting the state it belongs to.\n *\n * The regions arrive as the caller's own target arrays, which Stimulus has already\n * scoped to this instance: a nested controller registered under the same identifier\n * keeps its own regions. `host` narrows that set further, to the regions inside one\n * trigger or item, so a widget with several of them reflects each independently.\n *\n * **Two sides are a pair.** Where the state has a `whenFalse` side and only one half\n * sits inside `host`, the half that is there is left in view: hiding it would take\n * the only label with it, and the static check names the missing one instead. What\n * the author wrote on a lone half is theirs and stays — only a half this instance\n * took out of view is given back, which is what a pair losing one side at runtime\n * leaves behind.\n *\n * `hidden` moves only where it changes, and the record below only where what it says changes:\n * a transition costs a consumer watching its own subtree for attribute mutations two of them on\n * each region it moves — `hidden` and the record — and a reflection that moves nothing costs\n * none. A write that moves no `hidden` — the page moved the region first, or another\n * instance's hold lies above this one — changes only the record.\n *\n * **Every instance shares one stack of holds per region**, whatever its owner and whichever\n * file of the package constructed it (the stacks are one per page): the holds sit in the order\n * their instances first wrote the region, each with the visibility it wrote last. The region's\n * visibility is the highest hold's that carries it, and the page's when none does. A write\n * moves `hidden` unless a hold above the writer carries the region's visibility, so the top\n * hold always shows its writes and the page's visibility gives way to the next write of any\n * hold. A release gives a visibility back only from the hold the region's visibility is: the\n * one the hold beneath it wrote last, or the author's `hidden` once nothing is beneath it; any\n * other release only leaves the stack. Holds that wrote the same visibility are told apart by\n * the stack: the higher one keeps it. A first write over a top hold whose visibility the page\n * has replaced takes the region's `hidden` as the author's. Two instances of one owner on one\n * region stack the same way.\n *\n * **The stack travels with the region.** While the region carries anything but what the author\n * wrote under its top hold, or a hold lies on another hold or is covered by one, the region\n * carries that hold's owner's record `data-<owner>-hidden-region`: JSON of what the author\n * wrote (a string, or `null` for an absent attribute), whether the visibility written last\n * hides the region, `false` where the hold hands back the author's `hidden` rather than the\n * latest visibility of the hold beneath it, and the records of every hold beneath it, nearest\n * first; the last release of an owner removes it. A copy of the region — a page Turbo restores\n * from its cache — therefore carries the stack, read back under the record names of the\n * instances constructed so far and ordered by the records each hold lists beneath it, and an\n * instance that reflects, gives back or releases the copy takes the hold its owner's record\n * describes over in place. Complete records for distinct owners preserve their order across\n * a copy, including release without a new reflection. Records describe owners, not instances:\n * one owner holding the region more than once leaves only its topmost hold's record, which\n * the first of its instances to write or release on the copy takes. Its lower holds and\n * positions are absent; mutually listed owners cannot express their full live order. A hold\n * that showed the author's `hidden` alone carries no record and is taken by its first write\n * on the copy. Missing or unreadable records also leave their holds unknown, so copying the\n * DOM does not promise identical decisions for every live stack. A new stack with no readable\n * record takes the current value as the author's; a morph can remove records while existing\n * holds remain in memory until released.\n *\n * @example\n * ```ts\n * readonly #labels = new StateRegions(\n * {\n * whenTrue: () => this.expandedLabelTargets,\n * whenFalse: () => this.collapsedLabelTargets,\n * },\n * this.identifier,\n * );\n *\n * #reflect(): void {\n * this.#labels.reflect(this.triggerTarget, this.#expanded);\n * }\n * ```\n */\nexport class StateRegions {\n /** The holds on each region, bottom first, and the record names; one per page. */\n static readonly #registry = sharedRegistry(\n \"stimeo-ui.state-regions.registry.v1\",\n (): StateRegionsRegistry => ({ stacks: new WeakMap(), names: new Set() }),\n );\n readonly #whenTrue: () => readonly HTMLElement[];\n readonly #whenFalse: (() => readonly HTMLElement[]) | null;\n readonly #record: string;\n\n /**\n * @param options - The declared regions of each side.\n * @param owner - Names the record on a region; the controller's identifier.\n */\n constructor(options: StateRegionsOptions, owner: string) {\n this.#whenTrue = options.whenTrue;\n this.#whenFalse = options.whenFalse ?? null;\n this.#record = `data-${owner}-hidden-region`;\n StateRegions.#registry.names.add(this.#record);\n }\n\n /** Shows the regions inside `host` that belong to `isTrue` and hides the others. */\n reflect(host: Element, isTrue: boolean): void {\n const shown = this.#inside(host, this.#whenTrue());\n if (!this.#whenFalse) {\n for (const region of shown) this.#write(region, !isTrue);\n return;\n }\n const hiddenSide = this.#inside(host, this.#whenFalse());\n if (shown.length === 0 || hiddenSide.length === 0) {\n for (const region of shown) this.#give(region);\n for (const region of hiddenSide) this.#give(region);\n return;\n }\n for (const region of shown) this.#write(region, !isTrue);\n for (const region of hiddenSide) this.#write(region, isTrue);\n }\n\n /**\n * Restores the regions this instance wrote inside `host` to what the hold beneath it wrote last\n * or the authored `hidden`, unless changed since; found by scan, as the declared lists stop\n * resolving with targets.\n */\n release(host: Element): void {\n for (const region of [host, ...host.querySelectorAll(\"*\")]) {\n if (!(region instanceof HTMLElement)) continue;\n const stack = this.#held(region);\n const hold = stack && this.#take(stack);\n if (!stack || !hold) continue;\n const owns = region.hidden === hold.written && !this.#covered(region, stack, hold);\n const index = stack.indexOf(hold);\n stack.splice(index, 1);\n const above = stack[index];\n if (above) above.linked &&= hold.linked;\n if (owns) {\n const below = hold.linked ? stack[index - 1] : undefined;\n if (below) {\n if (region.hidden !== below.written) region.hidden = below.written;\n } else {\n setAttributeIfChanged(region, \"hidden\", hold.authored);\n }\n }\n this.#mark(region, stack);\n }\n }\n\n /** Writes `hidden` where it moves, unless a hold above this one carries the region's. */\n #write(region: HTMLElement, hidden: boolean): void {\n const stack = this.#stack(region);\n const hold = this.#take(stack) ?? this.#acquire(region, stack);\n const shows = !this.#covered(region, stack, hold);\n hold.written = hidden;\n if (shows && region.hidden !== hidden) region.hidden = hidden;\n this.#mark(region, stack);\n }\n\n /** Returns a region this instance hid; one it never hid keeps what it carries. */\n #give(region: HTMLElement): void {\n const stack = this.#held(region);\n if (stack && this.#take(stack)?.written) this.#write(region, false);\n }\n\n /** The region's stack, while it has one or carries this owner's record. */\n #held(region: HTMLElement): RegionHold[] | undefined {\n return StateRegions.#registry.stacks.has(region) || region.hasAttribute(this.#record)\n ? this.#stack(region)\n : undefined;\n }\n\n /** The region's stack, read from its records the first time. */\n #stack(region: HTMLElement): RegionHold[] {\n const stacks = StateRegions.#registry.stacks;\n const stack = stacks.get(region) ?? this.#seed(region);\n stacks.set(region, stack);\n return stack;\n }\n\n /** The holds a copy's records describe, each above every hold its record lists beneath. */\n #seed(region: HTMLElement): RegionHold[] {\n const found: (RegionRecord & { readonly record: string })[] = [];\n for (const record of StateRegions.#registry.names) {\n const read = this.#recorded(region, record);\n if (read) found.push({ ...read, record });\n }\n const depth = ({ beneath }: (typeof found)[number]) =>\n beneath.filter((name) => found.some((other) => other.record === name)).length;\n return found\n .sort((one, other) => depth(one) - depth(other))\n .map(({ record, authored, written, linked }, index) => ({\n instance: null,\n record,\n authored,\n written,\n linked: linked && index > 0,\n }));\n }\n\n /** Its hold in `stack`, taking over one read from its record. */\n #take(stack: RegionHold[]): RegionHold | undefined {\n const hold =\n stack.find((held) => held.instance === this) ??\n stack.find((held) => held.instance === null && held.record === this.#record);\n if (hold) hold.instance = this;\n return hold;\n }\n\n /** Whether a hold above `hold` carries the region's visibility, then that hold's. */\n #covered(region: HTMLElement, stack: readonly RegionHold[], hold: RegionHold): boolean {\n return stack.slice(stack.indexOf(hold) + 1).some((above) => above.written === region.hidden);\n }\n\n /** A new hold on top, over the top hold while the region shows what it wrote. */\n #acquire(region: HTMLElement, stack: RegionHold[]): RegionHold {\n const top = stack.at(-1);\n const over = top && region.hidden === top.written ? top : undefined;\n const hold: RegionHold = {\n instance: this,\n record: this.#record,\n authored: over ? over.authored : region.getAttribute(\"hidden\"),\n written: false,\n linked: over !== undefined,\n };\n stack.push(hold);\n return hold;\n }\n\n /** Leaves each owner's record of its topmost hold, or none where nothing needs one. */\n #mark(region: HTMLElement, stack: readonly RegionHold[]): void {\n const records = new Map<string, string | null>([[this.#record, null]]);\n stack.forEach((hold, index) => {\n const names = stack.slice(0, index).map((under) => under.record);\n const beneath = [...new Set(names.reverse())].filter((name) => name !== hold.record);\n const marker = hold.linked || beneath.length === 0 ? [] : [false];\n records.set(\n hold.record,\n region.getAttribute(\"hidden\") === hold.authored &&\n beneath.length === 0 &&\n index === stack.length - 1\n ? null\n : JSON.stringify([hold.authored, hold.written, ...marker, ...beneath]),\n );\n });\n for (const [name, recorded] of records) {\n setAttributeIfChanged(region, name, recorded);\n }\n }\n\n /**\n * The author's `hidden`, the visibility written last, whether it hands back the visibility\n * beneath it (`false` before the names when it does not) and the records beneath that the\n * record `name` on `region` holds.\n */\n #recorded(region: HTMLElement, name: string): RegionRecord | null {\n try {\n const parsed: unknown = JSON.parse(region.getAttribute(name) ?? \"null\");\n if (!Array.isArray(parsed)) return null;\n const [authored, written, ...rest] = parsed as unknown[];\n if (authored !== null && typeof authored !== \"string\") return null;\n const linked = rest[0] !== false;\n const beneath = linked ? rest : rest.slice(1);\n if (!beneath.every((under): under is string => typeof under === \"string\")) return null;\n return typeof written === \"boolean\" ? { authored, written, linked, beneath } : null;\n } catch {\n return null;\n }\n }\n\n /** The declared regions that sit within `host`, which may be the host itself. */\n #inside(host: Element, regions: readonly HTMLElement[]): HTMLElement[] {\n return regions.filter((region) => host.contains(region));\n }\n}\n","/**\n * Whether a disabled `<fieldset>` ancestor actually reaches `control`.\n *\n * HTML exempts the contents of a fieldset's **first direct-child `<legend>`**, and\n * the exemption is per fieldset — a control legal in one legend can still be\n * disabled by a second, outer fieldset, so the walk continues upward.\n *\n * Exported on its own for callers that need the disabled-inheritance rule without\n * the rest of {@link canTakeFocus} — a control's availability check, or a `hidden`\n * walk bounded at a widget root, which is a different rule to compose with.\n */\nexport function inheritsFieldsetDisabled(control: HTMLElement): boolean {\n let fieldset: Element | null = control.closest(\"fieldset[disabled]\");\n while (fieldset) {\n const legend = Array.from(fieldset.children).find((child) => child.tagName === \"LEGEND\");\n if (!legend?.contains(control)) return true;\n fieldset = fieldset.parentElement?.closest(\"fieldset[disabled]\") ?? null;\n }\n return false;\n}\n\n/**\n * Whether the engine reports `element` assigned to no slot of the open shadow root its parent\n * hosts: such an element is not in the flat tree, so it and what it holds are rendered nowhere\n * and cannot take focus.\n */\nfunction unslotted(element: Element): boolean {\n return element.assignedSlot === null && element.parentElement?.shadowRoot != null;\n}\n\n/**\n * The parent of `element` in the flat tree: the slot it is assigned to, its parent element,\n * or the host of the shadow root it is a child of; `null` at the top of the document or of a\n * detached tree, and for an element the engine assigns to no slot of the open shadow root its\n * parent hosts, which is outside the flat tree. A closed shadow root does not report its slots,\n * so an element assigned to one climbs to the host.\n */\nexport function flatTreeParent(element: Element): Element | null {\n if (unslotted(element)) return null;\n const parent = element.assignedSlot ?? element.parentNode;\n if (parent instanceof ShadowRoot) return parent.host;\n return parent instanceof Element ? parent : null;\n}\n\n/** Whether `element` is `ancestor` or one of its descendants in the flat tree. */\nexport function flatTreeContains(ancestor: Element, element: Element | null): boolean {\n for (let node = element; node; node = flatTreeParent(node)) {\n if (node === ancestor) return true;\n }\n return false;\n}\n\n/** The nearest of `element` and its flat-tree ancestors that matches `selector`, or `null`. */\nexport function closestInFlatTree(element: Element, selector: string): Element | null {\n for (let node: Element | null = element; node; node = flatTreeParent(node)) {\n if (node.matches(selector)) return node;\n }\n return null;\n}\n\n/**\n * The children of `element` in the flat tree: its open shadow root's children, a slot's\n * assigned elements (its own children when nothing is assigned to it), or its children.\n */\nexport function flatTreeChildren(element: Element): Element[] {\n return ownedScope(element) ?? Array.from(element.children);\n}\n\n/**\n * Whether an element can actually take focus, checked **before** `focus()` runs.\n *\n * A controller that must move focus off a control it is about to disable or hide\n * picks a destination and calls `focus()` on it. If that destination cannot take\n * focus, the call **fails silently**: `hidden` and natively `disabled` elements\n * swallow it, so the caret stays in the subtree that is disappearing and lands on\n * `<body>` a frame later — the exact outcome the rescue exists to prevent, minus\n * any signal that it happened.\n *\n * Testing after the fact is the obvious alternative and is deliberately not the\n * rule. Reading `document.activeElement` back only works in a real browser, and\n * looping over candidates that way performs a real focus move per failure —\n * observable to assistive technology. Checking first costs nothing and catches\n * the cases that actually occur.\n *\n * **`aria-disabled` is not disqualifying.** It is the attribute an author uses\n * for a control that must stay *discoverable*, and the roving contract keeps\n * such items reachable. Only the conditions that make the platform refuse\n * focus are checked: `hidden` / `inert` on the element or a flat-tree ancestor\n * (the host of an open shadow root it sits in, the slot it is assigned to), the\n * element or an ancestor left out of the flat tree (one the engine assigns to no\n * slot of the open shadow root its parent hosts), `input[type=\"hidden\"]`, the\n * native `disabled` property, and `disabled` inherited from an ancestor\n * `fieldset`. CSS-only invisibility is handled by {@link isRenderedForFocus}\n * when a consumer needs sequential-focus semantics.\n *\n * Reading `:disabled` instead of walking the fieldset chain would be shorter, but\n * that pseudo-class is not evaluated consistently outside real browsers and this\n * has to be right headlessly too. happy-dom in particular focuses a `<button>`\n * inside a disabled fieldset where a real engine refuses, so the inheritance is\n * spelled out rather than delegated.\n *\n * What a consumer does when nothing survives is its own call: some fall back to\n * their landmark, while a widget whose caret already sits somewhere legitimate\n * refuses the move outright rather than relocating it.\n *\n * @example\n * ```ts\n * const target = candidates.find(canTakeFocus);\n * if (target) target.focus();\n * else {\n * this.#tabindex.lend(this.element); // nothing left: fall back to the landmark\n * this.element.focus();\n * }\n * ```\n *\n * @param element - the candidate destination\n */\nexport function canTakeFocus(element: HTMLElement): boolean {\n for (let node: Element | null = element; node; node = flatTreeParent(node)) {\n if (unslotted(node) || node.matches(\"[hidden], [inert]\")) return false;\n }\n if (element instanceof HTMLInputElement && element.type === \"hidden\") return false;\n if (!(\"disabled\" in element)) return true;\n if ((element as HTMLElement & { disabled: boolean }).disabled) return false;\n return !inheritsFieldsetDisabled(element);\n}\n\n/** Elements whose semantics or authored attributes can place them in sequential focus order. */\nexport const TAB_STOP_CANDIDATE_SELECTOR = [\n \"a[href]\",\n \"area[href]\",\n \"button\",\n \"input\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"iframe\",\n \"audio[controls]\",\n \"video[controls]\",\n \"[tabindex]\",\n \"[contenteditable]\",\n].join(\",\");\n\n/** Optional browser visibility API used to exclude CSS-hidden candidates. */\ninterface VisibilityCheckable {\n checkVisibility?: (options?: { visibilityProperty?: boolean }) => boolean;\n}\n\n/** Whether CSS visibility allows an otherwise eligible element to participate in focus order. */\nexport function isRenderedForFocus(element: HTMLElement): boolean {\n const check = (element as HTMLElement & VisibilityCheckable).checkVisibility;\n return typeof check === \"function\" ? check.call(element, { visibilityProperty: true }) : true;\n}\n\n/** Parses an authored `tabindex`; invalid syntax has no explicit focus-order meaning. */\nfunction authoredTabindex(element: Element): number | null {\n const value = element.getAttribute(\"tabindex\");\n if (value === null || !/^[+-]?\\d+$/.test(value.trim())) return null;\n return Number(value);\n}\n\n/** Whether the element's native semantics place it in sequential focus order. */\nfunction hasNativeTabStop(element: HTMLElement): boolean {\n if (element instanceof HTMLAnchorElement || element instanceof HTMLAreaElement) {\n return element.hasAttribute(\"href\");\n }\n if (\n element instanceof HTMLButtonElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement\n ) {\n return true;\n }\n if (element instanceof HTMLInputElement) return element.type !== \"hidden\";\n if (element instanceof HTMLIFrameElement) return true;\n if (element.tagName === \"AUDIO\" || element.tagName === \"VIDEO\") {\n return element.hasAttribute(\"controls\");\n }\n if (element instanceof HTMLElement && element.tagName === \"SUMMARY\") {\n const details = element.parentElement;\n return (\n details instanceof HTMLDetailsElement &&\n Array.from(details.children).find((child) => child.tagName === \"SUMMARY\") === element\n );\n }\n return false;\n}\n\n/** Whether an explicit `contenteditable` value creates an editable tab stop. */\nfunction hasEditableTabStop(element: HTMLElement): boolean {\n const value = element.getAttribute(\"contenteditable\")?.toLowerCase();\n return value === \"\" || value === \"true\" || value === \"plaintext-only\";\n}\n\n/**\n * Whether an element is a usable sequential Tab stop right now.\n *\n * Native semantics, authored `tabindex`, editable hosts, inherited disabled state,\n * HTML `hidden`/`inert`, and CSS visibility are evaluated together. `aria-disabled`\n * remains focusable because it communicates unavailability without removing the\n * control from discovery order.\n */\nexport function isTabStop(element: HTMLElement): boolean {\n if (!canTakeFocus(element) || !isRenderedForFocus(element)) return false;\n\n const tabindex = authoredTabindex(element);\n if (tabindex !== null) return tabindex >= 0;\n return hasNativeTabStop(element) || hasEditableTabStop(element);\n}\n\n/** Returns every usable sequential Tab stop below `root` in document order. */\nexport function tabStopsWithin(root: ParentNode): HTMLElement[] {\n return Array.from(root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)).filter(\n isTabStop,\n );\n}\n\n/** Returns the first usable sequential Tab stop below `root`, if one exists. */\nexport function firstTabStop(root: ParentNode): HTMLElement | null {\n for (const candidate of root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)) {\n if (isTabStop(candidate)) return candidate;\n }\n return null;\n}\n\n/** Whether `root` contains at least one usable sequential Tab stop. */\nexport function hasTabStop(root: ParentNode): boolean {\n return firstTabStop(root) !== null;\n}\n\n/** An element sequential focus navigation can stop on. */\nexport type TabStopElement = HTMLElement | SVGElement;\n\n/** Whether the element is a radio button. */\nfunction isRadio(element: Element | null): element is HTMLInputElement {\n return element instanceof HTMLInputElement && element.type === \"radio\";\n}\n\n/**\n * Whether two radios form one group: the same non-empty `name`, the same form owner and\n * the same tree. A radio without a name is a group of its own.\n */\nfunction sameRadioGroup(a: HTMLInputElement, b: HTMLInputElement): boolean {\n return (\n a.name !== \"\" && a.name === b.name && a.form === b.form && a.getRootNode() === b.getRootNode()\n );\n}\n\n/**\n * Whether the element is part of editable content: the nearest ancestor that sets a valid\n * `contenteditable` decides. `false` ends the editable region (a non-editable island\n * inside an editor); an invalid value inherits from further up.\n */\nfunction isInEditableContent(element: Element): boolean {\n for (let node = element.parentElement; node; node = node.parentElement) {\n if (node.getAttribute(\"contenteditable\")?.toLowerCase() === \"false\") return false;\n if (hasEditableTabStop(node)) return true;\n }\n return false;\n}\n\n/** The XLink namespace, where an SVG link may carry its `href`. */\nconst XLINK_NAMESPACE = \"http://www.w3.org/1999/xlink\";\n\n/** Whether the element is an SVG link: an SVG `a` with `href` or `xlink:href`. */\nfunction isSvgLink(element: Element): boolean {\n return (\n element instanceof SVGElement &&\n element.localName === \"a\" &&\n (element.hasAttribute(\"href\") || element.hasAttributeNS(XLINK_NAMESPACE, \"href\"))\n );\n}\n\n/**\n * Whether an image-map area has a rendered image: an `img` in the area's tree whose\n * `usemap` names the area's map (by `name`, or by `id` without one) and that is rendered.\n * The area has no box of its own for {@link isRenderedForFocus} to check.\n */\nfunction hasRenderedImage(area: HTMLAreaElement): boolean {\n const map = area.closest(\"map\");\n const key = map?.name || map?.id;\n if (!map || !key) return false;\n const root = map.getRootNode() as Document | ShadowRoot;\n return Array.from(root.querySelectorAll<HTMLElement>(\"img[usemap]\")).some(\n (image) => image.getAttribute(\"usemap\") === `#${key}` && isRenderedForFocus(image),\n );\n}\n\n/** Whether the element can take focus and has no negative `tabindex`. */\nfunction isFocusableInOrder(element: TabStopElement): boolean {\n const tabindex = authoredTabindex(element);\n return (tabindex === null || tabindex >= 0) && canTakeFocus(element as HTMLElement);\n}\n\n/**\n * The engine's verdict for the stops {@link isTabStop} does not judge the way sequential\n * navigation does, or `null` for every other element: an image-map area with an `href` or\n * its own `tabindex` stops while an image that uses its map is rendered; an object stops\n * while it holds a nested document, as an iframe does; an SVG link stops while it is\n * rendered. Each also needs to take focus and not be taken out of the order with a\n * negative `tabindex`.\n */\nfunction extraStop(element: TabStopElement): boolean | null {\n if (element instanceof HTMLAreaElement) {\n const focusable = element.hasAttribute(\"href\") || authoredTabindex(element) !== null;\n return focusable && isFocusableInOrder(element) && hasRenderedImage(element);\n }\n if (element instanceof HTMLObjectElement) {\n return (\n isFocusableInOrder(element) && isRenderedForFocus(element) && element.contentWindow !== null\n );\n }\n if (isSvgLink(element))\n return isFocusableInOrder(element) && isRenderedForFocus(element as HTMLElement);\n return null;\n}\n\n/**\n * Whether sequential navigation stops on the element: a usable Tab stop\n * ({@link isTabStop}), or one of the stops `extraStop` judges, except a link inside\n * editable content without a `tabindex` of its own, which the engine leaves to editing.\n * Other controls inside an editing host, and the host itself, stay stops.\n */\nfunction isSequentialStop(element: TabStopElement): boolean {\n const stop =\n extraStop(element) ??\n (element.matches(TAB_STOP_CANDIDATE_SELECTOR) && isTabStop(element as HTMLElement));\n if (!stop) return false;\n const link =\n element instanceof HTMLAnchorElement ||\n element instanceof HTMLAreaElement ||\n isSvgLink(element);\n return !(link && authoredTabindex(element) === null && isInEditableContent(element));\n}\n\n/**\n * The elements of the focus navigation scope `element` owns: its open shadow root's\n * children, or a slot's assigned elements (its fallback content when nothing is\n * assigned). `null` when it owns no scope. A closed shadow root cannot be read, so its\n * host owns none.\n */\nfunction ownedScope(element: Element): Element[] | null {\n if (element.shadowRoot) return Array.from(element.shadowRoot.children);\n if (element instanceof HTMLSlotElement) {\n const assigned = element.assignedElements();\n return assigned.length > 0 ? assigned : Array.from(element.children);\n }\n return null;\n}\n\n/** One member of a focus navigation scope: its tabindex and the stops it contributes. */\ninterface ScopeEntry {\n readonly tabindex: number;\n readonly stops: TabStopElement[];\n}\n\n/** What a walk of the order records besides the order itself. */\ninterface OrderWalk {\n /** The element a move starts from. */\n readonly from: Element | null;\n /** Every stop, in flat-tree order. */\n readonly tree: TabStopElement[];\n /**\n * How many entries of {@link OrderWalk.tree} come before `from`; `-1` until the walk\n * meets it.\n */\n fromAt: number;\n}\n\n/**\n * Orders one focus navigation scope the way HTML's sequential navigation does: members\n * with a positive `tabindex` first, ascending, ties in tree order, then the rest in tree\n * order. A member that owns a scope (a shadow host, a slot) is followed by that scope's\n * own order; one taken out of the order with a negative `tabindex` takes its scope with it.\n */\nfunction orderScope(elements: Element[], walk: OrderWalk): TabStopElement[] {\n const entries: ScopeEntry[] = [];\n const visit = (element: Element): void => {\n if (element === walk.from) walk.fromAt = walk.tree.length;\n const tabindex = authoredTabindex(element) ?? 0;\n const stop =\n (element instanceof HTMLElement || element instanceof SVGElement) && isSequentialStop(element)\n ? element\n : null;\n if (stop) walk.tree.push(stop);\n const owned = ownedScope(element);\n if (owned) {\n if (tabindex >= 0) {\n entries.push({ tabindex, stops: [...(stop ? [stop] : []), ...orderScope(owned, walk)] });\n }\n return;\n }\n if (stop) entries.push({ tabindex, stops: [stop] });\n for (const child of Array.from(element.children)) visit(child);\n };\n for (const element of elements) visit(element);\n const positive = entries.filter((entry) => entry.tabindex > 0);\n positive.sort((a, b) => a.tabindex - b.tabindex);\n const rest = entries.filter((entry) => entry.tabindex === 0);\n return [...positive, ...rest].flatMap((entry) => entry.stops);\n}\n\n/**\n * Whether a candidate passes the radio-group rule the engine applies: a checked radio\n * among the stops always does; an unchecked one only as the first radio of a group with\n * no checked stop, and not while focus is on a radio of that group. `tree` is the walk's\n * stops in flat-tree order, so a group is counted within the walked root only.\n */\nfunction passesRadioRule(\n element: TabStopElement,\n tree: TabStopElement[],\n focusedRadio: HTMLInputElement | null,\n): boolean {\n if (!isRadio(element) || element.checked) return true;\n const group = tree.filter(\n (stop): stop is HTMLInputElement =>\n stop === element || (isRadio(stop) && sameRadioGroup(stop, element)),\n );\n if (group.some((radio) => radio.checked)) return false;\n if (group[0] !== element) return false;\n return focusedRadio === null || !sameRadioGroup(focusedRadio, element);\n}\n\n/**\n * The index in `order` a move from the walk's `from` visits first. A start the walk did\n * not meet is outside: the move enters at the first stop, or the last going backward. A\n * start that is a stop moves one place along the order. Any other start (the root, an\n * element with a negative `tabindex`) moves to the nearest stop after it in tree order,\n * or before it going backward, and wraps when there is none.\n */\nfunction startIndex(\n order: TabStopElement[],\n walk: OrderWalk,\n backward: boolean,\n isStop: (element: TabStopElement) => boolean,\n): number {\n if (walk.fromAt < 0) return backward ? order.length - 1 : 0;\n const at = order.indexOf(walk.from as TabStopElement);\n if (at >= 0) return backward ? at - 1 : at + 1;\n const neighbour = backward\n ? walk.tree.slice(0, walk.fromAt).reverse().find(isStop)\n : walk.tree.slice(walk.fromAt).find(isStop);\n if (neighbour) return order.indexOf(neighbour);\n return backward ? order.length - 1 : 0;\n}\n\n/**\n * The stops below `root` in the order a sequential move from `from` visits them: the\n * next stop first (the previous one when `backward`), wrapping at the ends, with `from`\n * itself left out. Without a `from` — or with one outside `root` — the list starts at the\n * first stop, or at the last one when `backward`.\n *\n * The order is HTML's sequential navigation order within `root`: positive `tabindex`\n * first, ascending, then `tabindex=\"0\"` and native stops in tree order. Open shadow roots\n * are walked in flat-tree order, slots expanded, each scope ordered on its own; a closed\n * shadow root is not read. A radio group, counted within `root`, stops once: on its\n * checked radio when that radio can take focus, even with focus elsewhere in the group,\n * and otherwise on its first radio that can, unless focus is already in the group.\n * A link inside editable content without its own `tabindex` is not a stop. Every stop\n * also passes its applicable focusability and rendering checks.\n *\n * @param root - The element whose descendants are ordered; it is not a stop itself.\n * @param from - Where the move starts, usually {@link deepActiveElement}.\n * @param backward - Whether the move goes backward (`Shift+Tab`).\n */\nexport function sequentialTabStops(\n root: Element,\n from: Element | null = null,\n backward = false,\n): TabStopElement[] {\n const walk: OrderWalk = { from, tree: [], fromAt: from === root ? 0 : -1 };\n const order = orderScope(ownedScope(root) ?? Array.from(root.children), walk);\n const focusedRadio = walk.fromAt >= 0 && isRadio(from) ? from : null;\n const isStop = (element: TabStopElement): boolean =>\n passesRadioRule(element, walk.tree, focusedRadio);\n const start = startIndex(order, walk, backward, isStop);\n const visited = backward\n ? [...order.slice(0, start + 1).reverse(), ...order.slice(start + 1).reverse()]\n : [...order.slice(start), ...order.slice(0, start)];\n return visited.filter((element) => element !== from && isStop(element));\n}\n\n/**\n * The element that holds focus in `ownerDocument`, looking through open shadow roots:\n * `document.activeElement` stops at a shadow host. A closed shadow root cannot be read,\n * so focus inside one reads as its host.\n */\nexport function deepActiveElement(ownerDocument: Document): Element | null {\n let active = ownerDocument.activeElement;\n while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;\n return active;\n}\n","/** Queries physical descendants and nested open shadow trees, including `root`'s own. */\nexport function queryOpenDescendants<T extends Element = Element>(\n root: ParentNode,\n selector: string,\n): T[] {\n const matches: T[] = [];\n const roots: ParentNode[] = [root];\n for (const scope of roots) {\n matches.push(...scope.querySelectorAll<T>(selector));\n if (scope.nodeType === Node.ELEMENT_NODE) {\n const shadow = (scope as Element).shadowRoot;\n if (shadow) roots.push(shadow);\n }\n for (const element of scope.querySelectorAll(\"*\")) {\n if (element.shadowRoot) roots.push(element.shadowRoot);\n }\n }\n return matches;\n}\n","import { setAttributeIfChanged } from \"./attribute_write\";\nimport { deepActiveElement } from \"./focus_candidate\";\nimport { queryOpenDescendants } from \"./query_open_descendants\";\nimport { sharedRegistry } from \"./shared_registry\";\n\n/** One loan's hold on one element's `tabindex`, in the stack every loan of it shares. */\ninterface LoanHold {\n /** The loan holding it; `null` for a loan read from a copy's record until a loan takes it. */\n loan: object | null;\n readonly record: string;\n readonly value: string;\n /** Whether it hands back the value of the hold beneath it; otherwise no `tabindex`. */\n linked: boolean;\n}\n\n/** The loans on each element, bottom first, and every loan's record name. */\ninterface TabindexLoanRegistry {\n readonly stacks: WeakMap<HTMLElement, LoanHold[]>;\n readonly names: Set<string>;\n}\n\n/** Focus can be retargeted to a shadow host rather than exposed on the document. */\nfunction holdsFocus(element: HTMLElement): boolean {\n return element.matches(\":focus\") || deepActiveElement(element.ownerDocument) === element;\n}\n\n/**\n * Shared bookkeeping for a `tabindex` a controller lends an element temporarily.\n *\n * A controller that must move focus somewhere the author never made focusable\n * (a landmark root, a scroll destination) reaches for the same trick: add a\n * `tabindex` just-in-time and hand it back once it is no longer needed. The\n * borrow is the easy half; the return is what the two conditions below are for.\n *\n * **Returning needs two conditions, not one.** Owning the borrow is not enough:\n * the attribute must also still hold the value this instance wrote. A consumer\n * that changed it afterwards — `tabindex=\"0\"` to make the root its own Tab stop\n * — owns it now, and removing it there silently discards authored markup. The\n * bookkeeping is dropped when returned. With `preserveFocus`, a focused element\n * still showing this loan keeps its hold and record until a later return can finish.\n *\n * **Never borrow over a value no loan holds.** An element whose `tabindex` no loan\n * holds — the author's, or one the page wrote over the loans — is the author's to\n * control, so there is nothing to lend and nothing to return.\n *\n * **Every loan of an element shares one stack of loans**, whatever its owner and\n * whichever file of the package constructed it (the stacks are one per page). A loan\n * lends over the loans that hold the element while its `tabindex` is theirs — sharing\n * their value, or covering it with its own — and lends again where the page removed\n * the `tabindex`. The `tabindex` is the highest loan's that lends its value: returning\n * that loan gives the element the value of the loan beneath it, or no `tabindex`, and\n * any other return only leaves the stack. So two loans of one value — every focus trap\n * lends its container under one owner — keep it until the last of them returns, and a\n * loan lent after the page removed an earlier one's `tabindex` keeps it when the\n * earlier one returns.\n *\n * **A loan is recorded on the element.** Lending writes\n * `data-<owner>-tabindex-loan` holding the value the owner's topmost loan lends next\n * to the `tabindex`, and the owner's last loan to end removes it. A copy of the\n * element — a page Turbo restores from its cache is one — so tells its owners' loans\n * from an authored `tabindex`: `lend()` takes over a loan its owner recorded, and\n * `reclaim()` gives back one no loan has taken over; the `tabindex` goes with the last\n * of them. A copy keeps no order of its loans beyond putting those of the value it\n * carries on top. Without a record a `tabindex` is the author's. Nothing returns a\n * live loan before Turbo caches the page: `turbo:before-cache` also fires on pages\n * that stay, and the loan is still in use there.\n *\n * The registry is keyed by element, so a controller borrowing on a single\n * element (`this.element`) and one borrowing across a changing set of targets\n * use the same API — the single-element case is a set of one. It holds no\n * opinion about *when* to borrow or where focus goes next; that stays in the\n * controller.\n *\n * **The API is deliberately small.** Each consumer entry includes its own copy\n * of the class, so unused methods still increase its runtime output.\n *\n * @example\n * ```ts\n * readonly #tabindex = new TabindexLoan(\"-1\", this.identifier);\n *\n * connect() {\n * this.#tabindex.reclaim(this.element);\n * }\n *\n * #rescueFocus() {\n * this.#tabindex.lend(this.element);\n * this.element.focus();\n * }\n *\n * disconnect() {\n * this.#tabindex.returnAll();\n * }\n * ```\n */\nexport class TabindexLoan<T extends HTMLElement = HTMLElement> {\n /** The loans on each element and the record names, one per page. */\n static readonly #registry = sharedRegistry(\n \"stimeo-ui.tabindex-loan.registry.v1\",\n (): TabindexLoanRegistry => ({ stacks: new WeakMap(), names: new Set() }),\n );\n readonly #value: string;\n readonly #record: string;\n readonly #preserveFocus: boolean;\n readonly #lent = new Set<T>();\n\n /**\n * @param value - the `tabindex` to lend. `\"-1\"` is programmatically focusable but\n * not a Tab stop; `\"0\"` is a real Tab stop, which a scroll region with no\n * focusable content of its own needs.\n * @param owner - Names the record on the element; the controller's identifier.\n * @param options - `preserveFocus`: keep a shown loan while its element holds focus.\n */\n constructor(value: string, owner: string, options: { readonly preserveFocus?: boolean } = {}) {\n this.#value = value;\n this.#record = `data-${owner}-tabindex-loan`;\n this.#preserveFocus = options.preserveFocus === true;\n TabindexLoan.#registry.names.add(this.#record);\n }\n\n /**\n * Lends `element` the value over the loans holding its `tabindex`, or where the page removed\n * it; a `tabindex` no loan holds is left alone, and a loan recorded on a copy taken over.\n * `onlyIfUnfocusable` starts no new loan on an element that carries any `tabindex` or is\n * natively focusable (a `tabIndex` of `0` or more).\n */\n lend(element: T, options: { readonly onlyIfUnfocusable?: boolean } = {}): void {\n const stack = this.#stack(element);\n const current = element.getAttribute(\"tabindex\");\n const held =\n stack.find((hold) => hold.loan === this) ??\n stack.find(\n (hold) => hold.loan === null && hold.record === this.#record && hold.value === this.#value,\n );\n const linked = stack.at(-1)?.value === current;\n if (!held && options.onlyIfUnfocusable && (current !== null || element.tabIndex >= 0)) return;\n if (!held && current !== null && !linked) return;\n this.#lent.add(element);\n if (held) held.loan = this;\n else stack.push({ loan: this, record: this.#record, value: this.#value, linked });\n this.#mark(element, stack);\n if (current === null || (!held && current !== this.#value)) {\n element.setAttribute(\"tabindex\", this.#value);\n }\n }\n\n /** Returns one live or restored loan, retaining a focus-protected hold for a later return. */\n return(element: T): boolean {\n const stack = this.#stack(element);\n const hold =\n stack.find((held) => held.loan === this) ??\n stack.find(\n (held) => held.loan === null && held.record === this.#record && held.value === this.#value,\n );\n if (!hold) return false;\n if (!this.#release(element, stack, hold, this.#preserveFocus)) {\n hold.loan = this;\n this.#lent.add(element);\n return false;\n }\n this.#lent.delete(element);\n return true;\n }\n\n /** Returns every loan, retaining focus-protected ones even outside the current target set. */\n returnAll(): void {\n for (const element of Array.from(this.#lent)) this.return(element);\n }\n\n /**\n * Gives back a loan its owner recorded on a restored copy that no loan has taken over, unless\n * the record holds another value or the element holds focus.\n */\n reclaim(element: HTMLElement): void {\n if (element.getAttribute(this.#record) !== this.#value) return;\n const stack = this.#stack(element);\n const hold = stack.find((held) => held.loan === null && held.record === this.#record);\n if (hold && !holdsFocus(element)) this.#release(element, stack, hold);\n }\n\n /** Gives back, as {@link reclaim} does, every loan of its owner recorded inside `root`. */\n reclaimWithin(root: ParentNode): void {\n for (const element of queryOpenDescendants<HTMLElement>(root, `[${this.#record}]`)) {\n this.reclaim(element);\n }\n }\n\n /** The element's loans, read from its records the first time. */\n #stack(element: HTMLElement): LoanHold[] {\n const stacks = TabindexLoan.#registry.stacks;\n const stack = stacks.get(element) ?? this.#seed(element);\n stacks.set(element, stack);\n return stack;\n }\n\n /** The loans a copy's records describe, those of the value it carries on top. */\n #seed(element: HTMLElement): LoanHold[] {\n const current = element.getAttribute(\"tabindex\");\n const holds: LoanHold[] = [];\n for (const record of TabindexLoan.#registry.names) {\n const value = element.getAttribute(record);\n if (value !== null) holds.push({ loan: null, record, value, linked: true });\n }\n holds.sort((one, other) => Number(one.value === current) - Number(other.value === current));\n for (const [index, hold] of holds.entries()) hold.linked = index > 0;\n return holds;\n }\n\n /** Takes `hold` off, handing the value it shows to the loan beneath. */\n #release(\n element: HTMLElement,\n stack: LoanHold[],\n hold: LoanHold,\n preserveFocus = false,\n ): boolean {\n const current = element.getAttribute(\"tabindex\");\n const index = stack.indexOf(hold);\n const owns =\n current === hold.value && !stack.slice(index + 1).some((above) => above.value === current);\n if (owns && preserveFocus && holdsFocus(element)) return false;\n stack.splice(index, 1);\n const above = stack[index];\n if (above) above.linked &&= hold.linked;\n this.#mark(element, stack);\n if (!owns) return true;\n const below = hold.linked ? stack[index - 1] : undefined;\n if (!below) element.removeAttribute(\"tabindex\");\n else if (below.value !== current) element.setAttribute(\"tabindex\", below.value);\n return true;\n }\n\n /** Leaves each owner's record of the value its topmost loan lends. */\n #mark(element: HTMLElement, stack: readonly LoanHold[]): void {\n const records = new Map<string, string | null>([[this.#record, null]]);\n for (const hold of stack) records.set(hold.record, hold.value);\n for (const [name, recorded] of records) {\n setAttributeIfChanged(element, name, recorded);\n }\n }\n}\n","/**\n * The attribute selector for one declared target, in a controller's own namespace.\n *\n * Stimulus reads `data-<identifier>-target` as a **space-separated token list**, so a\n * single element can carry several target names at once. Matching the attribute value\n * whole would reach only the elements that declare exactly one name, which is why the\n * name is paired with `~=`.\n *\n * `identifier` is the name the controller is registered under, so the selector reaches\n * the markup that registration renders rather than one fixed spelling.\n */\nexport function targetSelector(identifier: string, name: string): string {\n return `[data-${identifier}-target~=\"${name}\"]`;\n}\n","import { fillTemplate } from \"./announce\";\nimport { matchingPart } from \"./element_part\";\nimport { targetSelector } from \"./target_selector\";\n\n/**\n * Clones the first element of a `<template>`, and nothing else.\n *\n * A template is authored across lines, so its content holds whitespace text nodes\n * around that element — and a second element, where one is written. Cloning the\n * element on its own makes it the whole unit the caller appends, so the same node\n * a later `remove()` takes back is everything that went in, and the parent's child\n * list stays equal to its element list.\n *\n * `null` when the content has no element at all.\n */\nexport function cloneTemplateRoot(template: HTMLTemplateElement): HTMLElement | null {\n const root = template.content.firstElementChild;\n return root instanceof HTMLElement ? (root.cloneNode(true) as HTMLElement) : null;\n}\n\n/** What a consumer declares once about the rows it builds from a `<template>`. */\nexport interface TemplateRowOptions<R extends string, O extends string> {\n /** The controller identifier the row's parts are declared against. */\n readonly identifier: string;\n /** Target name the row itself carries. */\n readonly root: string;\n /** Target names the row must contain; the first one missing is the one reported. */\n readonly required: readonly R[];\n /** Target names the row may contain; a missing one resolves to `null`. */\n readonly optional?: readonly O[];\n /** Target name of the `<button>` whose authored `aria-label` names the row. */\n readonly button: string;\n /** What the widget did not do, e.g. `\"added no tag\"`. */\n readonly outcome: string;\n /** What the author wrote it in, e.g. `\"chip template\"`. */\n readonly noun: string;\n}\n\n/** One row: the element to append, the parts inside it, and its named button. */\nexport interface TemplateRowParts<R extends string, O extends string> {\n readonly root: HTMLElement;\n readonly slots: Readonly<Record<R, HTMLElement> & Record<O, HTMLElement | null>>;\n readonly button: HTMLButtonElement;\n}\n\n/**\n * Builds one row from an authored `<template>`, naming an unusable one once per connection.\n *\n * **The row is the template's only element, and it carries\n * {@link TemplateRowOptions.root} itself.** Cloning it alone ({@link cloneTemplateRoot})\n * makes what the caller appends exactly what a later `remove()` takes back; a row\n * wrapped in another element, or standing beside a second one, would leave that\n * other element behind on every removal — or never be rendered at all — so such a\n * template is refused rather than half-built.\n *\n * Parts resolve through the caller's own namespace, derived from the identifier\n * the controller is registered under, so a registration under any name reaches\n * the attributes that registration renders.\n *\n * A template that cannot produce a row yields `null` and changes nothing: what a\n * refused row means for the selection, the field, or the announcement stays with\n * the caller. The diagnostic names what is wrong — the element count, or the first\n * missing part — because the only other symptom is a widget that silently adds\n * nothing, and the causes a static check cannot see — a server-rendered template,\n * a name that renders empty from a missing translation — would have no diagnostic\n * anywhere. It is written once per connection, so one authoring mistake cannot\n * flood the console.\n *\n * @example\n * ```ts\n * readonly #rows = new TemplateRow({\n * identifier: this.identifier,\n * root: \"tag\",\n * required: [\"label\"],\n * button: \"remove\",\n * outcome: \"added no tag\",\n * noun: \"chip template\",\n * });\n *\n * connect(): void {\n * this.#rows.connect();\n * }\n * ```\n */\nexport class TemplateRow<R extends string, O extends string = never> {\n readonly #options: TemplateRowOptions<R, O>;\n #warned = false;\n\n constructor(options: TemplateRowOptions<R, O>) {\n this.#options = options;\n }\n\n /** The attribute selector for one declared part, in this controller's namespace. */\n selector(name: string): string {\n return targetSelector(this.#options.identifier, name);\n }\n\n /** Re-arms the once-per-connection diagnostic. */\n connect(): void {\n this.#warned = false;\n }\n\n /**\n * Names one missing part on the console, at most once per connection, and\n * returns `null` so a caller can hand it straight back.\n */\n report(missing: string): null {\n return this.#say(`lacks ${missing}`);\n }\n\n /** Writes one diagnostic per connection, saying what the template got wrong. */\n #say(problem: string): null {\n if (this.#warned) return null;\n this.#warned = true;\n const { identifier, outcome, noun } = this.#options;\n console.warn(`Stimeo UI: \"${identifier}\" ${outcome} because its ${noun} ${problem}.`);\n return null;\n }\n\n /**\n * Clones the row and resolves its parts, or names what the template got wrong\n * and returns `null`. `values` fills the button's authored `aria-label`.\n */\n instantiate(\n template: HTMLTemplateElement,\n values: Record<string, string | number>,\n ): TemplateRowParts<R, O> | null {\n const { root: rootName, required, optional, button: buttonName } = this.#options;\n const root = cloneTemplateRoot(template);\n if (!root?.matches(this.selector(rootName))) {\n return this.report(`${this.#article(rootName)} \"${rootName}\" root`);\n }\n // One element, and it is the row: anything beside it would be left behind by\n // a removal that takes the row back, which is the accumulation this contract\n // exists to stop. The row here is the one that was asked for, so the count is\n // what the diagnostic names — a missing part would point at the wrong element.\n const count = template.content.children.length;\n if (count !== 1) {\n return this.#say(`holds ${count} elements, and the row has to be its only one`);\n }\n // Required parts are resolved before they are written, so the declared shape\n // holds for every row returned at all — a missing one leaves through `report`\n // instead. The accumulator is keyed loosely because that ordering is what\n // makes the narrower return type true, and no index signature can say so.\n const slots: Record<string, HTMLElement | null> = {};\n for (const name of required) {\n const part = this.#resolve(root, name);\n if (!part) return this.report(`${this.#article(name)} \"${name}\" target`);\n slots[name] = part;\n }\n for (const name of optional ?? []) slots[name] = this.#resolve(root, name);\n const named = this.#resolve(root, buttonName);\n if (!(named instanceof HTMLButtonElement)) {\n return this.report(`${this.#article(buttonName)} \"${buttonName}\" target <button>`);\n }\n const button = named;\n const name = button.getAttribute(\"aria-label\")?.trim() ?? \"\";\n if (name === \"\") return this.report(`a non-empty aria-label on its \"${buttonName}\" target`);\n button.setAttribute(\"aria-label\", fillTemplate(name, values));\n return { root, slots, button } as TemplateRowParts<R, O>;\n }\n\n /** The row may be its own part; otherwise the first descendant carrying the target. */\n #resolve(root: HTMLElement, name: string): HTMLElement | null {\n return matchingPart(root, this.selector(name));\n }\n\n #article(name: string): string {\n return /^[aeiou]/i.test(name) ? \"an\" : \"a\";\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { actionSource } from \"../utils/action_source\";\nimport { announce, fillTemplate } from \"../utils/announce\";\nimport { ensureId } from \"../utils/aria_ids\";\nimport { hasModifierChord, isReservedArrowChord, logicalArrowKey } from \"../utils/arrow_step\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { setAttributeIfChanged } from \"../utils/attribute_write\";\nimport { ChipRow } from \"../utils/chip_row\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\nimport { matchingPart, readLabel, writeLabel } from \"../utils/element_part\";\nimport { commitField, writeFields } from \"../utils/field_mirror\";\nimport { ListenerSet } from \"../utils/listener_set\";\nimport { MorphRenderWatcher } from \"../utils/morph_render_watcher\";\nimport { MoveCounter } from \"../utils/move_counter\";\nimport { NUMBER_BOUNDS, type NumberValueConstraints } from \"../utils/number_bounds\";\nimport { NumberValueReader } from \"../utils/number_value\";\nimport { scrollOptionIntoView } from \"../utils/option_scroll\";\nimport type { StateReason } from \"../utils/state_reason\";\nimport { StateRegions } from \"../utils/state_regions\";\nimport { TabindexLoan } from \"../utils/tabindex_loan\";\nimport { targetSelector } from \"../utils/target_selector\";\nimport { TemplateRow } from \"../utils/template_row\";\n\n/**\n * Headless, accessible multi-select combobox with chips.\n *\n * Selection fields, chips and keyboard stops are settled before notification.\n * Confirmations compare with the last published selection; synchronous replacement\n * selections suppress the older notifications and announcements still pending.\n *\n * Markup contract (identifier: `stimeo--multi-select`):\n * <div data-controller=\"stimeo--multi-select\"\n * data-stimeo--multi-select-announce-text-value=\"{label} selected; {count} total\"\n * data-stimeo--multi-select-announce-removed-text-value=\"{label} removed; {count} total\">\n * <ul data-stimeo--multi-select-target=\"tags\" aria-label=\"Selected\"></ul>\n * <input type=\"text\" role=\"combobox\" aria-expanded=\"false\"\n * aria-autocomplete=\"list\" aria-controls=\"ms-list\"\n * data-stimeo--multi-select-target=\"input\"\n * data-action=\"input->stimeo--multi-select#filter\n * keydown->stimeo--multi-select#onKeydown\n * focus->stimeo--multi-select#open\" />\n * <ul id=\"ms-list\" role=\"listbox\" aria-multiselectable=\"true\" hidden\n * data-stimeo--multi-select-target=\"list\">\n * <li id=\"ms-opt-1\" role=\"option\" aria-selected=\"false\" data-value=\"apple\"\n * data-stimeo--multi-select-target=\"option\"\n * data-action=\"click->stimeo--multi-select#toggleOption\">Apple</li>\n * </ul>\n * <!-- Optional: the message shown while the open list has no match. -->\n * <p data-stimeo--multi-select-target=\"empty\" hidden>No fruits match</p>\n * <!-- Optional: submit the selection as name=\"fruits[]\" hidden inputs. -->\n * <div data-stimeo--multi-select-target=\"fields\"></div>\n * <template data-stimeo--multi-select-target=\"tagTemplate\">\n * <li data-stimeo--multi-select-target=\"tag\">\n * <span data-stimeo--multi-select-target=\"label\"></span>\n * <button type=\"button\" tabindex=\"-1\" aria-label=\"Remove {label}\"\n * data-stimeo--multi-select-target=\"remove\">×</button>\n * </li>\n * </template>\n * </div>\n *\n * Implements the WAI-ARIA APG **Combobox** pattern in its list-autocomplete,\n * multi-select form. Focus stays on the input; the active option is tracked with\n * `aria-activedescendant` and selection with `aria-selected`. Selected options are\n * mirrored as removable chips. For single selection use `stimeo--listbox` or\n * `stimeo--combobox`; for free-text tags use `stimeo--tags-input`.\n *\n * Behavior provided:\n * - Typing filters options by substring and opens the list; `ArrowDown`/`ArrowUp`\n * (wrapping), `Home`/`End` move the active option; `Enter` toggles it (the list\n * stays open); `Escape`/`Tab`/outside click close.\n * - Toggling syncs `aria-selected`, expands the author-localized remove-button\n * name from the chip template, adds/removes the chip, sends localized text to\n * the shared announcer, and dispatches\n * `stimeo--multi-select:change` with `values`; filtering dispatches\n * `stimeo--multi-select:filter` for async candidates. Option churn or a lowered\n * `max` that moves the selection without a user edit is reported as\n * `stimeo--multi-select:reconcile`, carrying the same `values` detail.\n * - The chips are one roving Tab stop: `ArrowLeft`/`ArrowRight` move between them,\n * `Delete`/`Backspace` remove the focused chip, and `Backspace` on an empty\n * input removes the last and keeps input focus; removal from a chip re-homes\n * focus to a neighbor or the input.\n * The current `tags` container defines horizontal direction for the chips and input boundary.\n * - An open list with nothing left to offer is reported on the root as\n * `data-stimeo--multi-select-empty`, and any declared `empty` region is shown\n * for exactly that state and hidden for its opposite, whatever the markup\n * authored: this controller owns the region's `hidden` and writes it at every\n * reflection of the state, including the one a region gets as it connects.\n * - `max` is a permanent selection invariant across initial markup, interaction,\n * runtime options, and runtime cap changes (`0` = unlimited).\n * - With a `fields` target the selected values are mirrored into named hidden\n * inputs (default name `options[]`), so the selection submits with a normal\n * form and no consumer JS — parity with `stimeo--tags-input`. An optional\n * `form` value sets the hidden inputs' `form` attribute, associating them with a\n * `<form>` by id even when the picker lives outside it. Without a `fields`\n * target the hidden inputs are simply not written. A selection the controller\n * changes — a user's choice or a `toggleOption()` call — emits a native bubbling\n * `change` from the container, the way a form control does, so\n * `stimeo--auto-submit` and form-level validation hear it; the rebuilds that\n * follow connect, a replacement container, option churn, or a `name` / `form`\n * change stay silent.\n * `change` dispatches `{ values: string[], reason: StateReason }`;\n * `reconcile` carries `{ values }`. `filter` dispatches `{ query: string }`.\n */\nexport class MultiSelectController extends Controller<HTMLElement> {\n /** Numeric read boundaries share one reader for this controller instance. */\n readonly #numbers = new NumberValueReader();\n\n /** Identifies the latest published state transition. */\n readonly #moves = new MoveCounter();\n\n static override targets = [\n \"input\",\n \"list\",\n \"option\",\n \"tags\",\n \"tag\",\n \"tagTemplate\",\n \"label\",\n \"remove\",\n \"fields\",\n \"empty\",\n ];\n static override values = {\n max: { type: Number, default: 0 },\n name: { type: String, default: \"options[]\" },\n form: { type: String, default: \"\" },\n announceText: { type: String, default: \"\" },\n announceRemovedText: { type: String, default: \"\" },\n };\n\n static valueConstraints = {\n max: NUMBER_BOUNDS.finite,\n } satisfies NumberValueConstraints<typeof MultiSelectController.values>;\n static actions = [\"close\", \"filter\", \"onKeydown\", \"open\", \"toggleOption\"] as const;\n static events = [\"change\", \"filter\", \"reconcile\"] as const;\n\n declare readonly inputTarget: HTMLInputElement;\n declare readonly inputTargets: HTMLInputElement[];\n declare readonly listTarget: HTMLElement;\n declare readonly listTargets: HTMLElement[];\n declare readonly optionTargets: HTMLElement[];\n declare readonly emptyTargets: HTMLElement[];\n declare readonly tagsTarget: HTMLElement;\n declare readonly tagTargets: HTMLElement[];\n declare readonly tagTemplateTarget: HTMLTemplateElement;\n declare readonly labelTargets: HTMLElement[];\n declare readonly removeTargets: HTMLButtonElement[];\n declare readonly fieldsTarget: HTMLElement;\n declare readonly hasListTarget: boolean;\n declare readonly hasInputTarget: boolean;\n declare readonly hasTagsTarget: boolean;\n declare readonly hasTagTemplateTarget: boolean;\n declare readonly hasFieldsTarget: boolean;\n\n declare maxValue: number;\n declare nameValue: string;\n declare formValue: string;\n declare readonly hasFormValue: boolean;\n declare announceTextValue: string;\n declare announceRemovedTextValue: string;\n\n /** Stable id of the active option; the current target is resolved from the DOM. */\n #activeOptionId: string | null = null;\n /** Whether the root borrowed a tab stop to catch focus, so teardown can undo it. */\n readonly #tabindex = new TabindexLoan(\"-1\", this.identifier);\n /** Last reconciled selection, used to distinguish state changes from derived-DOM repair. */\n #selectionValues: string[] = [];\n /** Whether initial normalization finished, so a fields callback cannot mirror stale state. */\n #connected = false;\n /** Owns `hidden` on the regions declared for the empty-result state. */\n readonly #emptyRegion = new StateRegions({ whenTrue: () => this.emptyTargets }, this.identifier);\n /** Borrows `hidden` on the list, to give back when an element stops being the list. */\n readonly #listHidden = new AttributeLease<HTMLElement>(\"hidden\", this.identifier);\n /** Borrows `aria-expanded` on the input, to give back when an element stops being the input. */\n readonly #expanded = new AttributeLease<HTMLElement>(\"aria-expanded\", this.identifier);\n /** Borrows `aria-activedescendant` on the input, for the same return. */\n readonly #activeDescendant = new AttributeLease<HTMLElement>(\n \"aria-activedescendant\",\n this.identifier,\n );\n /** Whether this widget holds the list open; a list that takes over is shown to match. */\n #open = false;\n /** The list the open state was last applied to; `null` once it stops being the list. */\n #openList: HTMLElement | null = null;\n /** Collapses one batch of target callbacks into a single final-DOM reconciliation. */\n readonly #reconcile = new MorphRenderWatcher(() => this.#reconcileOptions());\n /** Owns IME lifecycle state; confirmed text emits one filter result. */\n readonly #composition = new CompositionTracker({\n // Apply the confirmed query even in browsers that omit a final input event;\n // where one follows, the tracker folds it so consumers receive one filter\n // event for the confirmed text, not two.\n onEnd: () => this.filter(),\n });\n /** Builds one chip from the authored template and owns its diagnostic. */\n readonly #rows = new TemplateRow({\n identifier: this.identifier,\n root: \"tag\",\n required: [\"label\"],\n button: \"remove\",\n outcome: \"changed no selection\",\n noun: \"chip template\",\n });\n /** Shared delegated interaction for the replaceable row of removable chips. */\n readonly #chipRow = new ChipRow({\n getDirectionElement: () => this.#chipDirectionElement,\n getItems: () => this.tagTargets,\n getButton: (tag) =>\n matchingPart<HTMLButtonElement>(tag, `button${this.#rows.selector(\"remove\")}`),\n onRemove: (index) => this.#removeTagAt(index),\n focusAfterEnd: () => this.#focusInput(),\n });\n\n /** The listeners of one connection, released together on `disconnect()`. */\n readonly #listeners = new ListenerSet();\n\n /** Associates chip Tab with its next focus action. */\n #tab: Event | null = null;\n\n /** Starts closed, syncs chips for any pre-selected options, and listens out. */\n override connect(): void {\n this.#tab = null;\n this.#tabindex.reclaim(this.element);\n this.#rows.connect();\n // A fresh connection has no prior selection to preserve: deterministic DOM\n // order decides which authored selections survive a finite max.\n this.#normalizeSelection([]);\n this.close();\n if (this.hasTagsTarget) {\n this.#chipRow.connect(this.tagsTarget);\n this.#rebuildTags();\n }\n this.#selectionValues = this.#values;\n // Seed the hidden fields from any pre-selected options so the form submits\n // the initial selection without an interaction.\n this.#syncFields();\n this.#listeners.add(document, \"click\", this.#onOutsideClick, { capture: true });\n this.#listeners.add(this.element, \"keydown\", this.#onTab);\n for (const type of [\"focus\", \"keydown\", \"keyup\", \"pointerdown\"] as const)\n this.#listeners.add(document, type, this.#trackTab, { capture: true });\n this.#connected = true;\n this.#reconcile.observe(this.element);\n }\n\n /**\n * Derives the chips from the selected options, idempotently: a Turbo Drive cache\n * restore or morph can re-connect with chips already in the DOM, so they are\n * cleared before deriving afresh to avoid duplicates.\n */\n #rebuildTags(): void {\n if (!this.hasTagsTarget || !this.hasTagTemplateTarget) return;\n const chips: HTMLElement[] = [];\n for (const option of this.#selectedOptions) {\n const chip = this.#buildTag(option);\n if (!chip) return;\n chips.push(chip);\n }\n for (const tag of this.tagTargets) tag.remove();\n this.tagsTarget.append(...chips);\n this.#chipRow.ensureTabStop();\n }\n\n /** Tears down document and chip listeners on disconnect (Turbo included). */\n override disconnect(): void {\n this.#connected = false;\n this.#reconcile.disconnect();\n this.#composition.disconnect();\n this.#chipRow.disconnect();\n this.#listeners.dispose();\n this.#tab = null;\n this.#releaseTabindex();\n }\n\n /** Reconciles active state after an option target is added at runtime. */\n optionTargetConnected(): void {\n this.#scheduleOptionReconcile();\n }\n\n /** Cleans a removed target and reconciles active state against the surviving DOM. */\n optionTargetDisconnected(option: HTMLElement): void {\n // `#setActive` can only scan current targets; clean the old node explicitly in\n // case a Turbo morph reuses it elsewhere.\n option.removeAttribute(\"data-active\");\n this.#scheduleOptionReconcile();\n }\n\n /** Settles a region inserted after connect on the side of the current state. */\n emptyTargetConnected(): void {\n if (this.#connected) this.#reflectEmpty();\n }\n\n /** Rebinds delegated chip interaction when Turbo replaces the tags container. */\n tagsTargetConnected(tags: HTMLElement): void {\n this.#chipRow.connect(tags);\n this.#scheduleOptionReconcile();\n }\n\n /** Releases only the row that actually disconnected, never a newer replacement. */\n tagsTargetDisconnected(tags: HTMLElement): void {\n this.#chipRow.disconnect(tags);\n this.#scheduleOptionReconcile();\n }\n\n /** Seeds a fields target inserted after connect from the current selection. */\n fieldsTargetConnected(): void {\n if (this.#connected) this.#syncFields();\n }\n\n /** Seeds the fields target that stays when an earlier one leaves, in the next reconcile. */\n fieldsTargetDisconnected(): void {\n this.#scheduleOptionReconcile();\n }\n\n /** Brings the list that is first to the open state, then reconciles options. */\n listTargetConnected(_list: HTMLElement): void {\n if (!this.#connected) return;\n this.#reconcileOpenState();\n this.#scheduleOptionReconcile();\n }\n\n /**\n * Gives a list that no longer resolves as one back its `hidden` — after `disconnect()`\n * too, since dropping the identifier leaves the element on the page — and, while\n * connected, brings the list that stays to the open state. A departing list the state\n * was applied to, found hidden while open, was closed by the page; that is read before\n * its own `hidden` comes back.\n */\n listTargetDisconnected(list: HTMLElement): void {\n if (!this.listTargets.includes(list)) {\n if (list === this.#openList) {\n this.#adoptPageClose();\n this.#openList = null;\n }\n this.#listHidden.return(list);\n }\n if (!this.#connected) return;\n this.#reconcileOpenState();\n this.#scheduleOptionReconcile();\n }\n\n /** Reconciles a runtime max change, including dropping any newly invalid overflow. */\n maxValueChanged(): void {\n this.#scheduleOptionReconcile();\n }\n\n /** Rebuilds submitted fields when their public name changes at runtime. */\n nameValueChanged(): void {\n this.#scheduleOptionReconcile();\n }\n\n /** Rebuilds submitted fields when their associated form changes at runtime. */\n formValueChanged(): void {\n this.#scheduleOptionReconcile();\n }\n\n /** Schedules one reconciliation after all callbacks in the mutation batch. */\n #scheduleOptionReconcile(): void {\n this.#reconcile.schedule();\n }\n\n /**\n * Keeps a surviving/same-id active target, otherwise falls back to the first\n * visible one — and brings the derived state back in line with the new option set.\n *\n * The baseline pass fills in any missing `aria-selected`, and the chips and\n * hidden fields are re-derived from it, because the options are the truth source\n * for the selection. The chips are rebuilt only when their current value set\n * differs from the selected option values. Rebuilding removes and recreates\n * every chip, so doing it for an unrelated option would drop focus from a chip's\n * remove button to `<body>`, losing the keyboard user's place for something that\n * did not concern them.\n *\n * @stimeoRenderRoot\n */\n #reconcileOptions(): void {\n const visible = this.#visibleOptions;\n const active = this.#activeOption;\n const next = this.#isClosed ? null : active && !active.hidden ? active : (visible[0] ?? null);\n this.#setActive(next);\n this.#reflectEmpty();\n\n const previous = this.#selectionValues;\n const previousLabels = new Map(\n this.tagTargets.map((tag) => [\n tag.dataset.value ?? \"\",\n readLabel(matchingPart(tag, this.#rows.selector(\"label\"))),\n ]),\n );\n // Prefer the interaction order represented by live chips. A tags target can\n // be replaced with an empty container, so the last reconciled option set is\n // the fallback that prevents a derived-DOM repair from evicting user choices.\n const priority = [\n ...new Set([...this.tagTargets.map((tag) => tag.dataset.value ?? \"\"), ...previous]),\n ];\n this.#normalizeSelection(priority);\n const selected = this.#selectedOptions;\n // Compared as a set, not a sequence: the chips are in selection order while\n // the options are in DOM order, so an index-wise comparison reports a change\n // for every selection the user made out of DOM order and rebuilds forever.\n const nextValues = selected.map((option) => this.#optionValue(option)).sort();\n const tagValues = this.tagTargets.map((tag) => tag.dataset.value ?? \"\").sort();\n const unchanged =\n nextValues.length === tagValues.length &&\n nextValues.every((value, index) => value === tagValues[index]);\n if (unchanged) this.#refreshTagLabels(selected);\n else this.#rebuildTags();\n this.#syncFields();\n\n const values = this.#values;\n const changed = !this.#sameSelection(previous, values);\n this.#selectionValues = values;\n if (!changed) return;\n const token = this.#moves.record();\n\n const options = new Map(selected.map((option) => [this.#optionValue(option), option]));\n for (const value of previous) {\n if (!this.#moves.isLatest(token)) return;\n if (!values.includes(value)) {\n this.#announceTransition(false, previousLabels.get(value) || value, value, values.length);\n }\n }\n for (const value of values) {\n if (!this.#moves.isLatest(token)) return;\n if (previous.includes(value)) continue;\n // `values` is derived from `selected`, so this lookup is total.\n const option = options.get(value) as HTMLElement;\n this.#announceTransition(true, this.#optionLabel(option), value, values.length);\n }\n // Runtime option churn and the `max` cap move the selection by this\n // controller's rules, so the repair is reported apart from `change`, which\n // stays reserved for the user's own add and remove.\n if (!this.#moves.isLatest(token)) return;\n this.dispatch(\"reconcile\", { detail: { values } });\n }\n\n /**\n * Gives every option an explicit `aria-selected` and enforces the current cap.\n * Priority preserves existing chip order at runtime; a fresh connection passes\n * no priority, so deterministic option DOM order chooses the initial survivors.\n */\n #normalizeSelection(priority: readonly string[]): void {\n const selected = this.optionTargets.filter(\n (option) => option.getAttribute(\"aria-selected\") === \"true\",\n );\n const limit = this.#selectionLimit;\n const kept = new Set<HTMLElement>();\n\n if (limit === 0) {\n for (const option of selected) kept.add(option);\n } else {\n for (const value of priority) {\n if (kept.size >= limit) break;\n const option = selected.find(\n (candidate) => !kept.has(candidate) && this.#optionValue(candidate) === value,\n );\n if (option) kept.add(option);\n }\n for (const option of selected) {\n if (kept.size >= limit) break;\n kept.add(option);\n }\n }\n\n for (const option of this.optionTargets) {\n option.setAttribute(\"aria-selected\", String(kept.has(option)));\n }\n }\n\n /**\n * Tracks an input added initially or after connect, and makes it describe the\n * widget that is actually on screen: a swapped-in input arrives with the\n * authored ARIA of a fresh node while this controller still holds the popup\n * state, and the open path cannot repair that (it seeds an active option only\n * when there is none), so a live list would go unannounced.\n */\n inputTargetConnected(input: HTMLInputElement): void {\n this.#composition.observe(input);\n this.#describeInput(input);\n }\n\n /**\n * Removes the departing input's composition listeners and gives an input that no\n * longer resolves as one back its `aria-expanded` and `aria-activedescendant`, after\n * `disconnect()` too. While connected, it describes the widget to the input that\n * stays, which the popup state may have moved past while both were present.\n */\n inputTargetDisconnected(input: HTMLInputElement): void {\n this.#composition.unobserve(input);\n if (!this.inputTargets.includes(input)) {\n this.#expanded.return(input);\n this.#activeDescendant.return(input);\n }\n if (this.#connected && this.hasInputTarget) this.#describeInput(this.inputTarget);\n }\n\n /** Writes the popup state and the active option onto `input`. */\n #describeInput(input: HTMLInputElement): void {\n this.#expanded.write(input, String(!this.#isClosed));\n const active = this.#activeOption;\n this.#activeDescendant.write(input, active ? ensureId(active, \"stimeo-ms-opt\") : null);\n }\n\n /**\n * Brings the list and the input that are first to one open state. A list that takes\n * over from the one the state was applied to is shown or hidden to match it; the list\n * it was applied to, found hidden while open, was closed by the page. The input's\n * `aria-expanded` then follows the list. With no list left, nothing is written.\n */\n #reconcileOpenState(): void {\n if (!this.hasListTarget) return;\n this.#adoptPageClose();\n const list = this.listTarget;\n if (list !== this.#openList) {\n this.#showList(list, this.#open);\n this.#openList = list;\n }\n if (this.hasInputTarget) this.#expanded.write(this.inputTarget, String(!list.hidden));\n }\n\n /** Treats the widget as closed when the list the open state was applied to is hidden. */\n #adoptPageClose(): void {\n if (this.#openList?.hidden) this.#open = false;\n }\n\n /** Filters confirmed input text, opens, and re-seeds the active option. */\n filter(event?: InputEvent): void {\n if (!this.hasInputTarget) return;\n if (event && this.#composition.consumesConfirmedInput(event)) return;\n if (this.#composition.isComposing(event)) return;\n const query = this.inputTarget.value.trim().toLowerCase();\n for (const option of this.optionTargets) {\n const label = (option.textContent ?? \"\").trim().toLowerCase();\n option.hidden = query !== \"\" && !label.includes(query);\n }\n this.open();\n const visible = this.#visibleOptions;\n this.#setActive(visible[0] ?? null);\n this.dispatch(\"filter\", { detail: { query } });\n }\n\n /**\n * Opens the list and activates the first visible option when none is active.\n *\n * Needs the input, which owns `aria-expanded` and `aria-activedescendant`: a\n * list shown without one is a popup no assistive technology is told about. So\n * opening is skipped entirely, where {@link MultiSelectController.close | close}\n * still closes.\n * A focus action delivered by chip Tab keeps the list closed.\n */\n open(event?: Event): void {\n if (event instanceof FocusEvent && event === this.#tab) {\n this.#tab = null;\n return;\n }\n if (!this.hasListTarget || !this.hasInputTarget) {\n this.#reflectEmpty();\n return;\n }\n this.#showList(this.listTarget, true);\n this.#open = true;\n this.#openList = this.listTarget;\n this.#expanded.write(this.inputTarget, \"true\");\n if (!this.#activeOption) this.#setActive(this.#visibleOptions[0] ?? null);\n this.#reflectEmpty();\n }\n\n /**\n * Closes the list and clears the active option.\n *\n * Survives a missing input in both directions. `connect()` calls this before it\n * builds the chips, so dereferencing the input here would throw before the chips,\n * the roving seed, the chip listeners, the hidden fields and the outside-click\n * listener — and Stimulus keeps the controller alive after that throw, so none of\n * them would ever run and the selection would silently stop submitting. An input\n * removed while the list is open must still let it come down *and* forget its\n * active option, so only the `aria-expanded` write is guarded.\n */\n close(): void {\n this.#open = false;\n if (this.hasListTarget) {\n this.#showList(this.listTarget, false);\n this.#openList = this.listTarget;\n }\n this.#setActive(null);\n if (this.hasInputTarget) this.#expanded.write(this.inputTarget, \"false\");\n this.#reflectEmpty();\n }\n\n /** Routes input keyboard interaction per the multi-select combobox model. */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key must not ALSO open the\n // list or move the active option — composition depends on this yield.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n if ((event.key === \"Home\" || event.key === \"End\") && hasModifierChord(event)) return;\n if (!this.hasInputTarget) return;\n // Ignore keys fired during IME composition: the `Enter` that confirms a\n // candidate (and arrows that move within it) must not select an option or\n // navigate the chip list. Controller-owned lifecycle state covers confirming\n // events that omit the standard per-event signal.\n if (this.#composition.isComposing(event)) return;\n // Target callbacks are MutationObserver-driven. Resolve a replacement now, or\n // clear a removed id now, so a synchronously dispatched key cannot commit a\n // detached node before the callback gets its turn.\n this.#reconcileActiveForInteraction();\n // The tags container defines the same logical boundary as its chip buttons.\n switch (logicalArrowKey(event.key, this.#chipDirectionElement)) {\n case \"ArrowDown\":\n event.preventDefault();\n if (this.#isClosed) this.open();\n else this.#moveActive(1);\n break;\n case \"ArrowUp\":\n event.preventDefault();\n if (this.#isClosed) this.open();\n else this.#moveActive(-1);\n break;\n case \"Home\":\n if (!this.#isClosed) {\n event.preventDefault();\n this.#setActive(this.#visibleOptions[0] ?? null);\n }\n break;\n case \"End\": {\n if (!this.#isClosed) {\n event.preventDefault();\n const visible = this.#visibleOptions;\n this.#setActive(visible[visible.length - 1] ?? null);\n }\n break;\n }\n case \"Enter\": {\n const active = this.#activeOption;\n if (!this.#isClosed && active) {\n event.preventDefault();\n this.#toggleSelection(active);\n }\n break;\n }\n case \"Escape\":\n // A press an inner handler already owned is yielded at the top of this\n // handler. Escape is consumed only while the list is open: with it closed\n // the press stays free for the shared resolver, so an enclosing dialog\n // still closes from a focused input.\n if (this.#isClosed) break;\n event.preventDefault();\n this.close();\n break;\n case \"Backspace\":\n if (this.inputTarget.value === \"\") {\n const last = this.#chipRow.lastIndex;\n if (last >= 0) {\n event.preventDefault();\n this.#removeTagAt(last, \"input\");\n }\n }\n break;\n case \"ArrowLeft\":\n if (this.inputTarget.value === \"\" && this.#chipRow.length > 0) {\n event.preventDefault();\n this.#chipRow.focusLast();\n }\n break;\n case \"Tab\":\n this.close();\n break;\n default:\n break;\n }\n }\n\n /** Closes on chip Tab without moving focus. */\n readonly #onTab = (event: KeyboardEvent): void => {\n if (\n event.key !== \"Tab\" ||\n event.defaultPrevented ||\n event.isComposing ||\n !this.hasTagsTarget ||\n !this.tagsTarget.contains(event.target as Node)\n )\n return;\n this.#tab = event;\n this.close();\n };\n\n /** Associates the next input focus with chip Tab; other gestures release it. */\n readonly #trackTab = (event: Event): void => {\n const key = this.#tab;\n this.#tab =\n event.type === \"focus\" &&\n key instanceof KeyboardEvent &&\n !key.defaultPrevented &&\n event.target === this.inputTargets[0]\n ? event\n : null;\n };\n\n /**\n * Toggles an owned option or descendant. For action events, focus is\n * re-homed to the input afterwards: options are non-focusable, so the click blurs\n * the input to `body` — and with the list deliberately staying open, every\n * keyboard affordance (Escape, arrows, typing) is bound to the input and would\n * otherwise go dead until the user clicks back in (\"focus stays on the input\").\n */\n toggleOption(source: Event | HTMLElement): void {\n const { event, host, origin, reason } = actionSource(source);\n if (origin && origin.closest(`[data-controller~=\"${this.identifier}\"]`) !== this.element)\n return;\n const option = host?.closest<HTMLElement>(targetSelector(this.identifier, \"option\"));\n if (!option || !this.optionTargets.includes(option)) return;\n const focus = event !== null || this.element.contains(document.activeElement);\n if (!this.#toggleSelection(option, reason)) return;\n if (focus && (event !== null || this.element.contains(document.activeElement)))\n this.#focusInput();\n }\n\n /** Current tags container, or the root while the target is absent. */\n get #chipDirectionElement(): HTMLElement {\n return this.hasTagsTarget ? this.tagsTarget : this.element;\n }\n\n /** Re-homes focus to the input, or leaves it where it is when there is none. */\n #focusInput(): void {\n if (this.hasInputTarget) this.inputTarget.focus();\n }\n\n /**\n * Re-homes focus after the last chip was removed: to the input, else the root.\n *\n * Unlike the other {@link #focusInput} callers, the element that held focus has\n * just left the DOM, so \"leave it alone\" is not an option — the browser already\n * dropped it to `<body>`. The root borrows a `tabindex=\"-1\"` just-in-time (not a\n * Tab stop, returned on teardown or reclaimed on restoration). Focus that landed\n * on a real element is left alone, so a chip removed out of band never steals it.\n */\n #focusAfterLastTag(): void {\n if (this.hasInputTarget) {\n this.inputTarget.focus();\n return;\n }\n const doc = this.element.ownerDocument;\n const active = doc.activeElement;\n // Anything else still holding focus keeps it; only `<body>`, the root element\n // and a detached node mean the browser had nowhere to put it.\n if (active && active !== doc.body && active !== doc.documentElement && active.isConnected) {\n return;\n }\n this.#tabindex.lend(this.element);\n this.element.focus();\n }\n\n /**\n * Returns the borrowed tab stop. Owning the borrow is not enough — the value\n * has to still be the one this instance wrote, since a consumer that changed it\n * afterwards owns it now.\n */\n #releaseTabindex(): void {\n this.#tabindex.returnAll();\n }\n\n /** Moves the active option by `delta` among visible options, wrapping. */\n #moveActive(delta: number): void {\n const visible = this.#visibleOptions;\n const active = this.#activeOption;\n // `null` is the deliberate \"not found\" sentinel; Array#indexOf accepts it\n // at runtime and returns -1, although this array's static item type excludes it.\n const current = visible.indexOf(active as HTMLElement);\n const candidate = current === -1 ? (delta > 0 ? 0 : visible.length - 1) : current + delta;\n const next = (candidate + visible.length) % visible.length;\n this.#setActive(visible[next] ?? null);\n }\n\n /** Selects/deselects `option`, honoring `max`, and syncs chip + announcement. */\n #toggleSelection(option: HTMLElement, reason: StateReason = \"user\"): boolean {\n const selected = option.getAttribute(\"aria-selected\") === \"true\";\n const limit = this.#selectionLimit;\n if (!selected && limit > 0 && this.#selectedOptions.length >= limit) {\n return true;\n }\n if (selected) {\n option.setAttribute(\"aria-selected\", \"false\");\n this.#removeTagFor(option);\n } else {\n // Chips are a display affordance here, not the value model: the selection\n // lives on `aria-selected` and the hidden fields, so a field authored\n // without a chip template still selects. An authored template that cannot\n // be completed is the opposite case — leaving a selection whose chip is\n // missing would be the half-applied state, so that one aborts instead.\n if (this.hasTagTemplateTarget && !this.#appendTag(option)) return true;\n option.setAttribute(\"aria-selected\", \"true\");\n }\n this.#refreshRoving();\n return this.#publishSelection(\n !selected,\n this.#optionLabel(option),\n this.#optionValue(option),\n reason,\n );\n }\n\n /**\n * Re-reads each chip's label from its option, in place.\n *\n * The value order alone does not say the chips are still correct: a server can\n * re-render the same candidate with a new label (\"Apple\" → \"Green Apple\"), and\n * the chip text and its `Remove {label}` name are both derived from the option.\n * Updating them here avoids a focus-losing rebuild when the chip values already\n * match the selected option values.\n */\n #refreshTagLabels(selected: readonly HTMLElement[]): void {\n // Paired by value rather than by position: the chips are in selection order\n // and the options in DOM order, so the two lists hold the same values in\n // different places and an index-wise pairing would relabel the wrong chip.\n const options = new Map(selected.map((option) => [this.#optionValue(option), option]));\n for (const tag of this.tagTargets) {\n // The caller established equal selected/tag value sets before refreshing.\n const option = options.get(tag.dataset.value ?? \"\") as HTMLElement;\n const text = this.#optionLabel(option);\n const label = matchingPart(tag, this.#rows.selector(\"label\"));\n const button = matchingPart<HTMLButtonElement>(tag, `button${this.#rows.selector(\"remove\")}`);\n const name = this.#removeName(text, this.#optionValue(option));\n // Relabelling is one transaction, like building the chip is. Writing the\n // visible text without its accessible name would leave the button naming\n // a value the chip no longer shows, so a name this template cannot produce\n // holds the old text in place too.\n if (!label || !button || !name) continue;\n if (readLabel(label) !== text) writeLabel(label, text);\n setAttributeIfChanged(button, \"aria-label\", name);\n }\n }\n\n /** Builds one chip from the template for `option`. */\n #appendTag(option: HTMLElement): boolean {\n if (!this.hasTagsTarget) {\n this.#rows.report('a \"tags\" target to append the chip to');\n return false;\n }\n const chip = this.#buildTag(option);\n if (!chip) return false;\n this.tagsTarget.appendChild(chip);\n return true;\n }\n\n /**\n * Builds one fully named chip without mutating the live tag row, or `null`\n * when the authored template cannot produce one — in which case the selection\n * stays untouched and the row names the missing part once per connection.\n * Both callers establish the template first: a field authored without\n * `tagTemplate` renders no chips at all — a supported configuration — and\n * never reaches here.\n */\n #buildTag(option: HTMLElement): HTMLElement | null {\n const text = this.#optionLabel(option);\n const value = this.#optionValue(option);\n const row = this.#rows.instantiate(this.tagTemplateTarget, { label: text, value });\n if (!row) return null;\n row.root.dataset.value = value;\n writeLabel(row.slots.label, text);\n // Chip buttons are a single Tab stop the roving helper hands out.\n row.button.tabIndex = -1;\n return row.root;\n }\n\n /** Expands the current template's localized remove-button name. */\n #removeName(label: string, value: string): string | null {\n if (!this.hasTagTemplateTarget) return null;\n const template = this.tagTemplateTarget.content\n .querySelector<HTMLButtonElement>(`button${this.#rows.selector(\"remove\")}`)\n ?.getAttribute(\"aria-label\")\n ?.trim();\n return template ? fillTemplate(template, { label, value }) : null;\n }\n\n /** Removes the chip mirroring `option`, if present. */\n #removeTagFor(option: HTMLElement): void {\n const value = this.#optionValue(option);\n const tag = this.tagTargets.find((candidate) => candidate.dataset.value === value);\n tag?.remove();\n }\n\n /** Removes chip `index` and deselects its option, re-homing focus. */\n #removeTagAt(index: number, focus: \"neighbor\" | \"input\" = \"neighbor\"): void {\n const tag = this.tagTargets[index];\n if (!tag) return;\n const value = tag.dataset.value ?? \"\";\n // Match by the option's stable value, which falls back to its label when no\n // data-value is present, so a label-keyed chip still finds its option.\n const option = this.optionTargets.find((candidate) => this.#optionValue(candidate) === value);\n if (option) option.setAttribute(\"aria-selected\", \"false\");\n tag.remove();\n // Prefer the option's display label for the announcement (e.g. \"Apple\"),\n // which can differ from its data-value (e.g. \"apple\").\n this.#refreshRoving();\n if (!this.#publishSelection(false, option ? this.#optionLabel(option) : value, value)) return;\n\n if (focus === \"input\") {\n this.#focusInput();\n return;\n }\n if (!this.#chipRow.focusAfterRemoval(index)) this.#focusAfterLastTag();\n }\n\n /**\n * Marks `option` active via `data-active` and the input's\n * `aria-activedescendant` (the attribute is removed, not emptied, when null).\n *\n * The state half runs even with no input, so a `close()` that cannot touch ARIA\n * still clears it: {@link MultiSelectController.open | open} seeds an active\n * option only when there is none, so a stale one makes the next open skip the\n * seeding and a replacement input gets no `aria-activedescendant` at all.\n */\n #setActive(option: HTMLElement | null): void {\n const activeId = option ? ensureId(option, \"stimeo-ms-opt\") : null;\n this.#activeOptionId = activeId;\n for (const candidate of this.optionTargets) {\n candidate.toggleAttribute(\"data-active\", candidate === option);\n }\n // Virtual focus never triggers the browser's native focus-scrolling, so a\n // scrollable list must follow the active option itself (list-only scroll).\n if (option && this.hasListTarget) scrollOptionIntoView(this.listTarget, option);\n if (this.hasInputTarget) this.#activeDescendant.write(this.inputTarget, activeId);\n }\n\n /** Repairs only active identity before a key; the fallback waits for the target callback. */\n #reconcileActiveForInteraction(): void {\n const activeId = this.#activeOptionId;\n if (activeId === null) return;\n const resolved = this.#activeOption;\n const active = resolved && !resolved.hidden ? resolved : null;\n const marked = this.optionTargets.filter((candidate) => candidate.hasAttribute(\"data-active\"));\n // The only caller returns before reaching here when the input is absent.\n const idref = this.inputTarget.getAttribute(\"aria-activedescendant\");\n if (!active || marked.length !== 1 || marked[0] !== active || idref !== activeId) {\n this.#setActive(active);\n }\n }\n\n /**\n * Reflects whether the open list currently has no visible option targets, on\n * the root's state attribute and on the regions declared for that state.\n */\n #reflectEmpty(): void {\n const empty = !this.#isClosed && this.#visibleOptions.length === 0;\n this.element.toggleAttribute(`data-${this.identifier}-empty`, empty);\n this.#emptyRegion.reflect(this.element, empty);\n }\n\n /**\n * Mirrors the selected values into named hidden inputs under the `fields`\n * target so the selection submits with a normal form (parity with tags-input).\n * No-ops without a `fields` target. When the\n * `form` value is set, each input gets a matching `form` attribute so the picker\n * can submit with a `<form>` it lives outside of.\n */\n #syncFields(): boolean {\n if (!this.hasFieldsTarget) return false;\n const options = { name: this.nameValue, form: this.formValue };\n return writeFields(this.fieldsTarget, this.#values, options);\n }\n\n /** Settles the selection before its field, announcement and custom reports. */\n #publishSelection(\n selected: boolean,\n label: string,\n value: string,\n reason: StateReason = \"user\",\n ): boolean {\n const values = this.#values;\n const changed = !this.#sameSelection(this.#selectionValues, values);\n const fieldChanged = this.#syncFields();\n this.#selectionValues = values;\n if (!changed) return true;\n const token = this.#moves.record();\n if (fieldChanged) commitField(this.fieldsTarget);\n if (!this.#moves.isLatest(token)) return false;\n this.#announceTransition(selected, label, value, values.length);\n if (!this.#moves.isLatest(token)) return false;\n this.dispatch(\"change\", { detail: { values, reason } });\n return this.#moves.isLatest(token);\n }\n\n /** Keeps exactly one chip remove button tabbable after the set changes. */\n #refreshRoving(): void {\n this.#chipRow.ensureTabStop();\n }\n\n /**\n * Sends one localized selection transition through the page's shared announcer.\n *\n * @stimeoRuntimeOnly The texts word the one announcement of this change.\n */\n #announceTransition(selected: boolean, label: string, value: string, count: number): void {\n const template = selected ? this.announceTextValue : this.announceRemovedTextValue;\n announce(fillTemplate(template, { label, value, count }));\n }\n\n /** Whether two arrays represent the same selection set, independent of DOM order. */\n #sameSelection(left: readonly string[], right: readonly string[]): boolean {\n if (left.length !== right.length) return false;\n const a = [...left].sort();\n const b = [...right].sort();\n return a.every((value, index) => value === b[index]);\n }\n\n /** Closes the list on a click outside the controller element. */\n readonly #onOutsideClick = (event: MouseEvent): void => {\n if (!this.#isClosed && !this.element.contains(event.target as Node)) this.close();\n };\n\n /** Trimmed visible label of an option. */\n #optionLabel(option: HTMLElement): string {\n return (option.textContent ?? \"\").trim();\n }\n\n /** An option's stable value: its `data-value`, else its display label. */\n #optionValue(option: HTMLElement): string {\n return option.dataset.value ?? this.#optionLabel(option);\n }\n\n /** Options not hidden by the current filter. */\n get #visibleOptions(): HTMLElement[] {\n return this.optionTargets.filter((option) => !option.hidden);\n }\n\n /** Current active target resolved by stable id, never a detached node reference. */\n get #activeOption(): HTMLElement | null {\n return this.optionTargets.find((option) => option.id === this.#activeOptionId) ?? null;\n }\n\n /** Options currently selected. */\n get #selectedOptions(): HTMLElement[] {\n return this.optionTargets.filter((option) => option.getAttribute(\"aria-selected\") === \"true\");\n }\n\n /** Selected values in option order. */\n get #values(): string[] {\n return this.#selectedOptions.map((option) => this.#optionValue(option));\n }\n\n /**\n * Normalized cardinality cap: zero and below are unlimited; a positive value floors,\n * never below 1.\n */\n get #selectionLimit(): number {\n if (this.#safeMax <= 0) return 0;\n return Math.max(1, Math.floor(this.#safeMax));\n }\n\n /** Shows or hides `list` through the lease, so a departed list gets its authored value back. */\n #showList(list: HTMLElement, open: boolean): void {\n this.#listHidden.write(list, open ? null : \"\");\n }\n\n /** Whether the list is currently hidden. */\n get #isClosed(): boolean {\n return !this.hasListTarget || this.listTarget.hidden !== false;\n }\n /** Current `max` declaration resolved against its numeric contract. */\n get #safeMax(): number {\n return this.#numbers.read(\n this,\n \"max\",\n this.maxValue,\n MultiSelectController.values.max.default,\n MultiSelectController.valueConstraints.max,\n );\n }\n}\n"]}
|