stimeo-ui 0.3.0 → 0.4.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 +56 -0
- package/dist/controllers/alert_dialog_controller.js +32 -5
- package/dist/controllers/alert_dialog_controller.js.map +1 -1
- package/dist/controllers/announcer_controller.d.ts +32 -6
- package/dist/controllers/announcer_controller.js +255 -20
- package/dist/controllers/announcer_controller.js.map +1 -1
- package/dist/controllers/color_picker_controller.d.ts +2 -1
- package/dist/controllers/color_picker_controller.js +46 -0
- package/dist/controllers/color_picker_controller.js.map +1 -1
- package/dist/controllers/command_palette_controller.js +32 -5
- package/dist/controllers/command_palette_controller.js.map +1 -1
- package/dist/controllers/confirm_controller.js +32 -5
- package/dist/controllers/confirm_controller.js.map +1 -1
- package/dist/controllers/countdown_controller.d.ts +19 -5
- package/dist/controllers/countdown_controller.js +112 -12
- package/dist/controllers/countdown_controller.js.map +1 -1
- package/dist/controllers/date_range_picker_controller.d.ts +4 -1
- package/dist/controllers/date_range_picker_controller.js +50 -0
- package/dist/controllers/date_range_picker_controller.js.map +1 -1
- package/dist/controllers/dialog_controller.js +32 -5
- package/dist/controllers/dialog_controller.js.map +1 -1
- package/dist/controllers/dismissible_controller.js.map +1 -1
- package/dist/controllers/drawer_controller.js +32 -5
- package/dist/controllers/drawer_controller.js.map +1 -1
- package/dist/controllers/empty_state_controller.d.ts +9 -4
- package/dist/controllers/empty_state_controller.js +24 -10
- package/dist/controllers/empty_state_controller.js.map +1 -1
- package/dist/controllers/focus_controller.js +32 -5
- package/dist/controllers/focus_controller.js.map +1 -1
- package/dist/controllers/form_validation_controller.js.map +1 -1
- package/dist/controllers/frame_loading_controller.d.ts +14 -3
- package/dist/controllers/frame_loading_controller.js +177 -15
- package/dist/controllers/frame_loading_controller.js.map +1 -1
- package/dist/controllers/local_time_controller.d.ts +19 -3
- package/dist/controllers/local_time_controller.js +100 -6
- package/dist/controllers/local_time_controller.js.map +1 -1
- package/dist/controllers/meter_controller.d.ts +22 -2
- package/dist/controllers/meter_controller.js +145 -26
- package/dist/controllers/meter_controller.js.map +1 -1
- package/dist/controllers/network_status_controller.d.ts +13 -1
- package/dist/controllers/network_status_controller.js +28 -8
- package/dist/controllers/network_status_controller.js.map +1 -1
- package/dist/controllers/overflow_menu_controller.js +33 -6
- package/dist/controllers/overflow_menu_controller.js.map +1 -1
- package/dist/controllers/progress_controller.d.ts +16 -1
- package/dist/controllers/progress_controller.js +116 -9
- package/dist/controllers/progress_controller.js.map +1 -1
- package/dist/controllers/range_slider_controller.d.ts +4 -1
- package/dist/controllers/range_slider_controller.js +68 -3
- package/dist/controllers/range_slider_controller.js.map +1 -1
- package/dist/controllers/rating_controller.d.ts +4 -1
- package/dist/controllers/rating_controller.js +53 -0
- package/dist/controllers/rating_controller.js.map +1 -1
- package/dist/controllers/relative_time_controller.d.ts +13 -0
- package/dist/controllers/relative_time_controller.js +133 -12
- package/dist/controllers/relative_time_controller.js.map +1 -1
- package/dist/controllers/sidebar_controller.d.ts +1 -11
- package/dist/controllers/sidebar_controller.js +37 -8
- package/dist/controllers/sidebar_controller.js.map +1 -1
- package/dist/controllers/skeleton_controller.d.ts +7 -2
- package/dist/controllers/skeleton_controller.js +73 -20
- package/dist/controllers/skeleton_controller.js.map +1 -1
- package/dist/controllers/slider_controller.js +17 -2
- package/dist/controllers/slider_controller.js.map +1 -1
- package/dist/controllers/spinner_controller.d.ts +37 -4
- package/dist/controllers/spinner_controller.js +228 -27
- package/dist/controllers/spinner_controller.js.map +1 -1
- package/dist/controllers/step_indicator_controller.d.ts +12 -1
- package/dist/controllers/step_indicator_controller.js +82 -5
- package/dist/controllers/step_indicator_controller.js.map +1 -1
- package/dist/controllers/stick_to_bottom_controller.d.ts +26 -2
- package/dist/controllers/stick_to_bottom_controller.js +60 -10
- package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
- package/dist/index.js +1056 -281
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.js +785 -76
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js +785 -76
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +5 -5
- package/dist/inspector/manifest.json +21 -8
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/escape_layer.ts","../../src/utils/focus_trap.ts","../../src/controllers/confirm_controller.ts"],"names":[],"mappings":";;;;;AAuEO,IAAM,WAAA,GAAN,MAAM,YAAA,CAAY;AAAA,EACvB,OAAgB,WAAA,mBAAc,IAAI,OAAA,EAAuC;AAAA,EAEzE,cAAA,GAAkC,IAAA;AAAA;AAAA,EAElC,UAAA,GAAkC,IAAA;AAAA;AAAA,EAElC,OAAA,GAAkC,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlC,QAAA,CAAS,aAAA,GAA0B,QAAA,EAAU,OAAA,EAAmC;AAC9E,IAAA,IAAA,CAAK,UAAA,EAAW;AAChB,IAAA,IAAI,QAAA,GAAW,YAAA,CAAY,WAAA,CAAY,GAAA,CAAI,aAAa,CAAA;AACxD,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,QAAA,GAAW,aAAY,eAAA,EAAgB;AACvC,MAAA,YAAA,CAAY,WAAA,CAAY,GAAA,CAAI,aAAA,EAAe,QAAQ,CAAA;AACnD,MAAA,aAAA,CAAc,gBAAA,CAAiB,SAAA,EAAW,QAAA,CAAS,SAAS,CAAA;AAAA,IAC9D;AACA,IAAA,QAAA,CAAS,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB,IAAA,IAAA,CAAK,cAAA,GAAiB,aAAA;AACtB,IAAA,IAAA,CAAK,aAAa,OAAA,CAAQ,SAAA;AAC1B,IAAA,IAAA,CAAK,OAAA,GAAU,QAAQ,MAAA,IAAU,IAAA;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,UAAA,GAAmB;AACjB,IAAA,MAAM,gBAAgB,IA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,EACF;AAAA;AAAA,EAGA,iBAAA,GAA0B;AACxB,IAAA,MAAM,QAAS,MAAA,CAA0C,KAAA;AACzD,IAAA,MAAM,KAAA,GAAQ,OAAO,MAAA,EAAQ,KAAA;AAC7B,IAAA,IAAI,CAAC,KAAA,EAAO;AACZ,IAAA,IAAA,CAAK,WAAA,GAAc,KAAA;AACnB,IAAA,IAAA,CAAK,mBAAmB,KAAA,CAAM,OAAA;AAC9B,IAAA,KAAA,CAAM,OAAA,GAAU,CAAC,OAAA,KAAoB,IAAA,CAAK,QAAQ,OAAO,CAAA;AAAA,EAC3D;AAAA;AAAA,EAGA,oBAAA,GAA2C;AACzC,IAAA,IAAI,KAAK,iBAAA,KAAsB,SAAA,IAAa,IAAA,CAAK,gBAAA,SAAyB,IAAA,CAAK,aAAA;AAC/E,IAAA,OAAO,IAAA,CAAK,eAAA,GAAkB,IAAA,CAAK,YAAA,GAAe,IAAA;AAAA,EACpD;AACF","file":"confirm_controller.js","sourcesContent":["/**\n * Single resolver for layered Escape dismissal.\n *\n * Every Escape-dismissable overlay layer (modal focus traps, disclosure\n * overlays like dropdown/popover/menu, and hover-triggered transient layers)\n * registers here while it is open. One document-level listener per document\n * resolves each press to exactly one owner and invokes that layer's\n * {@link EscapeLayerOptions.onDismiss} — controllers never listen for a\n * dismissing Escape themselves.\n *\n * @remarks\n * Each document owns an activation-ordered stack. The owner of a press is the\n * **topmost layer whose {@link EscapeLayerOptions.claims} passes**; a layer\n * that declines is transparent, so a background overlay opened behind a modal\n * never blocks it. Because a layer opened from within another is necessarily\n * activated later, LIFO order is also inner-first for nested layers — no DOM\n * inspection is needed.\n *\n * The shared listener runs in the document bubble phase and honors\n * `event.defaultPrevented`, so an element-level widget handler that consumes\n * Escape first (an editor cancelling its edit, a combobox closing its list)\n * always wins over every registered layer — the deepest handler resolves the\n * press. A keydown that is part of an IME composition (`event.isComposing`)\n * cancels the composition, never a layer, and is ignored here for every layer\n * at once.\n *\n * A WeakMap keeps documents collectible; the listener is installed only while\n * a document's stack is non-empty, and controller lifecycle hooks guarantee\n * that disconnected layers never remain registered.\n */\n\n/** Behavior a layer registers when it activates. */\nexport interface EscapeLayerOptions {\n /**\n * Dismisses the layer. Called by the shared resolver when this layer owns a\n * press; the resolver has already consumed the event (`preventDefault()`),\n * so the callback only needs to close and place focus per the widget's\n * contract.\n */\n onDismiss: () => void;\n /**\n * Whether the layer claims the current press. Evaluated per press, so it can\n * depend on live state (e.g. \"focus is inside me or fell to the body\"). A\n * declining layer is skipped and the next layer down is consulted; omitting\n * it means the layer always claims while active.\n */\n claims?: () => boolean;\n}\n\n/** A document's stack plus the one shared listener bound to it. */\ninterface EscapeLayerRegistry {\n stack: EscapeLayer[];\n onKeydown: (event: KeyboardEvent) => void;\n}\n\n/**\n * Claims predicate shared by the click-opened disclosure overlays (dropdown /\n * popover / navigation-menu / menu / context-menu / menubar): the layer claims\n * a press while focus is inside `element`, or after focus fell to the body —\n * a click on non-focusable overlay content blurs to `<body>`, and Escape must\n * still close the overlay (the \"body-focus rescue\"). A press made after focus\n * moved to another interactive element is declined, so closing never yanks\n * focus away from where the user deliberately went.\n */\nexport function claimsWhileFocusWithin(element: Element): () => boolean {\n return () => {\n const active = element.ownerDocument.activeElement;\n return active === null || active === element.ownerDocument.body || element.contains(active);\n };\n}\n\nexport class EscapeLayer {\n static readonly #registries = new WeakMap<Document, EscapeLayerRegistry>();\n\n #ownerDocument: Document | null = null;\n /** Dismissal callback while active; `null` when inactive. */\n #onDismiss: (() => void) | null = null;\n /** Live predicate deciding whether the layer claims a press; `null` = always. */\n #claims: (() => boolean) | null = null;\n\n /**\n * Activates this layer at the top of its document's Escape stack, installing\n * the document's shared resolver listener if this is its first layer.\n * Re-activating an already-active layer moves it to the top.\n */\n activate(ownerDocument: Document = document, options: EscapeLayerOptions): void {\n this.deactivate();\n let registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) {\n registry = EscapeLayer.#createRegistry();\n EscapeLayer.#registries.set(ownerDocument, registry);\n ownerDocument.addEventListener(\"keydown\", registry.onKeydown);\n }\n registry.stack.push(this);\n this.#ownerDocument = ownerDocument;\n this.#onDismiss = options.onDismiss;\n this.#claims = options.claims ?? null;\n }\n\n /**\n * Removes this layer from its document's Escape stack, uninstalling the\n * shared listener when the stack empties. Safe to call when inactive.\n */\n deactivate(): void {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return;\n\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (registry) {\n const index = registry.stack.lastIndexOf(this);\n if (index >= 0) registry.stack.splice(index, 1);\n if (registry.stack.length === 0) {\n ownerDocument.removeEventListener(\"keydown\", registry.onKeydown);\n EscapeLayer.#registries.delete(ownerDocument);\n }\n }\n this.#ownerDocument = null;\n this.#onDismiss = null;\n this.#claims = null;\n }\n\n /**\n * Whether this active layer would own a press right now: it is the topmost\n * layer whose {@link EscapeLayerOptions.claims} passes. Exposed for tests\n * and diagnostics — production dismissal goes through the shared listener.\n */\n get ownsEscape(): boolean {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return false;\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) return false;\n return EscapeLayer.#resolveOwner(registry.stack) === this;\n }\n\n /** Builds a document's registry with its shared resolver listener. */\n static #createRegistry(): EscapeLayerRegistry {\n const registry: EscapeLayerRegistry = {\n stack: [],\n onKeydown: (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.defaultPrevented || event.isComposing) return;\n const owner = EscapeLayer.#resolveOwner(registry.stack);\n if (!owner) return;\n event.preventDefault();\n owner.#onDismiss?.();\n },\n };\n return registry;\n }\n\n /** The topmost stack layer whose claims predicate passes, or `null`. */\n static #resolveOwner(stack: EscapeLayer[]): EscapeLayer | null {\n for (let index = stack.length - 1; index >= 0; index--) {\n const layer = stack[index];\n if (!layer) continue;\n if (layer.#claims && !layer.#claims()) continue;\n return layer;\n }\n return null;\n }\n}\n","import { EscapeLayer } from \"./escape_layer\";\n\n/**\n * Modal focus-trap primitive shared by the modal-overlay controllers\n * (dialog / alert-dialog / confirm / drawer / command-palette / sidebar); the\n * non-modal focus scope (focus) reuses it with the modal side effects opted out.\n *\n * The WAI-ARIA APG modal pattern is more than \"cycle Tab inside a box\": a modal\n * also locks background scroll, makes the rest of the page `inert` (so assistive\n * technology and pointer/Tab cannot reach it, honoring `aria-modal=\"true\"`),\n * sends focus inside on open, and restores it to the opener on close — and every\n * one of those side effects must be reverted if the element is torn down while\n * open (a Turbo navigation mid-dialog) and kept out of the snapshot Turbo\n * caches (`turbo:before-cache`). {@link FocusTrap} owns that whole modal\n * lifecycle so each controller only decides *when* to open/close and *what*\n * \"close\" means.\n *\n * It is intentionally **policy-free about closing**. Escape semantics differ per\n * widget (a plain dialog just closes; an alert-dialog closes *as a cancel* with a\n * reason; a drawer runs an exit transition), so the trap merely forwards Escape\n * to an {@link FocusTrapOptions.onEscape | onEscape} callback and never decides on\n * its own what closing entails.\n *\n * @remarks\n * The container is read through a getter so a controller can hand over a Stimulus\n * target without worrying about when the trap instance is constructed relative to\n * `connect()`.\n */\n\n/**\n * Selector matching the elements considered focusable. Shared by the trap's Tab\n * cycling and by form-validation's invalid-focus delegation.\n */\nexport const FOCUSABLE =\n 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex=\"-1\"])';\n\n/** Behavior hooks a controller supplies when constructing a {@link FocusTrap}. */\nexport interface FocusTrapOptions {\n /**\n * Called when `Escape` is pressed while the trap is active. When omitted,\n * `Escape` is left alone (the trap never joins the Escape stack). Dismissal\n * is resolved by the shared {@link EscapeLayer}: an Escape already consumed\n * by an inner handler is ignored, and among active layers the most recently\n * activated claiming one owns the press. The resolver consumes the event\n * before invoking the callback.\n */\n onEscape?: () => void;\n /**\n * Returns the element to focus when the trap activates. When it returns `null`\n * (or is omitted), the first focusable descendant is used, falling back to the\n * container itself (made programmatically focusable with `tabindex=-1`).\n */\n initialFocus?: () => HTMLElement | null;\n /**\n * Returns the element to focus on deactivation when nothing was focused before\n * the trap opened (e.g. the trigger). The element focused *before* opening\n * always takes precedence.\n */\n fallbackFocus?: () => HTMLElement | null;\n /**\n * Lock background scroll (`body` overflow) while active. Defaults to `true` for\n * the modal overlays; a lighter focus scope passes `false`. Read on `activate`.\n */\n lockScroll?: boolean | (() => boolean);\n /**\n * Make background siblings `inert` while active (the `aria-modal` isolation).\n * Defaults to `true` for the modal overlays; a soft focus scope can opt out so\n * the background stays reachable while `Tab` still cycles inside. Read on `activate`.\n */\n isolate?: boolean | (() => boolean);\n /**\n * Move focus inside on `activate`. Defaults to `true`; a focus scope that only\n * wants the `Tab` boundary (no focus move) passes `false`. Read on `activate`.\n */\n autoFocus?: boolean | (() => boolean);\n}\n\n/**\n * Owns the modal side effects (scroll lock, background `inert`, focus trap, focus\n * restore) for a single container, applied on {@link activate} and reverted on\n * {@link deactivate}.\n */\nexport class FocusTrap {\n /** The element focused before activation, restored on deactivation. */\n #previouslyFocused: HTMLElement | null = null;\n /** The body's inline `overflow` before locking, restored on deactivation. */\n #previousBodyOverflow = \"\";\n /** Whether scroll was locked this activation (so it is only restored if applied). */\n #scrollLocked = false;\n /** Background siblings made `inert` while active, restored on deactivation. */\n #inertedSiblings: HTMLElement[] = [];\n /** Whether the modal side effects are currently applied. */\n #activeState = false;\n /** Registers the trap on the shared Escape stack while active (see {@link EscapeLayer}). */\n readonly #escapeLayer = new EscapeLayer();\n\n /** Returns the trapped element; called on every operation for the live target. */\n readonly #getContainer: () => HTMLElement;\n /** Closing/focus hooks; see {@link FocusTrapOptions}. */\n readonly #options: FocusTrapOptions;\n\n /**\n * @param getContainer - Returns the trapped element. Called on every operation\n * so the live target is always used.\n * @param options - Closing/focus hooks; see {@link FocusTrapOptions}.\n */\n constructor(getContainer: () => HTMLElement, options: FocusTrapOptions = {}) {\n this.#getContainer = getContainer;\n this.#options = options;\n }\n\n /** Whether the trap is currently active. */\n get active(): boolean {\n return this.#activeState;\n }\n\n /**\n * Applies the trap: records the current focus, optionally locks background scroll\n * and makes background siblings `inert`, listens for `Tab`/`Escape`, and (unless\n * `autoFocus` is off) moves focus inside. No-ops if already active.\n */\n activate(): void {\n if (this.#activeState) return;\n this.#activeState = true;\n // Record the opener so it can be refocused on close. `<body>` (the default\n // active element when nothing is focused) is treated as \"nothing\", so the\n // fallback target — typically the trigger — wins in that case.\n const active = document.activeElement;\n this.#previouslyFocused =\n active instanceof HTMLElement && active !== document.body ? active : null;\n if (this.#flag(this.#options.lockScroll, true)) {\n this.#previousBodyOverflow = document.body.style.overflow;\n document.body.style.overflow = \"hidden\";\n this.#scrollLocked = true;\n }\n if (this.#flag(this.#options.isolate, true)) this.#isolateBackground();\n document.addEventListener(\"keydown\", this.#onKeydown);\n document.addEventListener(\"turbo:before-cache\", this.#onBeforeCache);\n const onEscape = this.#options.onEscape;\n if (onEscape) this.#escapeLayer.activate(document, { onDismiss: () => onEscape() });\n if (this.#flag(this.#options.autoFocus, true)) this.#focusInitial();\n }\n\n /**\n * Reverts every side effect applied by {@link activate}. No-ops if inactive, so\n * a controller can call it defensively from both `close()` and `disconnect()`.\n *\n * @param restoreFocus - Move focus back to the opener (default `true`). Pass\n * `false` on teardown (`disconnect`), where yanking focus is undesirable.\n */\n deactivate({ restoreFocus = true }: { restoreFocus?: boolean } = {}): void {\n if (!this.#activeState) return;\n this.#activeState = false;\n this.#escapeLayer.deactivate();\n document.removeEventListener(\"keydown\", this.#onKeydown);\n document.removeEventListener(\"turbo:before-cache\", this.#onBeforeCache);\n if (this.#scrollLocked) {\n document.body.style.overflow = this.#previousBodyOverflow;\n this.#scrollLocked = false;\n }\n this.#releaseBackground();\n if (restoreFocus) {\n const target = this.#previouslyFocused ?? this.#options.fallbackFocus?.() ?? null;\n target?.focus();\n }\n }\n\n /** Resolves a boolean-or-getter option, defaulting when it was not provided. */\n #flag(option: boolean | (() => boolean) | undefined, fallback: boolean): boolean {\n if (option === undefined) return fallback;\n return typeof option === \"function\" ? option() : option;\n }\n\n /**\n * Reverts the side effects just before Turbo caches the page snapshot, so an\n * overlay left open does not bake the scroll lock into `body[style]` — a\n * restored page would feed that locked value back into {@link activate} as the\n * baseline, and closing would then never unlock the page. Markup state stays\n * untouched (restore-open designs reopen against a clean baseline), and focus\n * is left alone mid-navigation. The listener lives only while active.\n */\n readonly #onBeforeCache = (): void => {\n this.deactivate({ restoreFocus: false });\n };\n\n /**\n * Handles `Tab` (focus trap) while active. `Escape` dismissal is owned by the\n * shared {@link EscapeLayer} resolver, so Tab trapping stays independent of\n * which layer currently owns Escape.\n */\n readonly #onKeydown = (event: KeyboardEvent): void => {\n if (event.key === \"Tab\") this.#trapTab(event);\n };\n\n /** Keeps `Tab` focus cycling within the container's focusable elements. */\n #trapTab(event: KeyboardEvent): void {\n const focusable = this.#focusableElements();\n if (focusable.length === 0) {\n event.preventDefault();\n return;\n }\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n const active = document.activeElement;\n\n // If focus has somehow escaped the container, pull it back to the first item.\n if (!(active instanceof Node) || !this.#getContainer().contains(active)) {\n event.preventDefault();\n first?.focus();\n return;\n }\n\n if (event.shiftKey && active === first) {\n event.preventDefault();\n last?.focus();\n } else if (!event.shiftKey && active === last) {\n event.preventDefault();\n first?.focus();\n }\n }\n\n /**\n * Marks every element outside the container's subtree as `inert` so background\n * content cannot be focused or reached by assistive technology, honoring the\n * `aria-modal=\"true\"` contract. An element that was *already* `inert` is left\n * untracked so `#releaseBackground` does not wrongly clear it.\n */\n #isolateBackground(): void {\n const container = this.#getContainer();\n this.#inertedSiblings = [];\n for (const sibling of Array.from(document.body.children)) {\n if (!(sibling instanceof HTMLElement)) continue;\n if (sibling.contains(container) || sibling.inert) continue;\n sibling.inert = true;\n this.#inertedSiblings.push(sibling);\n }\n }\n\n /** Reverts the `inert` flags applied by `#isolateBackground`. */\n #releaseBackground(): void {\n for (const sibling of this.#inertedSiblings) {\n sibling.inert = false;\n }\n this.#inertedSiblings = [];\n }\n\n /** Moves focus to the initial target, the first focusable, or the container. */\n #focusInitial(): void {\n const preferred = this.#options.initialFocus?.();\n if (preferred) {\n preferred.focus();\n return;\n }\n const focusable = this.#focusableElements();\n if (focusable[0]) {\n focusable[0].focus();\n return;\n }\n const container = this.#getContainer();\n container.tabIndex = -1;\n container.focus();\n }\n\n /** Collects the container's currently focusable descendants in DOM order. */\n #focusableElements(): HTMLElement[] {\n return Array.from(this.#getContainer().querySelectorAll<HTMLElement>(FOCUSABLE)).filter(\n (el) => !el.hidden,\n );\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { FocusTrap } from \"../utils/focus_trap\";\n\n/** The slice of Turbo's form config this controller swaps the confirm method on. */\ninterface TurboFormsConfig {\n confirm?: (message: string, element?: HTMLElement) => boolean | Promise<boolean>;\n}\ninterface TurboLike {\n config?: { forms?: TurboFormsConfig };\n}\n\n/**\n * Headless **confirm bridge** — replaces the native `window.confirm()` Turbo uses\n * for `data-turbo-confirm` with an accessible **Alert Dialog** (WAI-ARIA APG Alert\n * Dialog pattern). Reuses the shared {@link FocusTrap}; the consumer only writes the\n * dialog markup and \"what to do on confirm\".\n *\n * Markup contract (identifier: `stimeo--confirm`):\n * <div data-controller=\"stimeo--confirm\">\n * <div data-stimeo--confirm-target=\"dialog\" role=\"alertdialog\" aria-modal=\"true\"\n * aria-labelledby=\"ct\" aria-describedby=\"cm\" hidden>\n * <h2 id=\"ct\" data-stimeo--confirm-target=\"title\">Are you sure?</h2>\n * <p id=\"cm\" data-stimeo--confirm-target=\"message\"></p>\n * <button data-stimeo--confirm-target=\"cancel\"\n * data-action=\"click->stimeo--confirm#cancel\"></button>\n * <button data-stimeo--confirm-target=\"confirm\"\n * data-action=\"click->stimeo--confirm#confirm\"></button>\n * </div>\n * </div>\n *\n * <!-- Driven automatically through Turbo's confirm hook: -->\n * <form data-turbo-confirm=\"Delete this item?\" action=\"/items/1\" method=\"post\">…</form>\n * <!-- Or intercept any link/button directly: -->\n * <a href=\"/items/1\" data-action=\"click->stimeo--confirm#request\"\n * data-stimeo--confirm-message-param=\"Delete this item?\">Delete</a>\n *\n * @remarks\n * Behavior only — the dialog's a11y (focus trap, restore, roles) is delegated to\n * the shared {@link FocusTrap}; this controller adds the Turbo bridge and the\n * confirm/cancel resolution. On `connect()` it swaps `Turbo.config.forms.confirm`\n * for a Promise-returning method and restores the original on `disconnect()` (Turbo\n * navigation included), so registration never leaks or stacks. Escape cancels\n * (returns `false`); when no dialog target exists it degrades to native\n * `window.confirm`. The least-destructive button (cancel, by default) takes initial\n * focus.\n */\nexport class ConfirmController extends Controller<HTMLElement> {\n static override targets = [\"dialog\", \"title\", \"message\", \"confirm\", \"cancel\"];\n static override values = {\n confirmLabel: { type: String, default: \"OK\" },\n cancelLabel: { type: String, default: \"Cancel\" },\n initialFocus: { type: String, default: \"cancel\" },\n };\n static actions = [\"confirm\", \"cancel\", \"request\"] as const;\n static events = [\"open\", \"resolve\"] as const;\n\n declare readonly dialogTarget: HTMLElement;\n /**\n * Static heading slot naming the dialog (via `aria-labelledby`). Never written\n * by the controller — the accessible name is author-owned; only `message` and\n * the button labels are injected per prompt.\n */\n declare readonly titleTarget: HTMLElement;\n declare readonly messageTarget: HTMLElement;\n declare readonly confirmTarget: HTMLElement;\n declare readonly cancelTarget: HTMLElement;\n declare readonly hasDialogTarget: boolean;\n declare readonly hasMessageTarget: boolean;\n declare readonly hasConfirmTarget: boolean;\n declare readonly hasCancelTarget: boolean;\n\n declare confirmLabelValue: string;\n declare cancelLabelValue: string;\n declare initialFocusValue: string;\n\n /** Resolver for the in-flight confirmation Promise (one dialog at a time). */\n #pending: ((confirmed: boolean) => void) | null = null;\n /** Turbo's forms config and its original confirm method, for restore. */\n #turboForms: TurboFormsConfig | null = null;\n #previousConfirm: TurboFormsConfig[\"confirm\"] = undefined;\n\n readonly #trap = new FocusTrap(() => this.dialogTarget, {\n onEscape: () => this.#resolve(false),\n initialFocus: () => this.#initialFocusElement(),\n });\n\n override connect(): void {\n if (this.hasDialogTarget) this.dialogTarget.hidden = true;\n this.#installTurboHook();\n }\n\n override disconnect(): void {\n if (this.#turboForms) {\n this.#turboForms.confirm = this.#previousConfirm;\n this.#turboForms = null;\n }\n // Settle any pending confirmation as cancelled WITHOUT restoring focus: a Turbo\n // teardown must not move focus. The trailing deactivate covers the (defensive)\n // case where the trap is active with nothing pending.\n this.#resolve(false, false);\n this.#trap.deactivate({ restoreFocus: false });\n }\n\n /** Confirms the pending request (resolves `true`). Bound via `data-action`. */\n confirm(): void {\n this.#resolve(true);\n }\n\n /** Cancels the pending request (resolves `false`). Bound via `data-action`. */\n cancel(): void {\n this.#resolve(false);\n }\n\n /**\n * Intercepts a link/button click, shows the confirm dialog, and continues the\n * original action (form submit or navigation) only when confirmed. The message\n * comes from the `message` action param or the element's `data-turbo-confirm`.\n */\n request(event: Event): void {\n const element = (event.currentTarget ?? event.target) as HTMLElement | null;\n if (!element) return;\n event.preventDefault();\n\n const params = (event as { params?: Record<string, unknown> }).params;\n const fromParam = typeof params?.message === \"string\" ? params.message : null;\n const message = fromParam ?? element.getAttribute(\"data-turbo-confirm\") ?? \"\";\n\n void this.#prompt(message).then((confirmed) => {\n if (confirmed) this.#continue(element);\n });\n }\n\n /**\n * Opens the dialog for `message` and resolves once the user confirms or cancels.\n * Degrades to native `window.confirm` when no dialog target is present.\n */\n #prompt(message: string): Promise<boolean> {\n if (!this.hasDialogTarget) return Promise.resolve(window.confirm(message));\n // A second prompt while one is open cancels the first to keep a single dialog.\n this.#resolve(false);\n\n if (this.hasMessageTarget) this.messageTarget.textContent = message;\n if (this.hasConfirmTarget) this.confirmTarget.textContent = this.confirmLabelValue;\n if (this.hasCancelTarget) this.cancelTarget.textContent = this.cancelLabelValue;\n\n return new Promise<boolean>((resolve) => {\n this.#pending = resolve;\n this.dialogTarget.hidden = false;\n this.dispatch(\"open\", { detail: { message } });\n this.#trap.activate();\n });\n }\n\n /**\n * Settles the pending Promise, closes the dialog, and emits `resolve`.\n * `restoreFocus` is forwarded to the trap so teardown (disconnect) can settle a\n * pending confirmation without moving focus.\n */\n #resolve(confirmed: boolean, restoreFocus = true): void {\n const pending = this.#pending;\n if (!pending) return;\n this.#pending = null;\n\n if (this.hasDialogTarget) this.dialogTarget.hidden = true;\n this.#trap.deactivate({ restoreFocus });\n this.dispatch(\"resolve\", { detail: { confirmed } });\n pending(confirmed);\n }\n\n /** Continues the intercepted action when confirmed: submit a form, else navigate. */\n #continue(element: HTMLElement): void {\n if (element instanceof HTMLAnchorElement && element.href) {\n window.location.href = element.href;\n return;\n }\n const form = element instanceof HTMLFormElement ? element : element.closest(\"form\");\n if (form) {\n form.requestSubmit(element instanceof HTMLButtonElement ? element : undefined);\n }\n }\n\n /** Swaps Turbo's confirm method for a Promise-returning bridge to this dialog. */\n #installTurboHook(): void {\n const turbo = (window as Window & { Turbo?: TurboLike }).Turbo;\n const forms = turbo?.config?.forms;\n if (!forms) return;\n this.#turboForms = forms;\n this.#previousConfirm = forms.confirm;\n forms.confirm = (message: string) => this.#prompt(message);\n }\n\n /** The button to focus on open — the least-destructive one (cancel) by default. */\n #initialFocusElement(): HTMLElement | null {\n if (this.initialFocusValue === \"confirm\" && this.hasConfirmTarget) return this.confirmTarget;\n return this.hasCancelTarget ? this.cancelTarget : null;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/before_cache_reset.ts","../../src/utils/escape_layer.ts","../../src/utils/focus_trap.ts","../../src/controllers/confirm_controller.ts"],"names":[],"mappings":";;;;;AA2CO,IAAM,gBAAA,GAAN,MAAM,iBAAA,CAAiB;AAAA;AAAA,EAE5B,OAAgB,YAAA,mBAAe,IAAI,GAAA,EAAsB;AAAA;AAAA,EAGzD,OAAgB,iBAAiB,MAAY;AAC3C,IAAA,KAAA,MAAW,UAAA,IAAc,iBAAA,CAAiB,YAAA,EAAc,UAAA,CAAW,OAAA,EAAQ;AAAA,EAC7E,CAAA;AAAA,EAES,OAAA;AAAA;AAAA,EAGT,YAAY,MAAA,EAAoB;AAC9B,IAAA,IAAA,CAAK,OAAA,GAAU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,MAAM,OAAO,OAAA,YAAmB,eAAA,GAAkB,OAAA,GAAU,OAAA,CAAQ,QAAQ,MAAM,CAAA;AAClF,IAAA,IAAI,IAAA,EAAM;AACR,MAAA,IAAA,CAAK,aAAA,CAAc,OAAA,YAAmB,iBAAA,GAAoB,OAAA,GAAU,MAAS,CAAA;AAAA,IAC/E;AAAA,EACF;AAAA;AAAA,EAGA,iBAAA,GAA0B;AACxB,IAAA,MAAM,QAAS,MAAA,CAA0C,KAAA;AACzD,IAAA,MAAM,KAAA,GAAQ,OAAO,MAAA,EAAQ,KAAA;AAC7B,IAAA,IAAI,CAAC,KAAA,EAAO;AACZ,IAAA,IAAA,CAAK,WAAA,GAAc,KAAA;AACnB,IAAA,IAAA,CAAK,mBAAmB,KAAA,CAAM,OAAA;AAC9B,IAAA,KAAA,CAAM,OAAA,GAAU,CAAC,OAAA,KAAoB,IAAA,CAAK,QAAQ,OAAO,CAAA;AAAA,EAC3D;AAAA;AAAA,EAGA,oBAAA,GAA2C;AACzC,IAAA,IAAI,KAAK,iBAAA,KAAsB,SAAA,IAAa,IAAA,CAAK,gBAAA,SAAyB,IAAA,CAAK,aAAA;AAC/E,IAAA,OAAO,IAAA,CAAK,eAAA,GAAkB,IAAA,CAAK,YAAA,GAAe,IAAA;AAAA,EACpD;AACF","file":"confirm_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 * Single resolver for layered Escape dismissal.\n *\n * Every Escape-dismissable overlay layer (modal focus traps, disclosure\n * overlays like dropdown/popover/menu, and hover-triggered transient layers)\n * registers here while it is open. One document-level listener per document\n * resolves each press to exactly one owner and invokes that layer's\n * {@link EscapeLayerOptions.onDismiss} — controllers never listen for a\n * dismissing Escape themselves.\n *\n * @remarks\n * Each document owns an activation-ordered stack. The owner of a press is the\n * **topmost layer whose {@link EscapeLayerOptions.claims} passes**; a layer\n * that declines is transparent, so a background overlay opened behind a modal\n * never blocks it. Because a layer opened from within another is necessarily\n * activated later, LIFO order is also inner-first for nested layers — no DOM\n * inspection is needed.\n *\n * The shared listener runs in the document bubble phase and honors\n * `event.defaultPrevented`, so an element-level widget handler that consumes\n * Escape first (an editor cancelling its edit, a combobox closing its list)\n * always wins over every registered layer — the deepest handler resolves the\n * press. A keydown that is part of an IME composition (`event.isComposing`)\n * cancels the composition, never a layer, and is ignored here for every layer\n * at once.\n *\n * A WeakMap keeps documents collectible; the listener is installed only while\n * a document's stack is non-empty, and controller lifecycle hooks guarantee\n * that disconnected layers never remain registered.\n */\n\n/** Behavior a layer registers when it activates. */\nexport interface EscapeLayerOptions {\n /**\n * Dismisses the layer. Called by the shared resolver when this layer owns a\n * press; the resolver has already consumed the event (`preventDefault()`),\n * so the callback only needs to close and place focus per the widget's\n * contract.\n */\n onDismiss: () => void;\n /**\n * Whether the layer claims the current press. Evaluated per press, so it can\n * depend on live state (e.g. \"focus is inside me or fell to the body\"). A\n * declining layer is skipped and the next layer down is consulted; omitting\n * it means the layer always claims while active.\n */\n claims?: () => boolean;\n}\n\n/** A document's stack plus the one shared listener bound to it. */\ninterface EscapeLayerRegistry {\n stack: EscapeLayer[];\n onKeydown: (event: KeyboardEvent) => void;\n}\n\n/**\n * Claims predicate shared by the click-opened disclosure overlays (dropdown /\n * popover / navigation-menu / menu / context-menu / menubar): the layer claims\n * a press while focus is inside `element`, or after focus fell to the body —\n * a click on non-focusable overlay content blurs to `<body>`, and Escape must\n * still close the overlay (the \"body-focus rescue\"). A press made after focus\n * moved to another interactive element is declined, so closing never yanks\n * focus away from where the user deliberately went.\n */\nexport function claimsWhileFocusWithin(element: Element): () => boolean {\n return () => {\n const active = element.ownerDocument.activeElement;\n return active === null || active === element.ownerDocument.body || element.contains(active);\n };\n}\n\nexport class EscapeLayer {\n static readonly #registries = new WeakMap<Document, EscapeLayerRegistry>();\n\n #ownerDocument: Document | null = null;\n /** Dismissal callback while active; `null` when inactive. */\n #onDismiss: (() => void) | null = null;\n /** Live predicate deciding whether the layer claims a press; `null` = always. */\n #claims: (() => boolean) | null = null;\n\n /**\n * Activates this layer at the top of its document's Escape stack, installing\n * the document's shared resolver listener if this is its first layer.\n * Re-activating an already-active layer moves it to the top.\n */\n activate(ownerDocument: Document = document, options: EscapeLayerOptions): void {\n this.deactivate();\n let registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) {\n registry = EscapeLayer.#createRegistry();\n EscapeLayer.#registries.set(ownerDocument, registry);\n ownerDocument.addEventListener(\"keydown\", registry.onKeydown);\n }\n registry.stack.push(this);\n this.#ownerDocument = ownerDocument;\n this.#onDismiss = options.onDismiss;\n this.#claims = options.claims ?? null;\n }\n\n /**\n * Removes this layer from its document's Escape stack, uninstalling the\n * shared listener when the stack empties. Safe to call when inactive.\n */\n deactivate(): void {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return;\n\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (registry) {\n const index = registry.stack.lastIndexOf(this);\n if (index >= 0) registry.stack.splice(index, 1);\n if (registry.stack.length === 0) {\n ownerDocument.removeEventListener(\"keydown\", registry.onKeydown);\n EscapeLayer.#registries.delete(ownerDocument);\n }\n }\n this.#ownerDocument = null;\n this.#onDismiss = null;\n this.#claims = null;\n }\n\n /**\n * Whether this active layer would own a press right now: it is the topmost\n * layer whose {@link EscapeLayerOptions.claims} passes. Exposed for tests\n * and diagnostics — production dismissal goes through the shared listener.\n */\n get ownsEscape(): boolean {\n const ownerDocument = this.#ownerDocument;\n if (!ownerDocument) return false;\n const registry = EscapeLayer.#registries.get(ownerDocument);\n if (!registry) return false;\n return EscapeLayer.#resolveOwner(registry.stack) === this;\n }\n\n /** Builds a document's registry with its shared resolver listener. */\n static #createRegistry(): EscapeLayerRegistry {\n const registry: EscapeLayerRegistry = {\n stack: [],\n onKeydown: (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.defaultPrevented || event.isComposing) return;\n const owner = EscapeLayer.#resolveOwner(registry.stack);\n if (!owner) return;\n event.preventDefault();\n owner.#onDismiss?.();\n },\n };\n return registry;\n }\n\n /** The topmost stack layer whose claims predicate passes, or `null`. */\n static #resolveOwner(stack: EscapeLayer[]): EscapeLayer | null {\n for (let index = stack.length - 1; index >= 0; index--) {\n const layer = stack[index];\n if (!layer) continue;\n if (layer.#claims && !layer.#claims()) continue;\n return layer;\n }\n return null;\n }\n}\n","import { BeforeCacheReset } from \"./before_cache_reset\";\nimport { EscapeLayer } from \"./escape_layer\";\n\n/**\n * Modal focus-trap primitive shared by the modal-overlay controllers\n * (dialog / alert-dialog / confirm / drawer / command-palette / sidebar); the\n * non-modal focus scope (focus) reuses it with the modal side effects opted out.\n *\n * The WAI-ARIA APG modal pattern is more than \"cycle Tab inside a box\": a modal\n * also locks background scroll, makes the rest of the page `inert` (so assistive\n * technology and pointer/Tab cannot reach it, honoring `aria-modal=\"true\"`),\n * sends focus inside on open, and restores it to the opener on close — and every\n * one of those side effects must be reverted if the element is torn down while\n * open (a Turbo navigation mid-dialog) and kept out of the snapshot Turbo\n * caches (`turbo:before-cache`). {@link FocusTrap} owns that whole modal\n * lifecycle so each controller only decides *when* to open/close and *what*\n * \"close\" means.\n *\n * It is intentionally **policy-free about closing**. Escape semantics differ per\n * widget (a plain dialog just closes; an alert-dialog closes *as a cancel* with a\n * reason; a drawer runs an exit transition), so the trap merely forwards Escape\n * to an {@link FocusTrapOptions.onEscape | onEscape} callback and never decides on\n * its own what closing entails.\n *\n * @remarks\n * The container is read through a getter so a controller can hand over a Stimulus\n * target without worrying about when the trap instance is constructed relative to\n * `connect()`.\n */\n\n/**\n * Selector matching the elements considered focusable. Shared by the trap's Tab\n * cycling and by form-validation's invalid-focus delegation.\n */\nexport const FOCUSABLE =\n 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex=\"-1\"])';\n\n/** Behavior hooks a controller supplies when constructing a {@link FocusTrap}. */\nexport interface FocusTrapOptions {\n /**\n * Called when `Escape` is pressed while the trap is active. When omitted,\n * `Escape` is left alone (the trap never joins the Escape stack). Dismissal\n * is resolved by the shared {@link EscapeLayer}: an Escape already consumed\n * by an inner handler is ignored, and among active layers the most recently\n * activated claiming one owns the press. The resolver consumes the event\n * before invoking the callback.\n */\n onEscape?: () => void;\n /**\n * Returns the element to focus when the trap activates. When it returns `null`\n * (or is omitted), the first focusable descendant is used, falling back to the\n * container itself (made programmatically focusable with `tabindex=-1`).\n */\n initialFocus?: () => HTMLElement | null;\n /**\n * Returns the element to focus on deactivation when nothing was focused before\n * the trap opened (e.g. the trigger). The element focused *before* opening\n * always takes precedence.\n */\n fallbackFocus?: () => HTMLElement | null;\n /**\n * Lock background scroll (`body` overflow) while active. Defaults to `true` for\n * the modal overlays; a lighter focus scope passes `false`. Read on `activate`.\n */\n lockScroll?: boolean | (() => boolean);\n /**\n * Make background siblings `inert` while active (the `aria-modal` isolation).\n * Defaults to `true` for the modal overlays; a soft focus scope can opt out so\n * the background stays reachable while `Tab` still cycles inside. Read on `activate`.\n */\n isolate?: boolean | (() => boolean);\n /**\n * Move focus inside on `activate`. Defaults to `true`; a focus scope that only\n * wants the `Tab` boundary (no focus move) passes `false`. Read on `activate`.\n */\n autoFocus?: boolean | (() => boolean);\n}\n\n/**\n * Owns the modal side effects (scroll lock, background `inert`, focus trap, focus\n * restore) for a single container, applied on {@link activate} and reverted on\n * {@link deactivate}.\n */\nexport class FocusTrap {\n /** The element focused before activation, restored on deactivation. */\n #previouslyFocused: HTMLElement | null = null;\n /** The body's inline `overflow` before locking, restored on deactivation. */\n #previousBodyOverflow = \"\";\n /** Whether scroll was locked this activation (so it is only restored if applied). */\n #scrollLocked = false;\n /** Background siblings made `inert` while active, restored on deactivation. */\n #inertedSiblings: HTMLElement[] = [];\n /** Whether the modal side effects are currently applied. */\n #activeState = false;\n /** Registers the trap on the shared Escape stack while active (see {@link EscapeLayer}). */\n readonly #escapeLayer = new EscapeLayer();\n\n /** Returns the trapped element; called on every operation for the live target. */\n readonly #getContainer: () => HTMLElement;\n /** Closing/focus hooks; see {@link FocusTrapOptions}. */\n readonly #options: FocusTrapOptions;\n\n /**\n * @param getContainer - Returns the trapped element. Called on every operation\n * so the live target is always used.\n * @param options - Closing/focus hooks; see {@link FocusTrapOptions}.\n */\n constructor(getContainer: () => HTMLElement, options: FocusTrapOptions = {}) {\n this.#getContainer = getContainer;\n this.#options = options;\n }\n\n /** Whether the trap is currently active. */\n get active(): boolean {\n return this.#activeState;\n }\n\n /**\n * Applies the trap: records the current focus, optionally locks background scroll\n * and makes background siblings `inert`, listens for `Tab`/`Escape`, and (unless\n * `autoFocus` is off) moves focus inside. No-ops if already active.\n */\n activate(): void {\n if (this.#activeState) return;\n this.#activeState = true;\n // Record the opener so it can be refocused on close. `<body>` (the default\n // active element when nothing is focused) is treated as \"nothing\", so the\n // fallback target — typically the trigger — wins in that case.\n const active = document.activeElement;\n this.#previouslyFocused =\n active instanceof HTMLElement && active !== document.body ? active : null;\n if (this.#flag(this.#options.lockScroll, true)) {\n this.#previousBodyOverflow = document.body.style.overflow;\n document.body.style.overflow = \"hidden\";\n this.#scrollLocked = true;\n }\n if (this.#flag(this.#options.isolate, true)) this.#isolateBackground();\n document.addEventListener(\"keydown\", this.#onKeydown);\n this.#beforeCache.activate();\n const onEscape = this.#options.onEscape;\n if (onEscape) this.#escapeLayer.activate(document, { onDismiss: () => onEscape() });\n if (this.#flag(this.#options.autoFocus, true)) this.#focusInitial();\n }\n\n /**\n * Reverts every side effect applied by {@link activate}. No-ops if inactive, so\n * a controller can call it defensively from both `close()` and `disconnect()`.\n *\n * @param restoreFocus - Move focus back to the opener (default `true`). Pass\n * `false` on teardown (`disconnect`), where yanking focus is undesirable.\n */\n deactivate({ restoreFocus = true }: { restoreFocus?: boolean } = {}): void {\n if (!this.#activeState) return;\n this.#activeState = false;\n this.#escapeLayer.deactivate();\n document.removeEventListener(\"keydown\", this.#onKeydown);\n this.#beforeCache.deactivate();\n if (this.#scrollLocked) {\n document.body.style.overflow = this.#previousBodyOverflow;\n this.#scrollLocked = false;\n }\n this.#releaseBackground();\n if (restoreFocus) {\n const target = this.#previouslyFocused ?? this.#options.fallbackFocus?.() ?? null;\n target?.focus();\n }\n }\n\n /** Resolves a boolean-or-getter option, defaulting when it was not provided. */\n #flag(option: boolean | (() => boolean) | undefined, fallback: boolean): boolean {\n if (option === undefined) return fallback;\n return typeof option === \"function\" ? option() : option;\n }\n\n /**\n * Reverts the side effects just before Turbo caches the page snapshot, so an\n * overlay left open does not bake the scroll lock into `body[style]` — a\n * restored page would feed that locked value back into {@link activate} as the\n * baseline, and closing would then never unlock the page. Markup state stays\n * untouched (restore-open designs reopen against a clean baseline), and focus\n * is left alone mid-navigation. The listener lives only while active.\n */\n readonly #beforeCache = new BeforeCacheReset(() => this.deactivate({ restoreFocus: false }));\n\n /**\n * Handles `Tab` (focus trap) while active. `Escape` dismissal is owned by the\n * shared {@link EscapeLayer} resolver, so Tab trapping stays independent of\n * which layer currently owns Escape.\n */\n readonly #onKeydown = (event: KeyboardEvent): void => {\n if (event.key === \"Tab\") this.#trapTab(event);\n };\n\n /** Keeps `Tab` focus cycling within the container's focusable elements. */\n #trapTab(event: KeyboardEvent): void {\n const focusable = this.#focusableElements();\n if (focusable.length === 0) {\n event.preventDefault();\n return;\n }\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n const active = document.activeElement;\n\n // If focus has somehow escaped the container, pull it back to the first item.\n if (!(active instanceof Node) || !this.#getContainer().contains(active)) {\n event.preventDefault();\n first?.focus();\n return;\n }\n\n if (event.shiftKey && active === first) {\n event.preventDefault();\n last?.focus();\n } else if (!event.shiftKey && active === last) {\n event.preventDefault();\n first?.focus();\n }\n }\n\n /**\n * Marks every element outside the container's subtree as `inert` so background\n * content cannot be focused or reached by assistive technology, honoring the\n * `aria-modal=\"true\"` contract. An element that was *already* `inert` is left\n * untracked so `#releaseBackground` does not wrongly clear it.\n */\n #isolateBackground(): void {\n const container = this.#getContainer();\n this.#inertedSiblings = [];\n for (const sibling of Array.from(document.body.children)) {\n if (!(sibling instanceof HTMLElement)) continue;\n if (sibling.contains(container) || sibling.inert) continue;\n sibling.inert = true;\n this.#inertedSiblings.push(sibling);\n }\n }\n\n /** Reverts the `inert` flags applied by `#isolateBackground`. */\n #releaseBackground(): void {\n for (const sibling of this.#inertedSiblings) {\n sibling.inert = false;\n }\n this.#inertedSiblings = [];\n }\n\n /** Moves focus to the initial target, the first focusable, or the container. */\n #focusInitial(): void {\n const preferred = this.#options.initialFocus?.();\n if (preferred) {\n preferred.focus();\n return;\n }\n const focusable = this.#focusableElements();\n if (focusable[0]) {\n focusable[0].focus();\n return;\n }\n const container = this.#getContainer();\n container.tabIndex = -1;\n container.focus();\n }\n\n /** Collects the container's currently focusable descendants in DOM order. */\n #focusableElements(): HTMLElement[] {\n return Array.from(this.#getContainer().querySelectorAll<HTMLElement>(FOCUSABLE)).filter(\n (el) => !el.hidden,\n );\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { FocusTrap } from \"../utils/focus_trap\";\n\n/** The slice of Turbo's form config this controller swaps the confirm method on. */\ninterface TurboFormsConfig {\n confirm?: (message: string, element?: HTMLElement) => boolean | Promise<boolean>;\n}\ninterface TurboLike {\n config?: { forms?: TurboFormsConfig };\n}\n\n/**\n * Headless **confirm bridge** — replaces the native `window.confirm()` Turbo uses\n * for `data-turbo-confirm` with an accessible **Alert Dialog** (WAI-ARIA APG Alert\n * Dialog pattern). Reuses the shared {@link FocusTrap}; the consumer only writes the\n * dialog markup and \"what to do on confirm\".\n *\n * Markup contract (identifier: `stimeo--confirm`):\n * <div data-controller=\"stimeo--confirm\">\n * <div data-stimeo--confirm-target=\"dialog\" role=\"alertdialog\" aria-modal=\"true\"\n * aria-labelledby=\"ct\" aria-describedby=\"cm\" hidden>\n * <h2 id=\"ct\" data-stimeo--confirm-target=\"title\">Are you sure?</h2>\n * <p id=\"cm\" data-stimeo--confirm-target=\"message\"></p>\n * <button data-stimeo--confirm-target=\"cancel\"\n * data-action=\"click->stimeo--confirm#cancel\"></button>\n * <button data-stimeo--confirm-target=\"confirm\"\n * data-action=\"click->stimeo--confirm#confirm\"></button>\n * </div>\n * </div>\n *\n * <!-- Driven automatically through Turbo's confirm hook: -->\n * <form data-turbo-confirm=\"Delete this item?\" action=\"/items/1\" method=\"post\">…</form>\n * <!-- Or intercept any link/button directly: -->\n * <a href=\"/items/1\" data-action=\"click->stimeo--confirm#request\"\n * data-stimeo--confirm-message-param=\"Delete this item?\">Delete</a>\n *\n * @remarks\n * Behavior only — the dialog's a11y (focus trap, restore, roles) is delegated to\n * the shared {@link FocusTrap}; this controller adds the Turbo bridge and the\n * confirm/cancel resolution. On `connect()` it swaps `Turbo.config.forms.confirm`\n * for a Promise-returning method and restores the original on `disconnect()` (Turbo\n * navigation included), so registration never leaks or stacks. Escape cancels\n * (returns `false`); when no dialog target exists it degrades to native\n * `window.confirm`. The least-destructive button (cancel, by default) takes initial\n * focus.\n */\nexport class ConfirmController extends Controller<HTMLElement> {\n static override targets = [\"dialog\", \"title\", \"message\", \"confirm\", \"cancel\"];\n static override values = {\n confirmLabel: { type: String, default: \"OK\" },\n cancelLabel: { type: String, default: \"Cancel\" },\n initialFocus: { type: String, default: \"cancel\" },\n };\n static actions = [\"confirm\", \"cancel\", \"request\"] as const;\n static events = [\"open\", \"resolve\"] as const;\n\n declare readonly dialogTarget: HTMLElement;\n /**\n * Static heading slot naming the dialog (via `aria-labelledby`). Never written\n * by the controller — the accessible name is author-owned; only `message` and\n * the button labels are injected per prompt.\n */\n declare readonly titleTarget: HTMLElement;\n declare readonly messageTarget: HTMLElement;\n declare readonly confirmTarget: HTMLElement;\n declare readonly cancelTarget: HTMLElement;\n declare readonly hasDialogTarget: boolean;\n declare readonly hasMessageTarget: boolean;\n declare readonly hasConfirmTarget: boolean;\n declare readonly hasCancelTarget: boolean;\n\n declare confirmLabelValue: string;\n declare cancelLabelValue: string;\n declare initialFocusValue: string;\n\n /** Resolver for the in-flight confirmation Promise (one dialog at a time). */\n #pending: ((confirmed: boolean) => void) | null = null;\n /** Turbo's forms config and its original confirm method, for restore. */\n #turboForms: TurboFormsConfig | null = null;\n #previousConfirm: TurboFormsConfig[\"confirm\"] = undefined;\n\n readonly #trap = new FocusTrap(() => this.dialogTarget, {\n onEscape: () => this.#resolve(false),\n initialFocus: () => this.#initialFocusElement(),\n });\n\n override connect(): void {\n if (this.hasDialogTarget) this.dialogTarget.hidden = true;\n this.#installTurboHook();\n }\n\n override disconnect(): void {\n if (this.#turboForms) {\n this.#turboForms.confirm = this.#previousConfirm;\n this.#turboForms = null;\n }\n // Settle any pending confirmation as cancelled WITHOUT restoring focus: a Turbo\n // teardown must not move focus. The trailing deactivate covers the (defensive)\n // case where the trap is active with nothing pending.\n this.#resolve(false, false);\n this.#trap.deactivate({ restoreFocus: false });\n }\n\n /** Confirms the pending request (resolves `true`). Bound via `data-action`. */\n confirm(): void {\n this.#resolve(true);\n }\n\n /** Cancels the pending request (resolves `false`). Bound via `data-action`. */\n cancel(): void {\n this.#resolve(false);\n }\n\n /**\n * Intercepts a link/button click, shows the confirm dialog, and continues the\n * original action (form submit or navigation) only when confirmed. The message\n * comes from the `message` action param or the element's `data-turbo-confirm`.\n */\n request(event: Event): void {\n const element = (event.currentTarget ?? event.target) as HTMLElement | null;\n if (!element) return;\n event.preventDefault();\n\n const params = (event as { params?: Record<string, unknown> }).params;\n const fromParam = typeof params?.message === \"string\" ? params.message : null;\n const message = fromParam ?? element.getAttribute(\"data-turbo-confirm\") ?? \"\";\n\n void this.#prompt(message).then((confirmed) => {\n if (confirmed) this.#continue(element);\n });\n }\n\n /**\n * Opens the dialog for `message` and resolves once the user confirms or cancels.\n * Degrades to native `window.confirm` when no dialog target is present.\n */\n #prompt(message: string): Promise<boolean> {\n if (!this.hasDialogTarget) return Promise.resolve(window.confirm(message));\n // A second prompt while one is open cancels the first to keep a single dialog.\n this.#resolve(false);\n\n if (this.hasMessageTarget) this.messageTarget.textContent = message;\n if (this.hasConfirmTarget) this.confirmTarget.textContent = this.confirmLabelValue;\n if (this.hasCancelTarget) this.cancelTarget.textContent = this.cancelLabelValue;\n\n return new Promise<boolean>((resolve) => {\n this.#pending = resolve;\n this.dialogTarget.hidden = false;\n this.dispatch(\"open\", { detail: { message } });\n this.#trap.activate();\n });\n }\n\n /**\n * Settles the pending Promise, closes the dialog, and emits `resolve`.\n * `restoreFocus` is forwarded to the trap so teardown (disconnect) can settle a\n * pending confirmation without moving focus.\n */\n #resolve(confirmed: boolean, restoreFocus = true): void {\n const pending = this.#pending;\n if (!pending) return;\n this.#pending = null;\n\n if (this.hasDialogTarget) this.dialogTarget.hidden = true;\n this.#trap.deactivate({ restoreFocus });\n this.dispatch(\"resolve\", { detail: { confirmed } });\n pending(confirmed);\n }\n\n /** Continues the intercepted action when confirmed: submit a form, else navigate. */\n #continue(element: HTMLElement): void {\n if (element instanceof HTMLAnchorElement && element.href) {\n window.location.href = element.href;\n return;\n }\n const form = element instanceof HTMLFormElement ? element : element.closest(\"form\");\n if (form) {\n form.requestSubmit(element instanceof HTMLButtonElement ? element : undefined);\n }\n }\n\n /** Swaps Turbo's confirm method for a Promise-returning bridge to this dialog. */\n #installTurboHook(): void {\n const turbo = (window as Window & { Turbo?: TurboLike }).Turbo;\n const forms = turbo?.config?.forms;\n if (!forms) return;\n this.#turboForms = forms;\n this.#previousConfirm = forms.confirm;\n forms.confirm = (message: string) => this.#prompt(message);\n }\n\n /** The button to focus on open — the least-destructive one (cancel) by default. */\n #initialFocusElement(): HTMLElement | null {\n if (this.initialFocusValue === \"confirm\" && this.hasConfirmTarget) return this.confirmTarget;\n return this.hasCancelTarget ? this.cancelTarget : null;\n }\n}\n"]}
|
|
@@ -24,9 +24,14 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
24
24
|
*
|
|
25
25
|
* @remarks
|
|
26
26
|
* Behavior only — slot text is updated, not styled. Pause/resume shifts an
|
|
27
|
-
* internal time anchor so the displayed amount is preserved across a pause
|
|
28
|
-
*
|
|
29
|
-
*
|
|
27
|
+
* internal time anchor so the displayed amount is preserved across a pause, down
|
|
28
|
+
* to the second actually on screen: resuming continues from that reading rather
|
|
29
|
+
* than from the fraction behind it, so the first tick after a resume steps by one
|
|
30
|
+
* unit like every other. The run state lives in `data-state` and the markup is its
|
|
31
|
+
* source of truth — `autostart` only decides the state of a timer whose markup does
|
|
32
|
+
* not carry one. The interval is owned by {@link SafeInterval} and torn down on
|
|
33
|
+
* `disconnect()` (Turbo navigation included); nothing else needs carrying across,
|
|
34
|
+
* because every reading is re-derived from `deadline` and the wall clock.
|
|
30
35
|
*/
|
|
31
36
|
declare class CountdownController extends Controller<HTMLElement> {
|
|
32
37
|
#private;
|
|
@@ -52,6 +57,10 @@ declare class CountdownController extends Controller<HTMLElement> {
|
|
|
52
57
|
type: StringConstructor;
|
|
53
58
|
default: string;
|
|
54
59
|
};
|
|
60
|
+
announceText: {
|
|
61
|
+
type: StringConstructor;
|
|
62
|
+
default: string;
|
|
63
|
+
};
|
|
55
64
|
};
|
|
56
65
|
static actions: readonly ["pause", "reset", "resume", "start"];
|
|
57
66
|
static events: readonly ["complete", "tick"];
|
|
@@ -70,8 +79,13 @@ declare class CountdownController extends Controller<HTMLElement> {
|
|
|
70
79
|
directionValue: string;
|
|
71
80
|
autostartValue: boolean;
|
|
72
81
|
completeLabelValue: string;
|
|
82
|
+
announceTextValue: string;
|
|
73
83
|
connect(): void;
|
|
74
84
|
disconnect(): void;
|
|
85
|
+
/** Re-derives the display when a morph swaps the deadline in place. */
|
|
86
|
+
deadlineValueChanged(): void;
|
|
87
|
+
/** Re-derives the display when a morph flips the counting direction in place. */
|
|
88
|
+
directionValueChanged(): void;
|
|
75
89
|
/** Starts (or restarts after pause) ticking toward the deadline. */
|
|
76
90
|
start(): void;
|
|
77
91
|
/** Pauses ticking, preserving the currently displayed amount. */
|
|
@@ -83,8 +97,8 @@ declare class CountdownController extends Controller<HTMLElement> {
|
|
|
83
97
|
* run state**: a running timer keeps counting down from the reset amount, while a
|
|
84
98
|
* paused (or completed) one resets the displayed amount but stays paused until the
|
|
85
99
|
* user resumes — it never silently restarts. The run state is read from the DOM,
|
|
86
|
-
* not re-derived from the declarative `autostart` Value (which only
|
|
87
|
-
*
|
|
100
|
+
* not re-derived from the declarative `autostart` Value (which governs only markup
|
|
101
|
+
* that states no run state at all); re-deriving it would override a user's pause —
|
|
88
102
|
* the DOM, not a re-run of declarative config, is the source of truth.
|
|
89
103
|
*/
|
|
90
104
|
reset(): void;
|
|
@@ -2,6 +2,56 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
2
2
|
|
|
3
3
|
// src/controllers/countdown_controller.ts
|
|
4
4
|
|
|
5
|
+
// src/utils/announce.ts
|
|
6
|
+
function announce(message, options = {}) {
|
|
7
|
+
const text = message.trim();
|
|
8
|
+
if (text.length === 0) return;
|
|
9
|
+
window.dispatchEvent(
|
|
10
|
+
new CustomEvent("stimeo--announcer:announce", {
|
|
11
|
+
detail: { message: text, assertive: options.assertive === true }
|
|
12
|
+
})
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
function fillTemplate(template, values) {
|
|
16
|
+
return template.replace(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g, (match, name) => {
|
|
17
|
+
const replacement = values[name];
|
|
18
|
+
return replacement === void 0 ? match : String(replacement);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// src/utils/microtask_coalescer.ts
|
|
23
|
+
var MicrotaskCoalescer = class {
|
|
24
|
+
#run;
|
|
25
|
+
#queued = false;
|
|
26
|
+
#active = false;
|
|
27
|
+
#generation = 0;
|
|
28
|
+
/** @param run - the single reconciliation pass, invoked at most once per batch. */
|
|
29
|
+
constructor(run) {
|
|
30
|
+
this.#run = run;
|
|
31
|
+
}
|
|
32
|
+
/** Opens the window in which {@link schedule} is honoured; call from `connect()`. */
|
|
33
|
+
activate() {
|
|
34
|
+
this.#active = true;
|
|
35
|
+
}
|
|
36
|
+
/** Closes the window and drops any pending pass; call from `disconnect()`. */
|
|
37
|
+
cancel() {
|
|
38
|
+
this.#active = false;
|
|
39
|
+
this.#queued = false;
|
|
40
|
+
this.#generation += 1;
|
|
41
|
+
}
|
|
42
|
+
/** Requests one pass after the batch settles. Idempotent; inert outside the window. */
|
|
43
|
+
schedule() {
|
|
44
|
+
if (!this.#active || this.#queued) return;
|
|
45
|
+
this.#queued = true;
|
|
46
|
+
const generation = this.#generation;
|
|
47
|
+
queueMicrotask(() => {
|
|
48
|
+
if (generation !== this.#generation || !this.#queued || !this.#active) return;
|
|
49
|
+
this.#queued = false;
|
|
50
|
+
this.#run();
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
5
55
|
// src/utils/safe_timeout.ts
|
|
6
56
|
var TimerRegistry = class {
|
|
7
57
|
/** Live timer ids that have not yet been cleared (or, for timeouts, fired). */
|
|
@@ -48,6 +98,7 @@ var SafeInterval = class extends TimerRegistry {
|
|
|
48
98
|
};
|
|
49
99
|
|
|
50
100
|
// src/controllers/countdown_controller.ts
|
|
101
|
+
var SECOND_MS = 1e3;
|
|
51
102
|
var CountdownController = class extends Controller {
|
|
52
103
|
static targets = ["days", "hours", "minutes", "seconds", "status"];
|
|
53
104
|
static values = {
|
|
@@ -55,34 +106,79 @@ var CountdownController = class extends Controller {
|
|
|
55
106
|
interval: { type: Number, default: 1e3 },
|
|
56
107
|
direction: { type: String, default: "down" },
|
|
57
108
|
autostart: { type: Boolean, default: true },
|
|
58
|
-
completeLabel: { type: String, default: "" }
|
|
109
|
+
completeLabel: { type: String, default: "" },
|
|
110
|
+
announceText: { type: String, default: "" }
|
|
59
111
|
};
|
|
60
112
|
static actions = ["pause", "reset", "resume", "start"];
|
|
61
113
|
static events = ["complete", "tick"];
|
|
62
114
|
#intervals = new SafeInterval();
|
|
63
115
|
#intervalId = null;
|
|
116
|
+
/** Collapses a morph that swaps several render inputs at once into one re-derive. */
|
|
117
|
+
#resync = new MicrotaskCoalescer(() => this.#resyncToValues());
|
|
64
118
|
/** Epoch-ms anchor: the deadline (down) or the count-up origin (up). */
|
|
65
119
|
#reference = 0;
|
|
66
120
|
/** Amount (ms) captured at pause, so resume can restore the same display. */
|
|
67
121
|
#pausedAmount = 0;
|
|
122
|
+
/**
|
|
123
|
+
* The amount the slots are currently showing, floored to the second they render.
|
|
124
|
+
* It lags {@link currentAmount} by up to one tick, and it — not the live reading —
|
|
125
|
+
* is what a pause has to preserve: storing the fraction behind the display instead
|
|
126
|
+
* makes the first tick after a resume step by two units.
|
|
127
|
+
*/
|
|
128
|
+
#renderedAmount = 0;
|
|
68
129
|
connect() {
|
|
130
|
+
this.#resync.activate();
|
|
69
131
|
this.#initReference();
|
|
70
|
-
this.#
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
132
|
+
const amount = this.#currentAmount();
|
|
133
|
+
this.#render(amount);
|
|
134
|
+
this.#pausedAmount = this.#renderedAmount;
|
|
135
|
+
const authored = this.element.getAttribute("data-state");
|
|
136
|
+
if (authored === null) {
|
|
137
|
+
if (this.autostartValue && this.#isValidDeadline) {
|
|
138
|
+
this.start();
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
74
141
|
this.element.setAttribute("data-state", "paused");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (authored === "complete" && this.#isDown && amount <= 0) {
|
|
145
|
+
return;
|
|
75
146
|
}
|
|
147
|
+
const wasRunning = authored === "running";
|
|
148
|
+
this.element.setAttribute("data-state", "paused");
|
|
149
|
+
if (wasRunning) this.start();
|
|
76
150
|
}
|
|
77
151
|
disconnect() {
|
|
152
|
+
this.#resync.cancel();
|
|
78
153
|
this.#intervals.clearAll();
|
|
79
154
|
this.#intervalId = null;
|
|
80
155
|
}
|
|
156
|
+
/** Re-derives the display when a morph swaps the deadline in place. */
|
|
157
|
+
deadlineValueChanged() {
|
|
158
|
+
this.#resync.schedule();
|
|
159
|
+
}
|
|
160
|
+
/** Re-derives the display when a morph flips the counting direction in place. */
|
|
161
|
+
directionValueChanged() {
|
|
162
|
+
this.#resync.schedule();
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Points the anchor at the current `deadline` / `direction` and repaints.
|
|
166
|
+
*
|
|
167
|
+
* Render only: it starts no interval and emits no event, so a morph cannot make a
|
|
168
|
+
* paused timer run or replay a milestone. A running one needs no restart either —
|
|
169
|
+
* every tick reads the anchor, so moving it is enough. While paused the stored
|
|
170
|
+
* amount follows the new reading, or resume would continue from the old deadline.
|
|
171
|
+
*/
|
|
172
|
+
#resyncToValues() {
|
|
173
|
+
this.#initReference();
|
|
174
|
+
this.#render(this.#currentAmount());
|
|
175
|
+
if (this.#state !== "running") this.#pausedAmount = this.#renderedAmount;
|
|
176
|
+
}
|
|
81
177
|
/** Starts (or restarts after pause) ticking toward the deadline. */
|
|
82
178
|
start() {
|
|
83
179
|
if (this.#state === "running" || !this.#isValidDeadline) return;
|
|
84
180
|
if (this.#isDown && this.#currentAmount() <= 0) {
|
|
85
|
-
this.#complete();
|
|
181
|
+
if (this.#state !== "complete") this.#complete();
|
|
86
182
|
return;
|
|
87
183
|
}
|
|
88
184
|
this.#runInterval();
|
|
@@ -90,7 +186,7 @@ var CountdownController = class extends Controller {
|
|
|
90
186
|
/** Pauses ticking, preserving the currently displayed amount. */
|
|
91
187
|
pause() {
|
|
92
188
|
if (this.#state !== "running") return;
|
|
93
|
-
this.#pausedAmount = this.#
|
|
189
|
+
this.#pausedAmount = this.#renderedAmount;
|
|
94
190
|
this.#teardownInterval();
|
|
95
191
|
this.element.setAttribute("data-state", "paused");
|
|
96
192
|
}
|
|
@@ -106,8 +202,8 @@ var CountdownController = class extends Controller {
|
|
|
106
202
|
* run state**: a running timer keeps counting down from the reset amount, while a
|
|
107
203
|
* paused (or completed) one resets the displayed amount but stays paused until the
|
|
108
204
|
* user resumes — it never silently restarts. The run state is read from the DOM,
|
|
109
|
-
* not re-derived from the declarative `autostart` Value (which only
|
|
110
|
-
*
|
|
205
|
+
* not re-derived from the declarative `autostart` Value (which governs only markup
|
|
206
|
+
* that states no run state at all); re-deriving it would override a user's pause —
|
|
111
207
|
* the DOM, not a re-run of declarative config, is the source of truth.
|
|
112
208
|
*/
|
|
113
209
|
reset() {
|
|
@@ -116,13 +212,15 @@ var CountdownController = class extends Controller {
|
|
|
116
212
|
this.#initReference();
|
|
117
213
|
const amount = this.#currentAmount();
|
|
118
214
|
this.#render(amount);
|
|
119
|
-
if (this.hasStatusTarget
|
|
215
|
+
if (this.hasStatusTarget && this.statusTarget.textContent === this.completeLabelValue) {
|
|
216
|
+
this.statusTarget.textContent = "";
|
|
217
|
+
}
|
|
120
218
|
this.element.setAttribute("data-state", "paused");
|
|
121
219
|
if (wasRunning && this.#isValidDeadline) {
|
|
122
220
|
this.#pausedAmount = 0;
|
|
123
221
|
this.start();
|
|
124
222
|
} else {
|
|
125
|
-
this.#pausedAmount =
|
|
223
|
+
this.#pausedAmount = this.#renderedAmount;
|
|
126
224
|
}
|
|
127
225
|
}
|
|
128
226
|
/** Schedules the repeating tick and marks the timer running. */
|
|
@@ -157,6 +255,7 @@ var CountdownController = class extends Controller {
|
|
|
157
255
|
this.statusTarget.textContent = this.completeLabelValue;
|
|
158
256
|
}
|
|
159
257
|
this.dispatch("complete", { detail: {} });
|
|
258
|
+
announce(fillTemplate(this.announceTextValue, {}));
|
|
160
259
|
}
|
|
161
260
|
/** Sets the time anchor from the `deadline` value. */
|
|
162
261
|
#initReference() {
|
|
@@ -171,7 +270,8 @@ var CountdownController = class extends Controller {
|
|
|
171
270
|
}
|
|
172
271
|
/** Writes the amount into the day/hour/minute/second slots. */
|
|
173
272
|
#render(amount) {
|
|
174
|
-
const totalSeconds = Math.floor(amount /
|
|
273
|
+
const totalSeconds = Math.floor(amount / SECOND_MS);
|
|
274
|
+
this.#renderedAmount = totalSeconds * SECOND_MS;
|
|
175
275
|
const days = Math.floor(totalSeconds / 86400);
|
|
176
276
|
const hours = Math.floor(totalSeconds % 86400 / 3600);
|
|
177
277
|
const minutes = Math.floor(totalSeconds % 3600 / 60);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/safe_timeout.ts","../../src/controllers/countdown_controller.ts"],"names":[],"mappings":";;;;;AAwBA,IAAe,gBAAf,MAA6B;AAAA;AAAA,EAER,GAAA,uBAAU,GAAA,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAczC,MAAM,EAAA,EAAkB;AACtB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,EAAG;AACvB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAA,GAAiB;AACf,IAAA,KAAA,MAAW,EAAA,IAAM,KAAK,GAAA,EAAK;AACzB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AACA,IAAA,IAAA,CAAK,IAAI,KAAA,EAAM;AAAA,EACjB;AAAA;AAAA,EAGA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,GAAA,CAAI,IAAA;AAAA,EAClB;AACF,CAAA;AA8DO,IAAM,YAAA,GAAN,cAA2B,aAAA,CAAc;AAAA;AAAA,EAE9C,GAAA,CAAI,UAAsB,KAAA,EAAuB;AAC/C,IAAA,MAAM,EAAA,GAAK,IAAA,CAAK,QAAA,CAAS,QAAA,EAAU,KAAK,CAAA;AACxC,IAAA,IAAA,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A,CAAa,YAAY,CAAA,IAAK,QAAA;AAAA,EACpD;AACF","file":"countdown_controller.js","sourcesContent":["/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { SafeInterval } from \"../utils/safe_timeout\";\n\n/**\n * Headless countdown/timer behavior built on the live-region `role=\"timer\"`\n * practice (no dedicated APG pattern).\n *\n * Markup contract (identifier: `stimeo--countdown`):\n * <div data-controller=\"stimeo--countdown\" role=\"timer\" aria-live=\"off\"\n * data-stimeo--countdown-deadline-value=\"2026-12-31T23:59:59+09:00\"\n * data-action=\"countdown:pause->stimeo--countdown#pause\n * countdown:resume->stimeo--countdown#resume\">\n * <span data-stimeo--countdown-target=\"days\">0</span>\n * <span data-stimeo--countdown-target=\"hours\">00</span>\n * <span data-stimeo--countdown-target=\"minutes\">00</span>\n * <span data-stimeo--countdown-target=\"seconds\">00</span>\n * </div>\n *\n * Computes the time remaining to `deadline` (or elapsed since it, in\n * `direction=\"up\"`), formats it into the day/hour/minute/second slots, and ticks\n * on `interval`. `aria-live=\"off\"` is recommended so the timer is not announced\n * every second; only the milestone (completion) is surfaced — via the optional\n * `status` live region when a `completeLabel` is provided, or the `complete`\n * event for the consumer to handle.\n *\n * @remarks\n * Behavior only — slot text is updated, not styled. Pause/resume shifts an\n * internal time anchor so the displayed amount is preserved across a pause. The\n * interval is owned by {@link SafeInterval} and torn down on `disconnect()`\n * (Turbo navigation included).\n */\nexport class CountdownController extends Controller<HTMLElement> {\n static override targets = [\"days\", \"hours\", \"minutes\", \"seconds\", \"status\"];\n static override values = {\n deadline: { type: String, default: \"\" },\n interval: { type: Number, default: 1000 },\n direction: { type: String, default: \"down\" },\n autostart: { type: Boolean, default: true },\n completeLabel: { type: String, default: \"\" },\n };\n static actions = [\"pause\", \"reset\", \"resume\", \"start\"] as const;\n static events = [\"complete\", \"tick\"] as const;\n\n declare readonly daysTarget: HTMLElement;\n declare readonly hoursTarget: HTMLElement;\n declare readonly minutesTarget: HTMLElement;\n declare readonly secondsTarget: HTMLElement;\n declare readonly statusTarget: HTMLElement;\n declare readonly hasDaysTarget: boolean;\n declare readonly hasHoursTarget: boolean;\n declare readonly hasMinutesTarget: boolean;\n declare readonly hasSecondsTarget: boolean;\n declare readonly hasStatusTarget: boolean;\n\n declare deadlineValue: string;\n declare intervalValue: number;\n declare directionValue: string;\n declare autostartValue: boolean;\n declare completeLabelValue: string;\n\n readonly #intervals = new SafeInterval();\n #intervalId: number | null = null;\n\n /** Epoch-ms anchor: the deadline (down) or the count-up origin (up). */\n #reference = 0;\n /** Amount (ms) captured at pause, so resume can restore the same display. */\n #pausedAmount = 0;\n\n override connect(): void {\n this.#initReference();\n this.#render(this.#currentAmount());\n if (this.autostartValue && this.#isValidDeadline) {\n this.start();\n } else {\n this.element.setAttribute(\"data-state\", \"paused\");\n }\n }\n\n override disconnect(): void {\n this.#intervals.clearAll();\n this.#intervalId = null;\n }\n\n /** Starts (or restarts after pause) ticking toward the deadline. */\n start(): void {\n if (this.#state === \"running\" || !this.#isValidDeadline) return;\n if (this.#isDown && this.#currentAmount() <= 0) {\n this.#complete();\n return;\n }\n this.#runInterval();\n }\n\n /** Pauses ticking, preserving the currently displayed amount. */\n pause(): void {\n if (this.#state !== \"running\") return;\n this.#pausedAmount = this.#currentAmount();\n this.#teardownInterval();\n this.element.setAttribute(\"data-state\", \"paused\");\n }\n\n /** Resumes from a pause, continuing from the preserved amount. */\n resume(): void {\n if (this.#state !== \"paused\" || !this.#isValidDeadline) return;\n const now = Date.now();\n this.#reference = this.#isDown ? now + this.#pausedAmount : now - this.#pausedAmount;\n this.start();\n }\n\n /**\n * Re-syncs to the deadline and clears any pause offset, **preserving the current\n * run state**: a running timer keeps counting down from the reset amount, while a\n * paused (or completed) one resets the displayed amount but stays paused until the\n * user resumes — it never silently restarts. The run state is read from the DOM,\n * not re-derived from the declarative `autostart` Value (which only governs the\n * initial state on connect); re-deriving it would override a user's pause —\n * the DOM, not a re-run of declarative config, is the source of truth.\n */\n reset(): void {\n const wasRunning = this.#state === \"running\";\n this.#teardownInterval();\n this.#initReference();\n const amount = this.#currentAmount();\n this.#render(amount);\n // A prior complete() may have written a completion message into the status live\n // region; clear it so a reset timer does not keep showing (and announcing to a\n // screen reader) the stale \"finished\" text.\n if (this.hasStatusTarget) this.statusTarget.textContent = \"\";\n // teardownInterval() leaves data-state untouched; drop any lingering \"running\" to a\n // resting \"paused\" so start() (a no-op while \"running\") can re-arm when we resume.\n this.element.setAttribute(\"data-state\", \"paused\");\n if (wasRunning && this.#isValidDeadline) {\n // Was counting down: re-arm and keep running from the reset amount.\n this.#pausedAmount = 0;\n this.start();\n } else {\n // Was paused/complete: hold at the reset amount and wait for the user to resume.\n // Remember the amount so resume() restores it instead of snapping the anchor to 0.\n this.#pausedAmount = amount;\n }\n }\n\n /** Schedules the repeating tick and marks the timer running. */\n #runInterval(): void {\n this.element.setAttribute(\"data-state\", \"running\");\n this.#intervalId = this.#intervals.set(() => this.#tick(), this.intervalValue);\n }\n\n /** Cancels the repeating tick, if any. */\n #teardownInterval(): void {\n if (this.#intervalId !== null) {\n this.#intervals.clear(this.#intervalId);\n this.#intervalId = null;\n }\n }\n\n /** Recomputes, renders, emits `tick`, and completes when a countdown hits 0. */\n #tick(): void {\n const amount = this.#currentAmount();\n this.#render(amount);\n // `remaining` is the displayed amount (time left when counting down, elapsed\n // when counting up); `direction` lets consumers disambiguate the two.\n this.dispatch(\"tick\", {\n detail: { remaining: amount, direction: this.#isDown ? \"down\" : \"up\" },\n });\n if (this.#isDown && this.#reference - Date.now() <= 0) {\n this.#complete();\n }\n }\n\n /** Stops at zero, marks completion, announces it, and emits `complete`. */\n #complete(): void {\n this.#teardownInterval();\n this.#render(0);\n this.element.setAttribute(\"data-state\", \"complete\");\n if (this.hasStatusTarget && this.completeLabelValue.length > 0) {\n this.statusTarget.textContent = this.completeLabelValue;\n }\n this.dispatch(\"complete\", { detail: {} });\n }\n\n /** Sets the time anchor from the `deadline` value. */\n #initReference(): void {\n this.#reference = Date.parse(this.deadlineValue);\n }\n\n /** Remaining (down) or elapsed (up) ms, never negative. */\n #currentAmount(): number {\n if (!this.#isValidDeadline) return 0;\n const now = Date.now();\n const raw = this.#isDown ? this.#reference - now : now - this.#reference;\n return Math.max(0, raw);\n }\n\n /** Writes the amount into the day/hour/minute/second slots. */\n #render(amount: number): void {\n const totalSeconds = Math.floor(amount / 1000);\n const days = Math.floor(totalSeconds / 86400);\n const hours = Math.floor((totalSeconds % 86400) / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n\n if (this.hasDaysTarget) this.daysTarget.textContent = String(days);\n if (this.hasHoursTarget) this.hoursTarget.textContent = this.#pad(hours);\n if (this.hasMinutesTarget) this.minutesTarget.textContent = this.#pad(minutes);\n if (this.hasSecondsTarget) this.secondsTarget.textContent = this.#pad(seconds);\n }\n\n /** Zero-pads a unit to two digits. */\n #pad(unit: number): string {\n return String(unit).padStart(2, \"0\");\n }\n\n get #isDown(): boolean {\n return this.directionValue !== \"up\";\n }\n\n get #isValidDeadline(): boolean {\n return !Number.isNaN(this.#reference);\n }\n\n /** Current lifecycle phase as reflected on `data-state`. */\n get #state(): string {\n return this.element.getAttribute(\"data-state\") ?? \"paused\";\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/safe_timeout.ts","../../src/controllers/countdown_controller.ts"],"names":[],"mappings":";;;;;AAoBO,SAAS,QAAA,CAAS,OAAA,EAAiB,OAAA,GAAmC,EAAC,EAAS;AACrF,EAAA,MAAM,IAAA,GAAO,QAAQ,IAAA,EAAK;AAC1B,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACvB,EAAA,MAAA,CAAO,aAAA;AAAA,IACL,IAAI,YAAY,4BAAA,EAA8B;AAAA,MAC5C,QAAQ,EAAE,OAAA,EAAS,MAAM,SAAA,EAAW,OAAA,CAAQ,cAAc,IAAA;AAAK,KAChE;AAAA,GACH;AACF;AAUO,SAAS,YAAA,CAAa,UAAkB,MAAA,EAAiD;AAC9F,EAAA,OAAO,QAAA,CAAS,OAAA,CAAQ,6BAAA,EAA+B,CAAC,OAAO,IAAA,KAAiB;AAC9E,IAAA,MAAM,WAAA,GAAc,OAAO,IAAI,CAAA;AAC/B,IAAA,OAAO,WAAA,KAAgB,MAAA,GAAY,KAAA,GAAQ,MAAA,CAAO,WAAW,CAAA;AAAA,EAC/D,CAAC,CAAA;AACH;;;ACQO,IAAM,qBAAN,MAAyB;AAAA,EACrB,IAAA;AAAA,EACT,OAAA,GAAU,KAAA;AAAA,EACV,OAAA,GAAU,KAAA;AAAA,EACV,WAAA,GAAc,CAAA;AAAA;AAAA,EAGd,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AAkB,IAAA,CAAK,cAAc,WAAA,GAAc,IAAA,CAAK,KAAK,OAAO,CAAA;AAC7E,IAAA,IAAI,KAAK,gBAAA,EAAkB,IAAA,CAAK,cAAc,WAAA,GAAc,IAAA,CAAK,KAAK,OAAO,CAAA;AAAA,EAC/E;AAAA;AAAA,EAGA,KAAK,IAAA,EAAsB;AACzB,IAAA,OAAO,MAAA,CAAO,IAAI,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAA;AAAA,EACrC;AAAA,EAEA,IAAI,OAAA,GAAmB;AACrB,IAAA,OAAO,KAAK,cAAA,KAAmB,IAAA;AAAA,EACjC;AAAA,EAEA,IAAI,gBAAA,GAA4B;AAC9B,IAAA,OAAO,CAAC,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,UAAU,CAAA;AAAA,EACtC;AAAA;AAAA,EAGA,IAAI,MAAA,GAAiB;AACnB,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAY,CAAA,IAAK,QAAA;AAAA,EACpD;AACF","file":"countdown_controller.js","sourcesContent":["/**\n * Sends one message to the page's shared `stimeo--announcer`.\n *\n * A component that has to reach assistive tech does not carry a live region of its\n * own: a region only announces what changes *after* assistive tech already knows\n * about it, which a region that appears (or is un-hidden) with its message cannot\n * satisfy. The one region that can is the announcer sitting in the page from the\n * start, so state changes are handed to it as an event and it does the reading.\n *\n * The event goes to `window` because the announcer is usually a sibling high in the\n * document rather than an ancestor of the component dispatching it.\n *\n * Wording comes from the consumer — the library ships no English strings — so an\n * empty message is silently dropped and nothing is announced.\n *\n * @example\n * ```ts\n * announce(this.announceTextValue, { assertive: false });\n * ```\n */\nexport function announce(message: string, options: { assertive?: boolean } = {}): void {\n const text = message.trim();\n if (text.length === 0) return;\n window.dispatchEvent(\n new CustomEvent(\"stimeo--announcer:announce\", {\n detail: { message: text, assertive: options.assertive === true },\n }),\n );\n}\n\n/**\n * Fills `{name}` placeholders in an announcement template from `values`.\n *\n * The same substitution the value-text templates use, so a consumer writes\n * `\"{percent}% complete\"` in one attribute and gets the same rules everywhere. A\n * placeholder with no matching entry is left as authored rather than blanked, which\n * keeps a typo visible instead of silently swallowing the word.\n */\nexport function fillTemplate(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, name: string) => {\n const replacement = values[name];\n return replacement === undefined ? match : String(replacement);\n });\n}\n","/**\n * Collapses many target callbacks from one DOM mutation into a single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element, so\n * replacing a list of N options delivers N callbacks — but the useful unit of\n * work is \"reconcile against the DOM that resulted\", once, after the batch has\n * settled. Every controller that owns a reconcilable target set needs the same\n * 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 the *initial* target callbacks\n * ahead of `connect()`. Reconciling there would compute a fallback 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 { announce, fillTemplate } from \"../utils/announce\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\nimport { SafeInterval } from \"../utils/safe_timeout\";\n\n/** Display granularity: the slots render whole seconds, so amounts snap to these. */\nconst SECOND_MS = 1000;\n\n/**\n * Headless countdown/timer behavior built on the live-region `role=\"timer\"`\n * practice (no dedicated APG pattern).\n *\n * Markup contract (identifier: `stimeo--countdown`):\n * <div data-controller=\"stimeo--countdown\" role=\"timer\" aria-live=\"off\"\n * data-stimeo--countdown-deadline-value=\"2026-12-31T23:59:59+09:00\"\n * data-action=\"countdown:pause->stimeo--countdown#pause\n * countdown:resume->stimeo--countdown#resume\">\n * <span data-stimeo--countdown-target=\"days\">0</span>\n * <span data-stimeo--countdown-target=\"hours\">00</span>\n * <span data-stimeo--countdown-target=\"minutes\">00</span>\n * <span data-stimeo--countdown-target=\"seconds\">00</span>\n * </div>\n *\n * Computes the time remaining to `deadline` (or elapsed since it, in\n * `direction=\"up\"`), formats it into the day/hour/minute/second slots, and ticks\n * on `interval`. `aria-live=\"off\"` is recommended so the timer is not announced\n * every second; only the milestone (completion) is surfaced — via the optional\n * `status` live region when a `completeLabel` is provided, or the `complete`\n * event for the consumer to handle.\n *\n * @remarks\n * Behavior only — slot text is updated, not styled. Pause/resume shifts an\n * internal time anchor so the displayed amount is preserved across a pause, down\n * to the second actually on screen: resuming continues from that reading rather\n * than from the fraction behind it, so the first tick after a resume steps by one\n * unit like every other. The run state lives in `data-state` and the markup is its\n * source of truth — `autostart` only decides the state of a timer whose markup does\n * not carry one. The interval is owned by {@link SafeInterval} and torn down on\n * `disconnect()` (Turbo navigation included); nothing else needs carrying across,\n * because every reading is re-derived from `deadline` and the wall clock.\n */\nexport class CountdownController extends Controller<HTMLElement> {\n static override targets = [\"days\", \"hours\", \"minutes\", \"seconds\", \"status\"];\n static override values = {\n deadline: { type: String, default: \"\" },\n interval: { type: Number, default: 1000 },\n direction: { type: String, default: \"down\" },\n autostart: { type: Boolean, default: true },\n completeLabel: { type: String, default: \"\" },\n announceText: { type: String, default: \"\" },\n };\n static actions = [\"pause\", \"reset\", \"resume\", \"start\"] as const;\n static events = [\"complete\", \"tick\"] as const;\n\n declare readonly daysTarget: HTMLElement;\n declare readonly hoursTarget: HTMLElement;\n declare readonly minutesTarget: HTMLElement;\n declare readonly secondsTarget: HTMLElement;\n declare readonly statusTarget: HTMLElement;\n declare readonly hasDaysTarget: boolean;\n declare readonly hasHoursTarget: boolean;\n declare readonly hasMinutesTarget: boolean;\n declare readonly hasSecondsTarget: boolean;\n declare readonly hasStatusTarget: boolean;\n\n declare deadlineValue: string;\n declare intervalValue: number;\n declare directionValue: string;\n declare autostartValue: boolean;\n declare completeLabelValue: string;\n declare announceTextValue: string;\n\n readonly #intervals = new SafeInterval();\n #intervalId: number | null = null;\n /** Collapses a morph that swaps several render inputs at once into one re-derive. */\n readonly #resync = new MicrotaskCoalescer(() => this.#resyncToValues());\n\n /** Epoch-ms anchor: the deadline (down) or the count-up origin (up). */\n #reference = 0;\n /** Amount (ms) captured at pause, so resume can restore the same display. */\n #pausedAmount = 0;\n /**\n * The amount the slots are currently showing, floored to the second they render.\n * It lags {@link currentAmount} by up to one tick, and it — not the live reading —\n * is what a pause has to preserve: storing the fraction behind the display instead\n * makes the first tick after a resume step by two units.\n */\n #renderedAmount = 0;\n\n override connect(): void {\n this.#resync.activate();\n this.#initReference();\n const amount = this.#currentAmount();\n this.#render(amount);\n // Remember what is on screen so resume() continues from it instead of snapping\n // the anchor to now (which would settle a countdown at once).\n this.#pausedAmount = this.#renderedAmount;\n\n const authored = this.element.getAttribute(\"data-state\");\n if (authored === null) {\n // Nothing to honor: this is the declarative first render, which is the only\n // thing `autostart` governs.\n if (this.autostartValue && this.#isValidDeadline) {\n this.start();\n return;\n }\n this.element.setAttribute(\"data-state\", \"paused\");\n return;\n }\n if (authored === \"complete\" && this.#isDown && amount <= 0) {\n // Still settled, so the milestone stands. Dropping it to the resting state\n // would let a later resume() cross zero a second time and announce the same\n // completion again; only a deadline moved forward re-arms it.\n return;\n }\n // A pause the user made survives the round trip, but nothing carries a live timer\n // across it — a restored \"running\" has to be re-armed here or it renders once and\n // freezes, because start() is a no-op while the attribute still says \"running\".\n const wasRunning = authored === \"running\";\n this.element.setAttribute(\"data-state\", \"paused\");\n if (wasRunning) this.start();\n }\n\n override disconnect(): void {\n this.#resync.cancel();\n this.#intervals.clearAll();\n this.#intervalId = null;\n }\n\n /** Re-derives the display when a morph swaps the deadline in place. */\n deadlineValueChanged(): void {\n this.#resync.schedule();\n }\n\n /** Re-derives the display when a morph flips the counting direction in place. */\n directionValueChanged(): void {\n this.#resync.schedule();\n }\n\n /**\n * Points the anchor at the current `deadline` / `direction` and repaints.\n *\n * Render only: it starts no interval and emits no event, so a morph cannot make a\n * paused timer run or replay a milestone. A running one needs no restart either —\n * every tick reads the anchor, so moving it is enough. While paused the stored\n * amount follows the new reading, or resume would continue from the old deadline.\n */\n #resyncToValues(): void {\n this.#initReference();\n this.#render(this.#currentAmount());\n if (this.#state !== \"running\") this.#pausedAmount = this.#renderedAmount;\n }\n\n /** Starts (or restarts after pause) ticking toward the deadline. */\n start(): void {\n if (this.#state === \"running\" || !this.#isValidDeadline) return;\n if (this.#isDown && this.#currentAmount() <= 0) {\n // Already settled — a restored snapshot keeps data-state=\"complete\". The\n // milestone was announced in the visit that reached zero, so completing again\n // here would re-emit `complete` on every reconnect.\n if (this.#state !== \"complete\") this.#complete();\n return;\n }\n this.#runInterval();\n }\n\n /** Pauses ticking, preserving the currently displayed amount. */\n pause(): void {\n if (this.#state !== \"running\") return;\n this.#pausedAmount = this.#renderedAmount;\n this.#teardownInterval();\n this.element.setAttribute(\"data-state\", \"paused\");\n }\n\n /** Resumes from a pause, continuing from the preserved amount. */\n resume(): void {\n if (this.#state !== \"paused\" || !this.#isValidDeadline) return;\n const now = Date.now();\n this.#reference = this.#isDown ? now + this.#pausedAmount : now - this.#pausedAmount;\n this.start();\n }\n\n /**\n * Re-syncs to the deadline and clears any pause offset, **preserving the current\n * run state**: a running timer keeps counting down from the reset amount, while a\n * paused (or completed) one resets the displayed amount but stays paused until the\n * user resumes — it never silently restarts. The run state is read from the DOM,\n * not re-derived from the declarative `autostart` Value (which governs only markup\n * that states no run state at all); re-deriving it would override a user's pause —\n * the DOM, not a re-run of declarative config, is the source of truth.\n */\n reset(): void {\n const wasRunning = this.#state === \"running\";\n this.#teardownInterval();\n this.#initReference();\n const amount = this.#currentAmount();\n this.#render(amount);\n // A prior complete() may have written a completion message into the status live\n // region; clear it so a reset timer does not keep showing (and announcing to a\n // screen reader) the stale \"finished\" text. Only that message is ours to take\n // back — `complete()` declines to write when `completeLabel` is empty, so\n // anything else in there belongs to the consumer.\n if (this.hasStatusTarget && this.statusTarget.textContent === this.completeLabelValue) {\n this.statusTarget.textContent = \"\";\n }\n // teardownInterval() leaves data-state untouched; drop any lingering \"running\" to a\n // resting \"paused\" so start() (a no-op while \"running\") can re-arm when we resume.\n this.element.setAttribute(\"data-state\", \"paused\");\n if (wasRunning && this.#isValidDeadline) {\n // Was counting down: re-arm and keep running from the reset amount.\n this.#pausedAmount = 0;\n this.start();\n } else {\n // Was paused/complete: hold at the reset amount and wait for the user to resume.\n // Remember what is on screen so resume() restores it instead of snapping the\n // anchor to 0.\n this.#pausedAmount = this.#renderedAmount;\n }\n }\n\n /** Schedules the repeating tick and marks the timer running. */\n #runInterval(): void {\n this.element.setAttribute(\"data-state\", \"running\");\n this.#intervalId = this.#intervals.set(() => this.#tick(), this.intervalValue);\n }\n\n /** Cancels the repeating tick, if any. */\n #teardownInterval(): void {\n if (this.#intervalId !== null) {\n this.#intervals.clear(this.#intervalId);\n this.#intervalId = null;\n }\n }\n\n /** Recomputes, renders, emits `tick`, and completes when a countdown hits 0. */\n #tick(): void {\n const amount = this.#currentAmount();\n this.#render(amount);\n // `remaining` is the displayed amount (time left when counting down, elapsed\n // when counting up); `direction` lets consumers disambiguate the two.\n this.dispatch(\"tick\", {\n detail: { remaining: amount, direction: this.#isDown ? \"down\" : \"up\" },\n });\n if (this.#isDown && this.#reference - Date.now() <= 0) {\n this.#complete();\n }\n }\n\n /** Stops at zero, marks completion, announces it, and emits `complete`. */\n #complete(): void {\n this.#teardownInterval();\n this.#render(0);\n this.element.setAttribute(\"data-state\", \"complete\");\n if (this.hasStatusTarget && this.completeLabelValue.length > 0) {\n this.statusTarget.textContent = this.completeLabelValue;\n }\n this.dispatch(\"complete\", { detail: {} });\n // Reaching zero is the transition; the ticking numbers in between are state\n // the consumer can see, and reading each one would be unusable.\n announce(fillTemplate(this.announceTextValue, {}));\n }\n\n /** Sets the time anchor from the `deadline` value. */\n #initReference(): void {\n this.#reference = Date.parse(this.deadlineValue);\n }\n\n /** Remaining (down) or elapsed (up) ms, never negative. */\n #currentAmount(): number {\n if (!this.#isValidDeadline) return 0;\n const now = Date.now();\n const raw = this.#isDown ? this.#reference - now : now - this.#reference;\n return Math.max(0, raw);\n }\n\n /** Writes the amount into the day/hour/minute/second slots. */\n #render(amount: number): void {\n const totalSeconds = Math.floor(amount / SECOND_MS);\n this.#renderedAmount = totalSeconds * SECOND_MS;\n const days = Math.floor(totalSeconds / 86400);\n const hours = Math.floor((totalSeconds % 86400) / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n\n if (this.hasDaysTarget) this.daysTarget.textContent = String(days);\n if (this.hasHoursTarget) this.hoursTarget.textContent = this.#pad(hours);\n if (this.hasMinutesTarget) this.minutesTarget.textContent = this.#pad(minutes);\n if (this.hasSecondsTarget) this.secondsTarget.textContent = this.#pad(seconds);\n }\n\n /** Zero-pads a unit to two digits. */\n #pad(unit: number): string {\n return String(unit).padStart(2, \"0\");\n }\n\n get #isDown(): boolean {\n return this.directionValue !== \"up\";\n }\n\n get #isValidDeadline(): boolean {\n return !Number.isNaN(this.#reference);\n }\n\n /** Current lifecycle phase as reflected on `data-state`. */\n get #state(): string {\n return this.element.getAttribute(\"data-state\") ?? \"paused\";\n }\n}\n"]}
|
|
@@ -67,10 +67,13 @@ declare class DateRangePickerController extends Controller<HTMLElement> {
|
|
|
67
67
|
readonly hasEndFieldTarget: boolean;
|
|
68
68
|
minValue: string;
|
|
69
69
|
maxValue: string;
|
|
70
|
-
/** Seeds the range from any pre-filled hidden fields and renders the grid. */
|
|
71
70
|
connect(): void;
|
|
72
71
|
/** Cancels any pending deferred focus so it never fires on a detached element. */
|
|
73
72
|
disconnect(): void;
|
|
73
|
+
/** Repaints when application code (or a Turbo morph) changes `min` at runtime. */
|
|
74
|
+
minValueChanged(): void;
|
|
75
|
+
/** Repaints when application code (or a Turbo morph) changes `max` at runtime. */
|
|
76
|
+
maxValueChanged(): void;
|
|
74
77
|
/** Navigates to the previous month. */
|
|
75
78
|
prev(event?: Event): void;
|
|
76
79
|
/** Navigates to the next month. */
|