stimeo-ui 0.2.1 → 0.3.0
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 +104 -0
- package/dist/cable/index.d.ts +16 -16
- package/dist/cable/index.js.map +1 -1
- package/dist/controllers/accordion_controller.js +10 -0
- package/dist/controllers/accordion_controller.js.map +1 -1
- package/dist/controllers/alert_dialog_controller.js.map +1 -1
- package/dist/controllers/breadcrumb_controller.d.ts +97 -10
- package/dist/controllers/breadcrumb_controller.js +225 -13
- package/dist/controllers/breadcrumb_controller.js.map +1 -1
- package/dist/controllers/calendar_controller.d.ts +11 -1
- package/dist/controllers/calendar_controller.js +89 -22
- package/dist/controllers/calendar_controller.js.map +1 -1
- package/dist/controllers/carousel_controller.d.ts +16 -1
- package/dist/controllers/carousel_controller.js +47 -6
- package/dist/controllers/carousel_controller.js.map +1 -1
- package/dist/controllers/collapsible_controller.js +2 -2
- package/dist/controllers/collapsible_controller.js.map +1 -1
- package/dist/controllers/color_picker_controller.d.ts +12 -1
- package/dist/controllers/color_picker_controller.js +46 -7
- package/dist/controllers/color_picker_controller.js.map +1 -1
- package/dist/controllers/combobox_controller.d.ts +14 -1
- package/dist/controllers/combobox_controller.js +162 -23
- package/dist/controllers/combobox_controller.js.map +1 -1
- package/dist/controllers/command_palette_controller.d.ts +2 -0
- package/dist/controllers/command_palette_controller.js +194 -17
- package/dist/controllers/command_palette_controller.js.map +1 -1
- package/dist/controllers/confirm_controller.js.map +1 -1
- package/dist/controllers/context_menu_controller.d.ts +7 -6
- package/dist/controllers/context_menu_controller.js +32 -10
- package/dist/controllers/context_menu_controller.js.map +1 -1
- package/dist/controllers/count_up_controller.js.map +1 -1
- package/dist/controllers/data_grid_controller.d.ts +19 -1
- package/dist/controllers/data_grid_controller.js +82 -4
- package/dist/controllers/data_grid_controller.js.map +1 -1
- package/dist/controllers/date_range_picker_controller.d.ts +1 -0
- package/dist/controllers/date_range_picker_controller.js +27 -3
- package/dist/controllers/date_range_picker_controller.js.map +1 -1
- package/dist/controllers/dialog_controller.js.map +1 -1
- package/dist/controllers/dismissible_controller.js.map +1 -1
- package/dist/controllers/drawer_controller.js.map +1 -1
- package/dist/controllers/dropdown_controller.d.ts +1 -2
- package/dist/controllers/dropdown_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/focus_controller.d.ts +1 -1
- package/dist/controllers/focus_controller.js.map +1 -1
- package/dist/controllers/form_field_controller.js.map +1 -1
- package/dist/controllers/form_validation_controller.js +1 -1
- package/dist/controllers/form_validation_controller.js.map +1 -1
- package/dist/controllers/highlight_controller.js.map +1 -1
- package/dist/controllers/hover_card_controller.d.ts +1 -1
- package/dist/controllers/hover_card_controller.js.map +1 -1
- package/dist/controllers/intersection_controller.js +36 -11
- package/dist/controllers/intersection_controller.js.map +1 -1
- package/dist/controllers/lazy_frame_controller.js +31 -10
- package/dist/controllers/lazy_frame_controller.js.map +1 -1
- package/dist/controllers/listbox_controller.d.ts +9 -2
- package/dist/controllers/listbox_controller.js +257 -53
- package/dist/controllers/listbox_controller.js.map +1 -1
- package/dist/controllers/local_time_controller.js +2 -2
- package/dist/controllers/local_time_controller.js.map +1 -1
- package/dist/controllers/menu_controller.d.ts +29 -11
- package/dist/controllers/menu_controller.js +104 -17
- package/dist/controllers/menu_controller.js.map +1 -1
- package/dist/controllers/menubar_controller.d.ts +91 -11
- package/dist/controllers/menubar_controller.js +415 -63
- package/dist/controllers/menubar_controller.js.map +1 -1
- package/dist/controllers/meter_controller.js.map +1 -1
- package/dist/controllers/multi_select_controller.d.ts +31 -5
- package/dist/controllers/multi_select_controller.js +312 -29
- package/dist/controllers/multi_select_controller.js.map +1 -1
- package/dist/controllers/navigation_menu_controller.d.ts +65 -18
- package/dist/controllers/navigation_menu_controller.js +154 -27
- package/dist/controllers/navigation_menu_controller.js.map +1 -1
- package/dist/controllers/nested_form_controller.d.ts +4 -5
- package/dist/controllers/nested_form_controller.js.map +1 -1
- package/dist/controllers/number_input_controller.d.ts +1 -1
- package/dist/controllers/number_input_controller.js +7 -0
- package/dist/controllers/number_input_controller.js.map +1 -1
- package/dist/controllers/otp_controller.js +18 -1
- package/dist/controllers/otp_controller.js.map +1 -1
- package/dist/controllers/overflow_indicator_controller.d.ts +3 -2
- package/dist/controllers/overflow_indicator_controller.js +81 -13
- package/dist/controllers/overflow_indicator_controller.js.map +1 -1
- package/dist/controllers/overflow_menu_controller.d.ts +78 -19
- package/dist/controllers/overflow_menu_controller.js +381 -57
- package/dist/controllers/overflow_menu_controller.js.map +1 -1
- package/dist/controllers/pagination_controller.d.ts +36 -5
- package/dist/controllers/pagination_controller.js +163 -32
- package/dist/controllers/pagination_controller.js.map +1 -1
- package/dist/controllers/persist_controller.js +6 -6
- package/dist/controllers/persist_controller.js.map +1 -1
- package/dist/controllers/pointer_drag_controller.d.ts +2 -3
- package/dist/controllers/pointer_drag_controller.js +9 -1
- package/dist/controllers/pointer_drag_controller.js.map +1 -1
- package/dist/controllers/popover_controller.d.ts +1 -2
- package/dist/controllers/popover_controller.js +2 -2
- package/dist/controllers/popover_controller.js.map +1 -1
- package/dist/controllers/portal_controller.d.ts +4 -4
- package/dist/controllers/portal_controller.js.map +1 -1
- package/dist/controllers/progress_controller.js.map +1 -1
- package/dist/controllers/radio_group_controller.js +22 -3
- package/dist/controllers/radio_group_controller.js.map +1 -1
- package/dist/controllers/range_slider_controller.d.ts +14 -4
- package/dist/controllers/range_slider_controller.js +32 -6
- package/dist/controllers/range_slider_controller.js.map +1 -1
- package/dist/controllers/rating_controller.js +16 -2
- package/dist/controllers/rating_controller.js.map +1 -1
- package/dist/controllers/read_more_controller.js +63 -19
- package/dist/controllers/read_more_controller.js.map +1 -1
- package/dist/controllers/reading_progress_controller.js.map +1 -1
- package/dist/controllers/resizable_controller.d.ts +3 -1
- package/dist/controllers/resizable_controller.js +65 -1
- package/dist/controllers/resizable_controller.js.map +1 -1
- package/dist/controllers/roving_controller.js +17 -2
- package/dist/controllers/roving_controller.js.map +1 -1
- package/dist/controllers/scroll_area_controller.js +86 -12
- package/dist/controllers/scroll_area_controller.js.map +1 -1
- package/dist/controllers/scroll_restore_controller.js +1 -1
- package/dist/controllers/scroll_restore_controller.js.map +1 -1
- package/dist/controllers/scroll_visibility_controller.d.ts +6 -3
- package/dist/controllers/scroll_visibility_controller.js +33 -3
- package/dist/controllers/scroll_visibility_controller.js.map +1 -1
- package/dist/controllers/scrollspy_controller.d.ts +64 -15
- package/dist/controllers/scrollspy_controller.js +346 -73
- package/dist/controllers/scrollspy_controller.js.map +1 -1
- package/dist/controllers/separator_controller.d.ts +20 -5
- package/dist/controllers/separator_controller.js +9 -0
- package/dist/controllers/separator_controller.js.map +1 -1
- package/dist/controllers/sidebar_controller.d.ts +1 -1
- package/dist/controllers/sidebar_controller.js.map +1 -1
- package/dist/controllers/skeleton_controller.js +1 -1
- package/dist/controllers/skeleton_controller.js.map +1 -1
- package/dist/controllers/slider_controller.d.ts +11 -1
- package/dist/controllers/slider_controller.js +32 -6
- package/dist/controllers/slider_controller.js.map +1 -1
- package/dist/controllers/sortable_controller.d.ts +3 -1
- package/dist/controllers/sortable_controller.js +34 -3
- package/dist/controllers/sortable_controller.js.map +1 -1
- package/dist/controllers/spinner_controller.js +1 -1
- package/dist/controllers/spinner_controller.js.map +1 -1
- package/dist/controllers/stick_to_bottom_controller.d.ts +5 -6
- package/dist/controllers/stick_to_bottom_controller.js +2 -1
- package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
- package/dist/controllers/sticky_observer_controller.js +32 -11
- package/dist/controllers/sticky_observer_controller.js.map +1 -1
- package/dist/controllers/submit_once_controller.d.ts +2 -2
- package/dist/controllers/submit_once_controller.js.map +1 -1
- package/dist/controllers/switch_controller.js +1 -0
- package/dist/controllers/switch_controller.js.map +1 -1
- package/dist/controllers/tabs_controller.d.ts +11 -3
- package/dist/controllers/tabs_controller.js +26 -3
- package/dist/controllers/tabs_controller.js.map +1 -1
- package/dist/controllers/tags_input_controller.js +22 -2
- package/dist/controllers/tags_input_controller.js.map +1 -1
- package/dist/controllers/theme_controller.d.ts +1 -1
- package/dist/controllers/theme_controller.js +22 -3
- package/dist/controllers/theme_controller.js.map +1 -1
- package/dist/controllers/time_picker_controller.js +20 -1
- package/dist/controllers/time_picker_controller.js.map +1 -1
- package/dist/controllers/toast_controller.d.ts +4 -5
- package/dist/controllers/toast_controller.js +4 -5
- package/dist/controllers/toast_controller.js.map +1 -1
- package/dist/controllers/toggle_group_controller.js +23 -2
- package/dist/controllers/toggle_group_controller.js.map +1 -1
- package/dist/controllers/toolbar_controller.d.ts +53 -13
- package/dist/controllers/toolbar_controller.js +230 -31
- package/dist/controllers/toolbar_controller.js.map +1 -1
- package/dist/controllers/tooltip_controller.d.ts +1 -1
- package/dist/controllers/tooltip_controller.js.map +1 -1
- package/dist/controllers/transition_controller.js.map +1 -1
- package/dist/controllers/tree_view_controller.d.ts +87 -6
- package/dist/controllers/tree_view_controller.js +467 -51
- package/dist/controllers/tree_view_controller.js.map +1 -1
- package/dist/index.js +3514 -689
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.d.ts +375 -39
- package/dist/inspector/cli.js +228 -14
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js +419 -48
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +24 -24
- package/dist/inspector/manifest.json +1040 -125
- package/package.json +5 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/controllers/sticky_observer_controller.ts"],"names":[],"mappings":";;;;;AA8BO,SAAS,kBAAkB,KAAA,EAA2C;AAC3E,EAAA,MAAM,OAAO,KAAA,CAAM,kBAAA;AACnB,EAAA,IAAI,KAAK,KAAA,KAAU,CAAA,IAAK,IAAA,CAAK,MAAA,KAAW,GAAG,OAAO,KAAA;AAGlD,EAAA,MAAM,OAAA,GAAU,K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MAAA,EAAQ;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAI,KAAK,gBAAA,EAAkB;AACzB,MAAA,IAAA,CAAK,aAAA,CAAc,YAAA,CAAa,YAAA,EAAc,IAAA,GAAO,SAAS,OAAO,CAAA;AAAA,IACvE;AACA,IAAA,IAAA,CAAK,QAAA,CAAS,UAAU,EAAE,MAAA,EAAQ,EAAE,KAAA,EAAO,IAAA,IAAQ,CAAA;AAAA,EACrD;AACF","file":"sticky_observer_controller.js","sourcesContent":["/**\n * Shared `IntersectionObserver` plumbing for Stimeo's scroll-triggered\n * controllers (`intersection`, `scrollspy`, `sticky-observer`, `lazy-frame`).\n *\n * It centralizes the `IntersectionObserver` support guard, root resolution from\n * a selector, observer creation/teardown, the **active guard** (the browser may\n * flush a final queued callback batch right after `disconnect()`, and a\n * detached controller must not mutate possibly-cached DOM), and the\n * unobserve→observe **re-arm** that re-delivers the current state even when the\n * target never leaves the viewport.\n *\n * Like {@link RovingTabindex} and `FocusTrap`, this is a policy-free internal\n * util: what an intersection *means* (a spied link, a stuck header, a lazy\n * load) stays in each controller. The public `stimeo--intersection` controller\n * is its thin declarative face.\n */\n/**\n * Whether `entry`'s target sits entirely before the root's **start (top)** edge —\n * the \"scrolled past the top\" half of a non-intersecting entry, as opposed to\n * \"not reached yet\" below the root.\n *\n * A target with no layout box (`display: none`, a `hidden` ancestor, a collapsed\n * `<details>`) is reported with an **empty rect**, whose `bottom` of `0` would\n * otherwise satisfy `bottom <= rootTop` for a viewport root and read as \"passed\"\n * even though the target was never scrolled anywhere. An empty rect carries no\n * position at all, so it is deliberately never \"before the edge\"; what a caller\n * publishes for that case is its own policy (both consumers treat it as the\n * neutral \"not passed\"/\"not stuck\", and the real rect that arrives once the\n * target is laid out re-establishes the true state).\n */\nexport function isBeforeRootStart(entry: IntersectionObserverEntry): boolean {\n const rect = entry.boundingClientRect;\n if (rect.width === 0 && rect.height === 0) return false;\n // rootBounds is null for a cross-origin/removed root; fall back to the\n // viewport origin.\n const rootTop = entry.rootBounds?.top ?? 0;\n return rect.bottom <= rootTop;\n}\n\nexport interface IntersectionWatchOptions {\n /**\n * The observation root. Pass an element (or `null` for the viewport) when\n * the caller already resolved it; omit to resolve from `rootSelector`.\n */\n root?: Element | null;\n /** Selector for the observation root; empty/omitted = viewport. */\n rootSelector?: string;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\nexport class IntersectionWatcher {\n readonly #onEntries: (entries: IntersectionObserverEntry[]) => void;\n #observer: IntersectionObserver | null = null;\n #active = false;\n\n constructor(onEntries: (entries: IntersectionObserverEntry[]) => void) {\n this.#onEntries = onEntries;\n }\n\n /** Whether an observer is live (started, `IntersectionObserver` supported). */\n get active(): boolean {\n return this.#active;\n }\n\n /**\n * (Re)creates the observer and observes `targets`. Returns `false` — leaving\n * the watcher inert — without `IntersectionObserver` support (very old\n * browsers; the caller's no-JS fallback stays in charge) or with no targets.\n *\n * @throws Whatever the platform throws for an invalid `rootMargin`/`threshold`\n * or a failing `observe()`. The exception is passed through unchanged, but\n * the watcher rolls back first: every target observed so far is released and\n * `active` stays `false`, so a caller that retries starts from a clean slate.\n */\n start(targets: Element | readonly Element[], options: IntersectionWatchOptions = {}): boolean {\n this.stop();\n if (typeof IntersectionObserver === \"undefined\") return false;\n const list = Array.isArray(targets) ? (targets as readonly Element[]) : [targets as Element];\n if (list.length === 0) return false;\n\n const root =\n \"root\" in options\n ? (options.root ?? null)\n : options.rootSelector\n ? document.querySelector(options.rootSelector)\n : null;\n\n let observer: IntersectionObserver | null = null;\n try {\n observer = new IntersectionObserver(\n (entries) => {\n // Identity matters across an immediate restart: the old observer can\n // flush a queued batch after the new observer has made `active` true.\n if (this.#active && this.#observer === observer) this.#onEntries(entries);\n },\n { root, rootMargin: options.rootMargin, threshold: options.threshold },\n );\n for (const target of list) observer.observe(target);\n this.#observer = observer;\n this.#active = true;\n return true;\n } catch (error) {\n // A constructor or partial observe failure must not leave earlier targets\n // observed or report an active watcher. Preserve the platform exception.\n observer?.disconnect();\n this.#observer = null;\n this.#active = false;\n throw error;\n }\n }\n\n /**\n * Re-delivers `target`'s CURRENT intersection state: `IntersectionObserver`\n * only reports *changes*, but `observe()` always reports the present state,\n * so unobserve→observe turns \"still intersecting\" into a fresh callback.\n *\n * @throws Whatever `unobserve()`/`observe()` throws. The watcher is stopped\n * first, so it never stays live with a half-rearmed target.\n */\n rearm(target: Element): void {\n if (!this.#observer) return;\n try {\n this.#observer.unobserve(target);\n this.#observer.observe(target);\n } catch (error) {\n this.stop();\n throw error;\n }\n }\n\n /** Severs the observer; late queued callbacks become no-ops via the guard. */\n stop(): void {\n this.#active = false;\n this.#observer?.disconnect();\n this.#observer = null;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { IntersectionWatcher, isBeforeRootStart } from \"../utils/intersection_watcher\";\n\n/**\n * Headless **Sticky State Observer**: detects whether a `position: sticky`\n * element is currently stuck and publishes it as `data-stuck`. No APG widget — a\n * pure state-detection utility. Detection uses an {@link IntersectionObserver}\n * and a sentinel placed just before the sticky element, avoiding per-frame scroll\n * math.\n *\n * Markup contract (identifier: `stimeo--sticky-observer`):\n * <div data-controller=\"stimeo--sticky-observer\">\n * <div data-stimeo--sticky-observer-target=\"sentinel\"\n * aria-hidden=\"true\" style=\"height: 1px;\"></div>\n * <header data-stimeo--sticky-observer-target=\"element\"\n * style=\"position: sticky; top: 0;\">Site heading</header>\n * <main>…</main>\n * </div>\n *\n * When the sentinel scrolls out past the top of the viewport (or `rootSelector`\n * container), the sticky element is considered stuck and `data-stuck=\"true\"` is\n * set; otherwise `false`. The observer's initial snapshot dispatches `change`\n * once with the current state, including after a Turbo reconnect; subsequent\n * notifications dispatch only when that state changes.\n *\n * @remarks\n * Behavior only — `position: sticky`, shadows, and shrink effects are the\n * consumer's CSS (`[data-stuck=\"true\"] { … }`). `data-stuck` is a visual hook\n * only: it carries no ARIA role/state. `offset` is negated numerically for the\n * top `rootMargin` (so negative offsets remain valid) and must match the sticky\n * element's CSS `top`. The observer follows dynamic sentinel targets and value\n * changes, and is disconnected on `disconnect()` (Turbo navigation included).\n */\nexport class StickyObserverController extends Controller<HTMLElement> {\n static override targets = [\"sentinel\", \"element\"];\n static override values = {\n rootSelector: { type: String, default: \"\" },\n offset: { type: Number, default: 0 },\n };\n static events = [\"change\"] as const;\n\n declare readonly sentinelTarget: HTMLElement;\n declare readonly elementTarget: HTMLElement;\n declare readonly hasSentinelTarget: boolean;\n declare readonly hasElementTarget: boolean;\n\n declare rootSelectorValue: string;\n declare offsetValue: number;\n\n /** Shared IO plumbing (support guard, root resolution, active guard). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersect(entries));\n /** Last reported stuck state, so `change` fires only on transitions. */\n #stuck: boolean | null = null;\n /** Target currently owned by the watcher, used to avoid duplicate restarts. */\n #observedSentinel: HTMLElement | null = null;\n #connected = false;\n\n #onIntersect(entries: IntersectionObserverEntry[]): void {\n // Delivery can batch multiple transitions after a fast scroll. Process\n // every snapshot in order so an above→visible pair is not collapsed.\n for (const entry of entries) {\n if (!this.#connected || !this.#watcher.active) return;\n // A sentinel with no layout box (hidden tab panel, collapsed section, an\n // undisplayed Turbo Frame) reports an empty rect that the shared edge test\n // deliberately refuses, so an unrendered sticky element is never published\n // as stuck; the state stays put until the sentinel is actually laid out.\n this.#setStuck(!entry.isIntersecting && isBeforeRootStart(entry));\n }\n }\n\n override connect(): void {\n this.#connected = true;\n this.#stuck = null;\n this.#syncObserver();\n }\n\n override disconnect(): void {\n this.#connected = false;\n this.#watcher.stop();\n this.#observedSentinel = null;\n this.#stuck = null;\n }\n\n /** Starts observation when a sentinel is inserted after connection. */\n sentinelTargetConnected(): void {\n if (this.#connected) this.#syncObserver();\n }\n\n /** Stops or transfers observation when the current sentinel is removed. */\n sentinelTargetDisconnected(): void {\n if (this.#connected) this.#syncObserver();\n }\n\n /** Reflects the last snapshot onto an element inserted after that snapshot. */\n elementTargetConnected(element: HTMLElement): void {\n if (this.#stuck !== null) {\n element.setAttribute(\"data-stuck\", this.#stuck ? \"true\" : \"false\");\n }\n }\n\n /** Rebuilds the observer when Turbo morphs the configured root. */\n rootSelectorValueChanged(): void {\n if (this.#connected) this.#syncObserver(true);\n }\n\n /** Rebuilds the observer when Turbo morphs the configured top offset. */\n offsetValueChanged(): void {\n if (this.#connected) this.#syncObserver(true);\n }\n\n #syncObserver(force = false): void {\n const sentinel = this.hasSentinelTarget ? this.sentinelTarget : null;\n if (!force && sentinel === this.#observedSentinel && this.#watcher.active) return;\n\n this.#watcher.stop();\n this.#observedSentinel = null;\n if (!sentinel) return;\n\n const configuredOffset = this.offsetValue;\n const offset = Number.isFinite(configuredOffset) ? configuredOffset : 0;\n const started = this.#watcher.start(sentinel, {\n rootSelector: this.rootSelectorValue,\n rootMargin: `${-offset}px 0px 0px 0px`,\n threshold: [0],\n });\n if (started) this.#observedSentinel = sentinel;\n }\n\n /** Reflects the stuck state onto the sticky element and emits `change`. */\n #setStuck(next: boolean): void {\n if (next === this.#stuck) return;\n this.#stuck = next;\n if (this.hasElementTarget) {\n this.elementTarget.setAttribute(\"data-stuck\", next ? \"true\" : \"false\");\n }\n this.dispatch(\"change\", { detail: { stuck: next } });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/controllers/sticky_observer_controller.ts"],"names":[],"mappings":";;;;;AA8BO,SAAS,kBAAkB,KAAA,EAA2C;AAC3E,EAAA,MAAM,OAAO,KAAA,CAAM,kBAAA;AACnB,EAAA,IAAI,KAAK,KAAA,KAAU,CAAA,IAAK,IAAA,CAAK,MAAA,KAAW,GAAG,OAAO,KAAA;AAGlD,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,UAAA,EAAY,GAAA,IAAO,CAAA;AACzC,EAAA,OAAO,KAAK,MAAA,IAAU,OAAA;AACxB;AAcO,IAAM,sBAAN,MAA0B;AAAA,EACtB,UAAA;AAAA,EACT,SAAA,GAAyC,IAAA;AAAA,EACzC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AA,CAAK,QAAA,CAAS,KAAA,CAAM,QAAA,EAAU;AAAA,MAC5C,cAAc,IAAA,CAAK,iBAAA;AAAA,MACnB,UAAA,EAAY,CAAA,EAAG,CAAC,MAAM,CAAA,cAAA,CAAA;AAAA,MACtB,SAAA,EAAW,CAAC,CAAC;AAAA,KACd,CAAA;AACD,IAAA,IAAI,OAAA,OAAc,iBAAA,GAAoB,QAAA;AAAA,EACxC;AAAA;AAAA,EAGA,UAAU,IAAA,EAAqB;AAC7B,IAAA,IAAI,IAAA,KAAS,KAAK,MAAA,EAAQ;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAI,KAAK,gBAAA,EAAkB;AACzB,MAAA,IAAA,CAAK,aAAA,CAAc,YAAA,CAAa,YAAA,EAAc,IAAA,GAAO,SAAS,OAAO,CAAA;AAAA,IACvE;AACA,IAAA,IAAA,CAAK,QAAA,CAAS,UAAU,EAAE,MAAA,EAAQ,EAAE,KAAA,EAAO,IAAA,IAAQ,CAAA;AAAA,EACrD;AACF","file":"sticky_observer_controller.js","sourcesContent":["/**\n * Shared `IntersectionObserver` plumbing for Stimeo's scroll-triggered\n * controllers (`intersection`, `scrollspy`, `sticky-observer`, `lazy-frame`).\n *\n * It centralizes the `IntersectionObserver` support guard, root resolution from\n * a selector, observer creation/teardown, the **active guard** (the browser may\n * flush a final queued callback batch right after `disconnect()`, and a\n * detached controller must not mutate possibly-cached DOM), and the\n * unobserve→observe **re-arm** that re-delivers the current state even when the\n * target never leaves the viewport.\n *\n * Like {@link RovingTabindex} and `FocusTrap`, this is a policy-free internal\n * util: what an intersection *means* (a spied link, a stuck header, a lazy\n * load) stays in each controller. The public `stimeo--intersection` controller\n * is its thin declarative face.\n */\n/**\n * Whether `entry`'s target sits entirely before the root's **start (top)** edge —\n * the \"scrolled past the top\" half of a non-intersecting entry, as opposed to\n * \"not reached yet\" below the root.\n *\n * A target with no layout box (`display: none`, a `hidden` ancestor, a collapsed\n * `<details>`) is reported with an **empty rect**, whose `bottom` of `0` would\n * otherwise satisfy `bottom <= rootTop` for a viewport root and read as \"passed\"\n * even though the target was never scrolled anywhere. An empty rect carries no\n * position at all, so it is deliberately never \"before the edge\"; what a caller\n * publishes for that case is its own policy (both consumers treat it as the\n * neutral \"not passed\"/\"not stuck\", and the real rect that arrives once the\n * target is laid out re-establishes the true state).\n */\nexport function isBeforeRootStart(entry: IntersectionObserverEntry): boolean {\n const rect = entry.boundingClientRect;\n if (rect.width === 0 && rect.height === 0) return false;\n // rootBounds is null for a cross-origin/removed root; fall back to the\n // viewport origin.\n const rootTop = entry.rootBounds?.top ?? 0;\n return rect.bottom <= rootTop;\n}\n\nexport interface IntersectionWatchOptions {\n /**\n * The observation root. Pass an element (or `null` for the viewport) when\n * the caller already resolved it; omit to resolve from `rootSelector`.\n */\n root?: Element | null;\n /** Selector for the observation root; empty/omitted = viewport. */\n rootSelector?: string;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\nexport class IntersectionWatcher {\n readonly #onEntries: (entries: IntersectionObserverEntry[]) => void;\n #observer: IntersectionObserver | null = null;\n #active = false;\n #usingPlatformDefaults = false;\n\n constructor(onEntries: (entries: IntersectionObserverEntry[]) => void) {\n this.#onEntries = onEntries;\n }\n\n /** Whether an observer is live (started, `IntersectionObserver` supported). */\n get active(): boolean {\n return this.#active;\n }\n\n /** Whether the live observer discarded configured options after construction failed. */\n get usingPlatformDefaults(): boolean {\n return this.#usingPlatformDefaults;\n }\n\n /**\n * (Re)creates the observer and observes `targets`. Returns `false` — leaving\n * the watcher inert — without `IntersectionObserver` support (very old\n * browsers; the caller's no-JS fallback stays in charge) or with no targets.\n * If initial construction with the configured options fails, the watcher\n * warns and retries once with the same root and platform defaults.\n *\n * @throws The fallback constructor error if both construction attempts fail,\n * or whatever the platform throws from `observe()`. The exception is passed\n * through unchanged, but the watcher rolls back first: every target observed\n * so far is released and `active` stays `false`, so a caller that retries\n * starts from a clean slate.\n */\n start(targets: Element | readonly Element[], options: IntersectionWatchOptions = {}): boolean {\n this.stop();\n if (typeof IntersectionObserver === \"undefined\") return false;\n const list = Array.isArray(targets) ? (targets as readonly Element[]) : [targets as Element];\n if (list.length === 0) return false;\n\n const root =\n \"root\" in options\n ? (options.root ?? null)\n : options.rootSelector\n ? document.querySelector(options.rootSelector)\n : null;\n\n let observer: IntersectionObserver | null = null;\n try {\n const onEntries = (entries: IntersectionObserverEntry[]): void => {\n // Identity matters across an immediate restart: the old observer can\n // flush a queued batch after the new observer has made `active` true.\n if (this.#active && this.#observer === observer) this.#onEntries(entries);\n };\n try {\n observer = new IntersectionObserver(onEntries, {\n root,\n rootMargin: options.rootMargin,\n threshold: options.threshold,\n });\n } catch (error) {\n console.warn(\n \"Stimeo UI: IntersectionObserver could not be constructed with the configured options; retrying with platform defaults.\",\n error,\n );\n observer = new IntersectionObserver(onEntries, { root });\n this.#usingPlatformDefaults = true;\n }\n for (const target of list) observer.observe(target);\n this.#observer = observer;\n this.#active = true;\n return true;\n } catch (error) {\n // A constructor or partial observe failure must not leave earlier targets\n // observed or report an active watcher. Preserve the platform exception.\n observer?.disconnect();\n this.#observer = null;\n this.#active = false;\n this.#usingPlatformDefaults = false;\n throw error;\n }\n }\n\n /**\n * Re-delivers `target`'s CURRENT intersection state: `IntersectionObserver`\n * only reports *changes*, but `observe()` always reports the present state,\n * so unobserve→observe turns \"still intersecting\" into a fresh callback.\n *\n * @throws Whatever `unobserve()`/`observe()` throws. The watcher is stopped\n * first, so it never stays live with a half-rearmed target.\n */\n rearm(target: Element): void {\n if (!this.#observer) return;\n try {\n this.#observer.unobserve(target);\n this.#observer.observe(target);\n } catch (error) {\n this.stop();\n throw error;\n }\n }\n\n /** Severs the observer; late queued callbacks become no-ops via the guard. */\n stop(): void {\n this.#active = false;\n this.#observer?.disconnect();\n this.#observer = null;\n this.#usingPlatformDefaults = false;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { IntersectionWatcher, isBeforeRootStart } from \"../utils/intersection_watcher\";\n\n/**\n * Headless **Sticky State Observer**: detects whether a `position: sticky`\n * element is currently stuck and publishes it as `data-stuck`. No APG widget — a\n * pure state-detection utility. Detection uses an {@link IntersectionObserver}\n * and a sentinel placed just before the sticky element, avoiding per-frame scroll\n * math.\n *\n * Markup contract (identifier: `stimeo--sticky-observer`):\n * <div data-controller=\"stimeo--sticky-observer\">\n * <div data-stimeo--sticky-observer-target=\"sentinel\"\n * aria-hidden=\"true\" style=\"height: 1px;\"></div>\n * <header data-stimeo--sticky-observer-target=\"element\"\n * style=\"position: sticky; top: 0;\">Site heading</header>\n * <main>…</main>\n * </div>\n *\n * When the sentinel scrolls out past the top of the viewport (or `rootSelector`\n * container), the sticky element is considered stuck and `data-stuck=\"true\"` is\n * set; otherwise `false`. The observer's initial snapshot dispatches `change`\n * once with the current state, including after a Turbo reconnect; subsequent\n * notifications dispatch only when that state changes.\n *\n * @remarks\n * Behavior only — `position: sticky`, shadows, and shrink effects are the\n * consumer's CSS (`[data-stuck=\"true\"] { … }`). `data-stuck` is a visual hook\n * only: it carries no ARIA role/state. `offset` is negated numerically for the\n * top `rootMargin` (so negative offsets remain valid) and must match the sticky\n * element's CSS `top`. The observer follows dynamic sentinel targets and value\n * changes, and is disconnected on `disconnect()` (Turbo navigation included).\n */\nexport class StickyObserverController extends Controller<HTMLElement> {\n static override targets = [\"sentinel\", \"element\"];\n static override values = {\n rootSelector: { type: String, default: \"\" },\n offset: { type: Number, default: 0 },\n };\n static events = [\"change\"] as const;\n\n declare readonly sentinelTarget: HTMLElement;\n declare readonly elementTarget: HTMLElement;\n declare readonly hasSentinelTarget: boolean;\n declare readonly hasElementTarget: boolean;\n\n declare rootSelectorValue: string;\n declare offsetValue: number;\n\n /** Shared IO plumbing (support guard, root resolution, active guard). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersect(entries));\n /** Last reported stuck state, so `change` fires only on transitions. */\n #stuck: boolean | null = null;\n /** Target currently owned by the watcher; comparing it avoids duplicate restarts. */\n #observedSentinel: HTMLElement | null = null;\n #connected = false;\n\n #onIntersect(entries: IntersectionObserverEntry[]): void {\n // Delivery can batch multiple transitions after a fast scroll. Process\n // every snapshot in order so an above→visible pair is not collapsed.\n for (const entry of entries) {\n if (!this.#connected || !this.#watcher.active) return;\n // A sentinel with no layout box (hidden tab panel, collapsed section, an\n // undisplayed Turbo Frame) reports an empty rect that the shared edge test\n // deliberately refuses, so an unrendered sticky element is never published\n // as stuck; the state stays put until the sentinel is actually laid out.\n this.#setStuck(!entry.isIntersecting && isBeforeRootStart(entry));\n }\n }\n\n override connect(): void {\n this.#connected = true;\n this.#stuck = null;\n this.#syncObserver();\n }\n\n override disconnect(): void {\n this.#connected = false;\n this.#watcher.stop();\n this.#observedSentinel = null;\n this.#stuck = null;\n }\n\n /** Starts observation when a sentinel is inserted after connection. */\n sentinelTargetConnected(): void {\n if (this.#connected) this.#syncObserver();\n }\n\n /** Stops or transfers observation when the current sentinel is removed. */\n sentinelTargetDisconnected(): void {\n if (this.#connected) this.#syncObserver();\n }\n\n /** Reflects the last snapshot onto an element inserted after that snapshot. */\n elementTargetConnected(element: HTMLElement): void {\n if (this.#stuck !== null) {\n element.setAttribute(\"data-stuck\", this.#stuck ? \"true\" : \"false\");\n }\n }\n\n /** Rebuilds the observer when Turbo morphs the configured root. */\n rootSelectorValueChanged(): void {\n if (this.#connected) this.#syncObserver(true);\n }\n\n /** Rebuilds the observer when Turbo morphs the configured top offset. */\n offsetValueChanged(): void {\n if (this.#connected) this.#syncObserver(true);\n }\n\n #syncObserver(force = false): void {\n const sentinel = this.hasSentinelTarget ? this.sentinelTarget : null;\n if (!force && sentinel === this.#observedSentinel && this.#watcher.active) return;\n\n this.#watcher.stop();\n this.#observedSentinel = null;\n if (!sentinel) return;\n\n const configuredOffset = this.offsetValue;\n const offset = Number.isFinite(configuredOffset) ? configuredOffset : 0;\n const started = this.#watcher.start(sentinel, {\n rootSelector: this.rootSelectorValue,\n rootMargin: `${-offset}px 0px 0px 0px`,\n threshold: [0],\n });\n if (started) this.#observedSentinel = sentinel;\n }\n\n /** Reflects the stuck state onto the sticky element and emits `change`. */\n #setStuck(next: boolean): void {\n if (next === this.#stuck) return;\n this.#stuck = next;\n if (this.hasElementTarget) {\n this.elementTarget.setAttribute(\"data-stuck\", next ? \"true\" : \"false\");\n }\n this.dispatch(\"change\", { detail: { stuck: next } });\n }\n}\n"]}
|
|
@@ -16,8 +16,8 @@ type SubmitButton = HTMLButtonElement | HTMLInputElement;
|
|
|
16
16
|
*
|
|
17
17
|
* Zero wiring for Turbo forms: `connect()` subscribes to `turbo:submit-start`
|
|
18
18
|
* itself (symmetric with the `turbo:submit-end` it already listens for), so no
|
|
19
|
-
* `data-action` is required. The public {@link start} action
|
|
20
|
-
*
|
|
19
|
+
* `data-action` is required. The public {@link start} action stays available for
|
|
20
|
+
* **non-Turbo** forms, where you bind it to the native event yourself:
|
|
21
21
|
* `data-action="submit->stimeo--submit-once#start"`. Re-entrancy is guarded — once
|
|
22
22
|
* busy, a second `start` (auto + manual, or a duplicate event) no-ops.
|
|
23
23
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/safe_timeout.ts","../../src/controllers/submit_once_controller.ts"],"names":[],"mappings":";;;;;AAwBA,IAAe,gBAAf,MAA6B;AAAA;AAAA,EAER,GAAA,uBAAU,GAAA,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAczC,MAAM,EAAA,EAAkB;AACtB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,EAAG;AACvB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAA,GAAiB;AACf,IAAA,KAAA,MAAW,EAAA,IAAM,KAAK,GAAA,EAAK;AACzB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AACA,IAAA,IAAA,CAAK,IAAI,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,YAAc,qBAAqB,EAAA,YAAc,gBAAA;AAAA,EAC1D;AAAA;AAAA,EAGA,UAAU,MAAA,EAA8B;AACtC,IAAA,IAAI,MAAA,YAAkB,gBAAA,EAAkB,OAAO,MAAA,CAAO,KAAA;AACtD,IAAA,MAAM,IAAA,GAAO,MAAA,CAAO,YAAA,CAAa,YAAY,CAAA;AAC7C,IAAA,IAAI,IAAA,KAAS,MAAM,OAAO,IAAA;AAC1B,IAAA,OAAO,OAAO,WAAA,IAAe,EAAA;AAAA,EAC/B;AAAA;AAAA,EAGA,SAAA,CAAU,QAAsB,IAAA,EAAoB;AAClD,IAAA,IAAI,kBAAkB,gBAAA,EAAkB;AACtC,MAAA,MAAA,CAAO,KAAA,GAAQ,IAAA;AACf,MAAA;AAAA,IACF;AACA,IAAA,IAAI,MAAA,CAAO,YAAA,CAAa,YAAY,CAAA,EAAG;AACrC,MAAA,MAAA,CAAO,YAAA,CAAa,cAAc,IAAI,CAAA;AACtC,MAAA;AAAA,IACF;AACA,IAAA,MAAA,CAAO,WAAA,GAAc,IAAA;AAAA,EACvB;AAAA,EAEA,aAAA,GAAsB;AACpB,IAAA,IAAI,IAAA,CAAK,eAAe,IAAA,EAAM;AAC5B,MAAA,IAAA,CAAK,SAAA,CAAU,KAAA,CAAM,IAAA,CAAK,UAAU,CAAA;AACpC,MAAA,IAAA,CAAK,UAAA,GAAa,IAAA;AAAA,IACpB;AAAA,EACF;AACF","file":"submit_once_controller.js","sourcesContent":["/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** Submit-capable controls this controller can disable. */\ntype SubmitButton = HTMLButtonElement | HTMLInputElement;\n\n/** Attribute the original label is parked in while busy (survives a cache restore). */\nconst ORIGINAL_LABEL = \"data-submit-once-original-label\";\n/** Marker on buttons this controller disabled (so we never re-enable authored-disabled ones). */\nconst DISABLED_MARKER = \"data-submit-once-disabled\";\n/** Per-button override for the busy label (a plain attribute, not a Stimulus Value). */\nconst BUTTON_BUSY_LABEL = \"data-submit-once-busy-label\";\n\n/**\n * Headless \"submit once\" behavior: disables the form's submit button(s) on submit\n * to prevent a double submission, optionally swaps in a busy label, and restores\n * on completion. The Headless superset of Rails' `disable_with` (no dedicated APG\n * pattern; follows the WCAG \"status messages\" practice via `aria-busy`).\n *\n * Markup contract (identifier: `stimeo--submit-once`):\n * <form data-controller=\"stimeo--submit-once\"\n * data-stimeo--submit-once-busy-label-value=\"Submitting…\">\n * <button type=\"submit\" data-stimeo--submit-once-target=\"submit\">Send</button>\n * </form>\n *\n * Zero wiring for Turbo forms: `connect()` subscribes to `turbo:submit-start`\n * itself (symmetric with the `turbo:submit-end` it already listens for), so no\n * `data-action` is required. The public {@link start} action is kept for back-compat\n * and for **non-Turbo** forms, where you bind it to the native event yourself:\n * `data-action=\"submit->stimeo--submit-once#start\"`. Re-entrancy is guarded — once\n * busy, a second `start` (auto + manual, or a duplicate event) no-ops.\n *\n * On submit it disables every `submit` target (or, with none, the form's native\n * `button[type=submit]` / `input[type=submit]`), sets `aria-busy` on them and\n * `data-submitting` on the form, and swaps the **triggering** button's visible\n * label for the busy label (per-button `data-submit-once-busy-label` overrides the\n * form's `busyLabel` Value). It restores on Turbo's `turbo:submit-end`, or after\n * `timeout` ms, re-enabling the buttons and putting the labels back.\n *\n * @remarks\n * Behavior only — no spinner is drawn (pair with {@link \"spinner\"}). The submit-end\n * listener and the timeout are torn down on `disconnect()` (Turbo navigation\n * included), and `connect()` clears any stale busy state parked in a restored cache\n * snapshot so a button is never left disabled. Non-Turbo caveat: the buttons are\n * disabled synchronously inside the `submit` handler, and a plain HTML submission\n * builds its entry list *after* that event — so a disabled submitter's `name`/`value`\n * is excluded from the payload. Turbo is unaffected (it appends the submitter's\n * name/value from attributes when building `FormData`); mirror the value into a\n * hidden field when a non-Turbo form depends on it.\n */\nexport class SubmitOnceController extends Controller<HTMLElement> {\n static override targets = [\"submit\"];\n static override values = {\n busyLabel: { type: String, default: \"\" },\n timeout: { type: Number, default: 0 },\n restoreFocus: { type: Boolean, default: false },\n };\n static actions = [\"start\"] as const;\n static events = [\"start\", \"end\"] as const;\n\n declare readonly submitTargets: SubmitButton[];\n declare readonly hasSubmitTarget: boolean;\n\n declare busyLabelValue: string;\n declare timeoutValue: number;\n declare restoreFocusValue: boolean;\n\n readonly #timeouts = new SafeTimeout();\n #timeoutId: number | null = null;\n #busy = false;\n #submitter: SubmitButton | null = null;\n\n readonly #onSubmitStart = (event: Event): void => {\n this.start(event);\n };\n\n readonly #onSubmitEnd = (event: Event): void => {\n const success = (event as CustomEvent<{ success?: boolean }>).detail?.success;\n this.#restore(success);\n };\n\n override connect(): void {\n // Auto-subscribe to both ends of a Turbo submission so a drop-in form needs\n // no `data-action`. `turbo:submit-start` bubbles from the <form>, so this\n // works whether the controller is mounted on the form or an ancestor. The\n // re-entrancy guard in `start` keeps a manual `submit->#start` (non-Turbo)\n // from double-firing.\n this.element.addEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.addEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n // Idempotent: drop any busy state carried over in a restored snapshot so a\n // cached, disabled button does not stay stuck.\n this.#clearStaleBusy();\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.removeEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n this.#clearTimeout();\n }\n\n /**\n * Enters the busy state for the submission started by `event`. Accepts both a\n * native `SubmitEvent` (manual `submit->#start` on non-Turbo forms) and Turbo's\n * `turbo:submit-start` CustomEvent (auto-subscribed in `connect`).\n */\n start(event: Event): void {\n if (this.#busy) return;\n this.#busy = true;\n const buttons = this.#buttons;\n const submitter = this.#resolveSubmitter(event, buttons);\n this.#submitter = submitter;\n for (const button of buttons) {\n this.#enterBusy(button, button === submitter);\n }\n this.element.setAttribute(\"data-submitting\", \"true\");\n this.element.setAttribute(\"aria-busy\", \"true\");\n this.dispatch(\"start\", { detail: {} });\n if (this.timeoutValue > 0) {\n this.#timeoutId = this.#timeouts.set(() => this.#restore(false), this.timeoutValue);\n }\n }\n\n /** Restores the non-busy state, re-enabling buttons and putting labels back. */\n #restore(success?: boolean): void {\n if (!this.#busy) return;\n this.#busy = false;\n this.#clearTimeout();\n for (const button of this.#buttons) {\n this.#exitBusy(button);\n }\n this.element.removeAttribute(\"data-submitting\");\n this.element.removeAttribute(\"aria-busy\");\n this.dispatch(\"end\", { detail: { success } });\n if (this.restoreFocusValue && this.#submitter) {\n this.#submitter.focus();\n }\n this.#submitter = null;\n }\n\n /** Disables a button, marks it busy, and swaps the trigger's label. */\n #enterBusy(button: SubmitButton, isTrigger: boolean): void {\n // Only disable (and mark) buttons that were enabled, so an authored-disabled\n // submit button — e.g. \"disabled until valid\" — is left untouched and is never\n // re-enabled by us on restore.\n if (!button.disabled) {\n button.disabled = true;\n button.setAttribute(DISABLED_MARKER, \"true\");\n button.setAttribute(\"aria-busy\", \"true\");\n }\n if (!isTrigger) return;\n const label = button.getAttribute(BUTTON_BUSY_LABEL) ?? this.busyLabelValue;\n if (label.length === 0) return;\n if (!button.hasAttribute(ORIGINAL_LABEL)) {\n button.setAttribute(ORIGINAL_LABEL, this.#getLabel(button));\n }\n this.#setLabel(button, label);\n }\n\n /** Re-enables a button we disabled and restores its parked label, if any. */\n #exitBusy(button: SubmitButton): void {\n if (button.hasAttribute(DISABLED_MARKER)) {\n button.disabled = false;\n button.removeAttribute(DISABLED_MARKER);\n button.removeAttribute(\"aria-busy\");\n }\n const original = button.getAttribute(ORIGINAL_LABEL);\n if (original !== null) {\n this.#setLabel(button, original);\n button.removeAttribute(ORIGINAL_LABEL);\n }\n }\n\n /** Resets busy state left in a restored cache snapshot without firing events. */\n #clearStaleBusy(): void {\n this.#busy = false;\n if (this.element.hasAttribute(\"data-submitting\")) {\n this.element.removeAttribute(\"data-submitting\");\n this.element.removeAttribute(\"aria-busy\");\n }\n for (const button of this.#buttons) {\n this.#exitBusy(button);\n }\n }\n\n /** The triggering button: the event's submitter when ours, else the first button. */\n #resolveSubmitter(event: Event, buttons: SubmitButton[]): SubmitButton | null {\n const submitter = this.#eventSubmitter(event);\n if (submitter && this.#isSubmitButton(submitter) && buttons.includes(submitter)) {\n return submitter;\n }\n return buttons[0] ?? null;\n }\n\n /**\n * Reads the submitter from a native `SubmitEvent` (`event.submitter`) or from\n * Turbo's `turbo:submit-start` detail (`detail.formSubmission.submitter`), so\n * the busy label swaps onto the right button under either path.\n */\n #eventSubmitter(event: Event): HTMLElement | null {\n // Guard the `instanceof` with a typeof check: `SubmitEvent` is absent in some\n // non-browser/older runtimes, where a bare reference would throw ReferenceError.\n if (typeof SubmitEvent !== \"undefined\" && event instanceof SubmitEvent) {\n return event.submitter;\n }\n const detail = (event as CustomEvent<{ formSubmission?: { submitter?: HTMLElement } }>).detail;\n return detail?.formSubmission?.submitter ?? null;\n }\n\n /** The controlled buttons: `submit` targets, or the form's native submit controls. */\n get #buttons(): SubmitButton[] {\n if (this.hasSubmitTarget) return this.submitTargets;\n return Array.from(\n this.element.querySelectorAll<SubmitButton>('button[type=\"submit\"], input[type=\"submit\"]'),\n );\n }\n\n #isSubmitButton(el: HTMLElement): el is SubmitButton {\n return el instanceof HTMLButtonElement || el instanceof HTMLInputElement;\n }\n\n /** Reads a button's visible label (input value, aria-label, or text). */\n #getLabel(button: SubmitButton): string {\n if (button instanceof HTMLInputElement) return button.value;\n const aria = button.getAttribute(\"aria-label\");\n if (aria !== null) return aria;\n return button.textContent ?? \"\";\n }\n\n /** Writes a button's visible label through the same channel it was read from. */\n #setLabel(button: SubmitButton, text: string): void {\n if (button instanceof HTMLInputElement) {\n button.value = text;\n return;\n }\n if (button.hasAttribute(\"aria-label\")) {\n button.setAttribute(\"aria-label\", text);\n return;\n }\n button.textContent = text;\n }\n\n #clearTimeout(): void {\n if (this.#timeoutId !== null) {\n this.#timeouts.clear(this.#timeoutId);\n this.#timeoutId = null;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/safe_timeout.ts","../../src/controllers/submit_once_controller.ts"],"names":[],"mappings":";;;;;AAwBA,IAAe,gBAAf,MAA6B;AAAA;AAAA,EAER,GAAA,uBAAU,GAAA,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAczC,MAAM,EAAA,EAAkB;AACtB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,EAAG;AACvB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAA,GAAiB;AACf,IAAA,KAAA,MAAW,EAAA,IAAM,KAAK,GAAA,EAAK;AACzB,MAA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AC3F;AAAA,EACF;AAAA,EAEA,gBAAgB,EAAA,EAAqC;AACnD,IAAA,OAAO,EAAA,YAAc,qBAAqB,EAAA,YAAc,gBAAA;AAAA,EAC1D;AAAA;AAAA,EAGA,UAAU,MAAA,EAA8B;AACtC,IAAA,IAAI,MAAA,YAAkB,gBAAA,EAAkB,OAAO,MAAA,CAAO,KAAA;AACtD,IAAA,MAAM,IAAA,GAAO,MAAA,CAAO,YAAA,CAAa,YAAY,CAAA;AAC7C,IAAA,IAAI,IAAA,KAAS,MAAM,OAAO,IAAA;AAC1B,IAAA,OAAO,OAAO,WAAA,IAAe,EAAA;AAAA,EAC/B;AAAA;AAAA,EAGA,SAAA,CAAU,QAAsB,IAAA,EAAoB;AAClD,IAAA,IAAI,kBAAkB,gBAAA,EAAkB;AACtC,MAAA,MAAA,CAAO,KAAA,GAAQ,IAAA;AACf,MAAA;AAAA,IACF;AACA,IAAA,IAAI,MAAA,CAAO,YAAA,CAAa,YAAY,CAAA,EAAG;AACrC,MAAA,MAAA,CAAO,YAAA,CAAa,cAAc,IAAI,CAAA;AACtC,MAAA;AAAA,IACF;AACA,IAAA,MAAA,CAAO,WAAA,GAAc,IAAA;AAAA,EACvB;AAAA,EAEA,aAAA,GAAsB;AACpB,IAAA,IAAI,IAAA,CAAK,eAAe,IAAA,EAAM;AAC5B,MAAA,IAAA,CAAK,SAAA,CAAU,KAAA,CAAM,IAAA,CAAK,UAAU,CAAA;AACpC,MAAA,IAAA,CAAK,UAAA,GAAa,IAAA;AAAA,IACpB;AAAA,EACF;AACF","file":"submit_once_controller.js","sourcesContent":["/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** Submit-capable controls this controller can disable. */\ntype SubmitButton = HTMLButtonElement | HTMLInputElement;\n\n/** Attribute the original label is parked in while busy (survives a cache restore). */\nconst ORIGINAL_LABEL = \"data-submit-once-original-label\";\n/** Marker on buttons this controller disabled (so we never re-enable authored-disabled ones). */\nconst DISABLED_MARKER = \"data-submit-once-disabled\";\n/** Per-button override for the busy label (a plain attribute, not a Stimulus Value). */\nconst BUTTON_BUSY_LABEL = \"data-submit-once-busy-label\";\n\n/**\n * Headless \"submit once\" behavior: disables the form's submit button(s) on submit\n * to prevent a double submission, optionally swaps in a busy label, and restores\n * on completion. The Headless superset of Rails' `disable_with` (no dedicated APG\n * pattern; follows the WCAG \"status messages\" practice via `aria-busy`).\n *\n * Markup contract (identifier: `stimeo--submit-once`):\n * <form data-controller=\"stimeo--submit-once\"\n * data-stimeo--submit-once-busy-label-value=\"Submitting…\">\n * <button type=\"submit\" data-stimeo--submit-once-target=\"submit\">Send</button>\n * </form>\n *\n * Zero wiring for Turbo forms: `connect()` subscribes to `turbo:submit-start`\n * itself (symmetric with the `turbo:submit-end` it already listens for), so no\n * `data-action` is required. The public {@link start} action stays available for\n * **non-Turbo** forms, where you bind it to the native event yourself:\n * `data-action=\"submit->stimeo--submit-once#start\"`. Re-entrancy is guarded — once\n * busy, a second `start` (auto + manual, or a duplicate event) no-ops.\n *\n * On submit it disables every `submit` target (or, with none, the form's native\n * `button[type=submit]` / `input[type=submit]`), sets `aria-busy` on them and\n * `data-submitting` on the form, and swaps the **triggering** button's visible\n * label for the busy label (per-button `data-submit-once-busy-label` overrides the\n * form's `busyLabel` Value). It restores on Turbo's `turbo:submit-end`, or after\n * `timeout` ms, re-enabling the buttons and putting the labels back.\n *\n * @remarks\n * Behavior only — no spinner is drawn (pair with {@link \"spinner\"}). The submit-end\n * listener and the timeout are torn down on `disconnect()` (Turbo navigation\n * included), and `connect()` clears any stale busy state parked in a restored cache\n * snapshot so a button is never left disabled. Non-Turbo caveat: the buttons are\n * disabled synchronously inside the `submit` handler, and a plain HTML submission\n * builds its entry list *after* that event — so a disabled submitter's `name`/`value`\n * is excluded from the payload. Turbo is unaffected (it appends the submitter's\n * name/value from attributes when building `FormData`); mirror the value into a\n * hidden field when a non-Turbo form depends on it.\n */\nexport class SubmitOnceController extends Controller<HTMLElement> {\n static override targets = [\"submit\"];\n static override values = {\n busyLabel: { type: String, default: \"\" },\n timeout: { type: Number, default: 0 },\n restoreFocus: { type: Boolean, default: false },\n };\n static actions = [\"start\"] as const;\n static events = [\"start\", \"end\"] as const;\n\n declare readonly submitTargets: SubmitButton[];\n declare readonly hasSubmitTarget: boolean;\n\n declare busyLabelValue: string;\n declare timeoutValue: number;\n declare restoreFocusValue: boolean;\n\n readonly #timeouts = new SafeTimeout();\n #timeoutId: number | null = null;\n #busy = false;\n #submitter: SubmitButton | null = null;\n\n readonly #onSubmitStart = (event: Event): void => {\n this.start(event);\n };\n\n readonly #onSubmitEnd = (event: Event): void => {\n const success = (event as CustomEvent<{ success?: boolean }>).detail?.success;\n this.#restore(success);\n };\n\n override connect(): void {\n // Auto-subscribe to both ends of a Turbo submission so a drop-in form needs\n // no `data-action`. `turbo:submit-start` bubbles from the <form>, so this\n // works whether the controller is mounted on the form or an ancestor. The\n // re-entrancy guard in `start` keeps a manual `submit->#start` (non-Turbo)\n // from double-firing.\n this.element.addEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.addEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n // Idempotent: drop any busy state carried over in a restored snapshot so a\n // cached, disabled button does not stay stuck.\n this.#clearStaleBusy();\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.removeEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n this.#clearTimeout();\n }\n\n /**\n * Enters the busy state for the submission started by `event`. Accepts both a\n * native `SubmitEvent` (manual `submit->#start` on non-Turbo forms) and Turbo's\n * `turbo:submit-start` CustomEvent (auto-subscribed in `connect`).\n */\n start(event: Event): void {\n if (this.#busy) return;\n this.#busy = true;\n const buttons = this.#buttons;\n const submitter = this.#resolveSubmitter(event, buttons);\n this.#submitter = submitter;\n for (const button of buttons) {\n this.#enterBusy(button, button === submitter);\n }\n this.element.setAttribute(\"data-submitting\", \"true\");\n this.element.setAttribute(\"aria-busy\", \"true\");\n this.dispatch(\"start\", { detail: {} });\n if (this.timeoutValue > 0) {\n this.#timeoutId = this.#timeouts.set(() => this.#restore(false), this.timeoutValue);\n }\n }\n\n /** Restores the non-busy state, re-enabling buttons and putting labels back. */\n #restore(success?: boolean): void {\n if (!this.#busy) return;\n this.#busy = false;\n this.#clearTimeout();\n for (const button of this.#buttons) {\n this.#exitBusy(button);\n }\n this.element.removeAttribute(\"data-submitting\");\n this.element.removeAttribute(\"aria-busy\");\n this.dispatch(\"end\", { detail: { success } });\n if (this.restoreFocusValue && this.#submitter) {\n this.#submitter.focus();\n }\n this.#submitter = null;\n }\n\n /** Disables a button, marks it busy, and swaps the trigger's label. */\n #enterBusy(button: SubmitButton, isTrigger: boolean): void {\n // Only disable (and mark) buttons that were enabled, so an authored-disabled\n // submit button — e.g. \"disabled until valid\" — is left untouched and is never\n // re-enabled by us on restore.\n if (!button.disabled) {\n button.disabled = true;\n button.setAttribute(DISABLED_MARKER, \"true\");\n button.setAttribute(\"aria-busy\", \"true\");\n }\n if (!isTrigger) return;\n const label = button.getAttribute(BUTTON_BUSY_LABEL) ?? this.busyLabelValue;\n if (label.length === 0) return;\n if (!button.hasAttribute(ORIGINAL_LABEL)) {\n button.setAttribute(ORIGINAL_LABEL, this.#getLabel(button));\n }\n this.#setLabel(button, label);\n }\n\n /** Re-enables a button we disabled and restores its parked label, if any. */\n #exitBusy(button: SubmitButton): void {\n if (button.hasAttribute(DISABLED_MARKER)) {\n button.disabled = false;\n button.removeAttribute(DISABLED_MARKER);\n button.removeAttribute(\"aria-busy\");\n }\n const original = button.getAttribute(ORIGINAL_LABEL);\n if (original !== null) {\n this.#setLabel(button, original);\n button.removeAttribute(ORIGINAL_LABEL);\n }\n }\n\n /** Resets busy state left in a restored cache snapshot without firing events. */\n #clearStaleBusy(): void {\n this.#busy = false;\n if (this.element.hasAttribute(\"data-submitting\")) {\n this.element.removeAttribute(\"data-submitting\");\n this.element.removeAttribute(\"aria-busy\");\n }\n for (const button of this.#buttons) {\n this.#exitBusy(button);\n }\n }\n\n /** The triggering button: the event's submitter when ours, else the first button. */\n #resolveSubmitter(event: Event, buttons: SubmitButton[]): SubmitButton | null {\n const submitter = this.#eventSubmitter(event);\n if (submitter && this.#isSubmitButton(submitter) && buttons.includes(submitter)) {\n return submitter;\n }\n return buttons[0] ?? null;\n }\n\n /**\n * Reads the submitter from a native `SubmitEvent` (`event.submitter`) or from\n * Turbo's `turbo:submit-start` detail (`detail.formSubmission.submitter`), so\n * the busy label swaps onto the right button under either path.\n */\n #eventSubmitter(event: Event): HTMLElement | null {\n // Guard the `instanceof` with a typeof check: `SubmitEvent` is absent in some\n // non-browser/older runtimes, where a bare reference would throw ReferenceError.\n if (typeof SubmitEvent !== \"undefined\" && event instanceof SubmitEvent) {\n return event.submitter;\n }\n const detail = (event as CustomEvent<{ formSubmission?: { submitter?: HTMLElement } }>).detail;\n return detail?.formSubmission?.submitter ?? null;\n }\n\n /** The controlled buttons: `submit` targets, or the form's native submit controls. */\n get #buttons(): SubmitButton[] {\n if (this.hasSubmitTarget) return this.submitTargets;\n return Array.from(\n this.element.querySelectorAll<SubmitButton>('button[type=\"submit\"], input[type=\"submit\"]'),\n );\n }\n\n #isSubmitButton(el: HTMLElement): el is SubmitButton {\n return el instanceof HTMLButtonElement || el instanceof HTMLInputElement;\n }\n\n /** Reads a button's visible label (input value, aria-label, or text). */\n #getLabel(button: SubmitButton): string {\n if (button instanceof HTMLInputElement) return button.value;\n const aria = button.getAttribute(\"aria-label\");\n if (aria !== null) return aria;\n return button.textContent ?? \"\";\n }\n\n /** Writes a button's visible label through the same channel it was read from. */\n #setLabel(button: SubmitButton, text: string): void {\n if (button instanceof HTMLInputElement) {\n button.value = text;\n return;\n }\n if (button.hasAttribute(\"aria-label\")) {\n button.setAttribute(\"aria-label\", text);\n return;\n }\n button.textContent = text;\n }\n\n #clearTimeout(): void {\n if (this.#timeoutId !== null) {\n this.#timeouts.clear(this.#timeoutId);\n this.#timeoutId = null;\n }\n }\n}\n"]}
|
|
@@ -27,6 +27,7 @@ var SwitchController = class extends Controller {
|
|
|
27
27
|
* which would otherwise toggle the switch twice.
|
|
28
28
|
*/
|
|
29
29
|
onKeydown(event) {
|
|
30
|
+
if (event.defaultPrevented) return;
|
|
30
31
|
if (this.element instanceof HTMLButtonElement) return;
|
|
31
32
|
if (event.repeat) return;
|
|
32
33
|
if (event.key === " " || event.key === "Enter") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/controllers/switch_controller.ts"],"names":[],"mappings":";;;AAyBO,IAAM,gBAAA,GAAN,cAA+B,UAAA,CAAwB;AAAA,EAC5D,OAAO,OAAA,GAAU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AAE,OAAA,EAAS,KAAA,IAAS,CAAA;AAAA,EACzD;AACF","file":"switch_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/**\n * Headless, accessible switch (toggle) behavior.\n *\n * Markup contract (identifier: `stimeo--switch`):\n * <button data-controller=\"stimeo--switch\"\n * data-action=\"stimeo--switch#toggle keydown->stimeo--switch#onKeydown\"\n * role=\"switch\" aria-checked=\"false\">…</button>\n *\n * Implements the WAI-ARIA APG **Switch** pattern. The controller element is the\n * switch itself; its on/off state is reflected solely through `aria-checked`.\n *\n * @remarks\n * Behavior only — the consumer owns all styling (typically keyed off the\n * `[aria-checked=\"true\"]` attribute). On a native `<button>` host, the browser\n * already synthesizes a click for Space/Enter, so {@link onKeydown} deliberately\n * does nothing there (to avoid a double toggle) and only drives non-button hosts\n * such as `<div role=\"switch\" tabindex=\"0\">`.\n *\n * Behavior provided:\n * - Click (or Space/Enter) toggles `aria-checked` between `\"true\"` and `\"false\"`.\n * - A `stimeo--switch:changed` event is dispatched on every toggle so the\n * consumer can react (its `detail.checked` carries the new boolean state).\n */\nexport class SwitchController extends Controller<HTMLElement> {\n static actions = [\"onKeydown\", \"toggle\"] as const;\n static events = [\"changed\"] as const;\n\n /** Ensures the switch exposes a role and is keyboard-reachable. */\n override connect(): void {\n if (!this.element.hasAttribute(\"role\")) {\n this.element.setAttribute(\"role\", \"switch\");\n }\n if (!this.element.hasAttribute(\"aria-checked\")) {\n this.element.setAttribute(\"aria-checked\", \"false\");\n }\n // Native <button> hosts are focusable already; a non-button host (e.g.\n // <div role=\"switch\">) needs an explicit tabindex to be keyboard-reachable,\n // otherwise the keyboard support below would be unreachable.\n if (!(this.element instanceof HTMLButtonElement) && !this.element.hasAttribute(\"tabindex\")) {\n this.element.setAttribute(\"tabindex\", \"0\");\n }\n }\n\n /** Toggles the checked state. Bound via `data-action` (click). */\n toggle(): void {\n this.#checked = !this.#checked;\n }\n\n /**\n * Activates the switch on Space/Enter for non-native hosts and prevents the\n * default Space scroll. Bound via `data-action` (keydown). Native `<button>`\n * hosts are skipped because the browser already turns Space/Enter into a click,\n * which would otherwise toggle the switch twice.\n */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key must not ALSO toggle the switch —\n // composition depends on this yield.\n if (event.defaultPrevented) return;\n if (this.element instanceof HTMLButtonElement) return;\n if (event.repeat) return;\n if (event.key === \" \" || event.key === \"Enter\") {\n event.preventDefault();\n this.toggle();\n }\n }\n\n /** Whether the switch is currently on. */\n get #checked(): boolean {\n return this.element.getAttribute(\"aria-checked\") === \"true\";\n }\n\n /** Reflects the new state on `aria-checked` and notifies listeners. */\n set #checked(value: boolean) {\n this.element.setAttribute(\"aria-checked\", value ? \"true\" : \"false\");\n this.dispatch(\"changed\", { detail: { checked: value } });\n }\n}\n"]}
|
|
@@ -25,8 +25,9 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
25
25
|
* Behavior only. State is exposed through `aria-selected`, roving `tabindex`
|
|
26
26
|
* (`0` for the active tab, `-1` for the rest), and the panel `hidden` attribute;
|
|
27
27
|
* the consumer owns all styling. The required `list` target marks the tablist
|
|
28
|
-
* container as part of the semantic contract —
|
|
29
|
-
* role and accessible name; the controller performs no runtime
|
|
28
|
+
* container as part of the semantic contract — that container carries
|
|
29
|
+
* `role="tablist"` and an accessible name; the controller performs no runtime
|
|
30
|
+
* work on it.
|
|
30
31
|
*
|
|
31
32
|
* Behavior provided:
|
|
32
33
|
* - Click a tab to select it.
|
|
@@ -40,7 +41,14 @@ declare class TabsController extends Controller<HTMLElement> {
|
|
|
40
41
|
readonly listTarget: HTMLElement;
|
|
41
42
|
readonly tabTargets: HTMLButtonElement[];
|
|
42
43
|
readonly panelTargets: HTMLElement[];
|
|
43
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
* Selects the initially active tab: the pre-selected one, else the first.
|
|
46
|
+
*
|
|
47
|
+
* `findIndex` makes this first-wins when the author marked several — the first
|
|
48
|
+
* in DOM order is the only deterministic reading of "which one did they mean" —
|
|
49
|
+
* and `#selectIndex` then writes an explicit value onto every tab, so a
|
|
50
|
+
* forgotten `aria-selected` cannot leave a tab looking unselectable.
|
|
51
|
+
*/
|
|
44
52
|
connect(): void;
|
|
45
53
|
/** Selects the clicked tab. Bound via `data-action` (click). */
|
|
46
54
|
select(event: Event): void;
|
|
@@ -1,10 +1,30 @@
|
|
|
1
1
|
import { Controller } from '@hotwired/stimulus';
|
|
2
2
|
|
|
3
|
+
// src/controllers/tabs_controller.ts
|
|
4
|
+
|
|
5
|
+
// src/utils/logical_scroll.ts
|
|
6
|
+
function isRtl(element) {
|
|
7
|
+
return window.getComputedStyle(element).direction === "rtl";
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// src/utils/arrow_step.ts
|
|
11
|
+
function isReservedArrowChord(event, allow = []) {
|
|
12
|
+
if (!event.key.startsWith("Arrow")) return false;
|
|
13
|
+
return event.altKey && !allow.includes("alt") || event.ctrlKey && !allow.includes("ctrl") || event.metaKey && !allow.includes("meta") || event.shiftKey && !allow.includes("shift");
|
|
14
|
+
}
|
|
15
|
+
|
|
3
16
|
// src/controllers/tabs_controller.ts
|
|
4
17
|
var TabsController = class extends Controller {
|
|
5
18
|
static targets = ["tab", "panel", "list"];
|
|
6
19
|
static actions = ["onKeydown", "select"];
|
|
7
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* Selects the initially active tab: the pre-selected one, else the first.
|
|
22
|
+
*
|
|
23
|
+
* `findIndex` makes this first-wins when the author marked several — the first
|
|
24
|
+
* in DOM order is the only deterministic reading of "which one did they mean" —
|
|
25
|
+
* and `#selectIndex` then writes an explicit value onto every tab, so a
|
|
26
|
+
* forgotten `aria-selected` cannot leave a tab looking unselectable.
|
|
27
|
+
*/
|
|
8
28
|
connect() {
|
|
9
29
|
const preselected = this.tabTargets.findIndex(
|
|
10
30
|
(tab) => tab.getAttribute("aria-selected") === "true"
|
|
@@ -18,16 +38,19 @@ var TabsController = class extends Controller {
|
|
|
18
38
|
}
|
|
19
39
|
/** Implements arrow/Home/End navigation with automatic activation. */
|
|
20
40
|
onKeydown(event) {
|
|
41
|
+
if (event.defaultPrevented) return;
|
|
42
|
+
if (isReservedArrowChord(event)) return;
|
|
21
43
|
const tabs = this.tabTargets;
|
|
22
44
|
const currentIndex = tabs.indexOf(event.currentTarget);
|
|
23
45
|
if (currentIndex === -1) return;
|
|
24
46
|
let nextIndex = null;
|
|
47
|
+
const step = isRtl(this.element) ? -1 : 1;
|
|
25
48
|
switch (event.key) {
|
|
26
49
|
case "ArrowRight":
|
|
27
|
-
nextIndex = (currentIndex +
|
|
50
|
+
nextIndex = (currentIndex + step + tabs.length) % tabs.length;
|
|
28
51
|
break;
|
|
29
52
|
case "ArrowLeft":
|
|
30
|
-
nextIndex = (currentIndex -
|
|
53
|
+
nextIndex = (currentIndex - step + tabs.length) % tabs.length;
|
|
31
54
|
break;
|
|
32
55
|
case "Home":
|
|
33
56
|
nextIndex = 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/controllers/tabs_controller.ts"],"names":[],"mappings":";;;AAmCO,IAAM,cAAA,GAAN,cAA6B,UAAA,CAAwB;AAAA,EAC1D,OAAgB,OAAA,GAAU,CAAC,KAAA,EAAO,SAAS,MAAM,CAAA;AAAA,EACjD,OAAO,OAAA,GAAU,CAAC,WAAA,EAAa,QAAQ,CAAA;AAAA;AAAA,EAO9B,OAAA,GAAgB;AACvB,IAAA,MAAM,WAAA,GAAc,KAAK,UAAA,CAAW,SAAA;AAAA,MAClC,CAAC,GAAA,KAAQ,GAAA,CAAI,YAAA,CAAa,eAAe,CAAA,KAAM;AAAA,KACjD;AACA,IAAA,IAAA,CAAK,YAAA,CAAa,gBAAgB,EAAA,GAAK,CAAA,GAAI,aAAa,EAAE,KAAA,EAAO,OAAO,CAAA;AAAA,EAC1E;AAAA;AAAA,EAGA,OAAO,KAAA,EAAoB;AACzB,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,UAAA,CAAW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AAO,CAAA;AAC7D,MAAA,GAAA,CAAI,QAAA,GAAW,WAAW,CAAA,GAAI,EAAA;AAAA,IAChC,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,YAAA,CAAa,OAAA,CAAQ,CAAC,KAAA,EAAO,CAAA,KAAM;AACtC,MAAA,KAAA,CAAM,SAAS,CAAA,KAAM,KAAA;AAAA,IACvB,CAAC,CAAA;AACD,IAAA,IAAI,KAAA,EAAO,IAAA,CAAK,UAAA,CAAW,KAAK,GAAG,KAAA,EAAM;AAAA,EAC3C;AACF","file":"tabs_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/**\n * Headless, accessible tabs behavior.\n *\n * Markup contract (identifier: `stimeo--tabs`):\n * <div data-controller=\"stimeo--tabs\">\n * <div role=\"tablist\" aria-label=\"…\" data-stimeo--tabs-target=\"list\">\n * <button role=\"tab\" id=\"tab-1\" aria-controls=\"panel-1\"\n * data-stimeo--tabs-target=\"tab\"\n * data-action=\"stimeo--tabs#select\n * keydown->stimeo--tabs#onKeydown\">Tab 1</button>\n * <!-- more tabs -->\n * </div>\n * <div role=\"tabpanel\" id=\"panel-1\" aria-labelledby=\"tab-1\"\n * data-stimeo--tabs-target=\"panel\">…</div>\n * <!-- more panels -->\n * </div>\n *\n * Implements the WAI-ARIA APG **Tabs** pattern with **automatic activation**:\n * moving focus with the arrow keys immediately selects the focused tab. Tabs are\n * paired to panels by index (the Nth tab controls the Nth panel).\n *\n * @remarks\n * Behavior only. State is exposed through `aria-selected`, roving `tabindex`\n * (`0` for the active tab, `-1` for the rest), and the panel `hidden` attribute;\n * the consumer owns all styling. The required `list` target marks the tablist\n * container as part of the semantic contract — the Inspector requires its\n * role and accessible name; the controller performs no runtime work on it.\n *\n * Behavior provided:\n * - Click a tab to select it.\n * - `ArrowRight`/`ArrowLeft` move to and select the next/previous tab (wrapping);\n * `Home`/`End` select the first/last tab.\n */\nexport class TabsController extends Controller<HTMLElement> {\n static override targets = [\"tab\", \"panel\", \"list\"];\n static actions = [\"onKeydown\", \"select\"] as const;\n\n declare readonly listTarget: HTMLElement;\n declare readonly tabTargets: HTMLButtonElement[];\n declare readonly panelTargets: HTMLElement[];\n\n /** Selects the initially active tab (the pre-selected one, else the first). */\n override connect(): void {\n const preselected = this.tabTargets.findIndex(\n (tab) => tab.getAttribute(\"aria-selected\") === \"true\",\n );\n this.#selectIndex(preselected === -1 ? 0 : preselected, { focus: false });\n }\n\n /** Selects the clicked tab. Bound via `data-action` (click). */\n select(event: Event): void {\n const index = this.tabTargets.indexOf(event.currentTarget as HTMLButtonElement);\n if (index !== -1) this.#selectIndex(index, { focus: false });\n }\n\n /** Implements arrow/Home/End navigation with automatic activation. */\n onKeydown(event: KeyboardEvent): void {\n const tabs = this.tabTargets;\n const currentIndex = tabs.indexOf(event.currentTarget as HTMLButtonElement);\n if (currentIndex === -1) return;\n\n let nextIndex: number | null = null;\n switch (event.key) {\n case \"ArrowRight\":\n nextIndex = (currentIndex + 1) % tabs.length;\n break;\n case \"ArrowLeft\":\n nextIndex = (currentIndex - 1 + tabs.length) % tabs.length;\n break;\n case \"Home\":\n nextIndex = 0;\n break;\n case \"End\":\n nextIndex = tabs.length - 1;\n break;\n default:\n return;\n }\n\n event.preventDefault();\n this.#selectIndex(nextIndex, { focus: true });\n }\n\n /**\n * Activates the tab/panel pair at `index`: updates `aria-selected`, the roving\n * `tabindex`, and panel visibility. Optionally moves focus to the new tab.\n */\n #selectIndex(index: number, { focus }: { focus: boolean }): void {\n this.tabTargets.forEach((tab, i) => {\n const selected = i === index;\n tab.setAttribute(\"aria-selected\", selected ? \"true\" : \"false\");\n tab.tabIndex = selected ? 0 : -1;\n });\n this.panelTargets.forEach((panel, i) => {\n panel.hidden = i !== index;\n });\n if (focus) this.tabTargets[index]?.focus();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/controllers/tabs_controller.ts"],"names":[],"mappings":";;;;;AAiBO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AA,EAAK,CAAA,KAAM;AAClC,MAAA,MAAM,WAAW,CAAA,KAAM,KAAA;AACvB,MAAA,GAAA,CAAI,YAAA,CAAa,eAAA,EAAiB,QAAA,GAAW,MAAA,GAAS,OAAO,CAAA;AAC7D,MAAA,GAAA,CAAI,QAAA,GAAW,WAAW,CAAA,GAAI,EAAA;AAAA,IAChC,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,YAAA,CAAa,OAAA,CAAQ,CAAC,KAAA,EAAO,CAAA,KAAM;AACtC,MAAA,KAAA,CAAM,SAAS,CAAA,KAAM,KAAA;AAAA,IACvB,CAAC,CAAA;AACD,IAAA,IAAI,KAAA,EAAO,IAAA,CAAK,UAAA,CAAW,KAAK,GAAG,KAAA,EAAM;AAAA,EAC3C;AACF","file":"tabs_controller.js","sourcesContent":["/** 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/** 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** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\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","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord } from \"../utils/arrow_step\";\nimport { isRtl } from \"../utils/logical_scroll\";\n\n/**\n * Headless, accessible tabs behavior.\n *\n * Markup contract (identifier: `stimeo--tabs`):\n * <div data-controller=\"stimeo--tabs\">\n * <div role=\"tablist\" aria-label=\"…\" data-stimeo--tabs-target=\"list\">\n * <button role=\"tab\" id=\"tab-1\" aria-controls=\"panel-1\"\n * data-stimeo--tabs-target=\"tab\"\n * data-action=\"stimeo--tabs#select\n * keydown->stimeo--tabs#onKeydown\">Tab 1</button>\n * <!-- more tabs -->\n * </div>\n * <div role=\"tabpanel\" id=\"panel-1\" aria-labelledby=\"tab-1\"\n * data-stimeo--tabs-target=\"panel\">…</div>\n * <!-- more panels -->\n * </div>\n *\n * Implements the WAI-ARIA APG **Tabs** pattern with **automatic activation**:\n * moving focus with the arrow keys immediately selects the focused tab. Tabs are\n * paired to panels by index (the Nth tab controls the Nth panel).\n *\n * @remarks\n * Behavior only. State is exposed through `aria-selected`, roving `tabindex`\n * (`0` for the active tab, `-1` for the rest), and the panel `hidden` attribute;\n * the consumer owns all styling. The required `list` target marks the tablist\n * container as part of the semantic contract — that container carries\n * `role=\"tablist\"` and an accessible name; the controller performs no runtime\n * work on it.\n *\n * Behavior provided:\n * - Click a tab to select it.\n * - `ArrowRight`/`ArrowLeft` move to and select the next/previous tab (wrapping);\n * `Home`/`End` select the first/last tab.\n */\nexport class TabsController extends Controller<HTMLElement> {\n static override targets = [\"tab\", \"panel\", \"list\"];\n static actions = [\"onKeydown\", \"select\"] as const;\n\n declare readonly listTarget: HTMLElement;\n declare readonly tabTargets: HTMLButtonElement[];\n declare readonly panelTargets: HTMLElement[];\n\n /**\n * Selects the initially active tab: the pre-selected one, else the first.\n *\n * `findIndex` makes this first-wins when the author marked several — the first\n * in DOM order is the only deterministic reading of \"which one did they mean\" —\n * and `#selectIndex` then writes an explicit value onto every tab, so a\n * forgotten `aria-selected` cannot leave a tab looking unselectable.\n */\n override connect(): void {\n const preselected = this.tabTargets.findIndex(\n (tab) => tab.getAttribute(\"aria-selected\") === \"true\",\n );\n this.#selectIndex(preselected === -1 ? 0 : preselected, { focus: false });\n }\n\n /** Selects the clicked tab. Bound via `data-action` (click). */\n select(event: Event): void {\n const index = this.tabTargets.indexOf(event.currentTarget as HTMLButtonElement);\n if (index !== -1) this.#selectIndex(index, { focus: false });\n }\n\n /** Implements arrow/Home/End navigation with automatic activation. */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key (a grabbed drag handle, a\n // nested menu) must not ALSO act on it — composition depends on this yield.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n const tabs = this.tabTargets;\n const currentIndex = tabs.indexOf(event.currentTarget as HTMLButtonElement);\n if (currentIndex === -1) return;\n\n let nextIndex: number | null = null;\n // Logical, not physical. APG defines these as \"next / previous control\", and\n // says a vertical arrangement swaps in Down/Up for the same meaning — so the\n // pair is one axis's spelling of an order, and the order reverses with the\n // writing direction. Read from the controller element: the container is what\n // lays the items out, and a child may carry its own `dir` (an LTR input\n // inside an RTL form is ordinary authoring).\n const step = isRtl(this.element) ? -1 : 1;\n switch (event.key) {\n case \"ArrowRight\":\n nextIndex = (currentIndex + step + tabs.length) % tabs.length;\n break;\n case \"ArrowLeft\":\n nextIndex = (currentIndex - step + tabs.length) % tabs.length;\n break;\n case \"Home\":\n nextIndex = 0;\n break;\n case \"End\":\n nextIndex = tabs.length - 1;\n break;\n default:\n return;\n }\n\n event.preventDefault();\n this.#selectIndex(nextIndex, { focus: true });\n }\n\n /**\n * Activates the tab/panel pair at `index`: updates `aria-selected`, the roving\n * `tabindex`, and panel visibility. Optionally moves focus to the new tab.\n */\n #selectIndex(index: number, { focus }: { focus: boolean }): void {\n this.tabTargets.forEach((tab, i) => {\n const selected = i === index;\n tab.setAttribute(\"aria-selected\", selected ? \"true\" : \"false\");\n tab.tabIndex = selected ? 0 : -1;\n });\n this.panelTargets.forEach((panel, i) => {\n panel.hidden = i !== index;\n });\n if (focus) this.tabTargets[index]?.focus();\n }\n}\n"]}
|
|
@@ -2,6 +2,22 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
2
2
|
|
|
3
3
|
// src/controllers/tags_input_controller.ts
|
|
4
4
|
|
|
5
|
+
// src/utils/logical_scroll.ts
|
|
6
|
+
function isRtl(element) {
|
|
7
|
+
return window.getComputedStyle(element).direction === "rtl";
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// src/utils/arrow_step.ts
|
|
11
|
+
function logicalArrowKey(key, element) {
|
|
12
|
+
if (key !== "ArrowRight" && key !== "ArrowLeft") return key;
|
|
13
|
+
if (!isRtl(element)) return key;
|
|
14
|
+
return key === "ArrowRight" ? "ArrowLeft" : "ArrowRight";
|
|
15
|
+
}
|
|
16
|
+
function isReservedArrowChord(event, allow = []) {
|
|
17
|
+
if (!event.key.startsWith("Arrow")) return false;
|
|
18
|
+
return event.altKey && !allow.includes("alt") || event.ctrlKey && !allow.includes("ctrl") || event.metaKey && !allow.includes("meta") || event.shiftKey && !allow.includes("shift");
|
|
19
|
+
}
|
|
20
|
+
|
|
5
21
|
// src/utils/composition_tracker.ts
|
|
6
22
|
var CompositionTracker = class {
|
|
7
23
|
#observedTargets = /* @__PURE__ */ new Set();
|
|
@@ -119,6 +135,8 @@ var TagsInputController = class extends Controller {
|
|
|
119
135
|
}
|
|
120
136
|
/** Commits on `Enter`/delimiter and deletes the last tag on empty `Backspace`. */
|
|
121
137
|
onKeydown(event) {
|
|
138
|
+
if (event.defaultPrevented) return;
|
|
139
|
+
if (isReservedArrowChord(event)) return;
|
|
122
140
|
if (this.#composition.isComposing(event)) return;
|
|
123
141
|
if (event.key === "Enter" || event.key === this.delimiterValue) {
|
|
124
142
|
event.preventDefault();
|
|
@@ -133,7 +151,7 @@ var TagsInputController = class extends Controller {
|
|
|
133
151
|
}
|
|
134
152
|
return;
|
|
135
153
|
}
|
|
136
|
-
if (event.key === "ArrowLeft" && this.inputTarget.value === "") {
|
|
154
|
+
if (logicalArrowKey(event.key, this.element) === "ArrowLeft" && this.inputTarget.value === "") {
|
|
137
155
|
const buttons = this.#removeButtons;
|
|
138
156
|
if (buttons.length > 0) {
|
|
139
157
|
event.preventDefault();
|
|
@@ -206,12 +224,14 @@ var TagsInputController = class extends Controller {
|
|
|
206
224
|
}
|
|
207
225
|
/** Handles arrow navigation and deletion within the chip list (delegated). */
|
|
208
226
|
#onTagKeydown = (event) => {
|
|
227
|
+
if (event.defaultPrevented) return;
|
|
228
|
+
if (isReservedArrowChord(event)) return;
|
|
209
229
|
const button = event.target.closest("button");
|
|
210
230
|
if (!button) return;
|
|
211
231
|
const buttons = this.#removeButtons;
|
|
212
232
|
const index = buttons.indexOf(button);
|
|
213
233
|
if (index === -1) return;
|
|
214
|
-
switch (event.key) {
|
|
234
|
+
switch (logicalArrowKey(event.key, this.element)) {
|
|
215
235
|
case "ArrowLeft":
|
|
216
236
|
if (index > 0) {
|
|
217
237
|
event.preventDefault();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/composition_tracker.ts","../../src/utils/roving_tabindex.ts","../../src/controllers/tags_input_controller.ts"],"names":[],"mappings":";;;;;AAuCO,IAAM,qBAAN,MAAyB;AAAA,EACrB,gBAAA,uBAAuB,GAAA,EAAiB;AAAA,EACxC,cAAA,uBAAqB,GAAA,EAAiB;AAAA,EACtC,QAAA;AAAA,EACA,MAAA;AAAA,EAET,WAAA,CAAY,OAAA,GAAqC,EAAC,EAAG;AACnD,IAAA,IAAA,CAAK,WAAW,OAAA,CAAQ,OAAA;AACxB,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,KAAA;AAAA,EACxB;AAAA;AAAA,EAGA,QAAQ,MAA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K,IAAA,CAAK,UAAA,CAAW,gBAAA,CAAoC,QAAQ,CAAC,CAAA;AAAA,EACjF;AAAA;AAAA,EAGA,IAAI,OAAA,GAAoB;AACtB,IAAA,OAAO,IAAA,CAAK,WAAW,GAAA,CAAI,CAAC,QAAQ,GAAA,CAAI,OAAA,CAAQ,SAAS,EAAE,CAAA;AAAA,EAC7D;AACF","file":"tags_input_controller.js","sourcesContent":["/** Minimal event shape carrying the platform's per-event composition signal. */\nexport interface CompositionSignal {\n readonly isComposing?: boolean;\n}\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\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 * @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 * onKeydown(event: KeyboardEvent): void {\n * if (this.#composition.isComposing(event)) return;\n * }\n * ```\n */\nexport class CompositionTracker {\n readonly #observedTargets = new Set<EventTarget>();\n readonly #activeTargets = new Set<EventTarget>();\n readonly #onStart: ((event: Event) => void) | undefined;\n readonly #onEnd: ((event: Event) => void) | undefined;\n\n constructor(options: CompositionTrackerOptions = {}) {\n this.#onStart = options.onStart;\n this.#onEnd = options.onEnd;\n }\n\n /** Starts lifecycle tracking for `target`; repeated calls are idempotent. */\n observe(target: EventTarget): void {\n if (this.#observedTargets.has(target)) return;\n target.addEventListener(\"compositionstart\", this.#handleStart);\n target.addEventListener(\"compositionend\", this.#handleEnd);\n this.#observedTargets.add(target);\n }\n\n /** Stops tracking one target and clears any active composition it owned. */\n unobserve(target: EventTarget): void {\n if (!this.#observedTargets.delete(target)) return;\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n this.#activeTargets.delete(target);\n }\n\n /** Releases every listener and clears state so reconnect starts cleanly. */\n disconnect(): void {\n for (const target of this.#observedTargets) {\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n }\n this.#observedTargets.clear();\n this.#activeTargets.clear();\n }\n\n /** True when lifecycle tracking or the current event reports composition. */\n isComposing(event?: CompositionSignal): boolean {\n return this.#activeTargets.size > 0 || event?.isComposing === true;\n }\n\n readonly #handleStart = (event: Event): void => {\n if (event.currentTarget) this.#activeTargets.add(event.currentTarget);\n this.#onStart?.(event);\n };\n\n readonly #handleEnd = (event: Event): void => {\n if (event.currentTarget) this.#activeTargets.delete(event.currentTarget);\n this.#onEnd?.(event);\n };\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, Rating, …); 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.\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 */\n setActive(index: number, { focus = false }: { focus?: boolean } = {}): void {\n const 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 { Controller } from \"@hotwired/stimulus\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\nimport { RovingTabindex } from \"../utils/roving_tabindex\";\n\n/**\n * Headless, accessible free-input tags / chips field.\n *\n * Markup contract (identifier: `stimeo--tags-input`):\n * <div data-controller=\"stimeo--tags-input\"\n * data-stimeo--tags-input-delimiter-value=\",\">\n * <ul role=\"list\" aria-label=\"Tags\" data-stimeo--tags-input-target=\"tags\"></ul>\n * <input type=\"text\" aria-label=\"Add tag\" aria-describedby=\"tags-help\"\n * data-stimeo--tags-input-target=\"input\"\n * data-action=\"keydown->stimeo--tags-input#onKeydown\" />\n * <span role=\"status\" aria-live=\"polite\" class=\"visually-hidden\"\n * data-stimeo--tags-input-target=\"status\"></span>\n * <div data-stimeo--tags-input-target=\"fields\"></div>\n * <template data-stimeo--tags-input-target=\"tagTemplate\">\n * <li role=\"listitem\" data-stimeo--tags-input-target=\"tag\">\n * <span data-tags-input-slot=\"label\"></span>\n * <!-- Removal is delegated on the tags container; no per-chip action needed. -->\n * <button type=\"button\" tabindex=\"-1\">×</button>\n * </li>\n * </template>\n * </div>\n *\n * There is no single established APG pattern; this composes a labeled text input\n * with a roving-tabindex list of removable chips, mapping to WCAG 2.1.1, 2.4.7,\n * 4.1.2, 4.1.3, and 1.3.1. Unlike {@link MultiSelectController} (pick from a\n * candidate list) the user types arbitrary strings.\n *\n * Behavior provided:\n * - `Enter` or the configured delimiter commits the trimmed input as a tag.\n * - Empty / duplicate / over-limit additions are rejected with\n * `stimeo--tags-input:reject`; duplicates are allowed when `allowDuplicates`.\n * - Tags render from the `tagTemplate`, each with a `Remove {label}` button; the\n * `fields` container mirrors the tag set as `name`d hidden inputs for form\n * submission, and every change dispatches `stimeo--tags-input:change`.\n * - The remove buttons form one roving Tab stop: `ArrowLeft`/`ArrowRight` move\n * between them (right past the end returns to the input), `Delete`/`Backspace`\n * delete the focused tag, and `Backspace` on an empty input deletes the last.\n * - Removing a tag moves focus to the neighboring tag, else back to the input.\n */\nexport class TagsInputController extends Controller<HTMLElement> {\n static override targets = [\"input\", \"tags\", \"tag\", \"tagTemplate\", \"status\", \"fields\"];\n static override values = {\n delimiter: { type: String, default: \",\" },\n max: { type: Number, default: 0 },\n allowDuplicates: { type: Boolean, default: false },\n name: { type: String, default: \"tags[]\" },\n };\n static actions = [\"onKeydown\"] as const;\n static events = [\"change\", \"reject\"] as const;\n\n declare readonly inputTarget: HTMLInputElement;\n declare readonly tagsTarget: HTMLElement;\n declare readonly tagTargets: HTMLElement[];\n declare readonly tagTemplateTarget: HTMLTemplateElement;\n declare readonly statusTarget: HTMLElement;\n declare readonly fieldsTarget: HTMLElement;\n declare readonly hasStatusTarget: boolean;\n declare readonly hasFieldsTarget: boolean;\n declare readonly hasTagTemplateTarget: boolean;\n declare readonly hasInputTarget: boolean;\n\n declare delimiterValue: string;\n declare maxValue: number;\n declare allowDuplicatesValue: boolean;\n declare nameValue: string;\n\n readonly #roving = new RovingTabindex(() => this.#removeButtons);\n /** Owns IME lifecycle state for commit-key guarding. */\n readonly #composition = new CompositionTracker();\n\n /** Wires tag-list keyboard navigation and removal, and seeds the single Tab stop. */\n override connect(): void {\n if (this.hasInputTarget) this.#composition.observe(this.inputTarget);\n this.tagsTarget.addEventListener(\"keydown\", this.#onTagKeydown);\n this.tagsTarget.addEventListener(\"click\", this.#onTagClick);\n this.#syncState();\n }\n\n /** Releases the delegated listeners so no handler outlives the element. */\n override disconnect(): void {\n this.#composition.disconnect();\n this.tagsTarget.removeEventListener(\"keydown\", this.#onTagKeydown);\n this.tagsTarget.removeEventListener(\"click\", this.#onTagClick);\n }\n\n /** Tracks an input added initially or after connect. */\n inputTargetConnected(input: HTMLInputElement): void {\n this.#composition.observe(input);\n }\n\n /** Removes composition listeners when the active input is replaced or removed. */\n inputTargetDisconnected(input: HTMLInputElement): void {\n this.#composition.unobserve(input);\n }\n\n /** Commits on `Enter`/delimiter and deletes the last tag on empty `Backspace`. */\n onKeydown(event: KeyboardEvent): void {\n // Ignore keys fired during IME composition: the `Enter` that confirms a\n // candidate (and arrows that move within it) must not commit/navigate the\n // chip list. Controller-owned lifecycle state covers confirming events that\n // omit the standard per-event signal.\n if (this.#composition.isComposing(event)) return;\n if (event.key === \"Enter\" || event.key === this.delimiterValue) {\n event.preventDefault();\n this.#commitInput();\n return;\n }\n if (event.key === \"Backspace\" && this.inputTarget.value === \"\") {\n const buttons = this.#removeButtons;\n if (buttons.length > 0) {\n event.preventDefault();\n this.#removeAt(buttons.length - 1);\n }\n return;\n }\n if (event.key === \"ArrowLeft\" && this.inputTarget.value === \"\") {\n const buttons = this.#removeButtons;\n if (buttons.length > 0) {\n event.preventDefault();\n this.#roving.setActive(buttons.length - 1, { focus: true });\n }\n }\n }\n\n /**\n * Deletes the tag whose remove button was clicked. Delegated on the tags\n * container (like `#onTagKeydown`) rather than bound per chip via\n * `data-action`, so it works the instant a chip is appended without waiting on\n * Stimulus to wire a freshly created element.\n */\n readonly #onTagClick = (event: MouseEvent): void => {\n const button = (event.target as HTMLElement).closest(\"button\");\n if (!button || !this.tagsTarget.contains(button)) return;\n const index = this.#removeButtons.indexOf(button as HTMLButtonElement);\n if (index !== -1) this.#removeAt(index);\n };\n\n /** Validates and adds the current input value as a tag, then clears the input. */\n #commitInput(): void {\n const value = this.inputTarget.value.trim();\n if (value === \"\") {\n this.#reject(value, \"empty\");\n return;\n }\n if (this.maxValue > 0 && this.tagTargets.length >= this.maxValue) {\n this.#reject(value, \"max\");\n return;\n }\n if (!this.allowDuplicatesValue && this.#values.includes(value)) {\n this.#reject(value, \"duplicate\");\n return;\n }\n this.#appendTag(value);\n this.inputTarget.value = \"\";\n this.#announce(value);\n this.#syncState();\n this.dispatch(\"change\", { detail: { tags: this.#values } });\n }\n\n /** Builds one chip from the template and appends it to the tag list. */\n #appendTag(value: string): void {\n if (!this.hasTagTemplateTarget) return;\n const fragment = this.tagTemplateTarget.content.cloneNode(true) as DocumentFragment;\n const tag = fragment.querySelector<HTMLElement>('[data-stimeo--tags-input-target=\"tag\"]');\n const label = fragment.querySelector<HTMLElement>('[data-tags-input-slot=\"label\"]');\n const button = fragment.querySelector<HTMLButtonElement>(\"button\");\n if (!tag || !button) return;\n tag.dataset.value = value;\n if (label) label.textContent = value;\n button.setAttribute(\"aria-label\", `Remove ${value}`);\n button.tabIndex = -1;\n this.tagsTarget.appendChild(fragment);\n }\n\n /** Removes the tag at `index`, then moves focus to a neighbor or the input. */\n #removeAt(index: number): void {\n const tag = this.tagTargets[index];\n if (!tag) return;\n const value = tag.dataset.value ?? \"\";\n tag.remove();\n this.#announce(value);\n this.#syncState();\n this.dispatch(\"change\", { detail: { tags: this.#values } });\n const remaining = this.#removeButtons;\n if (remaining.length === 0) {\n this.inputTarget.focus();\n } else {\n this.#roving.setActive(Math.min(index, remaining.length - 1), { focus: true });\n }\n }\n\n /** Handles arrow navigation and deletion within the chip list (delegated). */\n readonly #onTagKeydown = (event: KeyboardEvent): void => {\n const button = (event.target as HTMLElement).closest(\"button\");\n if (!button) return;\n const buttons = this.#removeButtons;\n const index = buttons.indexOf(button);\n if (index === -1) return;\n switch (event.key) {\n case \"ArrowLeft\":\n if (index > 0) {\n event.preventDefault();\n this.#roving.setActive(index - 1, { focus: true });\n }\n break;\n case \"ArrowRight\":\n event.preventDefault();\n if (index < buttons.length - 1) {\n this.#roving.setActive(index + 1, { focus: true });\n } else {\n this.inputTarget.focus();\n }\n break;\n case \"Delete\":\n case \"Backspace\":\n event.preventDefault();\n this.#removeAt(index);\n break;\n default:\n break;\n }\n };\n\n /** Rebuilds the hidden form fields, the `full` flag, and the roving Tab stop. */\n #syncState(): void {\n if (this.hasFieldsTarget) {\n this.fieldsTarget.replaceChildren(\n ...this.#values.map((value) => {\n const input = document.createElement(\"input\");\n input.type = \"hidden\";\n input.name = this.nameValue;\n input.value = value;\n return input;\n }),\n );\n }\n const full = this.maxValue > 0 && this.tagTargets.length >= this.maxValue;\n this.element.toggleAttribute(\"data-stimeo--tags-input-full\", full);\n // Keep exactly one remove button tabbable so the chip list is a single stop.\n if (this.#removeButtons.length > 0 && this.#roving.activeIndex === -1) {\n this.#roving.setActive(0);\n }\n }\n\n /** Mirrors the changed tag into the live region for assistive tech. */\n #announce(value: string): void {\n if (this.hasStatusTarget) this.statusTarget.textContent = value;\n }\n\n /** Reports a rejected addition via `stimeo--tags-input:reject`. */\n #reject(value: string, reason: \"duplicate\" | \"empty\" | \"max\"): void {\n this.dispatch(\"reject\", { detail: { value, reason } });\n }\n\n /** The remove buttons in document order (the roving navigation set). */\n get #removeButtons(): HTMLButtonElement[] {\n return Array.from(this.tagsTarget.querySelectorAll<HTMLButtonElement>(\"button\"));\n }\n\n /** Current tag values in order. */\n get #values(): string[] {\n return this.tagTargets.map((tag) => tag.dataset.value ?? \"\");\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/utils/composition_tracker.ts","../../src/utils/roving_tabindex.ts","../../src/controllers/tags_input_controller.ts"],"names":[],"mappings":";;;;;AAiBO,SAAS,MAAM,OAAA,EAA2B;AAC/C,EAAA,OAAO,MAAA,CAAO,gBAAA,CAAiB,OAAO,CAAA,CAAE,SAAA,KAAc,KAAA;AACxD;;;AC6CO,SAAS,eAAA,CAAgB,KAAa,OAAA,EAA0B;AACrE,EAAA,IAAI,GAAA,KAAQ,YAAA,IAAgB,GAAA,KAAQ,WAAA,EAAa,OAAO,GAAA;AACxD,EAAA,IAAI,CAAC,KAAA,CAAM,OAAO,CAAA,EAAG,OAAO,GAAA;AAC5B,EAAA,OAAO,GAAA,KAAQ,eAAe,WAAA,GAAc,YAAA;AAC9C;AA2BO,SAAS,oBAAA,CACd,KAAA,EACA,KAAA,GAAkC,EAAC,EAC1B;AACT,EAAA,IAAI,CAAC,KAAA,CAAM,GAAA,CAAI,UAAA,CAAW,OAAO,GAAG,OAAO,KAAA;AAC3C,EAAA,OACG,KAAA,CAAM,MAAA,IAAU,CAAC,KAAA,CAAM,QAAA,CAAS,KAAK,CAAA,IACrC,KAAA,CAAM,OAAA,IAAW,CAAC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AQ,KAAA;AACd,UAAA,OAAO,KAAA;AAAA,QACT,CAAC;AAAA,OACH;AAAA,IACF;AACA,IAAA,MAAM,OAAO,IAAA,CAAK,QAAA,GAAW,KAAK,IAAA,CAAK,UAAA,CAAW,UAAU,IAAA,CAAK,QAAA;AACjE,IAAA,IAAA,CAAK,OAAA,CAAQ,eAAA,CAAgB,8BAAA,EAAgC,IAAI,CAAA;AAEjE,IAAA,IAAI,KAAK,cAAA,CAAe,MAAA,GAAS,KAAK,IAAA,CAAK,OAAA,CAAQ,gBAAgB,EAAA,EAAI;AACrE,MAAA,IAAA,CAAK,OAAA,CAAQ,UAAU,CAAC,CAAA;AAAA,IAC1B;AAAA,EACF;AAAA;AAAA,EAGA,UAAU,KAAA,EAAqB;AAC7B,IAAA,IAAI,IAAA,CAAK,eAAA,EAAiB,IAAA,CAAK,YAAA,CAAa,WAAA,GAAc,KAAA;AAAA,EAC5D;AAAA;AAAA,EAGA,OAAA,CAAQ,OAAe,MAAA,EAA6C;AAClE,IAAA,IAAA,CAAK,QAAA,CAAS,UAAU,EAAE,MAAA,EAAQ,EAAE,KAAA,EAAO,MAAA,IAAU,CAAA;AAAA,EACvD;AAAA;AAAA,EAGA,IAAI,cAAA,GAAsC;AACxC,IAAA,OAAO,MAAM,IAAA,CAAK,IAAA,CAAK,UAAA,CAAW,gBAAA,CAAoC,QAAQ,CAAC,CAAA;AAAA,EACjF;AAAA;AAAA,EAGA,IAAI,OAAA,GAAoB;AACtB,IAAA,OAAO,IAAA,CAAK,WAAW,GAAA,CAAI,CAAC,QAAQ,GAAA,CAAI,OAAA,CAAQ,SAAS,EAAE,CAAA;AAAA,EAC7D;AACF","file":"tags_input_controller.js","sourcesContent":["/** 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/** 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** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\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","/** Minimal event shape carrying the platform's per-event composition signal. */\nexport interface CompositionSignal {\n readonly isComposing?: boolean;\n}\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\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 * @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 * onKeydown(event: KeyboardEvent): void {\n * if (this.#composition.isComposing(event)) return;\n * }\n * ```\n */\nexport class CompositionTracker {\n readonly #observedTargets = new Set<EventTarget>();\n readonly #activeTargets = new Set<EventTarget>();\n readonly #onStart: ((event: Event) => void) | undefined;\n readonly #onEnd: ((event: Event) => void) | undefined;\n\n constructor(options: CompositionTrackerOptions = {}) {\n this.#onStart = options.onStart;\n this.#onEnd = options.onEnd;\n }\n\n /** Starts lifecycle tracking for `target`; repeated calls are idempotent. */\n observe(target: EventTarget): void {\n if (this.#observedTargets.has(target)) return;\n target.addEventListener(\"compositionstart\", this.#handleStart);\n target.addEventListener(\"compositionend\", this.#handleEnd);\n this.#observedTargets.add(target);\n }\n\n /** Stops tracking one target and clears any active composition it owned. */\n unobserve(target: EventTarget): void {\n if (!this.#observedTargets.delete(target)) return;\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n this.#activeTargets.delete(target);\n }\n\n /** Releases every listener and clears state so reconnect starts cleanly. */\n disconnect(): void {\n for (const target of this.#observedTargets) {\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n }\n this.#observedTargets.clear();\n this.#activeTargets.clear();\n }\n\n /** True when lifecycle tracking or the current event reports composition. */\n isComposing(event?: CompositionSignal): boolean {\n return this.#activeTargets.size > 0 || event?.isComposing === true;\n }\n\n readonly #handleStart = (event: Event): void => {\n if (event.currentTarget) this.#activeTargets.add(event.currentTarget);\n this.#onStart?.(event);\n };\n\n readonly #handleEnd = (event: Event): void => {\n if (event.currentTarget) this.#activeTargets.delete(event.currentTarget);\n this.#onEnd?.(event);\n };\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, Rating, …); 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.\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 */\n setActive(index: number, { focus = false }: { focus?: boolean } = {}): void {\n const 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 { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord, logicalArrowKey } from \"../utils/arrow_step\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\nimport { RovingTabindex } from \"../utils/roving_tabindex\";\n\n/**\n * Headless, accessible free-input tags / chips field.\n *\n * Markup contract (identifier: `stimeo--tags-input`):\n * <div data-controller=\"stimeo--tags-input\"\n * data-stimeo--tags-input-delimiter-value=\",\">\n * <ul role=\"list\" aria-label=\"Tags\" data-stimeo--tags-input-target=\"tags\"></ul>\n * <input type=\"text\" aria-label=\"Add tag\" aria-describedby=\"tags-help\"\n * data-stimeo--tags-input-target=\"input\"\n * data-action=\"keydown->stimeo--tags-input#onKeydown\" />\n * <span role=\"status\" aria-live=\"polite\" class=\"visually-hidden\"\n * data-stimeo--tags-input-target=\"status\"></span>\n * <div data-stimeo--tags-input-target=\"fields\"></div>\n * <template data-stimeo--tags-input-target=\"tagTemplate\">\n * <li role=\"listitem\" data-stimeo--tags-input-target=\"tag\">\n * <span data-tags-input-slot=\"label\"></span>\n * <!-- Removal is delegated on the tags container; no per-chip action needed. -->\n * <button type=\"button\" tabindex=\"-1\">×</button>\n * </li>\n * </template>\n * </div>\n *\n * There is no single established APG pattern; this composes a labeled text input\n * with a roving-tabindex list of removable chips, mapping to WCAG 2.1.1, 2.4.7,\n * 4.1.2, 4.1.3, and 1.3.1. Unlike {@link MultiSelectController} (pick from a\n * candidate list) the user types arbitrary strings.\n *\n * Behavior provided:\n * - `Enter` or the configured delimiter commits the trimmed input as a tag.\n * - Empty / duplicate / over-limit additions are rejected with\n * `stimeo--tags-input:reject`; duplicates are allowed when `allowDuplicates`.\n * - Tags render from the `tagTemplate`, each with a `Remove {label}` button; the\n * `fields` container mirrors the tag set as `name`d hidden inputs for form\n * submission, and every change dispatches `stimeo--tags-input:change`.\n * - The remove buttons form one roving Tab stop: `ArrowLeft`/`ArrowRight` move\n * between them (right past the end returns to the input), `Delete`/`Backspace`\n * delete the focused tag, and `Backspace` on an empty input deletes the last.\n * - Removing a tag moves focus to the neighboring tag, else back to the input.\n */\nexport class TagsInputController extends Controller<HTMLElement> {\n static override targets = [\"input\", \"tags\", \"tag\", \"tagTemplate\", \"status\", \"fields\"];\n static override values = {\n delimiter: { type: String, default: \",\" },\n max: { type: Number, default: 0 },\n allowDuplicates: { type: Boolean, default: false },\n name: { type: String, default: \"tags[]\" },\n };\n static actions = [\"onKeydown\"] as const;\n static events = [\"change\", \"reject\"] as const;\n\n declare readonly inputTarget: HTMLInputElement;\n declare readonly tagsTarget: HTMLElement;\n declare readonly tagTargets: HTMLElement[];\n declare readonly tagTemplateTarget: HTMLTemplateElement;\n declare readonly statusTarget: HTMLElement;\n declare readonly fieldsTarget: HTMLElement;\n declare readonly hasStatusTarget: boolean;\n declare readonly hasFieldsTarget: boolean;\n declare readonly hasTagTemplateTarget: boolean;\n declare readonly hasInputTarget: boolean;\n\n declare delimiterValue: string;\n declare maxValue: number;\n declare allowDuplicatesValue: boolean;\n declare nameValue: string;\n\n readonly #roving = new RovingTabindex(() => this.#removeButtons);\n /** Owns IME lifecycle state for commit-key guarding. */\n readonly #composition = new CompositionTracker();\n\n /** Wires tag-list keyboard navigation and removal, and seeds the single Tab stop. */\n override connect(): void {\n if (this.hasInputTarget) this.#composition.observe(this.inputTarget);\n this.tagsTarget.addEventListener(\"keydown\", this.#onTagKeydown);\n this.tagsTarget.addEventListener(\"click\", this.#onTagClick);\n this.#syncState();\n }\n\n /** Releases the delegated listeners so no handler outlives the element. */\n override disconnect(): void {\n this.#composition.disconnect();\n this.tagsTarget.removeEventListener(\"keydown\", this.#onTagKeydown);\n this.tagsTarget.removeEventListener(\"click\", this.#onTagClick);\n }\n\n /** Tracks an input added initially or after connect. */\n inputTargetConnected(input: HTMLInputElement): void {\n this.#composition.observe(input);\n }\n\n /** Removes composition listeners when the active input is replaced or removed. */\n inputTargetDisconnected(input: HTMLInputElement): void {\n this.#composition.unobserve(input);\n }\n\n /** Commits on `Enter`/delimiter and deletes the last tag on empty `Backspace`. */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key must not ALSO commit a tag\n // or reach into the chips — composition depends on this yield.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n // Ignore keys fired during IME composition: the `Enter` that confirms a\n // candidate (and arrows that move within it) must not commit/navigate the\n // chip list. Controller-owned lifecycle state covers confirming events that\n // omit the standard per-event signal.\n if (this.#composition.isComposing(event)) return;\n if (event.key === \"Enter\" || event.key === this.delimiterValue) {\n event.preventDefault();\n this.#commitInput();\n return;\n }\n if (event.key === \"Backspace\" && this.inputTarget.value === \"\") {\n const buttons = this.#removeButtons;\n if (buttons.length > 0) {\n event.preventDefault();\n this.#removeAt(buttons.length - 1);\n }\n return;\n }\n // Same normalisation as the chip handler below, read from the same element.\n if (logicalArrowKey(event.key, this.element) === \"ArrowLeft\" && this.inputTarget.value === \"\") {\n const buttons = this.#removeButtons;\n if (buttons.length > 0) {\n event.preventDefault();\n this.#roving.setActive(buttons.length - 1, { focus: true });\n }\n }\n }\n\n /**\n * Deletes the tag whose remove button was clicked. Delegated on the tags\n * container (like `#onTagKeydown`) rather than bound per chip via\n * `data-action`, so it works the instant a chip is appended without waiting on\n * Stimulus to wire a freshly created element.\n */\n readonly #onTagClick = (event: MouseEvent): void => {\n const button = (event.target as HTMLElement).closest(\"button\");\n if (!button || !this.tagsTarget.contains(button)) return;\n const index = this.#removeButtons.indexOf(button as HTMLButtonElement);\n if (index !== -1) this.#removeAt(index);\n };\n\n /** Validates and adds the current input value as a tag, then clears the input. */\n #commitInput(): void {\n const value = this.inputTarget.value.trim();\n if (value === \"\") {\n this.#reject(value, \"empty\");\n return;\n }\n if (this.maxValue > 0 && this.tagTargets.length >= this.maxValue) {\n this.#reject(value, \"max\");\n return;\n }\n if (!this.allowDuplicatesValue && this.#values.includes(value)) {\n this.#reject(value, \"duplicate\");\n return;\n }\n this.#appendTag(value);\n this.inputTarget.value = \"\";\n this.#announce(value);\n this.#syncState();\n this.dispatch(\"change\", { detail: { tags: this.#values } });\n }\n\n /** Builds one chip from the template and appends it to the tag list. */\n #appendTag(value: string): void {\n if (!this.hasTagTemplateTarget) return;\n const fragment = this.tagTemplateTarget.content.cloneNode(true) as DocumentFragment;\n const tag = fragment.querySelector<HTMLElement>('[data-stimeo--tags-input-target=\"tag\"]');\n const label = fragment.querySelector<HTMLElement>('[data-tags-input-slot=\"label\"]');\n const button = fragment.querySelector<HTMLButtonElement>(\"button\");\n if (!tag || !button) return;\n tag.dataset.value = value;\n if (label) label.textContent = value;\n button.setAttribute(\"aria-label\", `Remove ${value}`);\n button.tabIndex = -1;\n this.tagsTarget.appendChild(fragment);\n }\n\n /** Removes the tag at `index`, then moves focus to a neighbor or the input. */\n #removeAt(index: number): void {\n const tag = this.tagTargets[index];\n if (!tag) return;\n const value = tag.dataset.value ?? \"\";\n tag.remove();\n this.#announce(value);\n this.#syncState();\n this.dispatch(\"change\", { detail: { tags: this.#values } });\n const remaining = this.#removeButtons;\n if (remaining.length === 0) {\n this.inputTarget.focus();\n } else {\n this.#roving.setActive(Math.min(index, remaining.length - 1), { focus: true });\n }\n }\n\n /** Handles arrow navigation and deletion within the chip list (delegated). */\n readonly #onTagKeydown = (event: KeyboardEvent): void => {\n // A descendant widget that already claimed the key must not ALSO move the\n // chip focus — composition depends on this yield. Chips render from the\n // consumer's template, so an arbitrary widget can live inside one.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n const button = (event.target as HTMLElement).closest(\"button\");\n if (!button) return;\n const buttons = this.#removeButtons;\n const index = buttons.indexOf(button);\n if (index === -1) return;\n // Logical, not physical. The key is normalised rather than a new case added:\n // the two horizontal branches are not mirror images — only one guards its\n // edge, and the other hands focus back to the input — so swapping the key\n // keeps each branch, guards and all, with its own direction. Both handlers\n // read the same element on purpose; probing the focused child would let the\n // input and the chips disagree at the boundary between them.\n switch (logicalArrowKey(event.key, this.element)) {\n case \"ArrowLeft\":\n if (index > 0) {\n event.preventDefault();\n this.#roving.setActive(index - 1, { focus: true });\n }\n break;\n case \"ArrowRight\":\n event.preventDefault();\n if (index < buttons.length - 1) {\n this.#roving.setActive(index + 1, { focus: true });\n } else {\n this.inputTarget.focus();\n }\n break;\n case \"Delete\":\n case \"Backspace\":\n event.preventDefault();\n this.#removeAt(index);\n break;\n default:\n break;\n }\n };\n\n /** Rebuilds the hidden form fields, the `full` flag, and the roving Tab stop. */\n #syncState(): void {\n if (this.hasFieldsTarget) {\n this.fieldsTarget.replaceChildren(\n ...this.#values.map((value) => {\n const input = document.createElement(\"input\");\n input.type = \"hidden\";\n input.name = this.nameValue;\n input.value = value;\n return input;\n }),\n );\n }\n const full = this.maxValue > 0 && this.tagTargets.length >= this.maxValue;\n this.element.toggleAttribute(\"data-stimeo--tags-input-full\", full);\n // Keep exactly one remove button tabbable so the chip list is a single stop.\n if (this.#removeButtons.length > 0 && this.#roving.activeIndex === -1) {\n this.#roving.setActive(0);\n }\n }\n\n /** Mirrors the changed tag into the live region for assistive tech. */\n #announce(value: string): void {\n if (this.hasStatusTarget) this.statusTarget.textContent = value;\n }\n\n /** Reports a rejected addition via `stimeo--tags-input:reject`. */\n #reject(value: string, reason: \"duplicate\" | \"empty\" | \"max\"): void {\n this.dispatch(\"reject\", { detail: { value, reason } });\n }\n\n /** The remove buttons in document order (the roving navigation set). */\n get #removeButtons(): HTMLButtonElement[] {\n return Array.from(this.tagsTarget.querySelectorAll<HTMLButtonElement>(\"button\"));\n }\n\n /** Current tag values in order. */\n get #values(): string[] {\n return this.tagTargets.map((tag) => tag.dataset.value ?? \"\");\n }\n}\n"]}
|
|
@@ -33,7 +33,7 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
33
33
|
* `aria-checked` + roving tabindex (APG radio) or the single button's `aria-pressed`
|
|
34
34
|
* in sync, and never moves focus. The `prefers-color-scheme` listener is attached on
|
|
35
35
|
* `connect()` and removed on `disconnect()` (Turbo included). FOUC avoidance for the
|
|
36
|
-
* very first paint is an inline `<head>` snippet
|
|
36
|
+
* very first paint is an inline `<head>` snippet, not this controller.
|
|
37
37
|
*/
|
|
38
38
|
declare class ThemeController extends Controller<HTMLElement> {
|
|
39
39
|
#private;
|