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
@@ -2,29 +2,58 @@ import { Controller } from '@hotwired/stimulus';
2
2
 
3
3
  // src/controllers/count_up_controller.ts
4
4
 
5
+ // src/utils/authored_integer.ts
6
+ var TOKEN_BODY = /\d[\d.,'’’    _]*\d|\d/;
7
+ var SIGN_OPENER = /[\s([]/;
8
+ function authoredInteger(text) {
9
+ const firstDigit = /\d/.exec(text);
10
+ if (firstDigit === null) return null;
11
+ const at = firstDigit.index;
12
+ const signed = at > 0 && text[at - 1] === "-" && (at === 1 || SIGN_OPENER.test(text[at - 2]));
13
+ const body = TOKEN_BODY.exec(text.slice(at));
14
+ const runs = body[0].split(/\D+/);
15
+ const separators = body[0].match(/\D+/g) ?? [];
16
+ const lead = runs[0];
17
+ const heads = lead.length <= 3 && !lead.startsWith("0");
18
+ let digits = lead;
19
+ for (let i = 1; heads && i < runs.length; i += 1) {
20
+ if (separators[i - 1]?.length !== 1 || runs[i]?.length !== 3) break;
21
+ digits += runs[i];
22
+ }
23
+ const magnitude = Number.parseInt(digits, 10);
24
+ return signed ? -magnitude || 0 : magnitude;
25
+ }
26
+
5
27
  // src/utils/reduced_motion.ts
6
28
  function prefersReducedMotion() {
7
29
  return typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
8
30
  }
9
31
 
10
32
  // src/controllers/count_up_controller.ts
33
+ var DEFAULT_DURATION = 1200;
11
34
  var CountUpController = class extends Controller {
12
35
  static values = {
13
- duration: { type: Number, default: 1200 },
36
+ duration: { type: Number, default: DEFAULT_DURATION },
14
37
  from: { type: Number, default: 0 },
15
38
  once: { type: Boolean, default: true }
16
39
  };
17
40
  static actions = ["start"];
18
41
  static events = ["end"];
19
42
  #frame = null;
20
- /** The authored final text, restored verbatim when the run settles. */
21
- #finalText = "";
43
+ /** The animation length, with a declaration outside its domain read as the default. */
44
+ get #duration() {
45
+ return Number.isFinite(this.durationValue) && this.durationValue > 0 ? this.durationValue : DEFAULT_DURATION;
46
+ }
47
+ /** The starting value, with a declaration that is not a finite number read as zero. */
48
+ get #from() {
49
+ return Number.isFinite(this.fromValue) ? this.fromValue : 0;
50
+ }
22
51
  connect() {
23
- if (this.element.hasAttribute("data-count-up-label")) {
24
- this.element.textContent = this.element.getAttribute("aria-label") ?? this.element.textContent;
25
- this.#restoreLabel();
26
- this.element.setAttribute("data-count-up-done", "true");
27
- }
52
+ const ticker = this.#ownedTicker();
53
+ if (ticker === null) return;
54
+ const authored = ticker.getAttribute("aria-label");
55
+ this.#unwrap(ticker, authored);
56
+ if (authored !== null) this.element.setAttribute("data-count-up-done", "true");
28
57
  }
29
58
  disconnect() {
30
59
  if (this.#frame !== null) this.#settle();
@@ -36,27 +65,22 @@ var CountUpController = class extends Controller {
36
65
  start() {
37
66
  if (this.#frame !== null) return;
38
67
  if (this.onceValue && this.element.hasAttribute("data-count-up-done")) return;
39
- this.#finalText = this.element.textContent ?? "";
40
- const target = Number.parseInt(this.#finalText.replace(/[^0-9-]/g, ""), 10);
41
- if (Number.isNaN(target)) return;
68
+ const node = this.#numericNode();
69
+ if (node === null) return;
70
+ const authored = node.data;
71
+ const target = authoredInteger(authored);
42
72
  if (prefersReducedMotion()) {
43
73
  this.element.setAttribute("data-count-up-done", "true");
44
74
  this.dispatch("end", { detail: { value: target } });
45
75
  return;
46
76
  }
47
- const authored = this.element.getAttribute("aria-label");
48
- if (authored !== null) {
49
- this.element.setAttribute("data-count-up-original-label", authored);
50
- }
51
- this.element.setAttribute("data-count-up-label", "true");
52
- this.element.setAttribute("aria-label", this.#finalText);
77
+ const ticker = this.#wrap(node, authored);
78
+ const from = this.#from;
53
79
  const started = performance.now();
54
80
  const step = (now) => {
55
- const t = Math.min((now - started) / this.durationValue, 1);
81
+ const t = Math.min((now - started) / this.#duration, 1);
56
82
  const eased = 1 - (1 - t) ** 3;
57
- this.element.textContent = String(
58
- Math.round(this.fromValue + (target - this.fromValue) * eased)
59
- );
83
+ ticker.textContent = String(Math.round(from + (target - from) * eased));
60
84
  if (t < 1) {
61
85
  this.#frame = requestAnimationFrame(step);
62
86
  } else {
@@ -66,26 +90,41 @@ var CountUpController = class extends Controller {
66
90
  };
67
91
  this.#frame = requestAnimationFrame(step);
68
92
  }
93
+ /** The first text node that displays a number, or null when the host has none. */
94
+ #numericNode() {
95
+ const walker = document.createTreeWalker(this.element, NodeFilter.SHOW_TEXT);
96
+ let node = walker.nextNode();
97
+ while (node !== null && authoredInteger(node.data) === null) {
98
+ node = walker.nextNode();
99
+ }
100
+ return node;
101
+ }
102
+ /** The wrapper this controller published, if one outlived its run. */
103
+ #ownedTicker() {
104
+ return this.element.querySelector("[data-count-up-label]");
105
+ }
106
+ /** Publishes the ticking number inside a named wrapper, replacing `node`. */
107
+ #wrap(node, authored) {
108
+ const ticker = document.createElement("span");
109
+ ticker.setAttribute("data-count-up-label", "true");
110
+ ticker.setAttribute("role", "img");
111
+ ticker.setAttribute("aria-label", authored);
112
+ node.replaceWith(ticker);
113
+ ticker.append(node);
114
+ return ticker;
115
+ }
116
+ /** Puts `text` back where the wrapper stood, leaving the rest of the host alone. */
117
+ #unwrap(ticker, text) {
118
+ ticker.replaceWith(document.createTextNode(text ?? ticker.textContent ?? ""));
119
+ }
69
120
  /** Ends the run: cancels the frame and restores the authored presentation. */
70
121
  #settle() {
71
122
  if (this.#frame !== null) cancelAnimationFrame(this.#frame);
72
123
  this.#frame = null;
73
- this.element.textContent = this.#finalText;
74
- this.#restoreLabel();
124
+ const ticker = this.#ownedTicker();
125
+ if (ticker !== null) this.#unwrap(ticker, ticker.getAttribute("aria-label"));
75
126
  this.element.setAttribute("data-count-up-done", "true");
76
127
  }
77
- /** Releases the marker-owned aria-label, restoring any parked authored value. */
78
- #restoreLabel() {
79
- if (!this.element.hasAttribute("data-count-up-label")) return;
80
- const original = this.element.getAttribute("data-count-up-original-label");
81
- if (original !== null) {
82
- this.element.setAttribute("aria-label", original);
83
- this.element.removeAttribute("data-count-up-original-label");
84
- } else {
85
- this.element.removeAttribute("aria-label");
86
- }
87
- this.element.removeAttribute("data-count-up-label");
88
- }
89
128
  };
90
129
 
91
130
  export { CountUpController };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/reduced_motion.ts","../../src/controllers/count_up_controller.ts"],"names":[],"mappings":";;;;;AAkBO,SAAS,oBAAA,GAAgC;AAC9C,EAAA,OACE,OAAO,MAAA,CAAO,UAAA,KAAe,cAC7B,MAAA,CAAO,UAAA,CAAW,kCAAkC,CAAA,CAAE,OAAA;AAE1D;;;ACaO,IAAM,iBAAA,GAAN,cAAgC,UAAA,CAAwB;AAAA,EAC7D,OAAgB,MAAA,GAAS;AAAA,IACvB,QAAA,EAAU,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,IAAA,EAAK;AAAA,IACxC,IAAA,EAAM,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,CAAA,EAAE;AAAA,IACjC,IAAA,EAAM,EAAE,IAAA,EAAM,OAAA,EAAS,SAAS,IAAA;AAAK,GACvC;AAAA,EACA,OAAO,OAAA,GAAU,CAAC,OAAO,CAAA;AAAA,EACzB,OAAO,MAAA,GAAS,CAAC,KAAK,CAAA;AAAA,EAMtB,MAAA,GAAwB,IAAA;AAAA;AAAA,EAExB,UAAA,GAAa,EAAA;AAAA,EAEJ,OAAA,GAAgB;AAKvB,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,qBAAqB,CAAA,EAAG;AACpD,MAAA,IAAA,CAAK,OAAA,CAAQ,cACX,IAAA,CAAK,OAAA,CAAQ,aAAa,YAAY,CAAA,IAAK,KAAK,OAAA,CAAQ,WAAA;AAC1D,MAAA,IAAA,CAAK,aAAA,EAAc;AACnB,MAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,oBAAA,EAAsB,MAAM,CAAA;AAAA,IACxD;AAAA,EACF;AAAA,EAES,UAAA,GAAmB;AAG1B,IAAA,IAAI,IAAA,CAAK,MAAA,KAAW,IAAA,EAAM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AAA,CAAQ,YAAA,CAAa,YAAA,EAAc,QAAQ,CAAA;AAChD,MAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,8BAA8B,CAAA;AAAA,IAC7D,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,YAAY,CAAA;AAAA,IAC3C;AACA,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,qBAAqB,CAAA;AAAA,EACpD;AACF","file":"count_up_controller.js","sourcesContent":["/**\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 { prefersReducedMotion } from \"../utils/reduced_motion\";\n\n/**\n * Headless **count-up**: animates a number from `from` up to the value already\n * in the DOM — typically started the moment the element scrolls into view by\n * composing with the `stimeo--intersection` primitive (the classic \"animate\n * when visible\"). Distinct from `stimeo--countdown` (time-based). Core\n * (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--count-up`):\n * <span data-controller=\"stimeo--intersection stimeo--count-up\"\n * data-stimeo--intersection-once-value=\"true\"\n * data-action=\"stimeo--intersection:enter->stimeo--count-up#start\">1200</span>\n *\n * The **final number stays authored in the markup** (SEO / no-JS / SR read the\n * real value); `start` animates the displayed text from `from` to it over\n * `duration` ms with an ease-out curve, then restores the exact authored text.\n * With `once` (default) later starts are ignored (`data-count-up-done` records\n * a finished run across Turbo cache restores).\n *\n * `end` dispatches `{ value }`.\n *\n * @remarks\n * Behavior only — no formatting is imposed: the authored text is parsed for\n * its integer value (separators are ignored) and restored verbatim at the end;\n * intermediate frames render plain integers. Accessibility: when the user\n * prefers reduced motion the animation is skipped entirely (the value just\n * stays final — WCAG 2.3.3). The element is not a live region, so the ticking\n * intermediate numbers are never actively announced; during the run the\n * authored value is additionally kept in `aria-label` (best-effort — generic\n * roles may ignore it) and that lingering label doubles as the\n * interrupted-run marker `connect()` restores from after a Turbo cache\n * snapshot taken mid-animation. The animation frame is canceled on\n * `disconnect()` (Turbo navigation included) and the authored text restored.\n */\nexport class CountUpController extends Controller<HTMLElement> {\n static override values = {\n duration: { type: Number, default: 1200 },\n from: { type: Number, default: 0 },\n once: { type: Boolean, default: true },\n };\n static actions = [\"start\"] as const;\n static events = [\"end\"] as const;\n\n declare durationValue: number;\n declare fromValue: number;\n declare onceValue: boolean;\n\n #frame: number | null = null;\n /** The authored final text, restored verbatim when the run settles. */\n #finalText = \"\";\n\n override connect(): void {\n // Turbo snapshots the page BEFORE the body swap, so a cached page can hold\n // a mid-animation frame (disconnect()'s settle runs too late for it). The\n // OWN-label marker (never a bare aria-label — that may be authored) flags\n // the interrupted run: the label it owns still holds the authored text.\n if (this.element.hasAttribute(\"data-count-up-label\")) {\n this.element.textContent =\n this.element.getAttribute(\"aria-label\") ?? this.element.textContent;\n this.#restoreLabel();\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n }\n }\n\n override disconnect(): void {\n // A run cannot survive the element: settle instantly so the cached\n // snapshot holds the real value, never a mid-animation frame.\n if (this.#frame !== null) this.#settle();\n }\n\n /**\n * Starts the animation (typically from `stimeo--intersection:enter` via\n * `data-action`). No-ops while running, and after a finished run when `once`.\n */\n start(): void {\n if (this.#frame !== null) return;\n if (this.onceValue && this.element.hasAttribute(\"data-count-up-done\")) return;\n\n this.#finalText = this.element.textContent ?? \"\";\n const target = Number.parseInt(this.#finalText.replace(/[^0-9-]/g, \"\"), 10);\n if (Number.isNaN(target)) return;\n\n // Reduced motion: no ticking, just the final value (WCAG 2.3.3).\n if (prefersReducedMotion()) {\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n this.dispatch(\"end\", { detail: { value: target } });\n return;\n }\n\n // AT keeps the real value while the visible text ticks. An authored\n // aria-label is parked (save-restore, never clobbered) and the override is\n // marker-owned so connect()/settle() only ever touch what this set.\n const authored = this.element.getAttribute(\"aria-label\");\n if (authored !== null) {\n this.element.setAttribute(\"data-count-up-original-label\", authored);\n }\n this.element.setAttribute(\"data-count-up-label\", \"true\");\n this.element.setAttribute(\"aria-label\", this.#finalText);\n const started = performance.now();\n const step = (now: number): void => {\n const t = Math.min((now - started) / this.durationValue, 1);\n const eased = 1 - (1 - t) ** 3; // ease-out cubic\n this.element.textContent = String(\n Math.round(this.fromValue + (target - this.fromValue) * eased),\n );\n if (t < 1) {\n this.#frame = requestAnimationFrame(step);\n } else {\n this.#settle();\n this.dispatch(\"end\", { detail: { value: target } });\n }\n };\n this.#frame = requestAnimationFrame(step);\n }\n\n /** Ends the run: cancels the frame and restores the authored presentation. */\n #settle(): void {\n if (this.#frame !== null) cancelAnimationFrame(this.#frame);\n this.#frame = null;\n this.element.textContent = this.#finalText;\n this.#restoreLabel();\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n }\n\n /** Releases the marker-owned aria-label, restoring any parked authored value. */\n #restoreLabel(): void {\n if (!this.element.hasAttribute(\"data-count-up-label\")) return;\n const original = this.element.getAttribute(\"data-count-up-original-label\");\n if (original !== null) {\n this.element.setAttribute(\"aria-label\", original);\n this.element.removeAttribute(\"data-count-up-original-label\");\n } else {\n this.element.removeAttribute(\"aria-label\");\n }\n this.element.removeAttribute(\"data-count-up-label\");\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/authored_integer.ts","../../src/utils/reduced_motion.ts","../../src/controllers/count_up_controller.ts"],"names":[],"mappings":";;;;;AACA,IAAM,UAAA,GAAa,wBAAA;AAEnB,IAAM,WAAA,GAAc,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A,CAAO,OAAO,IAAI,CAAA;AAClB,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA,EAGA,OAAA,CAAQ,QAAqB,IAAA,EAA2B;AACtD,IAAA,MAAA,CAAO,YAAY,QAAA,CAAS,cAAA,CAAe,QAAQ,MAAA,CAAO,WAAA,IAAe,EAAE,CAAC,CAAA;AAAA,EAC9E;AAAA;AAAA,EAGA,OAAA,GAAgB;AACd,IAAA,IAAI,IAAA,CAAK,MAAA,KAAW,IAAA,EAAM,oBAAA,CAAqB,KAAK,MAAM,CAAA;AAC1D,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,MAAM,MAAA,GAAS,KAAK,YAAA,EAAa;AACjC,IAAA,IAAI,MAAA,KAAW,MAAM,IAAA,CAAK,OAAA,CAAQ,QAAQ,MAAA,CAAO,YAAA,CAAa,YAAY,CAAC,CAAA;AAC3E,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,oBAAA,EAAsB,MAAM,CAAA;AAAA,EACxD;AACF","file":"count_up_controller.js","sourcesContent":["/** Digits plus the characters that may separate them inside one number. */\nconst TOKEN_BODY = /\\d[\\d.,'’’    _]*\\d|\\d/;\n/** A `-` opens a token only against one of these on its left. */\nconst SIGN_OPENER = /[\\s([]/;\n\n/**\n * Reads the integer that a human-formatted string displays.\n *\n * Takes the first numeric token, drops group separators, and truncates any\n * fractional part toward zero — so `\"1,200 users\"`, `\"$1,299.99\"` and\n * `\"1.299,99\"` read 1200, 1299 and 1299 without asking the platform which\n * locale is in play. A separator counts as grouping only where the digits that\n * follow it form a run of exactly three and the leading run could head a\n * grouped number; anything else is the decimal point, and the digits after it\n * are the fraction.\n *\n * `-` counts as a sign only where it opens the token — at the start of the\n * string, or after whitespace or an opening bracket — so a hyphen inside a\n * label (`\"Sign-ups: 1,200\"`, `\"Top-10 users\"`) never becomes one.\n *\n * `\"1.200\"` is genuinely ambiguous (1200 grouped, 1.2 with a decimal point) and\n * reads as 1200: display numbers group far more often than they carry a\n * fraction in exactly three digits.\n *\n * Returns `null` when the string holds no digits at all. What that means is the\n * caller's to decide — starting nothing, or falling back to a base value.\n */\nexport function authoredInteger(text: string): number | null {\n const firstDigit = /\\d/.exec(text);\n if (firstDigit === null) return null;\n\n const at = firstDigit.index;\n const signed =\n at > 0 && text[at - 1] === \"-\" && (at === 1 || SIGN_OPENER.test(text[at - 2] as string));\n\n const body = TOKEN_BODY.exec(text.slice(at)) as RegExpExecArray;\n const runs = body[0].split(/\\D+/);\n const separators = body[0].match(/\\D+/g) ?? [];\n\n // The leading run heads a grouped number only when it is short enough to be a\n // group itself and carries no leading zero; \"0.500\" and \"012,3\" are decimals.\n const lead = runs[0] as string;\n const heads = lead.length <= 3 && !lead.startsWith(\"0\");\n let digits = lead;\n for (let i = 1; heads && i < runs.length; i += 1) {\n if (separators[i - 1]?.length !== 1 || runs[i]?.length !== 3) break;\n digits += runs[i];\n }\n\n const magnitude = Number.parseInt(digits, 10);\n return signed ? -magnitude || 0 : magnitude;\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 { authoredInteger } from \"../utils/authored_integer\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\n/** The animation length used when `duration` falls outside its domain. */\nconst DEFAULT_DURATION = 1200;\n\n/**\n * Headless **count-up**: animates a number from `from` up to the value already\n * in the DOM — typically started the moment the element scrolls into view by\n * composing with the `stimeo--intersection` primitive (the classic \"animate\n * when visible\"). Distinct from `stimeo--countdown` (time-based). Core\n * (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--count-up`):\n * <span data-controller=\"stimeo--intersection stimeo--count-up\"\n * data-stimeo--intersection-once-value=\"true\"\n * data-action=\"stimeo--intersection:enter->stimeo--count-up#start\">1200</span>\n *\n * The **final number stays authored in the markup** (SEO / no-JS / SR read the\n * real value); `start` animates the displayed text from `from` to it over\n * `duration` ms with an ease-out curve, then restores the exact authored text.\n * With `once` (default) later starts are ignored (`data-count-up-done` records\n * a finished run across Turbo cache restores).\n *\n * Only the text node holding the number is animated, so sibling markup — a unit\n * in a `<small>`, a label in a `<b>` — is left where the author put it.\n *\n * `end` dispatches `{ value }`.\n *\n * @remarks\n * Behavior only — no formatting is imposed: the authored text is read for the\n * integer it displays and restored verbatim at the end; intermediate frames\n * render plain integers. Accessibility: when the user prefers reduced motion the\n * animation is skipped entirely (the value just stays final — WCAG 2.3.3).\n * During a run the ticking number is wrapped in a `role=\"img\"` element named\n * with the authored text, which is where a name is allowed to live — the host\n * keeps whatever semantics it had, so a `<dd>` stays a definition. That wrapper\n * doubles as the interrupted-run record `connect()` restores from after a Turbo\n * cache snapshot taken mid-animation. The animation frame is canceled on\n * `disconnect()` (Turbo navigation included) and the authored text restored.\n */\nexport class CountUpController extends Controller<HTMLElement> {\n static override values = {\n duration: { type: Number, default: DEFAULT_DURATION },\n from: { type: Number, default: 0 },\n once: { type: Boolean, default: true },\n };\n static actions = [\"start\"] as const;\n static events = [\"end\"] as const;\n\n declare durationValue: number;\n declare fromValue: number;\n declare onceValue: boolean;\n\n #frame: number | null = null;\n\n /** The animation length, with a declaration outside its domain read as the default. */\n get #duration(): number {\n return Number.isFinite(this.durationValue) && this.durationValue > 0\n ? this.durationValue\n : DEFAULT_DURATION;\n }\n\n /** The starting value, with a declaration that is not a finite number read as zero. */\n get #from(): number {\n return Number.isFinite(this.fromValue) ? this.fromValue : 0;\n }\n\n override connect(): void {\n // Turbo snapshots the page BEFORE the body swap, so a cached page can hold\n // a mid-animation frame (disconnect()'s settle runs too late for it). The\n // wrapper this controller owns flags the interrupted run and carries the\n // authored text in the name it published.\n const ticker = this.#ownedTicker();\n if (ticker === null) return;\n const authored = ticker.getAttribute(\"aria-label\");\n this.#unwrap(ticker, authored);\n if (authored !== null) this.element.setAttribute(\"data-count-up-done\", \"true\");\n }\n\n override disconnect(): void {\n // A run cannot survive the element: settle instantly so the cached\n // snapshot holds the real value, never a mid-animation frame.\n if (this.#frame !== null) this.#settle();\n }\n\n /**\n * Starts the animation (typically from `stimeo--intersection:enter` via\n * `data-action`). No-ops while running, and after a finished run when `once`.\n */\n start(): void {\n if (this.#frame !== null) return;\n if (this.onceValue && this.element.hasAttribute(\"data-count-up-done\")) return;\n\n const node = this.#numericNode();\n if (node === null) return;\n const authored = node.data;\n const target = authoredInteger(authored) as number;\n\n // Reduced motion: no ticking, just the final value (WCAG 2.3.3).\n if (prefersReducedMotion()) {\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n this.dispatch(\"end\", { detail: { value: target } });\n return;\n }\n\n // A name may not live on every host — a `<span>` prohibits one, and a role\n // that permits naming would cost a `<dd>` its own semantics — so the ticking\n // number gets a wrapper that permits naming, and the name carries the\n // authored text AT should hear instead of the ticks.\n const ticker = this.#wrap(node, authored);\n const from = this.#from;\n const started = performance.now();\n const step = (now: number): void => {\n const t = Math.min((now - started) / this.#duration, 1);\n const eased = 1 - (1 - t) ** 3; // ease-out cubic\n ticker.textContent = String(Math.round(from + (target - from) * eased));\n if (t < 1) {\n this.#frame = requestAnimationFrame(step);\n } else {\n this.#settle();\n this.dispatch(\"end\", { detail: { value: target } });\n }\n };\n this.#frame = requestAnimationFrame(step);\n }\n\n /** The first text node that displays a number, or null when the host has none. */\n #numericNode(): Text | null {\n const walker = document.createTreeWalker(this.element, NodeFilter.SHOW_TEXT);\n let node = walker.nextNode() as Text | null;\n while (node !== null && authoredInteger(node.data) === null) {\n node = walker.nextNode() as Text | null;\n }\n return node;\n }\n\n /** The wrapper this controller published, if one outlived its run. */\n #ownedTicker(): HTMLElement | null {\n return this.element.querySelector<HTMLElement>(\"[data-count-up-label]\");\n }\n\n /** Publishes the ticking number inside a named wrapper, replacing `node`. */\n #wrap(node: Text, authored: string): HTMLElement {\n const ticker = document.createElement(\"span\");\n ticker.setAttribute(\"data-count-up-label\", \"true\");\n ticker.setAttribute(\"role\", \"img\");\n ticker.setAttribute(\"aria-label\", authored);\n node.replaceWith(ticker);\n ticker.append(node);\n return ticker;\n }\n\n /** Puts `text` back where the wrapper stood, leaving the rest of the host alone. */\n #unwrap(ticker: HTMLElement, text: string | null): void {\n ticker.replaceWith(document.createTextNode(text ?? ticker.textContent ?? \"\"));\n }\n\n /** Ends the run: cancels the frame and restores the authored presentation. */\n #settle(): void {\n if (this.#frame !== null) cancelAnimationFrame(this.#frame);\n this.#frame = null;\n const ticker = this.#ownedTicker();\n if (ticker !== null) this.#unwrap(ticker, ticker.getAttribute(\"aria-label\"));\n this.element.setAttribute(\"data-count-up-done\", \"true\");\n }\n}\n"]}
@@ -15,9 +15,10 @@ import { Controller } from '@hotwired/stimulus';
15
15
  * data-action="stimeo--intersection:enter->feed#loadNextPage"></div>
16
16
  *
17
17
  * The controller observes its own element. `enter` fires when the element
18
- * becomes visible (intersection ratio reaches `threshold`), `exit` when it
19
- * leaves (detail carries `position`: `"before"` = scrolled past the root's
20
- * start edge, `"after"` = still ahead), `change` on every observed update
18
+ * becomes visible (intersection ratio reaches `threshold`; detail `{ ratio }`),
19
+ * `exit` when it leaves (detail `{ ratio, position }`, where `position` is the
20
+ * edge it left across — `"before"` = upward past the root's start edge,
21
+ * `"after"` = downward, still ahead), `change` on every observed update
21
22
  * (detail `{ intersecting, ratio }` — set `ratioSteps` for fine-grained ratio
22
23
  * reporting), and `passed` when the element fully crosses the root's start edge
23
24
  * in either direction (detail `{ passed }` — the sticky/progress line). The
@@ -30,10 +31,12 @@ import { Controller } from '@hotwired/stimulus';
30
31
  * idempotent: the previous state is read back from `data-intersecting`/
31
32
  * `data-passed`, so a Turbo cache restore does not re-fire `enter` for an
32
33
  * element that was already visible (and with `once`, an element whose enter
33
- * already fired is not observed again). Without `IntersectionObserver` (very
34
- * old browsers) the controller stays inert — consumers keep whatever no-JS
35
- * fallback their markup provides. The observer is disconnected on
36
- * `disconnect()` (Turbo navigation included).
34
+ * already fired is not observed again). `threshold` is re-read when Turbo morphs
35
+ * the attribute in place, and a `rootSelector` that does not parse observes the
36
+ * viewport rather than leaving the element unobserved. Without
37
+ * `IntersectionObserver` (very old browsers) the controller stays inert —
38
+ * consumers keep whatever no-JS fallback their markup provides. The observer is
39
+ * disconnected on `disconnect()` (Turbo navigation included).
37
40
  */
38
41
  declare class IntersectionController extends Controller<HTMLElement> {
39
42
  #private;
@@ -68,6 +71,16 @@ declare class IntersectionController extends Controller<HTMLElement> {
68
71
  onceValue: boolean;
69
72
  connect(): void;
70
73
  disconnect(): void;
74
+ /**
75
+ * Re-reads the visibility line and rebuilds the observer. Turbo 8 morphing
76
+ * rewrites the attribute in place without a reconnect, and the line is what
77
+ * the intersection callback compares every ratio against, so a value frozen at
78
+ * connect time would decide `data-intersecting` wrongly for the rest of the
79
+ * page's life. Nothing to rebuild before the first `connect()`; after a spent
80
+ * one-shot the watcher is deliberately stopped, and re-observing would deliver
81
+ * the current state and fire `enter` a second time.
82
+ */
83
+ thresholdValueChanged(): void;
71
84
  /**
72
85
  * Re-delivers the current intersection state as a fresh transition. Bound via
73
86
  * `data-action` (e.g. `my-feed:appended@window->stimeo--intersection#refresh`).
@@ -9,6 +9,14 @@ function isBeforeRootStart(entry) {
9
9
  const rootTop = entry.rootBounds?.top ?? 0;
10
10
  return rect.bottom <= rootTop;
11
11
  }
12
+ function queryRoot(selector) {
13
+ if (!selector) return null;
14
+ try {
15
+ return document.querySelector(selector);
16
+ } catch {
17
+ }
18
+ return null;
19
+ }
12
20
  var IntersectionWatcher = class {
13
21
  #onEntries;
14
22
  #observer = null;
@@ -30,7 +38,10 @@ var IntersectionWatcher = class {
30
38
  * the watcher inert — without `IntersectionObserver` support (very old
31
39
  * browsers; the caller's no-JS fallback stays in charge) or with no targets.
32
40
  * If initial construction with the configured options fails, the watcher
33
- * warns and retries once with the same root and platform defaults.
41
+ * warns and retries once with the same root and platform defaults. A
42
+ * `rootSelector` that does not parse resolves to the viewport (see
43
+ * {@link IntersectionWatchOptions.rootSelector}), so a typo never fails the
44
+ * call.
34
45
  *
35
46
  * @throws The fallback constructor error if both construction attempts fail,
36
47
  * or whatever the platform throws from `observe()`. The exception is passed
@@ -43,7 +54,7 @@ var IntersectionWatcher = class {
43
54
  if (typeof IntersectionObserver === "undefined") return false;
44
55
  const list = Array.isArray(targets) ? targets : [targets];
45
56
  if (list.length === 0) return false;
46
- const root = "root" in options ? options.root ?? null : options.rootSelector ? document.querySelector(options.rootSelector) : null;
57
+ const root = "root" in options ? options.root ?? null : queryRoot(options.rootSelector);
47
58
  let observer = null;
48
59
  try {
49
60
  const onEntries = (entries) => {
@@ -136,6 +147,25 @@ var IntersectionController = class extends Controller {
136
147
  }
137
148
  connect() {
138
149
  if (this.onceValue && this.element.getAttribute("data-intersecting") === "true") return;
150
+ this.#observe();
151
+ }
152
+ disconnect() {
153
+ this.#watcher.stop();
154
+ }
155
+ /**
156
+ * Re-reads the visibility line and rebuilds the observer. Turbo 8 morphing
157
+ * rewrites the attribute in place without a reconnect, and the line is what
158
+ * the intersection callback compares every ratio against, so a value frozen at
159
+ * connect time would decide `data-intersecting` wrongly for the rest of the
160
+ * page's life. Nothing to rebuild before the first `connect()`; after a spent
161
+ * one-shot the watcher is deliberately stopped, and re-observing would deliver
162
+ * the current state and fire `enter` a second time.
163
+ */
164
+ thresholdValueChanged() {
165
+ if (this.#watcher.active) this.#observe();
166
+ }
167
+ /** (Re)installs the observer from the current Values. */
168
+ #observe() {
139
169
  this.#effectiveThreshold = this.#clampedThreshold();
140
170
  this.#watcher.start(this.element, {
141
171
  rootSelector: this.rootSelectorValue,
@@ -144,9 +174,6 @@ var IntersectionController = class extends Controller {
144
174
  });
145
175
  if (this.#watcher.usingPlatformDefaults) this.#effectiveThreshold = 0;
146
176
  }
147
- disconnect() {
148
- this.#watcher.stop();
149
- }
150
177
  /**
151
178
  * Re-delivers the current intersection state as a fresh transition. Bound via
152
179
  * `data-action` (e.g. `my-feed:appended@window->stimeo--intersection#refresh`).
@@ -177,14 +204,29 @@ var IntersectionController = class extends Controller {
177
204
  const previous = this.element.getAttribute("data-intersecting");
178
205
  this.element.setAttribute("data-intersecting", intersecting ? "true" : "false");
179
206
  if (intersecting && previous !== "true") {
180
- this.dispatch("enter", { detail: { ratio } });
181
207
  if (this.onceValue) this.#watcher.stop();
208
+ this.dispatch("enter", { detail: { ratio } });
182
209
  } else if (!intersecting && previous === "true") {
183
210
  this.dispatch("exit", {
184
- detail: { ratio, position: isBeforeRootStart(entry) ? "before" : "after" }
211
+ detail: { ratio, position: this.#leftViaStartEdge(entry) ? "before" : "after" }
185
212
  });
186
213
  }
187
214
  }
215
+ /**
216
+ * Which edge the element left across, for the `exit` detail. A non-zero
217
+ * `threshold` withdraws visibility while the element still overlaps the root,
218
+ * so the leaving rect can straddle the start edge — the direction is the
219
+ * element's own top against that edge, not whether it has cleared the root
220
+ * entirely (that is what `passed` reports). An element with no layout box
221
+ * (`display: none`, a collapsed `<details>`) is reported with an empty rect
222
+ * that carries no position at all, so it is deliberately neither direction
223
+ * and takes the "still ahead" reading.
224
+ */
225
+ #leftViaStartEdge(entry) {
226
+ const rect = entry.boundingClientRect;
227
+ if (rect.width === 0 && rect.height === 0) return false;
228
+ return rect.top < (entry.rootBounds?.top ?? 0);
229
+ }
188
230
  /**
189
231
  * Reflects the "scrolled past" state onto `data-passed` and fires `passed` on
190
232
  * transitions — the line sticky headers and reading progress key off. Like
@@ -204,9 +246,14 @@ var IntersectionController = class extends Controller {
204
246
  /**
205
247
  * Observer thresholds: the `threshold` line itself, plus `ratioSteps` evenly
206
248
  * spaced steps when fine-grained `change` ratios are wanted (progress bars).
249
+ *
250
+ * 0 is always observed. An observer notifies only at the lines it was given,
251
+ * so a non-zero `threshold` on its own delivers its last callback while the
252
+ * element is still partly visible: the element leaving for good would never be
253
+ * reported, freezing the ratio and `data-passed` mid-departure.
207
254
  */
208
255
  #thresholds() {
209
- const thresholds = /* @__PURE__ */ new Set([this.#clampedThreshold()]);
256
+ const thresholds = /* @__PURE__ */ new Set([0, this.#clampedThreshold()]);
210
257
  if (this.ratioStepsValue > 0) {
211
258
  for (let i = 0; i <= this.ratioStepsValue; i += 1) {
212
259
  thresholds.add(i / this.ratioStepsValue);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/controllers/intersection_controller.ts"],"names":[],"mappings":";;;;;AA8BO,SAAS,kBAAkB,KAAA,EAA2C;AAC3E,EAAA,MAAM,OAAO,KAAA,CAAM,kBAAA;AACnB,EAAA,IAAI,KAAK,KAAA,KAAU,CAAA,IAAK,IAAA,CAAK,MAAA,KAAW,GAAG,OAAO,KAAA;AAGlD,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,UAAA,EAAY,GAAA,IAAO,CAAA;AACzC,EAAA,OAAO,KAAK,MAAA,IAAU,OAAA;AACxB;AAcO,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;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AA;AAAA;AAAA;AAAA,EAMA,WAAA,GAAwB;AACtB,IAAA,MAAM,6BAAa,IAAI,GAAA,CAAY,CAAC,IAAA,CAAK,iBAAA,EAAmB,CAAC,CAAA;AAC7D,IAAA,IAAI,IAAA,CAAK,kBAAkB,CAAA,EAAG;AAE5B,MAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,IAAK,IAAA,CAAK,eAAA,EAAiB,KAAK,CAAA,EAAG;AACjD,QAAA,UAAA,CAAW,GAAA,CAAI,CAAA,GAAI,IAAA,CAAK,eAAe,CAAA;AAAA,MACzC;AAAA,IACF;AACA,IAAA,OAAO,CAAC,GAAG,UAAU,CAAA,CAAE,KAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,GAAI,CAAC,CAAA;AAAA,EAC7C;AACF","file":"intersection_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","import { Controller } from \"@hotwired/stimulus\";\nimport { IntersectionWatcher, isBeforeRootStart } from \"../utils/intersection_watcher\";\n\n/** Name of the CSS custom property exposing the visible ratio (0..1). */\nconst RATIO_PROPERTY = \"--stimeo--intersection-ratio\";\n\n/**\n * Tolerance for the visibility test. Real observers can report a ratio a hair\n * below the configured threshold at that threshold's own crossing callback\n * (fractional device pixels / zoom), most visibly at threshold 1 where \"fully\n * visible\" may arrive as 0.99x — a strict `>=` would then never see it.\n */\nconst RATIO_EPSILON = 0.01;\n\n/**\n * Headless **intersection primitive**: a thin declarative wrapper over\n * {@link IntersectionObserver} that turns viewport visibility into events and\n * state hooks. It is the scroll-triggered building block for\n * scroll-driven behavior — loading more on approach, \"animate when visible\"\n * (compose it with `stimeo--count-up`), progress and sticky-header work — so a\n * consumer does not write its own observer. No APG widget — a pure\n * state-detection utility. Core (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--intersection`):\n * <div data-controller=\"stimeo--intersection\"\n * data-stimeo--intersection-root-margin-value=\"200px\"\n * data-action=\"stimeo--intersection:enter->feed#loadNextPage\"></div>\n *\n * The controller observes its own element. `enter` fires when the element\n * becomes visible (intersection ratio reaches `threshold`), `exit` when it\n * leaves (detail carries `position`: `\"before\"` = scrolled past the root's\n * start edge, `\"after\"` = still ahead), `change` on every observed update\n * (detail `{ intersecting, ratio }` — set `ratioSteps` for fine-grained ratio\n * reporting), and `passed` when the element fully crosses the root's start edge\n * in either direction (detail `{ passed }` — the sticky/progress line). The\n * visibility is mirrored as `data-intersecting`/`data-passed` and the ratio as\n * the `--stimeo--intersection-ratio` custom property for consumer CSS.\n *\n * @remarks\n * Behavior only — what visibility *means* (load a page, start an animation,\n * pin a header) belongs to the consumer via `data-action`/CSS. `connect()` is\n * idempotent: the previous state is read back from `data-intersecting`/\n * `data-passed`, so a Turbo cache restore does not re-fire `enter` for an\n * element that was already visible (and with `once`, an element whose enter\n * already fired is not observed again). Without `IntersectionObserver` (very\n * old browsers) the controller stays inert — consumers keep whatever no-JS\n * fallback their markup provides. The observer is disconnected on\n * `disconnect()` (Turbo navigation included).\n */\nexport class IntersectionController extends Controller<HTMLElement> {\n static override values = {\n threshold: { type: Number, default: 0 },\n ratioSteps: { type: Number, default: 0 },\n rootMargin: { type: String, default: \"0px\" },\n rootSelector: { type: String, default: \"\" },\n once: { type: Boolean, default: false },\n };\n static actions = [\"refresh\"] as const;\n static events = [\"enter\", \"exit\", \"change\", \"passed\"] as const;\n\n declare thresholdValue: number;\n declare ratioStepsValue: number;\n declare rootMarginValue: string;\n declare rootSelectorValue: string;\n declare onceValue: boolean;\n\n /** Shared IO plumbing (support guard, root resolution, active guard, re-arm). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersect(entries));\n /** Threshold actually installed in the live observer (0 after option fallback). */\n #effectiveThreshold = 0;\n /** Bumped by `refresh()`: an in-flight batch becomes stale and stops. */\n #generation = 0;\n\n #onIntersect(entries: IntersectionObserverEntry[]): void {\n // A single callback can batch several transitions for the same target\n // (delivery lagging behind a fast scroll), so process every entry in\n // order — collapsing to the last one alone would drop an enter→exit pair\n // and, under `once`, lose the one-shot enter entirely. If a handler calls\n // `refresh()` mid-batch (enter → append content → re-arm), the remaining\n // entries describe a state `refresh` just reset — replaying them would\n // re-fire `enter` for the same visibility episode — so the generation\n // bump abandons them and the re-observation delivers the fresh state\n // (`once` stopping the watcher mid-batch is caught by the active check).\n const generation = this.#generation;\n for (const entry of entries) {\n if (!this.#watcher.active || this.#generation !== generation) return;\n\n const ratio = entry.intersectionRatio;\n // `isIntersecting` is geometric (\"any overlap\"), so a non-zero `threshold`\n // (\"counts as visible at ≥N%\") must be applied to the ratio ourselves —\n // against the same 0..1-clamped value the observer was configured with, or\n // a `threshold` above 1 would make `intersecting` unreachable while the\n // observer still fires at ratio 1. The epsilon absorbs subpixel rounding\n // (see RATIO_EPSILON); keeping the geometric `isIntersecting` conjunct\n // stops it from underflowing a tiny threshold into \"always visible\".\n // A constructor fallback omits the configured threshold, so the observer\n // can only notify at its effective default line (0). Applying the authored\n // line here would wait for a callback that the fallback observer never\n // schedules after an initially intersecting entry.\n const threshold = this.#effectiveThreshold;\n const intersecting =\n threshold > 0\n ? entry.isIntersecting && ratio >= threshold - RATIO_EPSILON\n : entry.isIntersecting;\n\n this.element.style.setProperty(RATIO_PROPERTY, String(ratio));\n this.dispatch(\"change\", { detail: { intersecting, ratio } });\n this.#syncIntersecting(intersecting, ratio, entry);\n this.#syncPassed(!intersecting && isBeforeRootStart(entry));\n }\n }\n\n override connect(): void {\n // A cache restore may bring back an element whose one-shot enter already\n // fired; honor it instead of re-observing (mirrors `data-lazy-loaded`).\n if (this.onceValue && this.element.getAttribute(\"data-intersecting\") === \"true\") return;\n this.#effectiveThreshold = this.#clampedThreshold();\n this.#watcher.start(this.element, {\n rootSelector: this.rootSelectorValue,\n rootMargin: this.rootMarginValue,\n threshold: this.#thresholds(),\n });\n if (this.#watcher.usingPlatformDefaults) this.#effectiveThreshold = 0;\n }\n\n override disconnect(): void {\n this.#watcher.stop();\n }\n\n /**\n * Re-delivers the current intersection state as a fresh transition. Bound via\n * `data-action` (e.g. `my-feed:appended@window->stimeo--intersection#refresh`).\n *\n * `IntersectionObserver` only reports state *changes*, so a sentinel that\n * stays visible while content is appended below it never fires `enter` again\n * and a hand-rolled infinite scroll stalls. `observe()` always delivers the\n * current state, and clearing the recorded `data-intersecting`/`data-passed`\n * makes that delivery count as a transition — a still-visible sentinel\n * re-fires `enter`. No-op once the observer is gone (`once` fired, no\n * `IntersectionObserver` support, or after `disconnect()`).\n */\n refresh(): void {\n if (!this.#watcher.active) return;\n this.#generation += 1;\n this.element.removeAttribute(\"data-intersecting\");\n this.element.removeAttribute(\"data-passed\");\n this.#watcher.rearm(this.element);\n }\n\n /**\n * Reflects the visibility onto `data-intersecting` and fires `enter`/`exit`\n * on transitions. The previous state is the DOM attribute (source of truth),\n * so the observer's initial callback fires `enter` for an element that starts\n * visible but stays silent after a cache restore that already recorded it.\n * An initial not-visible state is established silently (no `exit`).\n */\n #syncIntersecting(intersecting: boolean, ratio: number, entry: IntersectionObserverEntry): void {\n const previous = this.element.getAttribute(\"data-intersecting\");\n this.element.setAttribute(\"data-intersecting\", intersecting ? \"true\" : \"false\");\n\n if (intersecting && previous !== \"true\") {\n this.dispatch(\"enter\", { detail: { ratio } });\n // One-shot mode: the enter fired; stop observing and leave the hooks in\n // their final state (`data-intersecting=\"true\"` marks it for reconnects).\n if (this.onceValue) this.#watcher.stop();\n } else if (!intersecting && previous === \"true\") {\n this.dispatch(\"exit\", {\n detail: { ratio, position: isBeforeRootStart(entry) ? \"before\" : \"after\" },\n });\n }\n }\n\n /**\n * Reflects the \"scrolled past\" state onto `data-passed` and fires `passed` on\n * transitions — the line sticky headers and reading progress key off. Like\n * `enter`, an initial `passed=true` (page restored mid-scroll) fires; the\n * initial `false` is established silently.\n */\n #syncPassed(passed: boolean): void {\n const previous = this.element.getAttribute(\"data-passed\");\n this.element.setAttribute(\"data-passed\", passed ? \"true\" : \"false\");\n const changed = previous === null ? passed : (previous === \"true\") !== passed;\n if (changed) this.dispatch(\"passed\", { detail: { passed } });\n }\n\n /** The configured `threshold`, clamped to the 0..1 the observer accepts. */\n #clampedThreshold(): number {\n return Math.min(1, Math.max(0, this.thresholdValue));\n }\n\n /**\n * Observer thresholds: the `threshold` line itself, plus `ratioSteps` evenly\n * spaced steps when fine-grained `change` ratios are wanted (progress bars).\n */\n #thresholds(): number[] {\n const thresholds = new Set<number>([this.#clampedThreshold()]);\n if (this.ratioStepsValue > 0) {\n // i counts up to ratioSteps, so i/ratioSteps is inherently 0..1.\n for (let i = 0; i <= this.ratioStepsValue; i += 1) {\n thresholds.add(i / this.ratioStepsValue);\n }\n }\n return [...thresholds].sort((a, b) => a - b);\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/controllers/intersection_controller.ts"],"names":[],"mappings":";;;;;AA+BO,SAAS,kBAAkB,KAAA,EAA2C;AAC3E,EAAA,MAAM,OAAO,KAAA,CAAM,kBAAA;AACnB,EAAA,IAAI,KAAK,KAAA,KAAU,CAAA,IAAK,IAAA,CAAK,MAAA,KAAW,GAAG,OAAO,KAAA;AAGlD,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,UAAA,EAAY,GAAA,IAAO,CAAA;AACzC,EAAA,OAAO,KAAK,MAAA,IAAU,OA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;AAAA;AAAA,EAWA,WAAA,GAAwB;AACtB,IAAA,MAAM,UAAA,uBAAiB,GAAA,CAAY,CAAC,GAAG,IAAA,CAAK,iBAAA,EAAmB,CAAC,CAAA;AAChE,IAAA,IAAI,IAAA,CAAK,kBAAkB,CAAA,EAAG;AAE5B,MAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,IAAK,IAAA,CAAK,eAAA,EAAiB,KAAK,CAAA,EAAG;AACjD,QAAA,UAAA,CAAW,GAAA,CAAI,CAAA,GAAI,IAAA,CAAK,eAAe,CAAA;AAAA,MACzC;AAAA,IACF;AACA,IAAA,OAAO,CAAC,GAAG,UAAU,CAAA,CAAE,KAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,GAAI,CAAC,CAAA;AAAA,EAC7C;AACF","file":"intersection_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","import { Controller } from \"@hotwired/stimulus\";\nimport { IntersectionWatcher, isBeforeRootStart } from \"../utils/intersection_watcher\";\n\n/** Name of the CSS custom property exposing the visible ratio (0..1). */\nconst RATIO_PROPERTY = \"--stimeo--intersection-ratio\";\n\n/**\n * Tolerance for the visibility test. Real observers can report a ratio a hair\n * below the configured threshold at that threshold's own crossing callback\n * (fractional device pixels / zoom), most visibly at threshold 1 where \"fully\n * visible\" may arrive as 0.99x — a strict `>=` would then never see it.\n */\nconst RATIO_EPSILON = 0.01;\n\n/**\n * Headless **intersection primitive**: a thin declarative wrapper over\n * {@link IntersectionObserver} that turns viewport visibility into events and\n * state hooks. It is the scroll-triggered building block for\n * scroll-driven behavior — loading more on approach, \"animate when visible\"\n * (compose it with `stimeo--count-up`), progress and sticky-header work — so a\n * consumer does not write its own observer. No APG widget — a pure\n * state-detection utility. Core (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--intersection`):\n * <div data-controller=\"stimeo--intersection\"\n * data-stimeo--intersection-root-margin-value=\"200px\"\n * data-action=\"stimeo--intersection:enter->feed#loadNextPage\"></div>\n *\n * The controller observes its own element. `enter` fires when the element\n * becomes visible (intersection ratio reaches `threshold`; detail `{ ratio }`),\n * `exit` when it leaves (detail `{ ratio, position }`, where `position` is the\n * edge it left across — `\"before\"` = upward past the root's start edge,\n * `\"after\"` = downward, still ahead), `change` on every observed update\n * (detail `{ intersecting, ratio }` — set `ratioSteps` for fine-grained ratio\n * reporting), and `passed` when the element fully crosses the root's start edge\n * in either direction (detail `{ passed }` — the sticky/progress line). The\n * visibility is mirrored as `data-intersecting`/`data-passed` and the ratio as\n * the `--stimeo--intersection-ratio` custom property for consumer CSS.\n *\n * @remarks\n * Behavior only — what visibility *means* (load a page, start an animation,\n * pin a header) belongs to the consumer via `data-action`/CSS. `connect()` is\n * idempotent: the previous state is read back from `data-intersecting`/\n * `data-passed`, so a Turbo cache restore does not re-fire `enter` for an\n * element that was already visible (and with `once`, an element whose enter\n * already fired is not observed again). `threshold` is re-read when Turbo morphs\n * the attribute in place, and a `rootSelector` that does not parse observes the\n * viewport rather than leaving the element unobserved. Without\n * `IntersectionObserver` (very old browsers) the controller stays inert —\n * consumers keep whatever no-JS fallback their markup provides. The observer is\n * disconnected on `disconnect()` (Turbo navigation included).\n */\nexport class IntersectionController extends Controller<HTMLElement> {\n static override values = {\n threshold: { type: Number, default: 0 },\n ratioSteps: { type: Number, default: 0 },\n rootMargin: { type: String, default: \"0px\" },\n rootSelector: { type: String, default: \"\" },\n once: { type: Boolean, default: false },\n };\n static actions = [\"refresh\"] as const;\n static events = [\"enter\", \"exit\", \"change\", \"passed\"] as const;\n\n declare thresholdValue: number;\n declare ratioStepsValue: number;\n declare rootMarginValue: string;\n declare rootSelectorValue: string;\n declare onceValue: boolean;\n\n /** Shared IO plumbing (support guard, root resolution, active guard, re-arm). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersect(entries));\n /** Threshold actually installed in the live observer (0 after option fallback). */\n #effectiveThreshold = 0;\n /** Bumped by `refresh()`: an in-flight batch becomes stale and stops. */\n #generation = 0;\n\n #onIntersect(entries: IntersectionObserverEntry[]): void {\n // A single callback can batch several transitions for the same target\n // (delivery lagging behind a fast scroll), so process every entry in\n // order — collapsing to the last one alone would drop an enter→exit pair\n // and, under `once`, lose the one-shot enter entirely. If a handler calls\n // `refresh()` mid-batch (enter → append content → re-arm), the remaining\n // entries describe a state `refresh` just reset — replaying them would\n // re-fire `enter` for the same visibility episode — so the generation\n // bump abandons them and the re-observation delivers the fresh state\n // (`once` stopping the watcher mid-batch is caught by the active check).\n const generation = this.#generation;\n for (const entry of entries) {\n if (!this.#watcher.active || this.#generation !== generation) return;\n\n const ratio = entry.intersectionRatio;\n // `isIntersecting` is geometric (\"any overlap\"), so a non-zero `threshold`\n // (\"counts as visible at ≥N%\") must be applied to the ratio ourselves —\n // against the same 0..1-clamped value the observer was configured with, or\n // a `threshold` above 1 would make `intersecting` unreachable while the\n // observer still fires at ratio 1. The epsilon absorbs subpixel rounding\n // (see RATIO_EPSILON); keeping the geometric `isIntersecting` conjunct\n // stops it from underflowing a tiny threshold into \"always visible\".\n // A constructor fallback omits the configured threshold, so the observer\n // can only notify at its effective default line (0). Applying the authored\n // line here would wait for a callback that the fallback observer never\n // schedules after an initially intersecting entry.\n const threshold = this.#effectiveThreshold;\n const intersecting =\n threshold > 0\n ? entry.isIntersecting && ratio >= threshold - RATIO_EPSILON\n : entry.isIntersecting;\n\n this.element.style.setProperty(RATIO_PROPERTY, String(ratio));\n this.dispatch(\"change\", { detail: { intersecting, ratio } });\n this.#syncIntersecting(intersecting, ratio, entry);\n this.#syncPassed(!intersecting && isBeforeRootStart(entry));\n }\n }\n\n override connect(): void {\n // A cache restore may bring back an element whose one-shot enter already\n // fired; honor it instead of re-observing (mirrors `data-lazy-loaded`).\n if (this.onceValue && this.element.getAttribute(\"data-intersecting\") === \"true\") return;\n this.#observe();\n }\n\n override disconnect(): void {\n this.#watcher.stop();\n }\n\n /**\n * Re-reads the visibility line and rebuilds the observer. Turbo 8 morphing\n * rewrites the attribute in place without a reconnect, and the line is what\n * the intersection callback compares every ratio against, so a value frozen at\n * connect time would decide `data-intersecting` wrongly for the rest of the\n * page's life. Nothing to rebuild before the first `connect()`; after a spent\n * one-shot the watcher is deliberately stopped, and re-observing would deliver\n * the current state and fire `enter` a second time.\n */\n thresholdValueChanged(): void {\n if (this.#watcher.active) this.#observe();\n }\n\n /** (Re)installs the observer from the current Values. */\n #observe(): void {\n this.#effectiveThreshold = this.#clampedThreshold();\n this.#watcher.start(this.element, {\n rootSelector: this.rootSelectorValue,\n rootMargin: this.rootMarginValue,\n threshold: this.#thresholds(),\n });\n if (this.#watcher.usingPlatformDefaults) this.#effectiveThreshold = 0;\n }\n\n /**\n * Re-delivers the current intersection state as a fresh transition. Bound via\n * `data-action` (e.g. `my-feed:appended@window->stimeo--intersection#refresh`).\n *\n * `IntersectionObserver` only reports state *changes*, so a sentinel that\n * stays visible while content is appended below it never fires `enter` again\n * and a hand-rolled infinite scroll stalls. `observe()` always delivers the\n * current state, and clearing the recorded `data-intersecting`/`data-passed`\n * makes that delivery count as a transition — a still-visible sentinel\n * re-fires `enter`. No-op once the observer is gone (`once` fired, no\n * `IntersectionObserver` support, or after `disconnect()`).\n */\n refresh(): void {\n if (!this.#watcher.active) return;\n this.#generation += 1;\n this.element.removeAttribute(\"data-intersecting\");\n this.element.removeAttribute(\"data-passed\");\n this.#watcher.rearm(this.element);\n }\n\n /**\n * Reflects the visibility onto `data-intersecting` and fires `enter`/`exit`\n * on transitions. The previous state is the DOM attribute (source of truth),\n * so the observer's initial callback fires `enter` for an element that starts\n * visible but stays silent after a cache restore that already recorded it.\n * An initial not-visible state is established silently (no `exit`).\n */\n #syncIntersecting(intersecting: boolean, ratio: number, entry: IntersectionObserverEntry): void {\n const previous = this.element.getAttribute(\"data-intersecting\");\n this.element.setAttribute(\"data-intersecting\", intersecting ? \"true\" : \"false\");\n\n if (intersecting && previous !== \"true\") {\n // One-shot mode: the shot is spent at this transition, so stop observing\n // before the event. A handler that re-arms (the `enter` -> append ->\n // `refresh()` reflex) then finds an inactive watcher and leaves the hooks\n // in their final state — `data-intersecting=\"true\"` marks it for reconnects.\n if (this.onceValue) this.#watcher.stop();\n this.dispatch(\"enter\", { detail: { ratio } });\n } else if (!intersecting && previous === \"true\") {\n this.dispatch(\"exit\", {\n detail: { ratio, position: this.#leftViaStartEdge(entry) ? \"before\" : \"after\" },\n });\n }\n }\n\n /**\n * Which edge the element left across, for the `exit` detail. A non-zero\n * `threshold` withdraws visibility while the element still overlaps the root,\n * so the leaving rect can straddle the start edge — the direction is the\n * element's own top against that edge, not whether it has cleared the root\n * entirely (that is what `passed` reports). An element with no layout box\n * (`display: none`, a collapsed `<details>`) is reported with an empty rect\n * that carries no position at all, so it is deliberately neither direction\n * and takes the \"still ahead\" reading.\n */\n #leftViaStartEdge(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 return rect.top < (entry.rootBounds?.top ?? 0);\n }\n\n /**\n * Reflects the \"scrolled past\" state onto `data-passed` and fires `passed` on\n * transitions — the line sticky headers and reading progress key off. Like\n * `enter`, an initial `passed=true` (page restored mid-scroll) fires; the\n * initial `false` is established silently.\n */\n #syncPassed(passed: boolean): void {\n const previous = this.element.getAttribute(\"data-passed\");\n this.element.setAttribute(\"data-passed\", passed ? \"true\" : \"false\");\n const changed = previous === null ? passed : (previous === \"true\") !== passed;\n if (changed) this.dispatch(\"passed\", { detail: { passed } });\n }\n\n /** The configured `threshold`, clamped to the 0..1 the observer accepts. */\n #clampedThreshold(): number {\n return Math.min(1, Math.max(0, this.thresholdValue));\n }\n\n /**\n * Observer thresholds: the `threshold` line itself, plus `ratioSteps` evenly\n * spaced steps when fine-grained `change` ratios are wanted (progress bars).\n *\n * 0 is always observed. An observer notifies only at the lines it was given,\n * so a non-zero `threshold` on its own delivers its last callback while the\n * element is still partly visible: the element leaving for good would never be\n * reported, freezing the ratio and `data-passed` mid-departure.\n */\n #thresholds(): number[] {\n const thresholds = new Set<number>([0, this.#clampedThreshold()]);\n if (this.ratioStepsValue > 0) {\n // i counts up to ratioSteps, so i/ratioSteps is inherently 0..1.\n for (let i = 0; i <= this.ratioStepsValue; i += 1) {\n thresholds.add(i / this.ratioStepsValue);\n }\n }\n return [...thresholds].sort((a, b) => a - b);\n }\n}\n"]}
@@ -14,19 +14,30 @@ import { Controller } from '@hotwired/stimulus';
14
14
  *
15
15
  * The URL is *held* in the `url` value (not on `src`) so Turbo does not load it eagerly;
16
16
  * when the frame intersects (within `rootMargin`) or focus enters it, the controller
17
- * writes `url` to `src` — which starts the Turbo load — marks `data-lazy-loaded`, and
18
- * emits `load`. With `once` (default) it then stops observing; otherwise re-entry asks
19
- * Turbo to `reload()` the frame.
17
+ * writes `url` to `src` — **writing `src` is what starts the fetch** — marks
18
+ * `data-lazy-loaded`, and emits `load`. Focus is the fallback for the *first* load only;
19
+ * once the frame has loaded, its listener is released and further focus moves inside the
20
+ * frame change nothing.
20
21
  *
21
- * `load` dispatches `{ url }`.
22
+ * With `once` (default) the controller then stops observing. With `once` off it keeps
23
+ * watching and re-fetches on a **re-entry** — the frame has to be seen inside the
24
+ * observed area, leave it, and come back. Where a connection first finds the frame is the
25
+ * baseline rather than a movement, so a focus-started load and a cache restore each begin
26
+ * the visit wherever the frame sits — in view or out of it — and re-fetch nothing until it
27
+ * leaves and returns. A re-entry serves the held `url`: when it still matches `src`, the
28
+ * host's own `reload()` refetches it; when it has moved on, writing the new `url` to `src`
29
+ * is the fetch.
30
+ *
31
+ * `load` dispatches `{ url }` — always the URL the fetch actually started for.
22
32
  *
23
33
  * @remarks
24
34
  * Behavior only — the load itself and the frame's content are Turbo's / the server's job,
25
- * and the loading UI (skeleton / `aria-busy`) belongs to Frame Loading State. The trigger
26
- * is idempotent (`data-lazy-loaded` guards a double load and is honored on a Turbo cache
27
- * restore — a frame that already loaded is not observed again). The `IntersectionObserver`
28
- * and focus listener are released once loaded (when `once`) and on `disconnect()` (Turbo
29
- * navigation included).
35
+ * and the loading UI (skeleton / `aria-busy`) belongs to `stimeo--frame-loading`. The trigger
36
+ * is idempotent (`data-lazy-loaded` guards a double load and is the truth source on a
37
+ * Turbo cache restore: a restored frame is observed again only while `once` is off, which
38
+ * is the mode that asked to keep re-fetching). An empty `url` arms nothing and is never
39
+ * written to `src`. The `IntersectionObserver` and focus listener are released once loaded
40
+ * (when `once`) and on `disconnect()` (Turbo navigation included).
30
41
  */
31
42
  declare class LazyFrameController extends Controller<HTMLElement> {
32
43
  #private;
@@ -48,6 +59,17 @@ declare class LazyFrameController extends Controller<HTMLElement> {
48
59
  urlValue: string;
49
60
  rootMarginValue: string;
50
61
  onceValue: boolean;
62
+ /**
63
+ * Follows the held URL at runtime: one that arrives arms the frame, one that is
64
+ * taken away disarms it, so an empty `url` holds no triggers either way.
65
+ *
66
+ * Stimulus runs value callbacks before `connect()`, so the connected guard keeps
67
+ * arming in one place. A frame that already loaded keeps its held URL for the next
68
+ * re-entry instead of fetching on the spot.
69
+ */
70
+ urlValueChanged(): void;
71
+ /** Rebuilds the observer when the early-load margin changes at runtime. */
72
+ rootMarginValueChanged(): void;
51
73
  connect(): void;
52
74
  disconnect(): void;
53
75
  }