stimeo-ui 0.16.0 → 0.18.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 (117) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +136 -0
  3. data/README.md +27 -11
  4. data/dist/cable/index.js +384 -449
  5. data/dist/controllers/accordion_controller.js +174 -55
  6. data/dist/controllers/alert_dialog_controller.js +903 -235
  7. data/dist/controllers/announcer_controller.js +238 -205
  8. data/dist/controllers/aspect_ratio_controller.js +0 -10
  9. data/dist/controllers/auto_submit_controller.js +414 -145
  10. data/dist/controllers/avatar_controller.js +185 -107
  11. data/dist/controllers/breadcrumb_controller.js +0 -130
  12. data/dist/controllers/bulk_select_controller.js +282 -58
  13. data/dist/controllers/calendar_controller.js +228 -260
  14. data/dist/controllers/carousel_controller.js +536 -436
  15. data/dist/controllers/character_counter_controller.js +493 -207
  16. data/dist/controllers/checkbox_controller.js +38 -74
  17. data/dist/controllers/clipboard_controller.js +261 -149
  18. data/dist/controllers/collapsible_controller.js +304 -120
  19. data/dist/controllers/color_picker_controller.js +178 -146
  20. data/dist/controllers/combobox_controller.js +522 -156
  21. data/dist/controllers/command_palette_controller.js +1156 -395
  22. data/dist/controllers/conditional_fields_controller.js +300 -171
  23. data/dist/controllers/confirm_controller.js +980 -262
  24. data/dist/controllers/context_menu_controller.js +346 -153
  25. data/dist/controllers/count_up_controller.js +73 -21
  26. data/dist/controllers/countdown_controller.js +281 -158
  27. data/dist/controllers/currency_input_controller.js +575 -225
  28. data/dist/controllers/data_grid_controller.js +248 -214
  29. data/dist/controllers/date_range_picker_controller.js +338 -235
  30. data/dist/controllers/dialog_controller.js +899 -237
  31. data/dist/controllers/direct_upload_controller.js +97 -167
  32. data/dist/controllers/dirty_form_controller.js +72 -69
  33. data/dist/controllers/dismissible_controller.js +196 -24
  34. data/dist/controllers/drawer_controller.js +974 -355
  35. data/dist/controllers/dropdown_controller.js +339 -96
  36. data/dist/controllers/editable_controller.js +315 -88
  37. data/dist/controllers/empty_state_controller.js +79 -58
  38. data/dist/controllers/file_dropzone_controller.js +322 -211
  39. data/dist/controllers/filter_controller.js +77 -42
  40. data/dist/controllers/flash_controller.js +238 -347
  41. data/dist/controllers/focus_controller.js +679 -240
  42. data/dist/controllers/form_field_controller.js +156 -132
  43. data/dist/controllers/form_validation_controller.js +31 -97
  44. data/dist/controllers/frame_loading_controller.js +275 -217
  45. data/dist/controllers/highlight_controller.js +107 -75
  46. data/dist/controllers/hover_card_controller.js +327 -130
  47. data/dist/controllers/idle_controller.js +271 -101
  48. data/dist/controllers/input_mask_controller.js +483 -97
  49. data/dist/controllers/intersection_controller.js +150 -106
  50. data/dist/controllers/lazy_frame_controller.js +24 -68
  51. data/dist/controllers/listbox_controller.js +523 -240
  52. data/dist/controllers/local_time_controller.js +102 -77
  53. data/dist/controllers/masonry_controller.js +80 -96
  54. data/dist/controllers/menu_controller.js +302 -188
  55. data/dist/controllers/menubar_controller.js +232 -345
  56. data/dist/controllers/meter_controller.js +417 -87
  57. data/dist/controllers/multi_select_controller.js +785 -393
  58. data/dist/controllers/navigation_menu_controller.js +190 -250
  59. data/dist/controllers/nested_form_controller.js +396 -192
  60. data/dist/controllers/network_status_controller.js +268 -62
  61. data/dist/controllers/number_input_controller.js +610 -303
  62. data/dist/controllers/optimistic_controller.js +45 -87
  63. data/dist/controllers/otp_controller.js +658 -255
  64. data/dist/controllers/overflow_indicator_controller.js +122 -113
  65. data/dist/controllers/overflow_menu_controller.js +470 -295
  66. data/dist/controllers/pagination_controller.js +332 -123
  67. data/dist/controllers/password_reveal_controller.js +392 -121
  68. data/dist/controllers/password_strength_controller.js +111 -158
  69. data/dist/controllers/persist_controller.js +165 -111
  70. data/dist/controllers/pointer_drag_controller.js +434 -188
  71. data/dist/controllers/popover_controller.js +269 -113
  72. data/dist/controllers/portal_controller.js +215 -76
  73. data/dist/controllers/preview_guard_controller.js +243 -116
  74. data/dist/controllers/progress_controller.js +391 -78
  75. data/dist/controllers/radio_group_controller.js +278 -211
  76. data/dist/controllers/range_slider_controller.js +220 -113
  77. data/dist/controllers/rating_controller.js +458 -211
  78. data/dist/controllers/read_more_controller.js +138 -63
  79. data/dist/controllers/reading_progress_controller.js +166 -137
  80. data/dist/controllers/relative_time_controller.js +211 -112
  81. data/dist/controllers/{reset_before_cache_controller.js → reset_on_restore_controller.js} +103 -38
  82. data/dist/controllers/resizable_controller.js +299 -150
  83. data/dist/controllers/roving_controller.js +49 -88
  84. data/dist/controllers/scroll_area_controller.js +490 -246
  85. data/dist/controllers/scroll_restore_controller.js +14 -55
  86. data/dist/controllers/scroll_visibility_controller.js +432 -149
  87. data/dist/controllers/scrollspy_controller.js +193 -248
  88. data/dist/controllers/separator_controller.js +285 -142
  89. data/dist/controllers/sidebar_controller.js +1069 -404
  90. data/dist/controllers/skeleton_controller.js +259 -101
  91. data/dist/controllers/slider_controller.js +187 -86
  92. data/dist/controllers/smart_sticky_header_controller.js +173 -66
  93. data/dist/controllers/sortable_controller.js +26 -125
  94. data/dist/controllers/spinner_controller.js +288 -173
  95. data/dist/controllers/step_indicator_controller.js +105 -46
  96. data/dist/controllers/stepper_controller.js +120 -73
  97. data/dist/controllers/stick_to_bottom_controller.js +275 -140
  98. data/dist/controllers/sticky_observer_controller.js +220 -49
  99. data/dist/controllers/submit_once_controller.js +376 -227
  100. data/dist/controllers/switch_controller.js +201 -84
  101. data/dist/controllers/tabs_controller.js +41 -30
  102. data/dist/controllers/tags_input_controller.js +293 -173
  103. data/dist/controllers/textarea_autosize_controller.js +108 -74
  104. data/dist/controllers/theme_controller.js +140 -116
  105. data/dist/controllers/time_picker_controller.js +331 -127
  106. data/dist/controllers/toast_controller.js +244 -324
  107. data/dist/controllers/toggle_group_controller.js +252 -191
  108. data/dist/controllers/toolbar_controller.js +219 -120
  109. data/dist/controllers/tooltip_controller.js +158 -124
  110. data/dist/controllers/transition_controller.js +123 -119
  111. data/dist/controllers/tree_view_controller.js +283 -369
  112. data/dist/index.js +8573 -10410
  113. data/dist/positioning/index.js +154 -47
  114. data/lib/generators/stimeo/install/install_generator.rb +7 -2
  115. data/lib/generators/stimeo/install/templates/stimeo.js +19 -6
  116. data/lib/stimeo/ui/version.rb +1 -1
  117. metadata +3 -3
