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.
Files changed (82) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/controllers/alert_dialog_controller.js +32 -5
  3. package/dist/controllers/alert_dialog_controller.js.map +1 -1
  4. package/dist/controllers/announcer_controller.d.ts +32 -6
  5. package/dist/controllers/announcer_controller.js +255 -20
  6. package/dist/controllers/announcer_controller.js.map +1 -1
  7. package/dist/controllers/color_picker_controller.d.ts +2 -1
  8. package/dist/controllers/color_picker_controller.js +46 -0
  9. package/dist/controllers/color_picker_controller.js.map +1 -1
  10. package/dist/controllers/command_palette_controller.js +32 -5
  11. package/dist/controllers/command_palette_controller.js.map +1 -1
  12. package/dist/controllers/confirm_controller.js +32 -5
  13. package/dist/controllers/confirm_controller.js.map +1 -1
  14. package/dist/controllers/countdown_controller.d.ts +19 -5
  15. package/dist/controllers/countdown_controller.js +112 -12
  16. package/dist/controllers/countdown_controller.js.map +1 -1
  17. package/dist/controllers/date_range_picker_controller.d.ts +4 -1
  18. package/dist/controllers/date_range_picker_controller.js +50 -0
  19. package/dist/controllers/date_range_picker_controller.js.map +1 -1
  20. package/dist/controllers/dialog_controller.js +32 -5
  21. package/dist/controllers/dialog_controller.js.map +1 -1
  22. package/dist/controllers/dismissible_controller.js.map +1 -1
  23. package/dist/controllers/drawer_controller.js +32 -5
  24. package/dist/controllers/drawer_controller.js.map +1 -1
  25. package/dist/controllers/empty_state_controller.d.ts +9 -4
  26. package/dist/controllers/empty_state_controller.js +24 -10
  27. package/dist/controllers/empty_state_controller.js.map +1 -1
  28. package/dist/controllers/focus_controller.js +32 -5
  29. package/dist/controllers/focus_controller.js.map +1 -1
  30. package/dist/controllers/form_validation_controller.js.map +1 -1
  31. package/dist/controllers/frame_loading_controller.d.ts +14 -3
  32. package/dist/controllers/frame_loading_controller.js +177 -15
  33. package/dist/controllers/frame_loading_controller.js.map +1 -1
  34. package/dist/controllers/local_time_controller.d.ts +19 -3
  35. package/dist/controllers/local_time_controller.js +100 -6
  36. package/dist/controllers/local_time_controller.js.map +1 -1
  37. package/dist/controllers/meter_controller.d.ts +22 -2
  38. package/dist/controllers/meter_controller.js +145 -26
  39. package/dist/controllers/meter_controller.js.map +1 -1
  40. package/dist/controllers/network_status_controller.d.ts +13 -1
  41. package/dist/controllers/network_status_controller.js +28 -8
  42. package/dist/controllers/network_status_controller.js.map +1 -1
  43. package/dist/controllers/overflow_menu_controller.js +33 -6
  44. package/dist/controllers/overflow_menu_controller.js.map +1 -1
  45. package/dist/controllers/progress_controller.d.ts +16 -1
  46. package/dist/controllers/progress_controller.js +116 -9
  47. package/dist/controllers/progress_controller.js.map +1 -1
  48. package/dist/controllers/range_slider_controller.d.ts +4 -1
  49. package/dist/controllers/range_slider_controller.js +68 -3
  50. package/dist/controllers/range_slider_controller.js.map +1 -1
  51. package/dist/controllers/rating_controller.d.ts +4 -1
  52. package/dist/controllers/rating_controller.js +53 -0
  53. package/dist/controllers/rating_controller.js.map +1 -1
  54. package/dist/controllers/relative_time_controller.d.ts +13 -0
  55. package/dist/controllers/relative_time_controller.js +133 -12
  56. package/dist/controllers/relative_time_controller.js.map +1 -1
  57. package/dist/controllers/sidebar_controller.d.ts +1 -11
  58. package/dist/controllers/sidebar_controller.js +37 -8
  59. package/dist/controllers/sidebar_controller.js.map +1 -1
  60. package/dist/controllers/skeleton_controller.d.ts +7 -2
  61. package/dist/controllers/skeleton_controller.js +73 -20
  62. package/dist/controllers/skeleton_controller.js.map +1 -1
  63. package/dist/controllers/slider_controller.js +17 -2
  64. package/dist/controllers/slider_controller.js.map +1 -1
  65. package/dist/controllers/spinner_controller.d.ts +37 -4
  66. package/dist/controllers/spinner_controller.js +228 -27
  67. package/dist/controllers/spinner_controller.js.map +1 -1
  68. package/dist/controllers/step_indicator_controller.d.ts +12 -1
  69. package/dist/controllers/step_indicator_controller.js +82 -5
  70. package/dist/controllers/step_indicator_controller.js.map +1 -1
  71. package/dist/controllers/stick_to_bottom_controller.d.ts +26 -2
  72. package/dist/controllers/stick_to_bottom_controller.js +60 -10
  73. package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
  74. package/dist/index.js +1056 -281
  75. package/dist/index.js.map +1 -1
  76. package/dist/inspector/cli.js +785 -76
  77. package/dist/inspector/cli.js.map +1 -1
  78. package/dist/inspector/cli_bin.js +785 -76
  79. package/dist/inspector/cli_bin.js.map +1 -1
  80. package/dist/inspector/examples.json +5 -5
  81. package/dist/inspector/manifest.json +21 -8
  82. package/package.json +1 -1
@@ -2,6 +2,145 @@ import { Controller } from '@hotwired/stimulus';
2
2
 
3
3
  // src/controllers/frame_loading_controller.ts
4
4
 
