stimeo-ui 0.11.0 → 0.12.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 (36) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/dist/cable/index.js +23 -2
  3. package/dist/cable/index.js.map +1 -1
  4. package/dist/controllers/count_up_controller.d.ts +12 -10
  5. package/dist/controllers/count_up_controller.js +74 -35
  6. package/dist/controllers/count_up_controller.js.map +1 -1
  7. package/dist/controllers/intersection_controller.d.ts +20 -7
  8. package/dist/controllers/intersection_controller.js +55 -8
  9. package/dist/controllers/intersection_controller.js.map +1 -1
  10. package/dist/controllers/lazy_frame_controller.d.ts +31 -9
  11. package/dist/controllers/lazy_frame_controller.js +81 -19
  12. package/dist/controllers/lazy_frame_controller.js.map +1 -1
  13. package/dist/controllers/pointer_drag_controller.js +4 -0
  14. package/dist/controllers/pointer_drag_controller.js.map +1 -1
  15. package/dist/controllers/reading_progress_controller.d.ts +18 -9
  16. package/dist/controllers/reading_progress_controller.js +177 -6
  17. package/dist/controllers/reading_progress_controller.js.map +1 -1
  18. package/dist/controllers/scrollspy_controller.js +13 -2
  19. package/dist/controllers/scrollspy_controller.js.map +1 -1
  20. package/dist/controllers/smart_sticky_header_controller.d.ts +17 -8
  21. package/dist/controllers/smart_sticky_header_controller.js +52 -10
  22. package/dist/controllers/smart_sticky_header_controller.js.map +1 -1
  23. package/dist/controllers/sortable_controller.d.ts +38 -8
  24. package/dist/controllers/sortable_controller.js +241 -67
  25. package/dist/controllers/sortable_controller.js.map +1 -1
  26. package/dist/controllers/sticky_observer_controller.js +13 -2
  27. package/dist/controllers/sticky_observer_controller.js.map +1 -1
  28. package/dist/index.js +486 -145
  29. package/dist/index.js.map +1 -1
  30. package/dist/inspector/cli.js +1 -0
  31. package/dist/inspector/cli.js.map +1 -1
  32. package/dist/inspector/cli_bin.js +1 -0
  33. package/dist/inspector/cli_bin.js.map +1 -1
  34. package/dist/inspector/examples.json +1 -1
  35. package/dist/inspector/manifest.json +8 -28
  36. package/package.json +1 -1
@@ -1,12 +1,158 @@
1
1
  import { Controller } from '@hotwired/stimulus';
2
2
 
