stimeo-ui 0.10.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.
@@ -1,19 +1,108 @@
1
1
  import { Controller } from '@hotwired/stimulus';
2
2
 
3
+ // src/controllers/preview_guard_controller.ts
4
+
5
+ // src/utils/before_cache_reset.ts
6
+ var BeforeCacheReset = class _BeforeCacheReset {
7
+ /** Every subscribed instance, iterated by the one shared document listener. */
8
+ static #subscribers = /* @__PURE__ */ new Set();
9
+ /** The shared listener; installed while at least one instance is subscribed. */
10
+ static #onBeforeCache = () => {
11
+ for (const subscriber of _BeforeCacheReset.#subscribers) subscriber.#rewind();
12
+ };
13
+ #rewind;
14
+ /** @param rewind - the pass that returns this controller's state to its initial form. */
15
+ constructor(rewind) {
16
+ this.#rewind = rewind;
17
+ }
18
+ /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */
19
+ activate() {
20
+ const first = _BeforeCacheReset.#subscribers.size === 0;
21
+ _BeforeCacheReset.#subscribers.add(this);
22
+ if (first) {
23
+ document.addEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
24
+ }
25
+ }
26
+ /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */
27
+ deactivate() {
28
+ _BeforeCacheReset.#subscribers.delete(this);
29
+ if (_BeforeCacheReset.#subscribers.size > 0) return;
30
+ document.removeEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
31
+ }
32
+ };
33
+
34
+ // src/utils/style_property_lease.ts
35
+ var StylePropertyLease = class {
36
+ #property;
37
+ #records = /* @__PURE__ */ new Map();
38
+ /** @param property - The CSS property whose temporary values this lease owns. */
39
+ constructor(property) {
40
+ this.#property = property;
41
+ }
42
+ /** Writes or removes the leased declaration while preserving its authored value. */
43
+ write(element, value, priority = "") {
44
+ const existing = this.#records.get(element);
45
+ if (existing) {
46
+ existing.writtenValue = value;
47
+ existing.writtenPriority = value === null ? "" : priority;
48
+ } else {
49
+ this.#records.set(element, {
50
+ originalValue: element.style.getPropertyValue(this.#property),
51
+ originalPriority: element.style.getPropertyPriority(this.#property),
52
+ writtenValue: value,
53
+ writtenPriority: value === null ? "" : priority
54
+ });
55
+ }
56
+ this.#reflect(element, value, priority);
57
+ }
58
+ /** Returns one lease without overwriting a later consumer declaration. */
59
+ return(element) {
60
+ const record = this.#records.get(element);
61
+ if (!record) return;
62
+ this.#records.delete(element);
63
+ const style = element.style;
64
+ const stillOwned = style.getPropertyValue(this.#property) === (record.writtenValue ?? "") && style.getPropertyPriority(this.#property) === record.writtenPriority;
65
+ if (stillOwned) {
66
+ this.#reflect(element, record.originalValue, record.originalPriority);
67
+ }
68
+ }
69
+ /** Returns every outstanding declaration lease. */
70
+ returnAll() {
71
+ for (const element of Array.from(this.#records.keys())) this.return(element);
72
+ }
73
+ /** Reflects only a real declaration transition. */
74
+ #reflect(element, value, priority) {
75
+ const style = element.style;
76
+ const nextValue = value ?? "";
77
+ const nextPriority = value === null ? "" : priority;
78
+ if (style.getPropertyValue(this.#property) === nextValue && style.getPropertyPriority(this.#property) === nextPriority) {
79
+ return;
80
+ }
81
+ if (value === null) style.removeProperty(this.#property);
82
+ else style.setProperty(this.#property, value, priority);
83
+ }
84
+ };
85
+
3
86
  // src/controllers/preview_guard_controller.ts
4
87
  var PreviewGuardController = class extends Controller {
5
88
  static values = {
6
- placeholder: { type: String, default: "" },
7
- mode: { type: String, default: "hide" }
89
+ placeholder: { type: String, default: "" }
8
90
  };
9
91
  static events = ["hide", "show"];
92
+ #visibility = new StylePropertyLease("visibility");
93
+ #beforeCache = new BeforeCacheReset(() => this.#restore());
10
94
  #observer = null;
95
+ #connected = false;
11
96
  #hidden = false;
12
- /** Saved inline visibility (hide mode), restored on show. */
13
- #savedVisibility = "";
14
- /** Saved text (placeholder mode); non-null marks that text — not visibility — was swapped. */
15
- #savedText = null;
97
+ /** Child nodes a placeholder displaced; non-null marks that content — not visibility — was swapped. */
98
+ #savedNodes = null;
99
+ /** The descendant that held focus when the guard went up, so show can hand it back. */
100
+ #focused = null;
16
101
  connect() {
102
+ this.#connected = true;
103
+ if (this.#hidden) this.#reguard();
104
+ else this.element.removeAttribute("data-preview-hidden");
105
+ this.#beforeCache.activate();
17
106
  if (typeof MutationObserver !== "undefined") {
18
107
  this.#observer = new MutationObserver(() => this.#sync());
19
108
  this.#observer.observe(document.documentElement, {
@@ -24,44 +113,115 @@ var PreviewGuardController = class extends Controller {
24
113
  this.#sync();
25
114
  }
26
115
  disconnect() {
116
+ this.#connected = false;
117
+ this.#beforeCache.deactivate();
27
118
  this.#observer?.disconnect();
28
119
  this.#observer = null;
29
- this.#restore();
30
120
  }
31
- /** Reflects the current `data-turbo-preview` state onto the element. */
121
+ /**
122
+ * Re-guards to match a `placeholder` changed at runtime — the value is the content on
123
+ * display while the guard is up, so a morph that swaps it must not leave the old one.
124
+ */
125
+ placeholderValueChanged() {
126
+ if (!this.#connected || !this.#hidden) return;
127
+ this.#reguard();
128
+ }
129
+ /**
130
+ * Reflects the current `data-turbo-preview` state onto the element.
131
+ *
132
+ * @stimeoRenderRoot
133
+ */
32
134
  #sync() {
33
135
  const previewing = document.documentElement.hasAttribute("data-turbo-preview");
34
136
  if (previewing && !this.#hidden) this.#hide();
35
137
  else if (!previewing && this.#hidden) this.#show();
36
138
  }
37
139
  #hide() {
140
+ this.#focused = this.#focusedInside();
141
+ this.#applyGuard();
142
+ this.dispatch("hide", { detail: {} });
143
+ }
144
+ /** Puts the guard up in the form the current `placeholder` calls for. */
145
+ #applyGuard() {
38
146
  this.#hidden = true;
39
- if (this.modeValue === "placeholder") {
40
- this.#savedText = this.element.textContent;
41
- this.element.textContent = this.placeholderValue;
147
+ if (this.placeholderValue === "") {
148
+ this.#visibility.write(this.element, "hidden");
42
149
  } else {
43
- this.#savedVisibility = this.element.style.visibility;
44
- this.element.style.visibility = "hidden";
150
+ this.#savedNodes = document.createDocumentFragment();
151
+ this.#savedNodes.append(...this.element.childNodes);
152
+ this.element.textContent = this.placeholderValue;
45
153
  }
46
154
  this.element.setAttribute("data-preview-hidden", "true");
47
- this.dispatch("hide", { detail: {} });
155
+ }
156
+ /**
157
+ * Re-forms a guard that is already up so it matches the current `placeholder`.
158
+ *
159
+ * No event: `hide` reports that the guard went up, and it has not come down. Swapping
160
+ * one stand-in text for another writes only that text — putting the held content back
161
+ * first would reconnect the whole subtree for an instant. Only a change of *form* —
162
+ * to or from the empty placeholder — has to revert, and the focus the guard is holding
163
+ * carries across it rather than being handed back and taken again.
164
+ */
165
+ #reguard() {
166
+ if (this.#savedNodes && this.placeholderValue !== "") {
167
+ this.element.textContent = this.placeholderValue;
168
+ return;
169
+ }
170
+ const held = this.#focused;
171
+ this.#revert();
172
+ this.#applyGuard();
173
+ this.#focused = held;
48
174
  }
49
175
  #show() {
50
176
  this.#restore();
51
177
  this.dispatch("show", { detail: {} });
52
178
  }
53
- /** Reverts the guard. Safe to call when not hidden (no-op) — used by show and teardown. */
179
+ /** Reverts the guard and hands focus back. Used by show and by the snapshot rewind. */
54
180
  #restore() {
55
- if (!this.#hidden) return;
181
+ this.#revert();
182
+ this.#refocus();
183
+ }
184
+ /**
185
+ * Puts the element back the way the guard found it.
186
+ *
187
+ * Every step is a no-op on an element this controller never guarded: the lease returns
188
+ * only declarations it recorded, and the hook is removed whether or not it is there.
189
+ */
190
+ #revert() {
56
191
  this.#hidden = false;
57
- if (this.#savedText !== null) {
58
- this.element.textContent = this.#savedText;
59
- this.#savedText = null;
192
+ if (this.#savedNodes) {
193
+ this.element.textContent = "";
194
+ this.element.append(this.#savedNodes);
195
+ this.#savedNodes = null;
60
196
  } else {
61
- this.element.style.visibility = this.#savedVisibility;
197
+ this.#visibility.return(this.element);
62
198
  }
63
199
  this.element.removeAttribute("data-preview-hidden");
64
200
  }
201
+ /**
202
+ * The focused element the guard is about to make unfocusable, if any.
203
+ *
204
+ * The element itself counts as well as its descendants: guarding takes focus either way
205
+ * — a `visibility: hidden` subtree cannot hold it, and a placeholder displaces the nodes
206
+ * outright — so the browser drops focus to `<body>` the moment the guard goes up.
207
+ */
208
+ #focusedInside() {
209
+ const active = document.activeElement;
210
+ return active instanceof HTMLElement && this.element.contains(active) ? active : null;
211
+ }
212
+ /**
213
+ * Hands focus back to the element the guard took it from.
214
+ *
215
+ * Only when that element is still in the document and focus has not moved on since —
216
+ * anything else is the user's or another controller's, and putting it back would be
217
+ * taking it.
218
+ */
219
+ #refocus() {
220
+ const target = this.#focused;
221
+ this.#focused = null;
222
+ if (!target?.isConnected || document.activeElement !== document.body) return;
223
+ target.focus();
224
+ }
65
225
  };
66
226
 
67
227
  export { PreviewGuardController };
@@ -1,12 +1,158 @@
1
1
  import { Controller } from '@hotwired/stimulus';
2
2
 
3
+ // src/controllers/reading_progress_controller.ts
4
+
5
+ // src/utils/before_cache_reset.ts
6
+ var BeforeCacheReset = class _BeforeCacheReset {
7
+ /** Every subscribed instance, iterated by the one shared document listener. */
8
+ static #subscribers = /* @__PURE__ */ new Set();
9
+ /** The shared listener; installed while at least one instance is subscribed. */
10
+ static #onBeforeCache = () => {
11
+ for (const subscriber of _BeforeCacheReset.#subscribers) subscriber.#rewind();
12
+ };
13
+ #rewind;
14
+ /** @param rewind - the pass that returns this controller's state to its initial form. */
15
+ constructor(rewind) {
16
+ this.#rewind = rewind;
17
+ }
18
+ /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */
19
+ activate() {
20
+ const first = _BeforeCacheReset.#subscribers.size === 0;
21
+ _BeforeCacheReset.#subscribers.add(this);
22
+ if (first) {
23
+ document.addEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
24
+ }
25
+ }
26
+ /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */
27
+ deactivate() {
28
+ _BeforeCacheReset.#subscribers.delete(this);
29
+ if (_BeforeCacheReset.#subscribers.size > 0) return;
30
+ document.removeEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
31
+ }
32
+ };
33
+
34
+ // src/utils/layout_observer.ts
35
+ var LayoutObserver = class {
36
+ #callback;
37
+ #resizeObserverFactory;
38
+ #resizeObserver = null;
39
+ #observingViewport = false;
40
+ /** Stable bound handler so add/removeEventListener target the same reference. */
41
+ #handleViewportResize = () => {
42
+ this.#callback();
43
+ };
44
+ constructor(callback, options = {}) {
45
+ this.#callback = callback;
46
+ this.#resizeObserverFactory = options.resizeObserverFactory ?? (typeof ResizeObserver === "undefined" ? null : (cb) => new ResizeObserver(cb));
47
+ }
48
+ /**
49
+ * Starts observing an element's size. Repeated calls observe additional
50
+ * elements through the same shared observer. No-ops when no
51
+ * `ResizeObserver` implementation is available.
52
+ */
53
+ observe(element) {
54
+ if (!this.#resizeObserverFactory) return;
55
+ if (!this.#resizeObserver) {
56
+ this.#resizeObserver = this.#resizeObserverFactory(() => {
57
+ this.#callback();
58
+ });
59
+ }
60
+ this.#resizeObserver.observe(element);
61
+ }
62
+ /** Stops observing a single element while leaving any others in place. */
63
+ unobserve(element) {
64
+ this.#resizeObserver?.unobserve(element);
65
+ }
66
+ /** Starts observing viewport resizes. Idempotent: the listener is added once. */
67
+ observeViewport() {
68
+ if (this.#observingViewport) return;
69
+ this.#observingViewport = true;
70
+ window.addEventListener("resize", this.#handleViewportResize);
71
+ }
72
+ /** Stops observing viewport resizes without affecting element observation. */
73
+ unobserveViewport() {
74
+ if (!this.#observingViewport) return;
75
+ this.#observingViewport = false;
76
+ window.removeEventListener("resize", this.#handleViewportResize);
77
+ }
78
+ /**
79
+ * Releases every observation: disconnects the {@link ResizeObserver} and
80
+ * removes the viewport listener. Safe to call multiple times. Call this from a
81
+ * controller's `disconnect()`.
82
+ */
83
+ disconnect() {
84
+ this.#resizeObserver?.disconnect();
85
+ this.#resizeObserver = null;
86
+ this.unobserveViewport();
87
+ }
88
+ };
89
+
90
+ // src/utils/style_property_lease.ts
91
+ var StylePropertyLease = class {
92
+ #property;
93
+ #records = /* @__PURE__ */ new Map();
94
+ /** @param property - The CSS property whose temporary values this lease owns. */
95
+ constructor(property) {
96
+ this.#property = property;
97
+ }
98
+ /** Writes or removes the leased declaration while preserving its authored value. */
99
+ write(element, value, priority = "") {
100
+ const existing = this.#records.get(element);
101
+ if (existing) {
102
+ existing.writtenValue = value;
103
+ existing.writtenPriority = value === null ? "" : priority;
104
+ } else {
105
+ this.#records.set(element, {
106
+ originalValue: element.style.getPropertyValue(this.#property),
107
+ originalPriority: element.style.getPropertyPriority(this.#property),
108
+ writtenValue: value,
109
+ writtenPriority: value === null ? "" : priority
110
+ });
111
+ }
112
+ this.#reflect(element, value, priority);
113
+ }
114
+ /** Returns one lease without overwriting a later consumer declaration. */
115
+ return(element) {
116
+ const record = this.#records.get(element);
117
+ if (!record) return;
118
+ this.#records.delete(element);
119
+ const style = element.style;
120
+ const stillOwned = style.getPropertyValue(this.#property) === (record.writtenValue ?? "") && style.getPropertyPriority(this.#property) === record.writtenPriority;
121
+ if (stillOwned) {
122
+ this.#reflect(element, record.originalValue, record.originalPriority);
123
+ }
124
+ }
125
+ /** Returns every outstanding declaration lease. */
126
+ returnAll() {
127
+ for (const element of Array.from(this.#records.keys())) this.return(element);
128
+ }
129
+ /** Reflects only a real declaration transition. */
130
+ #reflect(element, value, priority) {
131
+ const style = element.style;
132
+ const nextValue = value ?? "";
133
+ const nextPriority = value === null ? "" : priority;
134
+ if (style.getPropertyValue(this.#property) === nextValue && style.getPropertyPriority(this.#property) === nextPriority) {
135
+ return;
136
+ }
137
+ if (value === null) style.removeProperty(this.#property);
138
+ else style.setProperty(this.#property, value, priority);
139
+ }
140
+ };
141
+
3
142
  // src/controllers/reading_progress_controller.ts
4
143
  var PROGRESS_PROPERTY = "--stimeo--reading-progress";
5
144
  var ReadingProgressController = class extends Controller {
6
145
  static events = ["change", "complete"];
146
+ /** Owns both faces of the published property so teardown can hand them back. */
147
+ #lease = new StylePropertyLease(PROGRESS_PROPERTY);
148
+ /** The article's own box and the viewport: either changes the span. */
149
+ #layout = new LayoutObserver(() => this.#onScroll());
150
+ #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());
7
151
  #frame = null;
8
152
  /** Last published progress, so `change`/`complete` fire only on movement. */
9
153
  #progress = -1;
154
+ /** False until the connect frame has run: `complete` needs real reading. */
155
+ #baselined = false;
10
156
  #onScroll = () => {
11
157
  if (this.#frame !== null) return;
12
158
  this.#frame = requestAnimationFrame(() => {
@@ -16,20 +162,45 @@ var ReadingProgressController = class extends Controller {
16
162
  };
17
163
  connect() {
18
164
  this.#progress = -1;
165
+ this.#baselined = false;
19
166
  window.addEventListener("scroll", this.#onScroll, { passive: true, capture: true });
20
- window.addEventListener("resize", this.#onScroll, { passive: true });
167
+ this.#layout.observe(this.element);
168
+ this.#layout.observeViewport();
169
+ this.#beforeCache.activate();
21
170
  this.#measure();
171
+ this.#frame = requestAnimationFrame(() => {
172
+ this.#frame = null;
173
+ this.#measure();
174
+ this.#baselined = true;
175
+ });
22
176
  }
23
177
  disconnect() {
24
178
  window.removeEventListener("scroll", this.#onScroll, { capture: true });
25
- window.removeEventListener("resize", this.#onScroll);
179
+ this.#layout.disconnect();
180
+ this.#beforeCache.deactivate();
181
+ this.#cancelFrame();
182
+ this.#lease.returnAll();
183
+ }
184
+ /**
185
+ * Hands both declarations back before the page is snapshotted, so a restored
186
+ * page starts from the authored DOM rather than from someone else's progress.
187
+ * The baseline goes back with them: a cancelled visit leaves this page on
188
+ * screen, and the next measurement has to publish afresh rather than match a
189
+ * value that has already been handed back.
190
+ */
191
+ #rewindForCache() {
192
+ this.#cancelFrame();
193
+ this.#lease.returnAll();
194
+ this.#progress = -1;
195
+ }
196
+ #cancelFrame() {
26
197
  if (this.#frame !== null) cancelAnimationFrame(this.#frame);
27
198
  this.#frame = null;
28
- document.documentElement.style.removeProperty(PROGRESS_PROPERTY);
29
199
  }
30
200
  /** Computes and publishes the progress; emits on movement only. */
31
201
  #measure() {
32
202
  const rect = this.element.getBoundingClientRect();
203
+ if (rect.width === 0 && rect.height === 0) return;
33
204
  const span = rect.height - window.innerHeight;
34
205
  const raw = span > 0 ? -rect.top / span : rect.top <= 0 ? 1 : 0;
35
206
  const progress = Math.min(1, Math.max(0, raw));
@@ -37,10 +208,10 @@ var ReadingProgressController = class extends Controller {
37
208
  const previous = this.#progress;
38
209
  this.#progress = progress;
39
210
  const value = String(progress);
40
- this.element.style.setProperty(PROGRESS_PROPERTY, value);
41
- document.documentElement.style.setProperty(PROGRESS_PROPERTY, value);
211
+ this.#lease.write(this.element, value);
212
+ this.#lease.write(document.documentElement, value);
42
213
  this.dispatch("change", { detail: { progress } });
43
- if (progress === 1 && previous !== -1) this.dispatch("complete");
214
+ if (progress === 1 && previous !== -1 && this.#baselined) this.dispatch("complete");
44
215
  }
45
216
  };
46
217
 
@@ -12,6 +12,20 @@ function isReservedArrowChord(event, allow = []) {
12
12
  if (!event.key.startsWith("Arrow")) return false;
13
13
  return event.altKey && !allow.includes("alt") || event.ctrlKey && !allow.includes("ctrl") || event.metaKey && !allow.includes("meta") || event.shiftKey && !allow.includes("shift");
14
14
  }
15
+ function hasModifierChord(event) {
16
+ return event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
17
+ }
18
+
19
+ // src/utils/focus_candidate.ts
20
+ function inheritsFieldsetDisabled(control) {
21
+ let fieldset = control.closest("fieldset[disabled]");
22
+ while (fieldset) {
23
+ const legend = Array.from(fieldset.children).find((child) => child.tagName === "LEGEND");
24
+ if (!legend?.contains(control)) return true;
25
+ fieldset = fieldset.parentElement?.closest("fieldset[disabled]") ?? null;
26
+ }
27
+ return false;
28
+ }
15
29
 
16
30
  // src/utils/microtask_coalescer.ts
17
31
  var MicrotaskCoalescer = class {
@@ -88,6 +102,7 @@ function rovingMove(current, length, delta, wrap) {
88
102
  }
89
103
 
90
104
  // src/controllers/roving_controller.ts
105
+ var STATE_ATTRIBUTES = ["disabled", "hidden"];
91
106
  var RovingController = class extends Controller {
92
107
  static targets = ["item"];
93
108
  static values = {
@@ -97,12 +112,14 @@ var RovingController = class extends Controller {
97
112
  };
98
113
  static events = ["change"];
99
114
  #roving = new RovingTabindex(() => this.itemTargets);
100
- #reconcile = new MicrotaskCoalescer(() => this.#ensureTabStop());
115
+ #reconcile = new MicrotaskCoalescer(() => this.#ensureTabStop(true));
101
116
  #connected = false;
117
+ #observer = null;
102
118
  connect() {
103
- this.#ensureTabStop();
119
+ this.#ensureTabStop(false);
104
120
  this.element.addEventListener("keydown", this.#onKeydown);
105
121
  this.element.addEventListener("focusin", this.#onFocusin);
122
+ this.#watchState();
106
123
  this.#connected = true;
107
124
  this.#reconcile.activate();
108
125
  }
@@ -111,6 +128,8 @@ var RovingController = class extends Controller {
111
128
  this.#reconcile.cancel();
112
129
  this.element.removeEventListener("keydown", this.#onKeydown);
113
130
  this.element.removeEventListener("focusin", this.#onFocusin);
131
+ this.#observer?.disconnect();
132
+ this.#observer = null;
114
133
  }
115
134
  /** Drops a runtime-added item from the Tab sequence before batch reconciliation. */
116
135
  itemTargetConnected(item) {
@@ -126,10 +145,9 @@ var RovingController = class extends Controller {
126
145
  #onKeydown = (event) => {
127
146
  if (event.defaultPrevented) return;
128
147
  if (isReservedArrowChord(event)) return;
129
- const items = this.itemTargets;
148
+ if (event.isComposing) return;
130
149
  const current = this.#indexOf(event.target);
131
150
  if (current === -1) return;
132
- const length = items.length;
133
151
  const wrap = this.wrapValue ? "wrap" : "clamp";
134
152
  const orientation = this.orientationValue;
135
153
  const horizontal = orientation === "horizontal" || orientation === "both";
@@ -139,16 +157,16 @@ var RovingController = class extends Controller {
139
157
  const backwardKey = rtl ? "ArrowRight" : "ArrowLeft";
140
158
  let next;
141
159
  if (horizontal && event.key === forwardKey || vertical && event.key === "ArrowDown") {
142
- next = rovingMove(current, length, 1, wrap);
160
+ next = this.#step(current, 1, wrap);
143
161
  } else if (horizontal && event.key === backwardKey || vertical && event.key === "ArrowUp") {
144
- next = rovingMove(current, length, -1, wrap);
145
- } else if (this.homeEndValue && event.key === "Home") {
146
- next = 0;
147
- } else if (this.homeEndValue && event.key === "End") {
148
- next = length - 1;
162
+ next = this.#step(current, -1, wrap);
163
+ } else if (this.homeEndValue && (event.key === "Home" || event.key === "End")) {
164
+ if (hasModifierChord(event)) return;
165
+ next = event.key === "Home" ? this.#firstReachable() : this.#lastReachable();
149
166
  } else {
150
167
  return;
151
168
  }
169
+ if (next === -1) return;
152
170
  event.preventDefault();
153
171
  this.#activate(next, true);
154
172
  };
@@ -159,7 +177,8 @@ var RovingController = class extends Controller {
159
177
  */
160
178
  #onFocusin = (event) => {
161
179
  const index = this.#indexOf(event.target);
162
- if (index !== -1) this.#activate(index, false);
180
+ if (index === -1 || !this.#reachable(index)) return;
181
+ this.#activate(index, false);
163
182
  };
164
183
  /** Resolves the item index owning an event target (the item or a descendant). */
165
184
  #indexOf(target) {
@@ -175,10 +194,104 @@ var RovingController = class extends Controller {
175
194
  this.dispatch("change", { detail: { index, item: this.itemTargets[index] } });
176
195
  }
177
196
  }
178
- /** Keeps the first existing Tab stop, falling back to the first live item. */
179
- #ensureTabStop() {
197
+ /**
198
+ * Keeps the Tab stop on a reachable item.
199
+ *
200
+ * `followFocus` is on for re-establishment only: an item added and focused in
201
+ * the same task has already claimed the stop through `focusin`, and the batch
202
+ * that follows must not hand it back to the first item. `connect()` passes it
203
+ * off so the authored DOM decides the initial stop. With nothing reachable the
204
+ * DOM is left as it is — a group inside a collapsed region gets its stop back
205
+ * when the region opens, instead of losing it for good.
206
+ */
207
+ #ensureTabStop(followFocus) {
208
+ const items = this.itemTargets;
209
+ const focused = followFocus ? items.findIndex((item, i) => item === document.activeElement && this.#reachable(i)) : -1;
180
210
  const active = this.#roving.activeIndex;
181
- this.#roving.setActive(active === -1 ? 0 : active);
211
+ const kept = active !== -1 && this.#reachable(active) ? active : -1;
212
+ const index = focused !== -1 ? focused : kept !== -1 ? kept : this.#firstReachable();
213
+ if (index === -1) return;
214
+ this.#roving.setActive(index);
215
+ }
216
+ /**
217
+ * Resolves the next reachable index in `delta`'s direction, honouring `wrap`.
218
+ *
219
+ * An arrow on the widget's own axis is the widget's to consume even when the
220
+ * position does not change, so a clamped end resolves to the current item
221
+ * rather than to nothing. An unreachable origin escapes to the first reachable
222
+ * item instead of sitting in a dead end, and `-1` is left for the one case that
223
+ * really is not ours: no reachable item anywhere.
224
+ */
225
+ #step(current, delta, wrap) {
226
+ const length = this.itemTargets.length;
227
+ let index = current;
228
+ for (let taken = 0; taken < length; taken += 1) {
229
+ const candidate = rovingMove(index, length, delta, wrap);
230
+ if (candidate === index) break;
231
+ index = candidate;
232
+ if (this.#reachable(index)) return index;
233
+ }
234
+ return this.#reachable(current) ? current : this.#firstReachable();
235
+ }
236
+ /** Index of the first reachable item, or `-1`. */
237
+ #firstReachable() {
238
+ return this.itemTargets.findIndex((_item, i) => this.#reachable(i));
239
+ }
240
+ /** Index of the last reachable item, or `-1`. */
241
+ #lastReachable() {
242
+ for (let i = this.itemTargets.length - 1; i >= 0; i -= 1) {
243
+ if (this.#reachable(i)) return i;
244
+ }
245
+ return -1;
246
+ }
247
+ /**
248
+ * Whether the item at `index` can hold the Tab stop and take focus.
249
+ *
250
+ * `aria-disabled` is deliberately not consulted: it keeps an item reachable and
251
+ * only suppresses activation, which this part does not own.
252
+ */
253
+ #reachable(index) {
254
+ const item = this.itemTargets[index];
255
+ if (!item) return false;
256
+ if (this.#hidden(item)) return false;
257
+ if (!("disabled" in item)) return true;
258
+ if (item.disabled) return false;
259
+ return !inheritsFieldsetDisabled(item);
260
+ }
261
+ /**
262
+ * Whether `item`, or anything between it and the container, is `hidden`.
263
+ *
264
+ * The walk stops at the container on purpose: a group inside a hidden region is
265
+ * already out of the page's Tab order, and calling every item unreachable there
266
+ * would drop the stop with nothing left to restore it — the ancestor lies
267
+ * outside the subtree whose state attributes are watched.
268
+ */
269
+ #hidden(item) {
270
+ let node = item;
271
+ while (node && node !== this.element) {
272
+ if (node.hasAttribute("hidden")) return true;
273
+ node = node.parentElement;
274
+ }
275
+ return false;
276
+ }
277
+ /**
278
+ * Watches the attributes that decide reachability, so disabling the item that
279
+ * holds the Tab stop hands it to another one instead of taking the whole set
280
+ * out of the Tab sequence. An enclosing `fieldset` disables items from outside
281
+ * the observed subtree, so each one's own `disabled` is watched too.
282
+ */
283
+ #watchState() {
284
+ if (typeof MutationObserver === "undefined") return;
285
+ const observer = new MutationObserver(() => this.#reconcile.schedule());
286
+ observer.observe(this.element, {
287
+ subtree: true,
288
+ attributes: true,
289
+ attributeFilter: STATE_ATTRIBUTES
290
+ });
291
+ for (let fieldset = this.element.parentElement?.closest("fieldset") ?? null; fieldset; fieldset = fieldset.parentElement?.closest("fieldset") ?? null) {
292
+ observer.observe(fieldset, { attributes: true, attributeFilter: ["disabled"] });
293
+ }
294
+ this.#observer = observer;
182
295
  }
183
296
  };
184
297