stimeo-ui 0.12.0 → 0.13.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 +37 -0
- package/dist/cable/index.d.ts +67 -13
- package/dist/cable/index.js +438 -152
- package/dist/cable/index.js.map +1 -1
- package/dist/controllers/alert_dialog_controller.d.ts +1 -1
- package/dist/controllers/alert_dialog_controller.js.map +1 -1
- package/dist/controllers/announcer_controller.d.ts +1 -1
- package/dist/controllers/announcer_controller.js.map +1 -1
- package/dist/controllers/auto_submit_controller.js.map +1 -1
- package/dist/controllers/breadcrumb_controller.d.ts +1 -1
- package/dist/controllers/breadcrumb_controller.js.map +1 -1
- package/dist/controllers/calendar_controller.d.ts +2 -1
- package/dist/controllers/calendar_controller.js +10 -2
- package/dist/controllers/calendar_controller.js.map +1 -1
- package/dist/controllers/carousel_controller.js +1 -1
- package/dist/controllers/carousel_controller.js.map +1 -1
- package/dist/controllers/character_counter_controller.js.map +1 -1
- package/dist/controllers/clipboard_controller.d.ts +1 -1
- package/dist/controllers/clipboard_controller.js.map +1 -1
- package/dist/controllers/collapsible_controller.js.map +1 -1
- package/dist/controllers/color_picker_controller.d.ts +1 -1
- package/dist/controllers/color_picker_controller.js.map +1 -1
- package/dist/controllers/command_palette_controller.d.ts +3 -3
- package/dist/controllers/command_palette_controller.js +2 -2
- package/dist/controllers/command_palette_controller.js.map +1 -1
- package/dist/controllers/conditional_fields_controller.js.map +1 -1
- package/dist/controllers/confirm_controller.d.ts +2 -2
- package/dist/controllers/confirm_controller.js.map +1 -1
- package/dist/controllers/context_menu_controller.d.ts +1 -1
- package/dist/controllers/context_menu_controller.js.map +1 -1
- package/dist/controllers/countdown_controller.d.ts +1 -1
- package/dist/controllers/countdown_controller.js.map +1 -1
- package/dist/controllers/data_grid_controller.d.ts +1 -1
- package/dist/controllers/data_grid_controller.js.map +1 -1
- package/dist/controllers/date_range_picker_controller.js +10 -10
- package/dist/controllers/date_range_picker_controller.js.map +1 -1
- package/dist/controllers/dialog_controller.d.ts +1 -1
- package/dist/controllers/dialog_controller.js.map +1 -1
- package/dist/controllers/direct_upload_controller.js.map +1 -1
- package/dist/controllers/dirty_form_controller.js.map +1 -1
- package/dist/controllers/dismissible_controller.js.map +1 -1
- package/dist/controllers/drawer_controller.d.ts +2 -2
- package/dist/controllers/drawer_controller.js +2 -2
- package/dist/controllers/drawer_controller.js.map +1 -1
- package/dist/controllers/dropdown_controller.d.ts +1 -1
- package/dist/controllers/dropdown_controller.js.map +1 -1
- package/dist/controllers/file_dropzone_controller.js.map +1 -1
- package/dist/controllers/flash_controller.js.map +1 -1
- package/dist/controllers/focus_controller.d.ts +2 -2
- package/dist/controllers/focus_controller.js.map +1 -1
- package/dist/controllers/form_validation_controller.js.map +1 -1
- package/dist/controllers/frame_loading_controller.d.ts +3 -3
- package/dist/controllers/frame_loading_controller.js.map +1 -1
- package/dist/controllers/highlight_controller.js.map +1 -1
- package/dist/controllers/hover_card_controller.d.ts +1 -1
- package/dist/controllers/hover_card_controller.js.map +1 -1
- package/dist/controllers/idle_controller.d.ts +1 -1
- package/dist/controllers/idle_controller.js.map +1 -1
- package/dist/controllers/input_mask_controller.js.map +1 -1
- package/dist/controllers/intersection_controller.js.map +1 -1
- package/dist/controllers/lazy_frame_controller.js.map +1 -1
- package/dist/controllers/listbox_controller.js.map +1 -1
- package/dist/controllers/local_time_controller.d.ts +1 -1
- package/dist/controllers/local_time_controller.js.map +1 -1
- package/dist/controllers/masonry_controller.d.ts +1 -1
- package/dist/controllers/masonry_controller.js.map +1 -1
- package/dist/controllers/menu_controller.d.ts +1 -1
- package/dist/controllers/menu_controller.js.map +1 -1
- package/dist/controllers/menubar_controller.d.ts +2 -2
- package/dist/controllers/menubar_controller.js.map +1 -1
- package/dist/controllers/navigation_menu_controller.d.ts +1 -1
- package/dist/controllers/navigation_menu_controller.js.map +1 -1
- package/dist/controllers/nested_form_controller.js.map +1 -1
- package/dist/controllers/network_status_controller.js.map +1 -1
- package/dist/controllers/number_input_controller.js.map +1 -1
- package/dist/controllers/optimistic_controller.d.ts +23 -10
- package/dist/controllers/optimistic_controller.js +141 -20
- package/dist/controllers/optimistic_controller.js.map +1 -1
- package/dist/controllers/overflow_indicator_controller.d.ts +1 -1
- package/dist/controllers/overflow_indicator_controller.js.map +1 -1
- package/dist/controllers/overflow_menu_controller.js.map +1 -1
- package/dist/controllers/pagination_controller.js.map +1 -1
- package/dist/controllers/password_reveal_controller.js.map +1 -1
- package/dist/controllers/password_strength_controller.d.ts +2 -1
- package/dist/controllers/password_strength_controller.js.map +1 -1
- package/dist/controllers/persist_controller.js.map +1 -1
- package/dist/controllers/popover_controller.d.ts +1 -1
- package/dist/controllers/popover_controller.js.map +1 -1
- package/dist/controllers/portal_controller.d.ts +2 -2
- package/dist/controllers/portal_controller.js.map +1 -1
- package/dist/controllers/radio_group_controller.d.ts +1 -1
- package/dist/controllers/radio_group_controller.js.map +1 -1
- package/dist/controllers/relative_time_controller.d.ts +3 -3
- package/dist/controllers/relative_time_controller.js.map +1 -1
- package/dist/controllers/roving_controller.d.ts +1 -1
- package/dist/controllers/roving_controller.js.map +1 -1
- package/dist/controllers/scroll_area_controller.js.map +1 -1
- package/dist/controllers/scrollspy_controller.js.map +1 -1
- package/dist/controllers/sidebar_controller.d.ts +1 -1
- package/dist/controllers/sidebar_controller.js.map +1 -1
- package/dist/controllers/skeleton_controller.d.ts +2 -2
- package/dist/controllers/skeleton_controller.js.map +1 -1
- package/dist/controllers/spinner_controller.d.ts +3 -3
- package/dist/controllers/spinner_controller.js.map +1 -1
- package/dist/controllers/sticky_observer_controller.js.map +1 -1
- package/dist/controllers/submit_once_controller.d.ts +3 -3
- package/dist/controllers/submit_once_controller.js.map +1 -1
- package/dist/controllers/switch_controller.js.map +1 -1
- package/dist/controllers/textarea_autosize_controller.d.ts +1 -1
- package/dist/controllers/textarea_autosize_controller.js.map +1 -1
- package/dist/controllers/theme_controller.d.ts +3 -2
- package/dist/controllers/theme_controller.js.map +1 -1
- package/dist/controllers/toast_controller.js +1 -1
- package/dist/controllers/toast_controller.js.map +1 -1
- package/dist/controllers/toggle_group_controller.js.map +1 -1
- package/dist/controllers/toolbar_controller.d.ts +1 -1
- package/dist/controllers/toolbar_controller.js.map +1 -1
- package/dist/controllers/tooltip_controller.d.ts +1 -1
- package/dist/controllers/tooltip_controller.js.map +1 -1
- package/dist/controllers/transition_controller.d.ts +1 -1
- package/dist/controllers/transition_controller.js.map +1 -1
- package/dist/controllers/tree_view_controller.d.ts +4 -3
- package/dist/controllers/tree_view_controller.js.map +1 -1
- package/dist/index.js +101 -38
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.d.ts +1 -1
- package/dist/inspector/cli.js +1 -1
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js +1 -1
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +1 -1
- package/dist/inspector/manifest.json +6 -3
- package/package.json +1 -1
|
@@ -1,32 +1,115 @@
|
|
|
1
1
|
import { Controller } from '@hotwired/stimulus';
|
|
2
2
|
|
|
3
3
|
// src/controllers/optimistic_controller.ts
|
|
4
|
-
|
|
4
|
+
|
|
5
|
+
// src/utils/detach_gate.ts
|
|
6
|
+
var DetachGate = class _DetachGate {
|
|
7
|
+
/** Set while a probe is queued, waiting for a reconnect to cancel it. */
|
|
8
|
+
#pending = false;
|
|
9
|
+
/**
|
|
10
|
+
* True while a probe is queued — the last disconnect was ambiguous and no
|
|
11
|
+
* reconnect has cancelled it yet. Read it from `connect()` to tell the
|
|
12
|
+
* reconnect half of an in-page move from a first connect: a controller whose
|
|
13
|
+
* initialisation restarts a measurement (a min-duration floor, an elapsed
|
|
14
|
+
* counter) must skip it for the move, where nothing actually restarted.
|
|
15
|
+
*/
|
|
16
|
+
get pending() {
|
|
17
|
+
return this.#pending;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* True when the disconnect is definitely a real detach — the element left
|
|
21
|
+
* the document, or `data-controller` no longer lists the identifier. False
|
|
22
|
+
* means ambiguous (in-page move or observed-root exit), NOT "alive".
|
|
23
|
+
*/
|
|
24
|
+
static isDetached(host) {
|
|
25
|
+
if (!host.element.isConnected) return true;
|
|
26
|
+
const tokens = (host.element.getAttribute("data-controller") ?? "").split(/\s+/);
|
|
27
|
+
return !tokens.includes(host.identifier);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Call from `disconnect()`: runs `teardown` synchronously on a definite
|
|
31
|
+
* detach (fast path), otherwise defers it one microtask — a reconnect
|
|
32
|
+
* ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.
|
|
33
|
+
* One microtask is the whole probe window: Stimulus reconnects a moved
|
|
34
|
+
* element within the same mutation batch, before the checkpoint drains.
|
|
35
|
+
*/
|
|
36
|
+
disconnected(host, teardown) {
|
|
37
|
+
if (_DetachGate.isDetached(host)) {
|
|
38
|
+
this.#pending = false;
|
|
39
|
+
teardown();
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
this.#pending = true;
|
|
43
|
+
queueMicrotask(() => {
|
|
44
|
+
if (!this.#pending) return;
|
|
45
|
+
this.#pending = false;
|
|
46
|
+
teardown();
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Disarms a pending probe. Call from `connect()` (the reconnect that proves
|
|
51
|
+
* an in-page move) and from the head of any teardown path not routed through
|
|
52
|
+
* {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can
|
|
53
|
+
* never run the teardown a second time.
|
|
54
|
+
*/
|
|
55
|
+
cancel() {
|
|
56
|
+
this.#pending = false;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// src/controllers/optimistic_controller.ts
|
|
61
|
+
var HIDDEN_MARKER = "data-optimistic-toggled";
|
|
62
|
+
var BUSY_MARKER = "data-optimistic-busy";
|
|
63
|
+
var AUTHORED_ABSENT = "absent";
|
|
64
|
+
var AUTHORED_VALUE = "value:";
|
|
65
|
+
var SYNTHETIC_SUBMISSION = {};
|
|
66
|
+
function submissionOf(event) {
|
|
67
|
+
const detail = event.detail;
|
|
68
|
+
return detail?.formSubmission ?? SYNTHETIC_SUBMISSION;
|
|
69
|
+
}
|
|
5
70
|
var OptimisticController = class extends Controller {
|
|
6
71
|
static targets = ["show", "hide"];
|
|
7
72
|
static events = ["commit", "rollback"];
|
|
73
|
+
/** The submission that owns the applied optimistic state, if any. */
|
|
74
|
+
#pending = null;
|
|
75
|
+
#gate = new DetachGate();
|
|
76
|
+
/** True between `connect()` and `disconnect()`, so a repeat connect rewinds nothing. */
|
|
77
|
+
#connected = false;
|
|
8
78
|
connect() {
|
|
9
|
-
|
|
79
|
+
const restored = !this.#connected && !this.#gate.pending;
|
|
80
|
+
this.#gate.cancel();
|
|
81
|
+
this.#connected = true;
|
|
82
|
+
if (restored && this.element.hasAttribute("data-optimistic")) this.#revert();
|
|
10
83
|
this.element.addEventListener("turbo:submit-start", this.#onSubmitStart);
|
|
11
84
|
this.element.addEventListener("turbo:submit-end", this.#onSubmitEnd);
|
|
12
85
|
}
|
|
13
86
|
disconnect() {
|
|
87
|
+
this.#connected = false;
|
|
14
88
|
this.element.removeEventListener("turbo:submit-start", this.#onSubmitStart);
|
|
15
89
|
this.element.removeEventListener("turbo:submit-end", this.#onSubmitEnd);
|
|
90
|
+
this.#gate.disconnected(this, () => {
|
|
91
|
+
this.#pending = null;
|
|
92
|
+
});
|
|
16
93
|
}
|
|
17
|
-
#onSubmitStart = () => {
|
|
94
|
+
#onSubmitStart = (event) => {
|
|
95
|
+
this.#pending = submissionOf(event);
|
|
96
|
+
if (this.element instanceof HTMLFormElement && !this.element.hasAttribute(BUSY_MARKER)) {
|
|
97
|
+
this.element.setAttribute(BUSY_MARKER, AUTHORED_ABSENT);
|
|
98
|
+
}
|
|
99
|
+
this.#write(this.element, "aria-busy", "true", BUSY_MARKER);
|
|
18
100
|
this.element.setAttribute("data-optimistic", "true");
|
|
19
|
-
this.
|
|
20
|
-
for (const target of this.
|
|
21
|
-
for (const target of this.hideTargets) this.#toggleHidden(target, true);
|
|
101
|
+
for (const target of this.showTargets) this.#setHidden(target, false);
|
|
102
|
+
for (const target of this.hideTargets) this.#setHidden(target, true);
|
|
22
103
|
};
|
|
23
104
|
#onSubmitEnd = (event) => {
|
|
105
|
+
if (submissionOf(event) !== this.#pending) return;
|
|
106
|
+
this.#pending = null;
|
|
24
107
|
const success = event.detail?.success === true;
|
|
25
|
-
this.element.removeAttribute("aria-busy");
|
|
26
108
|
if (success) {
|
|
27
109
|
this.element.removeAttribute("data-optimistic");
|
|
110
|
+
this.#restore(this.element, "aria-busy", BUSY_MARKER, "true");
|
|
28
111
|
for (const target of [...this.showTargets, ...this.hideTargets]) {
|
|
29
|
-
target.removeAttribute(
|
|
112
|
+
target.removeAttribute(HIDDEN_MARKER);
|
|
30
113
|
}
|
|
31
114
|
this.dispatch("commit");
|
|
32
115
|
} else {
|
|
@@ -34,21 +117,59 @@ var OptimisticController = class extends Controller {
|
|
|
34
117
|
this.dispatch("rollback");
|
|
35
118
|
}
|
|
36
119
|
};
|
|
37
|
-
/**
|
|
38
|
-
#
|
|
39
|
-
if (target.hidden === hidden) return;
|
|
40
|
-
target
|
|
41
|
-
|
|
120
|
+
/** Hides or reveals a target, recording the authored `hidden` on first write. */
|
|
121
|
+
#setHidden(target, hidden) {
|
|
122
|
+
if (target.hasAttribute("hidden") === hidden) return;
|
|
123
|
+
this.#write(target, "hidden", hidden ? "" : null, HIDDEN_MARKER);
|
|
124
|
+
}
|
|
125
|
+
/** Writes an attribute, recording what it displaced under `marker` once. */
|
|
126
|
+
#write(element, attribute, value, marker) {
|
|
127
|
+
if (!element.hasAttribute(marker)) {
|
|
128
|
+
const authored = element.getAttribute(attribute);
|
|
129
|
+
element.setAttribute(
|
|
130
|
+
marker,
|
|
131
|
+
authored === null ? AUTHORED_ABSENT : `${AUTHORED_VALUE}${authored}`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
if (value === null) element.removeAttribute(attribute);
|
|
135
|
+
else element.setAttribute(attribute, value);
|
|
42
136
|
}
|
|
43
|
-
/**
|
|
137
|
+
/**
|
|
138
|
+
* Puts back the value `marker` recorded and drops the record.
|
|
139
|
+
*
|
|
140
|
+
* `written` is what this controller last put in the attribute. Anything else
|
|
141
|
+
* there now belongs to whoever wrote it — Turbo owns `aria-busy` on a form and
|
|
142
|
+
* clears it before the terminal arrives, and a consumer may have moved a face
|
|
143
|
+
* mid-flight — so the record is dropped without touching the attribute. A
|
|
144
|
+
* marker this build did not write names no authored value, so the attribute
|
|
145
|
+
* goes back to being absent.
|
|
146
|
+
*/
|
|
147
|
+
#restore(element, attribute, marker, written) {
|
|
148
|
+
const recorded = element.getAttribute(marker);
|
|
149
|
+
if (recorded === null) return;
|
|
150
|
+
element.removeAttribute(marker);
|
|
151
|
+
if (element.getAttribute(attribute) !== written) return;
|
|
152
|
+
if (recorded.startsWith(AUTHORED_VALUE)) {
|
|
153
|
+
element.setAttribute(attribute, recorded.slice(AUTHORED_VALUE.length));
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
element.removeAttribute(attribute);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Puts back exactly the markup this controller displaced (record-owned only).
|
|
160
|
+
*
|
|
161
|
+
* A face can be registered on both sides, and the hide pass runs last, so what
|
|
162
|
+
* this controller wrote there is `hidden` — matching it against the reveal's
|
|
163
|
+
* absent value instead would read as someone else's write and leave the face
|
|
164
|
+
* hidden. Each target is therefore restored once, against the write it last
|
|
165
|
+
* received.
|
|
166
|
+
*/
|
|
44
167
|
#revert() {
|
|
45
168
|
this.element.removeAttribute("data-optimistic");
|
|
46
|
-
this.element
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
target.removeAttribute(TOGGLED_MARKER);
|
|
51
|
-
}
|
|
169
|
+
this.#restore(this.element, "aria-busy", BUSY_MARKER, "true");
|
|
170
|
+
const hidden = new Set(this.hideTargets);
|
|
171
|
+
for (const target of /* @__PURE__ */ new Set([...this.showTargets, ...this.hideTargets])) {
|
|
172
|
+
this.#restore(target, "hidden", HIDDEN_MARKER, hidden.has(target) ? "" : null);
|
|
52
173
|
}
|
|
53
174
|
}
|
|
54
175
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/controllers/optimistic_controller.ts"],"names":[],"mappings":";;;AAGA,IAAM,cAAA,GAAiB,yBAAA;AAqChB,IAAM,oBAAA,GAAN,cAAmC,UAAA,CAAwB;AAAA,EAChE,OAAgB,OAAA,GAAU,CAAC,MAAA,EAAQ,MAAM,CAAA;AAAA,EACzC,OAAO,MAAA,GAAS,CAAC,QAAA,EAAU,UAAU,CAAA;AAAA,EAK5B,OAAA,GAAgB;AAGvB,IAAA,IAAI,KAAK,OAAA,CAAQ,YAAA,CAAa,iBAAiB,CAAA,OAAQ,OAAA,EAAQ;AAC/D,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAA,CAAiB,oBAAA,EAAsB,IAAA,CAAK,cAAc,CAAA;AACvE,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAA,CAAiB,kBAAA,EAAoB,IAAA,CAAK,YAAY,CAAA;AAAA,EACrE;AAAA,EAES,UAAA,GAAmB;AAC1B,IAAA,IAAA,CAAK,OAAA,CAAQ,mBAAA,CAAoB,oBAAA,EAAsB,IAAA,CAAK,cAAc,CAAA;AAC1E,IAAA,IAAA,CAAK,OAAA,CAAQ,mBAAA,CAAoB,kBAAA,EAAoB,IAAA,CAAK,YAAY,CAAA;AAAA,EACxE;AAAA,EAES,iBAAiB,MAAY;AACpC,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,iBAAA,EAAmB,MAAM,CAAA;AACnD,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,WAAA,EAAa,MAAM,CAAA;AAC7C,IAAA,KAAA,MAAW,UAAU,IAAA,CAAK,WAAA,EAAa,IAAA,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AAI,MAAA,CAAO,YAAA,CAAa,cAAc,CAAA,EAAG;AACvC,QAAA,MAAA,CAAO,MAAA,GAAS,CAAC,MAAA,CAAO,MAAA;AACxB,QAAA,MAAA,CAAO,gBAAgB,cAAc,CAAA;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AACF","file":"optimistic_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/** Marker recording that this controller toggled the element's `hidden`. */\nconst TOGGLED_MARKER = \"data-optimistic-toggled\";\n\n/**\n * Headless **optimistic UI** for Turbo form submissions — the one server-bound\n * behavior that needs no Action Cable: it wraps a Turbo form\n * and applies a *declared* optimistic state the moment the submission starts,\n * keeps it when the server confirms, and **rolls it back** when the submission\n * fails. The pattern: flip the like button instantly; the success response (a\n * Turbo Stream) replaces the fragment with the server truth anyway, so the\n * client only needs the instant flip and the failure rollback. Core (zero\n * dependencies — it rides Turbo's own `turbo:submit-*` events).\n *\n * Markup contract (identifier: `stimeo--optimistic`):\n * <form data-controller=\"stimeo--optimistic\" method=\"post\" action=\"/likes\">\n * <button type=\"submit\" aria-label=\"Like\">\n * <span data-stimeo--optimistic-target=\"hide\">♡</span>\n * <span hidden data-stimeo--optimistic-target=\"show\">♥</span>\n * </button>\n * </form>\n *\n * On `turbo:submit-start`, every `show` target is unhidden and every `hide`\n * target hidden (each mutation marker-tracked, so already-correct states are\n * untouched), the element gains `data-optimistic=\"true\"` + `aria-busy=\"true\"`.\n * On `turbo:submit-end`: success clears the pending hook and dispatches\n * `commit` (the toggled state stays — the server response owns the final DOM);\n * failure reverts exactly the mutations this controller made and dispatches\n * `rollback`.\n *\n * @remarks\n * Behavior only — what \"optimistic\" looks like is the author's markup (the\n * show/hide pair) and CSS (`[data-optimistic=\"true\"]`). Pairs with\n * `stimeo--submit-once` (double-submit guard) and `stimeo--live-counter`\n * (optimistic numbers). The listeners are delegated on the element (nested or\n * swapped forms keep working) and removed on `disconnect()`; `connect()` is\n * idempotent — a Turbo cache snapshot taken mid-submit is rolled back, since\n * no submission can be in flight across a restore.\n */\nexport class OptimisticController extends Controller<HTMLElement> {\n static override targets = [\"show\", \"hide\"];\n static events = [\"commit\", \"rollback\"] as const;\n\n declare readonly showTargets: HTMLElement[];\n declare readonly hideTargets: HTMLElement[];\n\n override connect(): void {\n // A submission cannot be in flight across a navigation: revert whatever a\n // Turbo cache snapshot preserved mid-submit (idempotent reconnect).\n if (this.element.hasAttribute(\"data-optimistic\")) this.#revert();\n this.element.addEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.addEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.removeEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n }\n\n readonly #onSubmitStart = (): void => {\n this.element.setAttribute(\"data-optimistic\", \"true\");\n this.element.setAttribute(\"aria-busy\", \"true\");\n for (const target of this.showTargets) this.#toggleHidden(target, false);\n for (const target of this.hideTargets) this.#toggleHidden(target, true);\n };\n\n readonly #onSubmitEnd = (event: Event): void => {\n const success = (event as CustomEvent<{ success?: boolean }>).detail?.success === true;\n this.element.removeAttribute(\"aria-busy\");\n if (success) {\n // Keep the optimistic state (the server response owns the final DOM;\n // markers are dropped so a later failure cannot revert a confirmed state).\n this.element.removeAttribute(\"data-optimistic\");\n for (const target of [...this.showTargets, ...this.hideTargets]) {\n target.removeAttribute(TOGGLED_MARKER);\n }\n this.dispatch(\"commit\");\n } else {\n this.#revert();\n this.dispatch(\"rollback\");\n }\n };\n\n /** Sets `hidden` only when it actually changes, marker-tracking the mutation. */\n #toggleHidden(target: HTMLElement, hidden: boolean): void {\n if (target.hidden === hidden) return;\n target.hidden = hidden;\n target.setAttribute(TOGGLED_MARKER, \"true\");\n }\n\n /** Reverts exactly the mutations this controller made (marker-owned only). */\n #revert(): void {\n this.element.removeAttribute(\"data-optimistic\");\n this.element.removeAttribute(\"aria-busy\");\n for (const target of [...this.showTargets, ...this.hideTargets]) {\n if (target.hasAttribute(TOGGLED_MARKER)) {\n target.hidden = !target.hidden;\n target.removeAttribute(TOGGLED_MARKER);\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/detach_gate.ts","../../src/controllers/optimistic_controller.ts"],"names":[],"mappings":";;;;;AA2EO,IAAM,UAAA,GAAN,MAAM,WAAA,CAAW;AAAA;AAAA,EAEtB,QAAA,GAAW,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASX,IAAI,OAAA,GAAmB;AACrB,IAAA,OAAO,IAAA,CAAK,QAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,WAAW,IAAA,EAA+B;AAC/C,IAAA,IAAI,CAAC,IAAA,CAAK,OAAA,CAAQ,WAAA,EAAa,OAAO,IAAA;AACtC,IAAA,MAAM,MAAA,GAAA,CAAU,KAAK,OAAA,CAAQ,YAAA,CAAa,iBAAiB,CAAA,IAAK,EAAA,EAAI,MAAM,KAAK,CAAA;AAC/E,IAAA,OAAO,CAAC,MAAA,CAAO,QAAA,CAAS,IAAA,CAAK,UAAU,CAAA;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,YAAA,CAAa,MAAsB,QAAA,EAA4B;AAC7D,IAAA,IAAI,WAAA,CAAW,UAAA,CAAW,IAAI,CAAA,EAAG;AAG/B,MAAA,IAAA,CAAK,QAAA,GAAW,KAAA;AAChB,MAAA,QAAA,EAAS;AACT,MAAA;AAAA,IACF;AACA,IAAA,IAAA,CAAK,QAAA,GAAW,IAAA;AAChB,IAAA,cAAA,CAAe,MAAM;AACnB,MAAA,IAAI,CAAC,KAAK,QAAA,EAAU;AACpB,MAAA,IAAA,CAAK,QAAA,GAAW,KAAA;AAChB,MAAA,QAAA,EAAS;AAAA,IACX,CAAC,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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cesContent":["/**\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 { DetachGate } from \"../utils/detach_gate\";\n\n/** Records that this controller wrote `hidden`, and the authored value to put back. */\nconst HIDDEN_MARKER = \"data-optimistic-toggled\";\n\n/** The same record for `aria-busy` on the controller element. */\nconst BUSY_MARKER = \"data-optimistic-busy\";\n\n/** Marker value standing for \"the attribute was not there\". */\nconst AUTHORED_ABSENT = \"absent\";\n\n/** Marker prefix carrying the authored attribute value that follows it. */\nconst AUTHORED_VALUE = \"value:\";\n\n/**\n * Stands in for the submission a synthetic lifecycle event does not name. Turbo\n * puts a `formSubmission` on both events, so this only ever pairs hand-dispatched\n * events with each other — one shared instance, so a start and its end match.\n */\nconst SYNTHETIC_SUBMISSION = {};\n\n/** The submission a Turbo lifecycle event belongs to. */\nfunction submissionOf(event: Event): unknown {\n const detail = (event as CustomEvent<{ formSubmission?: unknown }>).detail;\n return detail?.formSubmission ?? SYNTHETIC_SUBMISSION;\n}\n\n/**\n * Headless **optimistic UI** for Turbo form submissions — the one server-bound\n * behavior that needs no Action Cable: it wraps a Turbo form\n * and applies a *declared* optimistic state the moment the submission starts,\n * keeps it when the server confirms, and **rolls it back** when the submission\n * fails. The pattern: flip the like button instantly; the success response (a\n * Turbo Stream) replaces the fragment with the server truth anyway, so the\n * client only needs the instant flip and the failure rollback. Core (zero\n * dependencies — it rides Turbo's own `turbo:submit-*` events).\n *\n * Markup contract (identifier: `stimeo--optimistic`):\n * <form data-controller=\"stimeo--optimistic\" method=\"post\" action=\"/likes\">\n * <button type=\"submit\" aria-label=\"Like\">\n * <span data-stimeo--optimistic-target=\"hide\">♡</span>\n * <span hidden data-stimeo--optimistic-target=\"show\">♥</span>\n * </button>\n * </form>\n *\n * On `turbo:submit-start`, every `show` target is unhidden and every `hide`\n * target hidden, the element gains `data-optimistic=\"true\"` + `aria-busy=\"true\"`,\n * and the submission named by the event takes ownership of that state. On\n * `turbo:submit-end`: the terminal of any *other* submission is ignored; the\n * owner's terminal clears the pending hook and, on success, dispatches `commit`\n * (the toggled state stays — the server response owns the final DOM), or on\n * failure restores the authored markup and dispatches `rollback`.\n *\n * **Every write records what it displaced.** A target this controller hides or\n * reveals carries the authored `hidden` value in `data-optimistic-toggled`, and\n * the element carries the authored `aria-busy` in `data-optimistic-busy`, so a\n * rollback puts back exactly what the author wrote — not the inverse of whatever\n * the attribute says at that moment. The record lives in the DOM rather than in\n * memory because a Turbo cache snapshot has to carry it: `connect()` is what\n * rewinds a restored page.\n *\n * @remarks\n * Behavior only — what \"optimistic\" looks like is the author's markup (the\n * show/hide pair) and CSS (`[data-optimistic=\"true\"]`). Pairs with\n * `stimeo--submit-once` (double-submit guard) and `stimeo--live-counter`\n * (optimistic numbers). The listeners are delegated on the element, so a form\n * nested under it (or swapped for a new one) keeps working, and the submission\n * ownership is what keeps a sibling form's terminal from resolving this state.\n * With several submissions in flight the newest start owns the optimistic state,\n * so a submission whose terminal never arrives — its form replaced mid-flight —\n * cannot strand the element. `connect()` is idempotent: a Turbo cache snapshot\n * taken mid-submit is rewound, since no submission can be in flight across a\n * restore, while an in-page move (where the submission *does* survive) keeps it.\n * On a real detach the listeners go with the element.\n */\nexport class OptimisticController extends Controller<HTMLElement> {\n static override targets = [\"show\", \"hide\"];\n static events = [\"commit\", \"rollback\"] as const;\n\n declare readonly showTargets: HTMLElement[];\n declare readonly hideTargets: HTMLElement[];\n\n /** The submission that owns the applied optimistic state, if any. */\n #pending: unknown = null;\n\n readonly #gate = new DetachGate();\n\n /** True between `connect()` and `disconnect()`, so a repeat connect rewinds nothing. */\n #connected = false;\n\n override connect(): void {\n // Only a page this instance did not apply the state to can be holding a stale\n // one: a restored snapshot. An in-page move and a repeat connect both leave a\n // live submission behind, so neither may rewind — the gate names the first and\n // the connected flag the second.\n const restored = !this.#connected && !this.#gate.pending;\n this.#gate.cancel();\n this.#connected = true;\n if (restored && this.element.hasAttribute(\"data-optimistic\")) this.#revert();\n this.element.addEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.addEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n }\n\n override disconnect(): void {\n this.#connected = false;\n this.element.removeEventListener(\"turbo:submit-start\", this.#onSubmitStart);\n this.element.removeEventListener(\"turbo:submit-end\", this.#onSubmitEnd);\n // Ownership outlives an in-page move: only a real detach forgets it.\n this.#gate.disconnected(this, () => {\n this.#pending = null;\n });\n }\n\n readonly #onSubmitStart = (event: Event): void => {\n this.#pending = submissionOf(event);\n // Turbo owns `aria-busy` on a form and marks it before this event, so what is\n // there now is Turbo's, not the author's. Recording it would put Turbo's value\n // back on a page restored mid-submit, where no terminal ever arrives to clear it.\n if (this.element instanceof HTMLFormElement && !this.element.hasAttribute(BUSY_MARKER)) {\n this.element.setAttribute(BUSY_MARKER, AUTHORED_ABSENT);\n }\n this.#write(this.element, \"aria-busy\", \"true\", BUSY_MARKER);\n this.element.setAttribute(\"data-optimistic\", \"true\");\n for (const target of this.showTargets) this.#setHidden(target, false);\n for (const target of this.hideTargets) this.#setHidden(target, true);\n };\n\n readonly #onSubmitEnd = (event: Event): void => {\n // A terminal always names a submission, so an element holding none (nothing\n // started, or this one already resolved) falls out here too.\n if (submissionOf(event) !== this.#pending) return;\n this.#pending = null;\n\n const success = (event as CustomEvent<{ success?: boolean }>).detail?.success === true;\n if (success) {\n // Keep the toggled faces (the server response owns the final DOM) but drop\n // their records, so a later failure cannot revert a confirmed state.\n this.element.removeAttribute(\"data-optimistic\");\n this.#restore(this.element, \"aria-busy\", BUSY_MARKER, \"true\");\n for (const target of [...this.showTargets, ...this.hideTargets]) {\n target.removeAttribute(HIDDEN_MARKER);\n }\n this.dispatch(\"commit\");\n } else {\n this.#revert();\n this.dispatch(\"rollback\");\n }\n };\n\n /** Hides or reveals a target, recording the authored `hidden` on first write. */\n #setHidden(target: HTMLElement, hidden: boolean): void {\n if (target.hasAttribute(\"hidden\") === hidden) return;\n this.#write(target, \"hidden\", hidden ? \"\" : null, HIDDEN_MARKER);\n }\n\n /** Writes an attribute, recording what it displaced under `marker` once. */\n #write(element: Element, attribute: string, value: string | null, marker: string): void {\n if (!element.hasAttribute(marker)) {\n const authored = element.getAttribute(attribute);\n element.setAttribute(\n marker,\n authored === null ? AUTHORED_ABSENT : `${AUTHORED_VALUE}${authored}`,\n );\n }\n if (value === null) element.removeAttribute(attribute);\n else element.setAttribute(attribute, value);\n }\n\n /**\n * Puts back the value `marker` recorded and drops the record.\n *\n * `written` is what this controller last put in the attribute. Anything else\n * there now belongs to whoever wrote it — Turbo owns `aria-busy` on a form and\n * clears it before the terminal arrives, and a consumer may have moved a face\n * mid-flight — so the record is dropped without touching the attribute. A\n * marker this build did not write names no authored value, so the attribute\n * goes back to being absent.\n */\n #restore(element: Element, attribute: string, marker: string, written: string | null): void {\n const recorded = element.getAttribute(marker);\n if (recorded === null) return;\n element.removeAttribute(marker);\n if (element.getAttribute(attribute) !== written) return;\n if (recorded.startsWith(AUTHORED_VALUE)) {\n element.setAttribute(attribute, recorded.slice(AUTHORED_VALUE.length));\n return;\n }\n element.removeAttribute(attribute);\n }\n\n /**\n * Puts back exactly the markup this controller displaced (record-owned only).\n *\n * A face can be registered on both sides, and the hide pass runs last, so what\n * this controller wrote there is `hidden` — matching it against the reveal's\n * absent value instead would read as someone else's write and leave the face\n * hidden. Each target is therefore restored once, against the write it last\n * received.\n */\n #revert(): void {\n this.element.removeAttribute(\"data-optimistic\");\n this.#restore(this.element, \"aria-busy\", BUSY_MARKER, \"true\");\n const hidden = new Set(this.hideTargets);\n for (const target of new Set([...this.showTargets, ...this.hideTargets])) {\n this.#restore(target, \"hidden\", HIDDEN_MARKER, hidden.has(target) ? \"\" : null);\n }\n }\n}\n"]}
|
|
@@ -22,7 +22,7 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
22
22
|
* </div>
|
|
23
23
|
*
|
|
24
24
|
* The viewport's scroll position and size are watched (via the wired `scroll`
|
|
25
|
-
* action, plus
|
|
25
|
+
* action, plus `LayoutObserver` for viewport/content resize, a
|
|
26
26
|
* {@link MutationObserver}, and descendant load events). Optional page buttons
|
|
27
27
|
* scroll one logical viewport page at a time (including RTL) and have their
|
|
28
28
|
* disabled state synced to the matching direction's remaining room.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/blur_deferral.ts","../../src/utils/layout_observer.ts","../../src/utils/logical_scroll.ts","../../src/utils/reduced_motion.ts","../../src/controllers/overflow_indicator_controller.ts"],"names":[],"mappings":";;;;;AAoDO,IAAM,eAAN,MAAwD;AAAA;AAAA,EAEpD,QAAA,uBAAe,GAAA,EAAmB;AAAA;AAAA,EAElC,UAAA;AAAA;AAAA,EAGT,YAAY,SAAA,EAAiC;AAC3C,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,EACvB;AAAA;AAAA,EAGA,IAAI,QAAA,GAAgB;AAClB,IAAA,OAAO,CAAC,GAAG,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA;AAAA,EACjC;AAAA;AAAA,EAGA,IAAI,OAAA,EAAqB;AACvB,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAO,CAAA;AAAA,EAClC;AAAA;AAAA,EAGA,MAAM,OAAA,EAAkB;AACtB,IAAA,IAAI,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAO,CAAA,EAAG;AAChC,IAAA,MAAM,SAAS,MAAY;AACzB,MAAA,IAAA,CAAK,QAAQ,OAAO,CAAA;AACpB,MAAA,IAAA,CAAK,WAAW,OAAO,CAAA;AAAA,IACzB,CAAA;AACA,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,EAAS,MAAM,CAAA;AACjC,IAAA,OAAA,CAAQ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AAM;AAC5B,IAAA,IAAA,CAAK,iBAAA,GAAoB,IAAA;AACzB,IAAA,IAAA,CAAK,QAAQ,iBAAA,EAAkB;AAAA,EACjC;AAAA,EAES,iBAAiB,MAAY;AACpC,IAAA,IAAI,IAAA,CAAK,UAAA,EAAY,IAAA,CAAK,MAAA,EAAO;AAAA,EACnC,CAAA;AAAA,EAEA,IAAI,UAAA,GAAqB;AACvB,IAAA,MAAM,QAAQ,IAAA,CAAK,cAAA;AACnB,IAAA,OAAO,MAAA,CAAO,SAAS,KAAK,CAAA,GAAI,KAAK,GAAA,CAAI,CAAA,EAAG,KAAK,CAAA,GAAI,CAAA;AAAA,EACvD;AAAA,EAEA,oBAAoB,KAAA,EAAsC;AACxD,IAAA,MAAM,SAAU,KAAA,CAAuD,MAAA;AACvE,IAAA,MAAM,YAAY,MAAA,EAAQ,SAAA;AAC1B,IAAA,OAAO,SAAA,KAAc,OAAA,IAAW,SAAA,KAAc,KAAA,GAAQ,SAAA,GAAY,IAAA;AAAA,EACpE;AACF","file":"overflow_indicator_controller.js","sourcesContent":["/**\n * Shared bookkeeping for updates that must wait until an element loses focus.\n *\n * A control that becomes redundant while the user is standing on it cannot be\n * removed from the page immediately: hiding a focused element (or turning it\n * into a native `disabled` one) drops focus to `<body>`, stranding a keyboard\n * user mid-widget. The fix every affected controller reached for is the same —\n * keep the element reachable, hold the destructive update, listen for `blur`,\n * and apply it then.\n *\n * {@link BlurDeferral} owns *only* the registry part of that: which elements are\n * currently holding an update back, attaching and detaching the `blur` listener,\n * and guaranteeing teardown. It is deliberately **policy-free** — what the\n * interim state looks like (`aria-disabled`, an ownership marker, nothing at\n * all), and what the deferred update actually is, stay in the controller, which\n * receives the element back through its release callback.\n *\n * Three contracts are worth stating up front, because each one is a hazard the\n * consumers would otherwise hit:\n *\n * - **The release callback fires only on a real `blur`.** `release()` /\n * `releaseAll()` *cancel* a deferral; they do not complete it. Conflating the\n * two makes `overflow-indicator` disable a button that just left the boundary.\n * - **`elements` is a snapshot.** Iterating the live key set while releasing\n * inside the loop is the failure this registry exists to prevent.\n * - **The entry is detached before the callback runs**, so a controller that\n * decides the update is still unsafe can simply defer again.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and contracts belong on the members.\n *\n * @example\n * ```ts\n * readonly #deferred = new BlurDeferral<HTMLElement>((trigger) => {\n * if (this.#connected) this.#evaluate();\n * });\n *\n * #hide(trigger: HTMLElement) {\n * if (document.activeElement === trigger) {\n * this.#deferred.deferOnly(trigger); // stays visible until blur\n * return;\n * }\n * this.#deferred.releaseAll();\n * trigger.hidden = true;\n * }\n *\n * disconnect() {\n * this.#deferred.releaseAll();\n * }\n * ```\n */\nexport class BlurDeferral<T extends HTMLElement = HTMLElement> {\n /** Elements currently holding an update back, mapped to their `blur` listener. */\n readonly #pending = new Map<T, () => void>();\n /** Called after a pending element blurs and has been detached. */\n readonly #onRelease: (element: T) => void;\n\n /** @param onRelease - Invoked once `element` actually blurs; never on `release`. */\n constructor(onRelease: (element: T) => void) {\n this.#onRelease = onRelease;\n }\n\n /** Number of elements currently holding an update back. */\n get size(): number {\n return this.#pending.size;\n }\n\n /** Snapshot of the pending elements, safe to iterate while releasing them. */\n get elements(): T[] {\n return [...this.#pending.keys()];\n }\n\n /** Whether `element` is currently holding an update back. */\n has(element: T): boolean {\n return this.#pending.has(element);\n }\n\n /** Holds an update back until `element` blurs. Idempotent (no stacked listeners). */\n defer(element: T): void {\n if (this.#pending.has(element)) return;\n const onBlur = (): void => {\n this.#detach(element);\n this.#onRelease(element);\n };\n this.#pending.set(element, onBlur);\n element.addEventListener(\"blur\", onBlur);\n }\n\n /** Defers `element` as the only pending entry, cancelling any others. */\n deferOnly(element: T): void {\n for (const pending of this.elements) {\n if (pending !== element) this.#detach(pending);\n }\n this.defer(element);\n }\n\n /** Cancels `element`'s deferral without completing it; no-ops when not pending. */\n release(element: T): void {\n this.#detach(element);\n }\n\n /** Cancels every deferral without completing any of them. */\n releaseAll(): void {\n for (const element of this.elements) this.#detach(element);\n }\n\n /** Removes the `blur` listener for `element` and forgets it. */\n #detach(element: T): void {\n const onBlur = this.#pending.get(element);\n if (onBlur) element.removeEventListener(\"blur\", onBlur);\n this.#pending.delete(element);\n }\n}\n","/**\n * Unified element-size and viewport observation for Stimeo controllers.\n *\n * Widgets whose output is measured — an overflow boundary, a masonry column count,\n * an autosized textarea — need to react both to their *own* box changing — via {@link ResizeObserver} —\n * and to the *viewport* changing — via the `window` `resize` event. Wiring those\n * two sources by hand in every controller risks leaked listeners on\n * `disconnect()`. {@link LayoutObserver} owns both behind one callback and one\n * {@link LayoutObserver.disconnect | disconnect()} that releases everything.\n *\n * Behavior only: the helper reports *that* layout changed; it never reads or\n * writes styles. Consumers decide what to recompute.\n */\n\n/** Invoked whenever an observed element or the viewport changes size. */\nexport type LayoutCallback = () => void;\n\n/** Constructs a {@link ResizeObserver}; injectable so tests stay deterministic. */\nexport type ResizeObserverFactory = (callback: ResizeObserverCallback) => ResizeObserver;\n\n/** Options for {@link LayoutObserver}. */\nexport interface LayoutObserverOptions {\n /**\n * Factory for the {@link ResizeObserver} used by {@link LayoutObserver.observe}.\n * Defaults to the global constructor; override it in tests, or to no-op in\n * environments where `ResizeObserver` is unavailable.\n */\n resizeObserverFactory?: ResizeObserverFactory;\n}\n\n/**\n * Observes element resizes and/or viewport resizes through a single callback,\n * with guaranteed teardown.\n *\n * @example\n * ```ts\n * #layout = new LayoutObserver(() => this.#reposition());\n *\n * connect() {\n * this.#layout.observe(this.panelTarget);\n * this.#layout.observeViewport();\n * }\n *\n * disconnect() {\n * this.#layout.disconnect();\n * }\n * ```\n */\nexport class LayoutObserver {\n readonly #callback: LayoutCallback;\n readonly #resizeObserverFactory: ResizeObserverFactory | null;\n #resizeObserver: ResizeObserver | null = null;\n #observingViewport = false;\n\n /** Stable bound handler so add/removeEventListener target the same reference. */\n readonly #handleViewportResize = (): void => {\n this.#callback();\n };\n\n constructor(callback: LayoutCallback, options: LayoutObserverOptions = {}) {\n this.#callback = callback;\n this.#resizeObserverFactory =\n options.resizeObserverFactory ??\n (typeof ResizeObserver === \"undefined\" ? null : (cb) => new ResizeObserver(cb));\n }\n\n /**\n * Starts observing an element's size. Repeated calls observe additional\n * elements through the same shared observer. No-ops when no\n * `ResizeObserver` implementation is available.\n */\n observe(element: Element): void {\n if (!this.#resizeObserverFactory) return;\n if (!this.#resizeObserver) {\n this.#resizeObserver = this.#resizeObserverFactory(() => {\n this.#callback();\n });\n }\n this.#resizeObserver.observe(element);\n }\n\n /** Stops observing a single element while leaving any others in place. */\n unobserve(element: Element): void {\n this.#resizeObserver?.unobserve(element);\n }\n\n /** Starts observing viewport resizes. Idempotent: the listener is added once. */\n observeViewport(): void {\n if (this.#observingViewport) return;\n this.#observingViewport = true;\n window.addEventListener(\"resize\", this.#handleViewportResize);\n }\n\n /** Stops observing viewport resizes without affecting element observation. */\n unobserveViewport(): void {\n if (!this.#observingViewport) return;\n this.#observingViewport = false;\n window.removeEventListener(\"resize\", this.#handleViewportResize);\n }\n\n /**\n * Releases every observation: disconnects the {@link ResizeObserver} and\n * removes the viewport listener. Safe to call multiple times. Call this from a\n * controller's `disconnect()`.\n */\n disconnect(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = null;\n this.unobserveViewport();\n }\n}\n","/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","/**\n * Shared `prefers-reduced-motion` lookup for the motion-aware controllers\n *.\n *\n * This one-liner keeps the media query string and the environment guard\n * single-sourced across them. The preference is intentionally re-read on every\n * call — the controllers check it at each animation/scroll start (WCAG 2.2\n * **2.3.3**), so flipping the OS setting takes effect immediately without any\n * listener or cache bookkeeping here.\n */\n\n/**\n * Whether the user currently requests reduced motion.\n *\n * @returns `true` when `(prefers-reduced-motion: reduce)` matches; `false`\n * otherwise, including environments without `window.matchMedia` (treated as\n * \"no preference\").\n */\nexport function prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { BlurDeferral } from \"../utils/blur_deferral\";\nimport { LayoutObserver } from \"../utils/layout_observer\";\nimport { logicalScrollMetrics, physicalScrollDelta } from \"../utils/logical_scroll\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\nconst DIRECTION_BUTTON_SELECTOR = \"[data-stimeo--overflow-indicator-direction-param]\";\n\n/**\n * Headless **Overflow Indicator**: detects whether a scroll container can still\n * scroll toward its start and/or end and publishes it as `data-overflow-start` /\n * `data-overflow-end`. No APG widget — a state-detection utility. Consumers draw\n * edge shadows or arrows in CSS to signal \"more content this way\".\n *\n * Markup contract (identifier: `stimeo--overflow-indicator`):\n * <div data-controller=\"stimeo--overflow-indicator\"\n * data-stimeo--overflow-indicator-orientation-value=\"horizontal\">\n * <button type=\"button\" aria-label=\"Prev\"\n * data-stimeo--overflow-indicator-direction-param=\"start\"\n * data-action=\"click->stimeo--overflow-indicator#scrollByPage\">‹</button>\n * <div data-stimeo--overflow-indicator-target=\"viewport\"\n * data-action=\"scroll->stimeo--overflow-indicator#update\"\n * tabindex=\"0\" role=\"region\" aria-label=\"Products\"\n * style=\"overflow-x: auto;\"><!-- items --></div>\n * <button type=\"button\" aria-label=\"Next\"\n * data-stimeo--overflow-indicator-direction-param=\"end\"\n * data-action=\"click->stimeo--overflow-indicator#scrollByPage\">›</button>\n * </div>\n *\n * The viewport's scroll position and size are watched (via the wired `scroll`\n * action, plus {@link LayoutObserver} for viewport/content resize, a\n * {@link MutationObserver}, and descendant load events). Optional page buttons\n * scroll one logical viewport page at a time (including RTL) and have their\n * disabled state synced to the matching direction's remaining room.\n *\n * `change` dispatches `{ start: boolean, end: boolean }`.\n *\n * @remarks\n * Behavior only — shadows, arrows, and gradients are the consumer's CSS;\n * `data-overflow-*` carry no ARIA semantics. All observers/listeners are released\n * on `disconnect()` (Turbo navigation included). `scrollByPage` scrolls smoothly\n * by default and forces an instant jump under `prefers-reduced-motion`, regardless\n * of the consumer's CSS `scroll-behavior`.\n */\nexport class OverflowIndicatorController extends Controller<HTMLElement> {\n static override targets = [\"viewport\"];\n static override values = {\n orientation: { type: String, default: \"horizontal\" },\n threshold: { type: Number, default: 1 },\n };\n static actions = [\"scrollByPage\", \"update\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly viewportTarget: HTMLElement;\n declare readonly hasViewportTarget: boolean;\n\n declare orientationValue: string;\n declare thresholdValue: number;\n\n readonly #layout = new LayoutObserver(() => {\n if (this.#connected) this.update();\n });\n #connected = false;\n #observedViewport: HTMLElement | null = null;\n readonly #observedContent = new Set<Element>();\n #mutationObserver: MutationObserver | null = null;\n /**\n * Boundary buttons whose native `disabled` is held back while they hold focus.\n *\n * Completing the deferral is what actually disables the button, so the release\n * callback — unlike {@link #cancelPendingButtonDisable} — applies it.\n */\n readonly #pendingButtonDisables = new BlurDeferral<HTMLButtonElement>((button) => {\n this.#restorePendingMarkers(button);\n // If the author disabled it while focus was pending, do not claim ownership.\n if (!button.disabled) this.#disableButton(button);\n });\n /** Last reported room, so `change` fires only on transitions. */\n #state: { start: boolean; end: boolean } | null = null;\n\n override connect(): void {\n this.#connected = true;\n this.#syncViewport();\n }\n\n override disconnect(): void {\n this.#connected = false;\n this.#stopObservingViewport();\n this.#layout.disconnect();\n this.#clearPendingButtonDisables();\n this.#state = null;\n }\n\n viewportTargetConnected(): void {\n this.#syncViewport();\n }\n\n viewportTargetDisconnected(viewport: HTMLElement): void {\n if (this.#observedViewport === viewport) this.#stopObservingViewport();\n this.#syncViewport();\n }\n\n orientationValueChanged(): void {\n if (this.#connected) this.update();\n }\n\n thresholdValueChanged(): void {\n if (this.#connected) this.update();\n }\n\n /**\n * Re-measures remaining scroll room and reflects the state hooks.\n * Public so it can be wired to the viewport's `scroll`.\n */\n update(): void {\n if (!this.hasViewportTarget) return;\n const vp = this.viewportTarget;\n const horizontal = this.orientationValue !== \"vertical\";\n const t = this.#threshold;\n const { position: scrollPos, max: maxScroll } = logicalScrollMetrics(vp, horizontal);\n\n const start = scrollPos > t;\n const end = scrollPos < maxScroll - t;\n\n vp.setAttribute(\"data-overflow-start\", start ? \"true\" : \"false\");\n vp.setAttribute(\"data-overflow-end\", end ? \"true\" : \"false\");\n this.#syncButtons(start, end);\n\n if (!this.#state || this.#state.start !== start || this.#state.end !== end) {\n this.#state = { start, end };\n this.dispatch(\"change\", { detail: { start, end } });\n }\n }\n\n /** Scrolls one viewport page toward the `direction` param (`start`/`end`). */\n scrollByPage(event: Event): void {\n if (!this.hasViewportTarget) return;\n const direction = this.#directionFromEvent(event);\n if (!direction) return;\n if (this.#state && !this.#state[direction]) return;\n\n const vp = this.viewportTarget;\n const horizontal = this.orientationValue !== \"vertical\";\n const page = horizontal ? vp.clientWidth : vp.clientHeight;\n const logicalDelta = direction === \"start\" ? -page : page;\n const delta = physicalScrollDelta(vp, horizontal, logicalDelta);\n const behavior: ScrollBehavior = prefersReducedMotion() ? \"instant\" : \"smooth\";\n\n if (horizontal) {\n vp.scrollBy({ left: delta, behavior });\n } else {\n vp.scrollBy({ top: delta, behavior });\n }\n }\n\n /** Mirrors remaining room onto any direction buttons by toggling `disabled`. */\n #syncButtons(start: boolean, end: boolean): void {\n for (const button of this.#pendingButtonDisables.elements) {\n if (\n !button.isConnected ||\n button.closest(\"[data-controller~='stimeo--overflow-indicator']\") !== this.element\n ) {\n this.#cancelPendingButtonDisable(button);\n }\n }\n const buttons = this.element.querySelectorAll<HTMLButtonElement>(DIRECTION_BUTTON_SELECTOR);\n for (const button of buttons) {\n if (button.closest(\"[data-controller~='stimeo--overflow-indicator']\") !== this.element) {\n continue;\n }\n const direction = button.getAttribute(\"data-stimeo--overflow-indicator-direction-param\");\n if (direction === \"start\") this.#toggleButton(button, start);\n else if (direction === \"end\") this.#toggleButton(button, end);\n }\n }\n\n /**\n * Reflects the remaining room onto a page button's `disabled`, owning only the\n * `disabled` it sets itself via a marker (`data-overflow-indicator-disabled`,\n * like `number-input`/`conditional-fields`). An author-disabled button (e.g. the\n * whole control disabled) is therefore never blindly re-enabled.\n */\n #toggleButton(button: HTMLButtonElement, hasRoom: boolean): void {\n // A restored Turbo snapshot can carry pending markers from the previous visit\n // that this instance never created; release them from the DOM record before\n // deciding, or the displaced `aria-disabled` would never be given back.\n if (\n !this.#pendingButtonDisables.has(button) &&\n button.hasAttribute(\"data-overflow-indicator-pending-disabled\")\n ) {\n this.#cancelPendingButtonDisable(button);\n }\n if (hasRoom) {\n this.#cancelPendingButtonDisable(button);\n if (button.hasAttribute(\"data-overflow-indicator-disabled\")) {\n button.disabled = false;\n button.removeAttribute(\"data-overflow-indicator-disabled\");\n }\n return;\n }\n if (button.disabled) return; // already disabled (possibly by the author) — leave it\n if (document.activeElement === button) {\n this.#deferButtonDisable(button);\n } else {\n this.#disableButton(button);\n }\n }\n\n /**\n * Keeps a boundary button focusable until native blur, exposing its temporary\n * inoperability with `aria-disabled` and making its action a no-op meanwhile.\n */\n #deferButtonDisable(button: HTMLButtonElement): void {\n if (this.#pendingButtonDisables.has(button)) return;\n button.setAttribute(\"data-overflow-indicator-pending-disabled\", \"\");\n // The ownership marker carries the value we displace, so the DOM alone is\n // enough to undo it. A Turbo snapshot is cloned before `disconnect()` runs,\n // so a restored page arrives with these markers while the new instance has\n // no in-memory record of them — an empty marker means \"there was none\".\n button.setAttribute(\n \"data-overflow-indicator-aria-disabled\",\n button.getAttribute(\"aria-disabled\") ?? \"\",\n );\n button.setAttribute(\"aria-disabled\", \"true\");\n this.#pendingButtonDisables.defer(button);\n }\n\n #disableButton(button: HTMLButtonElement): void {\n button.disabled = true;\n button.setAttribute(\"data-overflow-indicator-disabled\", \"\");\n }\n\n /** Cancels a pending disable without applying it, restoring the displaced state. */\n #cancelPendingButtonDisable(button: HTMLButtonElement): void {\n this.#pendingButtonDisables.release(button);\n this.#restorePendingMarkers(button);\n }\n\n /**\n * Drops the pending marker and gives back the `aria-disabled` it displaced.\n *\n * Reads the displaced value from the DOM rather than memory: a Turbo snapshot is\n * cloned before `disconnect()` runs, so a restored page can arrive with markers\n * this instance never wrote.\n */\n #restorePendingMarkers(button: HTMLButtonElement): void {\n button.removeAttribute(\"data-overflow-indicator-pending-disabled\");\n const displaced = button.getAttribute(\"data-overflow-indicator-aria-disabled\");\n if (displaced !== null) {\n button.removeAttribute(\"data-overflow-indicator-aria-disabled\");\n if (button.getAttribute(\"aria-disabled\") === \"true\") {\n if (displaced === \"\") button.removeAttribute(\"aria-disabled\");\n else button.setAttribute(\"aria-disabled\", displaced);\n }\n }\n }\n\n #clearPendingButtonDisables(): void {\n for (const button of this.#pendingButtonDisables.elements) {\n this.#cancelPendingButtonDisable(button);\n }\n }\n\n /** Moves resize/mutation/load observation to the current viewport target. */\n #syncViewport(): void {\n if (!this.#connected) return;\n const next = this.hasViewportTarget ? this.viewportTarget : null;\n if (next === this.#observedViewport) return;\n this.#stopObservingViewport();\n if (!next) return;\n\n this.#observedViewport = next;\n this.#layout.observe(next);\n this.#layout.observeViewport();\n next.addEventListener(\"load\", this.#onContentLoad, true);\n this.#syncContentObservation();\n\n if (typeof MutationObserver !== \"undefined\") {\n this.#mutationObserver = new MutationObserver(() => {\n if (!this.#connected || this.#observedViewport !== next) return;\n this.#syncContentObservation();\n this.update();\n });\n this.#mutationObserver.observe(this.element, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n attributeFilter: [\"class\", \"style\", \"hidden\"],\n });\n }\n this.#state = null;\n this.update();\n }\n\n /** Observes direct content boxes whose resize can change the viewport's scroll extent. */\n #syncContentObservation(): void {\n const next = new Set<Element>(this.#observedViewport?.children ?? []);\n for (const content of this.#observedContent) {\n if (!next.has(content)) {\n this.#layout.unobserve(content);\n this.#observedContent.delete(content);\n }\n }\n for (const content of next) {\n if (!this.#observedContent.has(content)) {\n this.#observedContent.add(content);\n this.#layout.observe(content);\n }\n }\n }\n\n #stopObservingViewport(): void {\n this.#mutationObserver?.disconnect();\n this.#mutationObserver = null;\n this.#observedViewport?.removeEventListener(\"load\", this.#onContentLoad, true);\n if (this.#observedViewport) this.#layout.unobserve(this.#observedViewport);\n for (const content of this.#observedContent) this.#layout.unobserve(content);\n this.#observedContent.clear();\n this.#observedViewport = null;\n this.#layout.unobserveViewport();\n }\n\n readonly #onContentLoad = (): void => {\n if (this.#connected) this.update();\n };\n\n get #threshold(): number {\n const value = this.thresholdValue;\n return Number.isFinite(value) ? Math.max(0, value) : 1;\n }\n\n #directionFromEvent(event: Event): \"start\" | \"end\" | null {\n const params = (event as Event & { params?: { direction?: unknown } }).params;\n const direction = params?.direction;\n return direction === \"start\" || direction === \"end\" ? direction : null;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/blur_deferral.ts","../../src/utils/layout_observer.ts","../../src/utils/logical_scroll.ts","../../src/utils/reduced_motion.ts","../../src/controllers/overflow_indicator_controller.ts"],"names":[],"mappings":";;;;;AAoDO,IAAM,eAAN,MAAwD;AAAA;AAAA,EAEpD,QAAA,uBAAe,GAAA,EAAmB;AAAA;AAAA,EAElC,UAAA;AAAA;AAAA,EAGT,YAAY,SAAA,EAAiC;AAC3C,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,QAAA,CAAS,IAAA;AAAA,EACvB;AAAA;AAAA,EAGA,IAAI,QAAA,GAAgB;AAClB,IAAA,OAAO,CAAC,GAAG,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA;AAAA,EACjC;AAAA;AAAA,EAGA,IAAI,OAAA,EAAqB;AACvB,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAO,CAAA;AAAA,EAClC;AAAA;AAAA,EAGA,MAAM,OAAA,EAAkB;AACtB,IAAA,IAAI,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAO,CAAA,EAAG;AAChC,IAAA,MAAM,SAAS,MAAY;AACzB,MAAA,IAAA,CAAK,QAAQ,OAAO,CAAA;AACpB,MAAA,IAAA,CAAK,WAAW,OAAO,CAAA;AAAA,IACzB,CAAA;AACA,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,EAAS,MAAM,CAAA;AACjC,IAAA,OAAA,CAAQ,gBAAA,CAAiB,QAAQ,MAAM,CAAA;AAAA,EACzC;AAAA;AAAA,EAGA,UAAU,OAAA,EAAkB;AAC1B,IAAA,KAAA,MAAW,OAAA,I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,iBAAiB,MAAY;AACpC,IAAA,IAAI,IAAA,CAAK,UAAA,EAAY,IAAA,CAAK,MAAA,EAAO;AAAA,EACnC,CAAA;AAAA,EAEA,IAAI,UAAA,GAAqB;AACvB,IAAA,MAAM,QAAQ,IAAA,CAAK,cAAA;AACnB,IAAA,OAAO,MAAA,CAAO,SAAS,KAAK,CAAA,GAAI,KAAK,GAAA,CAAI,CAAA,EAAG,KAAK,CAAA,GAAI,CAAA;AAAA,EACvD;AAAA,EAEA,oBAAoB,KAAA,EAAsC;AACxD,IAAA,MAAM,SAAU,KAAA,CAAuD,MAAA;AACvE,IAAA,MAAM,YAAY,MAAA,EAAQ,SAAA;AAC1B,IAAA,OAAO,SAAA,KAAc,OAAA,IAAW,SAAA,KAAc,KAAA,GAAQ,SAAA,GAAY,IAAA;AAAA,EACpE;AACF","file":"overflow_indicator_controller.js","sourcesContent":["/**\n * Shared bookkeeping for updates that must wait until an element loses focus.\n *\n * A control that becomes redundant while the user is standing on it cannot be\n * removed from the page immediately: hiding a focused element (or turning it\n * into a native `disabled` one) drops focus to `<body>`, stranding a keyboard\n * user mid-widget. The fix every affected controller reached for is the same —\n * keep the element reachable, hold the destructive update, listen for `blur`,\n * and apply it then.\n *\n * {@link BlurDeferral} owns *only* the registry part of that: which elements are\n * currently holding an update back, attaching and detaching the `blur` listener,\n * and guaranteeing teardown. It is deliberately **policy-free** — what the\n * interim state looks like (`aria-disabled`, an ownership marker, nothing at\n * all), and what the deferred update actually is, stay in the controller, which\n * receives the element back through its release callback.\n *\n * Three contracts are worth stating up front, because each one is a hazard the\n * consumers would otherwise hit:\n *\n * - **The release callback fires only on a real `blur`.** `release()` /\n * `releaseAll()` *cancel* a deferral; they do not complete it. Conflating the\n * two makes `overflow-indicator` disable a button that just left the boundary.\n * - **`elements` is a snapshot.** Iterating the live key set while releasing\n * inside the loop is the failure this registry exists to prevent.\n * - **The entry is detached before the callback runs**, so a controller that\n * decides the update is still unsafe can simply defer again.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and contracts belong on the members.\n *\n * @example\n * ```ts\n * readonly #deferred = new BlurDeferral<HTMLElement>((trigger) => {\n * if (this.#connected) this.#evaluate();\n * });\n *\n * #hide(trigger: HTMLElement) {\n * if (document.activeElement === trigger) {\n * this.#deferred.deferOnly(trigger); // stays visible until blur\n * return;\n * }\n * this.#deferred.releaseAll();\n * trigger.hidden = true;\n * }\n *\n * disconnect() {\n * this.#deferred.releaseAll();\n * }\n * ```\n */\nexport class BlurDeferral<T extends HTMLElement = HTMLElement> {\n /** Elements currently holding an update back, mapped to their `blur` listener. */\n readonly #pending = new Map<T, () => void>();\n /** Called after a pending element blurs and has been detached. */\n readonly #onRelease: (element: T) => void;\n\n /** @param onRelease - Invoked once `element` actually blurs; never on `release`. */\n constructor(onRelease: (element: T) => void) {\n this.#onRelease = onRelease;\n }\n\n /** Number of elements currently holding an update back. */\n get size(): number {\n return this.#pending.size;\n }\n\n /** Snapshot of the pending elements, safe to iterate while releasing them. */\n get elements(): T[] {\n return [...this.#pending.keys()];\n }\n\n /** Whether `element` is currently holding an update back. */\n has(element: T): boolean {\n return this.#pending.has(element);\n }\n\n /** Holds an update back until `element` blurs. Idempotent (no stacked listeners). */\n defer(element: T): void {\n if (this.#pending.has(element)) return;\n const onBlur = (): void => {\n this.#detach(element);\n this.#onRelease(element);\n };\n this.#pending.set(element, onBlur);\n element.addEventListener(\"blur\", onBlur);\n }\n\n /** Defers `element` as the only pending entry, cancelling any others. */\n deferOnly(element: T): void {\n for (const pending of this.elements) {\n if (pending !== element) this.#detach(pending);\n }\n this.defer(element);\n }\n\n /** Cancels `element`'s deferral without completing it; no-ops when not pending. */\n release(element: T): void {\n this.#detach(element);\n }\n\n /** Cancels every deferral without completing any of them. */\n releaseAll(): void {\n for (const element of this.elements) this.#detach(element);\n }\n\n /** Removes the `blur` listener for `element` and forgets it. */\n #detach(element: T): void {\n const onBlur = this.#pending.get(element);\n if (onBlur) element.removeEventListener(\"blur\", onBlur);\n this.#pending.delete(element);\n }\n}\n","/**\n * Unified element-size and viewport observation for Stimeo controllers.\n *\n * Widgets whose output is measured — an overflow boundary, a masonry column count,\n * an autosized textarea — need to react both to their *own* box changing — via {@link ResizeObserver} —\n * and to the *viewport* changing — via the `window` `resize` event. Wiring those\n * two sources by hand in every controller risks leaked listeners on\n * `disconnect()`. {@link LayoutObserver} owns both behind one callback and one\n * {@link LayoutObserver.disconnect | disconnect()} that releases everything.\n *\n * Behavior only: the helper reports *that* layout changed; it never reads or\n * writes styles. Consumers decide what to recompute.\n */\n\n/** Invoked whenever an observed element or the viewport changes size. */\nexport type LayoutCallback = () => void;\n\n/** Constructs a {@link ResizeObserver}; injectable so tests stay deterministic. */\nexport type ResizeObserverFactory = (callback: ResizeObserverCallback) => ResizeObserver;\n\n/** Options for {@link LayoutObserver}. */\nexport interface LayoutObserverOptions {\n /**\n * Factory for the {@link ResizeObserver} used by {@link LayoutObserver.observe}.\n * Defaults to the global constructor; override it in tests, or to no-op in\n * environments where `ResizeObserver` is unavailable.\n */\n resizeObserverFactory?: ResizeObserverFactory;\n}\n\n/**\n * Observes element resizes and/or viewport resizes through a single callback,\n * with guaranteed teardown.\n *\n * @example\n * ```ts\n * #layout = new LayoutObserver(() => this.#reposition());\n *\n * connect() {\n * this.#layout.observe(this.panelTarget);\n * this.#layout.observeViewport();\n * }\n *\n * disconnect() {\n * this.#layout.disconnect();\n * }\n * ```\n */\nexport class LayoutObserver {\n readonly #callback: LayoutCallback;\n readonly #resizeObserverFactory: ResizeObserverFactory | null;\n #resizeObserver: ResizeObserver | null = null;\n #observingViewport = false;\n\n /** Stable bound handler so add/removeEventListener target the same reference. */\n readonly #handleViewportResize = (): void => {\n this.#callback();\n };\n\n constructor(callback: LayoutCallback, options: LayoutObserverOptions = {}) {\n this.#callback = callback;\n this.#resizeObserverFactory =\n options.resizeObserverFactory ??\n (typeof ResizeObserver === \"undefined\" ? null : (cb) => new ResizeObserver(cb));\n }\n\n /**\n * Starts observing an element's size. Repeated calls observe additional\n * elements through the same shared observer. No-ops when no\n * `ResizeObserver` implementation is available.\n */\n observe(element: Element): void {\n if (!this.#resizeObserverFactory) return;\n if (!this.#resizeObserver) {\n this.#resizeObserver = this.#resizeObserverFactory(() => {\n this.#callback();\n });\n }\n this.#resizeObserver.observe(element);\n }\n\n /** Stops observing a single element while leaving any others in place. */\n unobserve(element: Element): void {\n this.#resizeObserver?.unobserve(element);\n }\n\n /** Starts observing viewport resizes. Idempotent: the listener is added once. */\n observeViewport(): void {\n if (this.#observingViewport) return;\n this.#observingViewport = true;\n window.addEventListener(\"resize\", this.#handleViewportResize);\n }\n\n /** Stops observing viewport resizes without affecting element observation. */\n unobserveViewport(): void {\n if (!this.#observingViewport) return;\n this.#observingViewport = false;\n window.removeEventListener(\"resize\", this.#handleViewportResize);\n }\n\n /**\n * Releases every observation: disconnects the {@link ResizeObserver} and\n * removes the viewport listener. Safe to call multiple times. Call this from a\n * controller's `disconnect()`.\n */\n disconnect(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = null;\n this.unobserveViewport();\n }\n}\n","/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","/**\n * Shared `prefers-reduced-motion` lookup for the motion-aware controllers\n *.\n *\n * This one-liner keeps the media query string and the environment guard\n * single-sourced across them. The preference is intentionally re-read on every\n * call — the controllers check it at each animation/scroll start (WCAG 2.2\n * **2.3.3**), so flipping the OS setting takes effect immediately without any\n * listener or cache bookkeeping here.\n */\n\n/**\n * Whether the user currently requests reduced motion.\n *\n * @returns `true` when `(prefers-reduced-motion: reduce)` matches; `false`\n * otherwise, including environments without `window.matchMedia` (treated as\n * \"no preference\").\n */\nexport function prefersReducedMotion(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { BlurDeferral } from \"../utils/blur_deferral\";\nimport { LayoutObserver } from \"../utils/layout_observer\";\nimport { logicalScrollMetrics, physicalScrollDelta } from \"../utils/logical_scroll\";\nimport { prefersReducedMotion } from \"../utils/reduced_motion\";\n\nconst DIRECTION_BUTTON_SELECTOR = \"[data-stimeo--overflow-indicator-direction-param]\";\n\n/**\n * Headless **Overflow Indicator**: detects whether a scroll container can still\n * scroll toward its start and/or end and publishes it as `data-overflow-start` /\n * `data-overflow-end`. No APG widget — a state-detection utility. Consumers draw\n * edge shadows or arrows in CSS to signal \"more content this way\".\n *\n * Markup contract (identifier: `stimeo--overflow-indicator`):\n * <div data-controller=\"stimeo--overflow-indicator\"\n * data-stimeo--overflow-indicator-orientation-value=\"horizontal\">\n * <button type=\"button\" aria-label=\"Prev\"\n * data-stimeo--overflow-indicator-direction-param=\"start\"\n * data-action=\"click->stimeo--overflow-indicator#scrollByPage\">‹</button>\n * <div data-stimeo--overflow-indicator-target=\"viewport\"\n * data-action=\"scroll->stimeo--overflow-indicator#update\"\n * tabindex=\"0\" role=\"region\" aria-label=\"Products\"\n * style=\"overflow-x: auto;\"><!-- items --></div>\n * <button type=\"button\" aria-label=\"Next\"\n * data-stimeo--overflow-indicator-direction-param=\"end\"\n * data-action=\"click->stimeo--overflow-indicator#scrollByPage\">›</button>\n * </div>\n *\n * The viewport's scroll position and size are watched (via the wired `scroll`\n * action, plus `LayoutObserver` for viewport/content resize, a\n * {@link MutationObserver}, and descendant load events). Optional page buttons\n * scroll one logical viewport page at a time (including RTL) and have their\n * disabled state synced to the matching direction's remaining room.\n *\n * `change` dispatches `{ start: boolean, end: boolean }`.\n *\n * @remarks\n * Behavior only — shadows, arrows, and gradients are the consumer's CSS;\n * `data-overflow-*` carry no ARIA semantics. All observers/listeners are released\n * on `disconnect()` (Turbo navigation included). `scrollByPage` scrolls smoothly\n * by default and forces an instant jump under `prefers-reduced-motion`, regardless\n * of the consumer's CSS `scroll-behavior`.\n */\nexport class OverflowIndicatorController extends Controller<HTMLElement> {\n static override targets = [\"viewport\"];\n static override values = {\n orientation: { type: String, default: \"horizontal\" },\n threshold: { type: Number, default: 1 },\n };\n static actions = [\"scrollByPage\", \"update\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly viewportTarget: HTMLElement;\n declare readonly hasViewportTarget: boolean;\n\n declare orientationValue: string;\n declare thresholdValue: number;\n\n readonly #layout = new LayoutObserver(() => {\n if (this.#connected) this.update();\n });\n #connected = false;\n #observedViewport: HTMLElement | null = null;\n readonly #observedContent = new Set<Element>();\n #mutationObserver: MutationObserver | null = null;\n /**\n * Boundary buttons whose native `disabled` is held back while they hold focus.\n *\n * Completing the deferral is what actually disables the button, so the release\n * callback — unlike {@link #cancelPendingButtonDisable} — applies it.\n */\n readonly #pendingButtonDisables = new BlurDeferral<HTMLButtonElement>((button) => {\n this.#restorePendingMarkers(button);\n // If the author disabled it while focus was pending, do not claim ownership.\n if (!button.disabled) this.#disableButton(button);\n });\n /** Last reported room, so `change` fires only on transitions. */\n #state: { start: boolean; end: boolean } | null = null;\n\n override connect(): void {\n this.#connected = true;\n this.#syncViewport();\n }\n\n override disconnect(): void {\n this.#connected = false;\n this.#stopObservingViewport();\n this.#layout.disconnect();\n this.#clearPendingButtonDisables();\n this.#state = null;\n }\n\n viewportTargetConnected(): void {\n this.#syncViewport();\n }\n\n viewportTargetDisconnected(viewport: HTMLElement): void {\n if (this.#observedViewport === viewport) this.#stopObservingViewport();\n this.#syncViewport();\n }\n\n orientationValueChanged(): void {\n if (this.#connected) this.update();\n }\n\n thresholdValueChanged(): void {\n if (this.#connected) this.update();\n }\n\n /**\n * Re-measures remaining scroll room and reflects the state hooks.\n * Public so it can be wired to the viewport's `scroll`.\n */\n update(): void {\n if (!this.hasViewportTarget) return;\n const vp = this.viewportTarget;\n const horizontal = this.orientationValue !== \"vertical\";\n const t = this.#threshold;\n const { position: scrollPos, max: maxScroll } = logicalScrollMetrics(vp, horizontal);\n\n const start = scrollPos > t;\n const end = scrollPos < maxScroll - t;\n\n vp.setAttribute(\"data-overflow-start\", start ? \"true\" : \"false\");\n vp.setAttribute(\"data-overflow-end\", end ? \"true\" : \"false\");\n this.#syncButtons(start, end);\n\n if (!this.#state || this.#state.start !== start || this.#state.end !== end) {\n this.#state = { start, end };\n this.dispatch(\"change\", { detail: { start, end } });\n }\n }\n\n /** Scrolls one viewport page toward the `direction` param (`start`/`end`). */\n scrollByPage(event: Event): void {\n if (!this.hasViewportTarget) return;\n const direction = this.#directionFromEvent(event);\n if (!direction) return;\n if (this.#state && !this.#state[direction]) return;\n\n const vp = this.viewportTarget;\n const horizontal = this.orientationValue !== \"vertical\";\n const page = horizontal ? vp.clientWidth : vp.clientHeight;\n const logicalDelta = direction === \"start\" ? -page : page;\n const delta = physicalScrollDelta(vp, horizontal, logicalDelta);\n const behavior: ScrollBehavior = prefersReducedMotion() ? \"instant\" : \"smooth\";\n\n if (horizontal) {\n vp.scrollBy({ left: delta, behavior });\n } else {\n vp.scrollBy({ top: delta, behavior });\n }\n }\n\n /** Mirrors remaining room onto any direction buttons by toggling `disabled`. */\n #syncButtons(start: boolean, end: boolean): void {\n for (const button of this.#pendingButtonDisables.elements) {\n if (\n !button.isConnected ||\n button.closest(\"[data-controller~='stimeo--overflow-indicator']\") !== this.element\n ) {\n this.#cancelPendingButtonDisable(button);\n }\n }\n const buttons = this.element.querySelectorAll<HTMLButtonElement>(DIRECTION_BUTTON_SELECTOR);\n for (const button of buttons) {\n if (button.closest(\"[data-controller~='stimeo--overflow-indicator']\") !== this.element) {\n continue;\n }\n const direction = button.getAttribute(\"data-stimeo--overflow-indicator-direction-param\");\n if (direction === \"start\") this.#toggleButton(button, start);\n else if (direction === \"end\") this.#toggleButton(button, end);\n }\n }\n\n /**\n * Reflects the remaining room onto a page button's `disabled`, owning only the\n * `disabled` it sets itself via a marker (`data-overflow-indicator-disabled`,\n * like `number-input`/`conditional-fields`). An author-disabled button (e.g. the\n * whole control disabled) is therefore never blindly re-enabled.\n */\n #toggleButton(button: HTMLButtonElement, hasRoom: boolean): void {\n // A restored Turbo snapshot can carry pending markers from the previous visit\n // that this instance never created; release them from the DOM record before\n // deciding, or the displaced `aria-disabled` would never be given back.\n if (\n !this.#pendingButtonDisables.has(button) &&\n button.hasAttribute(\"data-overflow-indicator-pending-disabled\")\n ) {\n this.#cancelPendingButtonDisable(button);\n }\n if (hasRoom) {\n this.#cancelPendingButtonDisable(button);\n if (button.hasAttribute(\"data-overflow-indicator-disabled\")) {\n button.disabled = false;\n button.removeAttribute(\"data-overflow-indicator-disabled\");\n }\n return;\n }\n if (button.disabled) return; // already disabled (possibly by the author) — leave it\n if (document.activeElement === button) {\n this.#deferButtonDisable(button);\n } else {\n this.#disableButton(button);\n }\n }\n\n /**\n * Keeps a boundary button focusable until native blur, exposing its temporary\n * inoperability with `aria-disabled` and making its action a no-op meanwhile.\n */\n #deferButtonDisable(button: HTMLButtonElement): void {\n if (this.#pendingButtonDisables.has(button)) return;\n button.setAttribute(\"data-overflow-indicator-pending-disabled\", \"\");\n // The ownership marker carries the value we displace, so the DOM alone is\n // enough to undo it. A Turbo snapshot is cloned before `disconnect()` runs,\n // so a restored page arrives with these markers while the new instance has\n // no in-memory record of them — an empty marker means \"there was none\".\n button.setAttribute(\n \"data-overflow-indicator-aria-disabled\",\n button.getAttribute(\"aria-disabled\") ?? \"\",\n );\n button.setAttribute(\"aria-disabled\", \"true\");\n this.#pendingButtonDisables.defer(button);\n }\n\n #disableButton(button: HTMLButtonElement): void {\n button.disabled = true;\n button.setAttribute(\"data-overflow-indicator-disabled\", \"\");\n }\n\n /** Cancels a pending disable without applying it, restoring the displaced state. */\n #cancelPendingButtonDisable(button: HTMLButtonElement): void {\n this.#pendingButtonDisables.release(button);\n this.#restorePendingMarkers(button);\n }\n\n /**\n * Drops the pending marker and gives back the `aria-disabled` it displaced.\n *\n * Reads the displaced value from the DOM rather than memory: a Turbo snapshot is\n * cloned before `disconnect()` runs, so a restored page can arrive with markers\n * this instance never wrote.\n */\n #restorePendingMarkers(button: HTMLButtonElement): void {\n button.removeAttribute(\"data-overflow-indicator-pending-disabled\");\n const displaced = button.getAttribute(\"data-overflow-indicator-aria-disabled\");\n if (displaced !== null) {\n button.removeAttribute(\"data-overflow-indicator-aria-disabled\");\n if (button.getAttribute(\"aria-disabled\") === \"true\") {\n if (displaced === \"\") button.removeAttribute(\"aria-disabled\");\n else button.setAttribute(\"aria-disabled\", displaced);\n }\n }\n }\n\n #clearPendingButtonDisables(): void {\n for (const button of this.#pendingButtonDisables.elements) {\n this.#cancelPendingButtonDisable(button);\n }\n }\n\n /** Moves resize/mutation/load observation to the current viewport target. */\n #syncViewport(): void {\n if (!this.#connected) return;\n const next = this.hasViewportTarget ? this.viewportTarget : null;\n if (next === this.#observedViewport) return;\n this.#stopObservingViewport();\n if (!next) return;\n\n this.#observedViewport = next;\n this.#layout.observe(next);\n this.#layout.observeViewport();\n next.addEventListener(\"load\", this.#onContentLoad, true);\n this.#syncContentObservation();\n\n if (typeof MutationObserver !== \"undefined\") {\n this.#mutationObserver = new MutationObserver(() => {\n if (!this.#connected || this.#observedViewport !== next) return;\n this.#syncContentObservation();\n this.update();\n });\n this.#mutationObserver.observe(this.element, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n attributeFilter: [\"class\", \"style\", \"hidden\"],\n });\n }\n this.#state = null;\n this.update();\n }\n\n /** Observes direct content boxes whose resize can change the viewport's scroll extent. */\n #syncContentObservation(): void {\n const next = new Set<Element>(this.#observedViewport?.children ?? []);\n for (const content of this.#observedContent) {\n if (!next.has(content)) {\n this.#layout.unobserve(content);\n this.#observedContent.delete(content);\n }\n }\n for (const content of next) {\n if (!this.#observedContent.has(content)) {\n this.#observedContent.add(content);\n this.#layout.observe(content);\n }\n }\n }\n\n #stopObservingViewport(): void {\n this.#mutationObserver?.disconnect();\n this.#mutationObserver = null;\n this.#observedViewport?.removeEventListener(\"load\", this.#onContentLoad, true);\n if (this.#observedViewport) this.#layout.unobserve(this.#observedViewport);\n for (const content of this.#observedContent) this.#layout.unobserve(content);\n this.#observedContent.clear();\n this.#observedViewport = null;\n this.#layout.unobserveViewport();\n }\n\n readonly #onContentLoad = (): void => {\n if (this.#connected) this.update();\n };\n\n get #threshold(): number {\n const value = this.thresholdValue;\n return Number.isFinite(value) ? Math.max(0, value) : 1;\n }\n\n #directionFromEvent(event: Event): \"start\" | \"end\" | null {\n const params = (event as Event & { params?: { direction?: unknown } }).params;\n const direction = params?.direction;\n return direction === \"start\" || direction === \"end\" ? direction : null;\n }\n}\n"]}
|