@gustavogalveza/design-system 0.2.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +258 -149
  2. package/README.md +392 -297
  3. package/package.json +51 -51
  4. package/src/behaviors/fab-menu.js +19 -3
  5. package/src/behaviors/navigation-rail.d.ts +52 -0
  6. package/src/behaviors/navigation-rail.js +445 -0
  7. package/src/behaviors/search.js +28 -1
  8. package/src/behaviors/tooltip.js +8 -3
  9. package/src/components/app-bar.css +58 -55
  10. package/src/components/badge.css +31 -18
  11. package/src/components/bottom-sheet.css +45 -21
  12. package/src/components/button-group.css +71 -20
  13. package/src/components/button.css +159 -63
  14. package/src/components/card.css +235 -31
  15. package/src/components/carousel.css +285 -60
  16. package/src/components/checkbox.css +41 -27
  17. package/src/components/chip.css +260 -70
  18. package/src/components/date-picker.css +132 -46
  19. package/src/components/dialog.css +130 -20
  20. package/src/components/divider.css +38 -10
  21. package/src/components/extended-fab.css +58 -17
  22. package/src/components/fab-menu.css +69 -15
  23. package/src/components/fab.css +73 -9
  24. package/src/components/field.css +252 -23
  25. package/src/components/icon-button.css +138 -77
  26. package/src/components/list.css +74 -20
  27. package/src/components/loading-indicator.css +134 -104
  28. package/src/components/menu.css +37 -29
  29. package/src/components/navigation-bar.css +24 -13
  30. package/src/components/navigation-drawer.css +38 -32
  31. package/src/components/navigation-rail.css +507 -11
  32. package/src/components/progress.css +87 -18
  33. package/src/components/radio.css +72 -11
  34. package/src/components/search.css +54 -32
  35. package/src/components/segmented-button.css +53 -44
  36. package/src/components/side-sheet.css +78 -36
  37. package/src/components/slider.css +680 -103
  38. package/src/components/snackbar.css +105 -27
  39. package/src/components/split-button.css +191 -132
  40. package/src/components/surface.css +156 -28
  41. package/src/components/switch.css +109 -18
  42. package/src/components/tabs.css +109 -49
  43. package/src/components/time-picker.css +165 -55
  44. package/src/components/toolbar.css +27 -6
  45. package/src/components/tooltip.css +12 -2
