@gustavogalveza/design-system 0.7.0 → 0.8.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 CHANGED
@@ -3,6 +3,31 @@
3
3
  Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/)
4
4
  y versionado [SemVer](https://semver.org/lang/es/).
5
5
 
6
+ ## 0.8.0 — 2026-12-05
7
+
8
+ Button group Expressive: selección, ancho animado y overflow.
9
+
10
+ ### Añadido
11
+
12
+ - `behaviors/button-group.js`: selección `single`/`multiple` con
13
+ `aria-pressed`, `animateWidth` y overflow a un `m3-menu` generado.
14
+ - CSS del connected: `aria-pressed="true"` pasa a `CornerFull`; `data-animate-width`
15
+ expande el botón pulsado un 15 % y comprime a sus vecinos; `data-overflow`
16
+ oculta los ítems que no caben.
17
+ - Nueva sección de selección, ancho y overflow en `preview/button-group.html`.
18
+ - `tests/button-group.test.mjs` para overflow, selección y contrato CSS.
19
+ - `.d.ts` del behavior.
20
+
21
+ ### Cambiado
22
+
23
+ - El índice del README anuncia `behaviors/button-group.js`.
24
+ - La versión del paquete pasa a 0.8.0.
25
+
26
+ ### Verificación
27
+
28
+ - `npm test` → 30/30.
29
+ - `esbuild src/index.css` compila; la preview carga sin errores.
30
+
6
31
  ## 0.7.0 — 2026-12-04
7
32
 
8
33
  Movimiento spring para CSS, generado desde Compose Material3 1.5.
package/CONFORMANCE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Conformidad M3 Expressive — auditoría web
2
2
 
3
- > Fecha: **2026-12-04** · Base: `@gustavogalveza/design-system@0.7.0` ·
3
+ > Fecha: **2026-12-05** · Base: `@gustavogalveza/design-system@0.8.0` ·
4
4
  > Alcance: adaptación web token-first, no un port de Android.
5
5
 
6
6
  Este documento responde a una pregunta concreta: **qué tan fiel es el paquete a
@@ -11,23 +11,22 @@ fija la referencia, mide la brecha y prioriza.
11
11
 
12
12
  El paquete cubre la **base visual** (color, tipografía, forma, elevación,
13
13
  espaciado, estados) y varios componentes Expressive **total o parcialmente**.
14
- La suite pasa 25 pruebas; la validación visual se hará en la vertical de calidad.
14
+ La suite pasa 30 pruebas; la validación visual se hará en la vertical de calidad.
15
15
 
16
16
  La brecha principal no es “faltan colores o clases”. Es **comportamiento**:
17
17
 
18
18
  | Prioridad | Brecha | Por qué importa |
19
19
  |---|---|---|
20
- | **P1** | Button group Expressive completo | Faltan overflow menu, animación de ancho y selección conectada; es un componente central de M3E. |
21
20
  | **P2** | Wavy progress | Componente Expressive publicado y hoy declarado fuera de alcance. |
22
21
  | **P2** | Biblioteca de formas y morph | Solo el loading indicator usa 7 formas aproximadas; no hay API general para `MaterialShapes`. |
23
22
  | **P2** | Variantes Expressive 1.5 | App bar con colapso, toolbar con overflow, search con morph de ancho y variantes 1.5, chips con morph, text fields expresivos, menús selectable/checkable, listas segmented, time picker y tooltip expresivos. |
24
23
  | **P2** | Ejes variables de tipografía | La escala está, pero `GRAD`/`wdth`/`slnt` no se exponen ni se prueban. |
25
24
  | **P3** | Cobertura y exactitud | Vectores exactos del loading, bottom app bar, drag handle, `prefers-contrast`, previews de ejes. |
26
25
 
27
- **Decisión recomendada:** no perseguir paridad pixel a pixel con Compose. El
28
- motion spring CSS se cerró en **0.7.0**; sigue **button group**, después
29
- **wavy progress + shapes**, luego las **variantes 1.5** y el resto documentado
30
- como adaptación web.
26
+ **Decisión recomendada:** no perseguir paridad pixel a pixel con Compose. Los
27
+ P1 de motion (0.7.0) y button group (0.8.0) están cerrados; siguen **wavy
28
+ progress + shapes**, luego las **variantes 1.5** y el resto documentado como
29
+ adaptación web.
31
30
 
32
31
  ## Referencia canónica
33
32
 
@@ -84,7 +83,7 @@ exactitud o documentación. La regresión visual es transversal y se trata apart
84
83
  | App bars | **Parcial** | `small`, `medium`, `medium-flexible`, `large`, `large-flexible` en `src/components/app-bar.css:87-128` | Las flexibles son estáticas: abrazan el contenido y no colapsan por scroll. El propio archivo dice que el colapso no es CSS (`app-bar.css:9`). | P2 |
85
84
  | Buttons | **Cumple** | Tallas XS–XL, formas, colores y `aria-pressed` en `src/components/button.css:238-279` | — | — |
86
85
  | Toggle button | **Cumple** | Variante de alternancia en `src/components/button.css:238-279` | Compose 1.5 tiene API propia; el CSS cubre el estado visual y accesible. | — |
87
- | Button groups | **Parcial** | `standard` y `connected` en `src/components/button-group.css:1-200` | Sin overflow menu, sin `animateWidth` y sin selección conectada. Es el mayor hueco de componente. | **P1** |
86
+ | Button groups | **Cumple (behavior)** | CSS en `src/components/button-group.css`; selector, ancho y overflow en `src/behaviors/button-group.js` | `aria-pressed` single/multiple, `animateWidth` con flex-grow y overflow a menú. La animación de ancho es aproximación CSS, no el layout medido de Compose. | — |
88
87
  | Split button | **Parcial** | Menú con `behaviors/menu.js`, formas y estados en `src/components/split-button.css` | El menú se ancla a la flecha y no hay animación de ancho; documentado. | P3 |
89
88
  | FAB y FAB menu | **Cumple** | FAB menu con foco, teclado, cascada y estados de elevación en `src/components/fab-menu.css` | El ítem va 0 en reposo/disabled, 4 en hover y 3 en foco/pulsado; reposo/disabled los cubre `tests/tokens.test.mjs` y los estados `tests/p3.test.mjs`. | — |
90
89
  | Icon buttons | **Cumple** | Tallas, formas y estados en `src/components/icon-button.css` | — | — |
@@ -122,39 +121,33 @@ exactitud o documentación. La regresión visual es transversal y se trata apart
122
121
 
123
122
  ### P1 — Diferenciadores Expressive
124
123
 
125
- 1. **Button group Expressive**
126
- - Overflow menu cuando no caben los ítems.
127
- - `animateWidth` al pulsar (expansión del ítem y compresión de vecinos).
128
- - Selección conectada single/multi con forma y estado accesible.
129
- - Criterio: mismo markup que hoy; el comportamiento se añade con un módulo opcional.
130
-
131
- Motion springs se cerró en **0.7.0** con curvas `linear()` generadas y fallback; el helper WAAPI para gestos interrumpibles sigue en P3.
124
+ Ninguno abierto: motion springs (**0.7.0**) y button group (**0.8.0**) cerrados. El helper WAAPI interrumpible sigue en P3.
132
125
 
133
126
  ### P2 — Componentes y tokens
134
127
 
135
- 2. **Wavy progress** (linear y circular si M3 lo publica).
136
- 3. **MaterialShapes**: subconjunto curado + utilidad de morph; no implementar las 35 a ciegas.
137
- 4. **Ejes tipográficos**: tokens `GRAD`/`wdth`/`slnt` y preview con la fuente servida.
138
- 5. **Variantes Expressive 1.5**: colapso de app bar, overflow de toolbar, morph de ancho y variantes `AppBarWithSearch`/full-screen contained de search, chips con morph, text fields expresivos, menús selectable/checkable, listas segmented, `VibrantTimePickerDialog`/time picker scrollable y tooltip con caret. Cada una con decisión “implementar o documentar”.
128
+ 1. **Wavy progress** (linear y circular si M3 lo publica).
129
+ 2. **MaterialShapes**: subconjunto curado + utilidad de morph; no implementar las 35 a ciegas.
130
+ 3. **Ejes tipográficos**: tokens `GRAD`/`wdth`/`slnt` y preview con la fuente servida.
131
+ 4. **Variantes Expressive 1.5**: colapso de app bar, overflow de toolbar, morph de ancho y variantes `AppBarWithSearch`/full-screen contained de search, chips con morph, text fields expresivos, menús selectable/checkable, listas segmented, `VibrantTimePickerDialog`/time picker scrollable y tooltip con caret. Cada una con decisión “implementar o documentar”.
139
132
 
140
133
  ### P3 — Cobertura y exactitud
141
134
 
142
- 6. Split button (animación de ancho) y carousel (parallax), si el producto los necesita.
143
- 7. Densidad por componente (hoy solo segmented) o exclusión explícita.
144
- 8. Vectores exactos del loading indicator (si se consigue la fuente).
145
- 9. `prefers-contrast: more` o declaración definitiva de no soporte.
146
- 10. Bottom app bar y drag handle independiente, si el producto los necesita.
147
- 11. Previews de ejes variables y estados que aún no se demuestran.
148
- 12. Comparativa documentada con kits web de terceros, sin adoptarlos como canon.
149
- 13. Regresión visual (transversal): Playwright con 320/600/1440, claro/oscuro, RTL, 200 % y reduced motion.
150
- 14. Helper WAAPI opcional para springs interrumpibles en gestos.
135
+ 5. Split button (animación de ancho) y carousel (parallax), si el producto los necesita.
136
+ 6. Densidad por componente (hoy solo segmented) o exclusión explícita.
137
+ 7. Vectores exactos del loading indicator (si se consigue la fuente).
138
+ 8. `prefers-contrast: more` o declaración definitiva de no soporte.
139
+ 9. Bottom app bar y drag handle independiente, si el producto los necesita.
140
+ 10. Previews de ejes variables y estados que aún no se demuestran.
141
+ 11. Comparativa documentada con kits web de terceros, sin adoptarlos como canon.
142
+ 12. Regresión visual (transversal): Playwright con 320/600/1440, claro/oscuro, RTL, 200 % y reduced motion.
143
+ 13. Helper WAAPI opcional para springs interrumpibles en gestos.
151
144
 
152
145
  ## Plan de implementación por verticales
153
146
 
154
147
  | Vertical | Contenido | Verificación |
155
148
  |---|---|---|
156
149
  | **A. Motion** | **Hecho en 0.7.0**: tokens de springs, `linear()` generado, fallback y migración de morphs. Queda WAAPI opcional. | Tests de tokens, preview de movimiento, reduced motion, comparación visual. |
157
- | **B. Button group** | Overflow, `animateWidth`, selección conectada, teclado | Tests de estados, 320 px, RTL, foco, `aria-pressed`/`aria-selected`. |
150
+ | **B. Button group** | **Hecho en 0.8.0**: overflow, `animateWidth` y selección conectada con behavior opcional. | Tests de estados, 320 px, RTL y teclado; pendiente probar con lector de pantalla real. |
158
151
  | **C. Wavy + shapes** | Wavy progress, subset de `MaterialShapes`, utilidad de morph | Tests de UI, reduced motion, contraste, preview de formas. |
159
152
  | **D. Variantes 1.5** | App bar, toolbar, search, chips, text fields, menús y listas | Tests de estados y previews por componente. |
160
153
  | **E. Calidad** | Regresión visual, ejes de fuente, docs, release | Suite completa, capturas base, `verificar-*`, changelog. |
@@ -193,7 +186,7 @@ se prueba que el fallback sigue siendo usable.
193
186
 
194
187
  - Componentes locales: `README.md:148-183` y `src/components/`.
195
188
  - Tokens: `src/tokens.css`, `src/colors.css`, `src/base.css`.
196
- - Pruebas: `tests/tokens.test.mjs`, `tests/p3.test.mjs`, `tests/docs.test.mjs` y `tests/springs.test.mjs` (25/25).
189
+ - Pruebas: `tests/tokens.test.mjs`, `tests/p3.test.mjs`, `tests/docs.test.mjs`, `tests/springs.test.mjs` y `tests/button-group.test.mjs` (30/30).
197
190
  - Previews: `preview/typography.html`, `preview/schemes.html`, `preview/motion.html`, `preview.html`.
198
191
  - Generador de springs: `scripts/springs.mjs`, `scripts/generate-springs.mjs`.
199
192
  - Documentación de auditoría de componentes: interna y no versionada; no forma parte del PR.
package/README.md CHANGED
@@ -107,7 +107,7 @@ Firefox 128+**.
107
107
 
108
108
  ## Behaviors
109
109
 
110
- Los módulos de `src/behaviors/` son opcionales. **Doce de ellos se
110
+ Los módulos de `src/behaviors/` son opcionales. **Trece de ellos se
111
111
  autoinicializan al importarse** (`tabs`, `menu` y `time-picker` no). Para
112
112
  inicializar a mano:
113
113
 
@@ -119,7 +119,7 @@ initAllMenus(document.querySelector("#mi-zona"));
119
119
 
120
120
  ### Tipos
121
121
 
122
- El paquete incluye las declaraciones de los quince módulos
122
+ El paquete incluye las declaraciones de los dieciséis módulos
123
123
  (`src/behaviors/*.d.ts`), así que en TypeScript hay autocompletado y
124
124
  comprobación de opciones y eventos sin escribir nada:
125
125
 
@@ -152,7 +152,7 @@ implica respaldo.
152
152
  | Badge | `.m3-badge` | — |
153
153
  | Bottom sheet | `.m3-bottom-sheet` | `behaviors/bottom-sheet.js` |
154
154
  | Button | `.m3-button` | — |
155
- | Button group | `.m3-button-group` | — |
155
+ | Button group | `.m3-button-group` | `behaviors/button-group.js` |
156
156
  | Card | `.m3-card` | — |
157
157
  | Carousel | `.m3-carousel` | `behaviors/carousel.js` |
158
158
  | Checkbox | `.m3-checkbox` | nativo |
@@ -217,6 +217,24 @@ Tallas: `--sm` (XSmall 32), base (Small 40), `--md` (56), `--lg` (96) y
217
217
  `.m3-icon .m3-icon--20` con `aria-hidden="true"` si es decorativo.
218
218
  Alternancia: `aria-pressed="true"` pinta el seleccionado.
219
219
 
220
+ ### Button group
221
+
222
+ ```html
223
+ <div class="m3-button-group m3-button-group--connected"
224
+ data-m3-button-group data-select="single" data-animate-width>
225
+ <button class="m3-button m3-button--tonal" aria-pressed="true">Día</button>
226
+ <button class="m3-button m3-button--tonal" aria-pressed="false">Semana</button>
227
+ </div>
228
+ ```
229
+
230
+ El CSS del grupo funciona sin JS. `behaviors/button-group.js` añade
231
+ `data-select="single|multiple"` (mantiene `aria-pressed`), `data-animate-width`
232
+ (el botón pulsado crece un 15 %) y `data-overflow="auto"` (mueve los ítems que
233
+ no caben a un menú). **`data-animate-width` y `data-overflow` son excluyentes**:
234
+ el primero reparte el ancho con `flex`, así que no queda espacio que desbordar.
235
+ Límites: el ancho animado es una aproximación con `flex-grow` y el menú de
236
+ overflow no refleja el `aria-pressed` de un ítem oculto.
237
+
220
238
  ### Chip
221
239
 
222
240
  ```html
@@ -463,9 +481,9 @@ del componente y no afecta al uso.
463
481
  npm test
464
482
  ```
465
483
 
466
- La suite tiene 25 pruebas: comprueba los 12 roles fixed con sus valores, los
484
+ La suite tiene 30 pruebas: comprueba los 12 roles fixed con sus valores, los
467
485
  pares `on-*`, la igualdad entre el bloque oscuro y la copia de
468
486
  `prefers-color-scheme`, los contenedores retonados, las 16 duraciones exactas,
469
487
  las curvas spring generadas y su fallback, el espaciado en `px`, la tipografía
470
- por rol e idioma, las variantes de icono y que ningún componente vuelva a fijar
471
- `GRAD` o duraciones en crudo.
488
+ por rol e idioma, las variantes de icono, la selección y el overflow del button
489
+ group, y que ningún componente vuelva a fijar `GRAD` o duraciones en crudo.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gustavogalveza/design-system",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Implementación independiente y no oficial de M3 Expressive: tokens, CSS y HTML nativo, sin framework ni runtime obligatorio",
5
5
  "license": "MIT",
6
6
  "author": "gustavogalveza",
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Button group — selección, ancho animado y overflow.
3
+ *
4
+ * Atributos del DOM:
5
+ * `data-m3-button-group` en la raíz.
6
+ * `data-select="single" | "multiple"` para gestionar `aria-pressed`.
7
+ * `data-animate-width` para marcar el botón pulsado (`data-pressed`).
8
+ * `data-overflow="auto"` para mover los ítems que no caben a un menú.
9
+ *
10
+ * Evento: `m3-button-group-change` en la raíz, burbujea.
11
+ * detail = { value, index, pressed }
12
+ */
13
+
14
+ export interface ButtonGroupChangeDetail {
15
+ value: string;
16
+ index: number;
17
+ pressed: boolean;
18
+ }
19
+
20
+ export interface ButtonGroupOptions {
21
+ /** Activa el overflow si el markup lleva `data-overflow="auto"`. */
22
+ overflow?: boolean;
23
+ }
24
+
25
+ export interface ButtonGroupController {
26
+ readonly root: HTMLElement;
27
+ destroy(): boolean;
28
+ }
29
+
30
+ export class ButtonGroup implements ButtonGroupController {
31
+ constructor(root: HTMLElement, options?: ButtonGroupOptions);
32
+ readonly root: HTMLElement;
33
+ destroy(): boolean;
34
+ }
35
+
36
+ /**
37
+ * Calcula cuántos ítems caben dejando espacio para el botón de overflow.
38
+ */
39
+ export function computeOverflow(
40
+ widths: number[],
41
+ gap: number,
42
+ available: number,
43
+ overflowWidth: number,
44
+ ): { visibleCount: number; overflow: boolean };
45
+
46
+ /**
47
+ * Devuelve el conjunto de índices presionados tras activar uno.
48
+ */
49
+ export function pressedAfterClick(
50
+ current: Set<number>,
51
+ index: number,
52
+ mode: "single" | "multiple",
53
+ ): Set<number>;
54
+
55
+ export function initButtonGroup(
56
+ root: HTMLElement,
57
+ options?: ButtonGroupOptions,
58
+ ): ButtonGroup;
59
+
60
+ export function initButtonGroups(scope?: Document | Element): ButtonGroup[];
@@ -0,0 +1,489 @@
1
+ /**
2
+ * Button group — selección, ancho animado y overflow (ESM, sin dependencias).
3
+ *
4
+ * El CSS dibuja el grupo y sus estados; este módulo aporta lo que el navegador
5
+ * no resuelve:
6
+ *
7
+ * - `data-select="single|multiple"`: mantiene `aria-pressed` en los botones.
8
+ * - `data-animate-width`: marca el botón pulsado para que el CSS lo expanda y
9
+ * comprima a sus vecinos.
10
+ * - `data-overflow="auto"`: mide el grupo, oculta los ítems que no caben y los
11
+ * mueve a un menú de desbordamiento.
12
+ *
13
+ * Contrato de markup:
14
+ *
15
+ * <div class="m3-button-group m3-button-group--connected"
16
+ * data-m3-button-group data-select="single"
17
+ * data-animate-width data-overflow="auto">
18
+ * <button class="m3-button m3-button--tonal" aria-pressed="true">Día</button>
19
+ * <button class="m3-button m3-button--tonal" aria-pressed="false">Semana</button>
20
+ * </div>
21
+ *
22
+ * Sin `data-m3-button-group` el CSS sigue funcionando; el behavior es opcional.
23
+ */
24
+
25
+ import { initMenu } from "./menu.js";
26
+
27
+ const ROOT_SELECTOR = "[data-m3-button-group]";
28
+ const ITEM_SELECTOR = ":scope > .m3-button, :scope > .m3-icon-button";
29
+ const OVERFLOWED = "m3-button-group__item--overflowed";
30
+ const OVERFLOW_END = "m3-button-group__item--overflow-end";
31
+ const PRESSED = "is-pressing";
32
+ const ACTIVE = "m3-button-group--overflow-active";
33
+ const INSTANCES = new WeakMap();
34
+
35
+ let uid = 0;
36
+
37
+ /**
38
+ * Calcula cuántos ítems caben dejando espacio para el botón de overflow.
39
+ * @param {number[]} widths Anchos medidos de los ítems.
40
+ * @param {number} gap Separación entre ítems.
41
+ * @param {number} available Ancho disponible del grupo.
42
+ * @param {number} overflowWidth Ancho del botón de overflow.
43
+ * @returns {{visibleCount: number, overflow: boolean}}
44
+ */
45
+ export function computeOverflow(widths, gap, available, overflowWidth) {
46
+ if (widths.length === 0) return { visibleCount: 0, overflow: false };
47
+
48
+ const total = widths.reduce(
49
+ (sum, width, index) => sum + width + (index === 0 ? 0 : gap),
50
+ 0,
51
+ );
52
+ if (total <= available) {
53
+ return { visibleCount: widths.length, overflow: false };
54
+ }
55
+
56
+ const budget = available - overflowWidth - gap;
57
+ let used = 0;
58
+ let visibleCount = 0;
59
+ for (const width of widths) {
60
+ const next = used + (visibleCount === 0 ? 0 : gap) + width;
61
+ if (next > budget) break;
62
+ used = next;
63
+ visibleCount += 1;
64
+ }
65
+ return { visibleCount, overflow: true };
66
+ }
67
+
68
+ /**
69
+ * Devuelve el conjunto de índices presionados tras activar uno.
70
+ * @param {Set<number>} current
71
+ * @param {number} index
72
+ * @param {"single" | "multiple"} mode
73
+ * @returns {Set<number>}
74
+ */
75
+ export function pressedAfterClick(current, index, mode) {
76
+ const next = new Set(current);
77
+ if (mode === "single") {
78
+ next.clear();
79
+ next.add(index);
80
+ return next;
81
+ }
82
+ if (next.has(index)) next.delete(index);
83
+ else next.add(index);
84
+ return next;
85
+ }
86
+
87
+ function directItems(root) {
88
+ return [...root.querySelectorAll(ITEM_SELECTOR)];
89
+ }
90
+
91
+ function buttonLabel(button) {
92
+ return (
93
+ button.querySelector(".m3-button__label")?.textContent?.trim() ||
94
+ button.getAttribute("aria-label") ||
95
+ button.textContent.trim()
96
+ );
97
+ }
98
+
99
+ function isDisabled(button) {
100
+ return button.disabled || button.getAttribute("aria-disabled") === "true";
101
+ }
102
+
103
+ function cloneIcon(button) {
104
+ const icon = button.querySelector(".m3-icon");
105
+ if (!icon) return null;
106
+ const clone = icon.cloneNode(true);
107
+ clone.setAttribute("aria-hidden", "true");
108
+ return clone;
109
+ }
110
+
111
+ class SelectionController {
112
+ constructor(root, mode) {
113
+ this.root = root;
114
+ this.mode = mode;
115
+ this.buttons = null;
116
+ this.onClick = this.onClick.bind(this);
117
+ this.init();
118
+ }
119
+
120
+ init() {
121
+ const buttons = directItems(this.root);
122
+ let hasPressed = false;
123
+ for (const button of buttons) {
124
+ const pressed = button.getAttribute("aria-pressed") === "true";
125
+ if (pressed && hasPressed && this.mode === "single") {
126
+ button.setAttribute("aria-pressed", "false");
127
+ } else if (pressed) {
128
+ hasPressed = true;
129
+ } else if (!button.hasAttribute("aria-pressed")) {
130
+ button.setAttribute("aria-pressed", "false");
131
+ }
132
+ }
133
+ if (this.mode === "single" && !hasPressed && buttons.length > 0) {
134
+ buttons[0].setAttribute("aria-pressed", "true");
135
+ }
136
+ this.root.addEventListener("click", this.onClick);
137
+ }
138
+
139
+ setButtons(buttons) {
140
+ this.buttons = buttons;
141
+ }
142
+
143
+ onClick(event) {
144
+ const button = event.target.closest(".m3-button, .m3-icon-button");
145
+ if (!button || button.parentElement !== this.root || isDisabled(button)) {
146
+ return;
147
+ }
148
+ const buttons = this.buttons ?? directItems(this.root);
149
+ const index = buttons.indexOf(button);
150
+ if (index === -1) return;
151
+ const current = new Set(
152
+ buttons.flatMap((item, itemIndex) =>
153
+ item.getAttribute("aria-pressed") === "true" ? [itemIndex] : [],
154
+ ),
155
+ );
156
+ const next = pressedAfterClick(current, index, this.mode);
157
+ for (const [itemIndex, item] of buttons.entries()) {
158
+ item.setAttribute("aria-pressed", next.has(itemIndex) ? "true" : "false");
159
+ }
160
+ this.root.dispatchEvent(
161
+ new CustomEvent("m3-button-group-change", {
162
+ bubbles: true,
163
+ detail: {
164
+ value:
165
+ button.value ||
166
+ button.getAttribute("aria-label") ||
167
+ buttonLabel(button),
168
+ index,
169
+ pressed: next.has(index),
170
+ },
171
+ }),
172
+ );
173
+ }
174
+
175
+ destroy() {
176
+ this.root.removeEventListener("click", this.onClick);
177
+ return true;
178
+ }
179
+ }
180
+
181
+ class PressController {
182
+ constructor(root) {
183
+ this.root = root;
184
+ this.pressedButton = null;
185
+ this.onPointerDown = this.onPointerDown.bind(this);
186
+ this.onPointerUp = this.onPointerUp.bind(this);
187
+ this.onKeyDown = this.onKeyDown.bind(this);
188
+ this.onKeyUp = this.onKeyUp.bind(this);
189
+ this.init();
190
+ }
191
+
192
+ init() {
193
+ this.root.addEventListener("pointerdown", this.onPointerDown);
194
+ this.root.addEventListener("pointerup", this.onPointerUp);
195
+ this.root.addEventListener("pointercancel", this.onPointerUp);
196
+ this.root.addEventListener("pointerleave", this.onPointerUp);
197
+ this.root.addEventListener("keydown", this.onKeyDown);
198
+ this.root.addEventListener("keyup", this.onKeyUp);
199
+ this.root.addEventListener("blur", this.onPointerUp, true);
200
+ }
201
+
202
+ onPointerDown(event) {
203
+ if (event.button !== 0) return;
204
+ const button = event.target.closest(".m3-button, .m3-icon-button");
205
+ if (!button || button.parentElement !== this.root || isDisabled(button)) {
206
+ return;
207
+ }
208
+ this.setPressed(button);
209
+ }
210
+
211
+ onKeyDown(event) {
212
+ if (event.key !== " " && event.key !== "Enter") return;
213
+ const button = event.target.closest(".m3-button, .m3-icon-button");
214
+ if (!button || button.parentElement !== this.root || isDisabled(button)) {
215
+ return;
216
+ }
217
+ this.setPressed(button);
218
+ }
219
+
220
+ setPressed(button) {
221
+ this.clearPressed();
222
+ this.pressedButton = button;
223
+ button.dataset.pressed = "true";
224
+ this.root.classList.add(PRESSED);
225
+ }
226
+
227
+ onPointerUp() {
228
+ this.clearPressed();
229
+ }
230
+
231
+ onKeyUp(event) {
232
+ if (event.key === " " || event.key === "Enter") this.clearPressed();
233
+ }
234
+
235
+ clearPressed() {
236
+ if (!this.pressedButton) return;
237
+ delete this.pressedButton.dataset.pressed;
238
+ this.pressedButton = null;
239
+ this.root.classList.remove(PRESSED);
240
+ }
241
+
242
+ destroy() {
243
+ this.root.removeEventListener("pointerdown", this.onPointerDown);
244
+ this.root.removeEventListener("pointerup", this.onPointerUp);
245
+ this.root.removeEventListener("pointercancel", this.onPointerUp);
246
+ this.root.removeEventListener("pointerleave", this.onPointerUp);
247
+ this.root.removeEventListener("keydown", this.onKeyDown);
248
+ this.root.removeEventListener("keyup", this.onKeyUp);
249
+ this.root.removeEventListener("blur", this.onPointerUp, true);
250
+ this.clearPressed();
251
+ return true;
252
+ }
253
+ }
254
+
255
+ class OverflowController {
256
+ constructor(root) {
257
+ this.root = root;
258
+ this.buttons = directItems(root);
259
+ this.visibleCount = -1;
260
+ this.frame = null;
261
+ this.menuController = null;
262
+ this.scheduleMeasure = this.scheduleMeasure.bind(this);
263
+ this.init();
264
+ }
265
+
266
+ init() {
267
+ this.overflowRoot = document.createElement("div");
268
+ this.overflowRoot.className = "m3-button-group__overflow m3-menu-anchor";
269
+ this.overflowRoot.hidden = true;
270
+
271
+ const trigger = document.createElement("button");
272
+ trigger.type = "button";
273
+ trigger.className =
274
+ "m3-icon-button m3-icon-button--tonal m3-menu__trigger";
275
+ trigger.setAttribute("aria-label", "Más acciones");
276
+ trigger.setAttribute("aria-haspopup", "menu");
277
+ trigger.setAttribute("aria-expanded", "false");
278
+ const menuId = `m3-button-group-menu-${++uid}`;
279
+ trigger.setAttribute("aria-controls", menuId);
280
+
281
+ const icon = document.createElement("span");
282
+ icon.className = "m3-icon";
283
+ icon.setAttribute("aria-hidden", "true");
284
+ icon.textContent = "more_horiz";
285
+ trigger.append(icon);
286
+
287
+ this.menu = document.createElement("div");
288
+ this.menu.className = "m3-menu";
289
+ this.menu.id = menuId;
290
+ this.menu.setAttribute("role", "menu");
291
+ this.menu.setAttribute(
292
+ "aria-label",
293
+ this.root.getAttribute("aria-label") || "Más acciones",
294
+ );
295
+ this.menu.setAttribute("popover", "manual");
296
+
297
+ this.overflowRoot.append(trigger, this.menu);
298
+ this.root.append(this.overflowRoot);
299
+ this.root.classList.add(ACTIVE);
300
+ this.menuController = initMenu(trigger);
301
+
302
+ if (typeof ResizeObserver !== "undefined") {
303
+ this.resizeObserver = new ResizeObserver(this.scheduleMeasure);
304
+ this.resizeObserver.observe(this.root);
305
+ }
306
+ window.addEventListener("resize", this.scheduleMeasure);
307
+ this.scheduleMeasure();
308
+ }
309
+
310
+ scheduleMeasure() {
311
+ if (this.frame !== null) return;
312
+ this.frame = requestAnimationFrame(() => {
313
+ this.frame = null;
314
+ this.measure();
315
+ });
316
+ }
317
+
318
+ measure() {
319
+ if (!this.root.isConnected || this.root.clientWidth === 0) return;
320
+
321
+ for (const button of this.buttons) {
322
+ button.classList.remove(OVERFLOWED);
323
+ }
324
+ this.overflowRoot.hidden = false;
325
+ this.overflowRoot.style.visibility = "hidden";
326
+
327
+ const styles = getComputedStyle(this.root);
328
+ const gap = Number.parseFloat(styles.columnGap) || 0;
329
+ const widths = this.buttons.map(
330
+ (button) => button.getBoundingClientRect().width,
331
+ );
332
+ const overflowWidth = this.overflowRoot.getBoundingClientRect().width;
333
+ const result = computeOverflow(
334
+ widths,
335
+ gap,
336
+ this.root.clientWidth,
337
+ overflowWidth,
338
+ );
339
+
340
+ this.overflowRoot.style.visibility = "";
341
+ this.overflowRoot.hidden = !result.overflow;
342
+ for (const [index, button] of this.buttons.entries()) {
343
+ button.classList.toggle(
344
+ OVERFLOWED,
345
+ result.overflow && index >= result.visibleCount,
346
+ );
347
+ button.classList.remove(OVERFLOW_END);
348
+ }
349
+ this.buttons[result.visibleCount - 1]?.classList.add(OVERFLOW_END);
350
+
351
+ if (result.visibleCount !== this.visibleCount) {
352
+ const wasOpen = this.menuController?.isOpen;
353
+ this.menuController?.close({ returnFocus: result.overflow });
354
+ this.visibleCount = result.visibleCount;
355
+ this.renderMenu();
356
+ if (wasOpen && !result.overflow) {
357
+ this.buttons[result.visibleCount - 1]?.focus();
358
+ }
359
+ }
360
+ if (!result.overflow) this.menuController?.close({ returnFocus: false });
361
+ }
362
+
363
+ renderMenu() {
364
+ this.menu.replaceChildren();
365
+ for (const button of this.buttons.slice(this.visibleCount)) {
366
+ const item = document.createElement("button");
367
+ item.type = "button";
368
+ item.className = "m3-menu__item";
369
+ item.setAttribute("role", "menuitem");
370
+ const icon = cloneIcon(button);
371
+ if (icon) item.append(icon);
372
+ const label = document.createElement("span");
373
+ label.className = "m3-button__label";
374
+ label.textContent = buttonLabel(button);
375
+ item.append(label);
376
+ const disabled = isDisabled(button);
377
+ item.disabled = button.disabled;
378
+ if (button.getAttribute("aria-disabled") === "true") {
379
+ item.setAttribute("aria-disabled", "true");
380
+ }
381
+ item.addEventListener("click", () => {
382
+ if (disabled) return;
383
+ button.click();
384
+ this.menuController?.close();
385
+ });
386
+ this.menu.append(item);
387
+ }
388
+ }
389
+
390
+ destroy() {
391
+ window.removeEventListener("resize", this.scheduleMeasure);
392
+ this.resizeObserver?.disconnect();
393
+ if (this.frame !== null) cancelAnimationFrame(this.frame);
394
+ for (const button of this.buttons) {
395
+ button.classList.remove(OVERFLOWED, OVERFLOW_END);
396
+ }
397
+ this.menuController?.destroy();
398
+ this.overflowRoot?.remove();
399
+ this.root.classList.remove(ACTIVE);
400
+ this.visibleCount = -1;
401
+ return true;
402
+ }
403
+ }
404
+
405
+ export class ButtonGroup {
406
+ /**
407
+ * @param {HTMLElement} root Grupo con `data-m3-button-group`.
408
+ * @param {object} [options]
409
+ * @param {boolean} [options.overflow=true] Activa el overflow si el markup
410
+ * lo pide con `data-overflow="auto"`.
411
+ */
412
+ constructor(root, options = {}) {
413
+ const existing = INSTANCES.get(root);
414
+ if (existing) return existing;
415
+ if (!(root instanceof HTMLElement)) {
416
+ throw new TypeError("ButtonGroup necesita un elemento raíz");
417
+ }
418
+
419
+ this.root = root;
420
+ const mode =
421
+ root.dataset.select === "single"
422
+ ? "single"
423
+ : root.dataset.select === "multiple"
424
+ ? "multiple"
425
+ : null;
426
+ this.selection = mode ? new SelectionController(root, mode) : null;
427
+ this.press = root.hasAttribute("data-animate-width")
428
+ ? new PressController(root)
429
+ : null;
430
+ this.overflow =
431
+ options.overflow !== false && root.getAttribute("data-overflow") === "auto"
432
+ ? new OverflowController(root)
433
+ : null;
434
+ this.selection?.setButtons(this.overflow?.buttons ?? null);
435
+ INSTANCES.set(root, this);
436
+ }
437
+
438
+ destroy() {
439
+ this.press?.destroy();
440
+ this.overflow?.destroy();
441
+ this.selection?.destroy();
442
+ INSTANCES.delete(this.root);
443
+ return true;
444
+ }
445
+ }
446
+
447
+ /**
448
+ * @param {HTMLElement} root
449
+ * @param {object} [options]
450
+ * @returns {ButtonGroup}
451
+ */
452
+ export function initButtonGroup(root, options = {}) {
453
+ const existing = INSTANCES.get(root);
454
+ if (existing) return existing;
455
+ const instance = new ButtonGroup(root, options);
456
+ INSTANCES.set(root, instance);
457
+ return instance;
458
+ }
459
+
460
+ /**
461
+ * @param {Document | Element} [scope]
462
+ * @returns {ButtonGroup[]}
463
+ */
464
+ export function initButtonGroups(scope = document) {
465
+ const roots = [];
466
+ if (scope instanceof Element && scope.matches(ROOT_SELECTOR)) {
467
+ roots.push(scope);
468
+ }
469
+ roots.push(...scope.querySelectorAll(ROOT_SELECTOR));
470
+ return roots
471
+ .map((root) => {
472
+ try {
473
+ return initButtonGroup(root);
474
+ } catch (error) {
475
+ console.error("[button-group]", error);
476
+ return null;
477
+ }
478
+ })
479
+ .filter(Boolean);
480
+ }
481
+
482
+ if (typeof document !== "undefined" && !globalThis.__M3_MANUAL_INIT__) {
483
+ const boot = () => initButtonGroups();
484
+ if (document.readyState === "loading") {
485
+ document.addEventListener("DOMContentLoaded", boot, { once: true });
486
+ } else {
487
+ boot();
488
+ }
489
+ }
@@ -1,7 +1,8 @@
1
1
  /* Button group — M3 Expressive.
2
- * Agrupa .m3-button existentes: no reimplementa el botón ni gestiona selección.
3
- * Solo aporta separación, radios de extremo y, en --connected, la separación de
4
- * 2 dp entre segmentos con radios interiores por talla.
2
+ * Agrupa .m3-button existentes: no reimplementa el botón. El CSS aporta
3
+ * separación, radios de extremo, el estado seleccionado de --connected y las
4
+ * transiciones de ancho; el behavior opcional `button-group.js` gestiona
5
+ * `aria-pressed`, el botón pulsado y el menú de overflow.
5
6
  *
6
7
  * El kit separa los botones del grupo estándar con un hueco que escala con la
7
8
  * talla (XSmall 18, Small 12, Medium/Large/XLarge 8) y une los del conectado
@@ -144,11 +145,77 @@
144
145
  --_m3-bg-radius-pressed-start: var(--m3-button-group-pressed-radius);
145
146
  }
146
147
 
147
- .m3-button-group--connected > .m3-button-group__item--line-end {
148
+ .m3-button-group--connected > .m3-button-group__item--line-end,
149
+ .m3-button-group--connected > .m3-button-group__item--overflow-end {
148
150
  --_m3-bg-radius-end: var(--_m3-bg-outer-radius);
149
151
  --_m3-bg-radius-pressed-end: var(--m3-button-group-pressed-radius);
150
152
  }
151
153
 
154
+ /* Checked shape de Compose: el segmento seleccionado pasa a CornerFull en sus
155
+ * cuatro esquinas, incluso en medio del grupo. Va después de line-start/end
156
+ * para ganar el radio exterior/interior. */
157
+ .m3-button-group--connected > .m3-button[aria-pressed="true"] {
158
+ --_m3-bg-radius-start: var(--_m3-bg-outer-radius);
159
+ --_m3-bg-radius-end: var(--_m3-bg-outer-radius);
160
+ --_m3-bg-radius-pressed-start: var(--_m3-bg-outer-radius);
161
+ --_m3-bg-radius-pressed-end: var(--_m3-bg-outer-radius);
162
+ z-index: 1;
163
+ }
164
+
165
+ /* --- Ancho animado -------------------------------------------------------
166
+ * Aproximación CSS de `ButtonGroupScope.animateWidth`: el botón pulsado crece
167
+ * un 15 % y sus vecinos inmediatos comprimen la mitad cada uno. El grupo debe
168
+ * ocupar el ancho disponible; el behavior solo marca `data-pressed` y la clase
169
+ * `is-pressing`. */
170
+ .m3-button-group[data-animate-width] {
171
+ flex-wrap: nowrap;
172
+ inline-size: 100%;
173
+ }
174
+
175
+ .m3-button-group[data-animate-width] > .m3-button,
176
+ .m3-button-group[data-animate-width] > .m3-icon-button {
177
+ flex: 1 1 0;
178
+ transition: flex-grow var(--md-sys-motion-spatial-fast);
179
+ }
180
+
181
+ .m3-button-group[data-animate-width].is-pressing
182
+ > [data-pressed="true"] {
183
+ flex-grow: 1.15;
184
+ }
185
+
186
+ .m3-button-group[data-animate-width].is-pressing
187
+ > [data-pressed="true"] + .m3-button,
188
+ .m3-button-group[data-animate-width].is-pressing
189
+ > [data-pressed="true"] + .m3-icon-button,
190
+ .m3-button-group[data-animate-width].is-pressing
191
+ > .m3-button:has(+ [data-pressed="true"]),
192
+ .m3-button-group[data-animate-width].is-pressing
193
+ > .m3-icon-button:has(+ [data-pressed="true"]) {
194
+ flex-grow: 0.925;
195
+ }
196
+
197
+ /* --- Overflow ------------------------------------------------------------
198
+ * El behavior oculta los ítems que no caben y los replica en un menú. El
199
+ * contenedor opt-in no envuelve: la medición y el menú son su contrato. */
200
+ .m3-button-group--overflow-active {
201
+ flex-wrap: nowrap;
202
+ inline-size: 100%;
203
+ }
204
+
205
+ .m3-button-group__item--overflowed {
206
+ display: none !important;
207
+ }
208
+
209
+ .m3-button-group__overflow {
210
+ display: flex;
211
+ flex: 0 0 auto;
212
+ align-items: center;
213
+ }
214
+
215
+ .m3-button-group__overflow[hidden] {
216
+ display: none;
217
+ }
218
+
152
219
  /* En filled/tonal no se tiñe ningún borde: la separación la da el hueco de
153
220
  * 2 dp. Un borde claro sobre `primary-container` no alcanza 3:1, y un borde
154
221
  * oscuro sobre `secondary-container` tampoco. */