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.
- package/CHANGELOG.md +70 -0
- package/dist/cable/index.js +23 -2
- package/dist/cable/index.js.map +1 -1
- package/dist/controllers/count_up_controller.d.ts +12 -10
- package/dist/controllers/count_up_controller.js +74 -35
- package/dist/controllers/count_up_controller.js.map +1 -1
- package/dist/controllers/intersection_controller.d.ts +20 -7
- package/dist/controllers/intersection_controller.js +55 -8
- package/dist/controllers/intersection_controller.js.map +1 -1
- package/dist/controllers/lazy_frame_controller.d.ts +31 -9
- package/dist/controllers/lazy_frame_controller.js +81 -19
- package/dist/controllers/lazy_frame_controller.js.map +1 -1
- package/dist/controllers/pointer_drag_controller.js +4 -0
- package/dist/controllers/pointer_drag_controller.js.map +1 -1
- package/dist/controllers/reading_progress_controller.d.ts +18 -9
- package/dist/controllers/reading_progress_controller.js +177 -6
- package/dist/controllers/reading_progress_controller.js.map +1 -1
- package/dist/controllers/scrollspy_controller.js +13 -2
- package/dist/controllers/scrollspy_controller.js.map +1 -1
- package/dist/controllers/smart_sticky_header_controller.d.ts +17 -8
- package/dist/controllers/smart_sticky_header_controller.js +52 -10
- package/dist/controllers/smart_sticky_header_controller.js.map +1 -1
- package/dist/controllers/sortable_controller.d.ts +38 -8
- package/dist/controllers/sortable_controller.js +241 -67
- package/dist/controllers/sortable_controller.js.map +1 -1
- package/dist/controllers/sticky_observer_controller.js +13 -2
- package/dist/controllers/sticky_observer_controller.js.map +1 -1
- package/dist/index.js +486 -145
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.js +1 -0
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js +1 -0
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +1 -1
- package/dist/inspector/manifest.json +8 -28
- package/package.json +1 -1
|
@@ -3,6 +3,14 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
3
3
|
// src/controllers/lazy_frame_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 :
|
|
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) => {
|
|
@@ -106,47 +117,98 @@ var LazyFrameController = class extends Controller {
|
|
|
106
117
|
static events = ["load"];
|
|
107
118
|
/** Shared IO plumbing (support guard, active guard, teardown). */
|
|
108
119
|
#watcher = new IntersectionWatcher((entries) => this.#onIntersect(entries));
|
|
120
|
+
#connected = false;
|
|
109
121
|
#loaded = false;
|
|
110
|
-
/**
|
|
111
|
-
|
|
122
|
+
/**
|
|
123
|
+
* Whether the observer last saw the frame inside the observed area — `null`
|
|
124
|
+
* until it has reported. A re-entry needs a frame that was seen inside and
|
|
125
|
+
* then left, so an unknown position is never a departure.
|
|
126
|
+
*/
|
|
127
|
+
#inside = null;
|
|
128
|
+
/**
|
|
129
|
+
* Focus reaching the frame starts the FIRST load before it intersects (keyboard / AT).
|
|
130
|
+
* `#load` releases this listener, so focus never reaches an already-loaded frame.
|
|
131
|
+
*/
|
|
132
|
+
#onFocus = () => this.#load();
|
|
133
|
+
/**
|
|
134
|
+
* Follows the held URL at runtime: one that arrives arms the frame, one that is
|
|
135
|
+
* taken away disarms it, so an empty `url` holds no triggers either way.
|
|
136
|
+
*
|
|
137
|
+
* Stimulus runs value callbacks before `connect()`, so the connected guard keeps
|
|
138
|
+
* arming in one place. A frame that already loaded keeps its held URL for the next
|
|
139
|
+
* re-entry instead of fetching on the spot.
|
|
140
|
+
*/
|
|
141
|
+
urlValueChanged() {
|
|
142
|
+
if (!this.#connected || this.#loaded) return;
|
|
143
|
+
if (this.urlValue) this.#arm();
|
|
144
|
+
else this.#stopObserving();
|
|
145
|
+
}
|
|
146
|
+
/** Rebuilds the observer when the early-load margin changes at runtime. */
|
|
147
|
+
rootMarginValueChanged() {
|
|
148
|
+
if (this.#connected && this.#watcher.active) this.#observe();
|
|
149
|
+
}
|
|
112
150
|
connect() {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
this.element.addEventListener("focusin", this.#onFocus);
|
|
119
|
-
this.#watcher.start(this.element, { rootMargin: this.rootMarginValue });
|
|
151
|
+
this.#loaded = this.element.hasAttribute("data-lazy-loaded");
|
|
152
|
+
this.#inside = null;
|
|
153
|
+
this.#connected = true;
|
|
154
|
+
if (this.#loaded && this.onceValue) return;
|
|
155
|
+
this.#arm();
|
|
120
156
|
}
|
|
121
157
|
disconnect() {
|
|
158
|
+
this.#connected = false;
|
|
122
159
|
this.#stopObserving();
|
|
123
160
|
}
|
|
161
|
+
/** Attaches the triggers that still have a job to do. */
|
|
162
|
+
#arm() {
|
|
163
|
+
if (!this.urlValue) return;
|
|
164
|
+
if (!this.#loaded) this.element.addEventListener("focusin", this.#onFocus);
|
|
165
|
+
this.#observe();
|
|
166
|
+
}
|
|
167
|
+
#observe() {
|
|
168
|
+
this.#watcher.start(this.element, { rootMargin: this.rootMarginValue });
|
|
169
|
+
}
|
|
124
170
|
#onIntersect(entries) {
|
|
125
171
|
for (const entry of entries) {
|
|
126
172
|
if (entry.isIntersecting) {
|
|
127
|
-
this.#
|
|
128
|
-
|
|
173
|
+
const returning = this.#inside === false;
|
|
174
|
+
this.#inside = true;
|
|
175
|
+
this.#enter(returning);
|
|
176
|
+
} else if (this.#inside) {
|
|
177
|
+
this.#inside = false;
|
|
129
178
|
}
|
|
130
179
|
}
|
|
131
180
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
181
|
+
/** Applies an intersecting entry: the first one loads, a return re-fetches. */
|
|
182
|
+
#enter(returning) {
|
|
183
|
+
if (!this.#loaded) {
|
|
184
|
+
this.#load();
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (this.onceValue || !returning) return;
|
|
188
|
+
this.#reload();
|
|
135
189
|
}
|
|
136
190
|
/** Starts the load by writing the held URL to `src`. */
|
|
137
191
|
#load() {
|
|
192
|
+
if (!this.urlValue) return;
|
|
138
193
|
this.#loaded = true;
|
|
139
194
|
this.element.setAttribute("src", this.urlValue);
|
|
140
195
|
this.element.setAttribute("data-lazy-loaded", "true");
|
|
141
196
|
this.dispatch("load", { detail: { url: this.urlValue } });
|
|
142
|
-
|
|
197
|
+
this.element.removeEventListener("focusin", this.#onFocus);
|
|
198
|
+
if (this.onceValue) this.#watcher.stop();
|
|
143
199
|
}
|
|
144
|
-
/** Re-entry while `once` is off:
|
|
200
|
+
/** Re-entry while `once` is off: fetch the held URL again. */
|
|
145
201
|
#reload() {
|
|
202
|
+
const src = this.element.getAttribute("src");
|
|
203
|
+
if (this.urlValue && this.urlValue !== src) {
|
|
204
|
+
this.element.setAttribute("src", this.urlValue);
|
|
205
|
+
this.dispatch("load", { detail: { url: this.urlValue } });
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
146
208
|
const frame = this.element;
|
|
147
209
|
if (typeof frame.reload !== "function") return;
|
|
148
210
|
frame.reload();
|
|
149
|
-
this.dispatch("load", { detail: { url:
|
|
211
|
+
this.dispatch("load", { detail: { url: src ?? "" } });
|
|
150
212
|
}
|
|
151
213
|
#stopObserving() {
|
|
152
214
|
this.#watcher.stop();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/controllers/lazy_frame_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,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,IAAI,IAAA,CAAK,SAAA,EAAW,IAAA,CAAK,cAAA,EAAe;AAAA,EAC1C;AAAA;AAAA,EAGA,OAAA,GAAgB;AACd,IAAA,MAAM,QAAQ,IAAA,CAAK,OAAA;AAGnB,IAAA,IAAI,OAAO,KAAA,CAAM,MAAA,KAAW,UAAA,EAAY;AACxC,IAAA,KAAA,CAAM,MAAA,EAAO;AACb,IAAA,IAAA,CAAK,QAAA,CAAS,QAAQ,EAAE,MAAA,EAAQ,EAAE,GAAA,EAAK,IAAA,CAAK,QAAA,EAAS,EAAG,CAAA;AAAA,EAC1D;AAAA,EAEA,cAAA,GAAuB;AACrB,IAAA,IAAA,CAAK,SAAS,IAAA,EAAK;AACnB,IAAA,IAAA,CAAK,OAAA,CAAQ,mBAAA,CAAoB,SAAA,EAAW,IAAA,CAAK,QAAQ,CAAA;AAAA,EAC3D;AACF","file":"lazy_frame_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 } from \"../utils/intersection_watcher\";\n\n/**\n * Headless **lazy frame**: defers a `<turbo-frame>`'s load until it nears the viewport\n * (or focus reaches it), to keep the initial render light. Turbo's own `loading=\"lazy\"`\n * observes with no margin, so the frame loads only once it is already in view; this\n * drives an explicit `IntersectionObserver` with a configurable `rootMargin`, plus a focus fallback so keyboard /\n * assistive-tech users trigger the load too (no APG pattern).\n *\n * Markup contract (identifier: `stimeo--lazy-frame`):\n * <turbo-frame id=\"comments\" data-controller=\"stimeo--lazy-frame\"\n * data-stimeo--lazy-frame-url-value=\"/posts/1/comments\"\n * data-stimeo--lazy-frame-root-margin-value=\"200px\">Loading…</turbo-frame>\n *\n * The URL is *held* in the `url` value (not on `src`) so Turbo does not load it eagerly;\n * when the frame intersects (within `rootMargin`) or focus enters it, the controller\n * writes `url` to `src` — which starts the Turbo load — marks `data-lazy-loaded`, and\n * emits `load`. With `once` (default) it then stops observing; otherwise re-entry asks\n * Turbo to `reload()` the frame.\n *\n * `load` dispatches `{ url }`.\n *\n * @remarks\n * Behavior only — the load itself and the frame's content are Turbo's / the server's job,\n * and the loading UI (skeleton / `aria-busy`) belongs to Frame Loading State. The trigger\n * is idempotent (`data-lazy-loaded` guards a double load and is honored on a Turbo cache\n * restore — a frame that already loaded is not observed again). The `IntersectionObserver`\n * and focus listener are released once loaded (when `once`) and on `disconnect()` (Turbo\n * navigation included).\n */\nexport class LazyFrameController extends Controller<HTMLElement> {\n static override values = {\n url: { type: String, default: \"\" },\n rootMargin: { type: String, default: \"0px\" },\n once: { type: Boolean, default: true },\n };\n static events = [\"load\"] as const;\n\n declare urlValue: string;\n declare rootMarginValue: string;\n declare onceValue: boolean;\n\n /** Shared IO plumbing (support guard, active guard, teardown). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersect(entries));\n #loaded = false;\n\n /** Focus reaching the frame triggers the load before it intersects (keyboard / AT). */\n readonly #onFocus = (): void => this.#trigger();\n\n override connect(): void {\n // A cache restore may bring back an already-loaded frame; respect it, do not reload.\n if (this.element.hasAttribute(\"data-lazy-loaded\")) {\n this.#loaded = true;\n return;\n }\n if (!this.urlValue) return;\n\n this.element.addEventListener(\"focusin\", this.#onFocus);\n this.#watcher.start(this.element, { rootMargin: this.rootMarginValue });\n }\n\n override disconnect(): void {\n this.#stopObserving();\n }\n\n #onIntersect(entries: IntersectionObserverEntry[]): void {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n this.#trigger();\n return;\n }\n }\n }\n\n #trigger(): void {\n if (!this.#loaded) this.#load();\n else if (!this.onceValue) this.#reload();\n }\n\n /** Starts the load by writing the held URL to `src`. */\n #load(): void {\n this.#loaded = true;\n this.element.setAttribute(\"src\", this.urlValue);\n this.element.setAttribute(\"data-lazy-loaded\", \"true\");\n this.dispatch(\"load\", { detail: { url: this.urlValue } });\n if (this.onceValue) this.#stopObserving();\n }\n\n /** Re-entry while `once` is off: ask Turbo to reload the frame's current `src`. */\n #reload(): void {\n const frame = this.element as HTMLElement & { reload?: () => void };\n // Only signal `load` when a reload actually happens. On a non-`<turbo-frame>`\n // host (no `reload()`), firing it would announce a load that never occurred.\n if (typeof frame.reload !== \"function\") return;\n frame.reload();\n this.dispatch(\"load\", { detail: { url: this.urlValue } });\n }\n\n #stopObserving(): void {\n this.#watcher.stop();\n this.element.removeEventListener(\"focusin\", this.#onFocus);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/controllers/lazy_frame_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,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A,CAAoB,SAAA,EAAW,IAAA,CAAK,QAAQ,CAAA;AAAA,EAC3D;AACF","file":"lazy_frame_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 } from \"../utils/intersection_watcher\";\n\n/**\n * Headless **lazy frame**: defers a `<turbo-frame>`'s load until it nears the viewport\n * (or focus reaches it), to keep the initial render light. Turbo's own `loading=\"lazy\"`\n * observes with no margin, so the frame loads only once it is already in view; this\n * drives an explicit `IntersectionObserver` with a configurable `rootMargin`, plus a focus fallback so keyboard /\n * assistive-tech users trigger the load too (no APG pattern).\n *\n * Markup contract (identifier: `stimeo--lazy-frame`):\n * <turbo-frame id=\"comments\" data-controller=\"stimeo--lazy-frame\"\n * data-stimeo--lazy-frame-url-value=\"/posts/1/comments\"\n * data-stimeo--lazy-frame-root-margin-value=\"200px\">Loading…</turbo-frame>\n *\n * The URL is *held* in the `url` value (not on `src`) so Turbo does not load it eagerly;\n * when the frame intersects (within `rootMargin`) or focus enters it, the controller\n * writes `url` to `src` — **writing `src` is what starts the fetch** — marks\n * `data-lazy-loaded`, and emits `load`. Focus is the fallback for the *first* load only;\n * once the frame has loaded, its listener is released and further focus moves inside the\n * frame change nothing.\n *\n * With `once` (default) the controller then stops observing. With `once` off it keeps\n * watching and re-fetches on a **re-entry** — the frame has to be seen inside the\n * observed area, leave it, and come back. Where a connection first finds the frame is the\n * baseline rather than a movement, so a focus-started load and a cache restore each begin\n * the visit wherever the frame sits — in view or out of it — and re-fetch nothing until it\n * leaves and returns. A re-entry serves the held `url`: when it still matches `src`, the\n * host's own `reload()` refetches it; when it has moved on, writing the new `url` to `src`\n * is the fetch.\n *\n * `load` dispatches `{ url }` — always the URL the fetch actually started for.\n *\n * @remarks\n * Behavior only — the load itself and the frame's content are Turbo's / the server's job,\n * and the loading UI (skeleton / `aria-busy`) belongs to `stimeo--frame-loading`. The trigger\n * is idempotent (`data-lazy-loaded` guards a double load and is the truth source on a\n * Turbo cache restore: a restored frame is observed again only while `once` is off, which\n * is the mode that asked to keep re-fetching). An empty `url` arms nothing and is never\n * written to `src`. The `IntersectionObserver` and focus listener are released once loaded\n * (when `once`) and on `disconnect()` (Turbo navigation included).\n */\nexport class LazyFrameController extends Controller<HTMLElement> {\n static override values = {\n url: { type: String, default: \"\" },\n rootMargin: { type: String, default: \"0px\" },\n once: { type: Boolean, default: true },\n };\n static events = [\"load\"] as const;\n\n declare urlValue: string;\n declare rootMarginValue: string;\n declare onceValue: boolean;\n\n /** Shared IO plumbing (support guard, active guard, teardown). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersect(entries));\n #connected = false;\n #loaded = false;\n /**\n * Whether the observer last saw the frame inside the observed area — `null`\n * until it has reported. A re-entry needs a frame that was seen inside and\n * then left, so an unknown position is never a departure.\n */\n #inside: boolean | null = null;\n\n /**\n * Focus reaching the frame starts the FIRST load before it intersects (keyboard / AT).\n * `#load` releases this listener, so focus never reaches an already-loaded frame.\n */\n readonly #onFocus = (): void => this.#load();\n\n /**\n * Follows the held URL at runtime: one that arrives arms the frame, one that is\n * taken away disarms it, so an empty `url` holds no triggers either way.\n *\n * Stimulus runs value callbacks before `connect()`, so the connected guard keeps\n * arming in one place. A frame that already loaded keeps its held URL for the next\n * re-entry instead of fetching on the spot.\n */\n urlValueChanged(): void {\n if (!this.#connected || this.#loaded) return;\n if (this.urlValue) this.#arm();\n else this.#stopObserving();\n }\n\n /** Rebuilds the observer when the early-load margin changes at runtime. */\n rootMarginValueChanged(): void {\n if (this.#connected && this.#watcher.active) this.#observe();\n }\n\n override connect(): void {\n // `data-lazy-loaded` is the truth source across a cache restore, and `once`\n // decides whether a restored frame still has anything to watch for.\n this.#loaded = this.element.hasAttribute(\"data-lazy-loaded\");\n this.#inside = null;\n this.#connected = true;\n if (this.#loaded && this.onceValue) return;\n this.#arm();\n }\n\n override disconnect(): void {\n this.#connected = false;\n this.#stopObserving();\n }\n\n /** Attaches the triggers that still have a job to do. */\n #arm(): void {\n if (!this.urlValue) return;\n if (!this.#loaded) this.element.addEventListener(\"focusin\", this.#onFocus);\n this.#observe();\n }\n\n #observe(): void {\n this.#watcher.start(this.element, { rootMargin: this.rootMarginValue });\n }\n\n #onIntersect(entries: IntersectionObserverEntry[]): void {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const returning = this.#inside === false;\n this.#inside = true;\n this.#enter(returning);\n } else if (this.#inside) {\n // An observer reports where the frame is before it reports any movement,\n // so only a frame already seen inside can be leaving.\n this.#inside = false;\n }\n }\n }\n\n /** Applies an intersecting entry: the first one loads, a return re-fetches. */\n #enter(returning: boolean): void {\n if (!this.#loaded) {\n this.#load();\n return;\n }\n if (this.onceValue || !returning) return;\n this.#reload();\n }\n\n /** Starts the load by writing the held URL to `src`. */\n #load(): void {\n if (!this.urlValue) return;\n this.#loaded = true;\n this.element.setAttribute(\"src\", this.urlValue);\n this.element.setAttribute(\"data-lazy-loaded\", \"true\");\n this.dispatch(\"load\", { detail: { url: this.urlValue } });\n // The focus fallback exists to start the first load; it has nothing left to do.\n this.element.removeEventListener(\"focusin\", this.#onFocus);\n if (this.onceValue) this.#watcher.stop();\n }\n\n /** Re-entry while `once` is off: fetch the held URL again. */\n #reload(): void {\n const src = this.element.getAttribute(\"src\");\n if (this.urlValue && this.urlValue !== src) {\n // The held URL moved on. Writing it to `src` is the fetch, the same start\n // the first load uses, so it works on any host.\n this.element.setAttribute(\"src\", this.urlValue);\n this.dispatch(\"load\", { detail: { url: this.urlValue } });\n return;\n }\n const frame = this.element as HTMLElement & { reload?: () => void };\n // Refetching the URL already on `src` needs the host's own `reload()`. On a\n // non-`<turbo-frame>` host there is none, and firing `load` would announce a\n // fetch that never started.\n if (typeof frame.reload !== \"function\") return;\n frame.reload();\n this.dispatch(\"load\", { detail: { url: src ?? \"\" } });\n }\n\n #stopObserving(): void {\n this.#watcher.stop();\n this.element.removeEventListener(\"focusin\", this.#onFocus);\n }\n}\n"]}
|
|
@@ -255,6 +255,10 @@ var PointerDragController = class _PointerDragController extends Controller {
|
|
|
255
255
|
return;
|
|
256
256
|
}
|
|
257
257
|
if (!this.#keyboard) return;
|
|
258
|
+
if (event.key === "Home" || event.key === "End") {
|
|
259
|
+
event.preventDefault();
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
258
262
|
const step = this.#keyboardDelta(event.key);
|
|
259
263
|
if (!step) return;
|
|
260
264
|
event.preventDefault();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/arrow_step.ts","../../src/utils/detach_gate.ts","../../src/controllers/pointer_drag_controller.ts"],"names":[],"mappings":";;;;;AA+FO,SAAS,oBAAA,CACd,KAAA,EACA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AA,CAAgB,uBAAsB,gBAAgB,CAAA;AAAA,IAC1E;AAAA,EACF;AACF","file":"pointer_drag_controller.js","sourcesContent":["import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n\n/**\n * True when a press arrived carrying any modifier, for the keys the browser and\n * the OS own outright: return without calling `preventDefault()` and without\n * moving any state.\n *\n * `Control+Home` and `Control+End` jump the document to its ends, and a widget\n * that swallows them makes the shortcut work or not depending on where focus\n * happens to sit. {@link isReservedArrowChord} answers the same question for the\n * arrows, but returns `false` for every other key so that this one can decide.\n *\n * There is no `allow` list here on purpose. APG assigns no modifier chord to\n * `Home`/`End`, so a widget that wanted one would be claiming a combination the\n * pattern never gave it.\n *\n * @example\n * ```ts\n * case \"Home\":\n * case \"End\":\n * if (hasModifierChord(event)) return;\n * ```\n */\nexport function hasModifierChord(event: KeyboardEvent): boolean {\n return event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;\n}\n","/**\n * Shared \"in-page move vs real detach\" discriminator for `disconnect()`.\n *\n * A mid-session `disconnect()` whose element is still in the document is\n * ambiguous. It can be:\n *\n * - an **in-page move** — a consumer (sortable, a teleport) re-inserted the\n * element; Stimulus reconnects the SAME instance in the same mutation batch\n * and the controller's runtime state must survive;\n * - a **detach that keeps the element** — `data-controller` no longer lists the\n * identifier (a Turbo 8 morph), or the element moved outside the observed\n * root (a scoped `Application.start(root)`, a shadow root); no reconnect will\n * ever come and the controller must tear down or it leaks its sessions,\n * document listeners, and moved nodes.\n *\n * Neither available signal decides this alone. A synchronous `data-controller`\n * token check catches the morph case but misses an observed-root exit (the\n * token stays, the reconnect never comes). Deferring teardown one microtask and\n * letting `connect()` cancel it catches the root exit, but leans on Stimulus\n * reconnecting moved elements within the same mutation batch — internal\n * behavior, not a public contract. {@link DetachGate} composes both: the token\n * check is the synchronous fast path (no probe, no reliance on batching), the\n * microtask probe is the fallback for the genuinely ambiguous remainder.\n *\n * Policy stays with the consumer; this util owns the discrimination only:\n *\n * - **Probe** ({@link disconnected}) when the teardown must eventually happen —\n * live drag sessions, document listeners, teleported *content*. Call\n * {@link cancel} from `connect()` (a reconnect means in-page move) and from\n * the head of any direct teardown path (see below).\n * - **Keep** (bare {@link DetachGate.isDetached}) when undoing the ambiguous\n * case would fight the controller's own effect: a controller that moves its\n * OWN element (portal's no-`content` form) exits a scoped observed root as\n * its normal job — a probe-driven teardown would restore the element into\n * the root, reconnect, re-teleport, and disconnect again, forever. Such\n * controllers keep their state on an ambiguous disconnect and tear down only\n * on {@link DetachGate.isDetached}.\n *\n * Event convention for probe consumers: teardown into a dead (detached) tree is\n * silent — consumers restore from their own `connect()`; a detach that keeps the\n * tree alive must end an in-flight session with a `cancel` event, or composing\n * consumers strand their session bookkeeping.\n */\n\n/** The slice of a Stimulus controller the gate inspects. */\nexport interface DetachGateHost {\n readonly element: Element;\n readonly identifier: string;\n}\n\n/**\n * Per-controller-instance gate deciding whether a `disconnect()` is a real\n * detach. Hold one per controller (`#gate = new DetachGate()`) — Stimulus\n * reuses the instance across reconnects, so the pending probe state carries\n * over exactly as the protocol needs.\n *\n * @example\n * ```ts\n * #gate = new DetachGate();\n *\n * connect(): void {\n * this.#gate.cancel(); // a reconnect: the element moved in-page\n * // …\n * }\n *\n * disconnect(): void {\n * this.#gate.disconnected(this, () => this.#teardown());\n * }\n *\n * #teardown(): void {\n * this.#gate.cancel(); // disarm a still-queued probe (double-run guard)\n * // …\n * }\n * ```\n */\nexport class DetachGate {\n /** Set while a probe is queued, waiting for a reconnect to cancel it. */\n #pending = false;\n\n /**\n * True while a probe is queued — the last disconnect was ambiguous and no\n * reconnect has cancelled it yet. Read it from `connect()` to tell the\n * reconnect half of an in-page move from a first connect: a controller whose\n * initialisation restarts a measurement (a min-duration floor, an elapsed\n * counter) must skip it for the move, where nothing actually restarted.\n */\n get pending(): boolean {\n return this.#pending;\n }\n\n /**\n * True when the disconnect is definitely a real detach — the element left\n * the document, or `data-controller` no longer lists the identifier. False\n * means ambiguous (in-page move or observed-root exit), NOT \"alive\".\n */\n static isDetached(host: DetachGateHost): boolean {\n if (!host.element.isConnected) return true;\n const tokens = (host.element.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n return !tokens.includes(host.identifier);\n }\n\n /**\n * Call from `disconnect()`: runs `teardown` synchronously on a definite\n * detach (fast path), otherwise defers it one microtask — a reconnect\n * ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.\n * One microtask is the whole probe window: Stimulus reconnects a moved\n * element within the same mutation batch, before the checkpoint drains.\n */\n disconnected(host: DetachGateHost, teardown: () => void): void {\n if (DetachGate.isDetached(host)) {\n // Also disarms a probe a previous ambiguous disconnect left queued\n // (defer, element removed, disconnect again) — exactly one teardown.\n this.#pending = false;\n teardown();\n return;\n }\n this.#pending = true;\n queueMicrotask(() => {\n if (!this.#pending) return;\n this.#pending = false;\n teardown();\n });\n }\n\n /**\n * Disarms a pending probe. Call from `connect()` (the reconnect that proves\n * an in-page move) and from the head of any teardown path not routed through\n * {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can\n * never run the teardown a second time.\n */\n cancel(): void {\n this.#pending = false;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord } from \"../utils/arrow_step\";\nimport { DetachGate } from \"../utils/detach_gate\";\n\n/**\n * Elements whose own default action owns a key press. The browser never signals\n * those through `defaultPrevented`, so a yield on that flag cannot see them.\n */\nconst NATIVE_KEY_OWNERS = \"input, textarea, select, button, a[href], summary, [contenteditable]\";\n\n/** How a drag session was initiated; surfaced in every event detail. */\ntype DragPointerType = \"mouse\" | \"touch\" | \"pen\" | \"keyboard\";\n\n/** A pointer drag in flight (from `pointerdown` until up/cancel). */\ninterface PointerSession {\n pointerId: number;\n handle: HTMLElement;\n originX: number;\n originY: number;\n /** True once the movement passed `threshold` and `start` was dispatched. */\n started: boolean;\n /** Last axis-filtered deltas, reported again by `end`. */\n dx: number;\n dy: number;\n pointerType: DragPointerType;\n}\n\n/** A keyboard \"grabbed\" session (Space/Enter on the handle until drop/cancel). */\ninterface KeyboardSession {\n handle: HTMLElement;\n /** Cumulative synthetic deltas accumulated by the arrow keys. */\n dx: number;\n dy: number;\n}\n\n/**\n * Headless **pointer-drag primitive**: a normalized pointer/touch/mouse drag\n * lifecycle with a built-in keyboard alternative. It deliberately does NOT decide\n * what a drag *means* (reorder, dismiss, resize…) — it only emits a clean,\n * accessibility-friendly drag signal that higher-level behaviors compose from —\n * `stimeo--sortable` is one, and reordering, dismissal, and resizing are the usual\n * meanings a consumer layers on. No dedicated APG\n * pattern exists for drag-and-drop; the keyboard model below is the accepted\n * alternative-input technique (WCAG 2.1.1 / 2.5.7 Dragging Movements). Core\n * (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--pointer-drag`):\n * <li data-controller=\"stimeo--pointer-drag\"\n * data-stimeo--pointer-drag-axis-value=\"y\">\n * <button data-stimeo--pointer-drag-target=\"handle\" aria-label=\"Reorder\">⠿</button>\n * </li>\n *\n * The `handle` target is optional — without one, the controller element itself\n * is the handle. Pointer flow: `pointerdown` on a handle arms the drag; once the\n * axis-filtered movement exceeds `threshold`, `start` fires, every subsequent\n * movement fires `move` (deltas cumulative from the origin), and release fires\n * `end` (`pointercancel` → `cancel`). Keyboard flow: Space/Enter on the handle\n * grabs (`start`, `data-grabbed`), the arrow keys emit synthetic `move` events of\n * `keyboardStep` px each, Space/Enter drops (`end`) and Escape cancels — so every\n * consumer gets a keyboard path for free.\n *\n * `start` dispatches `{ x, y, pointerType }`; `move` dispatches `{ dx, dy, x, y, pointerType }`;\n * `end` dispatches `{ dx, dy, pointerType }`; `cancel` dispatches `{ pointerType }`.\n *\n * @remarks\n * Behavior only: consumers own all visuals (ghost, placeholder, transforms) by\n * reacting to the events and the `data-dragging` / `data-grabbed` hooks. The one\n * deliberate exception is the opt-in `follow` value for the \"just move the\n * element\" case: it applies the in-flight deltas to the element's CSS\n * `translate` (a property independent of `transform`, so authored transforms\n * survive), commits the offset on drop and restores it on cancel — the exact\n * boilerplate every simple consumer would otherwise re-write. With `follow` the\n * element's inline `translate` belongs to this controller (`connect()` re-reads\n * a committed `<x>px <y>px` offset, so Turbo restores stay consistent). ARIA 1.1\n * deprecated `aria-grabbed`/`aria-dropeffect`, so the grabbed state is\n * published as `data-grabbed` and the *meaning* of a drag must be announced by\n * the consumer (pair with `stimeo--announcer`). `touch-action` on the handles is\n * derived from `axis` (marker-guarded, authored values win) so the page does not\n * pan mid-drag. Deltas are physical (client coordinates): RTL semantics belong\n * to the consumer. `disconnect()` (Turbo navigation included) tears down any\n * active session — except across an in-page move, which the session survives\n * (the full lifecycle contract lives on `disconnect()`); `connect()` clears\n * stale hooks a Turbo cache restore may have preserved (a drag cannot survive\n * a navigation).\n */\nexport class PointerDragController extends Controller<HTMLElement> {\n static override targets = [\"handle\"];\n static override values = {\n axis: { type: String, default: \"both\" },\n threshold: { type: Number, default: 3 },\n keyboardStep: { type: Number, default: 10 },\n disabled: { type: Boolean, default: false },\n follow: { type: Boolean, default: false },\n };\n static actions = [\"reset\"] as const;\n static events = [\"start\", \"move\", \"end\", \"cancel\"] as const;\n\n declare readonly handleTargets: HTMLElement[];\n declare readonly hasHandleTarget: boolean;\n declare axisValue: string;\n declare thresholdValue: number;\n declare keyboardStepValue: number;\n declare disabledValue: boolean;\n declare followValue: boolean;\n\n /** Marker attribute recording that this controller set the touch-action. */\n static readonly #TOUCH_ACTION_MARKER = \"data-pointer-drag-touch-action\";\n /** Marker attribute recording that this controller set `tabindex`. */\n static readonly #TABINDEX_MARKER = \"data-pointer-drag-tabindex\";\n\n #pointer: PointerSession | null = null;\n #keyboard: KeyboardSession | null = null;\n /** Committed follow offset from past drops; a new drag's deltas add onto it. */\n #followBase = { x: 0, y: 0 };\n /** Aborts in-progress pointer-drag listeners on drag end / teardown. */\n #dragAbort: AbortController | null = null;\n /** Decides whether a mid-session disconnect() is an in-page move or a detach. */\n readonly #gate = new DetachGate();\n\n override connect(): void {\n // A reconnect disarms the probe a mid-session disconnect() armed — the\n // element was moved in-page and the session survives (see disconnect).\n this.#gate.cancel();\n // Transient drag state cannot survive a navigation: clear hooks a Turbo\n // cache restore may have snapshotted mid-drag (idempotent reconnect). But a\n // session preserved across an in-page move keeps its hooks.\n if (!this.#pointer) this.element.removeAttribute(\"data-dragging\");\n if (!this.#keyboard) this.element.removeAttribute(\"data-grabbed\");\n // Follow mode owns the element's inline `translate`: re-read a committed\n // offset so reconnects (Turbo cache restore included) keep accumulating from\n // where the element visually sits. A session surviving an in-page move keeps\n // its base — mid-drag inline state must not be committed as a new base.\n if (this.followValue && !this.#pointer && !this.#keyboard) {\n this.#followBase = this.#parseFollowBase();\n }\n // Delegated on the container so dynamically added handles need no per-element\n // data-action.\n this.element.addEventListener(\"pointerdown\", this.#onPointerDown);\n this.element.addEventListener(\"keydown\", this.#onKeydown);\n if (!this.hasHandleTarget) this.#prepareHandle(this.element);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"pointerdown\", this.#onPointerDown);\n this.element.removeEventListener(\"keydown\", this.#onKeydown);\n // A mid-session disconnect on a STILL-connected element is ambiguous: an\n // in-page move (a consumer like sortable re-inserts the item mid-grab —\n // Stimulus reconnects the same instance in the same mutation batch, and\n // the session must survive) vs a real detach that keeps the element\n // (`data-controller` removed, Turbo morph, element moved outside the\n // observed root). DetachGate discriminates: the token check is the\n // synchronous fast path (a morph's teardown — and its `cancel` — fires in\n // the same tick), the one-microtask probe cancelled by connect() covers\n // the rest — a detached-in-place controller never leaks its session or\n // document listeners. Probe only while a session needs protecting; an\n // idle controller tears down synchronously either way.\n if (this.#pointer || this.#keyboard) {\n this.#gate.disconnected(this, () => this.#teardown());\n return;\n }\n this.#teardown();\n }\n\n /**\n * Returns the element to its origin: drops the committed follow offset and the\n * inline `translate` that carries it.\n *\n * In follow mode the inline `translate` belongs to this controller, and the\n * committed offset lives in a field the DOM cannot reach — so a consumer that\n * wants the element back at the start, or that has written a position of its\n * own, needs this to make the two agree again. An in-flight drag is cancelled\n * first, or its deltas would land on top of the offset just cleared.\n */\n reset(): void {\n // Cancel first, then clear: the cancel contract snaps back to the committed\n // offset, so clearing before it would be undone on the way out.\n const live = this.#pointer?.started\n ? this.#pointer.pointerType\n : this.#keyboard\n ? \"keyboard\"\n : null;\n if (this.#pointer || this.#keyboard) this.#teardownSessions();\n if (live) this.#dispatchCancel(live);\n this.#followBase = { x: 0, y: 0 };\n this.#applyFollow(0, 0);\n }\n\n handleTargetConnected(handle: HTMLElement): void {\n // The element wears the handle contract only while it IS the handle; the\n // first real handle takes it back. (Marker-guarded, so this is a no-op when\n // the element never wore it.)\n if (handle !== this.element) this.#restoreHandle(this.element);\n this.#prepareHandle(handle);\n }\n\n handleTargetDisconnected(handle: HTMLElement): void {\n // The loan is due back the moment an element stops being a handle, and this\n // callback is the only place that sees every such element: once the\n // identifier token is gone, `#handles()` no longer resolves the targets.\n // Across an in-page move `handleTargetConnected` lends it again in the same\n // mutation batch.\n this.#restoreHandle(handle);\n // Target callbacks ALSO fire when the CONTROLLER goes away (Stimulus stops\n // the target observer after `disconnect()` has run) and across the in-page\n // move a live session must survive. In both the handle is still inside the\n // element: the session belongs to `disconnect()`, and handing the contract\n // to the container here would bake a nameless tab stop onto it on every\n // morph. Only a handle that actually LEFT is this callback's business.\n if (this.element.contains(handle)) return;\n\n // It can never deliver its keydown again (the delegated listener sits on the\n // container it left), so a live session would leak and the one-session guard\n // would reject every future pointerdown. The tree and the consumers are both\n // alive here, so it ends the way every other keep-the-element teardown does:\n // in `cancel`, or a composer like sortable strands its session bookkeeping.\n const interrupted =\n this.#pointer?.handle === handle && this.#pointer.started\n ? this.#pointer.pointerType\n : this.#keyboard?.handle === handle\n ? (\"keyboard\" as const)\n : null;\n if (this.#pointer?.handle === handle) this.#endPointerSession();\n if (this.#keyboard?.handle === handle) this.#clearKeyboardSession();\n // With the last handle gone the element is the handle again (`#handles()`),\n // so it needs the contract the departing handle just gave back.\n if (!this.hasHandleTarget) this.#prepareHandle(this.element);\n if (interrupted) this.#dispatchCancel(interrupted);\n }\n\n /**\n * Re-derives the handles' touch-action when the axis changes.\n *\n * Two layers, like the `tabindex` loan: the marker says the value was once\n * ours, and the current inline value says it still is. A consumer that wrote\n * its own `touch-action` after connect keeps it.\n */\n axisValueChanged(_value: string, previousValue: string | undefined): void {\n // The value to recognize as ours is the one the previous axis lent. Stimulus\n // also replays a value that did NOT change (ahead of every connect), and\n // there the axis in force is the one it was lent under.\n const lent = this.#touchActionFor(previousValue ?? this.axisValue);\n for (const handle of this.#handles()) {\n if (!handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER)) continue;\n if (handle.style.touchAction !== lent) continue;\n handle.style.touchAction = this.#touchActionForAxis();\n }\n }\n\n /** Cancels any in-flight session when the controller is disabled mid-drag. */\n disabledValueChanged(): void {\n if (!this.disabledValue) return;\n if (this.#pointer?.started || this.#keyboard) {\n this.#dispatchCancel(this.#keyboard ? \"keyboard\" : (this.#pointer?.pointerType ?? \"mouse\"));\n }\n this.#teardownSessions();\n }\n\n /** Arms a pointer drag on a handle; `start` waits for the threshold. */\n readonly #onPointerDown = (event: PointerEvent): void => {\n // One session at a time: ignore a second pointerdown (multi-touch, an\n // errant tap, a grabbed keyboard session) so an in-flight drag is never\n // silently overwritten and its captured pointer orphaned.\n if (this.disabledValue || this.#pointer || this.#keyboard || event.button !== 0) return;\n const handle = this.#handleFor(event.target);\n if (!handle) return;\n\n // Suppress text selection / native image drag; restore the focus the\n // suppressed default would have given, so Escape and the keyboard path\n // stay reachable right after a pointer interaction (WCAG 2.1.1).\n event.preventDefault();\n handle.focus();\n\n this.#pointer = {\n pointerId: event.pointerId,\n handle,\n originX: event.clientX,\n originY: event.clientY,\n started: false,\n dx: 0,\n dy: 0,\n pointerType: this.#pointerTypeOf(event),\n };\n\n // Pointer capture keeps fast drags delivering to the handle even when the\n // pointer strays outside it — but a consumer may re-insert the dragged\n // element mid-drag (sortable's live reorder), which silently releases the\n // capture. Tracking listeners therefore live on the DOCUMENT (captured\n // events bubble there; uncaptured ones fire there anyway), and the\n // AbortController releases them on drag end and disconnect() (Turbo included).\n handle.setPointerCapture(event.pointerId);\n this.#dragAbort?.abort();\n const abort = new AbortController();\n this.#dragAbort = abort;\n document.addEventListener(\"pointermove\", this.#onPointerMove, { signal: abort.signal });\n document.addEventListener(\"pointerup\", this.#onPointerUp, { signal: abort.signal });\n document.addEventListener(\"pointercancel\", this.#onPointerCancel, { signal: abort.signal });\n };\n\n readonly #onPointerMove = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n\n const [dx, dy] = this.#filterAxis(\n event.clientX - session.originX,\n event.clientY - session.originY,\n );\n if (!session.started) {\n if (Math.hypot(dx, dy) < this.thresholdValue) return;\n session.started = true;\n this.element.setAttribute(\"data-dragging\", \"true\");\n this.dispatch(\"start\", {\n detail: { x: event.clientX, y: event.clientY, pointerType: session.pointerType },\n });\n }\n\n session.dx = dx;\n session.dy = dy;\n this.#followMove(dx, dy);\n this.dispatch(\"move\", {\n detail: { dx, dy, x: event.clientX, y: event.clientY, pointerType: session.pointerType },\n });\n };\n\n readonly #onPointerUp = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n const { started, dx, dy, pointerType } = session;\n this.#endPointerSession();\n // Below the threshold the gesture was a plain click, not a drag: stay silent.\n if (!started) return;\n this.#followCommit(dx, dy);\n this.dispatch(\"end\", { detail: { dx, dy, pointerType } });\n };\n\n /** OS gesture / scroll takeover interrupted the drag: cancel, don't drop. */\n readonly #onPointerCancel = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n const { started, pointerType } = session;\n this.#endPointerSession();\n if (started) this.#dispatchCancel(pointerType);\n };\n\n /** Keyboard alternative: Space/Enter grab & drop, arrows move, Escape cancels. */\n readonly #onKeydown = (event: KeyboardEvent): void => {\n if (this.disabledValue) return;\n const handle = this.#handleFor(event.target);\n if (!handle) return;\n\n // A descendant widget that already claimed the key (a nested roving list, a\n // segmented field inside the handle) must not ALSO drive the drag —\n // composition depends on this yield.\n if (event.defaultPrevented) return;\n // A press that steers an IME conversion belongs to the composition, and an\n // input method never says so through `defaultPrevented`.\n if (event.isComposing) return;\n // Neither does a native control or editing surface inside the handle: typing\n // a space into a field and activating a link are default actions, not claims.\n // Widgets that do claim their keys keep composing through the yield above.\n if (this.#ownsNativeKeys(event.target, handle)) return;\n // A chorded arrow belongs to the browser. \"Someone already consumed it\"\n // outranks that, so it is checked after the yields above.\n if (isReservedArrowChord(event)) return;\n\n // Escape cancels whichever session is live (pointer drag or keyboard grab).\n if (event.key === \"Escape\") {\n if (this.#pointer?.started) {\n const { pointerType } = this.#pointer;\n this.#teardownSessions();\n event.preventDefault();\n this.#dispatchCancel(pointerType);\n } else if (this.#keyboard) {\n this.#teardownSessions();\n event.preventDefault();\n this.#dispatchCancel(\"keyboard\");\n }\n return;\n }\n\n if (event.key === \" \" || event.key === \"Enter\") {\n // A live pointer drag owns the session: pressing Space mid-drag (the\n // pointerdown focused the handle) must not start a parallel grab.\n if (this.#pointer) return;\n event.preventDefault();\n if (this.#keyboard) this.#dropKeyboard();\n else this.#grabKeyboard(handle);\n return;\n }\n\n if (!this.#keyboard) return;\n const step = this.#keyboardDelta(event.key);\n if (!step) return;\n // Consume every arrow while grabbed (even on a locked axis) so the page\n // never scrolls mid-grab; only allowed-axis arrows emit a move.\n event.preventDefault();\n const [dx, dy] = this.#filterAxis(step[0], step[1]);\n if (dx === 0 && dy === 0) return;\n this.#keyboard.dx += dx;\n this.#keyboard.dy += dy;\n this.#followMove(this.#keyboard.dx, this.#keyboard.dy);\n this.dispatch(\"move\", {\n detail: {\n dx: this.#keyboard.dx,\n dy: this.#keyboard.dy,\n x: this.#keyboard.dx,\n y: this.#keyboard.dy,\n pointerType: \"keyboard\",\n },\n });\n };\n\n /** Enters the grabbed mode: `data-grabbed` on element + handle, then `start`. */\n #grabKeyboard(handle: HTMLElement): void {\n this.#keyboard = { handle, dx: 0, dy: 0 };\n this.element.setAttribute(\"data-grabbed\", \"true\");\n handle.setAttribute(\"data-grabbed\", \"true\");\n this.dispatch(\"start\", { detail: { x: 0, y: 0, pointerType: \"keyboard\" } });\n }\n\n #dropKeyboard(): void {\n const session = this.#keyboard;\n if (!session) return;\n this.#clearKeyboardSession();\n this.#followCommit(session.dx, session.dy);\n this.dispatch(\"end\", { detail: { dx: session.dx, dy: session.dy, pointerType: \"keyboard\" } });\n }\n\n /** Maps an arrow key to a raw (unfiltered) `keyboardStep` delta. */\n #keyboardDelta(key: string): [number, number] | null {\n const step = this.keyboardStepValue;\n switch (key) {\n case \"ArrowRight\":\n return [step, 0];\n case \"ArrowLeft\":\n return [-step, 0];\n case \"ArrowDown\":\n return [0, step];\n case \"ArrowUp\":\n return [0, -step];\n default:\n return null;\n }\n }\n\n /** Zeroes the delta on the locked axis (`axis` = x | y | both). */\n #filterAxis(dx: number, dy: number): [number, number] {\n if (this.axisValue === \"x\") return [dx, 0];\n if (this.axisValue === \"y\") return [0, dy];\n return [dx, dy];\n }\n\n /** Releases capture + listeners and clears the pointer session and its hook. */\n #endPointerSession(): void {\n this.#releasePointerCapture();\n this.#pointer = null;\n this.#dragAbort?.abort();\n this.#dragAbort = null;\n this.element.removeAttribute(\"data-dragging\");\n }\n\n /** Releases the pointer capture the active session set (idempotent, safe). */\n #releasePointerCapture(): void {\n const session = this.#pointer;\n if (session?.handle.hasPointerCapture(session.pointerId)) {\n session.handle.releasePointerCapture(session.pointerId);\n }\n }\n\n #clearKeyboardSession(): void {\n this.#keyboard?.handle.removeAttribute(\"data-grabbed\");\n this.#keyboard = null;\n this.element.removeAttribute(\"data-grabbed\");\n }\n\n /**\n * Full teardown for a controller whose element is going away or lost its\n * controller. Into a dead (detached) tree it is silent — consumers restore\n * from their own `connect()`, not from a cancel event. But a detach that\n * KEEPS the element (Turbo morph, `data-controller` removed) leaves the\n * consumers alive and listening: an in-flight session must end in `cancel`\n * there, or a composer like sortable strands its one-at-a-time session\n * bookkeeping forever.\n */\n #teardown(): void {\n // Disarm any probe still queued: without this, an immediate teardown\n // (element removed right after a deferring disconnect) would let the\n // orphaned probe run #teardown a second time — a double cancel.\n this.#gate.cancel();\n const interrupted = this.#pointer?.started\n ? this.#pointer.pointerType\n : this.#keyboard\n ? (\"keyboard\" as const)\n : null;\n this.#teardownSessions();\n for (const handle of this.#handles()) this.#restoreHandle(handle);\n // An in-flight offset must leave the DOM even where nobody is listening: a\n // re-inserted element would have `connect()` read it back as a committed base.\n this.#followReset();\n if (interrupted && this.element.isConnected) this.#dispatchCancel(interrupted);\n }\n\n /**\n * Silently tears down whatever session is live (disconnect / disabled /\n * Escape). Composed from the two single-session teardowns so pointer and\n * keyboard cleanup cannot diverge as either path evolves.\n */\n #teardownSessions(): void {\n this.#endPointerSession();\n this.#clearKeyboardSession();\n }\n\n #dispatchCancel(pointerType: DragPointerType): void {\n // Every cancel path funnels here, so follow's snap-back can never be missed\n // (Escape, pointercancel, mid-session disable, detach-that-keeps-the-element).\n this.#followReset();\n this.dispatch(\"cancel\", { detail: { pointerType } });\n }\n\n /** Applies the in-flight offset to the element's `translate` (follow only). */\n #followMove(dx: number, dy: number): void {\n if (!this.followValue) return;\n this.#applyFollow(this.#followBase.x + dx, this.#followBase.y + dy);\n }\n\n /** Folds a drop's deltas into the committed base offset (follow only). */\n #followCommit(dx: number, dy: number): void {\n if (!this.followValue) return;\n this.#followBase = { x: this.#followBase.x + dx, y: this.#followBase.y + dy };\n this.#applyFollow(this.#followBase.x, this.#followBase.y);\n }\n\n /** Snaps back to the committed position (follow only) — the cancel contract. */\n #followReset(): void {\n if (!this.followValue) return;\n this.#applyFollow(this.#followBase.x, this.#followBase.y);\n }\n\n /**\n * Writes the offset as the standalone CSS `translate` property — independent\n * of `transform`, so an authored transform (scale, rotate…) is never\n * clobbered. At the origin the property is removed to keep the DOM clean.\n */\n #applyFollow(x: number, y: number): void {\n if (x === 0 && y === 0) this.element.style.removeProperty(\"translate\");\n else this.element.style.setProperty(\"translate\", `${x}px ${y}px`);\n }\n\n /**\n * Reads a committed follow offset back from the inline `translate`. Only the\n * controller's own `<x>px <y>px` shape is recognized; anything else (an\n * authored percentage, `none`, an empty string) starts the base at 0 — follow\n * mode owns this property, per the class contract.\n */\n #parseFollowBase(): { x: number; y: number } {\n const raw = this.element.style.getPropertyValue(\"translate\").trim();\n const match = /^(-?\\d+(?:\\.\\d+)?)px(?:\\s+(-?\\d+(?:\\.\\d+)?)px)?$/.exec(raw);\n if (!match) return { x: 0, y: 0 };\n return { x: Number(match[1]), y: Number(match[2] ?? \"0\") };\n }\n\n /** The active handles: the `handle` targets, else the element itself. */\n #handles(): HTMLElement[] {\n return this.hasHandleTarget ? this.handleTargets : [this.element];\n }\n\n /** Resolves the handle owning an event target (the handle or a descendant). */\n #handleFor(target: EventTarget | null): HTMLElement | null {\n const node = target as Node | null;\n if (!node) return null;\n return this.#handles().find((handle) => handle === node || handle.contains(node)) ?? null;\n }\n\n #pointerTypeOf(event: PointerEvent): DragPointerType {\n const type = event.pointerType;\n if (type === \"touch\" || type === \"pen\") return type;\n return \"mouse\";\n }\n\n /** `touch-action` that lets the page keep panning on the locked axis only. */\n #touchActionForAxis(): string {\n return this.#touchActionFor(this.axisValue);\n }\n\n /** The `touch-action` an `axis` declaration lends, for any axis value. */\n #touchActionFor(axis: string): string {\n if (axis === \"x\") return \"pan-y\";\n if (axis === \"y\") return \"pan-x\";\n return \"none\";\n }\n\n /**\n * Establishes the handle contract: a `touch-action` derived from `axis`\n * (marker-guarded so an authored inline value wins and reconnects stay\n * idempotent) and focusability for the keyboard path (`tabindex=\"0\"` only when\n * the author supplied none — prefer a real `<button>` handle). Both additions\n * are marker-owned so `#restoreHandle` reverts them symmetrically on teardown.\n */\n #prepareHandle(handle: HTMLElement): void {\n const lent = this.#touchActionForAxis();\n // Two layers, as when the loan is returned: a free property is ours to take,\n // and a marked one is still ours only while it reads back as what was lent.\n // A consumer that wrote its own value keeps it across every reconnect.\n const marked = handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER);\n if (handle.style.touchAction === \"\" || (marked && handle.style.touchAction === lent)) {\n handle.style.touchAction = lent;\n handle.setAttribute(PointerDragController.#TOUCH_ACTION_MARKER, \"true\");\n }\n if (handle.tabIndex < 0 && !handle.hasAttribute(\"tabindex\")) {\n handle.setAttribute(\"tabindex\", \"0\");\n handle.setAttribute(PointerDragController.#TABINDEX_MARKER, \"true\");\n }\n }\n\n /** Whether the key belongs to a native control or editing surface in the handle. */\n #ownsNativeKeys(target: EventTarget | null, handle: HTMLElement): boolean {\n const owner = (target as Element | null)?.closest(NATIVE_KEY_OWNERS) ?? null;\n return owner !== null && owner !== handle && handle.contains(owner);\n }\n\n /** Reverts the marker-owned touch-action + tabindex (authored values untouched). */\n #restoreHandle(handle: HTMLElement): void {\n if (handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER)) {\n // Only give back what is still ours: a consumer may have written its own\n // value since, and clearing then would lose it. The marker goes either\n // way — the loan is over regardless of who ends up owning the value.\n if (handle.style.touchAction === this.#touchActionForAxis()) {\n handle.style.touchAction = \"\";\n }\n handle.removeAttribute(PointerDragController.#TOUCH_ACTION_MARKER);\n }\n if (handle.hasAttribute(PointerDragController.#TABINDEX_MARKER)) {\n // Only remove what is verifiably still ours and safe to remove: another\n // owner (e.g. a roving list) may have rewritten the value since, and\n // stripping tabindex off the focused element would blur it to <body>\n // (losing the user's place — worse than leaking one tab stop).\n const ours = handle.getAttribute(\"tabindex\") === \"0\";\n if (ours && document.activeElement !== handle) {\n handle.removeAttribute(\"tabindex\");\n handle.removeAttribute(PointerDragController.#TABINDEX_MARKER);\n return;\n }\n // The loan ends when someone else owns the value; it stays recorded when\n // the value is still ours and only the focus stopped us returning it —\n // otherwise an in-page move (teardown + reconnect while focused) drops the\n // record and the borrowed tab stop is never given back.\n if (!ours) handle.removeAttribute(PointerDragController.#TABINDEX_MARKER);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/arrow_step.ts","../../src/utils/detach_gate.ts","../../src/controllers/pointer_drag_controller.ts"],"names":[],"mappings":";;;;;AA+FO,SAAS,oBAAA,CACd,KAAA,EACA,KAAA,GAAkC,EAAC,EAC1B;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A,CAAO,eAAA,CAAgB,uBAAsB,gBAAgB,CAAA;AAC7D,QAAA;AAAA,MACF;AAKA,MAAA,IAAI,CAAC,IAAA,EAAM,MAAA,CAAO,eAAA,CAAgB,uBAAsB,gBAAgB,CAAA;AAAA,IAC1E;AAAA,EACF;AACF","file":"pointer_drag_controller.js","sourcesContent":["import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n\n/**\n * True when a press arrived carrying any modifier, for the keys the browser and\n * the OS own outright: return without calling `preventDefault()` and without\n * moving any state.\n *\n * `Control+Home` and `Control+End` jump the document to its ends, and a widget\n * that swallows them makes the shortcut work or not depending on where focus\n * happens to sit. {@link isReservedArrowChord} answers the same question for the\n * arrows, but returns `false` for every other key so that this one can decide.\n *\n * There is no `allow` list here on purpose. APG assigns no modifier chord to\n * `Home`/`End`, so a widget that wanted one would be claiming a combination the\n * pattern never gave it.\n *\n * @example\n * ```ts\n * case \"Home\":\n * case \"End\":\n * if (hasModifierChord(event)) return;\n * ```\n */\nexport function hasModifierChord(event: KeyboardEvent): boolean {\n return event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;\n}\n","/**\n * Shared \"in-page move vs real detach\" discriminator for `disconnect()`.\n *\n * A mid-session `disconnect()` whose element is still in the document is\n * ambiguous. It can be:\n *\n * - an **in-page move** — a consumer (sortable, a teleport) re-inserted the\n * element; Stimulus reconnects the SAME instance in the same mutation batch\n * and the controller's runtime state must survive;\n * - a **detach that keeps the element** — `data-controller` no longer lists the\n * identifier (a Turbo 8 morph), or the element moved outside the observed\n * root (a scoped `Application.start(root)`, a shadow root); no reconnect will\n * ever come and the controller must tear down or it leaks its sessions,\n * document listeners, and moved nodes.\n *\n * Neither available signal decides this alone. A synchronous `data-controller`\n * token check catches the morph case but misses an observed-root exit (the\n * token stays, the reconnect never comes). Deferring teardown one microtask and\n * letting `connect()` cancel it catches the root exit, but leans on Stimulus\n * reconnecting moved elements within the same mutation batch — internal\n * behavior, not a public contract. {@link DetachGate} composes both: the token\n * check is the synchronous fast path (no probe, no reliance on batching), the\n * microtask probe is the fallback for the genuinely ambiguous remainder.\n *\n * Policy stays with the consumer; this util owns the discrimination only:\n *\n * - **Probe** ({@link disconnected}) when the teardown must eventually happen —\n * live drag sessions, document listeners, teleported *content*. Call\n * {@link cancel} from `connect()` (a reconnect means in-page move) and from\n * the head of any direct teardown path (see below).\n * - **Keep** (bare {@link DetachGate.isDetached}) when undoing the ambiguous\n * case would fight the controller's own effect: a controller that moves its\n * OWN element (portal's no-`content` form) exits a scoped observed root as\n * its normal job — a probe-driven teardown would restore the element into\n * the root, reconnect, re-teleport, and disconnect again, forever. Such\n * controllers keep their state on an ambiguous disconnect and tear down only\n * on {@link DetachGate.isDetached}.\n *\n * Event convention for probe consumers: teardown into a dead (detached) tree is\n * silent — consumers restore from their own `connect()`; a detach that keeps the\n * tree alive must end an in-flight session with a `cancel` event, or composing\n * consumers strand their session bookkeeping.\n */\n\n/** The slice of a Stimulus controller the gate inspects. */\nexport interface DetachGateHost {\n readonly element: Element;\n readonly identifier: string;\n}\n\n/**\n * Per-controller-instance gate deciding whether a `disconnect()` is a real\n * detach. Hold one per controller (`#gate = new DetachGate()`) — Stimulus\n * reuses the instance across reconnects, so the pending probe state carries\n * over exactly as the protocol needs.\n *\n * @example\n * ```ts\n * #gate = new DetachGate();\n *\n * connect(): void {\n * this.#gate.cancel(); // a reconnect: the element moved in-page\n * // …\n * }\n *\n * disconnect(): void {\n * this.#gate.disconnected(this, () => this.#teardown());\n * }\n *\n * #teardown(): void {\n * this.#gate.cancel(); // disarm a still-queued probe (double-run guard)\n * // …\n * }\n * ```\n */\nexport class DetachGate {\n /** Set while a probe is queued, waiting for a reconnect to cancel it. */\n #pending = false;\n\n /**\n * True while a probe is queued — the last disconnect was ambiguous and no\n * reconnect has cancelled it yet. Read it from `connect()` to tell the\n * reconnect half of an in-page move from a first connect: a controller whose\n * initialisation restarts a measurement (a min-duration floor, an elapsed\n * counter) must skip it for the move, where nothing actually restarted.\n */\n get pending(): boolean {\n return this.#pending;\n }\n\n /**\n * True when the disconnect is definitely a real detach — the element left\n * the document, or `data-controller` no longer lists the identifier. False\n * means ambiguous (in-page move or observed-root exit), NOT \"alive\".\n */\n static isDetached(host: DetachGateHost): boolean {\n if (!host.element.isConnected) return true;\n const tokens = (host.element.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n return !tokens.includes(host.identifier);\n }\n\n /**\n * Call from `disconnect()`: runs `teardown` synchronously on a definite\n * detach (fast path), otherwise defers it one microtask — a reconnect\n * ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.\n * One microtask is the whole probe window: Stimulus reconnects a moved\n * element within the same mutation batch, before the checkpoint drains.\n */\n disconnected(host: DetachGateHost, teardown: () => void): void {\n if (DetachGate.isDetached(host)) {\n // Also disarms a probe a previous ambiguous disconnect left queued\n // (defer, element removed, disconnect again) — exactly one teardown.\n this.#pending = false;\n teardown();\n return;\n }\n this.#pending = true;\n queueMicrotask(() => {\n if (!this.#pending) return;\n this.#pending = false;\n teardown();\n });\n }\n\n /**\n * Disarms a pending probe. Call from `connect()` (the reconnect that proves\n * an in-page move) and from the head of any teardown path not routed through\n * {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can\n * never run the teardown a second time.\n */\n cancel(): void {\n this.#pending = false;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord } from \"../utils/arrow_step\";\nimport { DetachGate } from \"../utils/detach_gate\";\n\n/**\n * Elements whose own default action owns a key press. The browser never signals\n * those through `defaultPrevented`, so a yield on that flag cannot see them.\n */\nconst NATIVE_KEY_OWNERS = \"input, textarea, select, button, a[href], summary, [contenteditable]\";\n\n/** How a drag session was initiated; surfaced in every event detail. */\ntype DragPointerType = \"mouse\" | \"touch\" | \"pen\" | \"keyboard\";\n\n/** A pointer drag in flight (from `pointerdown` until up/cancel). */\ninterface PointerSession {\n pointerId: number;\n handle: HTMLElement;\n originX: number;\n originY: number;\n /** True once the movement passed `threshold` and `start` was dispatched. */\n started: boolean;\n /** Last axis-filtered deltas, reported again by `end`. */\n dx: number;\n dy: number;\n pointerType: DragPointerType;\n}\n\n/** A keyboard \"grabbed\" session (Space/Enter on the handle until drop/cancel). */\ninterface KeyboardSession {\n handle: HTMLElement;\n /** Cumulative synthetic deltas accumulated by the arrow keys. */\n dx: number;\n dy: number;\n}\n\n/**\n * Headless **pointer-drag primitive**: a normalized pointer/touch/mouse drag\n * lifecycle with a built-in keyboard alternative. It deliberately does NOT decide\n * what a drag *means* (reorder, dismiss, resize…) — it only emits a clean,\n * accessibility-friendly drag signal that higher-level behaviors compose from —\n * `stimeo--sortable` is one, and reordering, dismissal, and resizing are the usual\n * meanings a consumer layers on. No dedicated APG\n * pattern exists for drag-and-drop; the keyboard model below is the accepted\n * alternative-input technique (WCAG 2.1.1 / 2.5.7 Dragging Movements). Core\n * (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--pointer-drag`):\n * <li data-controller=\"stimeo--pointer-drag\"\n * data-stimeo--pointer-drag-axis-value=\"y\">\n * <button data-stimeo--pointer-drag-target=\"handle\" aria-label=\"Reorder\">⠿</button>\n * </li>\n *\n * The `handle` target is optional — without one, the controller element itself\n * is the handle. Pointer flow: `pointerdown` on a handle arms the drag; once the\n * axis-filtered movement exceeds `threshold`, `start` fires, every subsequent\n * movement fires `move` (deltas cumulative from the origin), and release fires\n * `end` (`pointercancel` → `cancel`). Keyboard flow: Space/Enter on the handle\n * grabs (`start`, `data-grabbed`), the arrow keys emit synthetic `move` events of\n * `keyboardStep` px each, Space/Enter drops (`end`) and Escape cancels — so every\n * consumer gets a keyboard path for free.\n *\n * `start` dispatches `{ x, y, pointerType }`; `move` dispatches `{ dx, dy, x, y, pointerType }`;\n * `end` dispatches `{ dx, dy, pointerType }`; `cancel` dispatches `{ pointerType }`.\n *\n * @remarks\n * Behavior only: consumers own all visuals (ghost, placeholder, transforms) by\n * reacting to the events and the `data-dragging` / `data-grabbed` hooks. The one\n * deliberate exception is the opt-in `follow` value for the \"just move the\n * element\" case: it applies the in-flight deltas to the element's CSS\n * `translate` (a property independent of `transform`, so authored transforms\n * survive), commits the offset on drop and restores it on cancel — the exact\n * boilerplate every simple consumer would otherwise re-write. With `follow` the\n * element's inline `translate` belongs to this controller (`connect()` re-reads\n * a committed `<x>px <y>px` offset, so Turbo restores stay consistent). ARIA 1.1\n * deprecated `aria-grabbed`/`aria-dropeffect`, so the grabbed state is\n * published as `data-grabbed` and the *meaning* of a drag must be announced by\n * the consumer (pair with `stimeo--announcer`). `touch-action` on the handles is\n * derived from `axis` (marker-guarded, authored values win) so the page does not\n * pan mid-drag. Deltas are physical (client coordinates): RTL semantics belong\n * to the consumer. `disconnect()` (Turbo navigation included) tears down any\n * active session — except across an in-page move, which the session survives\n * (the full lifecycle contract lives on `disconnect()`); `connect()` clears\n * stale hooks a Turbo cache restore may have preserved (a drag cannot survive\n * a navigation).\n */\nexport class PointerDragController extends Controller<HTMLElement> {\n static override targets = [\"handle\"];\n static override values = {\n axis: { type: String, default: \"both\" },\n threshold: { type: Number, default: 3 },\n keyboardStep: { type: Number, default: 10 },\n disabled: { type: Boolean, default: false },\n follow: { type: Boolean, default: false },\n };\n static actions = [\"reset\"] as const;\n static events = [\"start\", \"move\", \"end\", \"cancel\"] as const;\n\n declare readonly handleTargets: HTMLElement[];\n declare readonly hasHandleTarget: boolean;\n declare axisValue: string;\n declare thresholdValue: number;\n declare keyboardStepValue: number;\n declare disabledValue: boolean;\n declare followValue: boolean;\n\n /** Marker attribute recording that this controller set the touch-action. */\n static readonly #TOUCH_ACTION_MARKER = \"data-pointer-drag-touch-action\";\n /** Marker attribute recording that this controller set `tabindex`. */\n static readonly #TABINDEX_MARKER = \"data-pointer-drag-tabindex\";\n\n #pointer: PointerSession | null = null;\n #keyboard: KeyboardSession | null = null;\n /** Committed follow offset from past drops; a new drag's deltas add onto it. */\n #followBase = { x: 0, y: 0 };\n /** Aborts in-progress pointer-drag listeners on drag end / teardown. */\n #dragAbort: AbortController | null = null;\n /** Decides whether a mid-session disconnect() is an in-page move or a detach. */\n readonly #gate = new DetachGate();\n\n override connect(): void {\n // A reconnect disarms the probe a mid-session disconnect() armed — the\n // element was moved in-page and the session survives (see disconnect).\n this.#gate.cancel();\n // Transient drag state cannot survive a navigation: clear hooks a Turbo\n // cache restore may have snapshotted mid-drag (idempotent reconnect). But a\n // session preserved across an in-page move keeps its hooks.\n if (!this.#pointer) this.element.removeAttribute(\"data-dragging\");\n if (!this.#keyboard) this.element.removeAttribute(\"data-grabbed\");\n // Follow mode owns the element's inline `translate`: re-read a committed\n // offset so reconnects (Turbo cache restore included) keep accumulating from\n // where the element visually sits. A session surviving an in-page move keeps\n // its base — mid-drag inline state must not be committed as a new base.\n if (this.followValue && !this.#pointer && !this.#keyboard) {\n this.#followBase = this.#parseFollowBase();\n }\n // Delegated on the container so dynamically added handles need no per-element\n // data-action.\n this.element.addEventListener(\"pointerdown\", this.#onPointerDown);\n this.element.addEventListener(\"keydown\", this.#onKeydown);\n if (!this.hasHandleTarget) this.#prepareHandle(this.element);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"pointerdown\", this.#onPointerDown);\n this.element.removeEventListener(\"keydown\", this.#onKeydown);\n // A mid-session disconnect on a STILL-connected element is ambiguous: an\n // in-page move (a consumer like sortable re-inserts the item mid-grab —\n // Stimulus reconnects the same instance in the same mutation batch, and\n // the session must survive) vs a real detach that keeps the element\n // (`data-controller` removed, Turbo morph, element moved outside the\n // observed root). DetachGate discriminates: the token check is the\n // synchronous fast path (a morph's teardown — and its `cancel` — fires in\n // the same tick), the one-microtask probe cancelled by connect() covers\n // the rest — a detached-in-place controller never leaks its session or\n // document listeners. Probe only while a session needs protecting; an\n // idle controller tears down synchronously either way.\n if (this.#pointer || this.#keyboard) {\n this.#gate.disconnected(this, () => this.#teardown());\n return;\n }\n this.#teardown();\n }\n\n /**\n * Returns the element to its origin: drops the committed follow offset and the\n * inline `translate` that carries it.\n *\n * In follow mode the inline `translate` belongs to this controller, and the\n * committed offset lives in a field the DOM cannot reach — so a consumer that\n * wants the element back at the start, or that has written a position of its\n * own, needs this to make the two agree again. An in-flight drag is cancelled\n * first, or its deltas would land on top of the offset just cleared.\n */\n reset(): void {\n // Cancel first, then clear: the cancel contract snaps back to the committed\n // offset, so clearing before it would be undone on the way out.\n const live = this.#pointer?.started\n ? this.#pointer.pointerType\n : this.#keyboard\n ? \"keyboard\"\n : null;\n if (this.#pointer || this.#keyboard) this.#teardownSessions();\n if (live) this.#dispatchCancel(live);\n this.#followBase = { x: 0, y: 0 };\n this.#applyFollow(0, 0);\n }\n\n handleTargetConnected(handle: HTMLElement): void {\n // The element wears the handle contract only while it IS the handle; the\n // first real handle takes it back. (Marker-guarded, so this is a no-op when\n // the element never wore it.)\n if (handle !== this.element) this.#restoreHandle(this.element);\n this.#prepareHandle(handle);\n }\n\n handleTargetDisconnected(handle: HTMLElement): void {\n // The loan is due back the moment an element stops being a handle, and this\n // callback is the only place that sees every such element: once the\n // identifier token is gone, `#handles()` no longer resolves the targets.\n // Across an in-page move `handleTargetConnected` lends it again in the same\n // mutation batch.\n this.#restoreHandle(handle);\n // Target callbacks ALSO fire when the CONTROLLER goes away (Stimulus stops\n // the target observer after `disconnect()` has run) and across the in-page\n // move a live session must survive. In both the handle is still inside the\n // element: the session belongs to `disconnect()`, and handing the contract\n // to the container here would bake a nameless tab stop onto it on every\n // morph. Only a handle that actually LEFT is this callback's business.\n if (this.element.contains(handle)) return;\n\n // It can never deliver its keydown again (the delegated listener sits on the\n // container it left), so a live session would leak and the one-session guard\n // would reject every future pointerdown. The tree and the consumers are both\n // alive here, so it ends the way every other keep-the-element teardown does:\n // in `cancel`, or a composer like sortable strands its session bookkeeping.\n const interrupted =\n this.#pointer?.handle === handle && this.#pointer.started\n ? this.#pointer.pointerType\n : this.#keyboard?.handle === handle\n ? (\"keyboard\" as const)\n : null;\n if (this.#pointer?.handle === handle) this.#endPointerSession();\n if (this.#keyboard?.handle === handle) this.#clearKeyboardSession();\n // With the last handle gone the element is the handle again (`#handles()`),\n // so it needs the contract the departing handle just gave back.\n if (!this.hasHandleTarget) this.#prepareHandle(this.element);\n if (interrupted) this.#dispatchCancel(interrupted);\n }\n\n /**\n * Re-derives the handles' touch-action when the axis changes.\n *\n * Two layers, like the `tabindex` loan: the marker says the value was once\n * ours, and the current inline value says it still is. A consumer that wrote\n * its own `touch-action` after connect keeps it.\n */\n axisValueChanged(_value: string, previousValue: string | undefined): void {\n // The value to recognize as ours is the one the previous axis lent. Stimulus\n // also replays a value that did NOT change (ahead of every connect), and\n // there the axis in force is the one it was lent under.\n const lent = this.#touchActionFor(previousValue ?? this.axisValue);\n for (const handle of this.#handles()) {\n if (!handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER)) continue;\n if (handle.style.touchAction !== lent) continue;\n handle.style.touchAction = this.#touchActionForAxis();\n }\n }\n\n /** Cancels any in-flight session when the controller is disabled mid-drag. */\n disabledValueChanged(): void {\n if (!this.disabledValue) return;\n if (this.#pointer?.started || this.#keyboard) {\n this.#dispatchCancel(this.#keyboard ? \"keyboard\" : (this.#pointer?.pointerType ?? \"mouse\"));\n }\n this.#teardownSessions();\n }\n\n /** Arms a pointer drag on a handle; `start` waits for the threshold. */\n readonly #onPointerDown = (event: PointerEvent): void => {\n // One session at a time: ignore a second pointerdown (multi-touch, an\n // errant tap, a grabbed keyboard session) so an in-flight drag is never\n // silently overwritten and its captured pointer orphaned.\n if (this.disabledValue || this.#pointer || this.#keyboard || event.button !== 0) return;\n const handle = this.#handleFor(event.target);\n if (!handle) return;\n\n // Suppress text selection / native image drag; restore the focus the\n // suppressed default would have given, so Escape and the keyboard path\n // stay reachable right after a pointer interaction (WCAG 2.1.1).\n event.preventDefault();\n handle.focus();\n\n this.#pointer = {\n pointerId: event.pointerId,\n handle,\n originX: event.clientX,\n originY: event.clientY,\n started: false,\n dx: 0,\n dy: 0,\n pointerType: this.#pointerTypeOf(event),\n };\n\n // Pointer capture keeps fast drags delivering to the handle even when the\n // pointer strays outside it — but a consumer may re-insert the dragged\n // element mid-drag (sortable's live reorder), which silently releases the\n // capture. Tracking listeners therefore live on the DOCUMENT (captured\n // events bubble there; uncaptured ones fire there anyway), and the\n // AbortController releases them on drag end and disconnect() (Turbo included).\n handle.setPointerCapture(event.pointerId);\n this.#dragAbort?.abort();\n const abort = new AbortController();\n this.#dragAbort = abort;\n document.addEventListener(\"pointermove\", this.#onPointerMove, { signal: abort.signal });\n document.addEventListener(\"pointerup\", this.#onPointerUp, { signal: abort.signal });\n document.addEventListener(\"pointercancel\", this.#onPointerCancel, { signal: abort.signal });\n };\n\n readonly #onPointerMove = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n\n const [dx, dy] = this.#filterAxis(\n event.clientX - session.originX,\n event.clientY - session.originY,\n );\n if (!session.started) {\n if (Math.hypot(dx, dy) < this.thresholdValue) return;\n session.started = true;\n this.element.setAttribute(\"data-dragging\", \"true\");\n this.dispatch(\"start\", {\n detail: { x: event.clientX, y: event.clientY, pointerType: session.pointerType },\n });\n }\n\n session.dx = dx;\n session.dy = dy;\n this.#followMove(dx, dy);\n this.dispatch(\"move\", {\n detail: { dx, dy, x: event.clientX, y: event.clientY, pointerType: session.pointerType },\n });\n };\n\n readonly #onPointerUp = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n const { started, dx, dy, pointerType } = session;\n this.#endPointerSession();\n // Below the threshold the gesture was a plain click, not a drag: stay silent.\n if (!started) return;\n this.#followCommit(dx, dy);\n this.dispatch(\"end\", { detail: { dx, dy, pointerType } });\n };\n\n /** OS gesture / scroll takeover interrupted the drag: cancel, don't drop. */\n readonly #onPointerCancel = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n const { started, pointerType } = session;\n this.#endPointerSession();\n if (started) this.#dispatchCancel(pointerType);\n };\n\n /** Keyboard alternative: Space/Enter grab & drop, arrows move, Escape cancels. */\n readonly #onKeydown = (event: KeyboardEvent): void => {\n if (this.disabledValue) return;\n const handle = this.#handleFor(event.target);\n if (!handle) return;\n\n // A descendant widget that already claimed the key (a nested roving list, a\n // segmented field inside the handle) must not ALSO drive the drag —\n // composition depends on this yield.\n if (event.defaultPrevented) return;\n // A press that steers an IME conversion belongs to the composition, and an\n // input method never says so through `defaultPrevented`.\n if (event.isComposing) return;\n // Neither does a native control or editing surface inside the handle: typing\n // a space into a field and activating a link are default actions, not claims.\n // Widgets that do claim their keys keep composing through the yield above.\n if (this.#ownsNativeKeys(event.target, handle)) return;\n // A chorded arrow belongs to the browser. \"Someone already consumed it\"\n // outranks that, so it is checked after the yields above.\n if (isReservedArrowChord(event)) return;\n\n // Escape cancels whichever session is live (pointer drag or keyboard grab).\n if (event.key === \"Escape\") {\n if (this.#pointer?.started) {\n const { pointerType } = this.#pointer;\n this.#teardownSessions();\n event.preventDefault();\n this.#dispatchCancel(pointerType);\n } else if (this.#keyboard) {\n this.#teardownSessions();\n event.preventDefault();\n this.#dispatchCancel(\"keyboard\");\n }\n return;\n }\n\n if (event.key === \" \" || event.key === \"Enter\") {\n // A live pointer drag owns the session: pressing Space mid-drag (the\n // pointerdown focused the handle) must not start a parallel grab.\n if (this.#pointer) return;\n event.preventDefault();\n if (this.#keyboard) this.#dropKeyboard();\n else this.#grabKeyboard(handle);\n return;\n }\n\n if (!this.#keyboard) return;\n // While grabbed, the handle owns the keyboard. `Home` / `End` move nothing\n // here, but a composition partner acts on them (a roving group jumps focus\n // to the ends), and focus leaving the handle strands the grab: the arrows\n // and Escape that end it are all delivered to whatever holds focus. So they\n // are consumed here and do nothing, the same reason every arrow is consumed.\n if (event.key === \"Home\" || event.key === \"End\") {\n event.preventDefault();\n return;\n }\n const step = this.#keyboardDelta(event.key);\n if (!step) return;\n // Consume every arrow while grabbed (even on a locked axis) so the page\n // never scrolls mid-grab; only allowed-axis arrows emit a move.\n event.preventDefault();\n const [dx, dy] = this.#filterAxis(step[0], step[1]);\n if (dx === 0 && dy === 0) return;\n this.#keyboard.dx += dx;\n this.#keyboard.dy += dy;\n this.#followMove(this.#keyboard.dx, this.#keyboard.dy);\n this.dispatch(\"move\", {\n detail: {\n dx: this.#keyboard.dx,\n dy: this.#keyboard.dy,\n x: this.#keyboard.dx,\n y: this.#keyboard.dy,\n pointerType: \"keyboard\",\n },\n });\n };\n\n /** Enters the grabbed mode: `data-grabbed` on element + handle, then `start`. */\n #grabKeyboard(handle: HTMLElement): void {\n this.#keyboard = { handle, dx: 0, dy: 0 };\n this.element.setAttribute(\"data-grabbed\", \"true\");\n handle.setAttribute(\"data-grabbed\", \"true\");\n this.dispatch(\"start\", { detail: { x: 0, y: 0, pointerType: \"keyboard\" } });\n }\n\n #dropKeyboard(): void {\n const session = this.#keyboard;\n if (!session) return;\n this.#clearKeyboardSession();\n this.#followCommit(session.dx, session.dy);\n this.dispatch(\"end\", { detail: { dx: session.dx, dy: session.dy, pointerType: \"keyboard\" } });\n }\n\n /** Maps an arrow key to a raw (unfiltered) `keyboardStep` delta. */\n #keyboardDelta(key: string): [number, number] | null {\n const step = this.keyboardStepValue;\n switch (key) {\n case \"ArrowRight\":\n return [step, 0];\n case \"ArrowLeft\":\n return [-step, 0];\n case \"ArrowDown\":\n return [0, step];\n case \"ArrowUp\":\n return [0, -step];\n default:\n return null;\n }\n }\n\n /** Zeroes the delta on the locked axis (`axis` = x | y | both). */\n #filterAxis(dx: number, dy: number): [number, number] {\n if (this.axisValue === \"x\") return [dx, 0];\n if (this.axisValue === \"y\") return [0, dy];\n return [dx, dy];\n }\n\n /** Releases capture + listeners and clears the pointer session and its hook. */\n #endPointerSession(): void {\n this.#releasePointerCapture();\n this.#pointer = null;\n this.#dragAbort?.abort();\n this.#dragAbort = null;\n this.element.removeAttribute(\"data-dragging\");\n }\n\n /** Releases the pointer capture the active session set (idempotent, safe). */\n #releasePointerCapture(): void {\n const session = this.#pointer;\n if (session?.handle.hasPointerCapture(session.pointerId)) {\n session.handle.releasePointerCapture(session.pointerId);\n }\n }\n\n #clearKeyboardSession(): void {\n this.#keyboard?.handle.removeAttribute(\"data-grabbed\");\n this.#keyboard = null;\n this.element.removeAttribute(\"data-grabbed\");\n }\n\n /**\n * Full teardown for a controller whose element is going away or lost its\n * controller. Into a dead (detached) tree it is silent — consumers restore\n * from their own `connect()`, not from a cancel event. But a detach that\n * KEEPS the element (Turbo morph, `data-controller` removed) leaves the\n * consumers alive and listening: an in-flight session must end in `cancel`\n * there, or a composer like sortable strands its one-at-a-time session\n * bookkeeping forever.\n */\n #teardown(): void {\n // Disarm any probe still queued: without this, an immediate teardown\n // (element removed right after a deferring disconnect) would let the\n // orphaned probe run #teardown a second time — a double cancel.\n this.#gate.cancel();\n const interrupted = this.#pointer?.started\n ? this.#pointer.pointerType\n : this.#keyboard\n ? (\"keyboard\" as const)\n : null;\n this.#teardownSessions();\n for (const handle of this.#handles()) this.#restoreHandle(handle);\n // An in-flight offset must leave the DOM even where nobody is listening: a\n // re-inserted element would have `connect()` read it back as a committed base.\n this.#followReset();\n if (interrupted && this.element.isConnected) this.#dispatchCancel(interrupted);\n }\n\n /**\n * Silently tears down whatever session is live (disconnect / disabled /\n * Escape). Composed from the two single-session teardowns so pointer and\n * keyboard cleanup cannot diverge as either path evolves.\n */\n #teardownSessions(): void {\n this.#endPointerSession();\n this.#clearKeyboardSession();\n }\n\n #dispatchCancel(pointerType: DragPointerType): void {\n // Every cancel path funnels here, so follow's snap-back can never be missed\n // (Escape, pointercancel, mid-session disable, detach-that-keeps-the-element).\n this.#followReset();\n this.dispatch(\"cancel\", { detail: { pointerType } });\n }\n\n /** Applies the in-flight offset to the element's `translate` (follow only). */\n #followMove(dx: number, dy: number): void {\n if (!this.followValue) return;\n this.#applyFollow(this.#followBase.x + dx, this.#followBase.y + dy);\n }\n\n /** Folds a drop's deltas into the committed base offset (follow only). */\n #followCommit(dx: number, dy: number): void {\n if (!this.followValue) return;\n this.#followBase = { x: this.#followBase.x + dx, y: this.#followBase.y + dy };\n this.#applyFollow(this.#followBase.x, this.#followBase.y);\n }\n\n /** Snaps back to the committed position (follow only) — the cancel contract. */\n #followReset(): void {\n if (!this.followValue) return;\n this.#applyFollow(this.#followBase.x, this.#followBase.y);\n }\n\n /**\n * Writes the offset as the standalone CSS `translate` property — independent\n * of `transform`, so an authored transform (scale, rotate…) is never\n * clobbered. At the origin the property is removed to keep the DOM clean.\n */\n #applyFollow(x: number, y: number): void {\n if (x === 0 && y === 0) this.element.style.removeProperty(\"translate\");\n else this.element.style.setProperty(\"translate\", `${x}px ${y}px`);\n }\n\n /**\n * Reads a committed follow offset back from the inline `translate`. Only the\n * controller's own `<x>px <y>px` shape is recognized; anything else (an\n * authored percentage, `none`, an empty string) starts the base at 0 — follow\n * mode owns this property, per the class contract.\n */\n #parseFollowBase(): { x: number; y: number } {\n const raw = this.element.style.getPropertyValue(\"translate\").trim();\n const match = /^(-?\\d+(?:\\.\\d+)?)px(?:\\s+(-?\\d+(?:\\.\\d+)?)px)?$/.exec(raw);\n if (!match) return { x: 0, y: 0 };\n return { x: Number(match[1]), y: Number(match[2] ?? \"0\") };\n }\n\n /** The active handles: the `handle` targets, else the element itself. */\n #handles(): HTMLElement[] {\n return this.hasHandleTarget ? this.handleTargets : [this.element];\n }\n\n /** Resolves the handle owning an event target (the handle or a descendant). */\n #handleFor(target: EventTarget | null): HTMLElement | null {\n const node = target as Node | null;\n if (!node) return null;\n return this.#handles().find((handle) => handle === node || handle.contains(node)) ?? null;\n }\n\n #pointerTypeOf(event: PointerEvent): DragPointerType {\n const type = event.pointerType;\n if (type === \"touch\" || type === \"pen\") return type;\n return \"mouse\";\n }\n\n /** `touch-action` that lets the page keep panning on the locked axis only. */\n #touchActionForAxis(): string {\n return this.#touchActionFor(this.axisValue);\n }\n\n /** The `touch-action` an `axis` declaration lends, for any axis value. */\n #touchActionFor(axis: string): string {\n if (axis === \"x\") return \"pan-y\";\n if (axis === \"y\") return \"pan-x\";\n return \"none\";\n }\n\n /**\n * Establishes the handle contract: a `touch-action` derived from `axis`\n * (marker-guarded so an authored inline value wins and reconnects stay\n * idempotent) and focusability for the keyboard path (`tabindex=\"0\"` only when\n * the author supplied none — prefer a real `<button>` handle). Both additions\n * are marker-owned so `#restoreHandle` reverts them symmetrically on teardown.\n */\n #prepareHandle(handle: HTMLElement): void {\n const lent = this.#touchActionForAxis();\n // Two layers, as when the loan is returned: a free property is ours to take,\n // and a marked one is still ours only while it reads back as what was lent.\n // A consumer that wrote its own value keeps it across every reconnect.\n const marked = handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER);\n if (handle.style.touchAction === \"\" || (marked && handle.style.touchAction === lent)) {\n handle.style.touchAction = lent;\n handle.setAttribute(PointerDragController.#TOUCH_ACTION_MARKER, \"true\");\n }\n if (handle.tabIndex < 0 && !handle.hasAttribute(\"tabindex\")) {\n handle.setAttribute(\"tabindex\", \"0\");\n handle.setAttribute(PointerDragController.#TABINDEX_MARKER, \"true\");\n }\n }\n\n /** Whether the key belongs to a native control or editing surface in the handle. */\n #ownsNativeKeys(target: EventTarget | null, handle: HTMLElement): boolean {\n const owner = (target as Element | null)?.closest(NATIVE_KEY_OWNERS) ?? null;\n return owner !== null && owner !== handle && handle.contains(owner);\n }\n\n /** Reverts the marker-owned touch-action + tabindex (authored values untouched). */\n #restoreHandle(handle: HTMLElement): void {\n if (handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER)) {\n // Only give back what is still ours: a consumer may have written its own\n // value since, and clearing then would lose it. The marker goes either\n // way — the loan is over regardless of who ends up owning the value.\n if (handle.style.touchAction === this.#touchActionForAxis()) {\n handle.style.touchAction = \"\";\n }\n handle.removeAttribute(PointerDragController.#TOUCH_ACTION_MARKER);\n }\n if (handle.hasAttribute(PointerDragController.#TABINDEX_MARKER)) {\n // Only remove what is verifiably still ours and safe to remove: another\n // owner (e.g. a roving list) may have rewritten the value since, and\n // stripping tabindex off the focused element would blur it to <body>\n // (losing the user's place — worse than leaking one tab stop).\n const ours = handle.getAttribute(\"tabindex\") === \"0\";\n if (ours && document.activeElement !== handle) {\n handle.removeAttribute(\"tabindex\");\n handle.removeAttribute(PointerDragController.#TABINDEX_MARKER);\n return;\n }\n // The loan ends when someone else owns the value; it stays recorded when\n // the value is still ours and only the focus stopped us returning it —\n // otherwise an in-page move (teardown + reconnect while focused) drops the\n // record and the borrowed tab stop is never given back.\n if (!ours) handle.removeAttribute(PointerDragController.#TABINDEX_MARKER);\n }\n }\n}\n"]}
|
|
@@ -16,13 +16,20 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
16
16
|
*
|
|
17
17
|
* Progress is `0` before the article's top reaches the viewport top and `1`
|
|
18
18
|
* once its bottom fits the viewport: `-top / (height - viewportHeight)`,
|
|
19
|
-
* clamped.
|
|
19
|
+
* clamped. An article no taller than the viewport has no such span, so reading
|
|
20
|
+
* it is binary: `1` from the moment its top reaches the viewport top. An
|
|
21
|
+
* article with no layout box at all — a `display: none` ancestor, a collapsed
|
|
22
|
+
* `<details>`, an inactive tab panel — is not measured: an empty rect sits at
|
|
23
|
+
* the document origin and carries no reading position, so publishing anything
|
|
24
|
+
* for it would report a place the reader never reached.
|
|
25
|
+
*
|
|
26
|
+
* The property is written on the controller element **and** on
|
|
20
27
|
* `document.documentElement`, so a fixed bar anywhere in the page can consume
|
|
21
|
-
* it without being a descendant.
|
|
22
|
-
*
|
|
23
|
-
* `complete` fires on *reaching* 1
|
|
24
|
-
*
|
|
25
|
-
*
|
|
28
|
+
* it without being a descendant. Both are written through a lease, so an
|
|
29
|
+
* authored declaration comes back on teardown and a later writer is left alone.
|
|
30
|
+
* `complete` fires on *reaching* 1, and never during the baseline: the frame in
|
|
31
|
+
* which the controller connects belongs to establishing where the reader
|
|
32
|
+
* already is (a restored scroll position lands there), not to reading.
|
|
26
33
|
*
|
|
27
34
|
* `change` dispatches `{ progress }`.
|
|
28
35
|
*
|
|
@@ -30,9 +37,11 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
30
37
|
* Behavior only — the bar itself (and hiding it, e.g. before any scroll) is
|
|
31
38
|
* the consumer's CSS; the progress value carries no ARIA (a decorative
|
|
32
39
|
* indicator — mark the bar `aria-hidden`; a *semantic* progress belongs to
|
|
33
|
-
* `stimeo--progress`).
|
|
34
|
-
*
|
|
35
|
-
*
|
|
40
|
+
* `stimeo--progress`). The article's own box is watched as well as the
|
|
41
|
+
* viewport, so content that settles late (images, fonts) re-measures instead of
|
|
42
|
+
* leaving a stale span. Scroll and layout work is rAF-throttled; the listeners,
|
|
43
|
+
* the observers, any pending frame and both leased declarations are released on
|
|
44
|
+
* `disconnect()` and returned again for a `turbo:before-cache` snapshot.
|
|
36
45
|
*/
|
|
37
46
|
declare class ReadingProgressController extends Controller<HTMLElement> {
|
|
38
47
|
#private;
|