package/package.json CHANGED
@@ -1,51 +1,51 @@
1
- {
2
- "name": "@gustavogalveza/design-system",
3
- "version": "0.2.0",
4
- "description": "Implementación independiente y no oficial de M3 Expressive: tokens, CSS y HTML nativo, sin framework ni runtime obligatorio",
5
- "license": "MIT",
6
- "author": "gustavogalveza",
7
- "homepage": "https://github.com/Gustavogalvez/design-system#readme",
8
- "repository": {
9
- "type": "git",
10
- "url": "git+https://github.com/Gustavogalvez/design-system.git"
11
- },
12
- "bugs": {
13
- "url": "https://github.com/Gustavogalvez/design-system/issues"
14
- },
15
- "keywords": [
16
- "material-design",
17
- "material-3",
18
- "m3",
19
- "m3-expressive",
20
- "design-system",
21
- "css",
22
- "design-tokens",
23
- "accessibility",
24
- "a11y"
25
- ],
26
- "type": "module",
27
- "engines": {
28
- "node": ">=18"
29
- },
30
- "publishConfig": {
31
- "access": "public"
32
- },
33
- "files": [
34
- "src",
35
- "LICENSE",
36
- "README.md",
37
- "CHANGELOG.md"
38
- ],
39
- "sideEffects": [
40
- "*.css",
41
- "./src/behaviors/*.js"
42
- ],
43
- "exports": {
44
- ".": "./src/index.css",
45
- "./index.css": "./src/index.css",
46
- "./tokens.css": "./src/tokens.css",
47
- "./colors.css": "./src/colors.css",
48
- "./src/*": "./src/*",
49
- "./package.json": "./package.json"
50
- }
51
- }
1
+ {
2
+ "name": "@gustavogalveza/design-system",
3
+ "version": "0.4.1",
4
+ "description": "Implementación independiente y no oficial de M3 Expressive: tokens, CSS y HTML nativo, sin framework ni runtime obligatorio",
5
+ "license": "MIT",
6
+ "author": "gustavogalveza",
7
+ "homepage": "https://github.com/Gustavogalvez/design-system#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Gustavogalvez/design-system.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/Gustavogalvez/design-system/issues"
14
+ },
15
+ "keywords": [
16
+ "material-design",
17
+ "material-3",
18
+ "m3",
19
+ "m3-expressive",
20
+ "design-system",
21
+ "css",
22
+ "design-tokens",
23
+ "accessibility",
24
+ "a11y"
25
+ ],
26
+ "type": "module",
27
+ "engines": {
28
+ "node": ">=18"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "files": [
34
+ "src",
35
+ "LICENSE",
36
+ "README.md",
37
+ "CHANGELOG.md"
38
+ ],
39
+ "sideEffects": [
40
+ "*.css",
41
+ "./src/behaviors/*.js"
42
+ ],
43
+ "exports": {
44
+ ".": "./src/index.css",
45
+ "./index.css": "./src/index.css",
46
+ "./tokens.css": "./src/tokens.css",
47
+ "./colors.css": "./src/colors.css",
48
+ "./src/*": "./src/*",
49
+ "./package.json": "./package.json"
50
+ }
51
+ }
@@ -184,7 +184,13 @@ export class FabMenu {
184
184
  ? opener
185
185
  : this.trigger;
186
186
  target.focus({ preventScroll: true });
187
- } else if (this.root.contains(document.activeElement)) {
187
+ } else if (
188
+ this.root.contains(document.activeElement) &&
189
+ document.activeElement !== this.trigger
190
+ ) {
191
+ /* Sin `restoreFocus` el foco no debe quedarse dentro de una lista que
192
+ se cierra; el disparador es la excepción: `Tab` lo deja anclado para
193
+ que el navegador continúe desde ahí. */
188
194
  document.activeElement.blur();
189
195
  }
190
196
 