3
+ // src/controllers/reading_progress_controller.ts
4
+
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;
17
+ }
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
+ };
33
+
34
+ // src/utils/layout_observer.ts
35
+ var LayoutObserver = class {
36
+ #callback;
37
+ #resizeObserverFactory;
38
+ #resizeObserver = null;
39
+ #observingViewport = false;
40
+ /** Stable bound handler so add/removeEventListener target the same reference. */
41
+ #handleViewportResize = () => {
42
+ this.#callback();
43
+ };
44
+ constructor(callback, options = {}) {
45
+ this.#callback = callback;
46
+ this.#resizeObserverFactory = options.resizeObserverFactory ?? (typeof ResizeObserver === "undefined" ? null : (cb) => new ResizeObserver(cb));
47
+ }
48
+ /**
49
+ * Starts observing an element's size. Repeated calls observe additional
50
+ * elements through the same shared observer. No-ops when no
51
+ * `ResizeObserver` implementation is available.
52
+ */
53
+ observe(element) {
54
+ if (!this.#resizeObserverFactory) return;
55
+ if (!this.#resizeObserver) {
56
+ this.#resizeObserver = this.#resizeObserverFactory(() => {
57
+ this.#callback();
58
+ });
59
+ }
60
+ this.#resizeObserver.observe(element);
61
+ }
62
+ /** Stops observing a single element while leaving any others in place. */
63
+ unobserve(element) {
64
+ this.#resizeObserver?.unobserve(element);
65
+ }
66
+ /** Starts observing viewport resizes. Idempotent: the listener is added once. */
67
+ observeViewport() {
68
+ if (this.#observingViewport) return;
69
+ this.#observingViewport = true;
70
+ window.addEventListener("resize", this.#handleViewportResize);
71
+ }
72
+ /** Stops observing viewport resizes without affecting element observation. */
73
+ unobserveViewport() {
74
+ if (!this.#observingViewport) return;
75
+ this.#observingViewport = false;
76
+ window.removeEventListener("resize", this.#handleViewportResize);
77
+ }
78
+ /**
79
+ * Releases every observation: disconnects the {@link ResizeObserver} and
80
+ * removes the viewport listener. Safe to call multiple times. Call this from a
81
+ * controller's `disconnect()`.
82
+ */
83
+ disconnect() {
84
+ this.#resizeObserver?.disconnect();
85
+ this.#resizeObserver = null;
86
+ this.unobserveViewport();
87
+ }
88
+ };
89
+
90
+ // src/utils/style_property_lease.ts
91
+ var StylePropertyLease = class {
92
+ #property;
93
+ #records = /* @__PURE__ */ new Map();
94
+ /** @param property - The CSS property whose temporary values this lease owns. */
95
+ constructor(property) {
96
+ this.#property = property;
97
+ }
98
+ /** Writes or removes the leased declaration while preserving its authored value. */
99
+ write(element, value, priority = "") {
100
+ const existing = this.#records.get(element);
101
+ if (existing) {
102
+ existing.writtenValue = value;
103
+ existing.writtenPriority = value === null ? "" : priority;
104
+ } else {
105
+ this.#records.set(element, {
106
+ originalValue: element.style.getPropertyValue(this.#property),
107
+ originalPriority: element.style.getPropertyPriority(this.#property),
108
+ writtenValue: value,
109
+ writtenPriority: value === null ? "" : priority
110
+ });
111
+ }
112
+ this.#reflect(element, value, priority);
113
+ }
114
+ /** Returns one lease without overwriting a later consumer declaration. */
115
+ return(element) {
116
+ const record = this.#records.get(element);
117
+ if (!record) return;
118
+ this.#records.delete(element);
119
+ const style = element.style;
120
+ const stillOwned = style.getPropertyValue(this.#property) === (record.writtenValue ?? "") && style.getPropertyPriority(this.#property) === record.writtenPriority;
121
+ if (stillOwned) {
122
+ this.#reflect(element, record.originalValue, record.originalPriority);
123
+ }
124
+ }
125
+ /** Returns every outstanding declaration lease. */
126
+ returnAll() {
127
+ for (const element of Array.from(this.#records.keys())) this.return(element);
128
+ }
129
+ /** Reflects only a real declaration transition. */
130
+ #reflect(element, value, priority) {
131
+ const style = element.style;
132
+ const nextValue = value ?? "";
133
+ const nextPriority = value === null ? "" : priority;
134
+ if (style.getPropertyValue(this.#property) === nextValue && style.getPropertyPriority(this.#property) === nextPriority) {
135
+ return;
136
+ }
137
+ if (value === null) style.removeProperty(this.#property);
138
+ else style.setProperty(this.#property, value, priority);
139
+ }
140
+ };
141
+
3
142
  // src/controllers/reading_progress_controller.ts
4
143
  var PROGRESS_PROPERTY = "--stimeo--reading-progress";
5
144
  var ReadingProgressController = class extends Controller {
6
145
  static events = ["change", "complete"];
146
+ /** Owns both faces of the published property so teardown can hand them back. */
147
+ #lease = new StylePropertyLease(PROGRESS_PROPERTY);
148
+ /** The article's own box and the viewport: either changes the span. */
149
+ #layout = new LayoutObserver(() => this.#onScroll());
150
+ #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());
7
151
  #frame = null;
8
152
  /** Last published progress, so `change`/`complete` fire only on movement. */
9
153
  #progress = -1;
154
+ /** False until the connect frame has run: `complete` needs real reading. */
155
+ #baselined = false;
10
156
  #onScroll = () => {
11
157
  if (this.#frame !== null) return;
12
158
  this.#frame = requestAnimationFrame(() => {
@@ -16,20 +162,45 @@ var ReadingProgressController = class extends Controller {
16
162
  };
17
163
  connect() {
18
164
  this.#progress = -1;
165
+ this.#baselined = false;
19
166
  window.addEventListener("scroll", this.#onScroll, { passive: true, capture: true });
20
- window.addEventListener("resize", this.#onScroll, { passive: true });
167
+ this.#layout.observe(this.element);
168
+ this.#layout.observeViewport();
169
+ this.#beforeCache.activate();
21
170
  this.#measure();
171
+ this.#frame = requestAnimationFrame(() => {
172
+ this.#frame = null;
173
+ this.#measure();
174
+ this.#baselined = true;
175
+ });
22
176
  }
23
177
  disconnect() {
24
178
  window.removeEventListener("scroll", this.#onScroll, { capture: true });
25
- window.removeEventListener("resize", this.#onScroll);
179
+ this.#layout.disconnect();
180
+ this.#beforeCache.deactivate();
181
+ this.#cancelFrame();
182
+ this.#lease.returnAll();
183
+ }
184
+ /**
185
+ * Hands both declarations back before the page is snapshotted, so a restored
186
+ * page starts from the authored DOM rather than from someone else's progress.
187
+ * The baseline goes back with them: a cancelled visit leaves this page on
188
+ * screen, and the next measurement has to publish afresh rather than match a
189
+ * value that has already been handed back.
190
+ */
191
+ #rewindForCache() {
192
+ this.#cancelFrame();
193
+ this.#lease.returnAll();
194
+ this.#progress = -1;
195
+ }
196
+ #cancelFrame() {
26
197
  if (this.#frame !== null) cancelAnimationFrame(this.#frame);
27
198
  this.#frame = null;
28
- document.documentElement.style.removeProperty(PROGRESS_PROPERTY);
29
199
  }
30
200
  /** Computes and publishes the progress; emits on movement only. */
31
201
  #measure() {
32
202
  const rect = this.element.getBoundingClientRect();
203
+ if (rect.width === 0 && rect.height === 0) return;
33
204
  const span = rect.height - window.innerHeight;
34
205
  const raw = span > 0 ? -rect.top / span : rect.top <= 0 ? 1 : 0;
35
206
  const progress = Math.min(1, Math.max(0, raw));
@@ -37,10 +208,10 @@ var ReadingProgressController = class extends Controller {
37
208
  const previous = this.#progress;
38
209
  this.#progress = progress;
39
210
  const value = String(progress);
40
- this.element.style.setProperty(PROGRESS_PROPERTY, value);
41
- document.documentElement.style.setProperty(PROGRESS_PROPERTY, value);
211
+ this.#lease.write(this.element, value);
212
+ this.#lease.write(document.documentElement, value);
42
213
  this.dispatch("change", { detail: { progress } });
43
- if (progress === 1 && previous !== -1) this.dispatch("complete");
214
+ if (progress === 1 && previous !== -1 && this.#baselined) this.dispatch("complete");
44
215
  }
45
216
  };
46
217
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/controllers/reading_progress_controller.ts"],"names":[],"mappings":";;;AAGA,IAAM,iBAAA,GAAoB,4BAAA;AAoCnB,IAAM,yBAAA,GAAN,cAAwC,UAAA,CAAwB;AAAA,EACrE,OAAO,MAAA,GAAS,CAAC,QAAA,EAAU,UAAU,CAAA;AAAA,EAErC,MAAA,GAAwB,IAAA;AAAA;AAAA,EAExB,SAAA,GAAY,EAAA;AAAA,EAEH,YAAY,MAAY;AAC/B,IAAA,IAAI,IAAA,CAAK,WAAW,IAAA,EAAM;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,sBAAsB,MAAM;AACxC,MAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,MAAA,IAAA,CAAK,QAAA,EAAS;AAAA,IAChB,CAAC,CAAA;AAAA,EACH,CAAA;AAAA,EAES,OAAA,GAAgB;AACvB,IAAA,IAAA,CAAK,SAAA,GAAY,EAAA;AAIjB,IAAA,MAAA,CAAO,gBAAA,CAAiB,UAAU,IAAA,CAAK,SAAA,EAAW,EAAE,OAAA,EAAS,IAAA,EAAM,OAAA,EAAS,IAAA,EAAM,CAAA;AAClF,IAAA,MAAA,CAAO,iBAAiB,QAAA,EAAU,IAAA,CAAK,WAAW,EAAE,OAAA,EAAS,MAAM,CAAA;AACnE,IAAA,IAAA,CAAK,QAAA,EAAS;AAAA,EAChB;AAAA,EAES,UAAA,GAAmB;AAC1B,IAAA,MAAA,CAAO,oBAAoB,QAAA,EAAU,IAAA,CAAK,WAAW,EAAE,OAAA,EAAS,MAAM,CAAA;AACtE,IAAA,MAAA,CAAO,mBAAA,CAAoB,QAAA,EAAU,IAAA,CAAK,SAAS,CAAA;AACnD,IAAA,IAAI,IAAA,CAAK,MAAA,KAAW,IAAA,EAAM,oBAAA,CAAqB,KAAK,MAAM,CAAA;AAC1D,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,QAAA,CAAS,eAAA,CAAgB,KAAA,CAAM,cAAA,CAAe,iBAAiB,CAAA;AAAA,EACjE;AAAA;AAAA,EAGA,QAAA,GAAiB;AACf,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,OAAA,CAAQ,qBAAA,EAAsB;AAChD,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,MAAA,GAAS,MAAA,CAAO,WAAA;AAElC,IAAA,MAAM,GAAA,GAAM,IAAA,GAAO,CAAA,GAAI,CAAC,IAAA,CAAK,MAAM,IAAA,GAAO,IAAA,CAAK,GAAA,IAAO,CAAA,GAAI,CAAA,GAAI,CAAA;AAC9D,IAAA,MAAM,QAAA,GAAW,KAAK,GAAA,CAAI,CAAA,EAAG,KAAK,GAAA,CAAI,CAAA,EAAG,GAAG,CAAC,CAAA;AAC7C,IAAA,IAAI,QAAA,KAAa,KAAK,SAAA,EAAW;AAEjC,IAAA,MAAM,WAAW,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,SAAA,GAAY,QAAA;AACjB,IAAA,MAAM,KAAA,GAAQ,OAAO,QAAQ,CAAA;AAC7B,IAAA,IAAA,CAAK,OAAA,CAAQ,KAAA,CAAM,WAAA,CAAY,iBAAA,EAAmB,KAAK,CAAA;AACvD,IAAA,QAAA,CAAS,eAAA,CAAgB,KAAA,CAAM,WAAA,CAAY,iBAAA,EAAmB,KAAK,CAAA;AACnE,IAAA,IAAA,CAAK,SAAS,QAAA,EAAU,EAAE,QAAQ,EAAE,QAAA,IAAY,CAAA;AAChD,IAAA,IAAI,aAAa,CAAA,IAAK,QAAA,KAAa,EAAA,EAAI,IAAA,CAAK,SAAS,UAAU,CAAA;AAAA,EACjE;AACF","file":"reading_progress_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/** Name of the CSS custom property exposing the reading progress (0..1). */\nconst PROGRESS_PROPERTY = \"--stimeo--reading-progress\";\n\n/**\n * Headless **reading progress**: how far the reader has scrolled *through* this\n * element (an article), published as a CSS custom property and a `change`\n * event stream — the classic top-of-page progress bar.\n * `IntersectionObserver` alone cannot express this (the ratio is constant\n * while a tall article scrolls through the viewport), so this controller owns\n * the scroll math; compose with `stimeo--intersection` when you also need\n * enter/exit triggers. Core (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--reading-progress`):\n * <article data-controller=\"stimeo--reading-progress\">…</article>\n * <div class=\"progress-bar\" aria-hidden=\"true\"></div>\n * <!-- .progress-bar { width: calc(var(--stimeo--reading-progress, 0) * 100%); } -->\n *\n * Progress is `0` before the article's top reaches the viewport top and `1`\n * once its bottom fits the viewport: `-top / (height - viewportHeight)`,\n * clamped. The property is written on the controller element **and** on\n * `document.documentElement`, so a fixed bar anywhere in the page can consume\n * it without being a descendant. The `:root` copy makes this a\n * one-instance-per-page contract (two articles would fight last-writer-wins);\n * `complete` fires on *reaching* 1 — a connect-time measurement that is\n * already 1 (e.g. a Turbo restore at the bottom) only establishes the\n * baseline and does not fire it.\n *\n * `change` dispatches `{ progress }`.\n *\n * @remarks\n * Behavior only — the bar itself (and hiding it, e.g. before any scroll) is\n * the consumer's CSS; the progress value carries no ARIA (a decorative\n * indicator — mark the bar `aria-hidden`; a *semantic* progress belongs to\n * `stimeo--progress`). Scroll/resize work is rAF-throttled; the listeners and\n * any pending frame are released and the root custom property removed on\n * `disconnect()` (Turbo navigation included).\n */\nexport class ReadingProgressController extends Controller<HTMLElement> {\n static events = [\"change\", \"complete\"] as const;\n\n #frame: number | null = null;\n /** Last published progress, so `change`/`complete` fire only on movement. */\n #progress = -1;\n\n readonly #onScroll = (): void => {\n if (this.#frame !== null) return;\n this.#frame = requestAnimationFrame(() => {\n this.#frame = null;\n this.#measure();\n });\n };\n\n override connect(): void {\n this.#progress = -1;\n // Capture phase: element scrolls do not bubble, but they ARE observable at\n // the window in capture — so an article inside an overflow container still\n // drives the progress.\n window.addEventListener(\"scroll\", this.#onScroll, { passive: true, capture: true });\n window.addEventListener(\"resize\", this.#onScroll, { passive: true });\n this.#measure();\n }\n\n override disconnect(): void {\n window.removeEventListener(\"scroll\", this.#onScroll, { capture: true });\n window.removeEventListener(\"resize\", this.#onScroll);\n if (this.#frame !== null) cancelAnimationFrame(this.#frame);\n this.#frame = null;\n document.documentElement.style.removeProperty(PROGRESS_PROPERTY);\n }\n\n /** Computes and publishes the progress; emits on movement only. */\n #measure(): void {\n const rect = this.element.getBoundingClientRect();\n const span = rect.height - window.innerHeight;\n // Shorter than the viewport: reading it is binary (reached or not).\n const raw = span > 0 ? -rect.top / span : rect.top <= 0 ? 1 : 0;\n const progress = Math.min(1, Math.max(0, raw));\n if (progress === this.#progress) return;\n\n const previous = this.#progress;\n this.#progress = progress;\n const value = String(progress);\n this.element.style.setProperty(PROGRESS_PROPERTY, value);\n document.documentElement.style.setProperty(PROGRESS_PROPERTY, value);\n this.dispatch(\"change\", { detail: { progress } });\n if (progress === 1 && previous !== -1) this.dispatch(\"complete\");\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/before_cache_reset.ts","../../src/utils/layout_observer.ts","../../src/utils/style_property_lease.ts","../../src/controllers/reading_progress_controller.ts"],"names":[],"mappings":";;;;;AA2CO,IAAM,gBAAA,GAAN,MAAM,iBAAA,CAAiB;AAAA;AAAA,EAE5B,OAAgB,YAAA,mBAAe,IAAI,GAAA,EAAsB;AAAA;AAAA,EAGzD,OAAgB,iBAAiB,MAAY;AAC3C,IAAA,KAAA,MAAW,UAAA,IAAc,iBAAA,CAAiB,YAAA,EAAc,UAAA,CAAW,OAAA,EAAQ;AAAA,EAC7E,CAAA;AAAA,EAES,OAAA;AAAA;AAAA,EAGT,YAAY,MAAA,EAAoB;AAC9B,IAAA,IAAA,CAAK,OAAA,GAAU,MAAA;AAAA,EACjB;AAAA;AAAA,EAGA,QAAA,GAAiB;AACf,IAAA,MAAM,KAAA,GAAQ,iBAAA,CAAiB,YAAA,CAAa,IAAA,KAAS,CAAA;AACrD,IAA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A;AAAA,EACpF;AACF","file":"reading_progress_controller.js","sourcesContent":["/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way.\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n}\n","/**\n * Unified element-size and viewport observation for Stimeo controllers.\n *\n * Widgets whose output is measured — an overflow boundary, a masonry column count,\n * an autosized textarea — need to react both to their *own* box changing — via {@link ResizeObserver} —\n * and to the *viewport* changing — via the `window` `resize` event. Wiring those\n * two sources by hand in every controller risks leaked listeners on\n * `disconnect()`. {@link LayoutObserver} owns both behind one callback and one\n * {@link LayoutObserver.disconnect | disconnect()} that releases everything.\n *\n * Behavior only: the helper reports *that* layout changed; it never reads or\n * writes styles. Consumers decide what to recompute.\n */\n\n/** Invoked whenever an observed element or the viewport changes size. */\nexport type LayoutCallback = () => void;\n\n/** Constructs a {@link ResizeObserver}; injectable so tests stay deterministic. */\nexport type ResizeObserverFactory = (callback: ResizeObserverCallback) => ResizeObserver;\n\n/** Options for {@link LayoutObserver}. */\nexport interface LayoutObserverOptions {\n /**\n * Factory for the {@link ResizeObserver} used by {@link LayoutObserver.observe}.\n * Defaults to the global constructor; override it in tests, or to no-op in\n * environments where `ResizeObserver` is unavailable.\n */\n resizeObserverFactory?: ResizeObserverFactory;\n}\n\n/**\n * Observes element resizes and/or viewport resizes through a single callback,\n * with guaranteed teardown.\n *\n * @example\n * ```ts\n * #layout = new LayoutObserver(() => this.#reposition());\n *\n * connect() {\n * this.#layout.observe(this.panelTarget);\n * this.#layout.observeViewport();\n * }\n *\n * disconnect() {\n * this.#layout.disconnect();\n * }\n * ```\n */\nexport class LayoutObserver {\n readonly #callback: LayoutCallback;\n readonly #resizeObserverFactory: ResizeObserverFactory | null;\n #resizeObserver: ResizeObserver | null = null;\n #observingViewport = false;\n\n /** Stable bound handler so add/removeEventListener target the same reference. */\n readonly #handleViewportResize = (): void => {\n this.#callback();\n };\n\n constructor(callback: LayoutCallback, options: LayoutObserverOptions = {}) {\n this.#callback = callback;\n this.#resizeObserverFactory =\n options.resizeObserverFactory ??\n (typeof ResizeObserver === \"undefined\" ? null : (cb) => new ResizeObserver(cb));\n }\n\n /**\n * Starts observing an element's size. Repeated calls observe additional\n * elements through the same shared observer. No-ops when no\n * `ResizeObserver` implementation is available.\n */\n observe(element: Element): void {\n if (!this.#resizeObserverFactory) return;\n if (!this.#resizeObserver) {\n this.#resizeObserver = this.#resizeObserverFactory(() => {\n this.#callback();\n });\n }\n this.#resizeObserver.observe(element);\n }\n\n /** Stops observing a single element while leaving any others in place. */\n unobserve(element: Element): void {\n this.#resizeObserver?.unobserve(element);\n }\n\n /** Starts observing viewport resizes. Idempotent: the listener is added once. */\n observeViewport(): void {\n if (this.#observingViewport) return;\n this.#observingViewport = true;\n window.addEventListener(\"resize\", this.#handleViewportResize);\n }\n\n /** Stops observing viewport resizes without affecting element observation. */\n unobserveViewport(): void {\n if (!this.#observingViewport) return;\n this.#observingViewport = false;\n window.removeEventListener(\"resize\", this.#handleViewportResize);\n }\n\n /**\n * Releases every observation: disconnects the {@link ResizeObserver} and\n * removes the viewport listener. Safe to call multiple times. Call this from a\n * controller's `disconnect()`.\n */\n disconnect(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = null;\n this.unobserveViewport();\n }\n}\n","/** One temporarily controlled style property and the authored declaration it displaced. */\ninterface StylePropertyLeaseRecord {\n readonly originalValue: string;\n readonly originalPriority: string;\n writtenValue: string | null;\n writtenPriority: string;\n}\n\n/**\n * Temporarily controls one inline CSS property across a changing set of elements.\n *\n * Authored value and priority are restored only while the declaration still matches\n * the last leased write. A later consumer write therefore wins.\n *\n * The lease has no lifecycle of its own, so it never subscribes to document events:\n * a consumer returns its leases from its own `turbo:before-cache` rewind.\n */\nexport class StylePropertyLease<T extends HTMLElement = HTMLElement> {\n readonly #property: string;\n readonly #records = new Map<T, StylePropertyLeaseRecord>();\n\n /** @param property - The CSS property whose temporary values this lease owns. */\n constructor(property: string) {\n this.#property = property;\n }\n\n /** Writes or removes the leased declaration while preserving its authored value. */\n write(element: T, value: string | null, priority = \"\"): void {\n const existing = this.#records.get(element);\n if (existing) {\n existing.writtenValue = value;\n existing.writtenPriority = value === null ? \"\" : priority;\n } else {\n this.#records.set(element, {\n originalValue: element.style.getPropertyValue(this.#property),\n originalPriority: element.style.getPropertyPriority(this.#property),\n writtenValue: value,\n writtenPriority: value === null ? \"\" : priority,\n });\n }\n\n this.#reflect(element, value, priority);\n }\n\n /** Returns one lease without overwriting a later consumer declaration. */\n return(element: T): void {\n const record = this.#records.get(element);\n if (!record) return;\n this.#records.delete(element);\n\n const style = element.style;\n const stillOwned =\n style.getPropertyValue(this.#property) === (record.writtenValue ?? \"\") &&\n style.getPropertyPriority(this.#property) === record.writtenPriority;\n if (stillOwned) {\n this.#reflect(element, record.originalValue, record.originalPriority);\n }\n }\n\n /** Returns every outstanding declaration lease. */\n returnAll(): void {\n for (const element of Array.from(this.#records.keys())) this.return(element);\n }\n\n /** Reflects only a real declaration transition. */\n #reflect(element: T, value: string | null, priority: string): void {\n const style = element.style;\n const nextValue = value ?? \"\";\n const nextPriority = value === null ? \"\" : priority;\n if (\n style.getPropertyValue(this.#property) === nextValue &&\n style.getPropertyPriority(this.#property) === nextPriority\n ) {\n return;\n }\n if (value === null) style.removeProperty(this.#property);\n else style.setProperty(this.#property, value, priority);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { LayoutObserver } from \"../utils/layout_observer\";\nimport { StylePropertyLease } from \"../utils/style_property_lease\";\n\n/** Name of the CSS custom property exposing the reading progress (0..1). */\nconst PROGRESS_PROPERTY = \"--stimeo--reading-progress\";\n\n/**\n * Headless **reading progress**: how far the reader has scrolled *through* this\n * element (an article), published as a CSS custom property and a `change`\n * event stream — the classic top-of-page progress bar.\n * `IntersectionObserver` alone cannot express this (the ratio is constant\n * while a tall article scrolls through the viewport), so this controller owns\n * the scroll math; compose with `stimeo--intersection` when you also need\n * enter/exit triggers. Core (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--reading-progress`):\n * <article data-controller=\"stimeo--reading-progress\">…</article>\n * <div class=\"progress-bar\" aria-hidden=\"true\"></div>\n * <!-- .progress-bar { width: calc(var(--stimeo--reading-progress, 0) * 100%); } -->\n *\n * Progress is `0` before the article's top reaches the viewport top and `1`\n * once its bottom fits the viewport: `-top / (height - viewportHeight)`,\n * clamped. An article no taller than the viewport has no such span, so reading\n * it is binary: `1` from the moment its top reaches the viewport top. An\n * article with no layout box at all — a `display: none` ancestor, a collapsed\n * `<details>`, an inactive tab panel — is not measured: an empty rect sits at\n * the document origin and carries no reading position, so publishing anything\n * for it would report a place the reader never reached.\n *\n * The property is written on the controller element **and** on\n * `document.documentElement`, so a fixed bar anywhere in the page can consume\n * it without being a descendant. Both are written through a lease, so an\n * authored declaration comes back on teardown and a later writer is left alone.\n * `complete` fires on *reaching* 1, and never during the baseline: the frame in\n * which the controller connects belongs to establishing where the reader\n * already is (a restored scroll position lands there), not to reading.\n *\n * `change` dispatches `{ progress }`.\n *\n * @remarks\n * Behavior only — the bar itself (and hiding it, e.g. before any scroll) is\n * the consumer's CSS; the progress value carries no ARIA (a decorative\n * indicator — mark the bar `aria-hidden`; a *semantic* progress belongs to\n * `stimeo--progress`). The article's own box is watched as well as the\n * viewport, so content that settles late (images, fonts) re-measures instead of\n * leaving a stale span. Scroll and layout work is rAF-throttled; the listeners,\n * the observers, any pending frame and both leased declarations are released on\n * `disconnect()` and returned again for a `turbo:before-cache` snapshot.\n */\nexport class ReadingProgressController extends Controller<HTMLElement> {\n static events = [\"change\", \"complete\"] as const;\n\n /** Owns both faces of the published property so teardown can hand them back. */\n readonly #lease = new StylePropertyLease(PROGRESS_PROPERTY);\n /** The article's own box and the viewport: either changes the span. */\n readonly #layout = new LayoutObserver(() => this.#onScroll());\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n #frame: number | null = null;\n /** Last published progress, so `change`/`complete` fire only on movement. */\n #progress = -1;\n /** False until the connect frame has run: `complete` needs real reading. */\n #baselined = false;\n\n readonly #onScroll = (): void => {\n if (this.#frame !== null) return;\n this.#frame = requestAnimationFrame(() => {\n this.#frame = null;\n this.#measure();\n });\n };\n\n override connect(): void {\n this.#progress = -1;\n this.#baselined = false;\n // Capture phase: element scrolls do not bubble, but they ARE observable at\n // the window in capture — so an article inside an overflow container still\n // drives the progress.\n window.addEventListener(\"scroll\", this.#onScroll, { passive: true, capture: true });\n this.#layout.observe(this.element);\n this.#layout.observeViewport();\n this.#beforeCache.activate();\n this.#measure();\n // The page's scroll position is restored *after* the controller connects,\n // so that jump arrives as a move the reader never made. Everything up to\n // the end of this frame is still the baseline — a restored scroll coalesces\n // into the frame below, and no reader can cross an article inside one.\n this.#frame = requestAnimationFrame(() => {\n this.#frame = null;\n this.#measure();\n this.#baselined = true;\n });\n }\n\n override disconnect(): void {\n window.removeEventListener(\"scroll\", this.#onScroll, { capture: true });\n this.#layout.disconnect();\n this.#beforeCache.deactivate();\n this.#cancelFrame();\n this.#lease.returnAll();\n }\n\n /**\n * Hands both declarations back before the page is snapshotted, so a restored\n * page starts from the authored DOM rather than from someone else's progress.\n * The baseline goes back with them: a cancelled visit leaves this page on\n * screen, and the next measurement has to publish afresh rather than match a\n * value that has already been handed back.\n */\n #rewindForCache(): void {\n this.#cancelFrame();\n this.#lease.returnAll();\n this.#progress = -1;\n }\n\n #cancelFrame(): void {\n if (this.#frame !== null) cancelAnimationFrame(this.#frame);\n this.#frame = null;\n }\n\n /** Computes and publishes the progress; emits on movement only. */\n #measure(): void {\n const rect = this.element.getBoundingClientRect();\n // No layout box (a `display: none` ancestor, a collapsed `<details>`): the\n // empty rect sits at the document origin, where the binary branch below\n // would read its `top` of 0 as \"the reader reached it\". There is no reading\n // position to publish, so the last one stands until the article is laid out\n // again — which the box observer reports.\n if (rect.width === 0 && rect.height === 0) return;\n\n const span = rect.height - window.innerHeight;\n // Shorter than the viewport: reading it is binary (reached or not).\n const raw = span > 0 ? -rect.top / span : rect.top <= 0 ? 1 : 0;\n const progress = Math.min(1, Math.max(0, raw));\n if (progress === this.#progress) return;\n\n const previous = this.#progress;\n this.#progress = progress;\n const value = String(progress);\n this.#lease.write(this.element, value);\n this.#lease.write(document.documentElement, value);\n this.dispatch(\"change\", { detail: { progress } });\n if (progress === 1 && previous !== -1 && this.#baselined) this.dispatch(\"complete\");\n }\n}\n"]}
@@ -3,6 +3,14 @@ import { Controller } from '@hotwired/stimulus';
3
3
  // src/controllers/scrollspy_controller.ts
4
4
 
5
5
  // src/utils/intersection_watcher.ts
6
+ function queryRoot(selector) {
7
+ if (!selector) return null;
8
+ try {
9
+ return document.querySelector(selector);
10
+ } catch {
11
+ }
12
+ return null;
13
+ }
6
14
  var IntersectionWatcher = class {
7
15
  #onEntries;
8
16
  #observer = null;
@@ -24,7 +32,10 @@ var IntersectionWatcher = class {
24
32
  * the watcher inert — without `IntersectionObserver` support (very old
25
33
  * browsers; the caller's no-JS fallback stays in charge) or with no targets.
26
34
  * If initial construction with the configured options fails, the watcher
27
- * warns and retries once with the same root and platform defaults.
35
+ * warns and retries once with the same root and platform defaults. A
36
+ * `rootSelector` that does not parse resolves to the viewport (see
37
+ * {@link IntersectionWatchOptions.rootSelector}), so a typo never fails the
38
+ * call.
28
39
  *
29
40
  * @throws The fallback constructor error if both construction attempts fail,
30
41
  * or whatever the platform throws from `observe()`. The exception is passed
@@ -37,7 +48,7 @@ var IntersectionWatcher = class {
37
48
  if (typeof IntersectionObserver === "undefined") return false;
38
49
  const list = Array.isArray(targets) ? targets : [targets];
39
50
  if (list.length === 0) return false;
40
- const root = "root" in options ? options.root ?? null : options.rootSelector ? document.querySelector(options.rootSelector) : null;
51
+ const root = "root" in options ? options.root ?? null : queryRoot(options.rootSelector);
41
52
  let observer = null;
42
53
  try {
43
54
  const onEntries = (entries) => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/utils/reduced_motion.ts","../../src/controllers/scrollspy_controller.ts"],"names":[],"mappings":";;;;;AAmDO,IAAM,sBAAN,MAA0B;AAAA,EACtB,UAAA;AAAA,EACT,SAAA,GAAyC,IAAA;AAAA,EACzC,OAAA,GAAU,KAAA;AAAA,EACV,sBAAA,GAAyB,KAAA;AAAA,EAEzB,YAAY,SAAA,EAA2D;AACrE,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,IAAI,MAAA,GAAkB;AACpB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA;AAAA,EAGA,IAAI,qBAAA,GAAiC;AACnC,IAAA,OAAO,IAAA,CAAK,sBAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeA,KAAA,CAAM,OAAA,EAAuC,OAAA,GAAoC,EAAC,EAAY;AAC5F,IAAA,IAAA,CAAK,IAAA,EAAK;AACV,IAAA,IAAI,OAAO,oBAAA,KAAyB,WAAA,EAAa,OAAO,KAAA;AACxD,IAAA,MAAM,OAAO,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,GAAK,OAAA,GAAiC,CAAC,OAAkB,CAAA;AAC3F,IAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAE9B,IAAA,MAAM,IAAA,GACJ,MAAA,IAAU,OAAA,GACL,OAAA,CAAQ,IAAA,IAAQ,IAAA,GACjB,OAAA,CAAQ,YAAA,GACN,QAAA,CAAS,aAA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AI,CAAA;AACjC,MAAA,IAAI,IAAI,OAAO,EAAA;AAAA,IACjB;AACA,IAAA,OAAO,EAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,aAAa,IAAA,EAAkC;AAC7C,IAAA,OACE,IAAA,CAAK,WAAA,CAAY,IAAA,CAAK,YAAA,CAAa,MAAM,CAAC,CAAA,IAC1C,IAAA,CAAK,WAAA,CAAY,IAAA,CAAK,YAAA,CAAa,WAAW,CAAC,CAAA;AAAA,EAEnD;AAAA;AAAA,EAGA,YAAY,KAAA,EAAqC;AAC/C,IAAA,IAAI,CAAC,KAAA,EAAO,UAAA,CAAW,GAAG,GAAG,OAAO,IAAA;AACpC,IAAA,OAAO,KAAA,CAAM,SAAA,CAAU,CAAC,CAAA,IAAK,IAAA;AAAA,EAC/B;AACF","file":"scrollspy_controller.js","sourcesContent":["/**\n * Shared `IntersectionObserver` plumbing for Stimeo's scroll-triggered\n * controllers (`intersection`, `scrollspy`, `sticky-observer`, `lazy-frame`).\n *\n * It centralizes the `IntersectionObserver` support guard, root resolution from\n * a selector, observer creation/teardown, the **active guard** (the browser may\n * flush a final queued callback batch right after `disconnect()`, and a\n * detached controller must not mutate possibly-cached DOM), and the\n * unobserve→observe **re-arm** that re-delivers the current state even when the\n * target never leaves the viewport.\n *\n * Like {@link RovingTabindex} and `FocusTrap`, this is a policy-free internal\n * util: what an intersection *means* (a spied link, a stuck header, a lazy\n * load) stays in each controller. The public `stimeo--intersection` controller\n * is its thin declarative face.\n */\n/**\n * Whether `entry`'s target sits entirely before the root's **start (top)** edge —\n * the \"scrolled past the top\" half of a non-intersecting entry, as opposed to\n * \"not reached yet\" below the root.\n *\n * A target with no layout box (`display: none`, a `hidden` ancestor, a collapsed\n * `<details>`) is reported with an **empty rect**, whose `bottom` of `0` would\n * otherwise satisfy `bottom <= rootTop` for a viewport root and read as \"passed\"\n * even though the target was never scrolled anywhere. An empty rect carries no\n * position at all, so it is deliberately never \"before the edge\"; what a caller\n * publishes for that case is its own policy (both consumers treat it as the\n * neutral \"not passed\"/\"not stuck\", and the real rect that arrives once the\n * target is laid out re-establishes the true state).\n */\nexport function isBeforeRootStart(entry: IntersectionObserverEntry): boolean {\n const rect = entry.boundingClientRect;\n if (rect.width === 0 && rect.height === 0) return false;\n // rootBounds is null for a cross-origin/removed root; fall back to the\n // viewport origin.\n const rootTop = entry.rootBounds?.top ?? 0;\n return rect.bottom <= rootTop;\n}\n\nexport interface IntersectionWatchOptions {\n /**\n * The observation root. Pass an element (or `null` for the viewport) when\n * the caller already resolved it; omit to resolve from `rootSelector`.\n */\n root?: Element | null;\n /** Selector for the observation root; empty/omitted = viewport. */\n rootSelector?: string;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\nexport class IntersectionWatcher {\n readonly #onEntries: (entries: IntersectionObserverEntry[]) => void;\n #observer: IntersectionObserver | null = null;\n #active = false;\n #usingPlatformDefaults = false;\n\n constructor(onEntries: (entries: IntersectionObserverEntry[]) => void) {\n this.#onEntries = onEntries;\n }\n\n /** Whether an observer is live (started, `IntersectionObserver` supported). */\n get active(): boolean {\n return this.#active;\n }\n\n /** Whether the live observer discarded configured options after construction failed. */\n get usingPlatformDefaults(): boolean {\n return this.#usingPlatformDefaults;\n }\n\n /**\n * (Re)creates the observer and observes `targets`. Returns `false` — leaving\n * the watcher inert — without `IntersectionObserver` support (very old\n * browsers; the caller's no-JS fallback stays in charge) or with no targets.\n * If initial construction with the configured options fails, the watcher\n * warns and retries once with the same root and platform defaults.\n *\n * @throws The fallback constructor error if both construction attempts fail,\n * or whatever the platform throws from `observe()`. The exception is passed\n * through unchanged, but the watcher rolls back first: every target observed\n * so far is released and `active` stays `false`, so a caller that retries\n * starts from a clean slate.\n */\n start(targets: Element | readonly Element[], options: IntersectionWatchOptions = {}): boolean {\n this.stop();\n if (typeof IntersectionObserver === \"undefined\") return false;\n const list = Array.isArray(targets) ? (targets as readonly Element[]) : [targets as Element];\n if (list.length === 0) return false;\n\n const root =\n \"root\" in options\n ? (options.root ?? null)\n : options.rootSelector\n ? document.querySelector(options.rootSelector)\n : null;\n\n let observer: IntersectionObserver | null = null;\n try {\n const onEntries = (entries: IntersectionObserverEntry[]): void => {\n // Identity matters across an immediate restart: the old observer can\n // flush a queued batch after the new observer has made `active` true.\n if (this.#active && this.#observer === observer) this.#onEntries(entries);\n };\n try {\n observer = new IntersectionObserver(onEntries, {\n root,\n rootMargin: options.rootMargin,\n threshold: options.threshold,\n });\n } catch (error) {\n console.warn(\n \"Stimeo UI: IntersectionObserver could not be constructed with the configured options; retrying with platform defaults.\",\n error,\n );\n observer = new IntersectionObserver(onEntries, { root });\n this.#usingPlatformDefaults = true;\n }\n for (const target of list) observer.observe(target);\n this.#observer = observer;\n this.#active = true;\n return true;\n } catch (error) {\n // A constructor or partial observe failure must not leave earlier targets\n // observed or report an active watcher. Preserve the platform exception.\n observer?.disconnect();\n this.#observer = null;\n this.#active = false;\n this.#usingPlatformDefaults = false;\n throw error;\n }\n }\n\n /**\n * Re-delivers `target`'s CURRENT intersection state: `IntersectionObserver`\n * only reports *changes*, but `observe()` always reports the present state,\n * so unobserve→observe turns \"still intersecting\" into a fresh callback.\n *\n * @throws Whatever `unobserve()`/`observe()` throws. The watcher is stopped\n * first, so it never stays live with a half-rearmed target.\n */\n rearm(target: Element): void {\n if (!this.#observer) return;\n try {\n this.#observer.unobserve(target);\n this.#observer.observe(target);\n } catch (error) {\n this.stop();\n throw error;\n }\n }\n\n /** Severs the observer; late queued callbacks become no-ops via the guard. */\n stop(): void {\n this.#active = false;\n this.#observer?.disconnect();\n this.#observer = null;\n this.#usingPlatformDefaults = false;\n }\n}\n","/**\n * Shared `prefers-reduced-motion` lookup for the motion-aware controllers\n *.\n *\n * This one-liner keeps the media query string and the environment guard\n * single-sourced across them. The preference is intentionally re-read on every\n * call — the controllers check it at each animation/scroll start (WCAG 2.2\n * **2.3.3**), so flipping the OS setting takes effect immediately without any\n * listener or cache bookkeeping here.\n */\n\n/**\n * Whether the user currently requests reduced motion.\n *\n * @returns `true` when `(prefers-reduced-motion: reduce)` matches; `false`\n * otherwise, including environments without `window.matchMedia` (treated as\n * \"no preference\").\n */\nexport function prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { IntersectionWatcher } from \"../utils/intersection_watcher\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\n/**\n * The attributes a link may anchor its section with, and therefore the only\n * ones whose rewrite has to re-sync the observation set. `aria-current` — the\n * attribute this controller writes itself — is deliberately absent, so\n * publishing the current location cannot feed back into a rebuild.\n */\nconst ANCHOR_ATTRIBUTES = [\"href\", \"data-href\"];\n\n/**\n * Headless, accessible **Scrollspy**: keeps a table of contents in sync with the\n * section the reader is currently in, published as `aria-current=\"location\"`.\n * There is no dedicated APG widget; it follows the `aria-current`\n * current-location practice inside a `<nav>` landmark.\n *\n * Markup contract (identifier: `stimeo--scrollspy`):\n * <nav data-controller=\"stimeo--scrollspy\"\n * data-stimeo--scrollspy-offset-value=\"80\"\n * data-stimeo--scrollspy-root-selector-value=\".content\"\n * aria-label=\"Table of contents\">\n * <a href=\"#intro\" data-stimeo--scrollspy-target=\"link\"\n * data-action=\"click->stimeo--scrollspy#scrollTo\">Intro</a>\n * <a href=\"#usage\" data-stimeo--scrollspy-target=\"link\"\n * data-action=\"click->stimeo--scrollspy#scrollTo\">Usage</a>\n * </nav>\n * <div class=\"content\">\n * <section id=\"intro\">…</section>\n * <section id=\"usage\">…</section>\n * </div>\n *\n * The active section is the one whose top edge sits closest to the **trigger\n * line**: `offset` px below the top of the *scroll root* — the `rootSelector`\n * container, or the viewport when that value is empty. It is not the viewport\n * top whenever a nested container is spied on. Intersecting sections win; when\n * none intersects (between two sections, scrolled past the last one) the\n * closest tracked section keeps the highlight, so a table of contents never\n * goes blank.\n *\n * `data-action` on the links is optional and opts into {@link scrollTo}, which\n * scrolls the nested container instead of bouncing the whole window.\n *\n * `change` dispatches `{ id: string, link: HTMLElement }`.\n *\n * @remarks\n * Behavior only — how a current link looks is the consumer's CSS\n * (`[aria-current=\"location\"] { … }`). `connect()` reads the current location\n * back from the DOM so a Turbo cache restore re-establishes it without a\n * redundant `change`, and `disconnect()` severs every resource acquired here:\n * the observers, the scroll listener, and any pending frame or queued rebuild.\n *\n * **What is followed automatically**, and what is not (the boundary a consumer\n * has to know, because everything outside it needs a re-`connect()`):\n *\n * - `link` targets added or removed — Stimulus's target callbacks.\n * - a `link` target's `href` / `data-href` rewritten in place — a Turbo 8 morph\n * keeps the element *and* its target marker, so no target callback fires;\n * {@link ANCHOR_ATTRIBUTES} is watched for exactly this case.\n * - the reader's scroll position, including inside a stretch where no section\n * crosses an observation threshold.\n *\n * Not followed: a *split* lifecycle in which the nav survives while the scroll\n * root or the sections are replaced underneath it. `rootSelector` is resolved\n * against the whole document and re-resolved once the cached container leaves\n * it, but section elements are looked up only while the observation set is\n * (re)built — swap those alone and nothing tells this controller to look again.\n */\nexport class ScrollspyController extends Controller<HTMLElement> {\n static override targets = [\"link\"];\n static override values = {\n offset: { type: Number, default: 0 },\n rootMargin: { type: String, default: \"\" },\n rootSelector: { type: String, default: \"\" },\n focusSection: { type: Boolean, default: false },\n };\n static actions = [\"scrollTo\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly linkTargets: HTMLElement[];\n\n declare offsetValue: number;\n declare rootMarginValue: string;\n declare rootSelectorValue: string;\n declare focusSectionValue: boolean;\n\n /**\n * The one offset shared by observation, active-section selection, and\n * scrolling. Stimulus parses a malformed Number Value as `NaN`; degrading it\n * to the declared default keeps every path aligned instead of only repairing\n * the observer margin while selection and scrolling still receive `NaN`.\n */\n get #offset(): number {\n return Number.isFinite(this.offsetValue) ? this.offsetValue : 0;\n }\n\n /** Shared IO plumbing (support guard, active guard, teardown). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersection(entries));\n #isConnected = false;\n\n /**\n * Sections currently tracked, by id. Only the *latest reported* intersection\n * flag is stored — never a coordinate. Positions are re-measured when the\n * active section is evaluated, so a section observed several batches ago is\n * never compared against a trigger line computed now.\n */\n #intersectionStates = new Map<string, { element: Element; isIntersecting: boolean }>();\n\n /** Current active section ID; comparing it suppresses duplicate `change` events. */\n #activeSectionId = \"\";\n\n /**\n * Scroll root resolved when the observer was (re)built; `null` = viewport.\n * Cached so a click and every intersection batch reuse the element the\n * observer is actually watching instead of re-querying the document.\n */\n #rootElement: HTMLElement | null = null;\n\n /**\n * The source the `scroll` listener is currently attached to — the resolved\n * root, or the window while the viewport is spied. `null` means \"nothing\n * attached\", so teardown always detaches from the source it attached to\n * rather than from whatever the selector resolves to now.\n */\n #scrollSource: HTMLElement | Window | null = null;\n\n /** Pending re-evaluation frame; coalesces a scroll burst into one measurement. */\n #frame: number | null = null;\n\n /** Watches the link targets' anchor attributes for an in-place morph rewrite. */\n #anchorObserver: MutationObserver | null = null;\n\n /** True while a coalesced observation rebuild is queued; see {@link #scheduleResync}. */\n #resyncQueued = false;\n\n override connect(): void {\n this.#isConnected = true;\n this.#observeAnchorAttributes();\n this.#initializeObserver();\n }\n\n override disconnect(): void {\n this.#isConnected = false;\n // Dropping the flag is what discards a rebuild queued moments ago: the\n // drain reads it, so the queued microtask becomes a no-op.\n this.#resyncQueued = false;\n this.#watcher.stop();\n this.#anchorObserver?.disconnect();\n this.#anchorObserver = null;\n this.#detachScrollListener();\n if (this.#frame !== null) {\n cancelAnimationFrame(this.#frame);\n this.#frame = null;\n }\n this.#intersectionStates.clear();\n this.#activeSectionId = \"\";\n this.#rootElement = null;\n }\n\n /**\n * Re-initializes the observer if the offset or rootMargin values change dynamically.\n */\n offsetValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n rootMarginValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n rootSelectorValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n /**\n * Re-syncs the observation set when a Turbo Stream/morph swaps the table of\n * contents. Stimulus fires these before `connect()` for the links already in\n * the markup, hence the guard: the initial observer is built exactly once, by\n * `connect()`.\n */\n linkTargetConnected(): void {\n if (this.#isConnected) this.#scheduleResync();\n }\n\n linkTargetDisconnected(): void {\n if (this.#isConnected) this.#scheduleResync();\n }\n\n /**\n * Queues **one** observation rebuild for the current mutation batch.\n *\n * A single Turbo morph can append one link, drop another, and rewrite a\n * third's `href`, and those arrive through two independent channels —\n * Stimulus's target callbacks and {@link #anchorObserver}. Each channel just\n * raises the flag and queues a drain; the first drain to run does the work and\n * clears it, so every later drain in the same batch finds nothing to do and\n * the set is rebuilt once instead of three times. `disconnect()` clears the\n * same flag, which is how a queued rebuild is dropped rather than run against\n * a detached controller.\n */\n #scheduleResync(): void {\n this.#resyncQueued = true;\n queueMicrotask(this.#drainResync);\n }\n\n readonly #drainResync = (): void => {\n if (!this.#resyncQueued) return;\n this.#resyncQueued = false;\n this.#initializeObserver();\n };\n\n /**\n * Watches the link targets' anchor attributes so an in-place rewrite re-syncs.\n *\n * A Turbo 8 morph keeps the element **and** its `data-*-target` marker and\n * only rewrites attributes, so Stimulus fires no target callback: without\n * this, a link re-pointed from `#intro` to `#faq` would keep the controller\n * observing `#intro` for the rest of the page's life. The filter is exactly\n * {@link ANCHOR_ATTRIBUTES}; guarding on `MutationObserver` keeps the\n * controller usable where the API is absent, matching `IntersectionWatcher`'s\n * own support guard.\n */\n #observeAnchorAttributes(): void {\n if (typeof MutationObserver !== \"undefined\") {\n this.#anchorObserver = new MutationObserver(this.#onAnchorMutation);\n this.#anchorObserver.observe(this.element, {\n subtree: true,\n attributes: true,\n attributeFilter: ANCHOR_ATTRIBUTES,\n });\n }\n }\n\n /**\n * Rebuilds only for a rewrite on a *current* link target. The observer is\n * scoped to this controller's element, but that subtree also holds links the\n * author never marked as targets (a \"back to top\" anchor, a nested nav), and\n * those anchor nothing here.\n */\n readonly #onAnchorMutation = (records: MutationRecord[]): void => {\n const links = this.linkTargets;\n for (const record of records) {\n if (!links.includes(record.target as HTMLElement)) continue;\n this.#scheduleResync();\n return;\n }\n };\n\n /**\n * Scrolls to the section the clicked link anchors, honoring `offset` and any\n * nested scroll container (a plain fragment jump would scroll the window).\n *\n * Honors `prefers-reduced-motion` (WCAG 2.2 **2.3.3**) by forcing an instant\n * jump independently of the consumer's CSS `scroll-behavior`. With\n * `focusSection` enabled it also moves the sequential focus starting point\n * into the destination; the URL fragment is deliberately not touched.\n */\n scrollTo(event: Event): void {\n const link = event.currentTarget as HTMLElement;\n const id = this.#getAnchorId(link);\n if (!id) return;\n\n event.preventDefault();\n\n const targetElement = document.getElementById(id);\n if (!targetElement) return;\n\n const behavior: ScrollBehavior = prefersReducedMotion() ? \"instant\" : \"smooth\";\n const rootElement = this.#scrollRoot();\n const targetRect = targetElement.getBoundingClientRect();\n const offset = this.#offset;\n\n if (rootElement) {\n const containerRect = rootElement.getBoundingClientRect();\n const scrollPosition = rootElement.scrollTop + (targetRect.top - containerRect.top) - offset;\n\n rootElement.scrollTo({ top: scrollPosition, behavior });\n } else {\n const scrollPosition = window.scrollY + targetRect.top - offset;\n\n window.scrollTo({ top: scrollPosition, behavior });\n }\n\n if (this.focusSectionValue) this.#focusSection(targetElement);\n }\n\n /**\n * Moves the sequential focus starting point into the section `scrollTo` just\n * jumped to, so the next Tab continues *inside* the destination instead of\n * resuming in the table of contents (`preventDefault()` alone would leave the\n * starting point on the link). Opt-in through `focusSection`, because moving\n * focus is a decision only the consuming page can make.\n *\n * `tabindex=\"-1\"` is established only when the section is not already\n * focusable and is never removed, so an author-owned tabindex is left alone.\n * `preventScroll` keeps the focus call from cancelling the smooth scroll\n * started just above.\n */\n #focusSection(section: HTMLElement): void {\n if (!section.hasAttribute(\"tabindex\")) section.setAttribute(\"tabindex\", \"-1\");\n section.focus({ preventScroll: true });\n }\n\n /**\n * The cached scroll root, re-resolved when the cached element has left the\n * document (a Turbo morph replaced the container) so `scrollTo` never\n * scrolls a detached node.\n */\n #scrollRoot(): HTMLElement | null {\n if (this.#rootElement && !this.#rootElement.isConnected) {\n this.#rootElement = this.#queryRootElement();\n }\n return this.#rootElement;\n }\n\n /**\n * Resolves `rootSelector` to a scrollable element.\n *\n * @returns The container, or `null` meaning \"spy the viewport\" when the value\n * is empty, matches nothing, matches a non-HTML element (an SVG node is not a\n * scroll container), or is not a valid selector — a typo in a data attribute\n * must degrade to viewport spying, not leave the controller inert.\n */\n #queryRootElement(): HTMLElement | null {\n if (!this.rootSelectorValue) return null;\n try {\n const root = document.querySelector(this.rootSelectorValue);\n return root instanceof HTMLElement ? root : null;\n } catch {\n return null;\n }\n }\n\n /**\n * Re-evaluates once per frame while the reader scrolls.\n *\n * `IntersectionObserver` reports **threshold crossings**, not positions, so a\n * reader moving inside one long section — or across a gap wider than the\n * observation band — produces no batch at all and the highlight would stay\n * frozen at whatever the last crossing decided. That would make the current\n * location depend on the *route* to a position instead of the position: a\n * stepwise scroll crosses thresholds an instant jump to the same offset never\n * does. Listening to the scroll source closes the gap, and because both paths\n * end in {@link #evaluateActiveSection} — which measures section rects and the\n * root's top edge at that instant — they converge on the same answer.\n */\n readonly #onScroll = (): void => {\n if (this.#frame !== null) return;\n this.#frame = requestAnimationFrame(() => {\n this.#frame = null;\n this.#evaluateActiveSection();\n });\n };\n\n /**\n * Points the `scroll` listener at whatever the reader actually scrolls: the\n * resolved root, or the window when the viewport is spied.\n *\n * The detach is unconditional, so rebuilding the observation set (a Value\n * change, a morph) **moves** the listener rather than stacking a second one on\n * a container the reader has stopped scrolling.\n */\n #syncScrollListener(): void {\n this.#detachScrollListener();\n this.#scrollSource = this.#rootElement ?? window;\n this.#scrollSource.addEventListener(\"scroll\", this.#onScroll, { passive: true });\n }\n\n #detachScrollListener(): void {\n this.#scrollSource?.removeEventListener(\"scroll\", this.#onScroll);\n this.#scrollSource = null;\n }\n\n #initializeObserver(): void {\n this.#watcher.stop();\n this.#intersectionStates.clear();\n // The DOM is the source of truth for the current location **only when this\n // controller has none of its own** — a fresh `connect()`, which is also the\n // Turbo cache-restore case, where the links still carry `aria-current` from\n // the snapshot. Adopting it there makes the observer's first batch a silent\n // confirmation instead of a duplicate `change`.\n //\n // On a *live* rebuild the memory wins, because the DOM has stopped meaning\n // what this controller wrote: an anchor rewritten underneath us leaves\n // `aria-current` on a link that now points somewhere else, so reading it\n // back would hand the current location to a section the reader never\n // scrolled to — and then announce the correction as a `change`, as if they\n // had travelled there and back.\n this.#activeSectionId = this.#activeSectionId || this.#activeIdFromDom();\n this.#rootElement = this.#queryRootElement();\n this.#syncScrollListener();\n\n if (this.linkTargets.length === 0) return;\n\n // Negate the numeric value so a valid negative offset becomes a positive margin.\n const margin = this.rootMarginValue || `${-this.#offset}px 0px -80% 0px`;\n\n // Observe each target section mapped by the href anchors.\n const sections: Element[] = [];\n for (const link of this.linkTargets) {\n const id = this.#getAnchorId(link);\n if (!id) continue;\n const section = document.getElementById(id);\n if (section && !sections.includes(section)) sections.push(section);\n }\n\n this.#watcher.start(sections, {\n root: this.#rootElement,\n rootMargin: margin,\n threshold: [0, 0.2, 0.4, 0.6, 0.8, 1], // Multiple thresholds handle large sections safely\n });\n\n // Republish the adopted location over the *current* link set. Evaluation\n // writes attributes only when the winning section changes, so a link added\n // — or re-anchored — while the reader stays put would otherwise never be\n // marked: a mobile table of contents rendered after the sidebar one would\n // stay blank until the reader happened to cross into another section.\n //\n // Unconditional, including when the adopted location is empty: a link whose\n // anchor was rewritten to something that resolves nowhere cannot be the\n // reader's location, and this controller is the one that published the\n // attribute saying it was, so it is the one that has to take it back.\n this.#syncActiveStates(false);\n }\n\n readonly #onIntersection = (entries: IntersectionObserverEntry[]): void => {\n // Defense in depth. `IntersectionWatcher` already drops a batch the browser\n // flushes after `stop()` (its active/identity guard), so this flag is the\n // second line that keeps a detached controller from mutating `aria-current`\n // on (possibly cached) links.\n const isDetached = !this.#isConnected;\n if (isDetached) return;\n\n for (const entry of entries) {\n const sectionId = entry.target.id;\n if (!sectionId) continue;\n\n this.#intersectionStates.set(sectionId, {\n element: entry.target,\n isIntersecting: entry.isIntersecting,\n });\n }\n\n this.#evaluateActiveSection();\n };\n\n /**\n * Picks the section closest to the trigger line and publishes it.\n *\n * Every coordinate is read **now**: the section rects *and* the root's top\n * edge share one measurement instant. Comparing an entry's recorded\n * `boundingClientRect.top` (captured whenever that section last crossed a\n * threshold) against a freshly computed trigger line mixes two moments in\n * time, which would make the result depend on how the reader arrived at a\n * position — a smooth scroll and an instant jump to the same offset disagree.\n */\n #evaluateActiveSection(): void {\n // The trigger line is `offset` px below the top of the scroll root. When a\n // nested `rootSelector` container is used it is not at the viewport top, so\n // the line must be measured from the container's current top — comparing the\n // viewport-based rect top against a bare `offset` would otherwise pick the\n // section nearest the viewport top, not the container's.\n const rootEl = this.#scrollRoot();\n const triggerLine = (rootEl ? rootEl.getBoundingClientRect().top : 0) + this.#offset;\n\n let intersectingId = \"\";\n let intersectingDistance = Number.POSITIVE_INFINITY;\n let trackedId = \"\";\n let trackedDistance = Number.POSITIVE_INFINITY;\n\n for (const [id, state] of this.#intersectionStates) {\n const rect = state.element.getBoundingClientRect();\n // A section with no layout box (`display: none`, a collapsed `<details>`,\n // an undisplayed Turbo Frame) is reported with an empty rect whose `top`\n // of 0 carries no position at all. Letting it compete would hand it the\n // fallback below; it re-enters the race once it is actually laid out.\n if (rect.width === 0 && rect.height === 0) continue;\n\n const distance = Math.abs(rect.top - triggerLine);\n if (distance < trackedDistance) {\n trackedDistance = distance;\n trackedId = id;\n }\n if (state.isIntersecting && distance < intersectingDistance) {\n intersectingDistance = distance;\n intersectingId = id;\n }\n }\n\n // Fallback: when no section currently intersects (e.g. scrolled past the\n // bottom, or between sections), keep the tracked section whose top is\n // closest to the trigger line so something stays highlighted.\n const bestId = intersectingId || trackedId;\n\n if (bestId && bestId !== this.#activeSectionId) {\n this.#activeSectionId = bestId;\n this.#syncActiveStates(true);\n }\n }\n\n /**\n * Writes `aria-current` across the current link set, optionally announcing.\n *\n * The two halves are separate because they answer different questions.\n * *Attributes* must be idempotently re-established whenever the link set\n * changes, even though the reader has not moved — otherwise a link that\n * appears (or is re-anchored) while its section is already current never gets\n * marked. *The `change` event* announces that the reader moved, so it fires\n * only from the evaluation path; re-publishing over a new link set is not\n * news, and dispatching there would make a rebuild look like navigation.\n *\n * @param announce Whether this sync represents a change of current section.\n */\n #syncActiveStates(announce: boolean): void {\n // Every link anchoring the active section is marked, not just the first:\n // a page may render the same table of contents twice (a sidebar and a\n // collapsed mobile menu) and both must show the current location.\n const activeLinks = this.linkTargets.filter(\n (link) => this.#getAnchorId(link) === this.#activeSectionId,\n );\n\n for (const link of this.linkTargets) {\n if (activeLinks.includes(link)) {\n link.setAttribute(\"aria-current\", \"location\");\n } else if (link.getAttribute(\"aria-current\") === \"location\") {\n // Reclaim only the value this controller publishes, so an author-owned\n // `aria-current=\"page\"` on a table-of-contents link survives.\n link.removeAttribute(\"aria-current\");\n }\n }\n\n if (!announce) return;\n\n const primaryLink = activeLinks[0];\n if (primaryLink) {\n this.dispatch(\"change\", { detail: { id: this.#activeSectionId, link: primaryLink } });\n }\n }\n\n /**\n * The current location already encoded in the DOM, i.e. the section anchored\n * by the first link carrying this controller's `aria-current=\"location\"`.\n * Empty when no link claims it (a genuinely fresh render).\n */\n #activeIdFromDom(): string {\n for (const link of this.linkTargets) {\n if (link.getAttribute(\"aria-current\") !== \"location\") continue;\n const id = this.#getAnchorId(link);\n if (id) return id;\n }\n return \"\";\n }\n\n /**\n * The section id a link anchors, resolved in a fixed order:\n *\n * 1. `href`, when it is a non-empty same-document fragment — the contract.\n * 2. otherwise `data-href`'s fragment — the fallback for a link whose `href`\n * must stay a real URL (a server-rendered permalink) or that is not an\n * `<a>` at all.\n * 3. otherwise `null`: the link anchors nothing here and is not observed.\n *\n * Step 2 is reached whenever `href` yields nothing usable — absent, `\"#\"`, or\n * a real URL — which is the whole point of the fallback: `href=\"/guide/usage\"`\n * with `data-href=\"#usage\"` is a permalink that also spies, and picking the\n * first *present* attribute instead of the first *usable* one would silently\n * exclude exactly that markup. When both are valid fragments `href` wins.\n */\n #getAnchorId(link: HTMLElement): string | null {\n return (\n this.#fragmentId(link.getAttribute(\"href\")) ??\n this.#fragmentId(link.getAttribute(\"data-href\"))\n );\n }\n\n /** The id in a `#fragment` value; `null` for absent, empty, or non-fragment. */\n #fragmentId(value: string | null): string | null {\n if (!value?.startsWith(\"#\")) return null;\n return value.substring(1) || null;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/utils/reduced_motion.ts","../../src/controllers/scrollspy_controller.ts"],"names":[],"mappings":";;;;;AA8CA,SAAS,UAAU,QAAA,EAA8C;AAC/D,EAAA,IAAI,CAAC,UAAU,OAAO,IAAA;AACtB,EAAA,IAAI;AACF,IAAA,OAAO,QAAA,CAAS,cAAc,QAAQ,CAAA;AAAA,EACxC,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,OAAO,IAAA;AACT;AAiBO,IAAM,sBAAN,MAA0B;AAAA,EACtB,UAAA;AAAA,EACT,SAAA,GAAyC,IAAA;AAAA,EACzC,OAAA,GAAU,KAAA;AAAA,EACV,sBAAA,GAAyB,KAAA;AAAA,EAEzB,YAAY,SAAA,EAA2D;AACrE,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,IAAI,MAAA,GAAkB;AACpB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA;AAAA,EAGA,IAAI,qBAAA,GAAiC;AACnC,IAAA,OAAO,IAAA,CAAK,sBAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,KAAA,CAAM,OAAA,EAAuC,OAAA,GAAoC,EAAC,EAAY;AAC5F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I,IAAA,CAAK,gBAAA,EAAkB,IAAA,EAAM,WAAA,EAAY,EAAG,CAAA;AAAA,IACtF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,gBAAA,GAA2B;AACzB,IAAA,KAAA,MAAW,IAAA,IAAQ,KAAK,WAAA,EAAa;AACnC,MAAA,IAAI,IAAA,CAAK,YAAA,CAAa,cAAc,CAAA,KAAM,UAAA,EAAY;AACtD,MAAA,MAAM,EAAA,GAAK,IAAA,CAAK,YAAA,CAAa,IAAI,CAAA;AACjC,MAAA,IAAI,IAAI,OAAO,EAAA;AAAA,IACjB;AACA,IAAA,OAAO,EAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,aAAa,IAAA,EAAkC;AAC7C,IAAA,OACE,IAAA,CAAK,WAAA,CAAY,IAAA,CAAK,YAAA,CAAa,MAAM,CAAC,CAAA,IAC1C,IAAA,CAAK,WAAA,CAAY,IAAA,CAAK,YAAA,CAAa,WAAW,CAAC,CAAA;AAAA,EAEnD;AAAA;AAAA,EAGA,YAAY,KAAA,EAAqC;AAC/C,IAAA,IAAI,CAAC,KAAA,EAAO,UAAA,CAAW,GAAG,GAAG,OAAO,IAAA;AACpC,IAAA,OAAO,KAAA,CAAM,SAAA,CAAU,CAAC,CAAA,IAAK,IAAA;AAAA,EAC/B;AACF","file":"scrollspy_controller.js","sourcesContent":["/**\n * Shared `IntersectionObserver` plumbing for Stimeo's scroll-triggered\n * controllers (`intersection`, `scrollspy`, `sticky-observer`, `lazy-frame`).\n *\n * It centralizes the `IntersectionObserver` support guard, root resolution from\n * a selector (degrading to the viewport rather than failing), observer\n * creation/teardown, the **active guard** (the browser may\n * flush a final queued callback batch right after `disconnect()`, and a\n * detached controller must not mutate possibly-cached DOM), and the\n * unobserve→observe **re-arm** that re-delivers the current state even when the\n * target never leaves the viewport.\n *\n * Like {@link RovingTabindex} and `FocusTrap`, this is a policy-free internal\n * util: what an intersection *means* (a spied link, a stuck header, a lazy\n * load) stays in each controller. The public `stimeo--intersection` controller\n * is its thin declarative face.\n */\n/**\n * Whether `entry`'s target sits entirely before the root's **start (top)** edge —\n * the \"scrolled past the top\" half of a non-intersecting entry, as opposed to\n * \"not reached yet\" below the root.\n *\n * A target with no layout box (`display: none`, a `hidden` ancestor, a collapsed\n * `<details>`) is reported with an **empty rect**, whose `bottom` of `0` would\n * otherwise satisfy `bottom <= rootTop` for a viewport root and read as \"passed\"\n * even though the target was never scrolled anywhere. An empty rect carries no\n * position at all, so it is deliberately never \"before the edge\"; what a caller\n * publishes for that case is its own policy (both consumers treat it as the\n * neutral \"not passed\"/\"not stuck\", and the real rect that arrives once the\n * target is laid out re-establishes the true state).\n */\nexport function isBeforeRootStart(entry: IntersectionObserverEntry): boolean {\n const rect = entry.boundingClientRect;\n if (rect.width === 0 && rect.height === 0) return false;\n // rootBounds is null for a cross-origin/removed root; fall back to the\n // viewport origin.\n const rootTop = entry.rootBounds?.top ?? 0;\n return rect.bottom <= rootTop;\n}\n\n/**\n * Resolves an observation root from a selector. Every reading of \"no root\" ends\n * at the same place — absent, matching nothing, or not parsing at all (a typo in\n * a data attribute) — so the observation falls back to the viewport instead of\n * leaving the caller inert with no state hooks published at all.\n */\nfunction queryRoot(selector: string | undefined): Element | null {\n if (!selector) return null;\n try {\n return document.querySelector(selector);\n } catch {\n // Unparsable selector: fall through to the viewport below.\n }\n return null;\n}\n\nexport interface IntersectionWatchOptions {\n /**\n * The observation root. Pass an element (or `null` for the viewport) when\n * the caller already resolved it; omit to resolve from `rootSelector`.\n */\n root?: Element | null;\n /**\n * Selector for the observation root; empty/omitted = viewport. A selector\n * that matches nothing or does not parse also means the viewport.\n */\n rootSelector?: string;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\nexport class IntersectionWatcher {\n readonly #onEntries: (entries: IntersectionObserverEntry[]) => void;\n #observer: IntersectionObserver | null = null;\n #active = false;\n #usingPlatformDefaults = false;\n\n constructor(onEntries: (entries: IntersectionObserverEntry[]) => void) {\n this.#onEntries = onEntries;\n }\n\n /** Whether an observer is live (started, `IntersectionObserver` supported). */\n get active(): boolean {\n return this.#active;\n }\n\n /** Whether the live observer discarded configured options after construction failed. */\n get usingPlatformDefaults(): boolean {\n return this.#usingPlatformDefaults;\n }\n\n /**\n * (Re)creates the observer and observes `targets`. Returns `false` — leaving\n * the watcher inert — without `IntersectionObserver` support (very old\n * browsers; the caller's no-JS fallback stays in charge) or with no targets.\n * If initial construction with the configured options fails, the watcher\n * warns and retries once with the same root and platform defaults. A\n * `rootSelector` that does not parse resolves to the viewport (see\n * {@link IntersectionWatchOptions.rootSelector}), so a typo never fails the\n * call.\n *\n * @throws The fallback constructor error if both construction attempts fail,\n * or whatever the platform throws from `observe()`. The exception is passed\n * through unchanged, but the watcher rolls back first: every target observed\n * so far is released and `active` stays `false`, so a caller that retries\n * starts from a clean slate.\n */\n start(targets: Element | readonly Element[], options: IntersectionWatchOptions = {}): boolean {\n this.stop();\n if (typeof IntersectionObserver === \"undefined\") return false;\n const list = Array.isArray(targets) ? (targets as readonly Element[]) : [targets as Element];\n if (list.length === 0) return false;\n\n const root = \"root\" in options ? (options.root ?? null) : queryRoot(options.rootSelector);\n\n let observer: IntersectionObserver | null = null;\n try {\n const onEntries = (entries: IntersectionObserverEntry[]): void => {\n // Identity matters across an immediate restart: the old observer can\n // flush a queued batch after the new observer has made `active` true.\n if (this.#active && this.#observer === observer) this.#onEntries(entries);\n };\n try {\n observer = new IntersectionObserver(onEntries, {\n root,\n rootMargin: options.rootMargin,\n threshold: options.threshold,\n });\n } catch (error) {\n console.warn(\n \"Stimeo UI: IntersectionObserver could not be constructed with the configured options; retrying with platform defaults.\",\n error,\n );\n observer = new IntersectionObserver(onEntries, { root });\n this.#usingPlatformDefaults = true;\n }\n for (const target of list) observer.observe(target);\n this.#observer = observer;\n this.#active = true;\n return true;\n } catch (error) {\n // A constructor or partial observe failure must not leave earlier targets\n // observed or report an active watcher. Preserve the platform exception.\n observer?.disconnect();\n this.#observer = null;\n this.#active = false;\n this.#usingPlatformDefaults = false;\n throw error;\n }\n }\n\n /**\n * Re-delivers `target`'s CURRENT intersection state: `IntersectionObserver`\n * only reports *changes*, but `observe()` always reports the present state,\n * so unobserve→observe turns \"still intersecting\" into a fresh callback.\n *\n * @throws Whatever `unobserve()`/`observe()` throws. The watcher is stopped\n * first, so it never stays live with a half-rearmed target.\n */\n rearm(target: Element): void {\n if (!this.#observer) return;\n try {\n this.#observer.unobserve(target);\n this.#observer.observe(target);\n } catch (error) {\n this.stop();\n throw error;\n }\n }\n\n /** Severs the observer; late queued callbacks become no-ops via the guard. */\n stop(): void {\n this.#active = false;\n this.#observer?.disconnect();\n this.#observer = null;\n this.#usingPlatformDefaults = false;\n }\n}\n","/**\n * Shared `prefers-reduced-motion` lookup for the motion-aware controllers\n *.\n *\n * This one-liner keeps the media query string and the environment guard\n * single-sourced across them. The preference is intentionally re-read on every\n * call — the controllers check it at each animation/scroll start (WCAG 2.2\n * **2.3.3**), so flipping the OS setting takes effect immediately without any\n * listener or cache bookkeeping here.\n */\n\n/**\n * Whether the user currently requests reduced motion.\n *\n * @returns `true` when `(prefers-reduced-motion: reduce)` matches; `false`\n * otherwise, including environments without `window.matchMedia` (treated as\n * \"no preference\").\n */\nexport function prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { IntersectionWatcher } from \"../utils/intersection_watcher\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\n/**\n * The attributes a link may anchor its section with, and therefore the only\n * ones whose rewrite has to re-sync the observation set. `aria-current` — the\n * attribute this controller writes itself — is deliberately absent, so\n * publishing the current location cannot feed back into a rebuild.\n */\nconst ANCHOR_ATTRIBUTES = [\"href\", \"data-href\"];\n\n/**\n * Headless, accessible **Scrollspy**: keeps a table of contents in sync with the\n * section the reader is currently in, published as `aria-current=\"location\"`.\n * There is no dedicated APG widget; it follows the `aria-current`\n * current-location practice inside a `<nav>` landmark.\n *\n * Markup contract (identifier: `stimeo--scrollspy`):\n * <nav data-controller=\"stimeo--scrollspy\"\n * data-stimeo--scrollspy-offset-value=\"80\"\n * data-stimeo--scrollspy-root-selector-value=\".content\"\n * aria-label=\"Table of contents\">\n * <a href=\"#intro\" data-stimeo--scrollspy-target=\"link\"\n * data-action=\"click->stimeo--scrollspy#scrollTo\">Intro</a>\n * <a href=\"#usage\" data-stimeo--scrollspy-target=\"link\"\n * data-action=\"click->stimeo--scrollspy#scrollTo\">Usage</a>\n * </nav>\n * <div class=\"content\">\n * <section id=\"intro\">…</section>\n * <section id=\"usage\">…</section>\n * </div>\n *\n * The active section is the one whose top edge sits closest to the **trigger\n * line**: `offset` px below the top of the *scroll root* — the `rootSelector`\n * container, or the viewport when that value is empty. It is not the viewport\n * top whenever a nested container is spied on. Intersecting sections win; when\n * none intersects (between two sections, scrolled past the last one) the\n * closest tracked section keeps the highlight, so a table of contents never\n * goes blank.\n *\n * `data-action` on the links is optional and opts into {@link scrollTo}, which\n * scrolls the nested container instead of bouncing the whole window.\n *\n * `change` dispatches `{ id: string, link: HTMLElement }`.\n *\n * @remarks\n * Behavior only — how a current link looks is the consumer's CSS\n * (`[aria-current=\"location\"] { … }`). `connect()` reads the current location\n * back from the DOM so a Turbo cache restore re-establishes it without a\n * redundant `change`, and `disconnect()` severs every resource acquired here:\n * the observers, the scroll listener, and any pending frame or queued rebuild.\n *\n * **What is followed automatically**, and what is not (the boundary a consumer\n * has to know, because everything outside it needs a re-`connect()`):\n *\n * - `link` targets added or removed — Stimulus's target callbacks.\n * - a `link` target's `href` / `data-href` rewritten in place — a Turbo 8 morph\n * keeps the element *and* its target marker, so no target callback fires;\n * {@link ANCHOR_ATTRIBUTES} is watched for exactly this case.\n * - the reader's scroll position, including inside a stretch where no section\n * crosses an observation threshold.\n *\n * Not followed: a *split* lifecycle in which the nav survives while the scroll\n * root or the sections are replaced underneath it. `rootSelector` is resolved\n * against the whole document and re-resolved once the cached container leaves\n * it, but section elements are looked up only while the observation set is\n * (re)built — swap those alone and nothing tells this controller to look again.\n */\nexport class ScrollspyController extends Controller<HTMLElement> {\n static override targets = [\"link\"];\n static override values = {\n offset: { type: Number, default: 0 },\n rootMargin: { type: String, default: \"\" },\n rootSelector: { type: String, default: \"\" },\n focusSection: { type: Boolean, default: false },\n };\n static actions = [\"scrollTo\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly linkTargets: HTMLElement[];\n\n declare offsetValue: number;\n declare rootMarginValue: string;\n declare rootSelectorValue: string;\n declare focusSectionValue: boolean;\n\n /**\n * The one offset shared by observation, active-section selection, and\n * scrolling. Stimulus parses a malformed Number Value as `NaN`; degrading it\n * to the declared default keeps every path aligned instead of only repairing\n * the observer margin while selection and scrolling still receive `NaN`.\n */\n get #offset(): number {\n return Number.isFinite(this.offsetValue) ? this.offsetValue : 0;\n }\n\n /** Shared IO plumbing (support guard, active guard, teardown). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersection(entries));\n #isConnected = false;\n\n /**\n * Sections currently tracked, by id. Only the *latest reported* intersection\n * flag is stored — never a coordinate. Positions are re-measured when the\n * active section is evaluated, so a section observed several batches ago is\n * never compared against a trigger line computed now.\n */\n #intersectionStates = new Map<string, { element: Element; isIntersecting: boolean }>();\n\n /** Current active section ID; comparing it suppresses duplicate `change` events. */\n #activeSectionId = \"\";\n\n /**\n * Scroll root resolved when the observer was (re)built; `null` = viewport.\n * Cached so a click and every intersection batch reuse the element the\n * observer is actually watching instead of re-querying the document.\n */\n #rootElement: HTMLElement | null = null;\n\n /**\n * The source the `scroll` listener is currently attached to — the resolved\n * root, or the window while the viewport is spied. `null` means \"nothing\n * attached\", so teardown always detaches from the source it attached to\n * rather than from whatever the selector resolves to now.\n */\n #scrollSource: HTMLElement | Window | null = null;\n\n /** Pending re-evaluation frame; coalesces a scroll burst into one measurement. */\n #frame: number | null = null;\n\n /** Watches the link targets' anchor attributes for an in-place morph rewrite. */\n #anchorObserver: MutationObserver | null = null;\n\n /** True while a coalesced observation rebuild is queued; see {@link #scheduleResync}. */\n #resyncQueued = false;\n\n override connect(): void {\n this.#isConnected = true;\n this.#observeAnchorAttributes();\n this.#initializeObserver();\n }\n\n override disconnect(): void {\n this.#isConnected = false;\n // Dropping the flag is what discards a rebuild queued moments ago: the\n // drain reads it, so the queued microtask becomes a no-op.\n this.#resyncQueued = false;\n this.#watcher.stop();\n this.#anchorObserver?.disconnect();\n this.#anchorObserver = null;\n this.#detachScrollListener();\n if (this.#frame !== null) {\n cancelAnimationFrame(this.#frame);\n this.#frame = null;\n }\n this.#intersectionStates.clear();\n this.#activeSectionId = \"\";\n this.#rootElement = null;\n }\n\n /**\n * Re-initializes the observer if the offset or rootMargin values change dynamically.\n */\n offsetValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n rootMarginValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n rootSelectorValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n /**\n * Re-syncs the observation set when a Turbo Stream/morph swaps the table of\n * contents. Stimulus fires these before `connect()` for the links already in\n * the markup, hence the guard: the initial observer is built exactly once, by\n * `connect()`.\n */\n linkTargetConnected(): void {\n if (this.#isConnected) this.#scheduleResync();\n }\n\n linkTargetDisconnected(): void {\n if (this.#isConnected) this.#scheduleResync();\n }\n\n /**\n * Queues **one** observation rebuild for the current mutation batch.\n *\n * A single Turbo morph can append one link, drop another, and rewrite a\n * third's `href`, and those arrive through two independent channels —\n * Stimulus's target callbacks and {@link #anchorObserver}. Each channel just\n * raises the flag and queues a drain; the first drain to run does the work and\n * clears it, so every later drain in the same batch finds nothing to do and\n * the set is rebuilt once instead of three times. `disconnect()` clears the\n * same flag, which is how a queued rebuild is dropped rather than run against\n * a detached controller.\n */\n #scheduleResync(): void {\n this.#resyncQueued = true;\n queueMicrotask(this.#drainResync);\n }\n\n readonly #drainResync = (): void => {\n if (!this.#resyncQueued) return;\n this.#resyncQueued = false;\n this.#initializeObserver();\n };\n\n /**\n * Watches the link targets' anchor attributes so an in-place rewrite re-syncs.\n *\n * A Turbo 8 morph keeps the element **and** its `data-*-target` marker and\n * only rewrites attributes, so Stimulus fires no target callback: without\n * this, a link re-pointed from `#intro` to `#faq` would keep the controller\n * observing `#intro` for the rest of the page's life. The filter is exactly\n * {@link ANCHOR_ATTRIBUTES}; guarding on `MutationObserver` keeps the\n * controller usable where the API is absent, matching `IntersectionWatcher`'s\n * own support guard.\n */\n #observeAnchorAttributes(): void {\n if (typeof MutationObserver !== \"undefined\") {\n this.#anchorObserver = new MutationObserver(this.#onAnchorMutation);\n this.#anchorObserver.observe(this.element, {\n subtree: true,\n attributes: true,\n attributeFilter: ANCHOR_ATTRIBUTES,\n });\n }\n }\n\n /**\n * Rebuilds only for a rewrite on a *current* link target. The observer is\n * scoped to this controller's element, but that subtree also holds links the\n * author never marked as targets (a \"back to top\" anchor, a nested nav), and\n * those anchor nothing here.\n */\n readonly #onAnchorMutation = (records: MutationRecord[]): void => {\n const links = this.linkTargets;\n for (const record of records) {\n if (!links.includes(record.target as HTMLElement)) continue;\n this.#scheduleResync();\n return;\n }\n };\n\n /**\n * Scrolls to the section the clicked link anchors, honoring `offset` and any\n * nested scroll container (a plain fragment jump would scroll the window).\n *\n * Honors `prefers-reduced-motion` (WCAG 2.2 **2.3.3**) by forcing an instant\n * jump independently of the consumer's CSS `scroll-behavior`. With\n * `focusSection` enabled it also moves the sequential focus starting point\n * into the destination; the URL fragment is deliberately not touched.\n */\n scrollTo(event: Event): void {\n const link = event.currentTarget as HTMLElement;\n const id = this.#getAnchorId(link);\n if (!id) return;\n\n event.preventDefault();\n\n const targetElement = document.getElementById(id);\n if (!targetElement) return;\n\n const behavior: ScrollBehavior = prefersReducedMotion() ? \"instant\" : \"smooth\";\n const rootElement = this.#scrollRoot();\n const targetRect = targetElement.getBoundingClientRect();\n const offset = this.#offset;\n\n if (rootElement) {\n const containerRect = rootElement.getBoundingClientRect();\n const scrollPosition = rootElement.scrollTop + (targetRect.top - containerRect.top) - offset;\n\n rootElement.scrollTo({ top: scrollPosition, behavior });\n } else {\n const scrollPosition = window.scrollY + targetRect.top - offset;\n\n window.scrollTo({ top: scrollPosition, behavior });\n }\n\n if (this.focusSectionValue) this.#focusSection(targetElement);\n }\n\n /**\n * Moves the sequential focus starting point into the section `scrollTo` just\n * jumped to, so the next Tab continues *inside* the destination instead of\n * resuming in the table of contents (`preventDefault()` alone would leave the\n * starting point on the link). Opt-in through `focusSection`, because moving\n * focus is a decision only the consuming page can make.\n *\n * `tabindex=\"-1\"` is established only when the section is not already\n * focusable and is never removed, so an author-owned tabindex is left alone.\n * `preventScroll` keeps the focus call from cancelling the smooth scroll\n * started just above.\n */\n #focusSection(section: HTMLElement): void {\n if (!section.hasAttribute(\"tabindex\")) section.setAttribute(\"tabindex\", \"-1\");\n section.focus({ preventScroll: true });\n }\n\n /**\n * The cached scroll root, re-resolved when the cached element has left the\n * document (a Turbo morph replaced the container) so `scrollTo` never\n * scrolls a detached node.\n */\n #scrollRoot(): HTMLElement | null {\n if (this.#rootElement && !this.#rootElement.isConnected) {\n this.#rootElement = this.#queryRootElement();\n }\n return this.#rootElement;\n }\n\n /**\n * Resolves `rootSelector` to a scrollable element.\n *\n * @returns The container, or `null` meaning \"spy the viewport\" when the value\n * is empty, matches nothing, matches a non-HTML element (an SVG node is not a\n * scroll container), or is not a valid selector — a typo in a data attribute\n * must degrade to viewport spying, not leave the controller inert.\n */\n #queryRootElement(): HTMLElement | null {\n if (!this.rootSelectorValue) return null;\n try {\n const root = document.querySelector(this.rootSelectorValue);\n return root instanceof HTMLElement ? root : null;\n } catch {\n return null;\n }\n }\n\n /**\n * Re-evaluates once per frame while the reader scrolls.\n *\n * `IntersectionObserver` reports **threshold crossings**, not positions, so a\n * reader moving inside one long section — or across a gap wider than the\n * observation band — produces no batch at all and the highlight would stay\n * frozen at whatever the last crossing decided. That would make the current\n * location depend on the *route* to a position instead of the position: a\n * stepwise scroll crosses thresholds an instant jump to the same offset never\n * does. Listening to the scroll source closes the gap, and because both paths\n * end in {@link #evaluateActiveSection} — which measures section rects and the\n * root's top edge at that instant — they converge on the same answer.\n */\n readonly #onScroll = (): void => {\n if (this.#frame !== null) return;\n this.#frame = requestAnimationFrame(() => {\n this.#frame = null;\n this.#evaluateActiveSection();\n });\n };\n\n /**\n * Points the `scroll` listener at whatever the reader actually scrolls: the\n * resolved root, or the window when the viewport is spied.\n *\n * The detach is unconditional, so rebuilding the observation set (a Value\n * change, a morph) **moves** the listener rather than stacking a second one on\n * a container the reader has stopped scrolling.\n */\n #syncScrollListener(): void {\n this.#detachScrollListener();\n this.#scrollSource = this.#rootElement ?? window;\n this.#scrollSource.addEventListener(\"scroll\", this.#onScroll, { passive: true });\n }\n\n #detachScrollListener(): void {\n this.#scrollSource?.removeEventListener(\"scroll\", this.#onScroll);\n this.#scrollSource = null;\n }\n\n #initializeObserver(): void {\n this.#watcher.stop();\n this.#intersectionStates.clear();\n // The DOM is the source of truth for the current location **only when this\n // controller has none of its own** — a fresh `connect()`, which is also the\n // Turbo cache-restore case, where the links still carry `aria-current` from\n // the snapshot. Adopting it there makes the observer's first batch a silent\n // confirmation instead of a duplicate `change`.\n //\n // On a *live* rebuild the memory wins, because the DOM has stopped meaning\n // what this controller wrote: an anchor rewritten underneath us leaves\n // `aria-current` on a link that now points somewhere else, so reading it\n // back would hand the current location to a section the reader never\n // scrolled to — and then announce the correction as a `change`, as if they\n // had travelled there and back.\n this.#activeSectionId = this.#activeSectionId || this.#activeIdFromDom();\n this.#rootElement = this.#queryRootElement();\n this.#syncScrollListener();\n\n if (this.linkTargets.length === 0) return;\n\n // Negate the numeric value so a valid negative offset becomes a positive margin.\n const margin = this.rootMarginValue || `${-this.#offset}px 0px -80% 0px`;\n\n // Observe each target section mapped by the href anchors.\n const sections: Element[] = [];\n for (const link of this.linkTargets) {\n const id = this.#getAnchorId(link);\n if (!id) continue;\n const section = document.getElementById(id);\n if (section && !sections.includes(section)) sections.push(section);\n }\n\n this.#watcher.start(sections, {\n root: this.#rootElement,\n rootMargin: margin,\n threshold: [0, 0.2, 0.4, 0.6, 0.8, 1], // Multiple thresholds handle large sections safely\n });\n\n // Republish the adopted location over the *current* link set. Evaluation\n // writes attributes only when the winning section changes, so a link added\n // — or re-anchored — while the reader stays put would otherwise never be\n // marked: a mobile table of contents rendered after the sidebar one would\n // stay blank until the reader happened to cross into another section.\n //\n // Unconditional, including when the adopted location is empty: a link whose\n // anchor was rewritten to something that resolves nowhere cannot be the\n // reader's location, and this controller is the one that published the\n // attribute saying it was, so it is the one that has to take it back.\n this.#syncActiveStates(false);\n }\n\n readonly #onIntersection = (entries: IntersectionObserverEntry[]): void => {\n // Defense in depth. `IntersectionWatcher` already drops a batch the browser\n // flushes after `stop()` (its active/identity guard), so this flag is the\n // second line that keeps a detached controller from mutating `aria-current`\n // on (possibly cached) links.\n const isDetached = !this.#isConnected;\n if (isDetached) return;\n\n for (const entry of entries) {\n const sectionId = entry.target.id;\n if (!sectionId) continue;\n\n this.#intersectionStates.set(sectionId, {\n element: entry.target,\n isIntersecting: entry.isIntersecting,\n });\n }\n\n this.#evaluateActiveSection();\n };\n\n /**\n * Picks the section closest to the trigger line and publishes it.\n *\n * Every coordinate is read **now**: the section rects *and* the root's top\n * edge share one measurement instant. Comparing an entry's recorded\n * `boundingClientRect.top` (captured whenever that section last crossed a\n * threshold) against a freshly computed trigger line mixes two moments in\n * time, which would make the result depend on how the reader arrived at a\n * position — a smooth scroll and an instant jump to the same offset disagree.\n */\n #evaluateActiveSection(): void {\n // The trigger line is `offset` px below the top of the scroll root. When a\n // nested `rootSelector` container is used it is not at the viewport top, so\n // the line must be measured from the container's current top — comparing the\n // viewport-based rect top against a bare `offset` would otherwise pick the\n // section nearest the viewport top, not the container's.\n const rootEl = this.#scrollRoot();\n const triggerLine = (rootEl ? rootEl.getBoundingClientRect().top : 0) + this.#offset;\n\n let intersectingId = \"\";\n let intersectingDistance = Number.POSITIVE_INFINITY;\n let trackedId = \"\";\n let trackedDistance = Number.POSITIVE_INFINITY;\n\n for (const [id, state] of this.#intersectionStates) {\n const rect = state.element.getBoundingClientRect();\n // A section with no layout box (`display: none`, a collapsed `<details>`,\n // an undisplayed Turbo Frame) is reported with an empty rect whose `top`\n // of 0 carries no position at all. Letting it compete would hand it the\n // fallback below; it re-enters the race once it is actually laid out.\n if (rect.width === 0 && rect.height === 0) continue;\n\n const distance = Math.abs(rect.top - triggerLine);\n if (distance < trackedDistance) {\n trackedDistance = distance;\n trackedId = id;\n }\n if (state.isIntersecting && distance < intersectingDistance) {\n intersectingDistance = distance;\n intersectingId = id;\n }\n }\n\n // Fallback: when no section currently intersects (e.g. scrolled past the\n // bottom, or between sections), keep the tracked section whose top is\n // closest to the trigger line so something stays highlighted.\n const bestId = intersectingId || trackedId;\n\n if (bestId && bestId !== this.#activeSectionId) {\n this.#activeSectionId = bestId;\n this.#syncActiveStates(true);\n }\n }\n\n /**\n * Writes `aria-current` across the current link set, optionally announcing.\n *\n * The two halves are separate because they answer different questions.\n * *Attributes* must be idempotently re-established whenever the link set\n * changes, even though the reader has not moved — otherwise a link that\n * appears (or is re-anchored) while its section is already current never gets\n * marked. *The `change` event* announces that the reader moved, so it fires\n * only from the evaluation path; re-publishing over a new link set is not\n * news, and dispatching there would make a rebuild look like navigation.\n *\n * @param announce Whether this sync represents a change of current section.\n */\n #syncActiveStates(announce: boolean): void {\n // Every link anchoring the active section is marked, not just the first:\n // a page may render the same table of contents twice (a sidebar and a\n // collapsed mobile menu) and both must show the current location.\n const activeLinks = this.linkTargets.filter(\n (link) => this.#getAnchorId(link) === this.#activeSectionId,\n );\n\n for (const link of this.linkTargets) {\n if (activeLinks.includes(link)) {\n link.setAttribute(\"aria-current\", \"location\");\n } else if (link.getAttribute(\"aria-current\") === \"location\") {\n // Reclaim only the value this controller publishes, so an author-owned\n // `aria-current=\"page\"` on a table-of-contents link survives.\n link.removeAttribute(\"aria-current\");\n }\n }\n\n if (!announce) return;\n\n const primaryLink = activeLinks[0];\n if (primaryLink) {\n this.dispatch(\"change\", { detail: { id: this.#activeSectionId, link: primaryLink } });\n }\n }\n\n /**\n * The current location already encoded in the DOM, i.e. the section anchored\n * by the first link carrying this controller's `aria-current=\"location\"`.\n * Empty when no link claims it (a genuinely fresh render).\n */\n #activeIdFromDom(): string {\n for (const link of this.linkTargets) {\n if (link.getAttribute(\"aria-current\") !== \"location\") continue;\n const id = this.#getAnchorId(link);\n if (id) return id;\n }\n return \"\";\n }\n\n /**\n * The section id a link anchors, resolved in a fixed order:\n *\n * 1. `href`, when it is a non-empty same-document fragment — the contract.\n * 2. otherwise `data-href`'s fragment — the fallback for a link whose `href`\n * must stay a real URL (a server-rendered permalink) or that is not an\n * `<a>` at all.\n * 3. otherwise `null`: the link anchors nothing here and is not observed.\n *\n * Step 2 is reached whenever `href` yields nothing usable — absent, `\"#\"`, or\n * a real URL — which is the whole point of the fallback: `href=\"/guide/usage\"`\n * with `data-href=\"#usage\"` is a permalink that also spies, and picking the\n * first *present* attribute instead of the first *usable* one would silently\n * exclude exactly that markup. When both are valid fragments `href` wins.\n */\n #getAnchorId(link: HTMLElement): string | null {\n return (\n this.#fragmentId(link.getAttribute(\"href\")) ??\n this.#fragmentId(link.getAttribute(\"data-href\"))\n );\n }\n\n /** The id in a `#fragment` value; `null` for absent, empty, or non-fragment. */\n #fragmentId(value: string | null): string | null {\n if (!value?.startsWith(\"#\")) return null;\n return value.substring(1) || null;\n }\n}\n"]}
@@ -11,17 +11,22 @@ import { Controller } from '@hotwired/stimulus';
11
11
  * style="position: sticky; top: 0;">…</header>
12
12
  *
13
13
  * The scroll source is the window by default; inside an overflow container,
14
- * point `containerSelector` at it (the header usually sits inside it too).
14
+ * point `containerSelector` at it (the header usually sits inside it too). A
15
+ * declaration that cannot be parsed as a selector reads as the window, so a
16
+ * typo costs the container binding rather than the whole header.
15
17
  * <!-- [data-header-hidden="true"] { transform: translateY(-100%); } -->
16
18
  *
17
- * Scrolling down past `offset` px sets `data-header-hidden="true"`; any
18
- * scroll-up (beyond the `tolerance` jitter guard) or returning above `offset`
19
- * reveals it again. Focus reaching the header always reveals it, and while
20
- * focus stays inside the header a scroll-down never hides it — a keyboard
21
- * user must be able to see where focus went AND keep seeing the element that
22
- * owns it (WCAG 2.4.7 / 2.4.11).
19
+ * Scrolling down past `offset` px sets `data-header-hidden="true"`, and a
20
+ * scroll-up beyond the `tolerance` jitter guard reveals it again. Within the
21
+ * `offset` zone the header is always revealed, decided ahead of that jitter
22
+ * guard: a header stranded off-screen near the top cannot be scrolled back
23
+ * into view. Focus reaching the header always reveals it, and while focus
24
+ * stays inside the header a scroll-down never hides it — a keyboard user must
25
+ * be able to see where focus went AND keep seeing the element that owns it
26
+ * (WCAG 2.4.7 / 2.4.11).
23
27
  *
24
- * `change` dispatches `{ hidden }`.
28
+ * `change` dispatches `{ hidden }` on transitions only: the reflection
29
+ * `connect()` performs is the current state rather than a change.
25
30
  *
26
31
  * @remarks
27
32
  * Behavior only — `position: sticky`, the translate animation, and
@@ -51,6 +56,10 @@ declare class SmartStickyHeaderController extends Controller<HTMLElement> {
51
56
  containerSelectorValue: string;
52
57
  offsetValue: number;
53
58
  toleranceValue: number;
59
+ /** Validates `containerSelector` once so connect never parses a selector that throws. */
60
+ containerSelectorValueChanged(): void;
61
+ /** Re-decides when application code (or a Turbo morph) changes `offset` at runtime. */
62
+ offsetValueChanged(): void;
54
63
  connect(): void;
55
64
  disconnect(): void;
56
65
  }