@matekit/react 0.0.0-stage → 0.1.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 +71 -0
- package/LICENSE +202 -0
- package/NOTICE +56 -0
- package/README.md +115 -2
- package/dist/atoms/Divider/Divider.d.ts +49 -0
- package/dist/atoms/Divider/Divider.js +29 -0
- package/dist/atoms/FocusRing/FocusRing.d.ts +16 -0
- package/dist/atoms/FocusRing/FocusRing.js +16 -0
- package/dist/atoms/Group/Group.d.ts +38 -0
- package/dist/atoms/Group/Group.js +34 -0
- package/dist/atoms/Icon/Icon.d.ts +23 -0
- package/dist/atoms/Icon/Icon.js +19 -0
- package/dist/atoms/Interactive/Interactive.d.ts +98 -0
- package/dist/atoms/Interactive/Interactive.js +87 -0
- package/dist/atoms/Ripple/Ripple.d.ts +14 -0
- package/dist/atoms/Ripple/Ripple.js +63 -0
- package/dist/atoms/Shape/Shape.d.ts +24 -0
- package/dist/atoms/Shape/Shape.js +19 -0
- package/dist/atoms/Shape/shapes.d.ts +8 -0
- package/dist/atoms/Shape/shapes.js +40 -0
- package/dist/atoms/Stack/Stack.d.ts +58 -0
- package/dist/atoms/Stack/Stack.js +33 -0
- package/dist/atoms/StateLayer/StateLayer.d.ts +17 -0
- package/dist/atoms/StateLayer/StateLayer.js +17 -0
- package/dist/atoms/index.d.ts +10 -0
- package/dist/atoms/index.js +10 -0
- package/dist/fonts/roboto-flex/OFL.txt +93 -0
- package/dist/fonts/roboto-flex/roboto-flex-cyrillic-ext.woff2 +0 -0
- package/dist/fonts/roboto-flex/roboto-flex-cyrillic.woff2 +0 -0
- package/dist/fonts/roboto-flex/roboto-flex-greek.woff2 +0 -0
- package/dist/fonts/roboto-flex/roboto-flex-latin-ext.woff2 +0 -0
- package/dist/fonts/roboto-flex/roboto-flex-latin.woff2 +0 -0
- package/dist/fonts/roboto-flex/roboto-flex-vietnamese.woff2 +0 -0
- package/dist/icons/icons.d.ts +89 -0
- package/dist/icons/icons.js +186 -0
- package/dist/icons/index.d.ts +1 -0
- package/dist/icons/index.js +3 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +12 -0
- package/dist/internal/accessible-name.d.ts +17 -0
- package/dist/internal/accessible-name.js +33 -0
- package/dist/internal/anchor-position.d.ts +99 -0
- package/dist/internal/anchor-position.js +159 -0
- package/dist/internal/anchored-drag.d.ts +25 -0
- package/dist/internal/anchored-drag.js +106 -0
- package/dist/internal/dev.d.ts +2 -0
- package/dist/internal/dev.js +18 -0
- package/dist/internal/diagnostics.d.ts +46 -0
- package/dist/internal/diagnostics.js +125 -0
- package/dist/internal/group-label.d.ts +22 -0
- package/dist/internal/group-label.js +50 -0
- package/dist/internal/interactive.d.ts +28 -0
- package/dist/internal/interactive.js +18 -0
- package/dist/internal/layout-element.d.ts +21 -0
- package/dist/internal/layout-element.js +33 -0
- package/dist/internal/merge-refs.d.ts +13 -0
- package/dist/internal/merge-refs.js +35 -0
- package/dist/internal/modal-dialog.d.ts +63 -0
- package/dist/internal/modal-dialog.js +267 -0
- package/dist/internal/navigation-count.d.ts +38 -0
- package/dist/internal/navigation-count.js +60 -0
- package/dist/internal/navigation-item.d.ts +14 -0
- package/dist/internal/navigation-item.js +17 -0
- package/dist/internal/nearest-scroller.d.ts +4 -0
- package/dist/internal/nearest-scroller.js +17 -0
- package/dist/internal/open-state.d.ts +15 -0
- package/dist/internal/open-state.js +42 -0
- package/dist/internal/roving-focus.d.ts +41 -0
- package/dist/internal/roving-focus.js +126 -0
- package/dist/internal/settle-animations.d.ts +33 -0
- package/dist/internal/settle-animations.js +48 -0
- package/dist/internal/time-period.d.ts +10 -0
- package/dist/internal/time-period.js +26 -0
- package/dist/internal/time.d.ts +23 -0
- package/dist/internal/time.js +69 -0
- package/dist/internal/typeahead.d.ts +17 -0
- package/dist/internal/typeahead.js +35 -0
- package/dist/molecules/Badge/Badge.d.ts +25 -0
- package/dist/molecules/Badge/Badge.js +16 -0
- package/dist/molecules/Button/Button.d.ts +48 -0
- package/dist/molecules/Button/Button.js +34 -0
- package/dist/molecules/Card/Card.d.ts +159 -0
- package/dist/molecules/Card/Card.js +119 -0
- package/dist/molecules/Checkbox/Checkbox.d.ts +26 -0
- package/dist/molecules/Checkbox/Checkbox.js +40 -0
- package/dist/molecules/Chip/AssistChip.d.ts +23 -0
- package/dist/molecules/Chip/AssistChip.js +22 -0
- package/dist/molecules/Chip/ChipGroup.d.ts +85 -0
- package/dist/molecules/Chip/ChipGroup.js +92 -0
- package/dist/molecules/Chip/FilterChip.d.ts +33 -0
- package/dist/molecules/Chip/FilterChip.js +30 -0
- package/dist/molecules/Chip/InputChip.d.ts +60 -0
- package/dist/molecules/Chip/InputChip.js +107 -0
- package/dist/molecules/Chip/SuggestionChip.d.ts +24 -0
- package/dist/molecules/Chip/SuggestionChip.js +17 -0
- package/dist/molecules/Chip/chip-content.d.ts +39 -0
- package/dist/molecules/Chip/chip-content.js +95 -0
- package/dist/molecules/Chip/chip-element.d.ts +14 -0
- package/dist/molecules/Chip/chip-element.js +14 -0
- package/dist/molecules/Chip/strings.d.ts +8 -0
- package/dist/molecules/Chip/strings.js +5 -0
- package/dist/molecules/Fab/Fab.d.ts +78 -0
- package/dist/molecules/Fab/Fab.js +52 -0
- package/dist/molecules/IconButton/IconButton.d.ts +59 -0
- package/dist/molecules/IconButton/IconButton.js +36 -0
- package/dist/molecules/LoadingIndicator/LoadingIndicator.d.ts +38 -0
- package/dist/molecules/LoadingIndicator/LoadingIndicator.js +25 -0
- package/dist/molecules/LoadingIndicator/determinate.d.ts +3 -0
- package/dist/molecules/LoadingIndicator/determinate.js +47 -0
- package/dist/molecules/LoadingIndicator/loading-indicator-data.d.ts +21 -0
- package/dist/molecules/LoadingIndicator/loading-indicator-data.js +72 -0
- package/dist/molecules/ProgressIndicator/CircularProgressIndicator.d.ts +35 -0
- package/dist/molecules/ProgressIndicator/CircularProgressIndicator.js +30 -0
- package/dist/molecules/ProgressIndicator/LinearProgressIndicator.d.ts +43 -0
- package/dist/molecules/ProgressIndicator/LinearProgressIndicator.js +28 -0
- package/dist/molecules/ProgressIndicator/circular-wavy-data.d.ts +5 -0
- package/dist/molecules/ProgressIndicator/circular-wavy-data.js +19 -0
- package/dist/molecules/ProgressIndicator/progress.d.ts +24 -0
- package/dist/molecules/ProgressIndicator/progress.js +60 -0
- package/dist/molecules/RadioButton/RadioButton.d.ts +27 -0
- package/dist/molecules/RadioButton/RadioButton.js +70 -0
- package/dist/molecules/RadioButton/RadioGroup.d.ts +73 -0
- package/dist/molecules/RadioButton/RadioGroup.js +82 -0
- package/dist/molecules/ScrollField/ScrollField.d.ts +61 -0
- package/dist/molecules/ScrollField/ScrollField.js +352 -0
- package/dist/molecules/Slider/RangeSlider.d.ts +60 -0
- package/dist/molecules/Slider/RangeSlider.js +169 -0
- package/dist/molecules/Slider/Slider.d.ts +54 -0
- package/dist/molecules/Slider/Slider.js +71 -0
- package/dist/molecules/Slider/slider-shared.d.ts +26 -0
- package/dist/molecules/Slider/slider-shared.js +98 -0
- package/dist/molecules/Switch/Switch.d.ts +22 -0
- package/dist/molecules/Switch/Switch.js +20 -0
- package/dist/molecules/TextField/TextField.d.ts +83 -0
- package/dist/molecules/TextField/TextField.js +146 -0
- package/dist/molecules/TextField/TextFieldSlots.d.ts +22 -0
- package/dist/molecules/TextField/TextFieldSlots.js +24 -0
- package/dist/molecules/TimeInput/TimeInput.d.ts +108 -0
- package/dist/molecules/TimeInput/TimeInput.js +347 -0
- package/dist/molecules/TimeInput/strings.d.ts +13 -0
- package/dist/molecules/TimeInput/strings.js +10 -0
- package/dist/molecules/TimeScroll/TimeScroll.d.ts +106 -0
- package/dist/molecules/TimeScroll/TimeScroll.js +213 -0
- package/dist/molecules/TimeScroll/strings.d.ts +13 -0
- package/dist/molecules/TimeScroll/strings.js +12 -0
- package/dist/molecules/index.d.ts +27 -0
- package/dist/molecules/index.js +25 -0
- package/dist/organisms/BottomSheet/BottomSheet.d.ts +128 -0
- package/dist/organisms/BottomSheet/BottomSheet.js +432 -0
- package/dist/organisms/BottomSheet/BottomSheetSlots.d.ts +17 -0
- package/dist/organisms/BottomSheet/BottomSheetSlots.js +16 -0
- package/dist/organisms/BottomSheet/StandardBottomSheet.d.ts +37 -0
- package/dist/organisms/BottomSheet/StandardBottomSheet.js +206 -0
- package/dist/organisms/BottomSheet/bottom-sheet-context.d.ts +31 -0
- package/dist/organisms/BottomSheet/bottom-sheet-context.js +12 -0
- package/dist/organisms/BottomSheet/sheet-drag.d.ts +1 -0
- package/dist/organisms/BottomSheet/sheet-drag.js +4 -0
- package/dist/organisms/BottomSheet/strings.d.ts +9 -0
- package/dist/organisms/BottomSheet/strings.js +8 -0
- package/dist/organisms/ButtonGroup/ButtonGroup.d.ts +97 -0
- package/dist/organisms/ButtonGroup/ButtonGroup.js +242 -0
- package/dist/organisms/ButtonGroup/ButtonGroupItem.d.ts +36 -0
- package/dist/organisms/ButtonGroup/ButtonGroupItem.js +47 -0
- package/dist/organisms/Dialog/Dialog.d.ts +186 -0
- package/dist/organisms/Dialog/Dialog.js +193 -0
- package/dist/organisms/Dialog/DialogSlots.d.ts +60 -0
- package/dist/organisms/Dialog/DialogSlots.js +54 -0
- package/dist/organisms/Dialog/strings.d.ts +5 -0
- package/dist/organisms/Dialog/strings.js +5 -0
- package/dist/organisms/FabMenu/FabMenu.d.ts +104 -0
- package/dist/organisms/FabMenu/FabMenu.js +142 -0
- package/dist/organisms/FabMenu/strings.d.ts +9 -0
- package/dist/organisms/FabMenu/strings.js +5 -0
- package/dist/organisms/List/List.d.ts +190 -0
- package/dist/organisms/List/List.js +148 -0
- package/dist/organisms/Menu/Menu.d.ts +313 -0
- package/dist/organisms/Menu/Menu.js +865 -0
- package/dist/organisms/Menu/MenuSlots.d.ts +35 -0
- package/dist/organisms/Menu/MenuSlots.js +36 -0
- package/dist/organisms/NavigationBar/NavigationBar.d.ts +96 -0
- package/dist/organisms/NavigationBar/NavigationBar.js +77 -0
- package/dist/organisms/NavigationRail/ModalNavigationRail.d.ts +105 -0
- package/dist/organisms/NavigationRail/ModalNavigationRail.js +272 -0
- package/dist/organisms/NavigationRail/NavigationRail.d.ts +148 -0
- package/dist/organisms/NavigationRail/NavigationRail.js +114 -0
- package/dist/organisms/NavigationRail/NavigationRailSection.d.ts +54 -0
- package/dist/organisms/NavigationRail/NavigationRailSection.js +96 -0
- package/dist/organisms/NavigationRail/strings.d.ts +7 -0
- package/dist/organisms/NavigationRail/strings.js +7 -0
- package/dist/organisms/NavigationSuite/NavigationSuite.d.ts +109 -0
- package/dist/organisms/NavigationSuite/NavigationSuite.js +86 -0
- package/dist/organisms/PaneScaffold/PaneScaffold.d.ts +106 -0
- package/dist/organisms/PaneScaffold/PaneScaffold.js +120 -0
- package/dist/organisms/Search/Search.d.ts +207 -0
- package/dist/organisms/Search/Search.js +754 -0
- package/dist/organisms/Search/SearchSlots.d.ts +16 -0
- package/dist/organisms/Search/SearchSlots.js +17 -0
- package/dist/organisms/Search/strings.d.ts +21 -0
- package/dist/organisms/Search/strings.js +12 -0
- package/dist/organisms/Select/Select.d.ts +186 -0
- package/dist/organisms/Select/Select.js +597 -0
- package/dist/organisms/Select/SelectSlots.d.ts +12 -0
- package/dist/organisms/Select/SelectSlots.js +12 -0
- package/dist/organisms/SideSheet/SideSheet.d.ts +88 -0
- package/dist/organisms/SideSheet/SideSheet.js +109 -0
- package/dist/organisms/SideSheet/SideSheetSlots.d.ts +35 -0
- package/dist/organisms/SideSheet/SideSheetSlots.js +37 -0
- package/dist/organisms/SideSheet/strings.d.ts +7 -0
- package/dist/organisms/SideSheet/strings.js +6 -0
- package/dist/organisms/Snackbar/Snackbar.d.ts +46 -0
- package/dist/organisms/Snackbar/Snackbar.js +36 -0
- package/dist/organisms/Snackbar/SnackbarHost.d.ts +57 -0
- package/dist/organisms/Snackbar/SnackbarHost.js +221 -0
- package/dist/organisms/Snackbar/snackbar-queue.d.ts +81 -0
- package/dist/organisms/Snackbar/snackbar-queue.js +114 -0
- package/dist/organisms/Snackbar/strings.d.ts +8 -0
- package/dist/organisms/Snackbar/strings.js +5 -0
- package/dist/organisms/SplitButton/SplitButton.d.ts +73 -0
- package/dist/organisms/SplitButton/SplitButton.js +77 -0
- package/dist/organisms/SplitButton/strings.d.ts +9 -0
- package/dist/organisms/SplitButton/strings.js +5 -0
- package/dist/organisms/Tabs/TabLink.d.ts +27 -0
- package/dist/organisms/Tabs/TabLink.js +25 -0
- package/dist/organisms/Tabs/TabNav.d.ts +19 -0
- package/dist/organisms/Tabs/TabNav.js +55 -0
- package/dist/organisms/Tabs/Tabs.d.ts +147 -0
- package/dist/organisms/Tabs/Tabs.js +223 -0
- package/dist/organisms/Tabs/tab-content.d.ts +23 -0
- package/dist/organisms/Tabs/tab-content.js +105 -0
- package/dist/organisms/Tabs/tab-fit.d.ts +4 -0
- package/dist/organisms/Tabs/tab-fit.js +65 -0
- package/dist/organisms/Tabs/tab-motion.d.ts +2 -0
- package/dist/organisms/Tabs/tab-motion.js +68 -0
- package/dist/organisms/TimePickerDialog/TimePickerDialog.d.ts +26 -0
- package/dist/organisms/TimePickerDialog/TimePickerDialog.js +34 -0
- package/dist/organisms/Toolbar/Toolbar.d.ts +75 -0
- package/dist/organisms/Toolbar/Toolbar.js +84 -0
- package/dist/organisms/Toolbar/ToolbarLayout.d.ts +44 -0
- package/dist/organisms/Toolbar/ToolbarLayout.js +90 -0
- package/dist/organisms/Toolbar/ToolbarScroll.d.ts +8 -0
- package/dist/organisms/Toolbar/ToolbarScroll.js +222 -0
- package/dist/organisms/Tooltip/RichTooltip.d.ts +73 -0
- package/dist/organisms/Tooltip/RichTooltip.js +250 -0
- package/dist/organisms/Tooltip/Tooltip.d.ts +52 -0
- package/dist/organisms/Tooltip/Tooltip.js +99 -0
- package/dist/organisms/Tooltip/tooltip-behavior.d.ts +43 -0
- package/dist/organisms/Tooltip/tooltip-behavior.js +307 -0
- package/dist/organisms/TopAppBar/TopAppBar.d.ts +107 -0
- package/dist/organisms/TopAppBar/TopAppBar.js +78 -0
- package/dist/organisms/TopAppBar/TopAppBarScroll.d.ts +7 -0
- package/dist/organisms/TopAppBar/TopAppBarScroll.js +155 -0
- package/dist/organisms/index.d.ts +36 -0
- package/dist/organisms/index.js +36 -0
- package/dist/palettes/blue.css +275 -0
- package/dist/palettes/green.css +275 -0
- package/dist/palettes/index.css +823 -0
- package/dist/palettes/orange.css +275 -0
- package/dist/shapes.css +115 -0
- package/dist/strings/index.d.ts +35 -0
- package/dist/strings/index.js +39 -0
- package/dist/styles-no-fonts.css +11991 -0
- package/dist/styles.css +12089 -0
- package/dist/stylesheet.d.ts +2 -0
- package/dist/tokens/breakpoints.d.ts +33 -0
- package/dist/tokens/breakpoints.js +31 -0
- package/dist/tokens/space.d.ts +26 -0
- package/dist/tokens/space.js +26 -0
- package/package.json +110 -3
|
@@ -0,0 +1,865 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
// Organismo interactivo (ADR-0003). Menu guarda el estado abierto/cerrado (controlado o no) y lo
|
|
4
|
+
// comparte por contexto; MenuTrigger agrega al botón del usuario los atributos ARIA y los
|
|
5
|
+
// eventos que lo abren; MenuContent muestra el popover, mueve el foco, escucha el teclado y el
|
|
6
|
+
// clic afuera, y espera el fin de la animación de salida; MenuItem avisa la elección y cierra.
|
|
7
|
+
// Todo eso necesita estado, efectos, contexto o eventos, así que estas cuatro partes son cliente.
|
|
8
|
+
// Los submenús (ADR-0040) repiten la forma: MenuSub guarda el estado del submenú, MenuSubTrigger es el
|
|
9
|
+
// elemento que lo abre (clic, teclado o puntero con demora) y MenuSubContent es otra capa del mismo
|
|
10
|
+
// MenuSurface interno que dibuja MenuContent, al costado del elemento.
|
|
11
|
+
// MenuGroup, MenuGroupLabel y MenuItemSupporting también son cliente: comparten por contexto el id
|
|
12
|
+
// de la etiqueta del grupo (con la base de src/internal/group-label.tsx, común con SelectGroupLabel)
|
|
13
|
+
// y el del texto de apoyo del elemento (ADR-0039). MenuDivider,
|
|
14
|
+
// MenuItemLeading y MenuItemTrailing no necesitan nada de eso y son universales: están en
|
|
15
|
+
// MenuSlots.tsx.
|
|
16
|
+
//
|
|
17
|
+
// Posicionamiento: CSS anchor positioning, con un respaldo en JavaScript para navegadores que
|
|
18
|
+
// no lo tienen (ADR-0007), compartido con Tooltip en src/internal/anchor-position.ts. El submenú se
|
|
19
|
+
// ubica siempre con placeBeside, del mismo módulo, sin anchor positioning (ADR-0040).
|
|
20
|
+
import { cloneElement, createContext, isValidElement, use, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, } from 'react';
|
|
21
|
+
import { FocusRing } from '../../atoms/FocusRing/FocusRing.js';
|
|
22
|
+
import { Ripple } from '../../atoms/Ripple/Ripple.js';
|
|
23
|
+
import { StateLayer } from '../../atoms/StateLayer/StateLayer.js';
|
|
24
|
+
import { mergeRefs } from '../../internal/merge-refs.js';
|
|
25
|
+
import { mkWarn, partOutsideParent, triggerNotElement } from '../../internal/diagnostics.js';
|
|
26
|
+
import { settleAnimations } from '../../internal/settle-animations.js';
|
|
27
|
+
import { followAnchor, placeBeside, placeNextTo, supportsAnchorPositioning } from '../../internal/anchor-position.js';
|
|
28
|
+
import { useOpenState } from '../../internal/open-state.js';
|
|
29
|
+
import { createTypeahead, typeaheadMatch } from '../../internal/typeahead.js';
|
|
30
|
+
import { useRegisteredId } from '../../internal/modal-dialog.js';
|
|
31
|
+
import { GroupLabel, useGroupLabel } from '../../internal/group-label.js';
|
|
32
|
+
import { isDevelopment } from '../../internal/dev.js';
|
|
33
|
+
import { ArrowRightIcon } from '../../icons/icons.js';
|
|
34
|
+
// Cierres que cierran todo el árbol de menús (el submenú los pasa hacia arriba, hasta el Menu).
|
|
35
|
+
const closesTree = (reason) => reason === 'select' || reason === 'tab' || reason === 'outside';
|
|
36
|
+
const MenuContext = createContext(null);
|
|
37
|
+
// El estado del Menu más cercano; fuera de uno lanza `MK_PART_OUTSIDE_PARENT` con el nombre de la
|
|
38
|
+
// parte. Exportado para las partes de otros componentes que van dentro de un Menu
|
|
39
|
+
// (`SplitButtonTrigger`), que así nombran su propio error; no está en el índice público.
|
|
40
|
+
export function useMenu(part) {
|
|
41
|
+
const ctx = use(MenuContext);
|
|
42
|
+
if (!ctx)
|
|
43
|
+
throw partOutsideParent(part, 'Menu');
|
|
44
|
+
return ctx;
|
|
45
|
+
}
|
|
46
|
+
const cx = (base, extra) => (extra ? `${base} ${extra}` : base);
|
|
47
|
+
const ITEM_SELECTOR = '[role="menuitem"], [role="menuitemradio"], [role="menuitemcheckbox"]';
|
|
48
|
+
const MENU_SELECTOR = '[role="menu"]';
|
|
49
|
+
// Elementos del menú en orden, incluidos los deshabilitados (APG: se enfocan, no se activan). Solo los
|
|
50
|
+
// de este nivel: un submenú está dentro del menú en el DOM (ADR-0040), y sus elementos son de él.
|
|
51
|
+
function menuItems(menu) {
|
|
52
|
+
return [...menu.querySelectorAll(ITEM_SELECTOR)].filter((el) => el.closest(MENU_SELECTOR) === menu && el.checkVisibility());
|
|
53
|
+
}
|
|
54
|
+
// Lo que el puntero descansa en un MenuSubTrigger antes de abrir su submenú, y lo que el submenú espera
|
|
55
|
+
// al puntero después de que sale del disparador: 400 ms, `hoverOpenDelay` y `hoverCloseDelay` del
|
|
56
|
+
// `md-sub-menu` de Material Web (menu/internal/submenu/sub-menu.ts, commit 58ce7b620c). Exportado para
|
|
57
|
+
// las pruebas; no está en el índice público.
|
|
58
|
+
export const MENU_SUB_HOVER_DELAY = 400;
|
|
59
|
+
const matchesOpen = (el) => el.matches(':popover-open');
|
|
60
|
+
const GROUP_CLASS = 'mk-menu-group';
|
|
61
|
+
const isGroup = (el) => el.classList.contains(GROUP_CLASS);
|
|
62
|
+
const isGroupedMenu = (menu) => [...menu.children].some(isGroup);
|
|
63
|
+
// El puntero cayó en la barra de desplazamiento del propio menú: fuera de su caja de relleno, que es
|
|
64
|
+
// donde se dibuja el contenido (offsetX y offsetY se miden desde el borde de relleno, sin la escala
|
|
65
|
+
// de la entrada; en RTL la barra queda a la izquierda y offsetX da negativo).
|
|
66
|
+
function onScrollbar(menu, e) {
|
|
67
|
+
return e.offsetX < 0 || e.offsetY < 0 || e.offsetX >= menu.clientWidth || e.offsetY >= menu.clientHeight;
|
|
68
|
+
}
|
|
69
|
+
// Texto de un elemento para la búsqueda por letra: el de la etiqueta, sin el texto de apoyo
|
|
70
|
+
// (MenuItemSupporting), que va debajo y no es parte del nombre.
|
|
71
|
+
const SUPPORTING_CLASS = 'mk-menu-item-supporting';
|
|
72
|
+
function itemText(item) {
|
|
73
|
+
let text = '';
|
|
74
|
+
for (const node of item.childNodes) {
|
|
75
|
+
if (node instanceof HTMLElement && node.classList.contains(SUPPORTING_CLASS))
|
|
76
|
+
continue;
|
|
77
|
+
text += node.textContent ?? '';
|
|
78
|
+
}
|
|
79
|
+
return text;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Material 3 Expressive menu, with the WAI-ARIA APG "menu button" pattern. It renders no element:
|
|
83
|
+
* it groups the trigger (`MenuTrigger`) and the menu (`MenuContent`).
|
|
84
|
+
*
|
|
85
|
+
* ```tsx
|
|
86
|
+
* <Menu>
|
|
87
|
+
* <MenuTrigger><IconButton label="More options"><MoreVertIcon /></IconButton></MenuTrigger>
|
|
88
|
+
* <MenuContent>
|
|
89
|
+
* <MenuItem onSelect={edit}><MenuItemLeading><EditIcon /></MenuItemLeading>Edit</MenuItem>
|
|
90
|
+
* <MenuDivider />
|
|
91
|
+
* <MenuItem onSelect={remove}><MenuItemLeading><DeleteIcon /></MenuItemLeading>Delete</MenuItem>
|
|
92
|
+
* </MenuContent>
|
|
93
|
+
* </Menu>
|
|
94
|
+
* ```
|
|
95
|
+
*
|
|
96
|
+
* - **Keyboard:** on the trigger, Enter, Space and Down Arrow open the menu and focus the first
|
|
97
|
+
* item; Up Arrow opens it and focuses the last one. In the menu, the arrows move with
|
|
98
|
+
* wrap-around, Home and End go to the ends, a letter focuses the next item that starts with it,
|
|
99
|
+
* Escape closes and returns focus to the trigger, and Tab closes and moves to the next focusable.
|
|
100
|
+
* - **Choosing** an item calls its `onSelect` and closes the menu; `event.preventDefault()` in
|
|
101
|
+
* `onSelect` keeps it open (for example, in a `menuitemcheckbox`).
|
|
102
|
+
* - A click outside the menu and the trigger closes it, without moving focus.
|
|
103
|
+
*/
|
|
104
|
+
export function Menu({ open, defaultOpen, onOpenChange, children }) {
|
|
105
|
+
// Abierto controlado o no, con el motivo (src/internal/open-state.ts, ADR-0034).
|
|
106
|
+
const { isOpen, setOpen } = useOpenState({ open, defaultOpen, onOpenChange });
|
|
107
|
+
const [focusRequest, setFocusRequest] = useState(0);
|
|
108
|
+
const [triggerId, setTriggerId] = useState(undefined);
|
|
109
|
+
const focusTarget = useRef('first');
|
|
110
|
+
const returnFocus = useRef(true);
|
|
111
|
+
const triggerRef = useRef(null);
|
|
112
|
+
const contentRef = useRef(null);
|
|
113
|
+
const closeReason = useRef(null);
|
|
114
|
+
const id = useId();
|
|
115
|
+
const requestOpen = useCallback((focus) => {
|
|
116
|
+
focusTarget.current = focus;
|
|
117
|
+
setFocusRequest((n) => n + 1);
|
|
118
|
+
setOpen(true, 'trigger');
|
|
119
|
+
}, [setOpen]);
|
|
120
|
+
const requestClose = useCallback((reason) => {
|
|
121
|
+
// Solo los submenús se cierran por las flechas, el puntero o al abrirse otro (CloseRequest).
|
|
122
|
+
if (reason === 'arrow' || reason === 'hover' || reason === 'replaced')
|
|
123
|
+
return;
|
|
124
|
+
closeReason.current = reason;
|
|
125
|
+
returnFocus.current = reason !== 'outside';
|
|
126
|
+
setOpen(false, reason);
|
|
127
|
+
}, [setOpen]);
|
|
128
|
+
const closedBecause = useCallback(() => closeReason.current, []);
|
|
129
|
+
// Un motivo viejo no tiene que llegar a los submenús si después la app cierra el menú controlado.
|
|
130
|
+
useLayoutEffect(() => {
|
|
131
|
+
if (isOpen)
|
|
132
|
+
closeReason.current = null;
|
|
133
|
+
}, [isOpen]);
|
|
134
|
+
const ctx = useMemo(() => {
|
|
135
|
+
return {
|
|
136
|
+
open: isOpen,
|
|
137
|
+
requestOpen,
|
|
138
|
+
requestClose,
|
|
139
|
+
closedBecause,
|
|
140
|
+
rootTriggerRef: triggerRef,
|
|
141
|
+
parentOpen: undefined,
|
|
142
|
+
focusRequest,
|
|
143
|
+
focusTarget,
|
|
144
|
+
returnFocus,
|
|
145
|
+
triggerRef,
|
|
146
|
+
contentRef,
|
|
147
|
+
triggerId,
|
|
148
|
+
setTriggerId,
|
|
149
|
+
generatedTriggerId: `${id}trigger`,
|
|
150
|
+
contentId: `${id}menu`,
|
|
151
|
+
anchorName: anchorNameOf(id),
|
|
152
|
+
};
|
|
153
|
+
}, [id, isOpen, requestOpen, requestClose, closedBecause, focusRequest, triggerId]);
|
|
154
|
+
return _jsx(MenuContext, { value: ctx, children: children });
|
|
155
|
+
}
|
|
156
|
+
// anchor-name tiene que ser un <dashed-ident>: sin los caracteres que pone useId.
|
|
157
|
+
const anchorNameOf = (id) => `--mk-menu-${id.replace(/[^a-zA-Z0-9_-]/g, '')}`;
|
|
158
|
+
/**
|
|
159
|
+
* Turns the child button into the menu's trigger, without adding elements: it adds
|
|
160
|
+
* `aria-haspopup="menu"`, `aria-expanded`, `aria-controls`, an `id` (if it has none), the
|
|
161
|
+
* `anchor-name` the menu uses to sit next to it and the events that open it. Its own `onClick`,
|
|
162
|
+
* `onKeyDown`, `style` and `ref` are kept; an `onClick` that calls `preventDefault()` keeps the menu
|
|
163
|
+
* from opening or closing.
|
|
164
|
+
*
|
|
165
|
+
* ```tsx
|
|
166
|
+
* <MenuTrigger><Button variant="tonal">Sort</Button></MenuTrigger>
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
export function MenuTrigger({ children }) {
|
|
170
|
+
const ctx = useMenu('MenuTrigger');
|
|
171
|
+
// Sin Children.only: su error genérico de React taparía el de matekit (MK_TRIGGER_NOT_ELEMENT),
|
|
172
|
+
// que salta en los mismos casos (varios hijos, un texto, nada).
|
|
173
|
+
const child = children;
|
|
174
|
+
if (!isValidElement(child)) {
|
|
175
|
+
throw triggerNotElement('MenuTrigger', child);
|
|
176
|
+
}
|
|
177
|
+
const { id: ownId, style, onClick, onKeyDown, ref } = child.props;
|
|
178
|
+
const id = ownId ?? ctx.generatedTriggerId;
|
|
179
|
+
const { setTriggerId } = ctx;
|
|
180
|
+
useLayoutEffect(() => {
|
|
181
|
+
setTriggerId(id);
|
|
182
|
+
return () => setTriggerId(undefined);
|
|
183
|
+
}, [id, setTriggerId]);
|
|
184
|
+
const mergedRef = useMemo(() => mergeRefs(ref, ctx.triggerRef), [ref, ctx.triggerRef]);
|
|
185
|
+
return cloneElement(child, {
|
|
186
|
+
id,
|
|
187
|
+
ref: mergedRef,
|
|
188
|
+
style: { ...style, anchorName: ctx.anchorName },
|
|
189
|
+
'aria-haspopup': 'menu',
|
|
190
|
+
'aria-expanded': ctx.open,
|
|
191
|
+
'aria-controls': ctx.contentId,
|
|
192
|
+
onClick: (e) => {
|
|
193
|
+
onClick?.(e);
|
|
194
|
+
if (e.defaultPrevented)
|
|
195
|
+
return;
|
|
196
|
+
// Enter y Espacio en un <button> también llegan acá, como clic.
|
|
197
|
+
if (ctx.open)
|
|
198
|
+
ctx.requestClose('trigger');
|
|
199
|
+
else
|
|
200
|
+
ctx.requestOpen('first');
|
|
201
|
+
},
|
|
202
|
+
onKeyDown: (e) => {
|
|
203
|
+
onKeyDown?.(e);
|
|
204
|
+
if (e.defaultPrevented)
|
|
205
|
+
return;
|
|
206
|
+
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
|
207
|
+
e.preventDefault();
|
|
208
|
+
ctx.requestOpen(e.key === 'ArrowDown' ? 'first' : 'last');
|
|
209
|
+
}
|
|
210
|
+
},
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
const MenuLevelContext = createContext(null);
|
|
214
|
+
const SUB_CLASS = 'mk-menu-sub';
|
|
215
|
+
// La superficie visible de una capa: con grupos, el contenedor se agranda 16 px por la sombra
|
|
216
|
+
// (menu.css) y lo que se ve es la unión de los grupos.
|
|
217
|
+
function surfaceRect(menu) {
|
|
218
|
+
const groups = [...menu.children].filter(isGroup);
|
|
219
|
+
if (groups.length === 0)
|
|
220
|
+
return menu.getBoundingClientRect();
|
|
221
|
+
const rects = groups.map((g) => g.getBoundingClientRect());
|
|
222
|
+
const left = Math.min(...rects.map((r) => r.left));
|
|
223
|
+
const top = Math.min(...rects.map((r) => r.top));
|
|
224
|
+
const right = Math.max(...rects.map((r) => r.right));
|
|
225
|
+
const bottom = Math.max(...rects.map((r) => r.bottom));
|
|
226
|
+
return new DOMRect(left, top, right - left, bottom - top);
|
|
227
|
+
}
|
|
228
|
+
// El punto está en el triángulo entre la salida del disparador (corrida 4 px hacia atrás, así el
|
|
229
|
+
// primer movimiento después de salir también cuenta) y las dos esquinas del borde cercano del submenú.
|
|
230
|
+
function inGrace(grace, x, y) {
|
|
231
|
+
const content = grace.sub.contentRef.current;
|
|
232
|
+
if (!content)
|
|
233
|
+
return false;
|
|
234
|
+
const r = surfaceRect(content);
|
|
235
|
+
const toRight = r.left >= grace.x - 1;
|
|
236
|
+
const edge = toRight ? r.left : r.right;
|
|
237
|
+
const ax = grace.x + (toRight ? -4 : 4);
|
|
238
|
+
const ay = grace.y;
|
|
239
|
+
const cross = (x1, y1, x2, y2) => (x2 - x1) * (y - y1) - (y2 - y1) * (x - x1);
|
|
240
|
+
const d1 = cross(ax, ay, edge, r.top);
|
|
241
|
+
const d2 = cross(edge, r.top, edge, r.bottom);
|
|
242
|
+
const d3 = cross(edge, r.bottom, ax, ay);
|
|
243
|
+
const negative = d1 < 0 || d2 < 0 || d3 < 0;
|
|
244
|
+
const positive = d1 > 0 || d2 > 0 || d3 > 0;
|
|
245
|
+
return !(negative && positive);
|
|
246
|
+
}
|
|
247
|
+
// La capa de un nivel: MenuContent (la raíz) y MenuSubContent la dibujan igual. Cambia la posición
|
|
248
|
+
// (debajo del disparador o al costado del elemento), quién escucha el clic afuera (la raíz, por todo
|
|
249
|
+
// el árbol) y las teclas para volver (solo el submenú).
|
|
250
|
+
function MenuSurface({ ctx, part, color, className, style, children, ref, onKeyDown, onPointerMove, ...props }) {
|
|
251
|
+
const { open, focusRequest, focusTarget, returnFocus, triggerRef, contentRef, requestClose, parentOpen } = ctx;
|
|
252
|
+
const isSub = parentOpen !== undefined;
|
|
253
|
+
const mergedRef = useMemo(() => mergeRefs(ref, contentRef), [ref, contentRef]);
|
|
254
|
+
// Salida en curso: identifica el cierre pendiente para anularlo si se vuelve a abrir.
|
|
255
|
+
const closing = useRef(null);
|
|
256
|
+
const typeahead = useRef(createTypeahead());
|
|
257
|
+
// El submenú abierto de este nivel y la gracia del puntero (ADR-0040).
|
|
258
|
+
const openSub = useRef(null);
|
|
259
|
+
const grace = useRef(null);
|
|
260
|
+
const level = useMemo(() => {
|
|
261
|
+
const cancelGrace = () => {
|
|
262
|
+
if (grace.current)
|
|
263
|
+
clearTimeout(grace.current.timer);
|
|
264
|
+
grace.current = null;
|
|
265
|
+
};
|
|
266
|
+
const startGrace = (sub, x, y) => {
|
|
267
|
+
cancelGrace();
|
|
268
|
+
const timer = setTimeout(() => {
|
|
269
|
+
if (grace.current?.timer !== timer)
|
|
270
|
+
return;
|
|
271
|
+
grace.current = null;
|
|
272
|
+
if (openSub.current === sub)
|
|
273
|
+
sub.close('hover');
|
|
274
|
+
}, MENU_SUB_HOVER_DELAY);
|
|
275
|
+
grace.current = { sub, x, y, timer };
|
|
276
|
+
};
|
|
277
|
+
return { color, openSub, startGrace, cancelGrace };
|
|
278
|
+
}, [color]);
|
|
279
|
+
useEffect(() => () => level.cancelGrace(), [level]);
|
|
280
|
+
// Ubicar el menú: con anchor positioning solo se anota de qué lado quedó (para el origen de
|
|
281
|
+
// la animación); sin él, se calcula la posición (respaldo, ADR-0007).
|
|
282
|
+
const place = useCallback(() => {
|
|
283
|
+
const menu = contentRef.current;
|
|
284
|
+
const trigger = triggerRef.current;
|
|
285
|
+
if (!menu || !trigger)
|
|
286
|
+
return;
|
|
287
|
+
if (isSub)
|
|
288
|
+
placeBeside(menu, trigger);
|
|
289
|
+
else
|
|
290
|
+
placeNextTo(menu, trigger);
|
|
291
|
+
}, [contentRef, triggerRef, isSub]);
|
|
292
|
+
useLayoutEffect(() => {
|
|
293
|
+
const menu = contentRef.current;
|
|
294
|
+
if (!menu)
|
|
295
|
+
return;
|
|
296
|
+
if (open) {
|
|
297
|
+
let cancelled = false;
|
|
298
|
+
const show = () => {
|
|
299
|
+
if (cancelled)
|
|
300
|
+
return;
|
|
301
|
+
closing.current = null;
|
|
302
|
+
menu.removeAttribute('data-closing');
|
|
303
|
+
if (!matchesOpen(menu)) {
|
|
304
|
+
menu.showPopover();
|
|
305
|
+
place();
|
|
306
|
+
// Un submenú que se abre mientras su menú todavía entra (con la escala de la entrada) se mide
|
|
307
|
+
// contra un disparador escalado: se vuelve a ubicar cuando la entrada del menú termina.
|
|
308
|
+
const parent = isSub ? menu.parentElement?.closest(MENU_SELECTOR) : null;
|
|
309
|
+
const entering = parent?.getAnimations() ?? [];
|
|
310
|
+
if (entering.length > 0) {
|
|
311
|
+
void Promise.allSettled(entering.map((a) => a.finished)).then(() => {
|
|
312
|
+
if (!cancelled && matchesOpen(menu))
|
|
313
|
+
place();
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
const target = focusTarget.current;
|
|
318
|
+
focusTarget.current = 'first';
|
|
319
|
+
if (target === 'none')
|
|
320
|
+
return;
|
|
321
|
+
const items = menuItems(menu);
|
|
322
|
+
((target === 'last' ? items.at(-1) : items[0]) ?? menu).focus();
|
|
323
|
+
};
|
|
324
|
+
// Un submenú que se abre junto con su menú (defaultOpen o controlado) corre este efecto antes que
|
|
325
|
+
// el del menú (los efectos van de los hijos a los padres): mostrado primero, quedaría debajo del
|
|
326
|
+
// menú en la capa superior y se mediría contra un disparador sin dibujar. Se espera a que termine
|
|
327
|
+
// el commit, cuando el menú ya se mostró.
|
|
328
|
+
const parentMenu = isSub ? menu.parentElement?.closest(MENU_SELECTOR) : null;
|
|
329
|
+
if (parentMenu && !matchesOpen(parentMenu)) {
|
|
330
|
+
queueMicrotask(show);
|
|
331
|
+
return () => {
|
|
332
|
+
cancelled = true;
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
show();
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
if (!matchesOpen(menu) || closing.current)
|
|
339
|
+
return;
|
|
340
|
+
// Devolver el foco al disparador si estaba en el menú (o se perdió), salvo tras un clic
|
|
341
|
+
// afuera: ahí el usuario eligió otro lugar. Un submenú que se cierra porque se cerró el menú
|
|
342
|
+
// que lo contiene no lo devuelve: de eso se ocupa ese menú.
|
|
343
|
+
const active = document.activeElement;
|
|
344
|
+
if (returnFocus.current &&
|
|
345
|
+
parentOpen !== false &&
|
|
346
|
+
(!active || active === document.body || menu.contains(active))) {
|
|
347
|
+
triggerRef.current?.focus();
|
|
348
|
+
}
|
|
349
|
+
returnFocus.current = true;
|
|
350
|
+
// Salida: data-closing dispara las transiciones (menu.css); se oculta al terminar.
|
|
351
|
+
// getAnimations() fuerza el cálculo de estilos, así que ya las incluye; sin transiciones,
|
|
352
|
+
// la lista está vacía y se oculta enseguida. Mismo patrón que Dialog.
|
|
353
|
+
const token = {};
|
|
354
|
+
closing.current = token;
|
|
355
|
+
menu.setAttribute('data-closing', '');
|
|
356
|
+
// src/internal/settle-animations.ts. Si se volvió a abrir, `closing` ya no es esta ficha.
|
|
357
|
+
// Con data-settle-subtree (FabMenuContent, ADR-0033), la salida son transiciones de los
|
|
358
|
+
// elementos y no del contenedor: se esperan también las de los descendientes.
|
|
359
|
+
const subtree = menu.hasAttribute('data-settle-subtree');
|
|
360
|
+
void settleAnimations(menu, () => closing.current === token, { subtree }).then(() => {
|
|
361
|
+
if (closing.current !== token)
|
|
362
|
+
return;
|
|
363
|
+
closing.current = null;
|
|
364
|
+
menu.removeAttribute('data-closing');
|
|
365
|
+
if (matchesOpen(menu))
|
|
366
|
+
menu.hidePopover();
|
|
367
|
+
});
|
|
368
|
+
}, [open, focusRequest, contentRef, triggerRef, focusTarget, returnFocus, place, parentOpen]);
|
|
369
|
+
useLayoutEffect(() => () => {
|
|
370
|
+
closing.current = null;
|
|
371
|
+
}, []);
|
|
372
|
+
// Mientras está abierto: clic afuera cierra (lo escucha la raíz, por todo el árbol: los submenús
|
|
373
|
+
// están dentro de ella en el DOM); sin anchor positioning, seguir al disparador cuando la página se
|
|
374
|
+
// desplaza o cambia de tamaño.
|
|
375
|
+
useEffect(() => {
|
|
376
|
+
if (!open)
|
|
377
|
+
return;
|
|
378
|
+
const menu = contentRef.current;
|
|
379
|
+
const onPointerDown = (e) => {
|
|
380
|
+
const target = e.target;
|
|
381
|
+
if (!target)
|
|
382
|
+
return;
|
|
383
|
+
// Con grupos, el contenedor solo recibe el puntero si tiene una barra clásica (abajo): un toque
|
|
384
|
+
// en su borde transparente o entre dos grupos es afuera; en la barra, no. Vale para cada capa del
|
|
385
|
+
// árbol (la del menú o la de un submenú).
|
|
386
|
+
const hit = target instanceof HTMLElement && target.matches(MENU_SELECTOR) ? target : null;
|
|
387
|
+
if (hit && isGroupedMenu(hit) && !onScrollbar(hit, e)) {
|
|
388
|
+
requestClose('outside');
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
if (menu?.contains(target) || triggerRef.current?.contains(target))
|
|
392
|
+
return;
|
|
393
|
+
requestClose('outside');
|
|
394
|
+
};
|
|
395
|
+
if (!isSub)
|
|
396
|
+
document.addEventListener('pointerdown', onPointerDown, true);
|
|
397
|
+
// El submenú se ubica siempre con JavaScript (placeBeside, ADR-0040): se vuelve a ubicar con el
|
|
398
|
+
// desplazamiento y el cambio de tamaño, como el respaldo del menú. El menú, anclado por el navegador,
|
|
399
|
+
// recién se corre en el cuadro siguiente al evento de desplazamiento (Chrome y Firefox, comprobado el
|
|
400
|
+
// 2026-11-29 con un contenedor que se desplaza): se repite en los dos cuadros que siguen.
|
|
401
|
+
let frame = 0;
|
|
402
|
+
const follow = isSub
|
|
403
|
+
? () => {
|
|
404
|
+
place();
|
|
405
|
+
cancelAnimationFrame(frame);
|
|
406
|
+
frame = requestAnimationFrame(() => {
|
|
407
|
+
place();
|
|
408
|
+
frame = requestAnimationFrame(place);
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
: place;
|
|
412
|
+
const unfollow = followAnchor(follow, !isSub && supportsAnchorPositioning());
|
|
413
|
+
// Barra de desplazamiento clásica (no superpuesta: Windows, o macOS con "mostrar siempre"): ocupa
|
|
414
|
+
// ancho. Con grupos, el contenedor no toma el puntero (menu.css) y la barra, que es suya, no se
|
|
415
|
+
// podría arrastrar; data-classic-scrollbar le devuelve el puntero. Se mide al abrir y cada vez que
|
|
416
|
+
// el menú cambia de tamaño (la barra aparece cuando el contenido pasa el alto máximo).
|
|
417
|
+
const measure = () => {
|
|
418
|
+
if (menu)
|
|
419
|
+
menu.toggleAttribute('data-classic-scrollbar', menu.offsetWidth - menu.clientWidth > 0);
|
|
420
|
+
};
|
|
421
|
+
const resize = new ResizeObserver(measure);
|
|
422
|
+
if (menu)
|
|
423
|
+
resize.observe(menu);
|
|
424
|
+
return () => {
|
|
425
|
+
document.removeEventListener('pointerdown', onPointerDown, true);
|
|
426
|
+
unfollow();
|
|
427
|
+
cancelAnimationFrame(frame);
|
|
428
|
+
resize.disconnect();
|
|
429
|
+
};
|
|
430
|
+
}, [open, contentRef, triggerRef, requestClose, place, isSub]);
|
|
431
|
+
// Con algún MenuGroup, un hijo directo que no es un grupo (un MenuItem, un MenuDivider) queda sin
|
|
432
|
+
// superficie: el contenedor ya no pinta (menu.css, `:has(> .mk-menu-group)`). Se revisa en el DOM
|
|
433
|
+
// después de cada render, como el ButtonGroup, para ver también lo que dibuja otro componente; el
|
|
434
|
+
// contenido está montado aunque el menú esté cerrado. Solo en desarrollo, una vez por instancia.
|
|
435
|
+
const warnedLoose = useRef({});
|
|
436
|
+
useEffect(() => {
|
|
437
|
+
const menu = contentRef.current;
|
|
438
|
+
if (!menu || !isDevelopment())
|
|
439
|
+
return;
|
|
440
|
+
const children = [...menu.children];
|
|
441
|
+
if (!children.some(isGroup))
|
|
442
|
+
return;
|
|
443
|
+
const loose = children.filter((el) => !isGroup(el));
|
|
444
|
+
if (loose.length === 0)
|
|
445
|
+
return;
|
|
446
|
+
mkWarn('MK_MENU_ITEM_OUTSIDE_GROUP', {
|
|
447
|
+
component: part,
|
|
448
|
+
problem: 'a menu with MenuGroup children also has a direct child outside any group, which sits on no surface (with groups, the menu paints no background or shadow; each group does)',
|
|
449
|
+
fix: 'put every item, divider and label inside a <MenuGroup>; to separate groups, use another <MenuGroup> instead of a <MenuDivider> between them',
|
|
450
|
+
}, { elements: loose.map((el) => el.getAttribute('role') ?? el.tagName.toLowerCase()) }, { once: warnedLoose.current });
|
|
451
|
+
});
|
|
452
|
+
const handleKeyDown = (e) => {
|
|
453
|
+
onKeyDown?.(e);
|
|
454
|
+
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey)
|
|
455
|
+
return;
|
|
456
|
+
// Las teclas de un submenú (dentro de este menú en el DOM y en React) son de ese submenú.
|
|
457
|
+
if (e.target.closest(MENU_SELECTOR) !== e.currentTarget)
|
|
458
|
+
return;
|
|
459
|
+
const items = menuItems(e.currentTarget);
|
|
460
|
+
const index = items.indexOf(document.activeElement);
|
|
461
|
+
const focusAt = (i) => {
|
|
462
|
+
e.preventDefault();
|
|
463
|
+
items[(i + items.length) % items.length]?.focus();
|
|
464
|
+
};
|
|
465
|
+
// APG: en un submenú, la flecha hacia el disparador (izquierda; derecha en RTL) lo cierra y
|
|
466
|
+
// vuelve a él, como Escape.
|
|
467
|
+
const back = getComputedStyle(e.currentTarget).direction === 'rtl' ? 'ArrowRight' : 'ArrowLeft';
|
|
468
|
+
if (isSub && e.key === back) {
|
|
469
|
+
e.preventDefault();
|
|
470
|
+
e.stopPropagation();
|
|
471
|
+
requestClose('arrow');
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
switch (e.key) {
|
|
475
|
+
case 'ArrowDown':
|
|
476
|
+
return focusAt(index + 1);
|
|
477
|
+
case 'ArrowUp':
|
|
478
|
+
return focusAt(index < 0 ? -1 : index - 1);
|
|
479
|
+
case 'Home':
|
|
480
|
+
return focusAt(0);
|
|
481
|
+
case 'End':
|
|
482
|
+
return focusAt(-1);
|
|
483
|
+
case 'Escape':
|
|
484
|
+
// stopPropagation: si el menú está dentro de un Dialog, Escape cierra solo el menú (y en un
|
|
485
|
+
// submenú, solo el submenú).
|
|
486
|
+
e.preventDefault();
|
|
487
|
+
e.stopPropagation();
|
|
488
|
+
requestClose('escape');
|
|
489
|
+
return;
|
|
490
|
+
case 'Tab':
|
|
491
|
+
// APG: Tab cierra el menú (desde un submenú, todo el árbol) y sigue al próximo enfocable. El
|
|
492
|
+
// foco pasa primero al disparador del Menu y el Tab del navegador (sin preventDefault) avanza
|
|
493
|
+
// desde ahí.
|
|
494
|
+
ctx.rootTriggerRef.current?.focus();
|
|
495
|
+
requestClose('tab');
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
// Búsqueda por letra (src/internal/typeahead.ts).
|
|
499
|
+
if (e.key.length !== 1 || e.key === ' ')
|
|
500
|
+
return;
|
|
501
|
+
const texts = items.map(itemText);
|
|
502
|
+
const match = typeaheadMatch(typeahead.current, e.key, texts, index);
|
|
503
|
+
if (match >= 0)
|
|
504
|
+
focusAt(match);
|
|
505
|
+
};
|
|
506
|
+
// El puntero en este nivel cierra su submenú abierto si pasa a otro elemento, salvo dentro del
|
|
507
|
+
// triángulo de gracia (ADR-0040). Lo que pasa dentro del submenú (también dentro de este menú en el
|
|
508
|
+
// DOM) o en su disparador lo mantiene.
|
|
509
|
+
const handlePointerMove = (e) => {
|
|
510
|
+
onPointerMove?.(e);
|
|
511
|
+
if (e.pointerType === 'touch')
|
|
512
|
+
return;
|
|
513
|
+
const sub = openSub.current;
|
|
514
|
+
if (!sub)
|
|
515
|
+
return;
|
|
516
|
+
const target = e.target;
|
|
517
|
+
if (sub.triggerRef.current?.contains(target) || sub.contentRef.current?.contains(target)) {
|
|
518
|
+
level.cancelGrace();
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
const g = grace.current;
|
|
522
|
+
if (g && g.sub === sub && inGrace(g, e.clientX, e.clientY))
|
|
523
|
+
return;
|
|
524
|
+
level.cancelGrace();
|
|
525
|
+
sub.close('hover');
|
|
526
|
+
};
|
|
527
|
+
return (_jsx("div", { role: "menu", "aria-labelledby": ctx.triggerId, ...props, ref: mergedRef, id: ctx.contentId, popover: "manual", className: cx(isSub ? `mk-menu ${SUB_CLASS}` : 'mk-menu', className), "data-color": color, style: isSub ? style : { ...style, '--_anchor': ctx.anchorName }, onKeyDown: handleKeyDown, onPointerMove: handlePointerMove, children: _jsx(MenuLevelContext, { value: level, children: children }) }));
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* The menu: a popover (`popover="manual"`, in the top layer) with `role="menu"`, placed next to the
|
|
531
|
+
* trigger with CSS anchor positioning: below and start-aligned; if it does not fit, above or
|
|
532
|
+
* towards the other side. Its accessible name is the trigger's (`aria-labelledby`).
|
|
533
|
+
*
|
|
534
|
+
* It is always mounted, and hidden while the menu is closed. On close, it animates its exit and
|
|
535
|
+
* only then hides. Native props, `className`, `style` and `ref` reach the container. Width between
|
|
536
|
+
* 112 and 280 px depending on the content.
|
|
537
|
+
*/
|
|
538
|
+
export function MenuContent({ color = 'standard', ...props }) {
|
|
539
|
+
const ctx = useMenu('MenuContent');
|
|
540
|
+
return _jsx(MenuSurface, { ...props, ctx: ctx, part: "MenuContent", color: color });
|
|
541
|
+
}
|
|
542
|
+
// El submenú más cercano. MenuSubContent lo vacía para sus hijos: un MenuSubTrigger dentro de un
|
|
543
|
+
// submenú tiene que estar en su propio MenuSub.
|
|
544
|
+
const MenuSubContext = createContext(null);
|
|
545
|
+
function useMenuSub(part) {
|
|
546
|
+
const sub = use(MenuSubContext);
|
|
547
|
+
if (!sub)
|
|
548
|
+
throw partOutsideParent(part, 'MenuSub');
|
|
549
|
+
return sub;
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* A submenu inside `MenuContent` (or inside another submenu, or a `MenuGroup`), with the WAI-ARIA APG
|
|
553
|
+
* "Menu and Menubar" keyboard. It renders no element: it groups the item that opens it
|
|
554
|
+
* (`MenuSubTrigger`) and the submenu (`MenuSubContent`).
|
|
555
|
+
*
|
|
556
|
+
* ```tsx
|
|
557
|
+
* <MenuContent>
|
|
558
|
+
* <MenuItem>Bold</MenuItem>
|
|
559
|
+
* <MenuSub>
|
|
560
|
+
* <MenuSubTrigger><MenuItemLeading><FormatAlignLeftIcon /></MenuItemLeading>Align</MenuSubTrigger>
|
|
561
|
+
* <MenuSubContent>
|
|
562
|
+
* <MenuItem onSelect={() => align('start')}>Start</MenuItem>
|
|
563
|
+
* <MenuItem onSelect={() => align('center')}>Center</MenuItem>
|
|
564
|
+
* </MenuSubContent>
|
|
565
|
+
* </MenuSub>
|
|
566
|
+
* </MenuContent>
|
|
567
|
+
* ```
|
|
568
|
+
*
|
|
569
|
+
* - **Opening:** a click, Enter, Space or Right Arrow (Left Arrow in right-to-left) on the trigger
|
|
570
|
+
* opens the submenu and focuses its first item; the pointer resting on the trigger opens it after
|
|
571
|
+
* 400 ms, without moving focus. One submenu per menu is open at a time.
|
|
572
|
+
* - **Going back:** Escape or Left Arrow (Right Arrow in right-to-left) closes only the submenu and
|
|
573
|
+
* returns focus to its trigger. Moving the pointer on to another item closes it; moving diagonally
|
|
574
|
+
* towards the submenu does not.
|
|
575
|
+
* - **Choosing** an item, Tab or a click outside closes the whole menu, with that reason in the
|
|
576
|
+
* `Menu`'s `onOpenChange` too.
|
|
577
|
+
*/
|
|
578
|
+
export function MenuSub({ open, defaultOpen, onOpenChange, children }) {
|
|
579
|
+
const parent = useMenu('MenuSub');
|
|
580
|
+
if (!use(MenuLevelContext))
|
|
581
|
+
throw partOutsideParent('MenuSub', 'MenuContent');
|
|
582
|
+
const { isOpen, setOpen, isOpenNow } = useOpenState({ open, defaultOpen, onOpenChange });
|
|
583
|
+
// Se muestra solo si el menú que lo contiene está abierto, también controlado.
|
|
584
|
+
const shown = isOpen && parent.open;
|
|
585
|
+
const [focusRequest, setFocusRequest] = useState(0);
|
|
586
|
+
const [triggerId, setTriggerId] = useState(undefined);
|
|
587
|
+
const focusTarget = useRef('first');
|
|
588
|
+
const returnFocus = useRef(true);
|
|
589
|
+
const triggerRef = useRef(null);
|
|
590
|
+
const contentRef = useRef(null);
|
|
591
|
+
const closeReason = useRef(null);
|
|
592
|
+
const id = useId();
|
|
593
|
+
const level = use(MenuLevelContext);
|
|
594
|
+
const requestOpen = useCallback((focus, reason = 'trigger') => {
|
|
595
|
+
focusTarget.current = focus;
|
|
596
|
+
setFocusRequest((n) => n + 1);
|
|
597
|
+
setOpen(true, reason);
|
|
598
|
+
}, [setOpen]);
|
|
599
|
+
const parentRequestClose = parent.requestClose;
|
|
600
|
+
const requestClose = useCallback((reason) => {
|
|
601
|
+
// Elegir, Tab y el clic afuera cierran todo el árbol: el pedido sube hasta el Menu y la cascada
|
|
602
|
+
// (abajo) cierra este submenú con el mismo motivo.
|
|
603
|
+
if (closesTree(reason)) {
|
|
604
|
+
parentRequestClose(reason);
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
// El disparador de un submenú solo abre.
|
|
608
|
+
if (reason === 'trigger')
|
|
609
|
+
return;
|
|
610
|
+
closeReason.current = reason;
|
|
611
|
+
returnFocus.current = true;
|
|
612
|
+
setOpen(false, reason);
|
|
613
|
+
}, [parentRequestClose, setOpen]);
|
|
614
|
+
const parentClosedBecause = parent.closedBecause;
|
|
615
|
+
const closedBecause = useCallback(() => (isOpenNow() ? parentClosedBecause() : closeReason.current), [isOpenNow, parentClosedBecause]);
|
|
616
|
+
// Cascada: si el menú que lo contiene se cerró, este también, con el motivo de arriba (el de todo el
|
|
617
|
+
// árbol) o `parent`.
|
|
618
|
+
const parentOpen = parent.open;
|
|
619
|
+
useEffect(() => {
|
|
620
|
+
if (parentOpen || !isOpenNow())
|
|
621
|
+
return;
|
|
622
|
+
const reason = parentClosedBecause();
|
|
623
|
+
closeReason.current = reason;
|
|
624
|
+
setOpen(false, reason && closesTree(reason) ? reason : 'parent');
|
|
625
|
+
}, [parentOpen, isOpenNow, parentClosedBecause, setOpen]);
|
|
626
|
+
// Un submenú abierto por nivel: al mostrarse, cierra el que estaba abierto.
|
|
627
|
+
const handle = useMemo(() => ({
|
|
628
|
+
close: (reason) => {
|
|
629
|
+
closeReason.current = reason;
|
|
630
|
+
returnFocus.current = true;
|
|
631
|
+
setOpen(false, reason);
|
|
632
|
+
},
|
|
633
|
+
triggerRef,
|
|
634
|
+
contentRef,
|
|
635
|
+
}), [setOpen]);
|
|
636
|
+
useLayoutEffect(() => {
|
|
637
|
+
const slot = level.openSub;
|
|
638
|
+
if (!shown) {
|
|
639
|
+
if (slot.current === handle)
|
|
640
|
+
slot.current = null;
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
const previous = slot.current;
|
|
644
|
+
slot.current = handle;
|
|
645
|
+
if (previous && previous !== handle)
|
|
646
|
+
previous.close('replaced');
|
|
647
|
+
}, [shown, handle, level]);
|
|
648
|
+
useLayoutEffect(() => () => {
|
|
649
|
+
if (level.openSub.current === handle)
|
|
650
|
+
level.openSub.current = null;
|
|
651
|
+
}, [level, handle]);
|
|
652
|
+
const value = useMemo(() => ({
|
|
653
|
+
handle,
|
|
654
|
+
ctx: {
|
|
655
|
+
open: shown,
|
|
656
|
+
requestOpen,
|
|
657
|
+
requestClose,
|
|
658
|
+
closedBecause,
|
|
659
|
+
rootTriggerRef: parent.rootTriggerRef,
|
|
660
|
+
parentOpen,
|
|
661
|
+
focusRequest,
|
|
662
|
+
focusTarget,
|
|
663
|
+
returnFocus,
|
|
664
|
+
triggerRef,
|
|
665
|
+
contentRef,
|
|
666
|
+
triggerId,
|
|
667
|
+
setTriggerId,
|
|
668
|
+
generatedTriggerId: `${id}trigger`,
|
|
669
|
+
contentId: `${id}menu`,
|
|
670
|
+
anchorName: anchorNameOf(id),
|
|
671
|
+
},
|
|
672
|
+
}), [handle, shown, requestOpen, requestClose, closedBecause, parent.rootTriggerRef, parentOpen, focusRequest, triggerId, id]);
|
|
673
|
+
// Las partes de adentro (los elementos del submenú) leen este nivel como su Menu: elegir pide
|
|
674
|
+
// cerrar acá y el pedido sube.
|
|
675
|
+
return (_jsx(MenuSubContext, { value: value, children: _jsx(MenuContext, { value: value.ctx, children: children }) }));
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* The item that opens a submenu: a `menuitem` with `aria-haspopup="menu"`, `aria-expanded` and
|
|
679
|
+
* `aria-controls`, the look of a `MenuItem` and the kit's `arrow_right` icon as its trailing content
|
|
680
|
+
* (mirrored in right-to-left). While its submenu is open it shows the kit's "Active" state (the
|
|
681
|
+
* state layer at 8 %). It does not choose anything: a click opens the submenu.
|
|
682
|
+
*
|
|
683
|
+
* Its children are the item's content, as in `MenuItem` (`MenuItemLeading`, the text,
|
|
684
|
+
* `MenuItemSupporting`). A disabled trigger is focusable and does not open.
|
|
685
|
+
*
|
|
686
|
+
* ```tsx
|
|
687
|
+
* <MenuSubTrigger><MenuItemLeading><ShareIcon /></MenuItemLeading>Share</MenuSubTrigger>
|
|
688
|
+
* ```
|
|
689
|
+
*/
|
|
690
|
+
export function MenuSubTrigger({ disabled = false, onClick, onKeyDown, onPointerEnter, onPointerLeave, className, style, children, ref, ...props }) {
|
|
691
|
+
const { ctx, handle } = useMenuSub('MenuSubTrigger');
|
|
692
|
+
const level = use(MenuLevelContext);
|
|
693
|
+
const { itemCtx, describedBy } = useItemDescription(props['aria-describedby']);
|
|
694
|
+
const id = props.id ?? ctx.generatedTriggerId;
|
|
695
|
+
const { setTriggerId, requestOpen } = ctx;
|
|
696
|
+
useLayoutEffect(() => {
|
|
697
|
+
setTriggerId(id);
|
|
698
|
+
return () => setTriggerId(undefined);
|
|
699
|
+
}, [id, setTriggerId]);
|
|
700
|
+
const triggerRef = ctx.triggerRef;
|
|
701
|
+
const mergedRef = useMemo(() => mergeRefs(ref, (node) => {
|
|
702
|
+
triggerRef.current = node;
|
|
703
|
+
}), [ref, triggerRef]);
|
|
704
|
+
// Demora del puntero antes de abrir (MENU_SUB_HOVER_DELAY).
|
|
705
|
+
const hoverTimer = useRef(undefined);
|
|
706
|
+
useEffect(() => () => clearTimeout(hoverTimer.current), []);
|
|
707
|
+
return (_jsxs("button", { ...props, ref: mergedRef, id: id, type: "button", role: "menuitem", "aria-haspopup": "menu", "aria-expanded": ctx.open, "aria-controls": ctx.contentId, "aria-disabled": disabled || undefined, "aria-describedby": describedBy, tabIndex: -1, className: cx('mk-menu-item mk-menu-sub-trigger', className), style: style, onClick: (e) => {
|
|
708
|
+
if (disabled) {
|
|
709
|
+
e.preventDefault();
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
onClick?.(e);
|
|
713
|
+
if (e.defaultPrevented)
|
|
714
|
+
return;
|
|
715
|
+
// Enter y Espacio en un <button> también llegan acá, como clic. Abierto, vuelve a enfocar.
|
|
716
|
+
clearTimeout(hoverTimer.current);
|
|
717
|
+
requestOpen('first', 'trigger');
|
|
718
|
+
}, onKeyDown: (e) => {
|
|
719
|
+
onKeyDown?.(e);
|
|
720
|
+
if (e.defaultPrevented || disabled)
|
|
721
|
+
return;
|
|
722
|
+
const forward = getComputedStyle(e.currentTarget).direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight';
|
|
723
|
+
if (e.key === forward) {
|
|
724
|
+
e.preventDefault();
|
|
725
|
+
clearTimeout(hoverTimer.current);
|
|
726
|
+
requestOpen('first', 'trigger');
|
|
727
|
+
}
|
|
728
|
+
}, onPointerEnter: (e) => {
|
|
729
|
+
onPointerEnter?.(e);
|
|
730
|
+
// Con el dedo no hay "pasar por encima": abre el toque (clic), como en md-sub-menu.
|
|
731
|
+
// La gracia de otro submenú abierto no se toca: pasar por este disparador en diagonal hacia aquel
|
|
732
|
+
// no lo cierra (el movimiento en el menú decide, en MenuSurface).
|
|
733
|
+
if (disabled || e.pointerType === 'touch')
|
|
734
|
+
return;
|
|
735
|
+
clearTimeout(hoverTimer.current);
|
|
736
|
+
if (ctx.open)
|
|
737
|
+
return;
|
|
738
|
+
hoverTimer.current = setTimeout(() => requestOpen('none', 'hover'), MENU_SUB_HOVER_DELAY);
|
|
739
|
+
}, onPointerLeave: (e) => {
|
|
740
|
+
onPointerLeave?.(e);
|
|
741
|
+
clearTimeout(hoverTimer.current);
|
|
742
|
+
if (e.pointerType === 'touch' || !ctx.open)
|
|
743
|
+
return;
|
|
744
|
+
level?.startGrace(handle, e.clientX, e.clientY);
|
|
745
|
+
}, children: [_jsx(StateLayer, {}), _jsx(Ripple, {}), _jsx(FocusRing, {}), _jsx(MenuItemContext, { value: itemCtx, children: children }), _jsx("span", { className: "mk-menu-item-trailing mk-menu-sub-trigger-arrow", children: _jsx(ArrowRightIcon, {}) })] }));
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* The submenu: a popover like `MenuContent` (`role="menu"`, named by its trigger, with the same look,
|
|
749
|
+
* groups included), placed next to its `MenuSubTrigger` with CSS anchor positioning: at the trigger's
|
|
750
|
+
* end side with their tops aligned; if it does not fit, towards the start side, or upwards with
|
|
751
|
+
* their bottoms aligned. Arrows, Home, End and typeahead stay inside the submenu.
|
|
752
|
+
*/
|
|
753
|
+
export function MenuSubContent({ color, ...props }) {
|
|
754
|
+
const { ctx } = useMenuSub('MenuSubContent');
|
|
755
|
+
const parentLevel = use(MenuLevelContext);
|
|
756
|
+
return (_jsx(MenuSubContext, { value: null, children: _jsx(MenuSurface, { ...props, ctx: ctx, part: "MenuSubContent", color: color ?? parentLevel?.color ?? 'standard' }) }));
|
|
757
|
+
}
|
|
758
|
+
const ROLES = { item: 'menuitem', radio: 'menuitemradio', checkbox: 'menuitemcheckbox' };
|
|
759
|
+
/**
|
|
760
|
+
* Menu item, on a `<button>` out of the Tab order (`tabindex="-1"`): focus moves with the arrows.
|
|
761
|
+
* 44 px tall with 2 px above and below (48 px rows), state layer, ripple and focus ring.
|
|
762
|
+
*
|
|
763
|
+
* The text goes as a child; the leading icon, in `MenuItemLeading`, and the trailing content
|
|
764
|
+
* (shortcut, icon), in `MenuItemTrailing`. If the text mixes elements (`Open <b>all</b>`), wrap it
|
|
765
|
+
* in a `<span>`.
|
|
766
|
+
*
|
|
767
|
+
* ```tsx
|
|
768
|
+
* <MenuItem type="radio" selected={sort === 'name'} onSelect={() => setSort('name')}>
|
|
769
|
+
* <MenuItemLeading>{sort === 'name' ? <CheckIcon /> : null}</MenuItemLeading>
|
|
770
|
+
* Name
|
|
771
|
+
* </MenuItem>
|
|
772
|
+
* ```
|
|
773
|
+
*/
|
|
774
|
+
export function MenuItem({ type = 'item', selected, disabled = false, onSelect, onClick, className, children, ...props }) {
|
|
775
|
+
const { requestClose } = useMenu('MenuItem');
|
|
776
|
+
const { itemCtx, describedBy } = useItemDescription(props['aria-describedby']);
|
|
777
|
+
const handleClick = (e) => {
|
|
778
|
+
if (disabled) {
|
|
779
|
+
e.preventDefault();
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
onClick?.(e);
|
|
783
|
+
onSelect?.(e);
|
|
784
|
+
if (!e.defaultPrevented)
|
|
785
|
+
requestClose('select');
|
|
786
|
+
};
|
|
787
|
+
return (_jsxs("button", { ...props, type: "button", role: ROLES[type], "aria-checked": type === 'item' ? undefined : selected, "aria-disabled": disabled || undefined, "aria-describedby": describedBy, tabIndex: -1, className: cx('mk-menu-item', className), onClick: handleClick, children: [_jsx(StateLayer, {}), _jsx(Ripple, {}), _jsx(FocusRing, {}), _jsx(MenuItemContext, { value: itemCtx, children: children })] }));
|
|
788
|
+
}
|
|
789
|
+
const MenuItemContext = createContext(null);
|
|
790
|
+
// El texto de apoyo (MenuItemSupporting) registra su id: es la descripción del elemento (MenuItem o
|
|
791
|
+
// MenuSubTrigger), salvo que la app pase su propio aria-describedby.
|
|
792
|
+
function useItemDescription(own) {
|
|
793
|
+
const generatedId = useId();
|
|
794
|
+
const [supportingId, setSupportingId] = useState(undefined);
|
|
795
|
+
const itemCtx = useMemo(() => ({ supportingId: `${generatedId}supporting`, setSupportingId }), [generatedId]);
|
|
796
|
+
return { itemCtx, describedBy: own ?? supportingId };
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Supporting text of a `MenuItem`, under its label (Body Medium, `on-surface-variant`; Compose's
|
|
800
|
+
* `supportingText`). The item's accessible name stays its label: this text is its description
|
|
801
|
+
* (`aria-describedby`), read after the name. The item grows from 44 to 64 px with 12 px above and
|
|
802
|
+
* below. It goes under the label even if written before it.
|
|
803
|
+
*
|
|
804
|
+
* ```tsx
|
|
805
|
+
* <MenuItem>
|
|
806
|
+
* <MenuItemLeading><EditIcon /></MenuItemLeading>
|
|
807
|
+
* Edit
|
|
808
|
+
* <MenuItemSupporting>Change the title and the cover</MenuItemSupporting>
|
|
809
|
+
* </MenuItem>
|
|
810
|
+
* ```
|
|
811
|
+
*/
|
|
812
|
+
export function MenuItemSupporting({ id, className, ...props }) {
|
|
813
|
+
const ctx = use(MenuItemContext);
|
|
814
|
+
if (!ctx)
|
|
815
|
+
throw partOutsideParent('MenuItemSupporting', 'MenuItem');
|
|
816
|
+
const ownId = useRegisteredId(id, ctx.supportingId, ctx.setSupportingId);
|
|
817
|
+
// aria-hidden: fuera del nombre que el botón toma de su contenido; aria-describedby lo lee igual,
|
|
818
|
+
// porque la descripción sigue la referencia aunque el elemento esté oculto (accname 1.2, paso 2A).
|
|
819
|
+
return _jsx("span", { "aria-hidden": "true", ...props, id: ownId, className: cx(SUPPORTING_CLASS, className) });
|
|
820
|
+
}
|
|
821
|
+
const MenuGroupContext = createContext(null);
|
|
822
|
+
/**
|
|
823
|
+
* A group of items inside `MenuContent` (`role="group"`, named by its `MenuGroupLabel`), drawn as
|
|
824
|
+
* its own surface, like Compose's `DropdownMenuGroup`: with groups, `MenuContent` paints no
|
|
825
|
+
* background or shadow and each group does, 2 px apart, with large outer corners and small inner
|
|
826
|
+
* ones by position (first, middle, last; one group alone keeps the menu's shape). Inside a group the
|
|
827
|
+
* items keep the menu's look, and the keyboard moves through the items of all groups as one list.
|
|
828
|
+
*
|
|
829
|
+
* Put every item of the menu in a group: an item outside one would sit on no surface (development
|
|
830
|
+
* builds warn with `MK_MENU_ITEM_OUTSIDE_GROUP`).
|
|
831
|
+
*
|
|
832
|
+
* ```tsx
|
|
833
|
+
* <MenuContent>
|
|
834
|
+
* <MenuGroup>
|
|
835
|
+
* <MenuGroupLabel>Edit</MenuGroupLabel>
|
|
836
|
+
* <MenuItem>Cut</MenuItem>
|
|
837
|
+
* <MenuItem>Copy</MenuItem>
|
|
838
|
+
* </MenuGroup>
|
|
839
|
+
* <MenuGroup>
|
|
840
|
+
* <MenuItem>Settings</MenuItem>
|
|
841
|
+
* </MenuGroup>
|
|
842
|
+
* </MenuContent>
|
|
843
|
+
* ```
|
|
844
|
+
*/
|
|
845
|
+
export function MenuGroup({ className, ...props }) {
|
|
846
|
+
useMenu('MenuGroup');
|
|
847
|
+
const { registry, labelledBy } = useGroupLabel(props['aria-labelledby']);
|
|
848
|
+
return (_jsx(MenuGroupContext, { value: registry, children: _jsx("div", { ...props, role: "group", "aria-labelledby": labelledBy, className: cx(GROUP_CLASS, className) }) }));
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* The heading of a `MenuGroup` (the kit's section label: 32 px, Label Large, `on-surface-variant`,
|
|
852
|
+
* or `on-tertiary-container` in a `vibrant` menu). It names the group (`aria-labelledby`), without
|
|
853
|
+
* passing ids. It is not focusable, and the arrows and the typeahead skip it.
|
|
854
|
+
*
|
|
855
|
+
* ```tsx
|
|
856
|
+
* <MenuGroup><MenuGroupLabel>Sort by</MenuGroupLabel>…</MenuGroup>
|
|
857
|
+
* ```
|
|
858
|
+
*/
|
|
859
|
+
export function MenuGroupLabel({ className, ...props }) {
|
|
860
|
+
const registry = use(MenuGroupContext);
|
|
861
|
+
if (!registry)
|
|
862
|
+
throw partOutsideParent('MenuGroupLabel', 'MenuGroup');
|
|
863
|
+
// La base (src/internal/group-label.tsx) pone el marcado, la clase común y el registro del id.
|
|
864
|
+
return _jsx(GroupLabel, { ...props, registry: registry, className: cx('mk-menu-group-label', className) });
|
|
865
|
+
}
|