@@ -208,6 +214,7 @@ export class FabMenu {
208
214
  cancelFocusFrame(this);
209
215
  this.root.classList.remove(OPEN_CLASS);
210
216
  this.root.classList.remove(BELOW_CLASS);
217
+ this.list.inert = false;
211
218
  this.trigger.setAttribute("aria-expanded", "false");
212
219
  this._opener = null;
213
220
  instances.delete(this.root);
@@ -221,6 +228,12 @@ export class FabMenu {
221
228
  if (!this.trigger.hasAttribute("aria-haspopup")) {
222
229
  this.trigger.setAttribute("aria-haspopup", "menu");
223
230
  }
231
+ /* La lista cerrada sale del orden de tabulación y del árbol de
232
+ accesibilidad en el mismo fotograma. `visibility` se demora lo que dura
233
+ la salida (hasta 350 ms) y, en ese hueco, ítems ya invisibles seguían
234
+ recibiendo `Tab`. `inert` no afecta a la pintura, así que la cascada de
235
+ salida se sigue viendo. */
236
+ this.list.inert = !this.isOpen;
224
237
  }
225
238
 
226
239
  _items() {
@@ -356,9 +369,12 @@ export class FabMenu {
356
369
  return;
357
370
  }
358
371
 
359
- /* APG: `Tab` sale del menú. Se cierra sin devolver el foco para que la
360
- tabulación siga su curso natural. */
372
+ /* APG: `Tab` sale del menú y sigue el orden de tabulación. El foco se
373
+ ancla en el disparador antes del desplazamiento por defecto: la lista
374
+ queda `inert` al cerrar y, sin el ancla, el navegador enfocaba un ítem
375
+ que dejaba de verse y terminaba devolviendo el foco a `body`. */
361
376
  if (event.key === "Tab" && this.isOpen) {
377
+ this.trigger.focus({ preventScroll: true });
362
378
  this.close({ restoreFocus: false });
363
379
  return;
364
380
  }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Navigation rail — comportamiento opcional para `.m3-navigation-rail`.
3
+ *
4
+ * Añade el menú que alterna collapsed/expanded, las flechas entre destinos y
5
+ * Escape para contraer. Emite `navigation-rail:toggle` en el rail (burbujea).
6
+ */
7
+
8
+ export interface NavigationRailOptions {
9
+ /** Escape contrae el rail o cierra el modal y devuelve el foco. Por defecto `true`. */
10
+ readonly collapseOnEscape?: boolean;
11
+ /** Al expandir u abrir, lleva el foco al primer destino. Por defecto `false`;
12
+ * el rail modal siempre enfoca el panel. */
13
+ readonly focusFirstItemOnExpand?: boolean;
14
+ }
15
+
16
+ export interface NavigationRailController {
17
+ /** Rail conectado. */
18
+ readonly root: HTMLElement;
19
+ /** Estado actual. */
20
+ readonly expanded: boolean;
21
+ /** Expande y actualiza `aria-expanded`. */
22
+ expand(): this;
23
+ /** Contrae y actualiza `aria-expanded`. */
24
+ collapse(): this;
25
+ /** Alterna el estado. */
26
+ toggle(): this;
27
+ /** Desconecta los listeners y libera el registro. */
28
+ destroy(): void;
29
+ }
30
+
31
+ /** `event.detail` de `navigation-rail:toggle`. */
32
+ export interface NavigationRailToggleDetail {
33
+ expanded: boolean;
34
+ }
35
+
36
+ declare global {
37
+ interface HTMLElementEventMap {
38
+ "navigation-rail:toggle": CustomEvent<NavigationRailToggleDetail>;
39
+ }
40
+ }
41
+
42
+ /** Inicializa un rail. Idempotente. */
43
+ export function initNavigationRail(
44
+ root: HTMLElement,
45
+ options?: NavigationRailOptions
46
+ ): NavigationRailController | null;
47
+
48
+ /** Inicializa todos los rails con menú dentro de `root`. */
49
+ export function initNavigationRails(
50
+ root?: ParentNode,
51
+ options?: NavigationRailOptions
52
+ ): Array<NavigationRailController | null>;
@@ -0,0 +1,445 @@
1
+ /* Navigation rail: comportamiento opcional.
2
+ *
3
+ * El componente es CSS: un rail expandido se puede servir ya con la clase
4
+ * `m3-navigation-rail--expanded`. Este módulo añade lo que necesita estado:
5
+ *
6
+ * · **Menú** (`data-navigation-rail-toggle`): alterna collapsed/expanded en el
7
+ * rail estático, o abre/cierra el contenedor cuando el rail es modal.
8
+ * · **Teclado**: flechas entre destinos, Home/End, Escape para contraer y
9
+ * Tab atrapado dentro del panel modal.
10
+ * · **Modal** (`data-navigation-rail-modal`): scrim, scroll bloqueado, foco
11
+ * inicial en el primer destino y devolución del foco al abridor.
12
+ *
13
+ * Contrato de markup (ver README):
14
+ *
15
+ * <!-- Estático -->
16
+ * <nav class="m3-navigation-rail" data-navigation-rail aria-label="Principal">
17
+ * <div class="m3-navigation-rail__header">
18
+ * <button class="m3-navigation-rail__menu m3-icon-button" type="button"
19
+ * aria-expanded="false" aria-label="Expandir navegación"
20
+ * data-navigation-rail-toggle>
21
+ * <span class="m3-icon" aria-hidden="true">menu</span>
22
+ * </button>
23
+ * </div>
24
+ * <a class="m3-navigation-rail__item" href="…" aria-current="page">…</a>
25
+ * </nav>
26
+ *
27
+ * <!-- Modal (el disparador puede vivir en la app bar) -->
28
+ * <div class="m3-navigation-rail-container" data-navigation-rail-modal>
29
+ * <div class="m3-navigation-rail__scrim" data-navigation-rail-scrim></div>
30
+ * <nav class="m3-navigation-rail m3-navigation-rail--expanded
31
+ * m3-navigation-rail--modal" data-navigation-rail>…</nav>
32
+ * </div>
33
+ *
34
+ * Sin `data-navigation-rail`, `initNavigationRails()` inicializa cualquier
35
+ * `.m3-navigation-rail` que tenga un `[data-navigation-rail-toggle]` y el CSS
36
+ * basta para el resto.
37
+ */
38
+
39
+ import { lockScroll, trapTab, unlockScroll } from "./_shared.js";
40
+
41
+ const RAIL_SELECTOR = ".m3-navigation-rail";
42
+ const TOGGLE_SELECTOR = "[data-navigation-rail-toggle]";
43
+ const ITEM_SELECTOR = ".m3-navigation-rail__item";
44
+ const MODAL_SELECTOR = "[data-navigation-rail-modal]";
45
+ const SCRIM_SELECTOR = "[data-navigation-rail-scrim]";
46
+ const EXPANDED_CLASS = "m3-navigation-rail--expanded";
47
+ const OPEN_CLASS = "m3-navigation-rail-container--open";
48
+ const CLOSING_CLASS = "m3-navigation-rail-container--closing";
49
+
50
+ const instances = new WeakMap();
51
+
52
+ /**
53
+ * @typedef {object} NavigationRailOptions
54
+ * @property {boolean} [collapseOnEscape=true] Escape contrae o cierra y
55
+ * devuelve el foco al abridor.
56
+ * @property {boolean} [focusFirstItemOnExpand=false] Al expandir (o abrir el
57
+ * modal), lleva el foco al primer destino.
58
+ */
59
+
60
+ /**
61
+ * Inicializa un rail. Idempotente: la segunda llamada devuelve la instancia.
62
+ *
63
+ * @param {HTMLElement} root Elemento `.m3-navigation-rail`.
64
+ * @param {NavigationRailOptions} [options]
65
+ */
66
+ export function initNavigationRail(root, options = {}) {
67
+ if (!(root instanceof HTMLElement)) return null;
68
+ const existing = instances.get(root);
69
+ if (existing) return existing;
70
+
71
+ const settings = {
72
+ collapseOnEscape: options.collapseOnEscape !== false,
73
+ /* Expandir no roba el foco: M3 lo deja en el menú y Tab entra en los
74
+ * destinos. El modal sí lo lleva dentro porque es un diálogo. */
75
+ focusFirstItemOnExpand: options.focusFirstItemOnExpand === true,
76
+ };
77
+
78
+ const container = root.closest(MODAL_SELECTOR);
79
+ const isModal = container instanceof HTMLElement;
80
+ /* Puede haber varios disparadores: el de dentro del panel y los externos con
81
+ * `aria-controls` (el patrón del rail modal, que se abre desde la app bar). */
82
+ const toggles = new Set(root.querySelectorAll(TOGGLE_SELECTOR));
83
+ if (isModal) {
84
+ for (const node of container.querySelectorAll(TOGGLE_SELECTOR)) {
85
+ toggles.add(node);
86
+ }
87
+ if (root.id) {
88
+ for (const node of document.querySelectorAll(
89
+ `[aria-controls="${root.id}"]`,
90
+ )) {
91
+ toggles.add(node);
92
+ }
93
+ }
94
+ }
95
+ const scrim = isModal ? container.querySelector(SCRIM_SELECTOR) : null;
96
+ const items = () => [...root.querySelectorAll(ITEM_SELECTOR)];
97
+
98
+ /* El modal es un diálogo: el rol va en el **contenedor** (no en el `<nav>`,
99
+ * que conservaría su landmark de navegación). El nombre se hereda del nav. */
100
+ if (isModal) {
101
+ container.setAttribute("aria-modal", "true");
102
+ if (!container.hasAttribute("role")) container.setAttribute("role", "dialog");
103
+ if (
104
+ !container.hasAttribute("aria-label") &&
105
+ root.hasAttribute("aria-label")
106
+ ) {
107
+ container.setAttribute("aria-label", root.getAttribute("aria-label"));
108
+ }
109
+ }
110
+
111
+ let open = isModal
112
+ ? container.classList.contains(OPEN_CLASS)
113
+ : root.classList.contains(EXPANDED_CLASS);
114
+ let opener = null;
115
+ let exitTimer = 0;
116
+ let exitFrame = 0;
117
+ let scrollLocked = false;
118
+ /** Hermanos del contenedor a los que se les puso `inert` al abrir el modal. */
119
+ let isolatedBackground = [];
120
+ let backgroundIsolated = false;
121
+
122
+ function isolateBackground() {
123
+ if (backgroundIsolated) return;
124
+ /* Se sube por la cadena de ancestros hasta `body`: un contenedor dentro de
125
+ * una sección no debe dejar el resto de la página expuesta. */
126
+ const isolated = [];
127
+ let node = container;
128
+ while (node && node.parentElement && node.parentElement !== document.documentElement) {
129
+ for (const sibling of node.parentElement.children) {
130
+ if (sibling === node) continue;
131
+ if (sibling.hasAttribute("inert")) continue;
132
+ isolated.push(sibling);
133
+ }
134
+ node = node.parentElement;
135
+ }
136
+ for (const el of isolated) el.setAttribute("inert", "");
137
+ isolatedBackground = isolated;
138
+ backgroundIsolated = true;
139
+ }
140
+
141
+ function releaseBackground() {
142
+ for (const el of isolatedBackground) el.removeAttribute("inert");
143
+ isolatedBackground = [];
144
+ backgroundIsolated = false;
145
+ }
146
+
147
+ function syncToggle() {
148
+ for (const toggle of toggles) {
149
+ toggle.setAttribute("aria-expanded", String(open));
150
+ /* `data-navigation-rail-label="Texto"` fija la etiqueta accesible; sin
151
+ * atributo se gestiona sola (Expandir/Contraer). */
152
+ const fixed = toggle.dataset.navigationRailLabel;
153
+ if (fixed) {
154
+ toggle.setAttribute("aria-label", fixed);
155
+ } else {
156
+ toggle.setAttribute(
157
+ "aria-label",
158
+ open ? "Contraer navegación" : "Expandir navegación",
159
+ );
160
+ }
161
+ }
162
+ }
163
+
164
+ /** Refleja el estado en la clase y en la accesibilidad del panel. */
165
+ function applyState() {
166
+ if (isModal) {
167
+ container.classList.toggle(OPEN_CLASS, open);
168
+ container.setAttribute("aria-hidden", String(!open));
169
+ if (open) {
170
+ container.classList.remove(CLOSING_CLASS);
171
+ root.removeAttribute("inert");
172
+ root.removeAttribute("aria-hidden");
173
+ } else {
174
+ /* Mientras se desplaza sigue visible: bloquea el puntero y no recibe
175
+ * foco hasta que termina (el cierre programa `inert`). */
176
+ container.classList.add(CLOSING_CLASS);
177
+ }
178
+ } else {
179
+ root.classList.toggle(EXPANDED_CLASS, open);
180
+ }
181
+ syncToggle();
182
+ }
183
+
184
+ /** Duración real de la transición de salida (con reduced-motion es ~1 ms). */
185
+ function transitionMs(element) {
186
+ const style = getComputedStyle(element);
187
+ const toMs = (value) => {
188
+ const v = value.trim();
189
+ const n = parseFloat(v);
190
+ if (Number.isNaN(n)) return 0;
191
+ return v.endsWith("ms") ? n : n * 1000;
192
+ };
193
+ const durations = style.transitionDuration.split(",").map(toMs);
194
+ const delays = style.transitionDelay.split(",").map(toMs);
195
+ /* Se suma duración + retardo **por propiedad**: el retardo de `visibility`
196
+ * no se acumula con el del `translate`. */
197
+ return Math.max(
198
+ 0,
199
+ ...durations.map((d, i) => d + (delays[i] ?? delays[0] ?? 0)),
200
+ );
201
+ }
202
+
203
+ function setOpen(next, { focusFirst = false, returnFocus = false } = {}) {
204
+ if (open === next) return;
205
+ open = next;
206
+ window.clearTimeout(exitTimer);
207
+
208
+ if (isModal) {
209
+ if (open) {
210
+ opener = document.activeElement;
211
+ if (!scrollLocked) {
212
+ lockScroll(document);
213
+ scrollLocked = true;
214
+ }
215
+ applyState();
216
+ isolateBackground();
217
+ /* El modal es un diálogo: el foco entra siempre en el panel. */
218
+ const first = items()[0];
219
+ if (first) {
220
+ first.focus({ preventScroll: true });
221
+ } else if (!root.hasAttribute("tabindex")) {
222
+ root.setAttribute("tabindex", "-1");
223
+ root.focus({ preventScroll: true });
224
+ }
225
+ } else {
226
+ applyState();
227
+ /* La página vuelve a estar disponible antes de devolver el foco: el
228
+ * disparador externo estaba en `inert` como fondo del modal. */
229
+ releaseBackground();
230
+ /* El foco sale **antes** de `inert`, y siempre a un disparador externo:
231
+ * el menú de dentro queda inerte y `body` no es un destino útil. */
232
+ const usable = opener instanceof HTMLElement &&
233
+ opener !== document.body &&
234
+ opener.isConnected &&
235
+ !root.contains(opener);
236
+ const external = [...toggles].find((node) => !root.contains(node));
237
+ const target = usable ? opener : external ?? [...toggles][0];
238
+ target?.focus({ preventScroll: true });
239
+ /* Inerte de inmediato: quita el panel del orden de tabulación y del
240
+ * árbol mientras se va; el puntero lo sigue bloqueando `--closing` y el
241
+ * scrim, que cubre el contenedor. */
242
+ root.setAttribute("inert", "");
243
+ root.setAttribute("aria-hidden", "true");
244
+
245
+ const exit = Math.max(transitionMs(root), 1);
246
+ window.clearTimeout(exitTimer);
247
+ cancelAnimationFrame(exitFrame);
248
+ const finishExit = () => {
249
+ window.clearTimeout(exitTimer);
250
+ cancelAnimationFrame(exitFrame);
251
+ exitFrame = 0;
252
+ if (open) return;
253
+ container.classList.remove(CLOSING_CLASS);
254
+ if (scrollLocked) {
255
+ unlockScroll(document);
256
+ scrollLocked = false;
257
+ }
258
+ };
259
+ /* La curva del spring aplana el desplazamiento mucho antes de su
260
+ * duración nominal: se libera cuando el panel está realmente fuera de
261
+ * la ventana, no a los 500 ms. */
262
+ const watch = () => {
263
+ if (open) return;
264
+ const rect = root.getBoundingClientRect();
265
+ const out =
266
+ rect.right <= 0.5 || rect.left >= window.innerWidth - 0.5;
267
+ if (out) finishExit();
268
+ else exitFrame = requestAnimationFrame(watch);
269
+ };
270
+ exitFrame = requestAnimationFrame(watch);
271
+ exitTimer = window.setTimeout(finishExit, exit + 60);
272
+ }
273
+ } else {
274
+ applyState();
275
+ if (open) {
276
+ if (focusFirst || settings.focusFirstItemOnExpand) {
277
+ items()[0]?.focus({ preventScroll: true });
278
+ }
279
+ } else if (root.contains(document.activeElement)) {
280
+ /* Al contraer, el foco vuelve al menú (convención de M3 y promesa del
281
+ * preview): el destino contraído sigue visible, pero el control que
282
+ * cambió el modo es el menú. */
283
+ [...toggles][0]?.focus({ preventScroll: true });
284
+ }
285
+ }
286
+
287
+ root.dispatchEvent(
288
+ new CustomEvent("navigation-rail:toggle", {
289
+ bubbles: true,
290
+ detail: { expanded: open },
291
+ }),
292
+ );
293
+ }
294
+
295
+ function onToggleClick(event) {
296
+ event.preventDefault();
297
+ setOpen(!open);
298
+ }
299
+
300
+ function onScrimClick(event) {
301
+ event.preventDefault();
302
+ setOpen(false, { returnFocus: true });
303
+ }
304
+
305
+ function onDocumentKeydown(event) {
306
+ if (!isModal || !open || !settings.collapseOnEscape) return;
307
+ if (event.key !== "Escape") return;
308
+ event.preventDefault();
309
+ setOpen(false, { returnFocus: true });
310
+ }
311
+
312
+ function onKeydown(event) {
313
+ if (isModal && open && event.key === "Tab") {
314
+ trapTab(container, event);
315
+ return;
316
+ }
317
+
318
+ /* En modal, Escape se escucha en el documento: el foco puede estar fuera
319
+ * del panel justo después de abrir o al volver del scrim. */
320
+ if (!isModal && event.key === "Escape" && open && settings.collapseOnEscape) {
321
+ event.preventDefault();
322
+ setOpen(false, { returnFocus: true });
323
+ return;
324
+ }
325
+
326
+ const list = items();
327
+ if (list.length === 0) return;
328
+ const index = list.indexOf(document.activeElement);
329
+
330
+ if (
331
+ event.key !== "ArrowDown" &&
332
+ event.key !== "ArrowUp" &&
333
+ event.key !== "Home" &&
334
+ event.key !== "End"
335
+ ) {
336
+ return;
337
+ }
338
+ event.preventDefault();
339
+ if (index === -1) {
340
+ /* Desde el menú/FAB: ↓ y Home entran por el primero, ↑ y End por el último. */
341
+ const target =
342
+ event.key === "End" || event.key === "ArrowUp"
343
+ ? list[list.length - 1]
344
+ : list[0];
345
+ target.focus({ preventScroll: true });
346
+ return;
347
+ }
348
+ const last = list.length - 1;
349
+ const next =
350
+ event.key === "Home"
351
+ ? 0
352
+ : event.key === "End"
353
+ ? last
354
+ : event.key === "ArrowDown"
355
+ ? Math.min(last, index + 1)
356
+ : Math.max(0, index - 1);
357
+ list[next].focus({ preventScroll: true });
358
+ }
359
+
360
+ for (const toggle of toggles) {
361
+ toggle.addEventListener("click", onToggleClick);
362
+ }
363
+ scrim?.addEventListener("click", onScrimClick);
364
+ document.addEventListener("keydown", onDocumentKeydown);
365
+ root.addEventListener("keydown", onKeydown);
366
+
367
+ /* Estado inicial coherente también sin interacción. */
368
+ if (isModal && !open) {
369
+ root.toggleAttribute("inert", true);
370
+ root.setAttribute("aria-hidden", "true");
371
+ }
372
+ syncToggle();
373
+
374
+ const instance = {
375
+ root,
376
+ get expanded() {
377
+ return open;
378
+ },
379
+ expand() {
380
+ setOpen(true);
381
+ return instance;
382
+ },
383
+ collapse() {
384
+ setOpen(false, { returnFocus: true });
385
+ return instance;
386
+ },
387
+ toggle() {
388
+ setOpen(!open);
389
+ return instance;
390
+ },
391
+ destroy() {
392
+ window.clearTimeout(exitTimer);
393
+ cancelAnimationFrame(exitFrame);
394
+ for (const toggle of toggles) {
395
+ toggle.removeEventListener("click", onToggleClick);
396
+ }
397
+ scrim?.removeEventListener("click", onScrimClick);
398
+ document.removeEventListener("keydown", onDocumentKeydown);
399
+ root.removeEventListener("keydown", onKeydown);
400
+ if (scrollLocked) {
401
+ unlockScroll(document);
402
+ scrollLocked = false;
403
+ }
404
+ releaseBackground();
405
+ instances.delete(root);
406
+ },
407
+ };
408
+
409
+ instances.set(root, instance);
410
+ return instance;
411
+ }
412
+
413
+ /**
414
+ * Inicializa todos los rails con menú (o modales) dentro de `root`.
415
+ *
416
+ * @param {ParentNode} [root=document]
417
+ * @param {NavigationRailOptions} [options]
418
+ */
419
+ export function initNavigationRails(root = document, options = {}) {
420
+ /* Un `Element` o un `DocumentFragment` acotan la búsqueda a su subárbol
421
+ * (antes un fragmento barría todo el documento). */
422
+ const scope =
423
+ root instanceof Element || root instanceof DocumentFragment
424
+ ? root
425
+ : document;
426
+ const rails = new Set(scope.querySelectorAll(RAIL_SELECTOR));
427
+ if (scope instanceof Element && scope.matches(RAIL_SELECTOR)) {
428
+ rails.add(scope);
429
+ }
430
+ return [...rails]
431
+ .filter(
432
+ (rail) =>
433
+ rail.querySelector(TOGGLE_SELECTOR) || rail.closest(MODAL_SELECTOR),
434
+ )
435
+ .map((rail) => initNavigationRail(rail, options));
436
+ }
437
+
438
+ if (typeof document !== "undefined" && !globalThis.__M3_MANUAL_INIT__) {
439
+ const boot = () => initNavigationRails();
440
+ if (document.readyState === "loading") {
441
+ document.addEventListener("DOMContentLoaded", boot, { once: true });
442
+ } else {
443
+ boot();
444
+ }
445
+ }