stimeo-ui 0.9.0 → 0.10.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 +74 -0
- package/dist/controllers/accordion_controller.js.map +1 -1
- package/dist/controllers/alert_dialog_controller.js +17 -7
- package/dist/controllers/alert_dialog_controller.js.map +1 -1
- package/dist/controllers/announcer_controller.js +1 -1
- package/dist/controllers/announcer_controller.js.map +1 -1
- package/dist/controllers/auto_submit_controller.js.map +1 -1
- package/dist/controllers/avatar_controller.js.map +1 -1
- package/dist/controllers/breadcrumb_controller.js.map +1 -1
- package/dist/controllers/bulk_select_controller.js +2 -2
- package/dist/controllers/bulk_select_controller.js.map +1 -1
- package/dist/controllers/calendar_controller.js.map +1 -1
- package/dist/controllers/carousel_controller.js.map +1 -1
- package/dist/controllers/character_counter_controller.js.map +1 -1
- package/dist/controllers/clipboard_controller.js.map +1 -1
- package/dist/controllers/collapsible_controller.d.ts +1 -1
- package/dist/controllers/collapsible_controller.js +1 -1
- package/dist/controllers/collapsible_controller.js.map +1 -1
- package/dist/controllers/color_picker_controller.d.ts +1 -1
- package/dist/controllers/color_picker_controller.js.map +1 -1
- package/dist/controllers/combobox_controller.js.map +1 -1
- package/dist/controllers/command_palette_controller.js +15 -5
- package/dist/controllers/command_palette_controller.js.map +1 -1
- package/dist/controllers/conditional_fields_controller.js.map +1 -1
- package/dist/controllers/confirm_controller.js +15 -5
- package/dist/controllers/confirm_controller.js.map +1 -1
- package/dist/controllers/context_menu_controller.d.ts +5 -4
- package/dist/controllers/context_menu_controller.js.map +1 -1
- package/dist/controllers/count_up_controller.js.map +1 -1
- package/dist/controllers/countdown_controller.js +1 -1
- package/dist/controllers/countdown_controller.js.map +1 -1
- package/dist/controllers/data_grid_controller.js +1 -1
- package/dist/controllers/data_grid_controller.js.map +1 -1
- package/dist/controllers/date_range_picker_controller.js.map +1 -1
- package/dist/controllers/dialog_controller.js +15 -5
- package/dist/controllers/dialog_controller.js.map +1 -1
- package/dist/controllers/direct_upload_controller.d.ts +2 -2
- package/dist/controllers/direct_upload_controller.js +1 -5
- package/dist/controllers/direct_upload_controller.js.map +1 -1
- package/dist/controllers/dismissible_controller.js.map +1 -1
- package/dist/controllers/drawer_controller.d.ts +2 -2
- package/dist/controllers/drawer_controller.js +17 -7
- package/dist/controllers/drawer_controller.js.map +1 -1
- package/dist/controllers/file_dropzone_controller.js.map +1 -1
- package/dist/controllers/flash_controller.js.map +1 -1
- package/dist/controllers/focus_controller.d.ts +5 -0
- package/dist/controllers/focus_controller.js +45 -7
- package/dist/controllers/focus_controller.js.map +1 -1
- package/dist/controllers/form_field_controller.js +1 -1
- package/dist/controllers/form_field_controller.js.map +1 -1
- package/dist/controllers/form_validation_controller.js.map +1 -1
- package/dist/controllers/frame_loading_controller.js.map +1 -1
- package/dist/controllers/highlight_controller.js.map +1 -1
- package/dist/controllers/input_mask_controller.js.map +1 -1
- package/dist/controllers/intersection_controller.d.ts +4 -3
- package/dist/controllers/intersection_controller.js.map +1 -1
- package/dist/controllers/lazy_frame_controller.d.ts +2 -2
- package/dist/controllers/lazy_frame_controller.js.map +1 -1
- package/dist/controllers/listbox_controller.js.map +1 -1
- package/dist/controllers/masonry_controller.d.ts +3 -1
- package/dist/controllers/masonry_controller.js.map +1 -1
- package/dist/controllers/menu_controller.d.ts +1 -1
- package/dist/controllers/menu_controller.js.map +1 -1
- package/dist/controllers/menubar_controller.js +2 -2
- package/dist/controllers/menubar_controller.js.map +1 -1
- package/dist/controllers/meter_controller.d.ts +1 -1
- package/dist/controllers/meter_controller.js.map +1 -1
- package/dist/controllers/multi_select_controller.js +1 -1
- package/dist/controllers/multi_select_controller.js.map +1 -1
- package/dist/controllers/navigation_menu_controller.js.map +1 -1
- package/dist/controllers/nested_form_controller.js.map +1 -1
- package/dist/controllers/number_input_controller.js.map +1 -1
- package/dist/controllers/otp_controller.js.map +1 -1
- package/dist/controllers/overflow_indicator_controller.js.map +1 -1
- package/dist/controllers/overflow_menu_controller.js +2 -2
- package/dist/controllers/overflow_menu_controller.js.map +1 -1
- package/dist/controllers/pagination_controller.d.ts +1 -1
- package/dist/controllers/pagination_controller.js.map +1 -1
- package/dist/controllers/password_reveal_controller.d.ts +27 -2
- package/dist/controllers/password_reveal_controller.js +102 -3
- package/dist/controllers/password_reveal_controller.js.map +1 -1
- package/dist/controllers/password_strength_controller.d.ts +71 -17
- package/dist/controllers/password_strength_controller.js +287 -42
- package/dist/controllers/password_strength_controller.js.map +1 -1
- package/dist/controllers/pointer_drag_controller.d.ts +3 -2
- package/dist/controllers/pointer_drag_controller.js.map +1 -1
- package/dist/controllers/popover_controller.js.map +1 -1
- package/dist/controllers/portal_controller.d.ts +1 -1
- 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.map +1 -1
- package/dist/controllers/range_slider_controller.js.map +1 -1
- package/dist/controllers/rating_controller.js.map +1 -1
- package/dist/controllers/read_more_controller.js.map +1 -1
- package/dist/controllers/relative_time_controller.js.map +1 -1
- package/dist/controllers/reset_before_cache_controller.d.ts +1 -2
- package/dist/controllers/reset_before_cache_controller.js.map +1 -1
- package/dist/controllers/resizable_controller.d.ts +1 -1
- package/dist/controllers/resizable_controller.js +1 -1
- package/dist/controllers/resizable_controller.js.map +1 -1
- package/dist/controllers/roving_controller.d.ts +2 -1
- package/dist/controllers/roving_controller.js.map +1 -1
- package/dist/controllers/scroll_area_controller.js.map +1 -1
- package/dist/controllers/scroll_restore_controller.d.ts +33 -11
- package/dist/controllers/scroll_restore_controller.js +127 -27
- package/dist/controllers/scroll_restore_controller.js.map +1 -1
- package/dist/controllers/scroll_visibility_controller.d.ts +42 -10
- package/dist/controllers/scroll_visibility_controller.js +167 -14
- package/dist/controllers/scroll_visibility_controller.js.map +1 -1
- package/dist/controllers/scrollspy_controller.js.map +1 -1
- package/dist/controllers/separator_controller.js.map +1 -1
- package/dist/controllers/sidebar_controller.js +15 -5
- package/dist/controllers/sidebar_controller.js.map +1 -1
- package/dist/controllers/skeleton_controller.js.map +1 -1
- package/dist/controllers/slider_controller.js.map +1 -1
- package/dist/controllers/spinner_controller.js.map +1 -1
- package/dist/controllers/step_indicator_controller.js +0 -5
- package/dist/controllers/step_indicator_controller.js.map +1 -1
- package/dist/controllers/stick_to_bottom_controller.d.ts +3 -2
- package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
- package/dist/controllers/submit_once_controller.js.map +1 -1
- package/dist/controllers/switch_controller.js.map +1 -1
- package/dist/controllers/tabs_controller.js.map +1 -1
- package/dist/controllers/tags_input_controller.js.map +1 -1
- package/dist/controllers/textarea_autosize_controller.js.map +1 -1
- package/dist/controllers/theme_controller.d.ts +32 -6
- package/dist/controllers/theme_controller.js +151 -40
- package/dist/controllers/theme_controller.js.map +1 -1
- package/dist/controllers/time_picker_controller.js.map +1 -1
- package/dist/controllers/toast_controller.d.ts +2 -2
- package/dist/controllers/toast_controller.js +2 -2
- package/dist/controllers/toast_controller.js.map +1 -1
- package/dist/controllers/toggle_group_controller.js.map +1 -1
- package/dist/controllers/toolbar_controller.js.map +1 -1
- package/dist/controllers/transition_controller.d.ts +11 -7
- package/dist/controllers/transition_controller.js +79 -15
- package/dist/controllers/transition_controller.js.map +1 -1
- package/dist/controllers/tree_view_controller.js.map +1 -1
- package/dist/index.d.ts +6 -3
- package/dist/index.js +740 -178
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.d.ts +3 -4
- package/dist/inspector/cli.js +1 -0
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js +6 -5
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +3 -3
- package/dist/inspector/manifest.json +7 -4
- package/dist/positioning/index.d.ts +18 -4
- package/dist/positioning/index.js +84 -25
- package/dist/positioning/index.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/before_cache_reset.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,CAAM,MAAA,GAAS,MAAA;AACf,EAAA,KAAA,CAAM,OAAA,GAAU,GAAA;AAChB,EAAA,KAAA,CAAM,MAAA,GAAS,GAAA;AACf,EAAA,KAAA,CAAM,QAAA,GAAW,QAAA;AACjB,EAAA,KAAA,CAAM,IAAA,GAAO,eAAA;AACb,EAAA,KAAA,CAAM,QAAA,GAAW,YAAA;AACjB,EAAA,KAAA,CAAM,UAAA,GAAa,QAAA;AACrB","file":"announcer_controller.js","sourcesContent":["/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way (the `MicrotaskCoalescer` split).\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","/**\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 { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** The two politeness levels this controller keeps a region for. */\nconst LEVELS = [\"polite\", \"assertive\"] as const;\n\n/** One of the politeness levels in {@link LEVELS}. */\ntype Level = (typeof LEVELS)[number];\n\n/**\n * Headless, shared **live-region announcer** — a polite/assertive screen-reader\n * announcement base (no dedicated APG pattern; follows the WAI-ARIA \"Alert\" /\n * \"Status\" live-region guidance and WCAG 2.2 **4.1.3 Status Messages**).\n *\n * Markup contract (identifier: `stimeo--announcer`):\n * <!-- Place once per page; the consumer visually hides the regions in CSS. -->\n * <div data-controller=\"stimeo--announcer\">\n * <div data-stimeo--announcer-target=\"polite\" aria-live=\"polite\" aria-atomic=\"true\"></div>\n * <div data-stimeo--announcer-target=\"assertive\" aria-live=\"assertive\" aria-atomic=\"true\"></div>\n * </div>\n *\n * <!-- Attribute-only trigger: declare the activation event explicitly. -->\n * <button data-action=\"click->stimeo--announcer#announce\"\n * data-stimeo--announcer-message-param=\"Saved\"\n * data-stimeo--announcer-assertive-param=\"false\">Save</button>\n *\n * <!-- Programmatic trigger (e.g. from another controller / Turbo Stream). -->\n * window.dispatchEvent(new CustomEvent(\"stimeo--announcer:announce\", {\n * detail: { message: \"12 results\", assertive: false },\n * }))\n *\n * The announcer is the shared substrate other controllers (Auto-Submit, Flash,\n * Bulk Select, …) lean on instead of each carrying their own live region.\n *\n * @remarks\n * Behavior only, with **one deliberate exception**: when a `polite`/`assertive`\n * target is absent the controller *generates* the missing region **on connect**\n * and applies the canonical visually-hidden inline style (see {@link visuallyHide}).\n * A live region must exist and be visually hidden to do its job, and a generated\n * node has no consumer CSS hook to hide it; consumers who want to own styling\n * supply their own targets. Generation happens up front rather than on the first\n * announcement because assistive tech reports changes to a region it already\n * knows about — a region created and written within one task loses that first\n * message. The controller never moves focus — announcements must not steal it\n * (WCAG 2.2 4.1.3). Listeners and clear timers are torn down on `disconnect()`\n * (Turbo included), and any generated regions are removed — from the cached\n * snapshot too, via {@link BeforeCacheReset}, because `connect()` cannot reuse a\n * restored region (it carries no target attribute) and would pair another one\n * with it on every visit.\n *\n * **Messages are queued, one write per task.** Assistive tech announces what it\n * observes changing, so two messages written into one region within a single task\n * are one observed change and the earlier message is never read. Each politeness\n * has its own FIFO — an assertive message never waits behind polite ones — and a\n * message is written only in a task where its region already existed.\n *\n * **The region set is kept whole while connected.** Exactly one region per\n * politeness is present: an authored target retires the stand-in generated for it,\n * losing one materialises a stand-in again, and a generated region removed by a\n * morph (it is absent from the server's HTML, so a morph drops it) is put back\n * without waiting for the next message.\n */\nexport class AnnouncerController extends Controller<HTMLElement> {\n static override targets = [\"polite\", \"assertive\"];\n static override values = {\n clearAfter: { type: Number, default: 1000 },\n dedupeReannounce: { type: Boolean, default: true },\n };\n static actions = [\"announce\"] as const;\n\n declare readonly politeTarget: HTMLElement;\n declare readonly assertiveTarget: HTMLElement;\n declare readonly hasPoliteTarget: boolean;\n declare readonly hasAssertiveTarget: boolean;\n\n declare clearAfterValue: number;\n declare dedupeReannounceValue: boolean;\n\n /** Clear/re-announce timers; one `clearAll()` in disconnect tears them all down. */\n readonly #timers = new SafeTimeout();\n\n /** Live regions generated to stand in for absent targets, for teardown. */\n readonly #generated = new Map<Level, HTMLElement>();\n\n /** Messages waiting to be written, oldest first, one queue per politeness. */\n readonly #queues = new Map<Level, string[]>();\n\n /** Politeness levels whose next drain is already armed. */\n readonly #draining = new Set<Level>();\n\n /** Collapses a batch of target callbacks (and morph removals) into one pass. */\n readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileRegions());\n\n /**\n * Watches the host's own children for a generated region disappearing. A morph\n * drops it — the server's HTML never had it — and no target callback reports\n * that, because a generated region carries no target attribute. `subtree` stays\n * off so writing a message inside a region does not re-enter this pass.\n */\n readonly #hostWatch = new MutationObserver(() => {\n this.#reconcile.schedule();\n });\n\n /** Rewinds to an announceable initial state for the snapshot; see the remarks. */\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n\n /**\n * The one timer a region may have outstanding — its dedupe re-set, then its\n * auto-clear. Held weakly so a swapped-out target is not retained; a leftover\n * id is harmless because {@link SafeTimeout.clear} no-ops on an id it does not\n * own.\n */\n readonly #pending = new WeakMap<HTMLElement, number>();\n\n /**\n * Guards against handling the same CustomEvent twice. An event dispatched on\n * the controller element with `bubbles: true` reaches both the element and the\n * `window` listener; this WeakSet ensures it announces only once.\n */\n readonly #handled = new WeakSet<Event>();\n\n /** Receives programmatic announcements at the element or bubbled to `window`. */\n readonly #onAnnounceEvent = (event: Event): void => {\n if (this.#handled.has(event)) return;\n this.#handled.add(event);\n const detail = (event as CustomEvent<unknown>).detail;\n const message = this.#messageFromDetail(detail);\n if (!message) return;\n this.#announce(message, this.#assertiveFromDetail(detail));\n };\n\n override connect(): void {\n this.#reconcile.activate();\n this.#beforeCache.activate();\n // Materialise any missing region now, so it is in the accessibility tree\n // before the first message rather than appearing with it.\n this.#reconcileRegions();\n this.#hostWatch.observe(this.element, { childList: true });\n this.element.addEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n window.addEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n }\n\n override disconnect(): void {\n this.#reconcile.cancel();\n this.#hostWatch.disconnect();\n this.#beforeCache.deactivate();\n this.element.removeEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n window.removeEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n this.#timers.clearAll();\n this.#queues.clear();\n this.#draining.clear();\n this.#removeGenerated();\n }\n\n /** Retires the stand-in once the consumer supplies a polite region. */\n politeTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Materialises a stand-in once the consumer's polite region goes away. */\n politeTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Retires the stand-in once the consumer supplies an assertive region. */\n assertiveTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Materialises a stand-in once the consumer's assertive region goes away. */\n assertiveTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /**\n * Brings the region set back to exactly one region per politeness and reports\n * whether anything had to be created.\n *\n * A region created here is not written to in the same task: assistive tech\n * reports changes to regions it already knows about, so {@link drain} waits a\n * task whenever this says a region is new.\n */\n #reconcileRegions(): boolean {\n let created = false;\n for (const level of LEVELS) {\n if (this.#hasTargetFor(level)) {\n // The consumer owns this politeness now; a stand-in would be a second\n // region for it, and an empty one nothing ever writes to.\n const generated = this.#generated.get(level);\n if (generated) {\n generated.remove();\n this.#generated.delete(level);\n }\n continue;\n }\n const existing = this.#generated.get(level);\n if (existing?.isConnected) continue;\n this.#generated.set(level, this.#createRegion(level));\n created = true;\n }\n return created;\n }\n\n /** Whether the consumer supplied a target for `level`. */\n #hasTargetFor(level: Level): boolean {\n return level === \"assertive\" ? this.hasAssertiveTarget : this.hasPoliteTarget;\n }\n\n /** Builds a visually hidden live region for `level` and attaches it. */\n #createRegion(level: Level): HTMLElement {\n const region = document.createElement(\"div\");\n region.setAttribute(\"aria-live\", level);\n region.setAttribute(\"aria-atomic\", \"true\");\n visuallyHide(region);\n this.element.appendChild(region);\n return region;\n }\n\n /**\n * Removes and forgets every region this controller generated. Authored targets\n * belong to the consumer and are left untouched. Forgetting them is what keeps\n * the live page working after a snapshot rewind: the next announcement finds an\n * empty map and materialises a fresh region.\n */\n #removeGenerated(): void {\n for (const region of this.#generated.values()) {\n region.remove();\n }\n this.#generated.clear();\n }\n\n /**\n * Announces a message. Reads the text from a Stimulus action param\n * (`message`, plus optional `assertive`) for attribute-only triggers, falling\n * back to a CustomEvent `detail` when the same handler is wired to an event.\n * An empty/non-string message is ignored so untrusted payloads cannot blank\n * the region.\n */\n announce(event: Event): void {\n const params = (event as { params?: Record<string, unknown> }).params;\n const fromParam = params?.message;\n const message =\n typeof fromParam === \"string\" && fromParam.length > 0\n ? fromParam\n : this.#messageFromDetail((event as CustomEvent<unknown>).detail);\n if (!message) return;\n\n const assertive =\n params?.assertive === true ||\n this.#assertiveFromDetail((event as CustomEvent<unknown>).detail);\n this.#announce(message, assertive);\n }\n\n /**\n * Queues `message` for its politeness and arms the drain.\n *\n * Queuing is what makes a burst audible: assistive tech announces the changes it\n * observes, so several messages written into one region within a single task are\n * one change and only the last is read.\n */\n #announce(message: string, assertive: boolean): void {\n const level: Level = assertive ? \"assertive\" : \"polite\";\n const queue = this.#queues.get(level);\n if (queue) {\n queue.push(message);\n } else {\n this.#queues.set(level, [message]);\n }\n this.#scheduleDrain(level);\n }\n\n /** Arms one drain pass for `level`; further messages ride the pass already armed. */\n #scheduleDrain(level: Level): void {\n if (this.#draining.has(level)) return;\n this.#draining.add(level);\n this.#timers.set(() => {\n this.#draining.delete(level);\n this.#drain(level);\n }, 0);\n }\n\n /**\n * Writes one queued message, then arms the next pass while the queue holds more.\n *\n * Two steps take a whole pass without consuming the message: materialising a\n * region (it has to be in the accessibility tree before the text arrives) and\n * emptying a region that already holds this exact text (an unchanged node is not\n * re-read, so `dedupeReannounce` clears first and writes on the following pass).\n */\n #drain(level: Level): void {\n const queue = this.#queues.get(level);\n const message = queue?.[0];\n if (queue === undefined || message === undefined) return;\n\n if (this.#reconcileRegions()) {\n this.#scheduleDrain(level);\n return;\n }\n\n const region = this.#regionFor(level);\n if (this.dedupeReannounceValue && region.textContent === message) {\n this.#cancelPending(region);\n region.textContent = \"\";\n this.#scheduleDrain(level);\n return;\n }\n\n queue.shift();\n this.#cancelPending(region);\n region.textContent = message;\n this.#scheduleClear(region, message);\n if (queue.length > 0) this.#scheduleDrain(level);\n }\n\n /** Clears the region after `clearAfter` ms, unless a newer message replaced it. */\n #scheduleClear(region: HTMLElement, message: string): void {\n if (this.clearAfterValue <= 0) return;\n this.#schedule(\n region,\n () => {\n if (region.textContent === message) region.textContent = \"\";\n },\n this.clearAfterValue,\n );\n }\n\n /**\n * Arms `region`'s single pending timer. Callers reach here with the slot\n * already free — `#announce` releases it, and a fired timer clears its own\n * entry below — so this does not cancel again.\n */\n #schedule(region: HTMLElement, callback: () => void, delay: number): void {\n const id = this.#timers.set(() => {\n // Drop the id as it fires: platform timer ids are recycled, and a stale\n // one left here could later cancel the *other* region's live timer.\n this.#pending.delete(region);\n callback();\n }, delay);\n this.#pending.set(region, id);\n }\n\n /** Releases `region`'s pending timer, if it has one. */\n #cancelPending(region: HTMLElement): void {\n // `SafeTimeout.clear` ignores an id it does not own, so the \"no pending\n // timer\" case needs no branch of its own.\n this.#timers.clear(this.#pending.get(region) ?? -1);\n this.#pending.delete(region);\n }\n\n /**\n * Resolves the live region for a politeness level.\n *\n * The remembered stand-in is used only while it is still in the document: a morph\n * can drop it, and writing into the detached node would announce nothing at all.\n */\n #regionFor(level: Level): HTMLElement {\n if (level === \"assertive\" && this.hasAssertiveTarget) return this.assertiveTarget;\n if (level === \"polite\" && this.hasPoliteTarget) return this.politeTarget;\n\n const existing = this.#generated.get(level);\n if (existing?.isConnected) return existing;\n\n const region = this.#createRegion(level);\n this.#generated.set(level, region);\n return region;\n }\n\n /**\n * Restores the announceable initial state for the snapshot Turbo is about to\n * take: queued and displayed messages go, generated regions go, and the live\n * page — which keeps running when a visit is aborted — gets its regions back on\n * the next task, after the clone.\n */\n #rewindForCache(): void {\n this.#queues.clear();\n this.#draining.clear();\n this.#timers.clearAll();\n for (const level of LEVELS) {\n if (this.#hasTargetFor(level)) {\n const target = level === \"assertive\" ? this.assertiveTarget : this.politeTarget;\n target.textContent = \"\";\n }\n }\n this.#removeGenerated();\n this.#timers.set(() => this.#reconcileRegions(), 0);\n }\n\n /** Extracts a non-empty string `message` from a CustomEvent detail, else null. */\n #messageFromDetail(detail: unknown): string | null {\n if (detail && typeof detail === \"object\" && \"message\" in detail) {\n const value = (detail as Record<string, unknown>).message;\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return null;\n }\n\n /** Reads an `assertive === true` flag from a CustomEvent detail (default polite). */\n #assertiveFromDetail(detail: unknown): boolean {\n return (\n !!detail &&\n typeof detail === \"object\" &&\n (detail as Record<string, unknown>).assertive === true\n );\n }\n}\n\n/**\n * Applies the canonical visually-hidden (\"sr-only\") inline style to a generated\n * live region so its text is announced without being seen. Inline so the library\n * stays self-contained when the consumer provides no target/CSS of its own.\n *\n * Pure (no `this`); exported for direct unit testing.\n */\nexport function visuallyHide(node: HTMLElement): void {\n const { style } = node;\n style.position = \"absolute\";\n style.width = \"1px\";\n style.height = \"1px\";\n style.margin = \"-1px\";\n style.padding = \"0\";\n style.border = \"0\";\n style.overflow = \"hidden\";\n style.clip = \"rect(0 0 0 0)\";\n style.clipPath = \"inset(50%)\";\n style.whiteSpace = \"nowrap\";\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/before_cache_reset.ts","../../src/utils/microtask_coalescer.ts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;AACf,EAAA,KAAA,CAAM,OAAA,GAAU,GAAA;AAChB,EAAA,KAAA,CAAM,MAAA,GAAS,GAAA;AACf,EAAA,KAAA,CAAM,QAAA,GAAW,QAAA;AACjB,EAAA,KAAA,CAAM,IAAA,GAAO,eAAA;AACb,EAAA,KAAA,CAAM,QAAA,GAAW,YAAA;AACjB,EAAA,KAAA,CAAM,UAAA,GAAa,QAAA;AACrB","file":"announcer_controller.js","sourcesContent":["/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way.\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","/**\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 { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** The two politeness levels this controller keeps a region for. */\nconst LEVELS = [\"polite\", \"assertive\"] as const;\n\n/** One of the politeness levels in {@link LEVELS}. */\ntype Level = (typeof LEVELS)[number];\n\n/**\n * Headless, shared **live-region announcer** — a polite/assertive screen-reader\n * announcement base (no dedicated APG pattern; follows the WAI-ARIA \"Alert\" /\n * \"Status\" live-region guidance and WCAG 2.2 **4.1.3 Status Messages**).\n *\n * Markup contract (identifier: `stimeo--announcer`):\n * <!-- Place once per page; the consumer visually hides the regions in CSS. -->\n * <div data-controller=\"stimeo--announcer\">\n * <div data-stimeo--announcer-target=\"polite\" aria-live=\"polite\" aria-atomic=\"true\"></div>\n * <div data-stimeo--announcer-target=\"assertive\" aria-live=\"assertive\" aria-atomic=\"true\"></div>\n * </div>\n *\n * <!-- Attribute-only trigger: declare the activation event explicitly. -->\n * <button data-action=\"click->stimeo--announcer#announce\"\n * data-stimeo--announcer-message-param=\"Saved\"\n * data-stimeo--announcer-assertive-param=\"false\">Save</button>\n *\n * <!-- Programmatic trigger (e.g. from another controller / Turbo Stream). -->\n * window.dispatchEvent(new CustomEvent(\"stimeo--announcer:announce\", {\n * detail: { message: \"12 results\", assertive: false },\n * }))\n *\n * The announcer is the shared substrate other controllers (Auto-Submit, Flash,\n * Bulk Select, …) lean on instead of each carrying their own live region.\n *\n * @remarks\n * Behavior only, with **one deliberate exception**: when a `polite`/`assertive`\n * target is absent the controller *generates* the missing region **on connect**\n * and applies the canonical visually-hidden inline style (see {@link visuallyHide}).\n * A live region must exist and be visually hidden to do its job, and a generated\n * node has no consumer CSS hook to hide it; consumers who want to own styling\n * supply their own targets. Generation happens up front rather than on the first\n * announcement because assistive tech reports changes to a region it already\n * knows about — a region created and written within one task loses that first\n * message. The controller never moves focus — announcements must not steal it\n * (WCAG 2.2 4.1.3). Listeners and clear timers are torn down on `disconnect()`\n * (Turbo included), and any generated regions are removed — from the cached\n * snapshot too, via {@link BeforeCacheReset}, because `connect()` cannot reuse a\n * restored region (it carries no target attribute) and would pair another one\n * with it on every visit.\n *\n * **Messages are queued, one write per task.** Assistive tech announces what it\n * observes changing, so two messages written into one region within a single task\n * are one observed change and the earlier message is never read. Each politeness\n * has its own FIFO — an assertive message never waits behind polite ones — and a\n * message is written only in a task where its region already existed.\n *\n * **The region set is kept whole while connected.** Exactly one region per\n * politeness is present: an authored target retires the stand-in generated for it,\n * losing one materialises a stand-in again, and a generated region removed by a\n * morph (it is absent from the server's HTML, so a morph drops it) is put back\n * without waiting for the next message.\n */\nexport class AnnouncerController extends Controller<HTMLElement> {\n static override targets = [\"polite\", \"assertive\"];\n static override values = {\n clearAfter: { type: Number, default: 1000 },\n dedupeReannounce: { type: Boolean, default: true },\n };\n static actions = [\"announce\"] as const;\n\n declare readonly politeTarget: HTMLElement;\n declare readonly assertiveTarget: HTMLElement;\n declare readonly hasPoliteTarget: boolean;\n declare readonly hasAssertiveTarget: boolean;\n\n declare clearAfterValue: number;\n declare dedupeReannounceValue: boolean;\n\n /** Clear/re-announce timers; one `clearAll()` in disconnect tears them all down. */\n readonly #timers = new SafeTimeout();\n\n /** Live regions generated to stand in for absent targets, for teardown. */\n readonly #generated = new Map<Level, HTMLElement>();\n\n /** Messages waiting to be written, oldest first, one queue per politeness. */\n readonly #queues = new Map<Level, string[]>();\n\n /** Politeness levels whose next drain is already armed. */\n readonly #draining = new Set<Level>();\n\n /** Collapses a batch of target callbacks (and morph removals) into one pass. */\n readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileRegions());\n\n /**\n * Watches the host's own children for a generated region disappearing. A morph\n * drops it — the server's HTML never had it — and no target callback reports\n * that, because a generated region carries no target attribute. `subtree` stays\n * off so writing a message inside a region does not re-enter this pass.\n */\n readonly #hostWatch = new MutationObserver(() => {\n this.#reconcile.schedule();\n });\n\n /** Rewinds to an announceable initial state for the snapshot; see the remarks. */\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n\n /**\n * The one timer a region may have outstanding — its dedupe re-set, then its\n * auto-clear. Held weakly so a swapped-out target is not retained; a leftover\n * id is harmless because {@link SafeTimeout.clear} no-ops on an id it does not\n * own.\n */\n readonly #pending = new WeakMap<HTMLElement, number>();\n\n /**\n * Guards against handling the same CustomEvent twice. An event dispatched on\n * the controller element with `bubbles: true` reaches both the element and the\n * `window` listener; this WeakSet ensures it announces only once.\n */\n readonly #handled = new WeakSet<Event>();\n\n /** Receives programmatic announcements at the element or bubbled to `window`. */\n readonly #onAnnounceEvent = (event: Event): void => {\n if (this.#handled.has(event)) return;\n this.#handled.add(event);\n const detail = (event as CustomEvent<unknown>).detail;\n const message = this.#messageFromDetail(detail);\n if (!message) return;\n this.#announce(message, this.#assertiveFromDetail(detail));\n };\n\n override connect(): void {\n this.#reconcile.activate();\n this.#beforeCache.activate();\n // Materialise any missing region now, so it is in the accessibility tree\n // before the first message rather than appearing with it.\n this.#reconcileRegions();\n this.#hostWatch.observe(this.element, { childList: true });\n this.element.addEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n window.addEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n }\n\n override disconnect(): void {\n this.#reconcile.cancel();\n this.#hostWatch.disconnect();\n this.#beforeCache.deactivate();\n this.element.removeEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n window.removeEventListener(\"stimeo--announcer:announce\", this.#onAnnounceEvent);\n this.#timers.clearAll();\n this.#queues.clear();\n this.#draining.clear();\n this.#removeGenerated();\n }\n\n /** Retires the stand-in once the consumer supplies a polite region. */\n politeTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Materialises a stand-in once the consumer's polite region goes away. */\n politeTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Retires the stand-in once the consumer supplies an assertive region. */\n assertiveTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Materialises a stand-in once the consumer's assertive region goes away. */\n assertiveTargetDisconnected(): void {\n this.#reconcile.schedule();\n }\n\n /**\n * Brings the region set back to exactly one region per politeness and reports\n * whether anything had to be created.\n *\n * A region created here is not written to in the same task: assistive tech\n * reports changes to regions it already knows about, so {@link drain} waits a\n * task whenever this says a region is new.\n */\n #reconcileRegions(): boolean {\n let created = false;\n for (const level of LEVELS) {\n if (this.#hasTargetFor(level)) {\n // The consumer owns this politeness now; a stand-in would be a second\n // region for it, and an empty one nothing ever writes to.\n const generated = this.#generated.get(level);\n if (generated) {\n generated.remove();\n this.#generated.delete(level);\n }\n continue;\n }\n const existing = this.#generated.get(level);\n if (existing?.isConnected) continue;\n this.#generated.set(level, this.#createRegion(level));\n created = true;\n }\n return created;\n }\n\n /** Whether the consumer supplied a target for `level`. */\n #hasTargetFor(level: Level): boolean {\n return level === \"assertive\" ? this.hasAssertiveTarget : this.hasPoliteTarget;\n }\n\n /** Builds a visually hidden live region for `level` and attaches it. */\n #createRegion(level: Level): HTMLElement {\n const region = document.createElement(\"div\");\n region.setAttribute(\"aria-live\", level);\n region.setAttribute(\"aria-atomic\", \"true\");\n visuallyHide(region);\n this.element.appendChild(region);\n return region;\n }\n\n /**\n * Removes and forgets every region this controller generated. Authored targets\n * belong to the consumer and are left untouched. Forgetting them is what keeps\n * the live page working after a snapshot rewind: the next announcement finds an\n * empty map and materialises a fresh region.\n */\n #removeGenerated(): void {\n for (const region of this.#generated.values()) {\n region.remove();\n }\n this.#generated.clear();\n }\n\n /**\n * Announces a message. Reads the text from a Stimulus action param\n * (`message`, plus optional `assertive`) for attribute-only triggers, falling\n * back to a CustomEvent `detail` when the same handler is wired to an event.\n * An empty/non-string message is ignored so untrusted payloads cannot blank\n * the region.\n */\n announce(event: Event): void {\n const params = (event as { params?: Record<string, unknown> }).params;\n const fromParam = params?.message;\n const message =\n typeof fromParam === \"string\" && fromParam.length > 0\n ? fromParam\n : this.#messageFromDetail((event as CustomEvent<unknown>).detail);\n if (!message) return;\n\n const assertive =\n params?.assertive === true ||\n this.#assertiveFromDetail((event as CustomEvent<unknown>).detail);\n this.#announce(message, assertive);\n }\n\n /**\n * Queues `message` for its politeness and arms the drain.\n *\n * Queuing is what makes a burst audible: assistive tech announces the changes it\n * observes, so several messages written into one region within a single task are\n * one change and only the last is read.\n */\n #announce(message: string, assertive: boolean): void {\n const level: Level = assertive ? \"assertive\" : \"polite\";\n const queue = this.#queues.get(level);\n if (queue) {\n queue.push(message);\n } else {\n this.#queues.set(level, [message]);\n }\n this.#scheduleDrain(level);\n }\n\n /** Arms one drain pass for `level`; further messages ride the pass already armed. */\n #scheduleDrain(level: Level): void {\n if (this.#draining.has(level)) return;\n this.#draining.add(level);\n this.#timers.set(() => {\n this.#draining.delete(level);\n this.#drain(level);\n }, 0);\n }\n\n /**\n * Writes one queued message, then arms the next pass while the queue holds more.\n *\n * Two steps take a whole pass without consuming the message: materialising a\n * region (it has to be in the accessibility tree before the text arrives) and\n * emptying a region that already holds this exact text (an unchanged node is not\n * re-read, so `dedupeReannounce` clears first and writes on the following pass).\n */\n #drain(level: Level): void {\n const queue = this.#queues.get(level);\n const message = queue?.[0];\n if (queue === undefined || message === undefined) return;\n\n if (this.#reconcileRegions()) {\n this.#scheduleDrain(level);\n return;\n }\n\n const region = this.#regionFor(level);\n if (this.dedupeReannounceValue && region.textContent === message) {\n this.#cancelPending(region);\n region.textContent = \"\";\n this.#scheduleDrain(level);\n return;\n }\n\n queue.shift();\n this.#cancelPending(region);\n region.textContent = message;\n this.#scheduleClear(region, message);\n if (queue.length > 0) this.#scheduleDrain(level);\n }\n\n /** Clears the region after `clearAfter` ms, unless a newer message replaced it. */\n #scheduleClear(region: HTMLElement, message: string): void {\n if (this.clearAfterValue <= 0) return;\n this.#schedule(\n region,\n () => {\n if (region.textContent === message) region.textContent = \"\";\n },\n this.clearAfterValue,\n );\n }\n\n /**\n * Arms `region`'s single pending timer. Callers reach here with the slot\n * already free — `#drain` releases it before writing, and a fired timer clears its own\n * entry below — so this does not cancel again.\n */\n #schedule(region: HTMLElement, callback: () => void, delay: number): void {\n const id = this.#timers.set(() => {\n // Drop the id as it fires: platform timer ids are recycled, and a stale\n // one left here could later cancel the *other* region's live timer.\n this.#pending.delete(region);\n callback();\n }, delay);\n this.#pending.set(region, id);\n }\n\n /** Releases `region`'s pending timer, if it has one. */\n #cancelPending(region: HTMLElement): void {\n // `SafeTimeout.clear` ignores an id it does not own, so the \"no pending\n // timer\" case needs no branch of its own.\n this.#timers.clear(this.#pending.get(region) ?? -1);\n this.#pending.delete(region);\n }\n\n /**\n * Resolves the live region for a politeness level.\n *\n * The remembered stand-in is used only while it is still in the document: a morph\n * can drop it, and writing into the detached node would announce nothing at all.\n */\n #regionFor(level: Level): HTMLElement {\n if (level === \"assertive\" && this.hasAssertiveTarget) return this.assertiveTarget;\n if (level === \"polite\" && this.hasPoliteTarget) return this.politeTarget;\n\n const existing = this.#generated.get(level);\n if (existing?.isConnected) return existing;\n\n const region = this.#createRegion(level);\n this.#generated.set(level, region);\n return region;\n }\n\n /**\n * Restores the announceable initial state for the snapshot Turbo is about to\n * take: queued and displayed messages go, generated regions go, and the live\n * page — which keeps running when a visit is aborted — gets its regions back on\n * the next task, after the clone.\n */\n #rewindForCache(): void {\n this.#queues.clear();\n this.#draining.clear();\n this.#timers.clearAll();\n for (const level of LEVELS) {\n if (this.#hasTargetFor(level)) {\n const target = level === \"assertive\" ? this.assertiveTarget : this.politeTarget;\n target.textContent = \"\";\n }\n }\n this.#removeGenerated();\n this.#timers.set(() => this.#reconcileRegions(), 0);\n }\n\n /** Extracts a non-empty string `message` from a CustomEvent detail, else null. */\n #messageFromDetail(detail: unknown): string | null {\n if (detail && typeof detail === \"object\" && \"message\" in detail) {\n const value = (detail as Record<string, unknown>).message;\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return null;\n }\n\n /** Reads an `assertive === true` flag from a CustomEvent detail (default polite). */\n #assertiveFromDetail(detail: unknown): boolean {\n return (\n !!detail &&\n typeof detail === \"object\" &&\n (detail as Record<string, unknown>).assertive === true\n );\n }\n}\n\n/**\n * Applies the canonical visually-hidden (\"sr-only\") inline style to a generated\n * live region so its text is announced without being seen. Inline so the library\n * stays self-contained when the consumer provides no target/CSS of its own.\n *\n * Pure (no `this`); exported for direct unit testing.\n */\nexport function visuallyHide(node: HTMLElement): void {\n const { style } = node;\n style.position = \"absolute\";\n style.width = \"1px\";\n style.height = \"1px\";\n style.margin = \"-1px\";\n style.padding = \"0\";\n style.border = \"0\";\n style.overflow = \"hidden\";\n style.clip = \"rect(0 0 0 0)\";\n style.clipPath = \"inset(50%)\";\n style.whiteSpace = \"nowrap\";\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/before_cache_reset.ts","../../src/utils/composition_tracker.ts","../../src/utils/safe_timeout.ts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F","file":"auto_submit_controller.js","sourcesContent":["/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way (the `MicrotaskCoalescer` split).\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\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 * 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 { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/**\n * Headless **debounced auto-submit** for forms (no dedicated APG pattern). Submits\n * the form a configurable delay after `input`/`change`, so Rails search/filter\n * forms refresh via Turbo without a submit button.\n *\n * Markup contract (identifier: `stimeo--auto-submit`):\n * <form data-controller=\"stimeo--auto-submit\"\n * data-stimeo--auto-submit-debounce-value=\"300\"\n * data-action=\"input->stimeo--auto-submit#submit\n * change->stimeo--auto-submit#submit\">\n * <input type=\"search\" name=\"q\">\n * </form>\n *\n * <!-- Or with the form as a target nested under the controller element: -->\n * <div data-controller=\"stimeo--auto-submit\">\n * <form data-stimeo--auto-submit-target=\"form\"> … </form>\n * </div>\n *\n * `submit` dispatches `{ trigger }`; `done` dispatches `{ message? }`.\n * `reconcile` dispatches `{}` when the Turbo cache rewind drops a submission\n * that was pending or in flight — `done` would claim a response arrived.\n *\n * @remarks\n * Behavior only — it owns *triggering* the submit (debounce + `requestSubmit`),\n * never the submit itself (Turbo / native form submission) or validation. It\n * **never moves focus** (WCAG 2.2 3.2.2 / 4.1.3): auto-submitting must not yank the\n * caret out of the field. While a result swap is silent for screen-reader users,\n * setting `announce` bridges the completion to the shared `stimeo--announcer`\n * as a safety net; apps can also listen for `stimeo--auto-submit:done`\n * and announce richer text themselves. `aria-busy` marks the in-flight window and\n * `data-auto-submit-pending` the debounce window, for consumer CSS; both hooks are\n * rewound just before Turbo caches the page so they never burn into a snapshot.\n * The `turbo:submit-end`/composition subscriptions follow the `form` target as it\n * is added, replaced, or removed at runtime; unbinding a form drops its pending\n * debounced submit, since that submit described a form that is going away. With\n * no resolvable form (no target and a non-`<form>` root) the controller is inert.\n * During IME composition it holds the submit until `compositionend` (the confirmed\n * conversion) so it does not fire on each intermediate keystroke. The debounce\n * timer and the `turbo:submit-end`/composition listeners are torn down on\n * `disconnect()`.\n */\nexport class AutoSubmitController extends Controller<HTMLElement> {\n static override targets = [\"form\"];\n static override values = {\n debounce: { type: Number, default: 300 },\n on: { type: String, default: \"input change\" },\n announce: { type: Boolean, default: false },\n message: { type: String, default: \"\" },\n };\n static actions = [\"submit\"] as const;\n static events = [\"submit\", \"done\", \"reconcile\"] as const;\n\n declare readonly formTarget: HTMLFormElement;\n declare readonly hasFormTarget: boolean;\n\n declare debounceValue: number;\n declare onValue: string;\n declare announceValue: boolean;\n declare messageValue: string;\n\n /** Debounce timer registry; one `clearAll()` in disconnect tears it down. */\n readonly #timers = new SafeTimeout();\n /** Id of the pending debounce timer, so a new keystroke can reset it. */\n #pendingId = 0;\n /** The form the listeners are attached to; target callbacks rebind it. */\n #boundForm: HTMLFormElement | null = null;\n /** Rewinds the transient state hooks just before Turbo snapshots the page. */\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n\n /** Clears `aria-busy` and emits completion once Turbo finishes the submit. */\n readonly #onSubmitEnd = (): void => {\n this.#boundForm?.removeAttribute(\"aria-busy\");\n const message = this.messageValue;\n this.dispatch(\"done\", { detail: { message: message || undefined } });\n // Bridge the silent result swap to the shared Announcer so SR users hear it.\n if (this.announceValue && message) {\n window.dispatchEvent(new CustomEvent(\"stimeo--announcer:announce\", { detail: { message } }));\n }\n };\n\n /** Owns delegated IME lifecycle state and submits confirmed input text. */\n readonly #composition = new CompositionTracker({\n onEnd: (event) => {\n if (this.#triggers(\"input\")) this.#schedule((event.target as HTMLElement | null) ?? null);\n },\n });\n\n override connect(): void {\n this.#beforeCache.activate();\n this.#bindForm(this.#resolveForm());\n }\n\n override disconnect(): void {\n this.#beforeCache.deactivate();\n this.#bindForm(null);\n this.#composition.disconnect();\n this.#timers.clearAll();\n this.#pendingId = 0;\n }\n\n /** Follows a `form` target added (or swapped in) at runtime. */\n formTargetConnected(): void {\n this.#bindForm(this.#resolveForm());\n }\n\n /** Follows a `form` target removed (or swapped out) at runtime. */\n formTargetDisconnected(): void {\n this.#bindForm(this.#resolveForm());\n }\n\n /**\n * Schedules a debounced submit. Wired to `input`/`change`; the `on` value is an\n * allowlist so a configured subset (e.g. only `change`) is honored even when both\n * are bound in markup. Coalesces rapid events into a single `requestSubmit`.\n */\n submit(event: Event): void {\n if (!this.#triggers(event.type)) return;\n // Ignore `input` events fired mid-IME-composition (e.g. typing kana before the\n // Japanese conversion is confirmed); the confirmed text submits on\n // `compositionend` and the browser's final post-composition `input`.\n if (event.type === \"input\" && this.#composition.isComposing(event as InputEvent)) return;\n this.#schedule((event.target as HTMLElement | null) ?? null);\n }\n\n /** Schedules (and coalesces) the debounced submit for the given trigger. */\n #schedule(trigger: HTMLElement | null): void {\n const form = this.#boundForm;\n if (!form) return;\n form.setAttribute(\"data-auto-submit-pending\", \"true\");\n this.#cancelPending();\n\n this.#pendingId = this.#timers.set(() => {\n this.#pendingId = 0;\n form.removeAttribute(\"data-auto-submit-pending\");\n this.dispatch(\"submit\", { detail: { trigger } });\n // `requestSubmit()` runs native constraint validation. If the form is\n // invalid the actual submit never happens — the browser blocks it (or, when\n // a `stimeo--form-validation` set `novalidate`, that controller cancels the\n // submit) — so no `turbo:submit-end` arrives to clear `aria-busy`. Only mark\n // the form busy when the submit will really proceed; still call\n // `requestSubmit()` either way so the validation surfaces to the user.\n if (form.checkValidity()) {\n form.setAttribute(\"aria-busy\", \"true\");\n }\n form.requestSubmit();\n }, this.debounceValue);\n }\n\n /** Cancels the pending debounced submit, if any (`clear` no-ops on unknown ids). */\n #cancelPending(): void {\n this.#timers.clear(this.#pendingId);\n this.#pendingId = 0;\n }\n\n /**\n * Replaces the subscribed form symmetrically. The outgoing form loses the\n * `turbo:submit-end`/composition listeners, its pending hook, and any pending\n * debounced submit (which described the outgoing form). An in-flight `aria-busy`\n * is left for `turbo:submit-end` or the pre-cache rewind — removing it here\n * would wipe a legitimately in-progress submission.\n */\n #bindForm(form: HTMLFormElement | null): void {\n if (form === this.#boundForm) return;\n const previous = this.#boundForm;\n if (previous) {\n this.#cancelPending();\n previous.removeAttribute(\"data-auto-submit-pending\");\n previous.removeEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n this.#composition.unobserve(previous);\n }\n this.#boundForm = form;\n if (!form) return;\n form.addEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n this.#composition.observe(form);\n }\n\n /** Resolves the form: the explicit `form` target, else a `<form>` root, else null. */\n #resolveForm(): HTMLFormElement | null {\n if (this.hasFormTarget) return this.formTarget;\n return this.element instanceof HTMLFormElement ? this.element : null;\n }\n\n /** Returns the transient state hooks to their initial (absent) state. */\n #rewindForCache(): void {\n const inProgress = this.#pendingId !== 0 || this.#boundForm?.hasAttribute(\"aria-busy\") === true;\n this.#cancelPending();\n this.#boundForm?.removeAttribute(\"data-auto-submit-pending\");\n this.#boundForm?.removeAttribute(\"aria-busy\");\n if (inProgress) this.dispatch(\"reconcile\", { detail: {} });\n }\n\n /** Whether `type` is one of the whitespace-separated event types in `on`. */\n #triggers(type: string): boolean {\n return this.onValue.split(/\\s+/).filter(Boolean).includes(type);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/before_cache_reset.ts","../../src/utils/composition_tracker.ts","../../src/utils/safe_timeout.ts","../../src/controllers/auto_submit_controller.ts"],"names":[],"mappings":";;;;;AA2CO,IAAM,gBAAA,GAAN,MA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AAS,gBAAgB,0BAA0B,CAAA;AACnD,MAAA,QAAA,CAAS,mBAAA,CAAoB,kBAAA,EAAoB,IAAA,CAAK,YAAY,CAAA;AAClE,MAAA,IAAA,CAAK,YAAA,CAAa,UAAU,QAAQ,CAAA;AAAA,IACtC;AACA,IAAA,IAAA,CAAK,UAAA,GAAa,IAAA;AAClB,IAAA,IAAI,CAAC,IAAA,EAAM;AACX,IAAA,IAAA,CAAK,gBAAA,CAAiB,kBAAA,EAAoB,IAAA,CAAK,YAAY,CAAA;AAC3D,IAAA,IAAA,CAAK,YAAA,CAAa,QAAQ,IAAI,CAAA;AAAA,EAChC;AAAA;AAAA,EAGA,YAAA,GAAuC;AACrC,IAAA,IAAI,IAAA,CAAK,aAAA,EAAe,OAAO,IAAA,CAAK,UAAA;AACpC,IAAA,OAAO,IAAA,CAAK,OAAA,YAAmB,eAAA,GAAkB,IAAA,CAAK,OAAA,GAAU,IAAA;AAAA,EAClE;AAAA;AAAA,EAGA,eAAA,GAAwB;AACtB,IAAA,MAAM,UAAA,GAAa,KAAK,UAAA,KAAe,CAAA,IAAK,KAAK,UAAA,EAAY,YAAA,CAAa,WAAW,CAAA,KAAM,IAAA;AAC3F,IAAA,IAAA,CAAK,cAAA,EAAe;AACpB,IAAA,IAAA,CAAK,UAAA,EAAY,gBAAgB,0BAA0B,CAAA;AAC3D,IAAA,IAAA,CAAK,UAAA,EAAY,gBAAgB,WAAW,CAAA;AAC5C,IAAA,IAAI,UAAA,OAAiB,QAAA,CAAS,WAAA,EAAa,EAAE,MAAA,EAAQ,IAAI,CAAA;AAAA,EAC3D;AAAA;AAAA,EAGA,UAAU,IAAA,EAAuB;AAC/B,IAAA,OAAO,IAAA,CAAK,QAAQ,KAAA,CAAM,KAAK,EAAE,MAAA,CAAO,OAAO,CAAA,CAAE,QAAA,CAAS,IAAI,CAAA;AAAA,EAChE;AACF","file":"auto_submit_controller.js","sourcesContent":["/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way.\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\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 * 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 { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/**\n * Headless **debounced auto-submit** for forms (no dedicated APG pattern). Submits\n * the form a configurable delay after `input`/`change`, so Rails search/filter\n * forms refresh via Turbo without a submit button.\n *\n * Markup contract (identifier: `stimeo--auto-submit`):\n * <form data-controller=\"stimeo--auto-submit\"\n * data-stimeo--auto-submit-debounce-value=\"300\"\n * data-action=\"input->stimeo--auto-submit#submit\n * change->stimeo--auto-submit#submit\">\n * <input type=\"search\" name=\"q\">\n * </form>\n *\n * <!-- Or with the form as a target nested under the controller element: -->\n * <div data-controller=\"stimeo--auto-submit\">\n * <form data-stimeo--auto-submit-target=\"form\"> … </form>\n * </div>\n *\n * `submit` dispatches `{ trigger }`; `done` dispatches `{ message? }`.\n * `reconcile` dispatches `{}` when the Turbo cache rewind drops a submission\n * that was pending or in flight — `done` would claim a response arrived.\n *\n * @remarks\n * Behavior only — it owns *triggering* the submit (debounce + `requestSubmit`),\n * never the submit itself (Turbo / native form submission) or validation. It\n * **never moves focus** (WCAG 2.2 3.2.2 / 4.1.3): auto-submitting must not yank the\n * caret out of the field. While a result swap is silent for screen-reader users,\n * setting `announce` bridges the completion to the shared `stimeo--announcer`\n * as a safety net; apps can also listen for `stimeo--auto-submit:done`\n * and announce richer text themselves. `aria-busy` marks the in-flight window and\n * `data-auto-submit-pending` the debounce window, for consumer CSS; both hooks are\n * rewound just before Turbo caches the page so they never burn into a snapshot.\n * The `turbo:submit-end`/composition subscriptions follow the `form` target as it\n * is added, replaced, or removed at runtime; unbinding a form drops its pending\n * debounced submit, since that submit described a form that is going away. With\n * no resolvable form (no target and a non-`<form>` root) the controller is inert.\n * During IME composition it holds the submit until `compositionend` (the confirmed\n * conversion) so it does not fire on each intermediate keystroke. The debounce\n * timer and the `turbo:submit-end`/composition listeners are torn down on\n * `disconnect()`.\n */\nexport class AutoSubmitController extends Controller<HTMLElement> {\n static override targets = [\"form\"];\n static override values = {\n debounce: { type: Number, default: 300 },\n on: { type: String, default: \"input change\" },\n announce: { type: Boolean, default: false },\n message: { type: String, default: \"\" },\n };\n static actions = [\"submit\"] as const;\n static events = [\"submit\", \"done\", \"reconcile\"] as const;\n\n declare readonly formTarget: HTMLFormElement;\n declare readonly hasFormTarget: boolean;\n\n declare debounceValue: number;\n declare onValue: string;\n declare announceValue: boolean;\n declare messageValue: string;\n\n /** Debounce timer registry; one `clearAll()` in disconnect tears it down. */\n readonly #timers = new SafeTimeout();\n /** Id of the pending debounce timer, so a new keystroke can reset it. */\n #pendingId = 0;\n /** The form the listeners are attached to; target callbacks rebind it. */\n #boundForm: HTMLFormElement | null = null;\n /** Rewinds the transient state hooks just before Turbo snapshots the page. */\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n\n /** Clears `aria-busy` and emits completion once Turbo finishes the submit. */\n readonly #onSubmitEnd = (): void => {\n this.#boundForm?.removeAttribute(\"aria-busy\");\n const message = this.messageValue;\n this.dispatch(\"done\", { detail: { message: message || undefined } });\n // Bridge the silent result swap to the shared Announcer so SR users hear it.\n if (this.announceValue && message) {\n window.dispatchEvent(new CustomEvent(\"stimeo--announcer:announce\", { detail: { message } }));\n }\n };\n\n /** Owns delegated IME lifecycle state and submits confirmed input text. */\n readonly #composition = new CompositionTracker({\n onEnd: (event) => {\n if (this.#triggers(\"input\")) this.#schedule((event.target as HTMLElement | null) ?? null);\n },\n });\n\n override connect(): void {\n this.#beforeCache.activate();\n this.#bindForm(this.#resolveForm());\n }\n\n override disconnect(): void {\n this.#beforeCache.deactivate();\n this.#bindForm(null);\n this.#composition.disconnect();\n this.#timers.clearAll();\n this.#pendingId = 0;\n }\n\n /** Follows a `form` target added (or swapped in) at runtime. */\n formTargetConnected(): void {\n this.#bindForm(this.#resolveForm());\n }\n\n /** Follows a `form` target removed (or swapped out) at runtime. */\n formTargetDisconnected(): void {\n this.#bindForm(this.#resolveForm());\n }\n\n /**\n * Schedules a debounced submit. Wired to `input`/`change`; the `on` value is an\n * allowlist so a configured subset (e.g. only `change`) is honored even when both\n * are bound in markup. Coalesces rapid events into a single `requestSubmit`.\n */\n submit(event: Event): void {\n if (!this.#triggers(event.type)) return;\n // Ignore `input` events fired mid-IME-composition (e.g. typing kana before the\n // Japanese conversion is confirmed); the confirmed text submits on\n // `compositionend` and the browser's final post-composition `input`.\n if (event.type === \"input\" && this.#composition.isComposing(event as InputEvent)) return;\n this.#schedule((event.target as HTMLElement | null) ?? null);\n }\n\n /** Schedules (and coalesces) the debounced submit for the given trigger. */\n #schedule(trigger: HTMLElement | null): void {\n const form = this.#boundForm;\n if (!form) return;\n form.setAttribute(\"data-auto-submit-pending\", \"true\");\n this.#cancelPending();\n\n this.#pendingId = this.#timers.set(() => {\n this.#pendingId = 0;\n form.removeAttribute(\"data-auto-submit-pending\");\n this.dispatch(\"submit\", { detail: { trigger } });\n // `requestSubmit()` runs native constraint validation. If the form is\n // invalid the actual submit never happens — the browser blocks it (or, when\n // a `stimeo--form-validation` set `novalidate`, that controller cancels the\n // submit) — so no `turbo:submit-end` arrives to clear `aria-busy`. Only mark\n // the form busy when the submit will really proceed; still call\n // `requestSubmit()` either way so the validation surfaces to the user.\n if (form.checkValidity()) {\n form.setAttribute(\"aria-busy\", \"true\");\n }\n form.requestSubmit();\n }, this.debounceValue);\n }\n\n /** Cancels the pending debounced submit, if any (`clear` no-ops on unknown ids). */\n #cancelPending(): void {\n this.#timers.clear(this.#pendingId);\n this.#pendingId = 0;\n }\n\n /**\n * Replaces the subscribed form symmetrically. The outgoing form loses the\n * `turbo:submit-end`/composition listeners, its pending hook, and any pending\n * debounced submit (which described the outgoing form). An in-flight `aria-busy`\n * is left for `turbo:submit-end` or the pre-cache rewind — removing it here\n * would wipe a legitimately in-progress submission.\n */\n #bindForm(form: HTMLFormElement | null): void {\n if (form === this.#boundForm) return;\n const previous = this.#boundForm;\n if (previous) {\n this.#cancelPending();\n previous.removeAttribute(\"data-auto-submit-pending\");\n previous.removeEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n this.#composition.unobserve(previous);\n }\n this.#boundForm = form;\n if (!form) return;\n form.addEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n this.#composition.observe(form);\n }\n\n /** Resolves the form: the explicit `form` target, else a `<form>` root, else null. */\n #resolveForm(): HTMLFormElement | null {\n if (this.hasFormTarget) return this.formTarget;\n return this.element instanceof HTMLFormElement ? this.element : null;\n }\n\n /** Returns the transient state hooks to their initial (absent) state. */\n #rewindForCache(): void {\n const inProgress = this.#pendingId !== 0 || this.#boundForm?.hasAttribute(\"aria-busy\") === true;\n this.#cancelPending();\n this.#boundForm?.removeAttribute(\"data-auto-submit-pending\");\n this.#boundForm?.removeAttribute(\"aria-busy\");\n if (inProgress) this.dispatch(\"reconcile\", { detail: {} });\n }\n\n /** Whether `type` is one of the whitespace-separated event types in `on`. */\n #triggers(type: string): boolean {\n return this.onValue.split(/\\s+/).filter(Boolean).includes(type);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/attribute_lease.ts","../../src/utils/before_cache_reset.ts","../../src/utils/microtask_coalescer.ts","../../src/controllers/avatar_controller.ts"],"names":[],"mappings":";;;;;AAwBO,IAAM,iBAAN,MAAkD;AAAA,EAC9C,UAAA;AAAA,EACA,QAAA,uBAAe,GAAA,EAA6B;AAAA;AAAA,EAG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AGA,YAAY,KAAA,EAAuC;AACjD,IAAA,MAAM,YAAY,KAAA,CAAM,aAAA;AACxB,IAAA,IAAI,EAAE,SAAA,YAAqB,gBAAA,CAAA,EAAmB,OAAO,IAAA;AACrD,IAAA,IAAI,CAAC,IAAA,CAAK,cAAA,IAAkB,SAAA,KAAc,IAAA,CAAK,aAAa,OAAO,IAAA;AACnE,IAAA,OAAO,SAAA;AAAA,EACT;AAAA;AAAA,EAGA,SAAS,KAAA,EAA0B;AACjC,IAAA,MAAM,SAAA,GAAY,KAAA,KAAU,SAAA,IAAa,KAAA,KAAU,QAAA;AACnD,IAAA,IAAI,KAAK,cAAA,EAAgB;AACvB,MAAA,IAAA,CAAK,aAAa,KAAA,CAAM,IAAA,CAAK,WAAA,EAAa,SAAA,GAAY,OAAO,EAAE,CAAA;AAAA,IACjE;AACA,IAAA,IAAI,KAAK,iBAAA,EAAmB;AAC1B,MAAA,IAAA,CAAK,gBAAgB,KAAA,CAAM,IAAA,CAAK,cAAA,EAAgB,SAAA,GAAY,KAAK,IAAI,CAAA;AAAA,IACvE;AACA,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc,KAAK,CAAA;AAAA,EAC/C;AAAA;AAAA,EAEA,eAAA,GAAwB;AACtB,IAAA,IAAA,CAAK,KAAK,SAAA,EAAU;AACpB,IAAA,IAAA,CAAK,aAAa,SAAA,EAAU;AAC5B,IAAA,IAAA,CAAK,gBAAgB,SAAA,EAAU;AAAA,EACjC;AACF","file":"avatar_controller.js","sourcesContent":["/** One temporarily controlled attribute value and the authored value it displaced. */\ninterface AttributeLeaseRecord {\n readonly original: string | null;\n written: string | null;\n}\n\n/**\n * Temporarily controls one attribute across a changing set of elements.\n *\n * The first write remembers the authored value, including the distinction between\n * an absent attribute and an authored empty string. Returning a lease restores that\n * value only while the attribute still matches the controller's last write. If a\n * consumer changed it in the meantime, the consumer owns the new value and teardown\n * leaves it alone.\n *\n * A `null` write deliberately removes the attribute while retaining the lease. This\n * is useful for derived ARIA whose valid absence is itself controller state, such as\n * an unbounded `aria-valuemin` or a blank spinbutton's `aria-valuenow`.\n *\n * The lease has no lifecycle of its own, so it never subscribes to document events.\n * A consumer that must not let a derived value become the authored baseline of a\n * cached page returns its leases from its own `turbo:before-cache` rewind, where the\n * matching `disconnect()` also releases the subscription.\n */\nexport class AttributeLease<T extends Element = Element> {\n readonly #attribute: string;\n readonly #records = new Map<T, AttributeLeaseRecord>();\n\n /** @param attribute - The attribute whose temporary values this lease owns. */\n constructor(attribute: string) {\n this.#attribute = attribute;\n }\n\n /** Writes or removes the leased attribute while preserving its authored value. */\n write(element: T, value: string | null): void {\n const existing = this.#records.get(element);\n if (existing) {\n existing.written = value;\n } else {\n this.#records.set(element, {\n original: element.getAttribute(this.#attribute),\n written: value,\n });\n }\n\n this.#reflect(element, value);\n }\n\n /** Returns one lease without overwriting a value subsequently authored by a consumer. */\n return(element: T): void {\n const record = this.#records.get(element);\n if (!record) return;\n this.#records.delete(element);\n const stillOwned = element.getAttribute(this.#attribute) === record.written;\n if (stillOwned) this.#reflect(element, record.original);\n }\n\n /** Reflects only a real value transition, avoiding self-triggered mutation work. */\n #reflect(element: T, value: string | null): void {\n if (element.getAttribute(this.#attribute) === value) return;\n if (value === null) element.removeAttribute(this.#attribute);\n else element.setAttribute(this.#attribute, value);\n }\n\n /** Returns every outstanding lease using the same ownership check as {@link return}. */\n returnAll(): void {\n for (const element of Array.from(this.#records.keys())) this.return(element);\n }\n}\n","/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way (the `MicrotaskCoalescer` split).\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\n\n/** Public rendering phases exposed through the root's `data-state`. */\ntype AvatarState = \"empty\" | \"loading\" | \"loaded\" | \"error\";\n\n/**\n * Headless **Avatar** behavior with image-load fallback. No dedicated APG\n * pattern; it follows the non-text-content practice (WCAG 1.1.1).\n *\n * Markup contract (identifier: `stimeo--avatar`):\n * <span data-controller=\"stimeo--avatar\" role=\"img\" aria-label=\"Jane Doe\"\n * data-stimeo--avatar-src-value=\"/u/123.jpg\">\n * <img alt=\"\" aria-hidden=\"true\"\n * data-stimeo--avatar-target=\"image\"\n * data-action=\"load->stimeo--avatar#onLoad error->stimeo--avatar#onError\" />\n * <span aria-hidden=\"true\" hidden data-stimeo--avatar-target=\"fallback\">JD</span>\n * </span>\n *\n * The `image` and `fallback` targets are optional. A present `src` Value owns the\n * current image's `src`, including an empty Value that explicitly clears it. When\n * the Value is absent, a directly authored `<img src>` is used instead. Runtime\n * Value changes, direct `src` changes, and target replacements all repaint.\n *\n * The accessible name lives on the container (`role=\"img\"` + `aria-label`); the\n * inner image and fallback are `aria-hidden` so assistive technology reads the\n * name once in every visual state.\n *\n * @remarks\n * Behavior only — shape, size, and colour are the consumer's CSS. Initials or\n * colour generation are out of scope: fallback content comes from markup. The\n * `empty`, `loading`, `loaded`, and `error` phases are exposed on `data-state`.\n * A native error from the current image dispatches `stimeo--avatar:error` with\n * `{ src: string }`; reconnecting or reconciling an already-broken image is\n * silent because no new failure event occurred.\n */\nexport class AvatarController extends Controller<HTMLElement> {\n static override targets = [\"image\", \"fallback\"];\n static override values = { src: String };\n static actions = [\"onError\", \"onLoad\"] as const;\n static events = [\"error\"] as const;\n\n declare readonly imageTarget: HTMLImageElement;\n declare readonly fallbackTarget: HTMLElement;\n declare readonly hasImageTarget: boolean;\n declare readonly hasFallbackTarget: boolean;\n declare srcValue: string;\n\n /** Collapses one morph's Value, target, and direct-attribute signals into one pass. */\n readonly #reconcile = new MicrotaskCoalescer(() => this.#render());\n /** Preserves directly-authored source and visibility while targets are controlled. */\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n readonly #src = new AttributeLease<HTMLImageElement>(\"src\");\n readonly #imageHidden = new AttributeLease<HTMLImageElement>(\"hidden\");\n readonly #fallbackHidden = new AttributeLease<HTMLElement>(\"hidden\");\n /** True only while target departure means ownership was actually relinquished. */\n #connected = false;\n /** Watches the non-Value render input used by the direct `<img src>` form. */\n readonly #srcObserver = new MutationObserver((records) => {\n if (records.some((record) => this.hasImageTarget && record.target === this.imageTarget)) {\n this.#reconcile.schedule();\n }\n });\n\n /** Starts retained-DOM observation and silently derives the current phase. */\n override connect(): void {\n this.#connected = true;\n this.#reconcile.activate();\n this.#beforeCache.activate();\n this.#srcObserver.observe(this.element, {\n attributes: true,\n attributeFilter: [\"src\"],\n subtree: true,\n });\n this.#render();\n }\n\n /** Cancels asynchronous work while retaining the last materialized visual state. */\n override disconnect(): void {\n this.#connected = false;\n this.#reconcile.cancel();\n this.#beforeCache.deactivate();\n this.#srcObserver.disconnect();\n }\n\n /** Repaints when application code or a Turbo morph changes the source Value. */\n srcValueChanged(): void {\n this.#reconcile.schedule();\n }\n\n /** Applies the current source and phase to an image inserted or replaced at runtime. */\n imageTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Returns attributes borrowed from an image that leaves this live avatar. */\n imageTargetDisconnected(image: HTMLImageElement): void {\n if (this.#connected) {\n this.#src.return(image);\n this.#imageHidden.return(image);\n }\n this.#reconcile.schedule();\n }\n\n /** Applies the current phase to a fallback inserted or replaced at runtime. */\n fallbackTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Returns authored visibility when a fallback leaves this live avatar. */\n fallbackTargetDisconnected(fallback: HTMLElement): void {\n if (this.#connected) this.#fallbackHidden.return(fallback);\n this.#reconcile.schedule();\n }\n\n /** Reveals the current image after its native `load` event. */\n onLoad(event: Event): void {\n const image = this.#eventImage(event);\n if (!image) return;\n if (!image.getAttribute(\"src\")) {\n this.#render();\n return;\n }\n this.#reflect(\"loaded\");\n }\n\n /**\n * Reveals the fallback after the current image's native `error` event.\n *\n * Dispatches `stimeo--avatar:error` with `{ src: string }`, where `src` is\n * the attempted attribute value. Empty/stale/detached image events are ignored.\n */\n onError(event: Event): void {\n const image = this.#eventImage(event);\n if (!image) return;\n const src = image.getAttribute(\"src\");\n if (!src) {\n this.#render();\n return;\n }\n this.#reflect(\"error\");\n this.dispatch(\"error\", { detail: { src } });\n }\n\n /**\n * Materializes the phase from the final source/target DOM after one mutation batch.\n *\n * Cached success and failure are state reconstruction, not new load events, so\n * this pass never dispatches the public `error` event.\n *\n * @stimeoRenderRoot\n */\n #render(): void {\n if (!this.hasImageTarget) {\n this.#reflect(\"empty\");\n return;\n }\n\n const image = this.imageTarget;\n const src = this.#applySource(image);\n if (!src) {\n this.#reflect(\"empty\");\n return;\n }\n if (!image.complete) {\n this.#reflect(\"loading\");\n return;\n }\n this.#reflect(image.naturalWidth > 0 ? \"loaded\" : \"error\");\n }\n\n /** Applies Value precedence and returns the effective raw `src` attribute. */\n #applySource(image: HTMLImageElement): string | null {\n if (!this.element.hasAttribute(\"data-stimeo--avatar-src-value\")) {\n this.#src.return(image);\n return image.getAttribute(\"src\");\n }\n\n const desired = this.srcValue.length > 0 ? this.srcValue : null;\n if (image.getAttribute(\"src\") !== desired) this.#src.write(image, desired);\n return desired;\n }\n\n /** Accepts an action only from the singular image target currently controlled. */\n #eventImage(event: Event): HTMLImageElement | null {\n const candidate = event.currentTarget;\n if (!(candidate instanceof HTMLImageElement)) return null;\n if (!this.hasImageTarget || candidate !== this.imageTarget) return null;\n return candidate;\n }\n\n /** Writes the visibility pair and public root state as one controller-owned output. */\n #reflect(state: AvatarState): void {\n const showImage = state === \"loading\" || state === \"loaded\";\n if (this.hasImageTarget) {\n this.#imageHidden.write(this.imageTarget, showImage ? null : \"\");\n }\n if (this.hasFallbackTarget) {\n this.#fallbackHidden.write(this.fallbackTarget, showImage ? \"\" : null);\n }\n this.element.setAttribute(\"data-state\", state);\n }\n /** Returns borrowed image and fallback semantics before Turbo snapshots the page. */\n #rewindForCache(): void {\n this.#src.returnAll();\n this.#imageHidden.returnAll();\n this.#fallbackHidden.returnAll();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/attribute_lease.ts","../../src/utils/before_cache_reset.ts","../../src/utils/microtask_coalescer.ts","../../src/controllers/avatar_controller.ts"],"names":[],"mappings":";;;;;AAwBO,IAAM,iBAAN,MAAkD;AAAA,EAC9C,UAAA;AAAA,EACA,QAAA,uBAAe,GAAA,EAA6B;AAAA;AAAA,EAGrD,YAAY,SAAA,EAAmB;AAC7B,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,KAAA,CAAM,SAAY,KAAA,EAA4B;AAC5C,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAO,CAAA;AAC1C,IA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AAO,IAAA;AACnE,IAAA,OAAO,SAAA;AAAA,EACT;AAAA;AAAA,EAGA,SAAS,KAAA,EAA0B;AACjC,IAAA,MAAM,SAAA,GAAY,KAAA,KAAU,SAAA,IAAa,KAAA,KAAU,QAAA;AACnD,IAAA,IAAI,KAAK,cAAA,EAAgB;AACvB,MAAA,IAAA,CAAK,aAAa,KAAA,CAAM,IAAA,CAAK,WAAA,EAAa,SAAA,GAAY,OAAO,EAAE,CAAA;AAAA,IACjE;AACA,IAAA,IAAI,KAAK,iBAAA,EAAmB;AAC1B,MAAA,IAAA,CAAK,gBAAgB,KAAA,CAAM,IAAA,CAAK,cAAA,EAAgB,SAAA,GAAY,KAAK,IAAI,CAAA;AAAA,IACvE;AACA,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc,KAAK,CAAA;AAAA,EAC/C;AAAA;AAAA,EAEA,eAAA,GAAwB;AACtB,IAAA,IAAA,CAAK,KAAK,SAAA,EAAU;AACpB,IAAA,IAAA,CAAK,aAAa,SAAA,EAAU;AAC5B,IAAA,IAAA,CAAK,gBAAgB,SAAA,EAAU;AAAA,EACjC;AACF","file":"avatar_controller.js","sourcesContent":["/** One temporarily controlled attribute value and the authored value it displaced. */\ninterface AttributeLeaseRecord {\n readonly original: string | null;\n written: string | null;\n}\n\n/**\n * Temporarily controls one attribute across a changing set of elements.\n *\n * The first write remembers the authored value, including the distinction between\n * an absent attribute and an authored empty string. Returning a lease restores that\n * value only while the attribute still matches the controller's last write. If a\n * consumer changed it in the meantime, the consumer owns the new value and teardown\n * leaves it alone.\n *\n * A `null` write deliberately removes the attribute while retaining the lease. This\n * is useful for derived ARIA whose valid absence is itself controller state, such as\n * an unbounded `aria-valuemin` or a blank spinbutton's `aria-valuenow`.\n *\n * The lease has no lifecycle of its own, so it never subscribes to document events.\n * A consumer that must not let a derived value become the authored baseline of a\n * cached page returns its leases from its own `turbo:before-cache` rewind, where the\n * matching `disconnect()` also releases the subscription.\n */\nexport class AttributeLease<T extends Element = Element> {\n readonly #attribute: string;\n readonly #records = new Map<T, AttributeLeaseRecord>();\n\n /** @param attribute - The attribute whose temporary values this lease owns. */\n constructor(attribute: string) {\n this.#attribute = attribute;\n }\n\n /** Writes or removes the leased attribute while preserving its authored value. */\n write(element: T, value: string | null): void {\n const existing = this.#records.get(element);\n if (existing) {\n existing.written = value;\n } else {\n this.#records.set(element, {\n original: element.getAttribute(this.#attribute),\n written: value,\n });\n }\n\n this.#reflect(element, value);\n }\n\n /** Returns one lease without overwriting a value subsequently authored by a consumer. */\n return(element: T): void {\n const record = this.#records.get(element);\n if (!record) return;\n this.#records.delete(element);\n const stillOwned = element.getAttribute(this.#attribute) === record.written;\n if (stillOwned) this.#reflect(element, record.original);\n }\n\n /** Reflects only a real value transition, avoiding self-triggered mutation work. */\n #reflect(element: T, value: string | null): void {\n if (element.getAttribute(this.#attribute) === value) return;\n if (value === null) element.removeAttribute(this.#attribute);\n else element.setAttribute(this.#attribute, value);\n }\n\n /** Returns every outstanding lease using the same ownership check as {@link return}. */\n returnAll(): void {\n for (const element of Array.from(this.#records.keys())) this.return(element);\n }\n}\n","/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way.\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\n\n/** Public rendering phases exposed through the root's `data-state`. */\ntype AvatarState = \"empty\" | \"loading\" | \"loaded\" | \"error\";\n\n/**\n * Headless **Avatar** behavior with image-load fallback. No dedicated APG\n * pattern; it follows the non-text-content practice (WCAG 1.1.1).\n *\n * Markup contract (identifier: `stimeo--avatar`):\n * <span data-controller=\"stimeo--avatar\" role=\"img\" aria-label=\"Jane Doe\"\n * data-stimeo--avatar-src-value=\"/u/123.jpg\">\n * <img alt=\"\" aria-hidden=\"true\"\n * data-stimeo--avatar-target=\"image\"\n * data-action=\"load->stimeo--avatar#onLoad error->stimeo--avatar#onError\" />\n * <span aria-hidden=\"true\" hidden data-stimeo--avatar-target=\"fallback\">JD</span>\n * </span>\n *\n * The `image` and `fallback` targets are optional. A present `src` Value owns the\n * current image's `src`, including an empty Value that explicitly clears it. When\n * the Value is absent, a directly authored `<img src>` is used instead. Runtime\n * Value changes, direct `src` changes, and target replacements all repaint.\n *\n * The accessible name lives on the container (`role=\"img\"` + `aria-label`); the\n * inner image and fallback are `aria-hidden` so assistive technology reads the\n * name once in every visual state.\n *\n * @remarks\n * Behavior only — shape, size, and colour are the consumer's CSS. Initials or\n * colour generation are out of scope: fallback content comes from markup. The\n * `empty`, `loading`, `loaded`, and `error` phases are exposed on `data-state`.\n * A native error from the current image dispatches `stimeo--avatar:error` with\n * `{ src: string }`; reconnecting or reconciling an already-broken image is\n * silent because no new failure event occurred.\n */\nexport class AvatarController extends Controller<HTMLElement> {\n static override targets = [\"image\", \"fallback\"];\n static override values = { src: String };\n static actions = [\"onError\", \"onLoad\"] as const;\n static events = [\"error\"] as const;\n\n declare readonly imageTarget: HTMLImageElement;\n declare readonly fallbackTarget: HTMLElement;\n declare readonly hasImageTarget: boolean;\n declare readonly hasFallbackTarget: boolean;\n declare srcValue: string;\n\n /** Collapses one morph's Value, target, and direct-attribute signals into one pass. */\n readonly #reconcile = new MicrotaskCoalescer(() => this.#render());\n /** Preserves directly-authored source and visibility while targets are controlled. */\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n readonly #src = new AttributeLease<HTMLImageElement>(\"src\");\n readonly #imageHidden = new AttributeLease<HTMLImageElement>(\"hidden\");\n readonly #fallbackHidden = new AttributeLease<HTMLElement>(\"hidden\");\n /** True only while target departure means ownership was actually relinquished. */\n #connected = false;\n /** Watches the non-Value render input used by the direct `<img src>` form. */\n readonly #srcObserver = new MutationObserver((records) => {\n if (records.some((record) => this.hasImageTarget && record.target === this.imageTarget)) {\n this.#reconcile.schedule();\n }\n });\n\n /** Starts retained-DOM observation and silently derives the current phase. */\n override connect(): void {\n this.#connected = true;\n this.#reconcile.activate();\n this.#beforeCache.activate();\n this.#srcObserver.observe(this.element, {\n attributes: true,\n attributeFilter: [\"src\"],\n subtree: true,\n });\n this.#render();\n }\n\n /** Cancels asynchronous work while retaining the last materialized visual state. */\n override disconnect(): void {\n this.#connected = false;\n this.#reconcile.cancel();\n this.#beforeCache.deactivate();\n this.#srcObserver.disconnect();\n }\n\n /** Repaints when application code or a Turbo morph changes the source Value. */\n srcValueChanged(): void {\n this.#reconcile.schedule();\n }\n\n /** Applies the current source and phase to an image inserted or replaced at runtime. */\n imageTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Returns attributes borrowed from an image that leaves this live avatar. */\n imageTargetDisconnected(image: HTMLImageElement): void {\n if (this.#connected) {\n this.#src.return(image);\n this.#imageHidden.return(image);\n }\n this.#reconcile.schedule();\n }\n\n /** Applies the current phase to a fallback inserted or replaced at runtime. */\n fallbackTargetConnected(): void {\n this.#reconcile.schedule();\n }\n\n /** Returns authored visibility when a fallback leaves this live avatar. */\n fallbackTargetDisconnected(fallback: HTMLElement): void {\n if (this.#connected) this.#fallbackHidden.return(fallback);\n this.#reconcile.schedule();\n }\n\n /** Reveals the current image after its native `load` event. */\n onLoad(event: Event): void {\n const image = this.#eventImage(event);\n if (!image) return;\n if (!image.getAttribute(\"src\")) {\n this.#render();\n return;\n }\n this.#reflect(\"loaded\");\n }\n\n /**\n * Reveals the fallback after the current image's native `error` event.\n *\n * Dispatches `stimeo--avatar:error` with `{ src: string }`, where `src` is\n * the attempted attribute value. Empty/stale/detached image events are ignored.\n */\n onError(event: Event): void {\n const image = this.#eventImage(event);\n if (!image) return;\n const src = image.getAttribute(\"src\");\n if (!src) {\n this.#render();\n return;\n }\n this.#reflect(\"error\");\n this.dispatch(\"error\", { detail: { src } });\n }\n\n /**\n * Materializes the phase from the final source/target DOM after one mutation batch.\n *\n * Cached success and failure are state reconstruction, not new load events, so\n * this pass never dispatches the public `error` event.\n *\n * @stimeoRenderRoot\n */\n #render(): void {\n if (!this.hasImageTarget) {\n this.#reflect(\"empty\");\n return;\n }\n\n const image = this.imageTarget;\n const src = this.#applySource(image);\n if (!src) {\n this.#reflect(\"empty\");\n return;\n }\n if (!image.complete) {\n this.#reflect(\"loading\");\n return;\n }\n this.#reflect(image.naturalWidth > 0 ? \"loaded\" : \"error\");\n }\n\n /** Applies Value precedence and returns the effective raw `src` attribute. */\n #applySource(image: HTMLImageElement): string | null {\n if (!this.element.hasAttribute(\"data-stimeo--avatar-src-value\")) {\n this.#src.return(image);\n return image.getAttribute(\"src\");\n }\n\n const desired = this.srcValue.length > 0 ? this.srcValue : null;\n if (image.getAttribute(\"src\") !== desired) this.#src.write(image, desired);\n return desired;\n }\n\n /** Accepts an action only from the singular image target currently controlled. */\n #eventImage(event: Event): HTMLImageElement | null {\n const candidate = event.currentTarget;\n if (!(candidate instanceof HTMLImageElement)) return null;\n if (!this.hasImageTarget || candidate !== this.imageTarget) return null;\n return candidate;\n }\n\n /** Writes the visibility pair and public root state as one controller-owned output. */\n #reflect(state: AvatarState): void {\n const showImage = state === \"loading\" || state === \"loaded\";\n if (this.hasImageTarget) {\n this.#imageHidden.write(this.imageTarget, showImage ? null : \"\");\n }\n if (this.hasFallbackTarget) {\n this.#fallbackHidden.write(this.fallbackTarget, showImage ? \"\" : null);\n }\n this.element.setAttribute(\"data-state\", state);\n }\n /** Returns borrowed image and fallback semantics before Turbo snapshots the page. */\n #rewindForCache(): void {\n this.#src.returnAll();\n this.#imageHidden.returnAll();\n this.#fallbackHidden.returnAll();\n }\n}\n"]}
|