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/safe_timeout.ts","../../src/controllers/spinner_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;AAmBO,IAAM,WAAA,GAAN,cAA0B,aAAA,CAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO7C,GAAA,CAAI,UAAsB,KAAA,EAAuB;AAC/C,IAAA,MAAM,EAAA,GAAK,IAAA,CAAK,QAAA,CAAS,MAAM;AAC7B,MAAA,IAAA,CAAK,GAAA,CAAI,OAAO,EAAE,CAAA;AAClB,MAAA,QAAA,EAAS;AAAA,IACX,GAAG,KAAK,CAAA;AACR,IAAA,IAAA,CAAK,GAAA,CAAI,IAAI,EAAE,CAAA;AACf,IAAA,OAAO,EAAA;AAAA,EACT;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AAClB,IAAA,IAAI,IAAA,CAAK,iBAAiB,IAAA,EAAM;AAC9B,MAAA,IAAA,CAAK,OAAA,CAAQ,KAAA,CAAM,IAAA,CAAK,YAAY,CAAA;AACpC,MAAA,IAAA,CAAK,YAAA,GAAe,IAAA;AAAA,IACtB;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,MAAA,GAAiB;AACnB,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAY,CAAA,IAAK,MAAA;AAAA,EACpD;AACF","file":"spinner_controller.js","sourcesContent":["/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/**\n * Headless loading-indicator behavior built on the live-region + `aria-busy`\n * practice (no dedicated APG pattern).\n *\n * Markup contract (identifier: `stimeo--spinner`):\n * <div data-controller=\"stimeo--spinner\"\n * data-stimeo--spinner-delay-value=\"150\"\n * data-stimeo--spinner-min-duration-value=\"500\"\n * data-action=\"loading:start->stimeo--spinner#start\n * loading:stop->stimeo--spinner#stop\">\n * <div role=\"status\" aria-live=\"polite\" hidden\n * data-stimeo--spinner-target=\"indicator\">\n * <span data-stimeo--spinner-target=\"message\">Loading…</span>\n * </div>\n * <div aria-busy=\"false\" data-stimeo--spinner-target=\"region\"></div>\n * </div>\n *\n * The indicator is a `role=\"status\"` live region carrying *text* (never an icon\n * alone) so screen readers announce loading; the controlled `region` mirrors the\n * busy state via `aria-busy`. Two timers tame flicker: `delay` suppresses the\n * spinner for fast operations, and `minDuration` keeps it visible long enough to\n * be perceived once shown.\n *\n * @remarks\n * Behavior only — the visual spinner is the consumer's, alongside the text and\n * `aria-hidden=\"true\"`. Both timers are owned by {@link SafeTimeout} and torn\n * down on `disconnect()` (Turbo navigation included).\n */\nexport class SpinnerController extends Controller<HTMLElement> {\n static override targets = [\"indicator\", \"region\", \"message\"];\n static override values = {\n delay: { type: Number, default: 0 },\n minDuration: { type: Number, default: 0 },\n };\n static actions = [\"start\", \"stop\"] as const;\n static events = [\"hide\", \"show\"] as const;\n\n declare readonly indicatorTarget: HTMLElement;\n declare readonly regionTarget: HTMLElement;\n declare readonly messageTarget: HTMLElement;\n declare readonly hasIndicatorTarget: boolean;\n declare readonly hasRegionTarget: boolean;\n declare readonly hasMessageTarget: boolean;\n\n declare delayValue: number;\n declare minDurationValue: number;\n\n readonly #timers = new SafeTimeout();\n\n /** Pending show-delay timer id, or `null` when no start is awaiting its delay. */\n #delayTimerId: number | null = null;\n /** Pending min-duration hide timer id, or `null` when none is scheduled. */\n #hideTimerId: number | null = null;\n /** Epoch ms when the spinner became visible; `minDuration` is measured from it. */\n #shownAt = 0;\n\n override connect(): void {\n if (!this.element.hasAttribute(\"data-state\")) {\n this.element.setAttribute(\"data-state\", \"idle\");\n }\n }\n\n override disconnect(): void {\n this.#timers.clearAll();\n this.#delayTimerId = null;\n this.#hideTimerId = null;\n }\n\n /** Begins loading. Honors `delay` before the spinner actually appears. */\n start(): void {\n if (this.#state === \"loading\") {\n // Already shown (possibly waiting out `minDuration` after a stop): a quick\n // stop→start within that window must keep the spinner visible. Restore the\n // busy state and cancel the pending hide instead of returning a no-op, which\n // would let the stale hide fire and flicker the spinner away mid-load.\n this.#setBusy(true);\n this.#cancelHide();\n return;\n }\n if (this.#state !== \"idle\") return;\n this.#setBusy(true);\n // A pending hide from a previous cycle is now stale.\n this.#cancelHide();\n if (this.delayValue > 0) {\n this.element.setAttribute(\"data-state\", \"pending\");\n this.#delayTimerId = this.#timers.set(() => {\n this.#delayTimerId = null;\n this.#show();\n }, this.delayValue);\n } else {\n this.#show();\n }\n }\n\n /** Ends loading. Honors `minDuration` so a shown spinner does not flicker. */\n stop(): void {\n const state = this.#state;\n if (state === \"pending\") {\n // The delay never elapsed — the spinner never appeared, so just cancel.\n this.#cancelDelay();\n this.#setBusy(false);\n this.element.setAttribute(\"data-state\", \"idle\");\n return;\n }\n if (state !== \"loading\") return;\n\n this.#setBusy(false);\n const remaining = this.minDurationValue - (Date.now() - this.#shownAt);\n if (remaining > 0) {\n this.#hideTimerId = this.#timers.set(() => {\n this.#hideTimerId = null;\n this.#hide();\n }, remaining);\n } else {\n this.#hide();\n }\n }\n\n /** Reveals the indicator, marks the moment shown, and announces via the live region. */\n #show(): void {\n this.#shownAt = Date.now();\n if (this.hasIndicatorTarget) this.indicatorTarget.hidden = false;\n this.element.setAttribute(\"data-state\", \"loading\");\n this.dispatch(\"show\", { detail: {} });\n }\n\n /** Hides the indicator and returns to the idle state. */\n #hide(): void {\n if (this.hasIndicatorTarget) this.indicatorTarget.hidden = true;\n this.element.setAttribute(\"data-state\", \"idle\");\n this.dispatch(\"hide\", { detail: {} });\n }\n\n /** Reflects busy state onto the controlled region (if present). */\n #setBusy(busy: boolean): void {\n if (this.hasRegionTarget) {\n this.regionTarget.setAttribute(\"aria-busy\", String(busy));\n }\n }\n\n #cancelDelay(): void {\n if (this.#delayTimerId !== null) {\n this.#timers.clear(this.#delayTimerId);\n this.#delayTimerId = null;\n }\n }\n\n #cancelHide(): void {\n if (this.#hideTimerId !== null) {\n this.#timers.clear(this.#hideTimerId);\n this.#hideTimerId = null;\n }\n }\n\n /** Current lifecycle phase as reflected on `data-state`. */\n get #state(): string {\n return this.element.getAttribute(\"data-state\") ?? \"idle\";\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/before_cache_reset.ts","../../src/utils/detach_gate.ts","../../src/utils/min_duration_floor.ts","../../src/utils/safe_timeout.ts","../../src/controllers/spinner_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;;;ACAO,IAAM,gBAAA,GAAN,MAAM,iBAAA,CAAiB;AAAA;AAAA,EAE5B,OAAgB,YAAA,mBAA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,EACpD;AACF","file":"spinner_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 * 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 * Shared \"in-page move vs real detach\" discriminator for `disconnect()`.\n *\n * A mid-session `disconnect()` whose element is still in the document is\n * ambiguous. It can be:\n *\n * - an **in-page move** — a consumer (sortable, a teleport) re-inserted the\n * element; Stimulus reconnects the SAME instance in the same mutation batch\n * and the controller's runtime state must survive;\n * - a **detach that keeps the element** — `data-controller` no longer lists the\n * identifier (a Turbo 8 morph), or the element moved outside the observed\n * root (a scoped `Application.start(root)`, a shadow root); no reconnect will\n * ever come and the controller must tear down or it leaks its sessions,\n * document listeners, and moved nodes.\n *\n * Neither available signal decides this alone. A synchronous `data-controller`\n * token check catches the morph case but misses an observed-root exit (the\n * token stays, the reconnect never comes). Deferring teardown one microtask and\n * letting `connect()` cancel it catches the root exit, but leans on Stimulus\n * reconnecting moved elements within the same mutation batch — internal\n * behavior, not a public contract. {@link DetachGate} composes both: the token\n * check is the synchronous fast path (no probe, no reliance on batching), the\n * microtask probe is the fallback for the genuinely ambiguous remainder.\n *\n * Policy stays with the consumer (the `SafeTimeout` / `FocusTrap` lineage —\n * this util owns the discrimination only):\n *\n * - **Probe** ({@link disconnected}) when the teardown must eventually happen —\n * live drag sessions, document listeners, teleported *content*. Call\n * {@link cancel} from `connect()` (a reconnect means in-page move) and from\n * the head of any direct teardown path (see below).\n * - **Keep** (bare {@link DetachGate.isDetached}) when undoing the ambiguous\n * case would fight the controller's own effect: a controller that moves its\n * OWN element (portal's no-`content` form) exits a scoped observed root as\n * its normal job — a probe-driven teardown would restore the element into\n * the root, reconnect, re-teleport, and disconnect again, forever. Such\n * controllers keep their state on an ambiguous disconnect and tear down only\n * on {@link DetachGate.isDetached}.\n *\n * Event convention for probe consumers: teardown into a dead (detached) tree is\n * silent — consumers restore from their own `connect()`; a detach that keeps the\n * tree alive must end an in-flight session with a `cancel` event, or composing\n * consumers strand their session bookkeeping.\n */\n\n/** The slice of a Stimulus controller the gate inspects. */\nexport interface DetachGateHost {\n readonly element: Element;\n readonly identifier: string;\n}\n\n/**\n * Per-controller-instance gate deciding whether a `disconnect()` is a real\n * detach. Hold one per controller (`#gate = new DetachGate()`) — Stimulus\n * reuses the instance across reconnects, so the pending probe state carries\n * over exactly as the protocol needs.\n *\n * @example\n * ```ts\n * #gate = new DetachGate();\n *\n * connect(): void {\n * this.#gate.cancel(); // a reconnect: the element moved in-page\n * // …\n * }\n *\n * disconnect(): void {\n * this.#gate.disconnected(this, () => this.#teardown());\n * }\n *\n * #teardown(): void {\n * this.#gate.cancel(); // disarm a still-queued probe (double-run guard)\n * // …\n * }\n * ```\n */\nexport class DetachGate {\n /** Set while a probe is queued, waiting for a reconnect to cancel it. */\n #pending = false;\n\n /**\n * True when the disconnect is definitely a real detach — the element left\n * the document, or `data-controller` no longer lists the identifier. False\n * means ambiguous (in-page move or observed-root exit), NOT \"alive\".\n */\n static isDetached(host: DetachGateHost): boolean {\n if (!host.element.isConnected) return true;\n const tokens = (host.element.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n return !tokens.includes(host.identifier);\n }\n\n /**\n * Call from `disconnect()`: runs `teardown` synchronously on a definite\n * detach (fast path), otherwise defers it one microtask — a reconnect\n * ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.\n * One microtask is the whole probe window: Stimulus reconnects a moved\n * element within the same mutation batch, before the checkpoint drains.\n */\n disconnected(host: DetachGateHost, teardown: () => void): void {\n if (DetachGate.isDetached(host)) {\n // Also disarms a probe a previous ambiguous disconnect left queued\n // (defer, element removed, disconnect again) — exactly one teardown.\n this.#pending = false;\n teardown();\n return;\n }\n this.#pending = true;\n queueMicrotask(() => {\n if (!this.#pending) return;\n this.#pending = false;\n teardown();\n });\n }\n\n /**\n * Disarms a pending probe. Call from `connect()` (the reconnect that proves\n * an in-page move) and from the head of any teardown path not routed through\n * {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can\n * never run the teardown a second time.\n */\n cancel(): void {\n this.#pending = false;\n }\n}\n","import type { SafeTimeout } from \"./safe_timeout\";\n\n/**\n * Holds a transient state visible for a minimum time before letting it end.\n *\n * A loading indicator that appears and disappears within a few frames reads as a\n * flicker rather than as feedback, so several controllers keep one up for a floor\n * of `minDuration` milliseconds measured from the moment it became visible. The\n * shape is always the same: note the moment, and when the end signal arrives\n * either run it now, because the floor has already passed, or hold it on a timer\n * for whatever is left.\n *\n * The floor **borrows** a {@link SafeTimeout} instead of owning one, so a\n * controller that also schedules other work (a show delay) keeps every timer in a\n * single registry and one `clearAll()` in its teardown still drops them all.\n * Cancelling after such a bulk clear is safe: the registry no-ops on an id it no\n * longer holds.\n *\n * Scope is the floor itself. **When an end signal is allowed to arrive at all\n * stays with the controller**, because the answers differ — one keeps the first\n * queued finish and ignores repeats, another lets the newest replace it — and\n * flattening that into a shared default would silently change what the consumers\n * already promise.\n *\n * @example\n * ```ts\n * readonly #timers = new SafeTimeout();\n * readonly #floor = new MinDurationFloor(this.#timers);\n *\n * #show() { this.#floor.begin(); … }\n * stop() { this.#floor.schedule(this.minDurationValue, () => this.#hide()); }\n * ```\n */\nexport class MinDurationFloor {\n readonly #timers: SafeTimeout;\n\n /** Pending finish timer id, or `null` when nothing is held back. */\n #timerId: number | null = null;\n\n /** Epoch ms the floor is measured from. */\n #since = 0;\n\n /** @param timers - the controller's registry; the floor schedules into it. */\n constructor(timers: SafeTimeout) {\n this.#timers = timers;\n }\n\n /** Starts the floor: call when the state being held becomes visible. */\n begin(): void {\n this.#since = Date.now();\n }\n\n /** True while a finish is held back waiting for the floor to elapse. */\n get pending(): boolean {\n return this.#timerId !== null;\n }\n\n /**\n * Runs `finish` once the floor has elapsed, immediately when it already has.\n *\n * A held-back finish is **replaced**, never stacked: only the most recently\n * queued id is cancellable, so a second timer would outlive every cancel and\n * end a state that has since restarted. Controllers that want the first signal\n * to win guard on {@link pending} before calling.\n */\n schedule(minDuration: number, finish: () => void): void {\n this.cancel();\n const remaining = minDuration - (Date.now() - this.#since);\n if (remaining > 0) {\n this.#timerId = this.#timers.set(() => {\n this.#timerId = null;\n finish();\n }, remaining);\n } else {\n finish();\n }\n }\n\n /** Drops a held-back finish. Safe when none is queued, or after a bulk clear. */\n cancel(): void {\n if (this.#timerId !== null) {\n this.#timers.clear(this.#timerId);\n this.#timerId = null;\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 { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { DetachGate } from \"../utils/detach_gate\";\nimport { MinDurationFloor } from \"../utils/min_duration_floor\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/**\n * Headless loading-indicator behavior built on the live-region + `aria-busy`\n * practice (no dedicated APG pattern).\n *\n * Markup contract (identifier: `stimeo--spinner`):\n * <div data-controller=\"stimeo--spinner\"\n * data-stimeo--spinner-delay-value=\"150\"\n * data-stimeo--spinner-min-duration-value=\"500\"\n * data-stimeo--spinner-timeout-value=\"0\"\n * data-action=\"loading:start->stimeo--spinner#start\n * loading:stop->stimeo--spinner#stop\">\n * <div role=\"status\" aria-live=\"polite\" hidden\n * data-stimeo--spinner-target=\"indicator\">\n * <span data-stimeo--spinner-target=\"message\">Loading…</span>\n * </div>\n * <div aria-busy=\"false\" data-stimeo--spinner-target=\"region\"></div>\n * </div>\n *\n * The indicator is a `role=\"status\"` live region carrying *text* (never an icon\n * alone) so screen readers announce loading; the controlled `region` mirrors the\n * busy state via `aria-busy`. Two timers tame flicker: `delay` suppresses the\n * spinner for fast operations, and `minDuration` keeps it visible long enough to\n * be perceived once shown. `timeout` is the opt-in safety net for the case the\n * consumer's `stop` never arrives.\n *\n * Events (all with an empty `detail`):\n * - `stimeo--spinner:show` — the indicator became visible, after `delay`.\n * - `stimeo--spinner:hide` — the indicator went away, after `minDuration`.\n * - `stimeo--spinner:timeout` — `timeout` elapsed with the load still running;\n * the controller then ends it exactly as `stop` would, so a `hide` follows.\n *\n * @remarks\n * Behavior only — the visual spinner is the consumer's, alongside the text and\n * `aria-hidden=\"true\"`. Both timers are owned by {@link SafeTimeout}, kept across\n * an in-page move and dropped on a real detach via {@link DetachGate}, while the\n * loading state a cached page would freeze is rewound by {@link BeforeCacheReset}.\n */\nexport class SpinnerController extends Controller<HTMLElement> {\n static override targets = [\"indicator\", \"region\", \"message\"];\n static override values = {\n announceText: { type: String, default: \"\" },\n announceReadyText: { type: String, default: \"\" },\n delay: { type: Number, default: 0 },\n minDuration: { type: Number, default: 0 },\n timeout: { type: Number, default: 0 },\n };\n static actions = [\"start\", \"stop\"] as const;\n static events = [\"hide\", \"show\", \"timeout\"] as const;\n\n declare readonly indicatorTarget: HTMLElement;\n declare readonly regionTarget: HTMLElement;\n declare readonly messageTarget: HTMLElement;\n declare readonly hasIndicatorTarget: boolean;\n declare readonly hasRegionTarget: boolean;\n declare readonly hasMessageTarget: boolean;\n\n declare delayValue: number;\n declare minDurationValue: number;\n declare timeoutValue: number;\n declare announceTextValue: string;\n declare announceReadyTextValue: string;\n\n readonly #timers = new SafeTimeout();\n readonly #floor = new MinDurationFloor(this.#timers);\n readonly #gate = new DetachGate();\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n\n /** Pending show-delay timer id, or `null` when no start is awaiting its delay. */\n #delayTimerId: number | null = null;\n /** Pending safety-net timer id, or `null` when `timeout` is off or not armed. */\n #timeoutTimerId: number | null = null;\n\n override connect(): void {\n this.#gate.cancel();\n this.#beforeCache.activate();\n if (this.#state === \"pending\" && this.#delayTimerId === null) {\n // `pending` lives exactly as long as its show-delay timer. Reading it back with\n // no timer of this instance behind it means the markup outlived the timer — a\n // restored snapshot, or an element re-attached too late to count as a move — so\n // nothing is left to advance it and `start()` would refuse every later load.\n // Fall back to idle, dropping the busy flag the interrupted `start()` set.\n this.#setBusy(false);\n this.element.setAttribute(\"data-state\", \"idle\");\n return;\n }\n if (!this.element.hasAttribute(\"data-state\")) {\n this.element.setAttribute(\"data-state\", \"idle\");\n }\n }\n\n /**\n * Re-applies the current phase to an indicator that arrived after `connect()`.\n *\n * A Turbo Stream can swap the indicator for a fresh node mid-load, and that node\n * carries the markup contract's `hidden`. Without this the spinner would vanish\n * while `data-state` still says `loading`, and nothing but the next cycle would\n * bring it back.\n */\n indicatorTargetConnected(target: HTMLElement): void {\n target.hidden = this.#state !== \"loading\";\n }\n\n override disconnect(): void {\n // Symmetric with `connect()` regardless of why the disconnect came: an in-page\n // move re-subscribes, and only the timers are held back for the reconnect.\n this.#beforeCache.deactivate();\n this.#gate.disconnected(this, () => this.#teardown());\n }\n\n /** Begins loading. Honors `delay` before the spinner actually appears. */\n start(): void {\n if (this.#state === \"loading\") {\n // Already shown (possibly waiting out `minDuration` after a stop): a quick\n // stop→start within that window must keep the spinner visible. Restore the\n // busy state and cancel the pending hide instead of returning a no-op, which\n // would let the stale hide fire and flicker the spinner away mid-load.\n this.#setBusy(true);\n this.#floor.cancel();\n this.#armTimeout();\n return;\n }\n if (this.#state !== \"idle\") return;\n this.#setBusy(true);\n // A hide held back from a previous cycle is now stale.\n this.#floor.cancel();\n this.#armTimeout();\n if (this.delayValue > 0) {\n this.element.setAttribute(\"data-state\", \"pending\");\n this.#delayTimerId = this.#timers.set(() => {\n this.#delayTimerId = null;\n this.#show();\n }, this.delayValue);\n } else {\n this.#show();\n }\n }\n\n /** Ends loading. Honors `minDuration` so a shown spinner does not flicker. */\n stop(): void {\n const state = this.#state;\n this.#cancelTimeout();\n if (state === \"pending\") {\n // The delay never elapsed — the spinner never appeared, so just cancel.\n this.#cancelDelay();\n this.#setBusy(false);\n this.element.setAttribute(\"data-state\", \"idle\");\n return;\n }\n if (state !== \"loading\") return;\n\n this.#setBusy(false);\n this.#floor.schedule(this.minDurationValue, () => this.#hide());\n }\n\n /** Reveals the indicator, marks the moment shown, and announces via the live region. */\n #show(): void {\n this.#floor.begin();\n // A visible spinner always means a busy region. Re-asserting it costs nothing on\n // the direct path and closes the one where a snapshot rewind cleared the flag\n // while the show-delay timer it deliberately spared was still armed.\n this.#setBusy(true);\n if (this.hasIndicatorTarget) this.indicatorTarget.hidden = false;\n this.element.setAttribute(\"data-state\", \"loading\");\n this.dispatch(\"show\", { detail: {} });\n // loading ↔ ready is the transition worth reading; the spinner itself is\n // visual and carries no words.\n announce(fillTemplate(this.announceTextValue, {}));\n }\n\n /** Hides the indicator and returns to the idle state. */\n #hide(): void {\n if (this.hasIndicatorTarget) this.indicatorTarget.hidden = true;\n this.element.setAttribute(\"data-state\", \"idle\");\n this.dispatch(\"hide\", { detail: {} });\n announce(fillTemplate(this.announceReadyTextValue, {}));\n }\n\n /**\n * Drops both timers on a real detach. The markup keeps whatever it last held: an\n * element on its way out of the document has no reader left, and one whose\n * `data-controller` dropped the identifier no longer resolves its own targets, so\n * the rollback could only ever be partial. The snapshot is rewound where it is\n * still whole, on `turbo:before-cache`.\n */\n #teardown(): void {\n this.#gate.cancel();\n this.#timers.clearAll();\n this.#delayTimerId = null;\n this.#timeoutTimerId = null;\n this.#floor.cancel();\n }\n\n /**\n * Returns the loading state to idle for the snapshot Turbo is about to take,\n * so a page reached with the Back button is not restored mid-load with a\n * spinner nothing can stop. State only: `data-state`, the indicator's `hidden`,\n * and `aria-busy`. No `hide` is dispatched — the load was never observed to\n * finish, and a snapshot rewind is not a lifecycle event the consumer can act\n * on. The live page keeps its timers, so a navigation that never completes\n * leaves the running cycle intact.\n */\n #rewindForCache(): void {\n this.#cancelTimeout();\n this.#setBusy(false);\n if (this.hasIndicatorTarget) this.indicatorTarget.hidden = true;\n this.element.setAttribute(\"data-state\", \"idle\");\n }\n\n /** Reflects busy state onto the controlled region (if present). */\n #setBusy(busy: boolean): void {\n if (this.hasRegionTarget) {\n this.regionTarget.setAttribute(\"aria-busy\", String(busy));\n }\n }\n\n /**\n * Arms the safety net so a `stop` that never arrives cannot strand the spinner.\n * Off by default: the consumer owns the async work, so only it knows whether a\n * ceiling makes sense. Re-arming on a restart measures from the newest start.\n */\n #armTimeout(): void {\n this.#cancelTimeout();\n if (this.timeoutValue <= 0) return;\n this.#timeoutTimerId = this.#timers.set(() => {\n this.#timeoutTimerId = null;\n this.dispatch(\"timeout\", { detail: {} });\n this.stop();\n }, this.timeoutValue);\n }\n\n #cancelTimeout(): void {\n if (this.#timeoutTimerId !== null) {\n this.#timers.clear(this.#timeoutTimerId);\n this.#timeoutTimerId = null;\n }\n }\n\n #cancelDelay(): void {\n if (this.#delayTimerId !== null) {\n this.#timers.clear(this.#delayTimerId);\n this.#delayTimerId = null;\n }\n }\n\n /** Current lifecycle phase as reflected on `data-state`. */\n get #state(): string {\n return this.element.getAttribute(\"data-state\") ?? \"idle\";\n }\n}\n"]}
|
|
@@ -25,6 +25,7 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
25
25
|
*
|
|
26
26
|
* Behavior provided:
|
|
27
27
|
* - Reflects `current` onto each step's `data-state` and `aria-current`.
|
|
28
|
+
* - Re-derives every step when the step set changes at runtime.
|
|
28
29
|
* - `setCurrent` (bound to an event whose `detail.current` is the 0-based index)
|
|
29
30
|
* updates the current step and dispatches `stimeo--step-indicator:change`.
|
|
30
31
|
*/
|
|
@@ -43,9 +44,19 @@ declare class StepIndicatorController extends Controller<HTMLElement> {
|
|
|
43
44
|
currentValue: number;
|
|
44
45
|
/** Renders the initial state from the `current` value. */
|
|
45
46
|
connect(): void;
|
|
47
|
+
/** Closes the window in which a queued repaint may still run. */
|
|
48
|
+
disconnect(): void;
|
|
49
|
+
/** Syncs a step appended or replaced at runtime (the consumer owns the list). */
|
|
50
|
+
stepTargetConnected(): void;
|
|
51
|
+
/** Re-derives the remaining steps when one is removed at runtime. */
|
|
52
|
+
stepTargetDisconnected(): void;
|
|
53
|
+
/** Repaints when application code (or a Turbo morph) changes `current` at runtime. */
|
|
54
|
+
currentValueChanged(): void;
|
|
46
55
|
/**
|
|
47
56
|
* Updates the current step from an external event (`detail.current`, 0-based)
|
|
48
|
-
* and dispatches `change`. Out-of-range indices are clamped to the step set
|
|
57
|
+
* and dispatches `change`. Out-of-range indices are clamped to the step set,
|
|
58
|
+
* and both sides of the no-op test are clamped, so moving onto the step an
|
|
59
|
+
* out-of-range `current` already renders is not reported as a change.
|
|
49
60
|
*/
|
|
50
61
|
setCurrent(event: CustomEvent<{
|
|
51
62
|
current?: number;
|
|
@@ -1,5 +1,40 @@
|
|
|
1
1
|
import { Controller } from '@hotwired/stimulus';
|
|
2
2
|
|
|
3
|
+
// src/controllers/step_indicator_controller.ts
|
|
4
|
+
|
|
5
|
+
// src/utils/microtask_coalescer.ts
|
|
6
|
+
var MicrotaskCoalescer = class {
|
|
7
|
+
#run;
|
|
8
|
+
#queued = false;
|
|
9
|
+
#active = false;
|
|
10
|
+
#generation = 0;
|
|
11
|
+
/** @param run - the single reconciliation pass, invoked at most once per batch. */
|
|
12
|
+
constructor(run) {
|
|
13
|
+
this.#run = run;
|
|
14
|
+
}
|
|
15
|
+
/** Opens the window in which {@link schedule} is honoured; call from `connect()`. */
|
|
16
|
+
activate() {
|
|
17
|
+
this.#active = true;
|
|
18
|
+
}
|
|
19
|
+
/** Closes the window and drops any pending pass; call from `disconnect()`. */
|
|
20
|
+
cancel() {
|
|
21
|
+
this.#active = false;
|
|
22
|
+
this.#queued = false;
|
|
23
|
+
this.#generation += 1;
|
|
24
|
+
}
|
|
25
|
+
/** Requests one pass after the batch settles. Idempotent; inert outside the window. */
|
|
26
|
+
schedule() {
|
|
27
|
+
if (!this.#active || this.#queued) return;
|
|
28
|
+
this.#queued = true;
|
|
29
|
+
const generation = this.#generation;
|
|
30
|
+
queueMicrotask(() => {
|
|
31
|
+
if (generation !== this.#generation || !this.#queued || !this.#active) return;
|
|
32
|
+
this.#queued = false;
|
|
33
|
+
this.#run();
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
3
38
|
// src/controllers/step_indicator_controller.ts
|
|
4
39
|
var StepIndicatorController = class extends Controller {
|
|
5
40
|
static targets = ["step"];
|
|
@@ -8,26 +43,63 @@ var StepIndicatorController = class extends Controller {
|
|
|
8
43
|
};
|
|
9
44
|
static actions = ["setCurrent"];
|
|
10
45
|
static events = ["change"];
|
|
46
|
+
/**
|
|
47
|
+
* Whether the target callbacks may render. Stimulus reports the authored steps
|
|
48
|
+
* as connected before `connect()` and the remaining ones as disconnected after
|
|
49
|
+
* `disconnect()`, so this keeps a connect at one render pass, not one per step.
|
|
50
|
+
*/
|
|
51
|
+
/**
|
|
52
|
+
* Collapses a batch of step callbacks — and a morph that swaps `current` with
|
|
53
|
+
* them — into one repaint. Replacing a list of N steps delivers N callbacks, and
|
|
54
|
+
* each one would otherwise rewrite every step's state.
|
|
55
|
+
*/
|
|
56
|
+
#repaint = new MicrotaskCoalescer(() => this.#render());
|
|
11
57
|
/** Renders the initial state from the `current` value. */
|
|
12
58
|
connect() {
|
|
59
|
+
this.#repaint.activate();
|
|
13
60
|
this.#render();
|
|
14
61
|
}
|
|
62
|
+
/** Closes the window in which a queued repaint may still run. */
|
|
63
|
+
disconnect() {
|
|
64
|
+
this.#repaint.cancel();
|
|
65
|
+
}
|
|
66
|
+
/** Syncs a step appended or replaced at runtime (the consumer owns the list). */
|
|
67
|
+
stepTargetConnected() {
|
|
68
|
+
this.#repaint.schedule();
|
|
69
|
+
}
|
|
70
|
+
/** Re-derives the remaining steps when one is removed at runtime. */
|
|
71
|
+
stepTargetDisconnected() {
|
|
72
|
+
this.#repaint.schedule();
|
|
73
|
+
}
|
|
74
|
+
/** Repaints when application code (or a Turbo morph) changes `current` at runtime. */
|
|
75
|
+
currentValueChanged() {
|
|
76
|
+
this.#repaint.schedule();
|
|
77
|
+
}
|
|
15
78
|
/**
|
|
16
79
|
* Updates the current step from an external event (`detail.current`, 0-based)
|
|
17
|
-
* and dispatches `change`. Out-of-range indices are clamped to the step set
|
|
80
|
+
* and dispatches `change`. Out-of-range indices are clamped to the step set,
|
|
81
|
+
* and both sides of the no-op test are clamped, so moving onto the step an
|
|
82
|
+
* out-of-range `current` already renders is not reported as a change.
|
|
18
83
|
*/
|
|
19
84
|
setCurrent(event) {
|
|
20
85
|
const next = event.detail?.current;
|
|
21
86
|
if (typeof next !== "number" || !Number.isFinite(next)) return;
|
|
22
87
|
const clamped = this.#clamp(next);
|
|
23
|
-
|
|
88
|
+
const moved = clamped !== this.#clamp(this.currentValue);
|
|
24
89
|
this.currentValue = clamped;
|
|
90
|
+
if (!moved) return;
|
|
25
91
|
this.#render();
|
|
26
92
|
this.dispatch("change", {
|
|
27
93
|
detail: { current: clamped, total: this.stepTargets.length }
|
|
28
94
|
});
|
|
29
95
|
}
|
|
30
|
-
/**
|
|
96
|
+
/**
|
|
97
|
+
* Applies `data-state`, `aria-current`, and the progress ratio custom property.
|
|
98
|
+
*
|
|
99
|
+
* A pure function of the step set and `current`, so running it again writes the
|
|
100
|
+
* same values — which is what lets the action path paint synchronously (the event
|
|
101
|
+
* goes out after the DOM is updated) while a coalesced pass may still follow.
|
|
102
|
+
*/
|
|
31
103
|
#render() {
|
|
32
104
|
const total = this.stepTargets.length;
|
|
33
105
|
const current = this.#clamp(this.currentValue);
|
|
@@ -42,10 +114,15 @@ var StepIndicatorController = class extends Controller {
|
|
|
42
114
|
const ratio = total > 1 ? current / (total - 1) : 0;
|
|
43
115
|
this.element.style.setProperty("--stimeo-step-indicator-ratio", String(ratio));
|
|
44
116
|
}
|
|
45
|
-
/**
|
|
117
|
+
/**
|
|
118
|
+
* Constrains an index to `[0, total-1]` (or `0` when there are no steps). A
|
|
119
|
+
* non-finite index falls back to the first step: `current` is read from markup,
|
|
120
|
+
* so an unparsable attribute arrives as `NaN` and would otherwise propagate
|
|
121
|
+
* into every state hook.
|
|
122
|
+
*/
|
|
46
123
|
#clamp(index) {
|
|
47
124
|
const last = this.stepTargets.length - 1;
|
|
48
|
-
if (last < 0) return 0;
|
|
125
|
+
if (last < 0 || !Number.isFinite(index)) return 0;
|
|
49
126
|
return Math.min(last, Math.max(0, Math.trunc(index)));
|
|
50
127
|
}
|
|
51
128
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/controllers/step_indicator_controller.ts"],"names":[],"mappings":";;;AA8BO,IAAM,uBAAA,GAAN,cAAsC,UAAA,CAAwB;AAAA,EACnE,OAAgB,OAAA,GAAU,CAAC,MAAM,CAAA;AAAA,EACjC,OAAgB,MAAA,GAAS;AAAA,IACvB,OAAA,EAAS,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,CAAA;AAAE,GACtC;AAAA,EACA,OAAO,OAAA,GAAU,CAAC,YAAY,CAAA;AAAA,EAC9B,OAAO,MAAA,GAAS,CAAC,QAAQ,CAAA;AAAA;AAAA,EAMhB,OAAA,GAAgB;AACvB,IAAA,IAAA,CAAK,OAAA,EAAQ;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAW,KAAA,EAAgD;AAC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CAAC,CAAA;AAAA,EAC/E;AAAA;AAAA,EAGA,OAAO,KAAA,EAAuB;AAC5B,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,WAAA,CAAY,MAAA,GAAS,CAAA;AACvC,IAAA,IAAI,IAAA,GAAO,GAAG,OAAO,CAAA;AACrB,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,IAAA,EAAM,IAAA,CAAK,GAAA,CAAI,GAAG,IAAA,CAAK,KAAA,CAAM,KAAK,CAAC,CAAC,CAAA;AAAA,EACtD;AACF","file":"step_indicator_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/**\n * Headless, accessible **read-only** step-progress indicator.\n *\n * Markup contract (identifier: `stimeo--step-indicator`):\n * <ol data-controller=\"stimeo--step-indicator\" aria-label=\"Checkout progress\"\n * data-stimeo--step-indicator-current-value=\"1\"\n * data-action=\"step:set->stimeo--step-indicator#setCurrent\">\n * <li data-stimeo--step-indicator-target=\"step\">Cart</li>\n * <li data-stimeo--step-indicator-target=\"step\">Shipping</li>\n * <li data-stimeo--step-indicator-target=\"step\">Payment</li>\n * </ol>\n *\n * There is no dedicated APG widget; the current position is expressed with\n * `aria-current=\"step\"`. This indicator is **read only** — it never moves focus\n * and the steps are not operable. For an interactive wizard whose steps are\n * `<button>`s, use {@link StepperController | Stepper}.\n *\n * @remarks\n * Behavior only. Each step `<li>` gets a `data-state` (`complete`/`current`/\n * `upcoming`) derived from the current index; the consumer draws the circles,\n * lines, and numbers from those hooks. A `--stimeo-step-indicator-ratio`\n * (0–1) custom property on the root expresses overall progress for CSS.\n *\n * Behavior provided:\n * - Reflects `current` onto each step's `data-state` and `aria-current`.\n * - `setCurrent` (bound to an event whose `detail.current` is the 0-based index)\n * updates the current step and dispatches `stimeo--step-indicator:change`.\n */\nexport class StepIndicatorController extends Controller<HTMLElement> {\n static override targets = [\"step\"];\n static override values = {\n current: { type: Number, default: 0 },\n };\n static actions = [\"setCurrent\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly stepTargets: HTMLElement[];\n declare currentValue: number;\n\n /** Renders the initial state from the `current` value. */\n override connect(): void {\n this.#render();\n }\n\n /**\n * Updates the current step from an external event (`detail.current`, 0-based)\n * and dispatches `change`. Out-of-range indices are clamped to the step set.\n */\n setCurrent(event: CustomEvent<{ current?: number }>): void {\n const next = event.detail?.current;\n if (typeof next !== \"number\" || !Number.isFinite(next)) return;\n const clamped = this.#clamp(next);\n if (clamped === this.currentValue) return;\n this.currentValue = clamped;\n this.#render();\n this.dispatch(\"change\", {\n detail: { current: clamped, total: this.stepTargets.length },\n });\n }\n\n /** Applies `data-state`, `aria-current`, and the progress ratio custom property. */\n #render(): void {\n const total = this.stepTargets.length;\n const current = this.#clamp(this.currentValue);\n this.stepTargets.forEach((step, index) => {\n step.dataset.state =\n index < current ? \"complete\" : index === current ? \"current\" : \"upcoming\";\n if (index === current) {\n step.setAttribute(\"aria-current\", \"step\");\n } else {\n step.removeAttribute(\"aria-current\");\n }\n });\n const ratio = total > 1 ? current / (total - 1) : 0;\n this.element.style.setProperty(\"--stimeo-step-indicator-ratio\", String(ratio));\n }\n\n /** Constrains an index to `[0, total-1]` (or `0` when there are no steps). */\n #clamp(index: number): number {\n const last = this.stepTargets.length - 1;\n if (last < 0) return 0;\n return Math.min(last, Math.max(0, Math.trunc(index)));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/microtask_coalescer.ts","../../src/controllers/step_indicator_controller.ts"],"names":[],"mappings":";;;;;AAmDO,IAAM,qBAAN,MAAyB;AAAA,EACrB,IAAA;AAAA,EACT,OAAA,GAAU,KAAA;AAAA,EACV,OAAA,GAAU,KAAA;AAAA,EACV,WAAA,GAAc,CAAA;AAAA;AAAA,EAGd,YAAY,GAAA,EAAiB;AAC3B,IAAA,IAAA,CAAK,IAAA,GAAO,GAAA;AAAA,EACd;AAAA;AAAA,EAGA,QAAA,GAAiB;AACf,IAAA,IAAA,CAAK,OAAA,GAAU,IAAA;AAAA,EACjB;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,GACX,KAAA,GAAQ,UAAU,UAAA,GAAa,KAAA,KAAU,UAAU,SAAA,GAAY,UAAA;AACjE,MAAA,IAAI,UAAU,OAAA,EAAS;AACrB,QAAA,IAAA,CAAK,YAAA,CAAa,gBAAgB,MAAM,CAAA;AAAA,MAC1C,CAAA,MAAO;AACL,QAAA,IAAA,CAAK,gBAAgB,cAAc,CAAA;AAAA,MACrC;AAAA,IACF,CAAC,CAAA;AACD,IAAA,MAAM,KAAA,GAAQ,KAAA,GAAQ,CAAA,GAAI,OAAA,IAAW,QAAQ,CAAA,CAAA,GAAK,CAAA;AAClD,IAAA,IAAA,CAAK,QAAQ,KAAA,CAAM,WAAA,CAAY,+BAAA,EAAiC,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,EAC/E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,KAAA,EAAuB;AAC5B,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,WAAA,CAAY,MAAA,GAAS,CAAA;AACvC,IAAA,IAAI,OAAO,CAAA,IAAK,CAAC,OAAO,QAAA,CAAS,KAAK,GAAG,OAAO,CAAA;AAChD,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,IAAA,EAAM,IAAA,CAAK,GAAA,CAAI,GAAG,IAAA,CAAK,KAAA,CAAM,KAAK,CAAC,CAAC,CAAA;AAAA,EACtD;AACF","file":"step_indicator_controller.js","sourcesContent":["/**\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","import { Controller } from \"@hotwired/stimulus\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\n\n/**\n * Headless, accessible **read-only** step-progress indicator.\n *\n * Markup contract (identifier: `stimeo--step-indicator`):\n * <ol data-controller=\"stimeo--step-indicator\" aria-label=\"Checkout progress\"\n * data-stimeo--step-indicator-current-value=\"1\"\n * data-action=\"step:set->stimeo--step-indicator#setCurrent\">\n * <li data-stimeo--step-indicator-target=\"step\">Cart</li>\n * <li data-stimeo--step-indicator-target=\"step\">Shipping</li>\n * <li data-stimeo--step-indicator-target=\"step\">Payment</li>\n * </ol>\n *\n * There is no dedicated APG widget; the current position is expressed with\n * `aria-current=\"step\"`. This indicator is **read only** — it never moves focus\n * and the steps are not operable. For an interactive wizard whose steps are\n * `<button>`s, use {@link StepperController | Stepper}.\n *\n * @remarks\n * Behavior only. Each step `<li>` gets a `data-state` (`complete`/`current`/\n * `upcoming`) derived from the current index; the consumer draws the circles,\n * lines, and numbers from those hooks. A `--stimeo-step-indicator-ratio`\n * (0–1) custom property on the root expresses overall progress for CSS.\n *\n * Behavior provided:\n * - Reflects `current` onto each step's `data-state` and `aria-current`.\n * - Re-derives every step when the step set changes at runtime.\n * - `setCurrent` (bound to an event whose `detail.current` is the 0-based index)\n * updates the current step and dispatches `stimeo--step-indicator:change`.\n */\nexport class StepIndicatorController extends Controller<HTMLElement> {\n static override targets = [\"step\"];\n static override values = {\n current: { type: Number, default: 0 },\n };\n static actions = [\"setCurrent\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly stepTargets: HTMLElement[];\n declare currentValue: number;\n\n /**\n * Whether the target callbacks may render. Stimulus reports the authored steps\n * as connected before `connect()` and the remaining ones as disconnected after\n * `disconnect()`, so this keeps a connect at one render pass, not one per step.\n */\n /**\n * Collapses a batch of step callbacks — and a morph that swaps `current` with\n * them — into one repaint. Replacing a list of N steps delivers N callbacks, and\n * each one would otherwise rewrite every step's state.\n */\n readonly #repaint = new MicrotaskCoalescer(() => this.#render());\n\n /** Renders the initial state from the `current` value. */\n override connect(): void {\n this.#repaint.activate();\n this.#render();\n }\n\n /** Closes the window in which a queued repaint may still run. */\n override disconnect(): void {\n this.#repaint.cancel();\n }\n\n /** Syncs a step appended or replaced at runtime (the consumer owns the list). */\n stepTargetConnected(): void {\n this.#repaint.schedule();\n }\n\n /** Re-derives the remaining steps when one is removed at runtime. */\n stepTargetDisconnected(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `current` at runtime. */\n currentValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /**\n * Updates the current step from an external event (`detail.current`, 0-based)\n * and dispatches `change`. Out-of-range indices are clamped to the step set,\n * and both sides of the no-op test are clamped, so moving onto the step an\n * out-of-range `current` already renders is not reported as a change.\n */\n setCurrent(event: CustomEvent<{ current?: number }>): void {\n const next = event.detail?.current;\n if (typeof next !== \"number\" || !Number.isFinite(next)) return;\n const clamped = this.#clamp(next);\n const moved = clamped !== this.#clamp(this.currentValue);\n // Normalise even when the display does not move: an out-of-range `current` left\n // in the markup would otherwise be re-clamped against a later step set and land\n // somewhere the consumer never asked for. Writing it here is the consumer-driven\n // path, the only one that owns the Value.\n this.currentValue = clamped;\n if (!moved) return;\n this.#render();\n this.dispatch(\"change\", {\n detail: { current: clamped, total: this.stepTargets.length },\n });\n }\n\n /**\n * Applies `data-state`, `aria-current`, and the progress ratio custom property.\n *\n * A pure function of the step set and `current`, so running it again writes the\n * same values — which is what lets the action path paint synchronously (the event\n * goes out after the DOM is updated) while a coalesced pass may still follow.\n */\n #render(): void {\n const total = this.stepTargets.length;\n const current = this.#clamp(this.currentValue);\n this.stepTargets.forEach((step, index) => {\n step.dataset.state =\n index < current ? \"complete\" : index === current ? \"current\" : \"upcoming\";\n if (index === current) {\n step.setAttribute(\"aria-current\", \"step\");\n } else {\n step.removeAttribute(\"aria-current\");\n }\n });\n const ratio = total > 1 ? current / (total - 1) : 0;\n this.element.style.setProperty(\"--stimeo-step-indicator-ratio\", String(ratio));\n }\n\n /**\n * Constrains an index to `[0, total-1]` (or `0` when there are no steps). A\n * non-finite index falls back to the first step: `current` is read from markup,\n * so an unparsable attribute arrives as `NaN` and would otherwise propagate\n * into every state hook.\n */\n #clamp(index: number): number {\n const last = this.stepTargets.length - 1;\n if (last < 0 || !Number.isFinite(index)) return 0;\n return Math.min(last, Math.max(0, Math.trunc(index)));\n }\n}\n"]}
|
|
@@ -9,7 +9,8 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
9
9
|
*
|
|
10
10
|
* Markup contract (identifier: `stimeo--stick-to-bottom`):
|
|
11
11
|
* <div data-controller="stimeo--stick-to-bottom"
|
|
12
|
-
* data-stimeo--stick-to-bottom-threshold-value="80"
|
|
12
|
+
* data-stimeo--stick-to-bottom-threshold-value="80"
|
|
13
|
+
* data-stimeo--stick-to-bottom-pin-on-connect-value="true" style="overflow:auto">
|
|
13
14
|
* <ul data-stimeo--stick-to-bottom-target="content"><!-- Turbo Stream appends --></ul>
|
|
14
15
|
* </div>
|
|
15
16
|
*
|
|
@@ -19,6 +20,14 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
19
20
|
* Scrolling recomputes pinned and reflects `data-pinned`, emitting `pin` on change; the
|
|
20
21
|
* `scrollToBottom` action jumps back down (a "new messages" button).
|
|
21
22
|
*
|
|
23
|
+
* A container renders at `scrollTop` 0 — unpinned — so out of the box it flags the first
|
|
24
|
+
* append rather than following it. `pinOnConnect` opts into the other starting point:
|
|
25
|
+
* `connect()` jumps to the bottom and reads the state back from where it landed. It runs
|
|
26
|
+
* on every connect, so a container inserted or re-rendered later (a Turbo Stream, a panel
|
|
27
|
+
* built on open) starts at the bottom too — which a once-per-document page event cannot
|
|
28
|
+
* do. It is off by default, so a restored reading position (a Turbo cache restore, a user
|
|
29
|
+
* who had scrolled up) is never yanked to the bottom unless the consumer asks for it.
|
|
30
|
+
*
|
|
22
31
|
* @remarks
|
|
23
32
|
* The `MutationObserver` watches `childList` only (not `subtree`), so it follows
|
|
24
33
|
* direct appends to `content` (or the element). Appends made deeper inside a nested
|
|
@@ -44,6 +53,10 @@ declare class StickToBottomController extends Controller<HTMLElement> {
|
|
|
44
53
|
type: StringConstructor;
|
|
45
54
|
default: string;
|
|
46
55
|
};
|
|
56
|
+
pinOnConnect: {
|
|
57
|
+
type: BooleanConstructor;
|
|
58
|
+
default: boolean;
|
|
59
|
+
};
|
|
47
60
|
};
|
|
48
61
|
static actions: readonly ["scrollToBottom"];
|
|
49
62
|
static events: readonly ["pin", "new"];
|
|
@@ -51,9 +64,20 @@ declare class StickToBottomController extends Controller<HTMLElement> {
|
|
|
51
64
|
readonly hasContentTarget: boolean;
|
|
52
65
|
thresholdValue: number;
|
|
53
66
|
behaviorValue: string;
|
|
67
|
+
pinOnConnectValue: boolean;
|
|
54
68
|
connect(): void;
|
|
55
69
|
disconnect(): void;
|
|
56
|
-
/**
|
|
70
|
+
/**
|
|
71
|
+
* Jumps to the bottom and re-pins (wired to a "new messages" button).
|
|
72
|
+
*
|
|
73
|
+
* The has-new flag clears on request — the user has acknowledged the arrival — while
|
|
74
|
+
* pinned is read back from where the scroll landed: a jump that arrives by the time
|
|
75
|
+
* this returns pins immediately, an animated one settles from its own scroll events,
|
|
76
|
+
* and a jump the engine cannot honor leaves the container unpinned, so the next append
|
|
77
|
+
* flags it again instead of being swallowed by a pinned state that does not hold.
|
|
78
|
+
*
|
|
79
|
+
* Which of those happens is not this method's to decide — see {@link behaviorValue}.
|
|
80
|
+
*/
|
|
57
81
|
scrollToBottom(): void;
|
|
58
82
|
}
|
|
59
83
|
|
|
@@ -17,14 +17,18 @@ var StickToBottomController = class extends Controller {
|
|
|
17
17
|
static targets = ["content"];
|
|
18
18
|
static values = {
|
|
19
19
|
threshold: { type: Number, default: 80 },
|
|
20
|
-
behavior: { type: String, default: "auto" }
|
|
20
|
+
behavior: { type: String, default: "auto" },
|
|
21
|
+
pinOnConnect: { type: Boolean, default: false }
|
|
21
22
|
};
|
|
22
23
|
static actions = ["scrollToBottom"];
|
|
23
24
|
static events = ["pin", "new"];
|
|
24
25
|
#observer = null;
|
|
26
|
+
/** Watches for the box a deferred `pinOnConnect` jump is still waiting on. */
|
|
27
|
+
#layout = null;
|
|
25
28
|
#pinned = false;
|
|
26
29
|
#onScroll = () => this.#updatePinned();
|
|
27
30
|
connect() {
|
|
31
|
+
if (this.pinOnConnectValue && this.#measurable()) this.#scrollToBottom("instant");
|
|
28
32
|
this.#pinned = this.#isPinned();
|
|
29
33
|
this.#reflectPinned();
|
|
30
34
|
this.element.addEventListener("scroll", this.#onScroll, { passive: true });
|
|
@@ -32,21 +36,29 @@ var StickToBottomController = class extends Controller {
|
|
|
32
36
|
this.#observer = new MutationObserver((mutations) => this.#onMutations(mutations));
|
|
33
37
|
this.#observer.observe(this.#watched(), { childList: true });
|
|
34
38
|
}
|
|
39
|
+
if (this.pinOnConnectValue && !this.#measurable()) this.#pinWhenLaidOut();
|
|
35
40
|
}
|
|
36
41
|
disconnect() {
|
|
37
42
|
this.element.removeEventListener("scroll", this.#onScroll);
|
|
38
43
|
this.#observer?.disconnect();
|
|
39
44
|
this.#observer = null;
|
|
45
|
+
this.#stopWaitingForLayout();
|
|
40
46
|
}
|
|
41
|
-
/**
|
|
47
|
+
/**
|
|
48
|
+
* Jumps to the bottom and re-pins (wired to a "new messages" button).
|
|
49
|
+
*
|
|
50
|
+
* The has-new flag clears on request — the user has acknowledged the arrival — while
|
|
51
|
+
* pinned is read back from where the scroll landed: a jump that arrives by the time
|
|
52
|
+
* this returns pins immediately, an animated one settles from its own scroll events,
|
|
53
|
+
* and a jump the engine cannot honor leaves the container unpinned, so the next append
|
|
54
|
+
* flags it again instead of being swallowed by a pinned state that does not hold.
|
|
55
|
+
*
|
|
56
|
+
* Which of those happens is not this method's to decide — see {@link behaviorValue}.
|
|
57
|
+
*/
|
|
42
58
|
scrollToBottom() {
|
|
43
59
|
this.#scrollToBottom();
|
|
44
60
|
this.element.removeAttribute("data-has-new");
|
|
45
|
-
|
|
46
|
-
this.#pinned = true;
|
|
47
|
-
this.element.setAttribute("data-pinned", "true");
|
|
48
|
-
this.dispatch("pin", { detail: { pinned: true } });
|
|
49
|
-
}
|
|
61
|
+
this.#updatePinned();
|
|
50
62
|
}
|
|
51
63
|
/** Follows appended children while pinned; otherwise flags new content. */
|
|
52
64
|
#onMutations(mutations) {
|
|
@@ -81,10 +93,43 @@ var StickToBottomController = class extends Controller {
|
|
|
81
93
|
const el = this.element;
|
|
82
94
|
return el.scrollHeight - el.clientHeight - el.scrollTop <= this.thresholdValue;
|
|
83
95
|
}
|
|
84
|
-
|
|
96
|
+
/**
|
|
97
|
+
* Whether the container has a box to scroll and to measure. One that is not rendered
|
|
98
|
+
* (inside a closed panel) reports every metric as 0, which reads as "already at the
|
|
99
|
+
* bottom" — a position describing no layout the user will ever see.
|
|
100
|
+
*/
|
|
101
|
+
#measurable() {
|
|
102
|
+
return this.element.clientHeight > 0;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Holds the `pinOnConnect` jump until the container is laid out, then runs it and
|
|
106
|
+
* re-reads the state — otherwise the panel opens at the top still claiming the bottom.
|
|
107
|
+
*/
|
|
108
|
+
#pinWhenLaidOut() {
|
|
109
|
+
if (typeof ResizeObserver === "undefined") return;
|
|
110
|
+
this.#layout = new ResizeObserver(() => {
|
|
111
|
+
if (!this.#measurable()) return;
|
|
112
|
+
this.#stopWaitingForLayout();
|
|
113
|
+
this.#scrollToBottom("instant");
|
|
114
|
+
this.#updatePinned();
|
|
115
|
+
});
|
|
116
|
+
this.#layout.observe(this.element);
|
|
117
|
+
}
|
|
118
|
+
/** Releases the layout watch, whether or not the deferred jump ever ran. */
|
|
119
|
+
#stopWaitingForLayout() {
|
|
120
|
+
this.#layout?.disconnect();
|
|
121
|
+
this.#layout = null;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Scrolls to the bottom, clamped by the engine to the maximum scroll offset — which is
|
|
125
|
+
* 0 for a container tall enough to hold its whole content, so the jump moves nothing
|
|
126
|
+
* there. `behavior` defaults to the configured follow behavior; pass `"instant"` for a
|
|
127
|
+
* jump that must not animate.
|
|
128
|
+
*/
|
|
129
|
+
#scrollToBottom(behavior = this.#behavior()) {
|
|
85
130
|
const top = this.element.scrollHeight;
|
|
86
131
|
if (typeof this.element.scrollTo === "function") {
|
|
87
|
-
this.element.scrollTo({ top, behavior
|
|
132
|
+
this.element.scrollTo({ top, behavior });
|
|
88
133
|
} else {
|
|
89
134
|
this.element.scrollTop = top;
|
|
90
135
|
}
|
|
@@ -93,7 +138,12 @@ var StickToBottomController = class extends Controller {
|
|
|
93
138
|
#watched() {
|
|
94
139
|
return this.hasContentTarget ? this.contentTarget : this.element;
|
|
95
140
|
}
|
|
96
|
-
/**
|
|
141
|
+
/**
|
|
142
|
+
* The behavior a follow-scroll runs with. `"auto"` is **not** a request to arrive at
|
|
143
|
+
* once: it hands the decision to the element's computed `scroll-behavior`, so a
|
|
144
|
+
* consumer stylesheet saying `smooth` animates these scrolls too. Only `"instant"`
|
|
145
|
+
* overrides that CSS, which is why reduced motion and the `pinOnConnect` jump name it.
|
|
146
|
+
*/
|
|
97
147
|
#behavior() {
|
|
98
148
|
if (prefersReducedMotion()) return "instant";
|
|
99
149
|
return this.behaviorValue === "smooth" ? "smooth" : "auto";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/reduced_motion.ts","../../src/controllers/stick_to_bottom_controller.ts"],"names":[],"mappings":";;;;;AAmBO,SAAS,oBAAA,GAAgC;AAC9C,EAAA,OACE,OAAO,MAAA,CAAO,UAAA,KAAe,cAC7B,MAAA,CAAO,UAAA,CAAW,kCAAkC,CAAA,CAAE,OAAA;AAE1D;;;ACpBA,IAAM,aAAA,GAAgB,CAAC,KAAA,KAA4B;AACjD,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,EAAA,KAAA,MAA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esContent":["/**\n * Shared `prefers-reduced-motion` lookup for the motion-aware controllers\n * (count-up, highlight, overflow-indicator, scroll-visibility, stick-to-bottom,\n * transition).\n *\n * This one-liner keeps the media query string and the environment guard\n * single-sourced across them. The preference is intentionally re-read on every\n * call — the controllers check it at each animation/scroll start (WCAG 2.2\n * **2.3.3**), so flipping the OS setting takes effect immediately without any\n * listener or cache bookkeeping here.\n */\n\n/**\n * Whether the user currently requests reduced motion.\n *\n * @returns `true` when `(prefers-reduced-motion: reduce)` matches; `false`\n * otherwise, including environments without `window.matchMedia` (treated as\n * \"no preference\").\n */\nexport function prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\n/** Counts the element nodes in an added-node list (text nodes are ignored). */\nconst countElements = (nodes: NodeList): number => {\n let n = 0;\n for (const node of nodes) if (node.nodeType === Node.ELEMENT_NODE) n += 1;\n return n;\n};\n\n/**\n * Headless **stick-to-bottom**: auto-follows new content to the bottom of a scroll\n * container (a chat log, a live console) — but only while the user is already near the\n * bottom; if they have scrolled up to read, it holds position and flags that new content\n * arrived instead (no APG pattern; honors WCAG 2.3.3 via `prefers-reduced-motion` and\n * never steals focus).\n *\n * Markup contract (identifier: `stimeo--stick-to-bottom`):\n * <div data-controller=\"stimeo--stick-to-bottom\"\n * data-stimeo--stick-to-bottom-threshold-value=\"80\" style=\"overflow:auto\">\n * <ul data-stimeo--stick-to-bottom-target=\"content\"><!-- Turbo Stream appends --></ul>\n * </div>\n *\n * The container is \"pinned\" while its distance from the bottom is within `threshold`. A\n * `MutationObserver` on `content` (or the element) reacts to appended children: while\n * pinned it scrolls to the bottom; while unpinned it sets `data-has-new` and emits `new`.\n * Scrolling recomputes pinned and reflects `data-pinned`, emitting `pin` on change; the\n * `scrollToBottom` action jumps back down (a \"new messages\" button).\n *\n * @remarks\n * The `MutationObserver` watches `childList` only (not `subtree`), so it follows\n * direct appends to `content` (or the element). Appends made deeper inside a nested\n * wrapper are not detected — keep messages as direct children, or call the public\n * `scrollToBottom` action after such inserts.\n *\n * Behavior only — it does not add content (Turbo Stream / the consumer does) and is the\n * minimal follow primitive, not a full chat UI (no virtualization / message input). State\n * is derived from the scroll position each pass (no module-scope state), so `connect()`\n * re-syncs after a Turbo Stream insert; reduced motion forces an instant jump\n * independently of consumer CSS; auto-scroll never moves focus; the observer and the\n * passive scroll listener are released on `disconnect()` (Turbo navigation included).\n */\nexport class StickToBottomController extends Controller<HTMLElement> {\n static override targets = [\"content\"];\n static override values = {\n threshold: { type: Number, default: 80 },\n behavior: { type: String, default: \"auto\" },\n };\n static actions = [\"scrollToBottom\"] as const;\n static events = [\"pin\", \"new\"] as const;\n\n declare readonly contentTarget: HTMLElement;\n declare readonly hasContentTarget: boolean;\n\n declare thresholdValue: number;\n declare behaviorValue: string;\n\n #observer: MutationObserver | null = null;\n #pinned = false;\n\n readonly #onScroll = (): void => this.#updatePinned();\n\n override connect(): void {\n this.#pinned = this.#isPinned();\n // Re-sync the hooks from the current geometry — a Turbo cache restore may bring back a\n // stale data-pinned / data-has-new that disagrees with the current scroll position.\n this.#reflectPinned();\n\n this.element.addEventListener(\"scroll\", this.#onScroll, { passive: true });\n if (typeof MutationObserver !== \"undefined\") {\n this.#observer = new MutationObserver((mutations) => this.#onMutations(mutations));\n this.#observer.observe(this.#watched(), { childList: true });\n }\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"scroll\", this.#onScroll);\n this.#observer?.disconnect();\n this.#observer = null;\n }\n\n /** Jumps to the bottom and re-pins (wired to a \"new messages\" button). */\n scrollToBottom(): void {\n this.#scrollToBottom();\n this.element.removeAttribute(\"data-has-new\");\n if (!this.#pinned) {\n this.#pinned = true;\n this.element.setAttribute(\"data-pinned\", \"true\");\n this.dispatch(\"pin\", { detail: { pinned: true } });\n }\n }\n\n /** Follows appended children while pinned; otherwise flags new content. */\n #onMutations(mutations: MutationRecord[]): void {\n let added = 0;\n for (const mutation of mutations) added += countElements(mutation.addedNodes);\n if (added === 0) return;\n\n if (this.#pinned) {\n this.#scrollToBottom();\n } else {\n this.element.setAttribute(\"data-has-new\", \"true\");\n this.dispatch(\"new\", { detail: { count: added } });\n }\n }\n\n /** Recomputes pinned from the scroll position and reflects it on a transition. */\n #updatePinned(): void {\n const pinned = this.#isPinned();\n if (pinned === this.#pinned) return;\n this.#pinned = pinned;\n this.#reflectPinned();\n this.dispatch(\"pin\", { detail: { pinned } });\n }\n\n /** Mirrors the current `#pinned` onto the state hooks (clearing has-new once pinned). */\n #reflectPinned(): void {\n if (this.#pinned) {\n this.element.setAttribute(\"data-pinned\", \"true\");\n this.element.removeAttribute(\"data-has-new\"); // caught up with the bottom\n } else {\n this.element.removeAttribute(\"data-pinned\");\n }\n }\n\n #isPinned(): boolean {\n const el = this.element;\n return el.scrollHeight - el.clientHeight - el.scrollTop <= this.thresholdValue;\n }\n\n #scrollToBottom(): void {\n const top = this.element.scrollHeight;\n if (typeof this.element.scrollTo === \"function\") {\n this.element.scrollTo({ top, behavior: this.#behavior() });\n } else {\n this.element.scrollTop = top;\n }\n }\n\n /** The append-watched element: the `content` target, or the container itself. */\n #watched(): HTMLElement {\n return this.hasContentTarget ? this.contentTarget : this.element;\n }\n\n /** Forces reduced-motion jumps while preserving the configured normal behavior. */\n #behavior(): ScrollBehavior {\n if (prefersReducedMotion()) return \"instant\";\n return this.behaviorValue === \"smooth\" ? \"smooth\" : \"auto\";\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/reduced_motion.ts","../../src/controllers/stick_to_bottom_controller.ts"],"names":[],"mappings":";;;;;AAmBO,SAAS,oBAAA,GAAgC;AAC9C,EAAA,OACE,OAAO,MAAA,CAAO,UAAA,KAAe,cAC7B,MAAA,CAAO,UAAA,CAAW,kCAAkC,CAAA,CAAE,OAAA;AAE1D;;;ACpBA,IAAM,aAAA,GAAg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AK,aAAA,EAAc;AAAA,IACrB,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,OAAA,CAAQ,OAAA,CAAQ,IAAA,CAAK,OAAO,CAAA;AAAA,EACnC;AAAA;AAAA,EAGA,qBAAA,GAA8B;AAC5B,IAAA,IAAA,CAAK,SAAS,UAAA,EAAW;AACzB,IAAA,IAAA,CAAK,OAAA,GAAU,IAAA;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,eAAA,CAAgB,QAAA,GAA2B,IAAA,CAAK,SAAA,EAAU,EAAS;AACjE,IAAA,MAAM,GAAA,GAAM,KAAK,OAAA,CAAQ,YAAA;AACzB,IAAA,IAAI,OAAO,IAAA,CAAK,OAAA,CAAQ,QAAA,KAAa,UAAA,EAAY;AAC/C,MAAA,IAAA,CAAK,OAAA,CAAQ,QAAA,CAAS,EAAE,GAAA,EAAK,UAAU,CAAA;AAAA,IACzC,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,QAAQ,SAAA,GAAY,GAAA;AAAA,IAC3B;AAAA,EACF;AAAA;AAAA,EAGA,QAAA,GAAwB;AACtB,IAAA,OAAO,IAAA,CAAK,gBAAA,GAAmB,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,OAAA;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,SAAA,GAA4B;AAC1B,IAAA,IAAI,oBAAA,IAAwB,OAAO,SAAA;AACnC,IAAA,OAAO,IAAA,CAAK,aAAA,KAAkB,QAAA,GAAW,QAAA,GAAW,MAAA;AAAA,EACtD;AACF","file":"stick_to_bottom_controller.js","sourcesContent":["/**\n * Shared `prefers-reduced-motion` lookup for the motion-aware controllers\n * (count-up, highlight, overflow-indicator, scroll-visibility, stick-to-bottom,\n * transition).\n *\n * This one-liner keeps the media query string and the environment guard\n * single-sourced across them. The preference is intentionally re-read on every\n * call — the controllers check it at each animation/scroll start (WCAG 2.2\n * **2.3.3**), so flipping the OS setting takes effect immediately without any\n * listener or cache bookkeeping here.\n */\n\n/**\n * Whether the user currently requests reduced motion.\n *\n * @returns `true` when `(prefers-reduced-motion: reduce)` matches; `false`\n * otherwise, including environments without `window.matchMedia` (treated as\n * \"no preference\").\n */\nexport function prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\n/** Counts the element nodes in an added-node list (text nodes are ignored). */\nconst countElements = (nodes: NodeList): number => {\n let n = 0;\n for (const node of nodes) if (node.nodeType === Node.ELEMENT_NODE) n += 1;\n return n;\n};\n\n/**\n * Headless **stick-to-bottom**: auto-follows new content to the bottom of a scroll\n * container (a chat log, a live console) — but only while the user is already near the\n * bottom; if they have scrolled up to read, it holds position and flags that new content\n * arrived instead (no APG pattern; honors WCAG 2.3.3 via `prefers-reduced-motion` and\n * never steals focus).\n *\n * Markup contract (identifier: `stimeo--stick-to-bottom`):\n * <div data-controller=\"stimeo--stick-to-bottom\"\n * data-stimeo--stick-to-bottom-threshold-value=\"80\"\n * data-stimeo--stick-to-bottom-pin-on-connect-value=\"true\" style=\"overflow:auto\">\n * <ul data-stimeo--stick-to-bottom-target=\"content\"><!-- Turbo Stream appends --></ul>\n * </div>\n *\n * The container is \"pinned\" while its distance from the bottom is within `threshold`. A\n * `MutationObserver` on `content` (or the element) reacts to appended children: while\n * pinned it scrolls to the bottom; while unpinned it sets `data-has-new` and emits `new`.\n * Scrolling recomputes pinned and reflects `data-pinned`, emitting `pin` on change; the\n * `scrollToBottom` action jumps back down (a \"new messages\" button).\n *\n * A container renders at `scrollTop` 0 — unpinned — so out of the box it flags the first\n * append rather than following it. `pinOnConnect` opts into the other starting point:\n * `connect()` jumps to the bottom and reads the state back from where it landed. It runs\n * on every connect, so a container inserted or re-rendered later (a Turbo Stream, a panel\n * built on open) starts at the bottom too — which a once-per-document page event cannot\n * do. It is off by default, so a restored reading position (a Turbo cache restore, a user\n * who had scrolled up) is never yanked to the bottom unless the consumer asks for it.\n *\n * @remarks\n * The `MutationObserver` watches `childList` only (not `subtree`), so it follows\n * direct appends to `content` (or the element). Appends made deeper inside a nested\n * wrapper are not detected — keep messages as direct children, or call the public\n * `scrollToBottom` action after such inserts.\n *\n * Behavior only — it does not add content (Turbo Stream / the consumer does) and is the\n * minimal follow primitive, not a full chat UI (no virtualization / message input). State\n * is derived from the scroll position each pass (no module-scope state), so `connect()`\n * re-syncs after a Turbo Stream insert; reduced motion forces an instant jump\n * independently of consumer CSS; auto-scroll never moves focus; the observer and the\n * passive scroll listener are released on `disconnect()` (Turbo navigation included).\n */\nexport class StickToBottomController extends Controller<HTMLElement> {\n static override targets = [\"content\"];\n static override values = {\n threshold: { type: Number, default: 80 },\n behavior: { type: String, default: \"auto\" },\n pinOnConnect: { type: Boolean, default: false },\n };\n static actions = [\"scrollToBottom\"] as const;\n static events = [\"pin\", \"new\"] as const;\n\n declare readonly contentTarget: HTMLElement;\n declare readonly hasContentTarget: boolean;\n\n declare thresholdValue: number;\n declare behaviorValue: string;\n declare pinOnConnectValue: boolean;\n\n #observer: MutationObserver | null = null;\n /** Watches for the box a deferred `pinOnConnect` jump is still waiting on. */\n #layout: ResizeObserver | null = null;\n #pinned = false;\n\n readonly #onScroll = (): void => this.#updatePinned();\n\n override connect(): void {\n // Instant whatever `behavior` says, overriding a consumer's `scroll-behavior: smooth`:\n // an animated jump emits scroll events on the way down, each recomputing pinned from a\n // position still far from the bottom, so the container would unpin (and re-pin)\n // mid-flight before it ever settles.\n if (this.pinOnConnectValue && this.#measurable()) this.#scrollToBottom(\"instant\");\n // Read the state back from where the container actually is, asked for a jump or not: a\n // request the engine does not honor must leave it unpinned, so the next append is\n // flagged rather than swallowed. This also drops a stale data-pinned / data-has-new a\n // Turbo cache restore brought back.\n this.#pinned = this.#isPinned();\n this.#reflectPinned();\n\n this.element.addEventListener(\"scroll\", this.#onScroll, { passive: true });\n if (typeof MutationObserver !== \"undefined\") {\n this.#observer = new MutationObserver((mutations) => this.#onMutations(mutations));\n this.#observer.observe(this.#watched(), { childList: true });\n }\n if (this.pinOnConnectValue && !this.#measurable()) this.#pinWhenLaidOut();\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"scroll\", this.#onScroll);\n this.#observer?.disconnect();\n this.#observer = null;\n this.#stopWaitingForLayout();\n }\n\n /**\n * Jumps to the bottom and re-pins (wired to a \"new messages\" button).\n *\n * The has-new flag clears on request — the user has acknowledged the arrival — while\n * pinned is read back from where the scroll landed: a jump that arrives by the time\n * this returns pins immediately, an animated one settles from its own scroll events,\n * and a jump the engine cannot honor leaves the container unpinned, so the next append\n * flags it again instead of being swallowed by a pinned state that does not hold.\n *\n * Which of those happens is not this method's to decide — see {@link behaviorValue}.\n */\n scrollToBottom(): void {\n this.#scrollToBottom();\n this.element.removeAttribute(\"data-has-new\");\n this.#updatePinned();\n }\n\n /** Follows appended children while pinned; otherwise flags new content. */\n #onMutations(mutations: MutationRecord[]): void {\n let added = 0;\n for (const mutation of mutations) added += countElements(mutation.addedNodes);\n if (added === 0) return;\n\n if (this.#pinned) {\n this.#scrollToBottom();\n } else {\n this.element.setAttribute(\"data-has-new\", \"true\");\n this.dispatch(\"new\", { detail: { count: added } });\n }\n }\n\n /** Recomputes pinned from the scroll position and reflects it on a transition. */\n #updatePinned(): void {\n const pinned = this.#isPinned();\n if (pinned === this.#pinned) return;\n this.#pinned = pinned;\n this.#reflectPinned();\n this.dispatch(\"pin\", { detail: { pinned } });\n }\n\n /** Mirrors the current `#pinned` onto the state hooks (clearing has-new once pinned). */\n #reflectPinned(): void {\n if (this.#pinned) {\n this.element.setAttribute(\"data-pinned\", \"true\");\n this.element.removeAttribute(\"data-has-new\"); // caught up with the bottom\n } else {\n this.element.removeAttribute(\"data-pinned\");\n }\n }\n\n #isPinned(): boolean {\n const el = this.element;\n return el.scrollHeight - el.clientHeight - el.scrollTop <= this.thresholdValue;\n }\n\n /**\n * Whether the container has a box to scroll and to measure. One that is not rendered\n * (inside a closed panel) reports every metric as 0, which reads as \"already at the\n * bottom\" — a position describing no layout the user will ever see.\n */\n #measurable(): boolean {\n return this.element.clientHeight > 0;\n }\n\n /**\n * Holds the `pinOnConnect` jump until the container is laid out, then runs it and\n * re-reads the state — otherwise the panel opens at the top still claiming the bottom.\n */\n #pinWhenLaidOut(): void {\n if (typeof ResizeObserver === \"undefined\") return;\n this.#layout = new ResizeObserver(() => {\n if (!this.#measurable()) return;\n this.#stopWaitingForLayout();\n this.#scrollToBottom(\"instant\");\n this.#updatePinned();\n });\n this.#layout.observe(this.element);\n }\n\n /** Releases the layout watch, whether or not the deferred jump ever ran. */\n #stopWaitingForLayout(): void {\n this.#layout?.disconnect();\n this.#layout = null;\n }\n\n /**\n * Scrolls to the bottom, clamped by the engine to the maximum scroll offset — which is\n * 0 for a container tall enough to hold its whole content, so the jump moves nothing\n * there. `behavior` defaults to the configured follow behavior; pass `\"instant\"` for a\n * jump that must not animate.\n */\n #scrollToBottom(behavior: ScrollBehavior = this.#behavior()): void {\n const top = this.element.scrollHeight;\n if (typeof this.element.scrollTo === \"function\") {\n this.element.scrollTo({ top, behavior });\n } else {\n this.element.scrollTop = top;\n }\n }\n\n /** The append-watched element: the `content` target, or the container itself. */\n #watched(): HTMLElement {\n return this.hasContentTarget ? this.contentTarget : this.element;\n }\n\n /**\n * The behavior a follow-scroll runs with. `\"auto\"` is **not** a request to arrive at\n * once: it hands the decision to the element's computed `scroll-behavior`, so a\n * consumer stylesheet saying `smooth` animates these scrolls too. Only `\"instant\"`\n * overrides that CSS, which is why reduced motion and the `pinOnConnect` jump name it.\n */\n #behavior(): ScrollBehavior {\n if (prefersReducedMotion()) return \"instant\";\n return this.behaviorValue === \"smooth\" ? \"smooth\" : \"auto\";\n }\n}\n"]}
|