5
+ // src/utils/announce.ts
6
+ function announce(message, options = {}) {
7
+ const text = message.trim();
8
+ if (text.length === 0) return;
9
+ window.dispatchEvent(
10
+ new CustomEvent("stimeo--announcer:announce", {
11
+ detail: { message: text, assertive: options.assertive === true }
12
+ })
13
+ );
14
+ }
15
+ function fillTemplate(template, values) {
16
+ return template.replace(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g, (match, name) => {
17
+ const replacement = values[name];
18
+ return replacement === void 0 ? match : String(replacement);
19
+ });
20
+ }
21
+
22
+ // src/utils/before_cache_reset.ts
23
+ var BeforeCacheReset = class _BeforeCacheReset {
24
+ /** Every subscribed instance, iterated by the one shared document listener. */
25
+ static #subscribers = /* @__PURE__ */ new Set();
26
+ /** The shared listener; installed while at least one instance is subscribed. */
27
+ static #onBeforeCache = () => {
28
+ for (const subscriber of _BeforeCacheReset.#subscribers) subscriber.#rewind();
29
+ };
30
+ #rewind;
31
+ /** @param rewind - the pass that returns this controller's state to its initial form. */
32
+ constructor(rewind) {
33
+ this.#rewind = rewind;
34
+ }
35
+ /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */
36
+ activate() {
37
+ const first = _BeforeCacheReset.#subscribers.size === 0;
38
+ _BeforeCacheReset.#subscribers.add(this);
39
+ if (first) {
40
+ document.addEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
41
+ }
42
+ }
43
+ /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */
44
+ deactivate() {
45
+ _BeforeCacheReset.#subscribers.delete(this);
46
+ if (_BeforeCacheReset.#subscribers.size > 0) return;
47
+ document.removeEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
48
+ }
49
+ };
50
+
51
+ // src/utils/detach_gate.ts
52
+ var DetachGate = class _DetachGate {
53
+ /** Set while a probe is queued, waiting for a reconnect to cancel it. */
54
+ #pending = false;
55
+ /**
56
+ * True when the disconnect is definitely a real detach — the element left
57
+ * the document, or `data-controller` no longer lists the identifier. False
58
+ * means ambiguous (in-page move or observed-root exit), NOT "alive".
59
+ */
60
+ static isDetached(host) {
61
+ if (!host.element.isConnected) return true;
62
+ const tokens = (host.element.getAttribute("data-controller") ?? "").split(/\s+/);
63
+ return !tokens.includes(host.identifier);
64
+ }
65
+ /**
66
+ * Call from `disconnect()`: runs `teardown` synchronously on a definite
67
+ * detach (fast path), otherwise defers it one microtask — a reconnect
68
+ * ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.
69
+ * One microtask is the whole probe window: Stimulus reconnects a moved
70
+ * element within the same mutation batch, before the checkpoint drains.
71
+ */
72
+ disconnected(host, teardown) {
73
+ if (_DetachGate.isDetached(host)) {
74
+ this.#pending = false;
75
+ teardown();
76
+ return;
77
+ }
78
+ this.#pending = true;
79
+ queueMicrotask(() => {
80
+ if (!this.#pending) return;
81
+ this.#pending = false;
82
+ teardown();
83
+ });
84
+ }
85
+ /**
86
+ * Disarms a pending probe. Call from `connect()` (the reconnect that proves
87
+ * an in-page move) and from the head of any teardown path not routed through
88
+ * {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can
89
+ * never run the teardown a second time.
90
+ */
91
+ cancel() {
92
+ this.#pending = false;
93
+ }
94
+ };
95
+
96
+ // src/utils/min_duration_floor.ts
97
+ var MinDurationFloor = class {
98
+ #timers;
99
+ /** Pending finish timer id, or `null` when nothing is held back. */
100
+ #timerId = null;
101
+ /** Epoch ms the floor is measured from. */
102
+ #since = 0;
103
+ /** @param timers - the controller's registry; the floor schedules into it. */
104
+ constructor(timers) {
105
+ this.#timers = timers;
106
+ }
107
+ /** Starts the floor: call when the state being held becomes visible. */
108
+ begin() {
109
+ this.#since = Date.now();
110
+ }
111
+ /** True while a finish is held back waiting for the floor to elapse. */
112
+ get pending() {
113
+ return this.#timerId !== null;
114
+ }
115
+ /**
116
+ * Runs `finish` once the floor has elapsed, immediately when it already has.
117
+ *
118
+ * A held-back finish is **replaced**, never stacked: only the most recently
119
+ * queued id is cancellable, so a second timer would outlive every cancel and
120
+ * end a state that has since restarted. Controllers that want the first signal
121
+ * to win guard on {@link pending} before calling.
122
+ */
123
+ schedule(minDuration, finish) {
124
+ this.cancel();
125
+ const remaining = minDuration - (Date.now() - this.#since);
126
+ if (remaining > 0) {
127
+ this.#timerId = this.#timers.set(() => {
128
+ this.#timerId = null;
129
+ finish();
130
+ }, remaining);
131
+ } else {
132
+ finish();
133
+ }
134
+ }
135
+ /** Drops a held-back finish. Safe when none is queued, or after a bulk clear. */
136
+ cancel() {
137
+ if (this.#timerId !== null) {
138
+ this.#timers.clear(this.#timerId);
139
+ this.#timerId = null;
140
+ }
141
+ }
142
+ };
143
+
5
144
  // src/utils/safe_timeout.ts
6
145
  var TimerRegistry = class {
7
146
  /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */
@@ -59,32 +198,32 @@ var SafeTimeout = class extends TimerRegistry {
59
198
  var FrameLoadingController = class extends Controller {
60
199
  static targets = ["content", "skeleton", "overlay"];
61
200
  static values = {
201
+ announceText: { type: String, default: "" },
202
+ announceReadyText: { type: String, default: "" },
62
203
  minDuration: { type: Number, default: 0 },
63
204
  restoreFocus: { type: Boolean, default: true }
64
205
  };
65
206
  static events = ["start", "end"];
66
207
  #timeouts = new SafeTimeout();
208
+ #floor = new MinDurationFloor(this.#timeouts);
209
+ #gate = new DetachGate();
210
+ #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());
67
211
  #loading = false;
68
- #startedAt = 0;
69
212
  #inertApplied = false;
70
213
  #previousFocus = null;
71
214
  /** The id of the retreated element, used to re-find it if the load replaced it. */
72
215
  #previousFocusId = "";
73
216
  #onStart = () => {
74
- this.#timeouts.clearAll();
217
+ this.#floor.cancel();
75
218
  if (!this.#loading) this.#begin();
76
219
  };
77
220
  #onEnd = () => {
78
221
  if (!this.#loading) return;
79
- const remaining = this.minDurationValue - (Date.now() - this.#startedAt);
80
- if (remaining > 0) {
81
- this.#timeouts.clearAll();
82
- this.#timeouts.set(() => this.#finish(), remaining);
83
- } else {
84
- this.#finish();
85
- }
222
+ this.#floor.schedule(this.minDurationValue, () => this.#finish());
86
223
  };
87
224
  connect() {
225
+ this.#gate.cancel();
226
+ this.#beforeCache.activate();
88
227
  this.element.addEventListener("turbo:before-fetch-request", this.#onStart);
89
228
  this.element.addEventListener("turbo:frame-load", this.#onEnd);
90
229
  this.element.addEventListener("turbo:fetch-request-error", this.#onEnd);
@@ -93,19 +232,40 @@ var FrameLoadingController = class extends Controller {
93
232
  this.element.removeEventListener("turbo:before-fetch-request", this.#onStart);
94
233
  this.element.removeEventListener("turbo:frame-load", this.#onEnd);
95
234
  this.element.removeEventListener("turbo:fetch-request-error", this.#onEnd);
235
+ this.#beforeCache.deactivate();
236
+ this.#gate.disconnected(this, () => this.#teardown());
237
+ }
238
+ /**
239
+ * Drops the held finish and the loading bookkeeping on a real detach. The markup
240
+ * keeps whatever it last held: the page being cached is rewound at
241
+ * `turbo:before-cache` instead, where the frame is still whole.
242
+ */
243
+ #teardown() {
244
+ this.#gate.cancel();
96
245
  this.#timeouts.clearAll();
97
- if (this.#loading) {
98
- this.element.removeAttribute("aria-busy");
99
- this.element.removeAttribute("data-frame-loading");
100
- this.#clearInert();
101
- }
246
+ this.#floor.cancel();
102
247
  this.#loading = false;
103
248
  this.#previousFocus = null;
104
249
  }
250
+ /**
251
+ * Returns the frame to its resting hooks for the snapshot Turbo is about to
252
+ * take, so a page reached with the Back button does not restore a frame that is
253
+ * busy and inert with nothing left to finish it. State only — no `end` event and
254
+ * no focus move, because the load did not actually complete. The live page keeps
255
+ * its held finish, so a navigation that never completes still ends properly.
256
+ */
257
+ #rewindForCache() {
258
+ if (!this.#loading) return;
259
+ this.element.removeAttribute("aria-busy");
260
+ this.element.removeAttribute("data-frame-loading");
261
+ if (this.hasSkeletonTarget) this.skeletonTarget.hidden = true;
262
+ if (this.hasOverlayTarget) this.overlayTarget.hidden = true;
263
+ this.#clearInert();
264
+ }
105
265
  /** Enters the loading state: hooks, skeleton/overlay, inert content, focus retreat. */
106
266
  #begin() {
107
267
  this.#loading = true;
108
- this.#startedAt = Date.now();
268
+ this.#floor.begin();
109
269
  this.element.setAttribute("aria-busy", "true");
110
270
  this.element.setAttribute("data-frame-loading", "true");
111
271
  if (this.hasSkeletonTarget) this.skeletonTarget.hidden = false;
@@ -113,6 +273,7 @@ var FrameLoadingController = class extends Controller {
113
273
  this.#applyInert();
114
274
  this.#retreatFocus();
115
275
  this.dispatch("start", { detail: {} });
276
+ announce(fillTemplate(this.announceTextValue, {}));
116
277
  }
117
278
  /** Leaves the loading state: restore hooks, hide skeleton/overlay, restore focus. */
118
279
  #finish() {
@@ -124,6 +285,7 @@ var FrameLoadingController = class extends Controller {
124
285
  this.#clearInert();
125
286
  this.#restoreFocus();
126
287
  this.dispatch("end", { detail: {} });
288
+ announce(fillTemplate(this.announceReadyTextValue, {}));
127
289
  }
128
290
  /** Marks the content inert to block double-submits while stale (if we own it). */
129
291
  #applyInert() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/safe_timeout.ts","../../src/controllers/frame_loading_controller.ts"],"names":[],"mappings":";;;;;AAwBA,IAAe,gBAAf,MAA6B;AAAA;AAAA,EAER,GAAA,uBAAU,GAAA,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAczC,MA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AA,MAAM,SAAS,QAAA,CAAS,aAAA;AACxB,IAAA,IAAI,MAAA,YAAkB,eAAe,MAAA,KAAW,IAAA,CAAK,WAAW,IAAA,CAAK,OAAA,CAAQ,QAAA,CAAS,MAAM,CAAA,EAAG;AAC7F,MAAA,IAAA,CAAK,cAAA,GAAiB,MAAA;AACtB,MAAA,IAAA,CAAK,mBAAmB,MAAA,CAAO,EAAA;AAC/B,MAAA,MAAA,CAAO,IAAA,EAAK;AAAA,IACd;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,aAAA,GAAsB;AACpB,IAAA,MAAM,SAAS,IAAA,CAAK,cAAA;AACpB,IAAA,MAAM,KAAK,IAAA,CAAK,gBAAA;AAChB,IAAA,IAAA,CAAK,cAAA,GAAiB,IAAA;AACtB,IAAA,IAAA,CAAK,gBAAA,GAAmB,EAAA;AACxB,IAAA,IAAI,CAAC,KAAK,iBAAA,EAAmB;AAC7B,IAAA,IAAI,QAAQ,WAAA,EAAa;AACvB,MAAA,MAAA,CAAO,KAAA,EAAM;AACb,MAAA;AAAA,IACF;AACA,IAAA,IAAI,EAAA,EAAI;AACN,MAAA,MAAM,WAAA,GAAc,QAAA,CAAS,cAAA,CAAe,EAAE,CAAA;AAC9C,MAAA,IAAI,eAAe,IAAA,CAAK,OAAA,CAAQ,SAAS,WAAW,CAAA,cAAe,KAAA,EAAM;AAAA,IAC3E;AAAA,EACF;AACF","file":"frame_loading_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 `<turbo-frame>` loading-state behavior: while the frame is fetching it\n * sets `aria-busy` + `data-frame-loading`, reveals an optional skeleton / overlay,\n * suppresses interaction with the stale content, and retreats focus, restoring it on\n * completion (no dedicated APG pattern; supports WCAG 2.2 **4.1.3 Status Messages**\n * via `aria-busy` and 2.4.3 focus order via the retreat/restore).\n *\n * Markup contract (identifier: `stimeo--frame-loading`):\n * <turbo-frame id=\"panel\" data-controller=\"stimeo--frame-loading\">\n * <div data-stimeo--frame-loading-target=\"skeleton\" hidden>…</div>\n * <div data-stimeo--frame-loading-target=\"content\">…</div>\n * </turbo-frame>\n *\n * It subscribes on the frame to Turbo's own fetch lifecycle: `turbo:before-fetch-request`\n * (which bubbles from the frame's links/forms or the frame itself) starts the loading\n * state, and `turbo:frame-load` ends it (with `turbo:fetch-request-error` as a safety\n * net so the state never sticks). `minDuration` keeps the skeleton up long enough to\n * avoid a flicker.\n *\n * @remarks\n * Behavior only — it ships no skeleton markup or styling (pair with Skeleton/CSS);\n * loading is held purely in `aria-busy` / `data-frame-loading` and the optional\n * targets' `hidden`. The `content` target is marked `inert` while loading to block\n * double-submits, and focus inside the frame is explicitly blurred then restored\n * (when `restoreFocus`) so it is testable without relying on emergent `inert`\n * focus behavior. Listeners and the min-duration timer are torn down on\n * `disconnect()` (Turbo navigation included), which also tidies the hooks so a\n * cached frame is never left busy.\n */\nexport class FrameLoadingController extends Controller<HTMLElement> {\n static override targets = [\"content\", \"skeleton\", \"overlay\"];\n static override values = {\n minDuration: { type: Number, default: 0 },\n restoreFocus: { type: Boolean, default: true },\n };\n static events = [\"start\", \"end\"] as const;\n\n declare readonly contentTarget: HTMLElement;\n declare readonly skeletonTarget: HTMLElement;\n declare readonly overlayTarget: HTMLElement;\n declare readonly hasContentTarget: boolean;\n declare readonly hasSkeletonTarget: boolean;\n declare readonly hasOverlayTarget: boolean;\n\n declare minDurationValue: number;\n declare restoreFocusValue: boolean;\n\n readonly #timeouts = new SafeTimeout();\n #loading = false;\n #startedAt = 0;\n #inertApplied = false;\n #previousFocus: HTMLElement | null = null;\n /** The id of the retreated element, used to re-find it if the load replaced it. */\n #previousFocusId = \"\";\n\n readonly #onStart = (): void => {\n // A (possibly new) fetch began: cancel any pending min-duration finish so the\n // loading state is not torn down mid-load, then begin if not already loading.\n this.#timeouts.clearAll();\n if (!this.#loading) this.#begin();\n };\n\n readonly #onEnd = (): void => {\n if (!this.#loading) return;\n const remaining = this.minDurationValue - (Date.now() - this.#startedAt);\n if (remaining > 0) {\n this.#timeouts.clearAll();\n this.#timeouts.set(() => this.#finish(), remaining);\n } else {\n this.#finish();\n }\n };\n\n override connect(): void {\n this.element.addEventListener(\"turbo:before-fetch-request\", this.#onStart);\n this.element.addEventListener(\"turbo:frame-load\", this.#onEnd);\n this.element.addEventListener(\"turbo:fetch-request-error\", this.#onEnd);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"turbo:before-fetch-request\", this.#onStart);\n this.element.removeEventListener(\"turbo:frame-load\", this.#onEnd);\n this.element.removeEventListener(\"turbo:fetch-request-error\", this.#onEnd);\n this.#timeouts.clearAll();\n // Tidy the hooks so a cached frame is not restored mid-loading (no focus move —\n // the element is leaving the DOM).\n if (this.#loading) {\n this.element.removeAttribute(\"aria-busy\");\n this.element.removeAttribute(\"data-frame-loading\");\n this.#clearInert();\n }\n this.#loading = false;\n this.#previousFocus = null;\n }\n\n /** Enters the loading state: hooks, skeleton/overlay, inert content, focus retreat. */\n #begin(): void {\n this.#loading = true;\n this.#startedAt = Date.now();\n this.element.setAttribute(\"aria-busy\", \"true\");\n this.element.setAttribute(\"data-frame-loading\", \"true\");\n if (this.hasSkeletonTarget) this.skeletonTarget.hidden = false;\n if (this.hasOverlayTarget) this.overlayTarget.hidden = false;\n this.#applyInert();\n this.#retreatFocus();\n this.dispatch(\"start\", { detail: {} });\n }\n\n /** Leaves the loading state: restore hooks, hide skeleton/overlay, restore focus. */\n #finish(): void {\n this.#loading = false;\n this.element.removeAttribute(\"aria-busy\");\n this.element.removeAttribute(\"data-frame-loading\");\n if (this.hasSkeletonTarget) this.skeletonTarget.hidden = true;\n if (this.hasOverlayTarget) this.overlayTarget.hidden = true;\n this.#clearInert();\n this.#restoreFocus();\n this.dispatch(\"end\", { detail: {} });\n }\n\n /** Marks the content inert to block double-submits while stale (if we own it). */\n #applyInert(): void {\n if (!this.hasContentTarget || this.contentTarget.hasAttribute(\"inert\")) return;\n this.contentTarget.setAttribute(\"inert\", \"\");\n this.#inertApplied = true;\n }\n\n #clearInert(): void {\n if (!this.#inertApplied) return;\n this.#inertApplied = false;\n if (this.hasContentTarget) this.contentTarget.removeAttribute(\"inert\");\n }\n\n /** Saves and blurs focus if it sits inside the frame about to go stale. */\n #retreatFocus(): void {\n this.#previousFocus = null;\n this.#previousFocusId = \"\";\n if (!this.restoreFocusValue) return;\n const active = document.activeElement;\n if (active instanceof HTMLElement && active !== this.element && this.element.contains(active)) {\n this.#previousFocus = active;\n this.#previousFocusId = active.id;\n active.blur();\n }\n }\n\n /**\n * Restores focus after the load. The same node when it survived (e.g. a\n * non-replacing update), else the element re-rendered with the same id inside the\n * frame — Turbo frames typically re-emit the same controls. When neither is present\n * (an anonymous control was replaced) focus is left where the browser put it, to\n * avoid an unexpected jump (WCAG 3.2.x).\n */\n #restoreFocus(): void {\n const target = this.#previousFocus;\n const id = this.#previousFocusId;\n this.#previousFocus = null;\n this.#previousFocusId = \"\";\n if (!this.restoreFocusValue) return;\n if (target?.isConnected) {\n target.focus();\n return;\n }\n if (id) {\n const replacement = document.getElementById(id);\n if (replacement && this.element.contains(replacement)) replacement.focus();\n }\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/frame_loading_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,mBAAe,IAAI,GAAA,EAAsB;AAAA;AAA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AA,EACvE;AAAA;AAAA,EAGA,aAAA,GAAsB;AACpB,IAAA,IAAA,CAAK,cAAA,GAAiB,IAAA;AACtB,IAAA,IAAA,CAAK,gBAAA,GAAmB,EAAA;AACxB,IAAA,IAAI,CAAC,KAAK,iBAAA,EAAmB;AAC7B,IAAA,MAAM,SAAS,QAAA,CAAS,aAAA;AACxB,IAAA,IAAI,MAAA,YAAkB,eAAe,MAAA,KAAW,IAAA,CAAK,WAAW,IAAA,CAAK,OAAA,CAAQ,QAAA,CAAS,MAAM,CAAA,EAAG;AAC7F,MAAA,IAAA,CAAK,cAAA,GAAiB,MAAA;AACtB,MAAA,IAAA,CAAK,mBAAmB,MAAA,CAAO,EAAA;AAC/B,MAAA,MAAA,CAAO,IAAA,EAAK;AAAA,IACd;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,aAAA,GAAsB;AACpB,IAAA,MAAM,SAAS,IAAA,CAAK,cAAA;AACpB,IAAA,MAAM,KAAK,IAAA,CAAK,gBAAA;AAChB,IAAA,IAAA,CAAK,cAAA,GAAiB,IAAA;AACtB,IAAA,IAAA,CAAK,gBAAA,GAAmB,EAAA;AACxB,IAAA,IAAI,CAAC,KAAK,iBAAA,EAAmB;AAC7B,IAAA,IAAI,QAAQ,WAAA,EAAa;AACvB,MAAA,MAAA,CAAO,KAAA,EAAM;AACb,MAAA;AAAA,IACF;AACA,IAAA,IAAI,EAAA,EAAI;AACN,MAAA,MAAM,WAAA,GAAc,QAAA,CAAS,cAAA,CAAe,EAAE,CAAA;AAC9C,MAAA,IAAI,eAAe,IAAA,CAAK,OAAA,CAAQ,SAAS,WAAW,CAAA,cAAe,KAAA,EAAM;AAAA,IAC3E;AAAA,EACF;AACF","file":"frame_loading_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 `<turbo-frame>` loading-state behavior: while the frame is fetching it\n * sets `aria-busy` + `data-frame-loading`, reveals an optional skeleton / overlay,\n * suppresses interaction with the stale content, and retreats focus, restoring it on\n * completion (no dedicated APG pattern; supports WCAG 2.2 **4.1.3 Status Messages**\n * via `aria-busy` and 2.4.3 focus order via the retreat/restore).\n *\n * Markup contract (identifier: `stimeo--frame-loading`):\n * <turbo-frame id=\"panel\" data-controller=\"stimeo--frame-loading\">\n * <div data-stimeo--frame-loading-target=\"skeleton\" hidden>…</div>\n * <div data-stimeo--frame-loading-target=\"content\">…</div>\n * </turbo-frame>\n *\n * It subscribes on the frame to Turbo's own fetch lifecycle: `turbo:before-fetch-request`\n * (which bubbles from the frame's links/forms or the frame itself) starts the loading\n * state, and `turbo:frame-load` ends it (with `turbo:fetch-request-error` as a safety\n * net so the state never sticks). `minDuration` keeps the skeleton up long enough to\n * avoid a flicker.\n *\n * @remarks\n * Behavior only — it ships no skeleton markup or styling (pair with Skeleton/CSS);\n * loading is held purely in `aria-busy` / `data-frame-loading` and the optional\n * targets' `hidden`. The `content` target is marked `inert` while loading to block\n * double-submits, and focus inside the frame is explicitly blurred then restored\n * (when `restoreFocus`) so it is testable without relying on emergent `inert`\n * focus behavior. Listeners are torn down on `disconnect()` (Turbo navigation\n * included) along with the {@link MinDurationFloor} holding the finish back, kept\n * across an in-page move by {@link DetachGate}; the hooks a cached page would\n * freeze are rewound by {@link BeforeCacheReset}.\n */\nexport class FrameLoadingController extends Controller<HTMLElement> {\n static override targets = [\"content\", \"skeleton\", \"overlay\"];\n static override values = {\n announceText: { type: String, default: \"\" },\n announceReadyText: { type: String, default: \"\" },\n minDuration: { type: Number, default: 0 },\n restoreFocus: { type: Boolean, default: true },\n };\n static events = [\"start\", \"end\"] as const;\n\n declare readonly contentTarget: HTMLElement;\n declare readonly skeletonTarget: HTMLElement;\n declare readonly overlayTarget: HTMLElement;\n declare readonly hasContentTarget: boolean;\n declare readonly hasSkeletonTarget: boolean;\n declare readonly hasOverlayTarget: boolean;\n\n declare minDurationValue: number;\n declare restoreFocusValue: boolean;\n declare announceTextValue: string;\n declare announceReadyTextValue: string;\n\n readonly #timeouts = new SafeTimeout();\n readonly #floor = new MinDurationFloor(this.#timeouts);\n readonly #gate = new DetachGate();\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n #loading = false;\n #inertApplied = false;\n #previousFocus: HTMLElement | null = null;\n /** The id of the retreated element, used to re-find it if the load replaced it. */\n #previousFocusId = \"\";\n\n readonly #onStart = (): void => {\n // A (possibly new) fetch began: drop a finish the floor is still holding so the\n // loading state is not torn down mid-load, then begin if not already loading.\n this.#floor.cancel();\n if (!this.#loading) this.#begin();\n };\n\n readonly #onEnd = (): void => {\n if (!this.#loading) return;\n // The newest end signal owns the finish: the floor replaces whatever it was\n // holding rather than letting a second wait stack behind the first.\n this.#floor.schedule(this.minDurationValue, () => this.#finish());\n };\n\n override connect(): void {\n this.#gate.cancel();\n this.#beforeCache.activate();\n this.element.addEventListener(\"turbo:before-fetch-request\", this.#onStart);\n this.element.addEventListener(\"turbo:frame-load\", this.#onEnd);\n this.element.addEventListener(\"turbo:fetch-request-error\", this.#onEnd);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"turbo:before-fetch-request\", this.#onStart);\n this.element.removeEventListener(\"turbo:frame-load\", this.#onEnd);\n this.element.removeEventListener(\"turbo:fetch-request-error\", this.#onEnd);\n this.#beforeCache.deactivate();\n this.#gate.disconnected(this, () => this.#teardown());\n }\n\n /**\n * Drops the held finish and the loading bookkeeping on a real detach. The markup\n * keeps whatever it last held: the page being cached is rewound at\n * `turbo:before-cache` instead, where the frame is still whole.\n */\n #teardown(): void {\n this.#gate.cancel();\n this.#timeouts.clearAll();\n this.#floor.cancel();\n this.#loading = false;\n this.#previousFocus = null;\n }\n\n /**\n * Returns the frame to its resting hooks for the snapshot Turbo is about to\n * take, so a page reached with the Back button does not restore a frame that is\n * busy and inert with nothing left to finish it. State only — no `end` event and\n * no focus move, because the load did not actually complete. The live page keeps\n * its held finish, so a navigation that never completes still ends properly.\n */\n #rewindForCache(): void {\n if (!this.#loading) return;\n this.element.removeAttribute(\"aria-busy\");\n this.element.removeAttribute(\"data-frame-loading\");\n if (this.hasSkeletonTarget) this.skeletonTarget.hidden = true;\n if (this.hasOverlayTarget) this.overlayTarget.hidden = true;\n this.#clearInert();\n }\n\n /** Enters the loading state: hooks, skeleton/overlay, inert content, focus retreat. */\n #begin(): void {\n this.#loading = true;\n this.#floor.begin();\n this.element.setAttribute(\"aria-busy\", \"true\");\n this.element.setAttribute(\"data-frame-loading\", \"true\");\n if (this.hasSkeletonTarget) this.skeletonTarget.hidden = false;\n if (this.hasOverlayTarget) this.overlayTarget.hidden = false;\n this.#applyInert();\n this.#retreatFocus();\n this.dispatch(\"start\", { detail: {} });\n announce(fillTemplate(this.announceTextValue, {}));\n }\n\n /** Leaves the loading state: restore hooks, hide skeleton/overlay, restore focus. */\n #finish(): void {\n this.#loading = false;\n this.element.removeAttribute(\"aria-busy\");\n this.element.removeAttribute(\"data-frame-loading\");\n if (this.hasSkeletonTarget) this.skeletonTarget.hidden = true;\n if (this.hasOverlayTarget) this.overlayTarget.hidden = true;\n this.#clearInert();\n this.#restoreFocus();\n this.dispatch(\"end\", { detail: {} });\n announce(fillTemplate(this.announceReadyTextValue, {}));\n }\n\n /** Marks the content inert to block double-submits while stale (if we own it). */\n #applyInert(): void {\n if (!this.hasContentTarget || this.contentTarget.hasAttribute(\"inert\")) return;\n this.contentTarget.setAttribute(\"inert\", \"\");\n this.#inertApplied = true;\n }\n\n #clearInert(): void {\n if (!this.#inertApplied) return;\n this.#inertApplied = false;\n if (this.hasContentTarget) this.contentTarget.removeAttribute(\"inert\");\n }\n\n /** Saves and blurs focus if it sits inside the frame about to go stale. */\n #retreatFocus(): void {\n this.#previousFocus = null;\n this.#previousFocusId = \"\";\n if (!this.restoreFocusValue) return;\n const active = document.activeElement;\n if (active instanceof HTMLElement && active !== this.element && this.element.contains(active)) {\n this.#previousFocus = active;\n this.#previousFocusId = active.id;\n active.blur();\n }\n }\n\n /**\n * Restores focus after the load. The same node when it survived (e.g. a\n * non-replacing update), else the element re-rendered with the same id inside the\n * frame — Turbo frames typically re-emit the same controls. When neither is present\n * (an anonymous control was replaced) focus is left where the browser put it, to\n * avoid an unexpected jump (WCAG 3.2.x).\n */\n #restoreFocus(): void {\n const target = this.#previousFocus;\n const id = this.#previousFocusId;\n this.#previousFocus = null;\n this.#previousFocusId = \"\";\n if (!this.restoreFocusValue) return;\n if (target?.isConnected) {\n target.focus();\n return;\n }\n if (id) {\n const replacement = document.getElementById(id);\n if (replacement && this.element.contains(replacement)) replacement.focus();\n }\n }\n}\n"]}
@@ -20,9 +20,14 @@ import { Controller } from '@hotwired/stimulus';
20
20
  * Behavior only. The machine-readable `datetime` (UTC) is left untouched so
21
21
  * assistive tech and crawlers keep the canonical value while only the display
22
22
  * text — and an optional `title` — change. Formatting is a pure function of
23
- * `datetime` with no module-scope state, listeners, or timers, so a Turbo Drive
24
- * cache restore or morph re-runs `connect()` and stays consistent. A parse or
25
- * `Intl` error leaves the authored absolute text in place rather than throwing.
23
+ * `datetime` with no module-scope state or timers, so a Turbo Drive cache restore
24
+ * re-runs `connect()` and stays consistent. A parse or `Intl` error leaves the
25
+ * authored absolute text in place rather than throwing.
26
+ *
27
+ * Render inputs are followed at runtime: a morph that swaps a Value or the
28
+ * `datetime` attribute on the live element — which keeps the element, so
29
+ * `connect()` never runs again — repaints through one coalesced pass
30
+ * ({@link MicrotaskCoalescer}) rather than leaving a stale reading on screen.
26
31
  */
27
32
  declare class LocalTimeController extends Controller<HTMLElement> {
28
33
  #private;
@@ -55,6 +60,17 @@ declare class LocalTimeController extends Controller<HTMLElement> {
55
60
  timeStyleValue: string;
56
61
  titleFormatValue: string;
57
62
  connect(): void;
63
+ disconnect(): void;
64
+ /** Repaints when application code (or a Turbo morph) changes `locale` at runtime. */
65
+ localeValueChanged(): void;
66
+ /** Repaints when application code (or a Turbo morph) changes `timeZone` at runtime. */
67
+ timeZoneValueChanged(): void;
68
+ /** Repaints when application code (or a Turbo morph) changes `dateStyle` at runtime. */
69
+ dateStyleValueChanged(): void;
70
+ /** Repaints when application code (or a Turbo morph) changes `timeStyle` at runtime. */
71
+ timeStyleValueChanged(): void;
72
+ /** Repaints when application code (or a Turbo morph) changes `titleFormat` at runtime. */
73
+ titleFormatValueChanged(): void;
58
74
  }
59
75
 
60
76
  export { LocalTimeController };
@@ -1,5 +1,40 @@
1
1
  import { Controller } from '@hotwired/stimulus';
2
2
 
3
+ // src/controllers/local_time_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/local_time_controller.ts
4
39
  var STYLES = /* @__PURE__ */ new Set(["full", "long", "medium", "short"]);
5
40
  function toStyle(value) {
@@ -14,7 +49,53 @@ var LocalTimeController = class extends Controller {
14
49
  titleFormat: { type: String, default: "" }
15
50
  };
16
51
  static events = ["format"];
52
+ /** Collapses a morph that swaps several render inputs at once into one repaint. */
53
+ #resync = new MicrotaskCoalescer(() => this.#render());
54
+ /**
55
+ * Watches the one render input that is not a Value. Only `datetime` is filtered
56
+ * in, so the text and `title` this controller writes cannot re-enter the pass.
57
+ */
58
+ #datetimeWatch = new MutationObserver(() => {
59
+ this.#resync.schedule();
60
+ });
17
61
  connect() {
62
+ this.#resync.activate();
63
+ this.#datetimeWatch.observe(this.element, { attributeFilter: ["datetime"] });
64
+ this.#render();
65
+ }
66
+ disconnect() {
67
+ this.#resync.cancel();
68
+ this.#datetimeWatch.disconnect();
69
+ }
70
+ /** Repaints when application code (or a Turbo morph) changes `locale` at runtime. */
71
+ localeValueChanged() {
72
+ this.#resync.schedule();
73
+ }
74
+ /** Repaints when application code (or a Turbo morph) changes `timeZone` at runtime. */
75
+ timeZoneValueChanged() {
76
+ this.#resync.schedule();
77
+ }
78
+ /** Repaints when application code (or a Turbo morph) changes `dateStyle` at runtime. */
79
+ dateStyleValueChanged() {
80
+ this.#resync.schedule();
81
+ }
82
+ /** Repaints when application code (or a Turbo morph) changes `timeStyle` at runtime. */
83
+ timeStyleValueChanged() {
84
+ this.#resync.schedule();
85
+ }
86
+ /** Repaints when application code (or a Turbo morph) changes `titleFormat` at runtime. */
87
+ titleFormatValueChanged() {
88
+ this.#resync.schedule();
89
+ }
90
+ /**
91
+ * Formats the instant in `datetime` against the current Values and writes it out.
92
+ *
93
+ * The `format` event rides with every pass, including a repaint a morph triggers:
94
+ * its condition is that formatting was applied, and a repaint applies it with a
95
+ * new result. A pass that cannot format writes nothing and emits nothing, so the
96
+ * authored absolute text stays as the fallback.
97
+ */
98
+ #render() {
18
99
  const date = this.#parse();
19
100
  if (date === null) return;
20
101
  const formatted = this.#applyFormat(date, this.dateStyleValue, this.timeStyleValue);
@@ -24,7 +105,10 @@ var LocalTimeController = class extends Controller {
24
105
  if (title !== null) this.element.setAttribute("title", title);
25
106
  this.dispatch("format", { detail: { formatted } });
26
107
  }
27
- /** Parses the UTC `datetime` attribute into a {@link Date}, or `null`. */
108
+ /**
109
+ * Parses the UTC `datetime` attribute into a {@link Date}, or `null`. Whitespace
110
+ * around the attribute value is tolerated.
111
+ */
28
112
  #parse() {
29
113
  const raw = this.element.getAttribute("datetime");
30
114
  if (!raw) return null;
@@ -37,11 +121,21 @@ var LocalTimeController = class extends Controller {
37
121
  * the *runtime's* local zone, contradicting "the server emits UTC". Values that
38
122
  * already carry `Z` or a `±hh:mm` offset (and bare `YYYY-MM-DD` dates, already
39
123
  * parsed as UTC) are returned unchanged.
124
+ *
125
+ * HTML accepts a space where ISO 8601 wants `T`, and `Date.parse` of that form is
126
+ * left to each engine, so a whole value shaped that way is normalized to the `T`
127
+ * separator first. The pattern is anchored: a value trailing anything else — a
128
+ * zone word such as `"2026-06-08 12:30:00 UTC"` — is handed to `Date.parse` as
129
+ * authored instead of being turned into a string nothing can parse.
40
130
  */
41
131
  #asUtc(value) {
42
- const hasTime = /T\d{2}:\d{2}/.test(value);
43
- const hasZone = /(Z|[+-]\d{2}:?\d{2})$/.test(value);
44
- return hasTime && !hasZone ? `${value}Z` : value;
132
+ const isoLike = value.replace(
133
+ /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)$/,
134
+ "$1T$2"
135
+ );
136
+ const hasTime = /T\d{2}:\d{2}/.test(isoLike);
137
+ const hasZone = /(Z|[+-]\d{2}:?\d{2})$/.test(isoLike);
138
+ return hasTime && !hasZone ? `${isoLike}Z` : isoLike;
45
139
  }
46
140
  /**
47
141
  * Builds the optional detailed `title`. `titleFormat` is an `Intl` style
@@ -70,9 +164,9 @@ var LocalTimeController = class extends Controller {
70
164
  return null;
71
165
  }
72
166
  }
73
- /** Locale precedence: the value, then the element's `lang`, then the document's. */
167
+ /** Locale precedence: the value, then the nearest `lang` up the ancestor chain. */
74
168
  get #locale() {
75
- return this.localeValue || this.element.lang || document.documentElement.lang || void 0;
169
+ return this.localeValue || this.element.closest("[lang]")?.getAttribute("lang") || void 0;
76
170
  }
77
171
  };
78
172
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/controllers/local_time_controller.ts"],"names":[],"mappings":";;;AAMA,IAAM,MAAA,uBAAa,GAAA,CAAmB,CAAC,QAAQ,MAAA,EAAQ,QAAA,EAAU,OAAO,CAAC,CAAA;AAGzE,SAAS,QAAQ,KAAA,EAA0C;AACzD,EAAA,OAAQ,MAAA,CAAuB,GAAA,CAAI,KAAK,CAAA,GAAK,KAAA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,CAAe,IAAA,CAAK,SAAS,OAAO,CAAA,CAAE,OAAO,IAAI,CAAA;AAAA,IACnE,CAAA,CAAA,MAAQ;AAGN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,OAAA,GAA8B;AAChC,IAAA,OAAO,KAAK,WAAA,IAAe,IAAA,CAAK,QAAQ,IAAA,IAAQ,QAAA,CAAS,gBAAgB,IAAA,IAAQ,MAAA;AAAA,EACnF;AACF","file":"local_time_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/** A date/time style keyword accepted by `Intl` `dateStyle` / `timeStyle`. */\ntype DateTimeStyle = \"full\" | \"long\" | \"medium\" | \"short\";\n\n/** The valid `Intl` style keywords, used to validate the string-typed values. */\nconst STYLES = new Set<DateTimeStyle>([\"full\", \"long\", \"medium\", \"short\"]);\n\n/** Narrows an arbitrary string to a valid {@link DateTimeStyle}, or `undefined`. */\nfunction toStyle(value: string): DateTimeStyle | undefined {\n return (STYLES as Set<string>).has(value) ? (value as DateTimeStyle) : undefined;\n}\n\n/**\n * Headless local-time behavior: renders the UTC instant in a `<time datetime>`\n * as an absolute, viewer-localized string via `Intl.DateTimeFormat`. No\n * dedicated APG pattern; it follows the HTML `<time>` semantics.\n *\n * Markup contract (identifier: `stimeo--local-time`):\n * <time datetime=\"2026-06-08T12:30:00Z\"\n * data-controller=\"stimeo--local-time\"\n * data-stimeo--local-time-date-style-value=\"medium\"\n * data-stimeo--local-time-time-style-value=\"short\">2026-06-08 12:30 UTC</time>\n *\n * The server emits UTC (cache-friendly — it never needs to know the viewer's\n * timezone), and the controller reformats the visible text into the viewer's\n * locale/zone on connect. This is the *absolute* localization axis, distinct from\n * {@link RelativeTimeController}'s \"3 minutes ago\".\n *\n * @remarks\n * Behavior only. The machine-readable `datetime` (UTC) is left untouched so\n * assistive tech and crawlers keep the canonical value while only the display\n * text — and an optional `title` — change. Formatting is a pure function of\n * `datetime` with no module-scope state, listeners, or timers, so a Turbo Drive\n * cache restore or morph re-runs `connect()` and stays consistent. A parse or\n * `Intl` error leaves the authored absolute text in place rather than throwing.\n */\nexport class LocalTimeController extends Controller<HTMLElement> {\n static override values = {\n locale: { type: String, default: \"\" },\n timeZone: { type: String, default: \"\" },\n dateStyle: { type: String, default: \"medium\" },\n timeStyle: { type: String, default: \"short\" },\n titleFormat: { type: String, default: \"\" },\n };\n static events = [\"format\"] as const;\n\n declare localeValue: string;\n declare timeZoneValue: string;\n declare dateStyleValue: string;\n declare timeStyleValue: string;\n declare titleFormatValue: string;\n\n override connect(): void {\n const date = this.#parse();\n if (date === null) return;\n\n const formatted = this.#applyFormat(date, this.dateStyleValue, this.timeStyleValue);\n if (formatted === null) return;\n\n // Only the visible text (and optional title) change; `datetime` is the\n // immutable machine-readable source and is never rewritten.\n this.element.textContent = formatted;\n\n const title = this.#title(date);\n if (title !== null) this.element.setAttribute(\"title\", title);\n\n this.dispatch(\"format\", { detail: { formatted } });\n }\n\n /** Parses the UTC `datetime` attribute into a {@link Date}, or `null`. */\n #parse(): Date | null {\n const raw = this.element.getAttribute(\"datetime\");\n if (!raw) return null;\n const ms = Date.parse(this.#asUtc(raw.trim()));\n return Number.isNaN(ms) ? null : new Date(ms);\n }\n\n /**\n * Reads a timezone-less date-time as UTC — the input contract of this\n * controller — since `Date.parse` would otherwise read `\"2026-06-08T12:30:00\"` in\n * the *runtime's* local zone, contradicting \"the server emits UTC\". Values that\n * already carry `Z` or a `±hh:mm` offset (and bare `YYYY-MM-DD` dates, already\n * parsed as UTC) are returned unchanged.\n */\n #asUtc(value: string): string {\n const hasTime = /T\\d{2}:\\d{2}/.test(value);\n const hasZone = /(Z|[+-]\\d{2}:?\\d{2})$/.test(value);\n return hasTime && !hasZone ? `${value}Z` : value;\n }\n\n /**\n * Builds the optional detailed `title`. `titleFormat` is an `Intl` style\n * keyword applied to *both* date and time; empty (the default) adds no title.\n */\n #title(date: Date): string | null {\n if (this.titleFormatValue.length === 0) return null;\n return this.#applyFormat(date, this.titleFormatValue, this.titleFormatValue);\n }\n\n /**\n * Formats `date` with `Intl.DateTimeFormat`, including each style only when it\n * is a valid keyword (so a consumer can show date-only or time-only by clearing\n * the other). Returns `null` when neither style is usable or `Intl` throws, so\n * the caller can leave the authored text untouched.\n */\n #applyFormat(date: Date, dateStyle: string, timeStyle: string): string | null {\n // `toStyle` yields `undefined` for an empty/invalid keyword; assigning it is\n // equivalent to omitting the option, so a consumer can show date- or time-only.\n const options: Intl.DateTimeFormatOptions = {\n dateStyle: toStyle(dateStyle),\n timeStyle: toStyle(timeStyle),\n };\n if (options.dateStyle === undefined && options.timeStyle === undefined) return null;\n if (this.timeZoneValue.length > 0) options.timeZone = this.timeZoneValue;\n\n try {\n return new Intl.DateTimeFormat(this.#locale, options).format(date);\n } catch {\n // An invalid locale / timeZone (or unsupported style) must not break the\n // page; the authored absolute text remains as the graceful fallback.\n return null;\n }\n }\n\n /** Locale precedence: the value, then the element's `lang`, then the document's. */\n get #locale(): string | undefined {\n return this.localeValue || this.element.lang || document.documentElement.lang || undefined;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/microtask_coalescer.ts","../../src/controllers/local_time_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;AAAA;AAAA,EAGA,MAAA,GAAe;AACb,IAAA,IAAA,CAAK,OAAA,GAAU,KAAA;AACf,IAAA,IAAA,CAAK,OAAA,GAAU,KAAA;AACf,IAAA,IAAA,CAAK,WAAA,IAAe,CAAA;AAAA,EACtB;AAAA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CAAA,EAAG,OAAO,IAAA;AAC/C,IAAA,OAAO,KAAK,YAAA,CAAa,IAAA,EAAM,IAAA,CAAK,gBAAA,EAAkB,KAAK,gBAAgB,CAAA;AAAA,EAC7E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,YAAA,CAAa,IAAA,EAAY,SAAA,EAAmB,SAAA,EAAkC;AAG5E,IAAA,MAAM,OAAA,GAAsC;AAAA,MAC1C,SAAA,EAAW,QAAQ,SAAS,CAAA;AAAA,MAC5B,SAAA,EAAW,QAAQ,SAAS;AAAA,KAC9B;AACA,IAAA,IAAI,QAAQ,SAAA,KAAc,MAAA,IAAa,OAAA,CAAQ,SAAA,KAAc,QAAW,OAAO,IAAA;AAC/E,IAAA,IAAI,KAAK,aAAA,CAAc,MAAA,GAAS,CAAA,EAAG,OAAA,CAAQ,WAAW,IAAA,CAAK,aAAA;AAE3D,IAAA,IAAI;AACF,MAAA,OAAO,IAAI,KAAK,cAAA,CAAe,IAAA,CAAK,SAAS,OAAO,CAAA,CAAE,OAAO,IAAI,CAAA;AAAA,IACnE,CAAA,CAAA,MAAQ;AAGN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,OAAA,GAA8B;AAChC,IAAA,OAAO,IAAA,CAAK,eAAe,IAAA,CAAK,OAAA,CAAQ,QAAQ,QAAQ,CAAA,EAAG,YAAA,CAAa,MAAM,CAAA,IAAK,MAAA;AAAA,EACrF;AACF","file":"local_time_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/** A date/time style keyword accepted by `Intl` `dateStyle` / `timeStyle`. */\ntype DateTimeStyle = \"full\" | \"long\" | \"medium\" | \"short\";\n\n/** The valid `Intl` style keywords, used to validate the string-typed values. */\nconst STYLES = new Set<DateTimeStyle>([\"full\", \"long\", \"medium\", \"short\"]);\n\n/** Narrows an arbitrary string to a valid {@link DateTimeStyle}, or `undefined`. */\nfunction toStyle(value: string): DateTimeStyle | undefined {\n return (STYLES as Set<string>).has(value) ? (value as DateTimeStyle) : undefined;\n}\n\n/**\n * Headless local-time behavior: renders the UTC instant in a `<time datetime>`\n * as an absolute, viewer-localized string via `Intl.DateTimeFormat`. No\n * dedicated APG pattern; it follows the HTML `<time>` semantics.\n *\n * Markup contract (identifier: `stimeo--local-time`):\n * <time datetime=\"2026-06-08T12:30:00Z\"\n * data-controller=\"stimeo--local-time\"\n * data-stimeo--local-time-date-style-value=\"medium\"\n * data-stimeo--local-time-time-style-value=\"short\">2026-06-08 12:30 UTC</time>\n *\n * The server emits UTC (cache-friendly — it never needs to know the viewer's\n * timezone), and the controller reformats the visible text into the viewer's\n * locale/zone on connect. This is the *absolute* localization axis, distinct from\n * {@link RelativeTimeController}'s \"3 minutes ago\".\n *\n * @remarks\n * Behavior only. The machine-readable `datetime` (UTC) is left untouched so\n * assistive tech and crawlers keep the canonical value while only the display\n * text — and an optional `title` — change. Formatting is a pure function of\n * `datetime` with no module-scope state or timers, so a Turbo Drive cache restore\n * re-runs `connect()` and stays consistent. A parse or `Intl` error leaves the\n * authored absolute text in place rather than throwing.\n *\n * Render inputs are followed at runtime: a morph that swaps a Value or the\n * `datetime` attribute on the live element — which keeps the element, so\n * `connect()` never runs again — repaints through one coalesced pass\n * ({@link MicrotaskCoalescer}) rather than leaving a stale reading on screen.\n */\nexport class LocalTimeController extends Controller<HTMLElement> {\n static override values = {\n locale: { type: String, default: \"\" },\n timeZone: { type: String, default: \"\" },\n dateStyle: { type: String, default: \"medium\" },\n timeStyle: { type: String, default: \"short\" },\n titleFormat: { type: String, default: \"\" },\n };\n static events = [\"format\"] as const;\n\n declare localeValue: string;\n declare timeZoneValue: string;\n declare dateStyleValue: string;\n declare timeStyleValue: string;\n declare titleFormatValue: string;\n\n /** Collapses a morph that swaps several render inputs at once into one repaint. */\n readonly #resync = new MicrotaskCoalescer(() => this.#render());\n /**\n * Watches the one render input that is not a Value. Only `datetime` is filtered\n * in, so the text and `title` this controller writes cannot re-enter the pass.\n */\n readonly #datetimeWatch = new MutationObserver(() => {\n this.#resync.schedule();\n });\n\n override connect(): void {\n this.#resync.activate();\n this.#datetimeWatch.observe(this.element, { attributeFilter: [\"datetime\"] });\n this.#render();\n }\n\n override disconnect(): void {\n this.#resync.cancel();\n this.#datetimeWatch.disconnect();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `locale` at runtime. */\n localeValueChanged(): void {\n this.#resync.schedule();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `timeZone` at runtime. */\n timeZoneValueChanged(): void {\n this.#resync.schedule();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `dateStyle` at runtime. */\n dateStyleValueChanged(): void {\n this.#resync.schedule();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `timeStyle` at runtime. */\n timeStyleValueChanged(): void {\n this.#resync.schedule();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `titleFormat` at runtime. */\n titleFormatValueChanged(): void {\n this.#resync.schedule();\n }\n\n /**\n * Formats the instant in `datetime` against the current Values and writes it out.\n *\n * The `format` event rides with every pass, including a repaint a morph triggers:\n * its condition is that formatting was applied, and a repaint applies it with a\n * new result. A pass that cannot format writes nothing and emits nothing, so the\n * authored absolute text stays as the fallback.\n */\n #render(): void {\n const date = this.#parse();\n if (date === null) return;\n\n const formatted = this.#applyFormat(date, this.dateStyleValue, this.timeStyleValue);\n if (formatted === null) return;\n\n // Only the visible text (and optional title) change; `datetime` is the\n // immutable machine-readable source and is never rewritten.\n this.element.textContent = formatted;\n\n const title = this.#title(date);\n if (title !== null) this.element.setAttribute(\"title\", title);\n\n this.dispatch(\"format\", { detail: { formatted } });\n }\n\n /**\n * Parses the UTC `datetime` attribute into a {@link Date}, or `null`. Whitespace\n * around the attribute value is tolerated.\n */\n #parse(): Date | null {\n const raw = this.element.getAttribute(\"datetime\");\n if (!raw) return null;\n const ms = Date.parse(this.#asUtc(raw.trim()));\n return Number.isNaN(ms) ? null : new Date(ms);\n }\n\n /**\n * Reads a timezone-less date-time as UTC — the input contract of this\n * controller — since `Date.parse` would otherwise read `\"2026-06-08T12:30:00\"` in\n * the *runtime's* local zone, contradicting \"the server emits UTC\". Values that\n * already carry `Z` or a `±hh:mm` offset (and bare `YYYY-MM-DD` dates, already\n * parsed as UTC) are returned unchanged.\n *\n * HTML accepts a space where ISO 8601 wants `T`, and `Date.parse` of that form is\n * left to each engine, so a whole value shaped that way is normalized to the `T`\n * separator first. The pattern is anchored: a value trailing anything else — a\n * zone word such as `\"2026-06-08 12:30:00 UTC\"` — is handed to `Date.parse` as\n * authored instead of being turned into a string nothing can parse.\n */\n #asUtc(value: string): string {\n const isoLike = value.replace(\n /^(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}:?\\d{2})?)$/,\n \"$1T$2\",\n );\n const hasTime = /T\\d{2}:\\d{2}/.test(isoLike);\n const hasZone = /(Z|[+-]\\d{2}:?\\d{2})$/.test(isoLike);\n return hasTime && !hasZone ? `${isoLike}Z` : isoLike;\n }\n\n /**\n * Builds the optional detailed `title`. `titleFormat` is an `Intl` style\n * keyword applied to *both* date and time; empty (the default) adds no title.\n */\n #title(date: Date): string | null {\n if (this.titleFormatValue.length === 0) return null;\n return this.#applyFormat(date, this.titleFormatValue, this.titleFormatValue);\n }\n\n /**\n * Formats `date` with `Intl.DateTimeFormat`, including each style only when it\n * is a valid keyword (so a consumer can show date-only or time-only by clearing\n * the other). Returns `null` when neither style is usable or `Intl` throws, so\n * the caller can leave the authored text untouched.\n */\n #applyFormat(date: Date, dateStyle: string, timeStyle: string): string | null {\n // `toStyle` yields `undefined` for an empty/invalid keyword; assigning it is\n // equivalent to omitting the option, so a consumer can show date- or time-only.\n const options: Intl.DateTimeFormatOptions = {\n dateStyle: toStyle(dateStyle),\n timeStyle: toStyle(timeStyle),\n };\n if (options.dateStyle === undefined && options.timeStyle === undefined) return null;\n if (this.timeZoneValue.length > 0) options.timeZone = this.timeZoneValue;\n\n try {\n return new Intl.DateTimeFormat(this.#locale, options).format(date);\n } catch {\n // An invalid locale / timeZone (or unsupported style) must not break the\n // page; the authored absolute text remains as the graceful fallback.\n return null;\n }\n }\n\n /** Locale precedence: the value, then the nearest `lang` up the ancestor chain. */\n get #locale(): string | undefined {\n return this.localeValue || this.element.closest(\"[lang]\")?.getAttribute(\"lang\") || undefined;\n }\n}\n"]}