@@ -1,37 +1,52 @@
1
1
  import { Controller } from '@hotwired/stimulus';
2
2
 
3
- // src/controllers/relative_time_controller.ts
3
+ function setAttributeIfChanged(element, name, value, beforeWrite) {
4
+ if (element.getAttribute(name) === value) return false;
5
+ if (value === null) element.removeAttribute(name);
6
+ else element.setAttribute(name, value);
7
+ return true;
8
+ }
4
9
 
5
- // src/utils/before_cache_reset.ts
6
- var BeforeCacheReset = class _BeforeCacheReset {
7
- /** Every subscribed instance, iterated by the one shared document listener. */
8
- static #subscribers = /* @__PURE__ */ new Set();
9
- /** The shared listener; installed while at least one instance is subscribed. */
10
- static #onBeforeCache = () => {
11
- for (const subscriber of _BeforeCacheReset.#subscribers) subscriber.#rewind();
12
- };
13
- #rewind;
14
- /** @param rewind - the pass that returns this controller's state to its initial form. */
15
- constructor(rewind) {
16
- this.#rewind = rewind;
10
+ var DATETIME = /^([+-]\d{6}|\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
11
+ function readDatetime(element) {
12
+ const raw = element.getAttribute("datetime");
13
+ if (raw === null) return null;
14
+ const match = DATETIME.exec(raw.trim());
15
+ if (match === null) return null;
16
+ const [
17
+ ,
18
+ yearText,
19
+ monthText,
20
+ dayText,
21
+ hourText = "00",
22
+ minuteText = "00",
23
+ secondText = "00",
24
+ fraction = "",
25
+ zone = "Z"
26
+ ] = match;
27
+ const year = Number(yearText);
28
+ const month = Number(monthText);
29
+ const day = Number(dayText);
30
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
31
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
32
+ if (month < 1 || month > 12 || day < 1 || day > (days[month - 1] ?? 0)) return null;
33
+ const hour = Number(hourText);
34
+ const minute = Number(minuteText);
35
+ const second = Number(secondText);
36
+ if (hour === 24 && (minute !== 0 || second !== 0 || /[1-9]/.test(fraction))) return null;
37
+ let offset = zone;
38
+ if (zone !== "Z") {
39
+ const digits = zone.slice(1).replace(":", "");
40
+ const offsetHour = digits.slice(0, 2);
41
+ const offsetMinute = digits.slice(2);
42
+ offset = `${zone[0]}${offsetHour}:${offsetMinute}`;
17
43
  }
18
- /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */
19
- activate() {
20
- const first = _BeforeCacheReset.#subscribers.size === 0;
21
- _BeforeCacheReset.#subscribers.add(this);
22
- if (first) {
23
- document.addEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
24
- }
25
- }
26
- /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */
27
- deactivate() {
28
- _BeforeCacheReset.#subscribers.delete(this);
29
- if (_BeforeCacheReset.#subscribers.size > 0) return;
30
- document.removeEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
31
- }
32
- };
44
+ const milliseconds = fraction.slice(0, 3).padEnd(3, "0");
45
+ const canonical = `${yearText}-${monthText}-${dayText}T${hourText}:${minuteText}:${secondText}.${milliseconds}${offset}`;
46
+ const instant = Date.parse(canonical);
47
+ return Number.isNaN(instant) ? null : instant;
48
+ }
33
49
 
34
- // src/utils/intl_format.ts
35
50
  var formatters = /* @__PURE__ */ new WeakMap();
36
51
  function intlFormatter(factory, locale, options, fallbackLocale) {
37
52
  const cache = cacheFor(factory);
@@ -60,32 +75,40 @@ function construct(factory, locale, options, fallbackLocale) {
60
75
  }
61
76
  }
62
77
 
63
- // src/utils/locale.ts
64
78
  function resolveLocale(element, declared = "") {
65
79
  return declared || element.closest("[lang]")?.getAttribute("lang") || void 0;
66
80
  }
67
81
 
68
- // src/utils/microtask_coalescer.ts
82
+ var ListenerSet = class {
83
+ #abort = new AbortController();
84
+ add(target, type, handler, options) {
85
+ target.addEventListener(type, handler, { ...options, signal: this.#abort.signal });
86
+ }
87
+ dispose() {
88
+ this.#abort.abort();
89
+ this.#abort = new AbortController();
90
+ }
91
+ };
92
+
69
93
  var MicrotaskCoalescer = class {
70
94
  #run;
71
95
  #queued = false;
72
96
  #active = false;
73
97
  #generation = 0;
74
- /** @param run - the single reconciliation pass, invoked at most once per batch. */
75
98
  constructor(run) {
76
99
  this.#run = run;
77
100
  }
78
- /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */
79
101
  activate() {
80
102
  this.#active = true;
81
103
  }
82
- /** Closes the window and drops any pending pass; call from `disconnect()`. */
83
104
  cancel() {
84
105
  this.#active = false;
85
106
  this.#queued = false;
86
107
  this.#generation += 1;
87
108
  }
88
- /** Requests one pass after the batch settles. Idempotent; inert outside the window. */
109
+ get pending() {
110
+ return this.#queued;
111
+ }
89
112
  schedule() {
90
113
  if (!this.#active || this.#queued) return;
91
114
  this.#queued = true;
@@ -98,43 +121,99 @@ var MicrotaskCoalescer = class {
98
121
  }
99
122
  };
100
123
 
101
- // src/utils/safe_timeout.ts
124
+ var MorphRenderWatcher = class {
125
+ #listeners = new ListenerSet();
126
+ #pass;
127
+ #element = null;
128
+ #onMorph = () => this.#pass.schedule();
129
+ constructor(run) {
130
+ this.#pass = new MicrotaskCoalescer(run);
131
+ }
132
+ observe(element) {
133
+ if (this.#element === element) return;
134
+ this.disconnect();
135
+ this.#element = element;
136
+ this.#pass.activate();
137
+ this.#listeners.add(element, "turbo:morph-element", this.#onMorph);
138
+ }
139
+ schedule() {
140
+ this.#pass.schedule();
141
+ }
142
+ get pending() {
143
+ return this.#pass.pending;
144
+ }
145
+ disconnect() {
146
+ this.#listeners.dispose();
147
+ this.#pass.cancel();
148
+ this.#element = null;
149
+ }
150
+ };
151
+
152
+ var MAX_TIMER_DELAY_MS = 2147483647;
153
+
154
+ var NUMBER_BOUNDS = {
155
+ nonNegative: { finite: true, min: 0 },
156
+ timer: { finite: true, min: 0, max: MAX_TIMER_DELAY_MS }};
157
+ function matchesNumberBounds(value, bounds) {
158
+ if (!Number.isFinite(value)) {
159
+ const direction = value === Infinity ? "positive" : value === -Infinity ? "negative" : null;
160
+ if (direction === null) return false;
161
+ if (bounds.allowInfinity !== "both" && bounds.allowInfinity !== direction) return false;
162
+ }
163
+ if (bounds.min !== void 0 && value < bounds.min) return false;
164
+ if (bounds.max !== void 0 && value > bounds.max) return false;
165
+ if (bounds.exclusiveMin !== void 0 && value <= bounds.exclusiveMin) return false;
166
+ if (bounds.integer && !Number.isInteger(value)) return false;
167
+ if (bounds.allowedValues !== void 0 && !bounds.allowedValues.includes(value)) return false;
168
+ return true;
169
+ }
170
+
171
+ function readNumber(raw, fallback, bounds) {
172
+ return matchesNumberBounds(raw, bounds) ? raw : fallback;
173
+ }
174
+
175
+ var NumberValueReader = class {
176
+ #lastRejected = /* @__PURE__ */ new Map();
177
+ read(owner, name, raw, fallback, bounds) {
178
+ const resolved = readNumber(raw, fallback, bounds);
179
+ if (matchesNumberBounds(raw, bounds)) {
180
+ this.#lastRejected.delete(name);
181
+ return resolved;
182
+ }
183
+ const attribute = `data-${owner.identifier}-${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}-value`;
184
+ const literal = owner.element.getAttribute(attribute);
185
+ if (literal === null) {
186
+ this.#lastRejected.delete(name);
187
+ return resolved;
188
+ }
189
+ if (this.#lastRejected.get(name) !== literal) {
190
+ this.#lastRejected.set(name, literal);
191
+ console.warn(
192
+ `Stimeo UI: "${owner.identifier}" has an invalid number Value "${name}" declaration ${JSON.stringify(literal)}; using ${fallback}.`
193
+ );
194
+ }
195
+ return resolved;
196
+ }
197
+ };
198
+
102
199
  var TimerRegistry = class {
103
- /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */
104
200
  ids = /* @__PURE__ */ new Set();
105
- /**
106
- * Cancels a single tracked timer.
107
- *
108
- * No-ops if the id is unknown (already cleared, fired, or never owned by this
109
- * registry), so callers can clear defensively without guarding.
110
- */
111
201
  clear(id) {
112
202
  if (this.ids.delete(id)) {
113
203
  this.cancel(id);
114
204
  }
115
205
  }
116
- /**
117
- * Cancels every tracked timer. Call this from a controller's `disconnect()`
118
- * to guarantee no timer outlives the element.
119
- */
120
206
  clearAll() {
121
207
  for (const id of this.ids) {
122
208
  this.cancel(id);
123
209
  }
124
210
  this.ids.clear();
125
211
  }
126
- /** Number of timers currently tracked (pending). */
127
212
  get size() {
128
213
  return this.ids.size;
129
214
  }
130
215
  };
131
216
  var SafeTimeout = class extends TimerRegistry {
132
- /**
133
- * Schedules `callback` after `delay` ms and returns the timer id.
134
- *
135
- * The id is removed from the registry automatically when the timeout fires,
136
- * so {@link TimerRegistry.size | size} reflects only still-pending timers.
137
- */
138
217
  set(callback, delay) {
139
218
  const id = this.schedule(() => {
140
219
  this.ids.delete(id);
@@ -151,7 +230,6 @@ var SafeTimeout = class extends TimerRegistry {
151
230
  }
152
231
  };
153
232
 
154
- // src/controllers/relative_time_controller.ts
155
233
  var YEAR_SCALE = { limit: Number.POSITIVE_INFINITY, unit: "year", ms: 315576e5 };
156
234
  var UNITS = [
157
235
  { limit: 60, unit: "second", ms: 1e3 },
@@ -163,112 +241,116 @@ var UNITS = [
163
241
  YEAR_SCALE
164
242
  ];
165
243
  var RELATIVE_OPTIONS = { numeric: "auto" };
166
- var RelativeTimeController = class extends Controller {
244
+ var TEXT_RECORD = "text";
245
+ var RelativeTimeController = class _RelativeTimeController extends Controller {
246
+ #numbers = new NumberValueReader();
167
247
  static values = {
168
248
  locale: { type: String, default: "" },
169
249
  threshold: { type: Number, default: 0 },
170
250
  tickInterval: { type: Number, default: 6e4 }
171
251
  };
252
+ static valueConstraints = {
253
+ threshold: NUMBER_BOUNDS.nonNegative,
254
+ tickInterval: NUMBER_BOUNDS.timer
255
+ };
172
256
  #timers = new SafeTimeout();
173
- /** Collapses a morph that swaps several render inputs at once into one repaint. */
174
- #resync = new MicrotaskCoalescer(() => this.#resyncToValues());
175
- #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());
176
- /** Epoch ms parsed from `datetime`; `NaN` when absent or invalid. */
257
+ #resync = new MorphRenderWatcher(() => {
258
+ const target = readDatetime(this.element) ?? Number.NaN;
259
+ if (!Object.is(target, this.#targetMs)) {
260
+ this.#targetMs = target;
261
+ this.#adoptAuthoredText();
262
+ this.#valuesDirty = true;
263
+ }
264
+ if (this.#valuesDirty) {
265
+ this.#valuesDirty = false;
266
+ this.#resyncToValues();
267
+ } else if (!Number.isNaN(this.#targetMs)) {
268
+ this.#applyAndComputeDelay();
269
+ }
270
+ });
271
+ #valuesDirty = false;
272
+ #datetimeWatch = new MutationObserver(() => this.#resync.schedule());
177
273
  #targetMs = Number.NaN;
178
- /** The authored absolute text, restored when the threshold fallback kicks in. */
179
274
  #absoluteText = "";
180
275
  connect() {
181
- this.#resync.activate();
182
- this.#beforeCache.activate();
183
- if (this.element.getAttribute("data-state") !== "relative") {
184
- this.#absoluteText = (this.element.textContent ?? "").trim();
185
- }
186
- this.#targetMs = Date.parse(this.element.getAttribute("datetime") ?? "");
276
+ this.#timers.clearAll();
277
+ this.#valuesDirty = false;
278
+ this.#resync.observe(this.element);
279
+ this.#datetimeWatch.observe(this.element, { attributeFilter: ["datetime"] });
280
+ this.#adoptAuthoredText();
281
+ this.#targetMs = readDatetime(this.element) ?? Number.NaN;
187
282
  if (Number.isNaN(this.#targetMs)) return;
188
283
  this.#schedule();
189
284
  }
190
285
  disconnect() {
191
- this.#resync.cancel();
192
- this.#beforeCache.deactivate();
286
+ this.#resync.disconnect();
287
+ this.#datetimeWatch.disconnect();
193
288
  this.#timers.clearAll();
194
289
  }
195
- /** Repaints when application code (or a Turbo morph) changes `locale` at runtime. */
290
+ #adoptAuthoredText() {
291
+ if (this.element.getAttribute("data-state") !== "relative") {
292
+ this.#absoluteText = (this.element.textContent ?? "").trim();
293
+ } else {
294
+ const recorded = this.#recordedText();
295
+ if (recorded !== null) this.#absoluteText = recorded;
296
+ }
297
+ }
298
+ get #textRecord() {
299
+ return `data-${this.identifier}-${TEXT_RECORD}`;
300
+ }
301
+ #recordedText() {
302
+ try {
303
+ const parsed = JSON.parse(this.element.getAttribute(this.#textRecord) ?? "null");
304
+ return typeof parsed === "string" ? parsed : null;
305
+ } catch {
306
+ return null;
307
+ }
308
+ }
196
309
  localeValueChanged() {
310
+ this.#valuesDirty = true;
197
311
  this.#resync.schedule();
198
312
  }
199
- /** Repaints when application code (or a Turbo morph) changes `threshold` at runtime. */
200
313
  thresholdValueChanged() {
314
+ this.#valuesDirty = true;
201
315
  this.#resync.schedule();
202
316
  }
203
- /** Repaints when application code (or a Turbo morph) changes `tickInterval` at runtime. */
204
317
  tickIntervalValueChanged() {
318
+ this.#valuesDirty = true;
205
319
  this.#resync.schedule();
206
320
  }
207
- /**
208
- * Renders against the current Values and re-arms the poll from now.
209
- *
210
- * Render only: it emits no event, and clearing first keeps the single self-arming
211
- * timer single — scheduling on top of a pending one would double the poll rate for
212
- * the rest of the session. A stamp whose `datetime` never parsed has nothing to
213
- * render, and one that already reached its terminal fallback simply renders it
214
- * again and stops.
215
- */
216
321
  #resyncToValues() {
217
- if (Number.isNaN(this.#targetMs)) return;
218
322
  this.#timers.clearAll();
323
+ if (Number.isNaN(this.#targetMs)) return;
219
324
  this.#schedule();
220
325
  }
221
- /**
222
- * Restores the authored absolute text and the pre-render state for the snapshot
223
- * Turbo is about to take, leaving the live page's poll timer alone.
224
- *
225
- * With no authored text held there is nothing to restore, and `data-state` has to
226
- * stay as it is: that marker is what tells the next `connect()` the visible text is
227
- * a rendered relative form rather than an absolute fallback to hold on to.
228
- */
229
- #rewindForCache() {
230
- if (!this.#absoluteText) return;
231
- this.element.textContent = this.#absoluteText;
232
- this.element.removeAttribute("data-state");
233
- }
234
- /** Renders the current representation and reschedules unless polling can stop. */
235
326
  #schedule() {
236
327
  const nextDelay = this.#applyAndComputeDelay();
237
328
  if (nextDelay !== null) {
238
329
  this.#timers.set(() => this.#schedule(), nextDelay);
239
330
  }
240
331
  }
241
- /**
242
- * Updates the visible text and returns the next poll delay (ms), or `null` when
243
- * polling can stop: a *past* timestamp that fell back to the absolute text can
244
- * never leave it again, and a locale the runtime rejects has nothing to render
245
- * until that value is corrected.
246
- *
247
- * @stimeoRenderRoot
248
- */
249
332
  #applyAndComputeDelay() {
250
333
  const deltaMs = this.#targetMs - Date.now();
251
334
  const absSeconds = Math.abs(deltaMs) / 1e3;
252
335
  const scale = UNITS.find((u) => absSeconds < u.limit) ?? YEAR_SCALE;
253
336
  const unitFloor = scale.unit === "second" || scale.unit === "minute" ? 6e4 : scale.ms;
254
- const nextDelay = Math.max(this.tickIntervalValue, Math.min(unitFloor, 864e5));
255
- if (this.thresholdValue > 0 && absSeconds >= this.thresholdValue && this.#absoluteText) {
337
+ const nextDelay = Math.max(this.#safeTickInterval, Math.min(unitFloor, 864e5));
338
+ if (this.#safeThreshold > 0 && absSeconds >= this.#safeThreshold && this.#absoluteText) {
256
339
  this.element.textContent = this.#absoluteText;
257
340
  this.element.setAttribute("data-state", "absolute");
341
+ this.element.removeAttribute(this.#textRecord);
258
342
  if (deltaMs <= 0) return null;
259
- return Math.min(nextDelay, deltaMs - this.thresholdValue * 1e3 + 1);
343
+ return Math.max(1, Math.min(nextDelay, deltaMs - this.#safeThreshold * 1e3 + 1));
260
344
  }
261
345
  const formatter = this.#formatter;
262
346
  if (formatter === null) return null;
263
347
  const value = Math.round(deltaMs / scale.ms);
264
348
  this.element.textContent = formatter.format(value, scale.unit);
265
349
  this.element.setAttribute("data-state", "relative");
350
+ const record = JSON.stringify(this.#absoluteText);
351
+ setAttributeIfChanged(this.element, this.#textRecord, record);
266
352
  return nextDelay;
267
353
  }
268
- /**
269
- * A `RelativeTimeFormat` for the resolved locale (`numeric: "auto"`), or `null`
270
- * when the runtime rejects that locale.
271
- */
272
354
  get #formatter() {
273
355
  return intlFormatter(
274
356
  Intl.RelativeTimeFormat,
@@ -276,8 +358,25 @@ var RelativeTimeController = class extends Controller {
276
358
  RELATIVE_OPTIONS
277
359
  );
278
360
  }
361
+ get #safeThreshold() {
362
+ return this.#numbers.read(
363
+ this,
364
+ "threshold",
365
+ this.thresholdValue,
366
+ _RelativeTimeController.values.threshold.default,
367
+ _RelativeTimeController.valueConstraints.threshold
368
+ );
369
+ }
370
+ get #safeTickInterval() {
371
+ return this.#numbers.read(
372
+ this,
373
+ "tickInterval",
374
+ this.tickIntervalValue,
375
+ _RelativeTimeController.values.tickInterval.default,
376
+ _RelativeTimeController.valueConstraints.tickInterval
377
+ );
378
+ }
279
379
  };
280
380
 
281
381
  export { RelativeTimeController };
282
- //# sourceMappingURL=relative_time_controller.js.map
283
382
  //# sourceMappingURL=relative_time_controller.js.map
@@ -1,8 +1,5 @@
1
1
  import { Controller } from '@hotwired/stimulus';
2
2
 
3
- // src/controllers/reset_before_cache_controller.ts
4
-
5
- // src/utils/declared_value.ts
6
3
  function parseDeclared(raw, parse, fallback) {
7
4
  try {
8
5
  return parse(raw);
@@ -22,7 +19,100 @@ function validSelector(element, raw, fallback) {
22
19
  );
23
20
  }
24
21
 
25
- // src/controllers/reset_before_cache_controller.ts
22
+ var ListenerSet = class {
23
+ #abort = new AbortController();
24
+ add(target, type, handler, options) {
25
+ target.addEventListener(type, handler, { ...options, signal: this.#abort.signal });
26
+ }
27
+ dispose() {
28
+ this.#abort.abort();
29
+ this.#abort = new AbortController();
30
+ }
31
+ };
32
+
33
+ var MicrotaskCoalescer = class {
34
+ #run;
35
+ #queued = false;
36
+ #active = false;
37
+ #generation = 0;
38
+ constructor(run) {
39
+ this.#run = run;
40
+ }
41
+ activate() {
42
+ this.#active = true;
43
+ }
44
+ cancel() {
45
+ this.#active = false;
46
+ this.#queued = false;
47
+ this.#generation += 1;
48
+ }
49
+ get pending() {
50
+ return this.#queued;
51
+ }
52
+ schedule() {
53
+ if (!this.#active || this.#queued) return;
54
+ this.#queued = true;
55
+ const generation = this.#generation;
56
+ queueMicrotask(() => {
57
+ if (generation !== this.#generation || !this.#queued || !this.#active) return;
58
+ this.#queued = false;
59
+ this.#run();
60
+ });
61
+ }
62
+ };
63
+
64
+ var MorphRenderWatcher = class {
65
+ #listeners = new ListenerSet();
66
+ #pass;
67
+ #element = null;
68
+ #onMorph = () => this.#pass.schedule();
69
+ constructor(run) {
70
+ this.#pass = new MicrotaskCoalescer(run);
71
+ }
72
+ observe(element) {
73
+ if (this.#element === element) return;
74
+ this.disconnect();
75
+ this.#element = element;
76
+ this.#pass.activate();
77
+ this.#listeners.add(element, "turbo:morph-element", this.#onMorph);
78
+ }
79
+ schedule() {
80
+ this.#pass.schedule();
81
+ }
82
+ get pending() {
83
+ return this.#pass.pending;
84
+ }
85
+ disconnect() {
86
+ this.#listeners.dispose();
87
+ this.#pass.cancel();
88
+ this.#element = null;
89
+ }
90
+ };
91
+
92
+ var LivedMark = class {
93
+ #name;
94
+ #lived = false;
95
+ #element = null;
96
+ #morph = new MorphRenderWatcher(() => this.#write());
97
+ constructor(identifier) {
98
+ this.#name = `data-${identifier}-lived`;
99
+ }
100
+ connect(element) {
101
+ const connection = this.#lived ? "reconnect" : element.hasAttribute(this.#name) ? "restored" : "fresh";
102
+ this.#lived = true;
103
+ this.#element = element;
104
+ this.#write();
105
+ this.#morph.observe(element);
106
+ return connection;
107
+ }
108
+ disconnect() {
109
+ this.#morph.disconnect();
110
+ }
111
+ #write() {
112
+ this.#element?.setAttribute(this.#name, "");
113
+ }
114
+ };
115
+
26
116
  var STATELESS_INPUT_TYPES = /* @__PURE__ */ new Set(["hidden", "submit", "reset", "button", "image"]);
27
117
  function restoreField(element) {
28
118
  if (element instanceof HTMLTextAreaElement) {
@@ -43,48 +133,25 @@ function restoreField(element) {
43
133
  }
44
134
  }
45
135
  }
46
- var ResetBeforeCacheController = class extends Controller {
136
+ var ResetOnRestoreController = class extends Controller {
47
137
  static values = {
48
- scope: { type: String, default: "" },
49
- dispatchReset: { type: Boolean, default: true }
138
+ scope: { type: String, default: "" }
50
139
  };
51
140
  static actions = ["reset"];
52
- static events = ["reset", "request"];
53
- /** The `scope` declaration after validation; empty when it cannot be parsed. */
141
+ static events = ["reset"];
54
142
  #scopeSelector = "";
55
- /** Runs the reset just before Turbo caches the snapshot. */
56
- #onBeforeCache = () => this.reset();
57
- /**
58
- * Validates the scope declaration once, keeping only a selector the engine can
59
- * read.
60
- *
61
- * A selector reads back as an ordinary string, so a malformed one survives
62
- * until it is handed to the DOM — and this part runs from a single listener
63
- * whose whole job is to keep a cached page from freezing. Falling back to the
64
- * default keeps that job running with a visible, findable result instead of
65
- * silently taking the sweep down.
66
- */
143
+ #lived = new LivedMark(this.identifier);
67
144
  scopeValueChanged() {
68
145
  this.#scopeSelector = validSelector(this.element, this.scopeValue, "");
69
146
  }
70
147
  connect() {
71
- document.addEventListener("turbo:before-cache", this.#onBeforeCache);
148
+ if (this.#lived.connect(this.element) === "restored") this.reset();
72
149
  }
73
150
  disconnect() {
74
- document.removeEventListener("turbo:before-cache", this.#onBeforeCache);
75
- }
76
- /**
77
- * Resets transient UI within scope to its initial state. Asks controllers to
78
- * close (via `request`) first, then applies the declarative `data-reset-*` cleanup,
79
- * and finally emits `reset`. Safe to call any number of times (idempotent).
80
- *
81
- * `dispatchReset` decides only whether the `request` ask goes out; the cleanup
82
- * and the closing `reset` run either way. Both the listener and this action
83
- * reach the same sweep, so `reset` is emitted for a manual call too.
84
- */
151
+ this.#lived.disconnect();
152
+ }
85
153
  reset() {
86
154
  const root = this.#scopeRoot();
87
- if (this.dispatchResetValue) this.dispatch("request");
88
155
  for (const element of root.querySelectorAll("[data-reset-attr]")) {
89
156
  for (const name of (element.getAttribute("data-reset-attr") ?? "").split(/\s+/)) {
90
157
  if (name) element.removeAttribute(name);
@@ -109,13 +176,11 @@ var ResetBeforeCacheController = class extends Controller {
109
176
  }
110
177
  this.dispatch("reset");
111
178
  }
112
- /** The scan root: a `scope` descendant when set, else the controller element. */
113
179
  #scopeRoot() {
114
180
  if (!this.#scopeSelector) return this.element;
115
181
  return this.element.querySelector(this.#scopeSelector) ?? this.element;
116
182
  }
117
183
  };
118
184
 
119
- export { ResetBeforeCacheController };
120
- //# sourceMappingURL=reset_before_cache_controller.js.map
121
- //# sourceMappingURL=reset_before_cache_controller.js.map
185
+ export { ResetOnRestoreController };
186
+ //# sourceMappingURL=reset_on_restore_controller.js.map