@allxsmith/bestax-bulma 5.67.2 → 5.67.3
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/dist/bestax.css +1 -1
- package/dist/bestax.css.map +1 -1
- package/dist/esm/components/Card.js +3 -14
- package/dist/esm/components/Card.js.map +1 -1
- package/dist/esm/components/Command.js +14 -3
- package/dist/esm/components/Command.js.map +1 -1
- package/dist/esm/components/ContextMenu.js +10 -10
- package/dist/esm/components/ContextMenu.js.map +1 -1
- package/dist/esm/components/Dialog.js +7 -3
- package/dist/esm/components/Dialog.js.map +1 -1
- package/dist/esm/components/HoverCard.js +2 -2
- package/dist/esm/components/HoverCard.js.map +1 -1
- package/dist/esm/components/Menu.js +2 -1
- package/dist/esm/components/Menu.js.map +1 -1
- package/dist/esm/components/Modal.js +11 -9
- package/dist/esm/components/Modal.js.map +1 -1
- package/dist/esm/components/Popover.js +2 -2
- package/dist/esm/components/Popover.js.map +1 -1
- package/dist/esm/components/Tabs.js +4 -3
- package/dist/esm/components/Tabs.js.map +1 -1
- package/dist/esm/elements/CopyButton.js +6 -3
- package/dist/esm/elements/CopyButton.js.map +1 -1
- package/dist/esm/elements/IconButton.js +3 -2
- package/dist/esm/elements/IconButton.js.map +1 -1
- package/dist/esm/elements/Stat.js +3 -2
- package/dist/esm/elements/Stat.js.map +1 -1
- package/dist/esm/form/ColorInputBase.js.map +1 -1
- package/dist/esm/form/Combobox.js +2 -2
- package/dist/esm/form/Combobox.js.map +1 -1
- package/dist/esm/form/DateInputBase.js.map +1 -1
- package/dist/esm/form/DateRangeInputBase.js.map +1 -1
- package/dist/esm/form/DateTimeInputBase.js.map +1 -1
- package/dist/esm/form/Field.js +6 -6
- package/dist/esm/form/Field.js.map +1 -1
- package/dist/esm/form/TimeInputBase.js.map +1 -1
- package/dist/esm/form/TreeSelect.js.map +1 -1
- package/dist/esm/form/_pickerInternals/PickerPopover.js +3 -3
- package/dist/esm/form/_pickerInternals/PickerPopover.js.map +1 -1
- package/dist/esm/helpers/Config.js.map +1 -1
- package/dist/esm/helpers/elementType.js +42 -0
- package/dist/esm/helpers/elementType.js.map +1 -0
- package/dist/esm/helpers/portal.js +57 -1
- package/dist/esm/helpers/portal.js.map +1 -1
- package/dist/esm/helpers/useAnchoredPosition.js +23 -12
- package/dist/esm/helpers/useAnchoredPosition.js.map +1 -1
- package/dist/esm/helpers/withSubComponents.js +1 -1
- package/dist/esm/helpers/withSubComponents.js.map +1 -1
- package/dist/esm/layout/AppFrame.js +4 -3
- package/dist/esm/layout/AppFrame.js.map +1 -1
- package/dist/esm/layout/Splitter.js +3 -2
- package/dist/esm/layout/Splitter.js.map +1 -1
- package/dist/extras.css +1 -1
- package/dist/extras.css.map +1 -1
- package/dist/index.cjs +177 -69
- package/dist/index.cjs.map +1 -1
- package/dist/types/components/HoverCard.d.ts +9 -8
- package/dist/types/components/Popover.d.ts +6 -5
- package/dist/types/form/ColorInputBase.d.ts +2 -1
- package/dist/types/form/Combobox.d.ts +6 -7
- package/dist/types/form/DateInputBase.d.ts +2 -1
- package/dist/types/form/DateRangeInputBase.d.ts +2 -1
- package/dist/types/form/DateTimeInputBase.d.ts +2 -1
- package/dist/types/form/TimeInputBase.d.ts +2 -1
- package/dist/types/form/TreeSelect.d.ts +1 -1
- package/dist/types/helpers/Config.d.ts +6 -3
- package/dist/types/helpers/elementType.d.ts +20 -0
- package/dist/types/helpers/portal.d.ts +44 -0
- package/dist/types/helpers/useAnchoredPosition.d.ts +3 -1
- package/dist/types/helpers/withSubComponents.d.ts +1 -1
- package/dist/types-cjs/components/HoverCard.d.ts +9 -8
- package/dist/types-cjs/components/Popover.d.ts +6 -5
- package/dist/types-cjs/form/ColorInputBase.d.ts +2 -1
- package/dist/types-cjs/form/Combobox.d.ts +6 -7
- package/dist/types-cjs/form/DateInputBase.d.ts +2 -1
- package/dist/types-cjs/form/DateRangeInputBase.d.ts +2 -1
- package/dist/types-cjs/form/DateTimeInputBase.d.ts +2 -1
- package/dist/types-cjs/form/TimeInputBase.d.ts +2 -1
- package/dist/types-cjs/form/TreeSelect.d.ts +1 -1
- package/dist/types-cjs/helpers/Config.d.ts +6 -3
- package/dist/types-cjs/helpers/elementType.d.ts +20 -0
- package/dist/types-cjs/helpers/portal.d.ts +44 -0
- package/dist/types-cjs/helpers/useAnchoredPosition.d.ts +3 -1
- package/dist/types-cjs/helpers/withSubComponents.d.ts +1 -1
- package/dist/versions/bestax-no-dark-mode.css +1 -1
- package/dist/versions/bestax-no-dark-mode.css.map +1 -1
- package/dist/versions/bestax-no-helpers-prefixed.css +1 -1
- package/dist/versions/bestax-no-helpers-prefixed.css.map +1 -1
- package/dist/versions/bestax-no-helpers.css +1 -1
- package/dist/versions/bestax-no-helpers.css.map +1 -1
- package/dist/versions/bestax-prefixed.css +1 -1
- package/dist/versions/bestax-prefixed.css.map +1 -1
- package/package.json +1 -1
- package/src/scss/components/_menu.scss +16 -2
|
@@ -5,8 +5,7 @@ import { useState, useRef, useEffect, cloneElement } from 'react';
|
|
|
5
5
|
import { usePrefixedClassNames, classNames } from '../helpers/classNames.js';
|
|
6
6
|
import { useBulmaClasses } from '../helpers/useBulmaClasses.js';
|
|
7
7
|
import { withSubComponents } from '../helpers/withSubComponents.js';
|
|
8
|
-
import { Portal } from '../helpers/portal.js';
|
|
9
|
-
import { useConfig } from '../helpers/Config.js';
|
|
8
|
+
import { usePopupContainer, Portal } from '../helpers/portal.js';
|
|
10
9
|
import { useClientLayoutEffect } from '../helpers/useClientLayoutEffect.js';
|
|
11
10
|
import { getDeepestActiveElement, isEventInside } from '../helpers/shadowDom.js';
|
|
12
11
|
import { warnOnce } from '../helpers/devWarnings.js';
|
|
@@ -38,14 +37,15 @@ function chain(own, ours) {
|
|
|
38
37
|
*
|
|
39
38
|
* Shift+F10 and the context menu key open it too, where the browser fires
|
|
40
39
|
* `contextmenu` for them, which Windows and Linux do. The menu is Dropdown's
|
|
41
|
-
* markup, portaled
|
|
42
|
-
*
|
|
43
|
-
*
|
|
40
|
+
* markup, portaled, so it never has server markup: into the
|
|
41
|
+
* `portalContainer` a `ConfigProvider` sets, else the `Modal`, `Dialog` or
|
|
42
|
+
* `Command.Dialog` it's in, where screen readers that honor the dialog's
|
|
43
|
+
* `aria-modal` reach it, else the end of the trigger's own document's
|
|
44
|
+
* `<body>`. It opens below and to the right of the point, flips above or to
|
|
44
45
|
* the left where there's no room, moves in where it fits neither way, and
|
|
45
46
|
* scrolls inside when it's taller than the viewport. It doesn't follow the
|
|
46
|
-
* trigger, since scrolling closes it. Inside a
|
|
47
|
-
*
|
|
48
|
-
* `aria-modal` reach the menu and the shadow root's styles apply.
|
|
47
|
+
* trigger, since scrolling closes it. Inside a shadow root, point
|
|
48
|
+
* `portalContainer` inside it, so the shadow root's styles apply.
|
|
49
49
|
*
|
|
50
50
|
* Opening moves focus to the first enabled item. The arrow keys, Home, End
|
|
51
51
|
* and typing move between items, and Enter and Space activate one. Escape,
|
|
@@ -69,7 +69,7 @@ function chain(own, ours) {
|
|
|
69
69
|
*/
|
|
70
70
|
const ContextMenuComponent = ({ trigger, children, onOpenChange, closeOnClick = true, disabled = false, className, onKeyDown, onClick, onContextMenu, ...props }) => {
|
|
71
71
|
const { bulmaHelperClasses, rest } = useBulmaClasses(props);
|
|
72
|
-
const
|
|
72
|
+
const popupContainer = usePopupContainer();
|
|
73
73
|
const [menu, setMenu] = useState(null);
|
|
74
74
|
// Turning `disabled` on closes it.
|
|
75
75
|
if (disabled && menu)
|
|
@@ -226,7 +226,7 @@ const ContextMenuComponent = ({ trigger, children, onOpenChange, closeOnClick =
|
|
|
226
226
|
});
|
|
227
227
|
const menuClasses = classNames(usePrefixedClassNames('dropdown-menu'), bulmaHelperClasses, className);
|
|
228
228
|
const contentClasses = usePrefixedClassNames('dropdown-content');
|
|
229
|
-
return (jsxs(Fragment, { children: [clonedTrigger, menu && (jsx(Portal, { container:
|
|
229
|
+
return (jsxs(Fragment, { children: [clonedTrigger, menu && (jsx(Portal, { container: popupContainer || menu.doc.body, children: jsx("div", { ref: boxRef, className: boxClasses, style: {
|
|
230
230
|
top: placed?.top ?? menu.point.y,
|
|
231
231
|
left: placed?.left ?? menu.point.x,
|
|
232
232
|
}, children: jsx("div", { ...rest, ref: menuRef, role: "menu", tabIndex: -1, className: menuClasses, onKeyDown: handleKeyDown, onClick: handleClick, onContextMenu: handleContextMenu, children: jsx("div", { className: contentClasses, children: children }) }) }) }))] }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ContextMenu.js","sources":["../../../src/components/ContextMenu.tsx"],"sourcesContent":["import React, { cloneElement, useEffect, useRef, useState } from 'react';\nimport { classNames, usePrefixedClassNames } from '../helpers/classNames';\nimport { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses';\nimport { withSubComponents } from '../helpers/withSubComponents';\nimport { Portal } from '../helpers/portal';\nimport { useConfig } from '../helpers/Config';\nimport { useClientLayoutEffect } from '../helpers/useClientLayoutEffect';\nimport { getDeepestActiveElement, isEventInside } from '../helpers/shadowDom';\nimport { warnOnce } from '../helpers/devWarnings';\nimport {\n useContextMenuTrigger,\n type ContextMenuPoint,\n type ContextMenuTriggerHandlers,\n} from '../helpers/useContextMenuTrigger';\nimport {\n enabledMenuItems,\n isEnabledMenuItem,\n MENU_ITEM_SELECTOR,\n useMenuKeys,\n} from '../helpers/useMenuKeys';\nimport { DropdownDivider, DropdownItem } from './Dropdown';\n\n/**\n * Props for the ContextMenu component. `className`, `id`, `aria-label`, the\n * other HTML attributes and the helper props land on the menu\n * (`role=\"menu\"`). The trigger keeps its own.\n * @extraProp {string} [aria-label] - The menu's accessible name, such as \"Actions for report.pdf\". There's no button to borrow a name from, so pass this or `aria-labelledby`, and a development build warns when the menu opens with neither.\n * @extraProp {string} [className] - Additional classes for the menu (`role=\"menu\"`). The trigger keeps its own.\n */\nexport interface ContextMenuProps\n extends\n Omit<React.HTMLAttributes<HTMLDivElement>, 'color' | 'children'>,\n Omit<BulmaClassesProps, 'color' | 'backgroundColor'> {\n /**\n * The element a right-click, Shift+F10, the context menu key or a long\n * press opens the menu from: a table row, a card, an image. It's cloned,\n * not wrapped, so a row stays a row, which means it has to be a single\n * element that passes `className` and the `onContextMenu`,\n * `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerCancel` and\n * `onTouchEnd` handlers to its DOM node. Its own handlers for those run\n * first, and one that calls `preventDefault()` on `contextmenu` keeps the\n * menu closed. A `ContextMenu` inside it opens instead of this one.\n *\n * It gets no ARIA and no tab stop, since it can be any element and a\n * right-click isn't an activation. Keyboard users reach it through\n * something focusable inside it, such as the row's own `Dropdown` button,\n * or a `tabIndex={0}` you give it, and press Shift+F10 or the context menu\n * key there. It gets `-webkit-touch-callout: none`, so iOS doesn't put its\n * own callout for a link or an image over the menu. A long press still\n * selects text the way it does anywhere, so give a region where it\n * shouldn't `interaction=\"unselectable\"`.\n */\n trigger: React.ReactElement;\n /**\n * The menu's items: `ContextMenu.Item` and `ContextMenu.Divider`, the same\n * components as `Dropdown.Item` and `Dropdown.Divider`. Every action in it\n * needs a visible way in as well, such as a `Dropdown` on the same row:\n * nothing tells a screen reader user the menu is there, and on macOS only\n * VoiceOver opens it from the keyboard.\n */\n children: React.ReactNode;\n /**\n * Called with `true` when the menu opens and `false` when it closes,\n * whatever closed it, such as for highlighting the row whose menu is open.\n * Nothing fires after ContextMenu unmounts. There's no `open` prop to go\n * with it: a menu opened from code has no point to open at.\n */\n onOpenChange?: (open: boolean) => void;\n /**\n * Close the menu when an item is clicked, or activated with Enter or\n * Space. A click on a divider or between items leaves it open either way.\n */\n closeOnClick?: boolean;\n /**\n * Leave the trigger to the browser: a right-click shows the browser's own\n * menu, a long press does what it does anywhere, and an open menu closes.\n */\n disabled?: boolean;\n}\n\n/** Where the menu goes once it's measured. */\ninterface Placement {\n /** The box's corner in the viewport, which the menu hangs from. */\n top: number;\n left: number;\n /** The menu sits above the box rather than below it. */\n up: boolean;\n /** The menu sits to the left of the box rather than to its right. */\n right: boolean;\n}\n\n/** An open menu. */\ninterface OpenMenu {\n point: ContextMenuPoint;\n /** The trigger's document, where presses and scrolling are watched. */\n doc: Document;\n /** Unset until the menu is measured, which happens before it paints. */\n placed?: Placement;\n}\n\n/**\n * Where the menu goes along one axis, from the point at `at`: after it when\n * there's room, before it when there's room there instead, and otherwise\n * moved in until it fits in `room`.\n */\nfunction placeAlong(\n at: number,\n size: number,\n room: number\n): { start: number; flip: boolean } {\n if (at + size <= room) return { start: at, flip: false };\n if (at - size >= 0) return { start: at, flip: true };\n return { start: Math.max(0, room - size), flip: false };\n}\n\n/** Runs the trigger's own handler, then the context menu's. */\nfunction chain<E>(\n own: ((event: E) => void) | undefined,\n ours: (event: E) => void\n): (event: E) => void {\n return event => {\n own?.(event);\n ours(event);\n };\n}\n\n/**\n * The `ContextMenu` component opens a menu of actions where you right-click an element, such as a table row or a card, or long press it on a touch screen.\n *\n * Shift+F10 and the context menu key open it too, where the browser fires\n * `contextmenu` for them, which Windows and Linux do. The menu is Dropdown's\n * markup, portaled into the `portalContainer` a `ConfigProvider` sets, or\n * the end of the trigger's own document's `<body>`, so it never has server\n * markup. It opens below and to the right of the point, flips above or to\n * the left where there's no room, moves in where it fits neither way, and\n * scrolls inside when it's taller than the viewport. It doesn't follow the\n * trigger, since scrolling closes it. Inside a `Modal` or a shadow root,\n * point `portalContainer` inside it, so screen readers that honor\n * `aria-modal` reach the menu and the shadow root's styles apply.\n *\n * Opening moves focus to the first enabled item. The arrow keys, Home, End\n * and typing move between items, and Enter and Space activate one. Escape,\n * Tab, an item, a press outside, scrolling, resizing and the window losing\n * focus close it, handing focus back to what had it unless an item moved it\n * somewhere else. For a menu opened from a button use `Dropdown`.\n *\n * @function\n * @param {ContextMenuProps} props - Props for the ContextMenu component.\n * @returns {JSX.Element} The trigger, and the menu while open.\n *\n * @example\n * <ContextMenu\n * aria-label=\"Actions for report.pdf\"\n * trigger={<Box>report.pdf</Box>}\n * >\n * <ContextMenu.Item as=\"button\">Rename</ContextMenu.Item>\n * <ContextMenu.Divider />\n * <ContextMenu.Item as=\"button\">Delete</ContextMenu.Item>\n * </ContextMenu>\n */\nconst ContextMenuComponent: React.FC<ContextMenuProps> = ({\n trigger,\n children,\n onOpenChange,\n closeOnClick = true,\n disabled = false,\n className,\n onKeyDown,\n onClick,\n onContextMenu,\n ...props\n}) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n const { portalContainer } = useConfig();\n const [menu, setMenu] = useState<OpenMenu | null>(null);\n // Turning `disabled` on closes it.\n if (disabled && menu) setMenu(null);\n const open = menu !== null;\n const doc = menu?.doc;\n const placed = menu?.placed;\n\n const boxRef = useRef<HTMLDivElement>(null);\n const menuRef = useRef<HTMLDivElement>(null);\n const openerRef = useRef<Element | null>(null);\n const reportedRef = useRef(false);\n const menuKeys = useMenuKeys();\n const named = Boolean(props['aria-label'] || props['aria-labelledby']);\n\n const handlers = useContextMenuTrigger({\n disabled,\n onOpen: (point, triggerNode) => {\n const ownerDoc = triggerNode.ownerDocument;\n openerRef.current = getDeepestActiveElement(ownerDoc);\n setMenu({ point, doc: ownerDoc });\n },\n });\n\n // Measured once per opening, before it paints, against what a fixed box\n // resolves against: the root element's client area, which leaves out a\n // classic scrollbar. `useAnchoredPosition` and Tooltip read innerWidth and\n // innerHeight, which count it. A menu pinned to the viewport's edge would\n // sit under the scrollbar by that much, so this reads the narrower box.\n useClientLayoutEffect(() => {\n const menuNode = menuRef.current;\n if (!menu || menu.placed || !menuNode) return;\n const root = menuNode.ownerDocument.documentElement;\n const { width, height } = menuNode.getBoundingClientRect();\n const x = placeAlong(menu.point.x, width, root.clientWidth);\n const y = placeAlong(menu.point.y, height, root.clientHeight);\n setMenu({\n ...menu,\n placed: { left: x.start, top: y.start, right: x.flip, up: y.flip },\n });\n }, [menu]);\n const isPlaced = Boolean(placed);\n\n // What closes it while it's open, and focus back on closing. Nothing\n // listens while it's closed.\n useEffect(() => {\n const box = boxRef.current;\n const menuNode = menuRef.current;\n if (!doc || !box || !menuNode) return undefined;\n const view = doc.defaultView as Window;\n // What had focus when it opened. This runs once per opening, so opening\n // again at a new point while it's open keeps it.\n const opener = openerRef.current as HTMLElement | null;\n const close = () => setMenu(null);\n const closeOutside = (event: Event) => {\n if (!isEventInside(event, box)) close();\n };\n doc.addEventListener('pointerdown', closeOutside, true);\n view.addEventListener('resize', close);\n view.addEventListener('blur', close);\n return () => {\n doc.removeEventListener('pointerdown', closeOutside, true);\n view.removeEventListener('resize', close);\n view.removeEventListener('blur', close);\n // Back to what had focus while the menu still has it, or it dropped to\n // <body> when the menu left. An item that put it somewhere else, such\n // as a Modal or a rename field, keeps it there.\n const now = getDeepestActiveElement(doc);\n if (!now || now === doc.body || menuNode.contains(now)) opener?.focus();\n };\n }, [doc]);\n\n // Focus in, and closing on scroll, once it's placed. Placed, it's inside\n // the viewport, so its first item has nothing to scroll into view, and\n // `preventScroll` makes sure: a scroll the focus caused would close it as\n // it opened. Opening again at a new point places it again, and leaves\n // focus where it is in the menu.\n useEffect(() => {\n const box = boxRef.current;\n const menuNode = menuRef.current;\n if (!doc || !isPlaced || !box || !menuNode) return undefined;\n if (!menuNode.contains(getDeepestActiveElement(doc))) {\n menuKeys.reset();\n (enabledMenuItems(menuNode)[0] ?? menuNode).focus({\n preventScroll: true,\n });\n }\n const closeOutside = (event: Event) => {\n if (!isEventInside(event, box)) setMenu(null);\n };\n doc.addEventListener('scroll', closeOutside, true);\n return () => doc.removeEventListener('scroll', closeOutside, true);\n }, [doc, isPlaced, menuKeys]);\n\n // Before paint, so what the caller does with it, such as highlighting the\n // row, shows with the menu rather than a frame behind it.\n useClientLayoutEffect(() => {\n if (open === reportedRef.current) return;\n reportedRef.current = open;\n onOpenChange?.(open);\n });\n\n useEffect(() => {\n if (open && !named) {\n warnOnce(\n 'ContextMenu:unnamed',\n '[bestax-bulma] <ContextMenu> opened a menu with no accessible ' +\n 'name. Pass aria-label or aria-labelledby.'\n );\n }\n }, [open, named]);\n\n const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n onKeyDown?.(event);\n // The menu has the keyboard while focus is in it. React brings its keys\n // up the tree to wherever the ContextMenu sits, where a table that moves\n // between rows on the arrow keys, or a Popover or a Modal waiting for\n // Escape, would take them too.\n event.stopPropagation();\n if (event.key === 'Escape' || event.key === 'Tab') {\n // Tab would go on from the end of <body>, past the rest of the page.\n event.preventDefault();\n setMenu(null);\n return;\n }\n menuKeys.onKeyDown(event);\n };\n\n const handleClick = (event: React.MouseEvent<HTMLDivElement>) => {\n onClick?.(event);\n if (!closeOnClick) return;\n const item = (event.target as Element).closest(MENU_ITEM_SELECTOR);\n if (item && isEnabledMenuItem(item)) setMenu(null);\n };\n\n const handleContextMenu = (event: React.MouseEvent<HTMLDivElement>) => {\n onContextMenu?.(event);\n // No other menu over this one: not the browser's, and not a trigger's\n // that React brings the event up to.\n event.preventDefault();\n event.stopPropagation();\n };\n\n const own = trigger.props as Partial<ContextMenuTriggerHandlers> & {\n className?: string;\n };\n const triggerClass = usePrefixedClassNames('context-menu');\n const clonedTrigger = cloneElement(\n trigger as React.ReactElement<Record<string, unknown>>,\n {\n className:\n classNames(own.className, !disabled && triggerClass) || undefined,\n onContextMenu: chain(own.onContextMenu, handlers.onContextMenu),\n onPointerDown: chain(own.onPointerDown, handlers.onPointerDown),\n onPointerMove: chain(own.onPointerMove, handlers.onPointerMove),\n onPointerUp: chain(own.onPointerUp, handlers.onPointerUp),\n onPointerCancel: chain(own.onPointerCancel, handlers.onPointerCancel),\n onTouchEnd: chain(own.onTouchEnd, handlers.onTouchEnd),\n }\n );\n\n const boxClasses = usePrefixedClassNames('context-menu-content', 'dropdown', {\n 'is-active': true,\n 'is-up': placed?.up,\n 'is-right': placed?.right,\n });\n const menuClasses = classNames(\n usePrefixedClassNames('dropdown-menu'),\n bulmaHelperClasses,\n className\n );\n const contentClasses = usePrefixedClassNames('dropdown-content');\n\n return (\n <>\n {clonedTrigger}\n {menu && (\n <Portal container={portalContainer || menu.doc.body}>\n <div\n ref={boxRef}\n className={boxClasses}\n style={{\n top: placed?.top ?? menu.point.y,\n left: placed?.left ?? menu.point.x,\n }}\n >\n <div\n {...rest}\n ref={menuRef}\n role=\"menu\"\n tabIndex={-1}\n className={menuClasses}\n onKeyDown={handleKeyDown}\n onClick={handleClick}\n onContextMenu={handleContextMenu}\n >\n <div className={contentClasses}>{children}</div>\n </div>\n </div>\n </Portal>\n )}\n </>\n );\n};\n\n/**\n * ContextMenu with Item and Divider sub-components, which are `Dropdown.Item`\n * and `Dropdown.Divider`, so items written for a Dropdown work here\n * unchanged.\n */\nexport const ContextMenu = withSubComponents(\n ContextMenuComponent,\n {\n Item: DropdownItem,\n Divider: DropdownDivider,\n },\n 'ContextMenu'\n);\n\nexport default ContextMenu;\n"],"names":["_jsxs","_Fragment","_jsx"],"mappings":";;;;;;;;;;;;;;;;AAoGA;;;;AAIG;AACH,SAAS,UAAU,CACjB,EAAU,EACV,IAAY,EACZ,IAAY,EAAA;AAEZ,IAAA,IAAI,EAAE,GAAG,IAAI,IAAI,IAAI;QAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE;AACxD,IAAA,IAAI,EAAE,GAAG,IAAI,IAAI,CAAC;QAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE;AACpD,IAAA,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE;AACzD;AAEA;AACA,SAAS,KAAK,CACZ,GAAqC,EACrC,IAAwB,EAAA;IAExB,OAAO,KAAK,IAAG;AACb,QAAA,GAAG,GAAG,KAAK,CAAC;QACZ,IAAI,CAAC,KAAK,CAAC;AACb,IAAA,CAAC;AACH;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCG;AACH,MAAM,oBAAoB,GAA+B,CAAC,EACxD,OAAO,EACP,QA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AoB,EACpB;AACE,IAAA,IAAI,EAAE,YAAY;AAClB,IAAA,OAAO,EAAE,eAAe;CACzB,EACD,aAAa;;"}
|
|
1
|
+
{"version":3,"file":"ContextMenu.js","sources":["../../../src/components/ContextMenu.tsx"],"sourcesContent":["import React, { cloneElement, useEffect, useRef, useState } from 'react';\nimport { classNames, usePrefixedClassNames } from '../helpers/classNames';\nimport { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses';\nimport { withSubComponents } from '../helpers/withSubComponents';\nimport { Portal, usePopupContainer } from '../helpers/portal';\nimport { useClientLayoutEffect } from '../helpers/useClientLayoutEffect';\nimport { getDeepestActiveElement, isEventInside } from '../helpers/shadowDom';\nimport { warnOnce } from '../helpers/devWarnings';\nimport {\n useContextMenuTrigger,\n type ContextMenuPoint,\n type ContextMenuTriggerHandlers,\n} from '../helpers/useContextMenuTrigger';\nimport {\n enabledMenuItems,\n isEnabledMenuItem,\n MENU_ITEM_SELECTOR,\n useMenuKeys,\n} from '../helpers/useMenuKeys';\nimport { DropdownDivider, DropdownItem } from './Dropdown';\n\n/**\n * Props for the ContextMenu component. `className`, `id`, `aria-label`, the\n * other HTML attributes and the helper props land on the menu\n * (`role=\"menu\"`). The trigger keeps its own.\n * @extraProp {string} [aria-label] - The menu's accessible name, such as \"Actions for report.pdf\". There's no button to borrow a name from, so pass this or `aria-labelledby`, and a development build warns when the menu opens with neither.\n * @extraProp {string} [className] - Additional classes for the menu (`role=\"menu\"`). The trigger keeps its own.\n */\nexport interface ContextMenuProps\n extends\n Omit<React.HTMLAttributes<HTMLDivElement>, 'color' | 'children'>,\n Omit<BulmaClassesProps, 'color' | 'backgroundColor'> {\n /**\n * The element a right-click, Shift+F10, the context menu key or a long\n * press opens the menu from: a table row, a card, an image. It's cloned,\n * not wrapped, so a row stays a row, which means it has to be a single\n * element that passes `className` and the `onContextMenu`,\n * `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerCancel` and\n * `onTouchEnd` handlers to its DOM node. Its own handlers for those run\n * first, and one that calls `preventDefault()` on `contextmenu` keeps the\n * menu closed. A `ContextMenu` inside it opens instead of this one.\n *\n * It gets no ARIA and no tab stop, since it can be any element and a\n * right-click isn't an activation. Keyboard users reach it through\n * something focusable inside it, such as the row's own `Dropdown` button,\n * or a `tabIndex={0}` you give it, and press Shift+F10 or the context menu\n * key there. It gets `-webkit-touch-callout: none`, so iOS doesn't put its\n * own callout for a link or an image over the menu. A long press still\n * selects text the way it does anywhere, so give a region where it\n * shouldn't `interaction=\"unselectable\"`.\n */\n trigger: React.ReactElement;\n /**\n * The menu's items: `ContextMenu.Item` and `ContextMenu.Divider`, the same\n * components as `Dropdown.Item` and `Dropdown.Divider`. Every action in it\n * needs a visible way in as well, such as a `Dropdown` on the same row:\n * nothing tells a screen reader user the menu is there, and on macOS only\n * VoiceOver opens it from the keyboard.\n */\n children: React.ReactNode;\n /**\n * Called with `true` when the menu opens and `false` when it closes,\n * whatever closed it, such as for highlighting the row whose menu is open.\n * Nothing fires after ContextMenu unmounts. There's no `open` prop to go\n * with it: a menu opened from code has no point to open at.\n */\n onOpenChange?: (open: boolean) => void;\n /**\n * Close the menu when an item is clicked, or activated with Enter or\n * Space. A click on a divider or between items leaves it open either way.\n */\n closeOnClick?: boolean;\n /**\n * Leave the trigger to the browser: a right-click shows the browser's own\n * menu, a long press does what it does anywhere, and an open menu closes.\n */\n disabled?: boolean;\n}\n\n/** Where the menu goes once it's measured. */\ninterface Placement {\n /** The box's corner in the viewport, which the menu hangs from. */\n top: number;\n left: number;\n /** The menu sits above the box rather than below it. */\n up: boolean;\n /** The menu sits to the left of the box rather than to its right. */\n right: boolean;\n}\n\n/** An open menu. */\ninterface OpenMenu {\n point: ContextMenuPoint;\n /** The trigger's document, where presses and scrolling are watched. */\n doc: Document;\n /** Unset until the menu is measured, which happens before it paints. */\n placed?: Placement;\n}\n\n/**\n * Where the menu goes along one axis, from the point at `at`: after it when\n * there's room, before it when there's room there instead, and otherwise\n * moved in until it fits in `room`.\n */\nfunction placeAlong(\n at: number,\n size: number,\n room: number\n): { start: number; flip: boolean } {\n if (at + size <= room) return { start: at, flip: false };\n if (at - size >= 0) return { start: at, flip: true };\n return { start: Math.max(0, room - size), flip: false };\n}\n\n/** Runs the trigger's own handler, then the context menu's. */\nfunction chain<E>(\n own: ((event: E) => void) | undefined,\n ours: (event: E) => void\n): (event: E) => void {\n return event => {\n own?.(event);\n ours(event);\n };\n}\n\n/**\n * The `ContextMenu` component opens a menu of actions where you right-click an element, such as a table row or a card, or long press it on a touch screen.\n *\n * Shift+F10 and the context menu key open it too, where the browser fires\n * `contextmenu` for them, which Windows and Linux do. The menu is Dropdown's\n * markup, portaled, so it never has server markup: into the\n * `portalContainer` a `ConfigProvider` sets, else the `Modal`, `Dialog` or\n * `Command.Dialog` it's in, where screen readers that honor the dialog's\n * `aria-modal` reach it, else the end of the trigger's own document's\n * `<body>`. It opens below and to the right of the point, flips above or to\n * the left where there's no room, moves in where it fits neither way, and\n * scrolls inside when it's taller than the viewport. It doesn't follow the\n * trigger, since scrolling closes it. Inside a shadow root, point\n * `portalContainer` inside it, so the shadow root's styles apply.\n *\n * Opening moves focus to the first enabled item. The arrow keys, Home, End\n * and typing move between items, and Enter and Space activate one. Escape,\n * Tab, an item, a press outside, scrolling, resizing and the window losing\n * focus close it, handing focus back to what had it unless an item moved it\n * somewhere else. For a menu opened from a button use `Dropdown`.\n *\n * @function\n * @param {ContextMenuProps} props - Props for the ContextMenu component.\n * @returns {JSX.Element} The trigger, and the menu while open.\n *\n * @example\n * <ContextMenu\n * aria-label=\"Actions for report.pdf\"\n * trigger={<Box>report.pdf</Box>}\n * >\n * <ContextMenu.Item as=\"button\">Rename</ContextMenu.Item>\n * <ContextMenu.Divider />\n * <ContextMenu.Item as=\"button\">Delete</ContextMenu.Item>\n * </ContextMenu>\n */\nconst ContextMenuComponent: React.FC<ContextMenuProps> = ({\n trigger,\n children,\n onOpenChange,\n closeOnClick = true,\n disabled = false,\n className,\n onKeyDown,\n onClick,\n onContextMenu,\n ...props\n}) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n const popupContainer = usePopupContainer();\n const [menu, setMenu] = useState<OpenMenu | null>(null);\n // Turning `disabled` on closes it.\n if (disabled && menu) setMenu(null);\n const open = menu !== null;\n const doc = menu?.doc;\n const placed = menu?.placed;\n\n const boxRef = useRef<HTMLDivElement>(null);\n const menuRef = useRef<HTMLDivElement>(null);\n const openerRef = useRef<Element | null>(null);\n const reportedRef = useRef(false);\n const menuKeys = useMenuKeys();\n const named = Boolean(props['aria-label'] || props['aria-labelledby']);\n\n const handlers = useContextMenuTrigger({\n disabled,\n onOpen: (point, triggerNode) => {\n const ownerDoc = triggerNode.ownerDocument;\n openerRef.current = getDeepestActiveElement(ownerDoc);\n setMenu({ point, doc: ownerDoc });\n },\n });\n\n // Measured once per opening, before it paints, against what a fixed box\n // resolves against: the root element's client area, which leaves out a\n // classic scrollbar. `useAnchoredPosition` and Tooltip read innerWidth and\n // innerHeight, which count it. A menu pinned to the viewport's edge would\n // sit under the scrollbar by that much, so this reads the narrower box.\n useClientLayoutEffect(() => {\n const menuNode = menuRef.current;\n if (!menu || menu.placed || !menuNode) return;\n const root = menuNode.ownerDocument.documentElement;\n const { width, height } = menuNode.getBoundingClientRect();\n const x = placeAlong(menu.point.x, width, root.clientWidth);\n const y = placeAlong(menu.point.y, height, root.clientHeight);\n setMenu({\n ...menu,\n placed: { left: x.start, top: y.start, right: x.flip, up: y.flip },\n });\n }, [menu]);\n const isPlaced = Boolean(placed);\n\n // What closes it while it's open, and focus back on closing. Nothing\n // listens while it's closed.\n useEffect(() => {\n const box = boxRef.current;\n const menuNode = menuRef.current;\n if (!doc || !box || !menuNode) return undefined;\n const view = doc.defaultView as Window;\n // What had focus when it opened. This runs once per opening, so opening\n // again at a new point while it's open keeps it.\n const opener = openerRef.current as HTMLElement | null;\n const close = () => setMenu(null);\n const closeOutside = (event: Event) => {\n if (!isEventInside(event, box)) close();\n };\n doc.addEventListener('pointerdown', closeOutside, true);\n view.addEventListener('resize', close);\n view.addEventListener('blur', close);\n return () => {\n doc.removeEventListener('pointerdown', closeOutside, true);\n view.removeEventListener('resize', close);\n view.removeEventListener('blur', close);\n // Back to what had focus while the menu still has it, or it dropped to\n // <body> when the menu left. An item that put it somewhere else, such\n // as a Modal or a rename field, keeps it there.\n const now = getDeepestActiveElement(doc);\n if (!now || now === doc.body || menuNode.contains(now)) opener?.focus();\n };\n }, [doc]);\n\n // Focus in, and closing on scroll, once it's placed. Placed, it's inside\n // the viewport, so its first item has nothing to scroll into view, and\n // `preventScroll` makes sure: a scroll the focus caused would close it as\n // it opened. Opening again at a new point places it again, and leaves\n // focus where it is in the menu.\n useEffect(() => {\n const box = boxRef.current;\n const menuNode = menuRef.current;\n if (!doc || !isPlaced || !box || !menuNode) return undefined;\n if (!menuNode.contains(getDeepestActiveElement(doc))) {\n menuKeys.reset();\n (enabledMenuItems(menuNode)[0] ?? menuNode).focus({\n preventScroll: true,\n });\n }\n const closeOutside = (event: Event) => {\n if (!isEventInside(event, box)) setMenu(null);\n };\n doc.addEventListener('scroll', closeOutside, true);\n return () => doc.removeEventListener('scroll', closeOutside, true);\n }, [doc, isPlaced, menuKeys]);\n\n // Before paint, so what the caller does with it, such as highlighting the\n // row, shows with the menu rather than a frame behind it.\n useClientLayoutEffect(() => {\n if (open === reportedRef.current) return;\n reportedRef.current = open;\n onOpenChange?.(open);\n });\n\n useEffect(() => {\n if (open && !named) {\n warnOnce(\n 'ContextMenu:unnamed',\n '[bestax-bulma] <ContextMenu> opened a menu with no accessible ' +\n 'name. Pass aria-label or aria-labelledby.'\n );\n }\n }, [open, named]);\n\n const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n onKeyDown?.(event);\n // The menu has the keyboard while focus is in it. React brings its keys\n // up the tree to wherever the ContextMenu sits, where a table that moves\n // between rows on the arrow keys, or a Popover or a Modal waiting for\n // Escape, would take them too.\n event.stopPropagation();\n if (event.key === 'Escape' || event.key === 'Tab') {\n // Tab would go on from the end of <body>, past the rest of the page.\n event.preventDefault();\n setMenu(null);\n return;\n }\n menuKeys.onKeyDown(event);\n };\n\n const handleClick = (event: React.MouseEvent<HTMLDivElement>) => {\n onClick?.(event);\n if (!closeOnClick) return;\n const item = (event.target as Element).closest(MENU_ITEM_SELECTOR);\n if (item && isEnabledMenuItem(item)) setMenu(null);\n };\n\n const handleContextMenu = (event: React.MouseEvent<HTMLDivElement>) => {\n onContextMenu?.(event);\n // No other menu over this one: not the browser's, and not a trigger's\n // that React brings the event up to.\n event.preventDefault();\n event.stopPropagation();\n };\n\n const own = trigger.props as Partial<ContextMenuTriggerHandlers> & {\n className?: string;\n };\n const triggerClass = usePrefixedClassNames('context-menu');\n const clonedTrigger = cloneElement(\n trigger as React.ReactElement<Record<string, unknown>>,\n {\n className:\n classNames(own.className, !disabled && triggerClass) || undefined,\n onContextMenu: chain(own.onContextMenu, handlers.onContextMenu),\n onPointerDown: chain(own.onPointerDown, handlers.onPointerDown),\n onPointerMove: chain(own.onPointerMove, handlers.onPointerMove),\n onPointerUp: chain(own.onPointerUp, handlers.onPointerUp),\n onPointerCancel: chain(own.onPointerCancel, handlers.onPointerCancel),\n onTouchEnd: chain(own.onTouchEnd, handlers.onTouchEnd),\n }\n );\n\n const boxClasses = usePrefixedClassNames('context-menu-content', 'dropdown', {\n 'is-active': true,\n 'is-up': placed?.up,\n 'is-right': placed?.right,\n });\n const menuClasses = classNames(\n usePrefixedClassNames('dropdown-menu'),\n bulmaHelperClasses,\n className\n );\n const contentClasses = usePrefixedClassNames('dropdown-content');\n\n return (\n <>\n {clonedTrigger}\n {menu && (\n <Portal container={popupContainer || menu.doc.body}>\n <div\n ref={boxRef}\n className={boxClasses}\n style={{\n top: placed?.top ?? menu.point.y,\n left: placed?.left ?? menu.point.x,\n }}\n >\n <div\n {...rest}\n ref={menuRef}\n role=\"menu\"\n tabIndex={-1}\n className={menuClasses}\n onKeyDown={handleKeyDown}\n onClick={handleClick}\n onContextMenu={handleContextMenu}\n >\n <div className={contentClasses}>{children}</div>\n </div>\n </div>\n </Portal>\n )}\n </>\n );\n};\n\n/**\n * ContextMenu with Item and Divider sub-components, which are `Dropdown.Item`\n * and `Dropdown.Divider`, so items written for a Dropdown work here\n * unchanged.\n */\nexport const ContextMenu = withSubComponents(\n ContextMenuComponent,\n {\n Item: DropdownItem,\n Divider: DropdownDivider,\n },\n 'ContextMenu'\n);\n\nexport default ContextMenu;\n"],"names":["_jsxs","_Fragment","_jsx"],"mappings":";;;;;;;;;;;;;;;AAmGA;;;;AAIG;AACH,SAAS,UAAU,CACjB,EAAU,EACV,IAAY,EACZ,IAAY,EAAA;AAEZ,IAAA,IAAI,EAAE,GAAG,IAAI,IAAI,IAAI;QAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE;AACxD,IAAA,IAAI,EAAE,GAAG,IAAI,IAAI,CAAC;QAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE;AACpD,IAAA,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE;AACzD;AAEA;AACA,SAAS,KAAK,CACZ,GAAqC,EACrC,IAAwB,EAAA;IAExB,OAAO,KAAK,IAAG;AACb,QAAA,GAAG,GAAG,KAAK,CAAC;QACZ,IAAI,CAAC,KAAK,CAAC;AACb,IAAA,CAAC;AACH;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCG;AACH,MAAM,oBAAoB,GAA+B,CAAC,EACxD,OAAO,EACP,QAAQ,EACR,YAAY,EACZ,YAAY,GAAG,IAAI,EACnB,QAAQ,GAAG,KAAK,EAChB,SAAS,EACT,SAAS,EACT,OAAO,EACP,aAAa,EACb,GAAG,KAAK,EACT,KAAI;IACH,MAAM,EAAE,kBAAkB,EAAE,IAAI,EAAE,GA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|
|
2
2
|
'use client';
|
|
3
3
|
import { jsxs, jsx } from 'react/jsx-runtime';
|
|
4
|
-
import { forwardRef, useRef, useCallback, useEffect, useSyncExternalStore } from 'react';
|
|
4
|
+
import { forwardRef, useRef, useState, useCallback, useEffect, useSyncExternalStore } from 'react';
|
|
5
5
|
import { usePrefixedClassNames, classNames } from '../helpers/classNames.js';
|
|
6
6
|
import { useBulmaClasses } from '../helpers/useBulmaClasses.js';
|
|
7
|
-
import { usePortalProp } from '../helpers/portal.js';
|
|
7
|
+
import { usePortalProp, PortalScope } from '../helpers/portal.js';
|
|
8
8
|
import { Modal } from './Modal.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
@@ -43,6 +43,9 @@ const Dialog = forwardRef(({ isOpen, title, message, type = 'default', confirmTe
|
|
|
43
43
|
const dialogRef = useRef(null);
|
|
44
44
|
// Cleanup returned by a consumer's callback ref on attach, held until detach.
|
|
45
45
|
const consumerCleanupRef = useRef(null);
|
|
46
|
+
// The box, as state, for the popups in the message to portal into. It's
|
|
47
|
+
// what carries `aria-modal`, rather than the Modal's root around it.
|
|
48
|
+
const [scopeNode, setScopeNode] = useState(null);
|
|
46
49
|
const confirmRef = useRef(null);
|
|
47
50
|
const cancelRef = useRef(null);
|
|
48
51
|
// Handle cancel
|
|
@@ -79,6 +82,7 @@ const Dialog = forwardRef(({ isOpen, title, message, type = 'default', confirmTe
|
|
|
79
82
|
const combinedRef = useCallback((node) => {
|
|
80
83
|
dialogRef.current =
|
|
81
84
|
node;
|
|
85
|
+
setScopeNode(node);
|
|
82
86
|
if (typeof ref === 'function') {
|
|
83
87
|
// React 19 lets a callback ref return a cleanup function and detaches by
|
|
84
88
|
// running it instead of calling the ref with `null`; React 18 discards the
|
|
@@ -144,7 +148,7 @@ const Dialog = forwardRef(({ isOpen, title, message, type = 'default', confirmTe
|
|
|
144
148
|
if (!isOpen) {
|
|
145
149
|
return null;
|
|
146
150
|
}
|
|
147
|
-
return (jsxs(Modal, { isActive: isOpen, onClose: handleCancel, role: "presentation", portal: portal, children: [jsx(Modal.Background, { onClick: handleBackgroundClick }), jsxs("div", { ref: combinedRef, className: combinedClasses, role: "alertdialog", "aria-modal": "true", "aria-labelledby": title ? 'dialog-title' : undefined, "aria-describedby": "dialog-message", ...rest, children: [title && (jsxs("div", { className: headerClass, children: [displayIcon && jsx("span", { className: iconClass, children: displayIcon }), jsx("h3", { id: "dialog-title", className: titleClass, children: title })] })), jsx("div", { id: "dialog-message", className: bodyClass, children: message }), jsxs("div", { className: footerClass, children: [showCancel && (jsx("button", { ref: cancelRef, type: "button", className: cancelButtonClass, onClick: handleCancel, children: cancelText })), jsx("button", { ref: confirmRef, type: "button", className: confirmButtonClass, onClick: handleConfirm, children: confirmText })] })] })] }));
|
|
151
|
+
return (jsxs(Modal, { isActive: isOpen, onClose: handleCancel, role: "presentation", portal: portal, children: [jsx(Modal.Background, { onClick: handleBackgroundClick }), jsx(PortalScope, { node: scopeNode, children: jsxs("div", { ref: combinedRef, className: combinedClasses, role: "alertdialog", "aria-modal": "true", "aria-labelledby": title ? 'dialog-title' : undefined, "aria-describedby": "dialog-message", ...rest, children: [title && (jsxs("div", { className: headerClass, children: [displayIcon && (jsx("span", { className: iconClass, children: displayIcon })), jsx("h3", { id: "dialog-title", className: titleClass, children: title })] })), jsx("div", { id: "dialog-message", className: bodyClass, children: message }), jsxs("div", { className: footerClass, children: [showCancel && (jsx("button", { ref: cancelRef, type: "button", className: cancelButtonClass, onClick: handleCancel, children: cancelText })), jsx("button", { ref: confirmRef, type: "button", className: confirmButtonClass, onClick: handleConfirm, children: confirmText })] })] }) })] }));
|
|
148
152
|
});
|
|
149
153
|
Dialog.displayName = 'Dialog';
|
|
150
154
|
let dialogListeners = new Set();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Dialog.js","sources":["../../../src/components/Dialog.tsx"],"sourcesContent":["import React, {\n forwardRef,\n useCallback,\n useEffect,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport { classNames, usePrefixedClassNames } from '../helpers/classNames';\nimport { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses';\nimport { usePortalProp } from '../helpers/portal';\nimport { Modal } from './Modal';\n\n/** Valid dialog type/color values. */\nexport type DialogType = 'default' | 'success' | 'danger' | 'warning' | 'info';\n\n/**\n * Props for the Dialog component.\n * @extraProp {string} [className] - Additional CSS classes.\n * @extraProp {React.Ref<HTMLElement>} [ref] - Ref forwarded to the dialog element.\n */\nexport interface DialogProps\n extends\n Omit<React.HTMLAttributes<HTMLDivElement>, 'color'>,\n Omit<BulmaClassesProps, 'color'> {\n /** Whether the dialog is open (required). */\n isOpen: boolean;\n /** Dialog title. */\n title?: string;\n /** Dialog message/content (required). */\n message: string | React.ReactNode;\n /** The type/color of the dialog. Default: 'default'. */\n type?: DialogType;\n /** Text for confirm button. Default: 'OK'. */\n confirmText?: string;\n /** Text for cancel button. Default: 'Cancel'. */\n cancelText?: string;\n /** Callback when confirm button is clicked. */\n onConfirm?: () => void;\n /** Callback when cancel button is clicked or dismissed. */\n onCancel?: () => void;\n /** Whether to show cancel button. Default: true for confirm dialogs. */\n showCancel?: boolean;\n /** Whether the dialog can be dismissed. Default: true. */\n canCancel?: boolean;\n /** Focus cancel button instead of confirm. Default: false. */\n focusCancel?: boolean;\n /** Custom icon to display. */\n icon?: React.ReactNode;\n /**\n * Renders the dialog into a portal target instead of inline. Forwarded to\n * the underlying `Modal`; see its `portal` prop for the accepted values.\n * @defaultValue false\n */\n portal?: boolean | string | HTMLElement;\n}\n\n/**\n * The `Dialog` component provides ready-made confirm and alert dialogs, so a destructive action stays one `await dialog.confirm()` call away.\n *\n * @function\n * @param {DialogProps} props - Props for the Dialog component.\n * @param {React.Ref<HTMLDivElement>} ref - Forwarded ref to the dialog element.\n * @returns {JSX.Element | null} The rendered dialog component.\n *\n * @example\n * // Alert dialog\n * <Dialog\n * isOpen={showAlert}\n * title=\"Success\"\n * message=\"Operation completed successfully!\"\n * type=\"success\"\n * onConfirm={() => setShowAlert(false)}\n * showCancel={false}\n * />\n *\n * @example\n * // Confirm dialog\n * <Dialog\n * isOpen={showConfirm}\n * title=\"Delete Item?\"\n * message=\"This action cannot be undone.\"\n * type=\"danger\"\n * confirmText=\"Delete\"\n * onConfirm={handleDelete}\n * onCancel={() => setShowConfirm(false)}\n * />\n */\nexport const Dialog = forwardRef<HTMLDivElement, DialogProps>(\n (\n {\n isOpen,\n title,\n message,\n type = 'default',\n confirmText = 'OK',\n cancelText = 'Cancel',\n onConfirm,\n onCancel,\n showCancel = true,\n canCancel = true,\n focusCancel = false,\n icon,\n portal,\n className,\n ...props\n },\n ref\n ) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n const dialogRef = useRef<HTMLDivElement>(null);\n // Cleanup returned by a consumer's callback ref on attach, held until detach.\n const consumerCleanupRef = useRef<(() => void) | null>(null);\n const confirmRef = useRef<HTMLButtonElement>(null);\n const cancelRef = useRef<HTMLButtonElement>(null);\n\n // Handle cancel\n const handleCancel = useCallback(() => {\n if (canCancel) {\n onCancel?.();\n }\n }, [canCancel, onCancel]);\n\n // Handle confirm\n const handleConfirm = useCallback(() => {\n onConfirm?.();\n }, [onConfirm]);\n\n // Handle background click\n const handleBackgroundClick = useCallback(() => {\n if (canCancel) {\n handleCancel();\n }\n }, [canCancel, handleCancel]);\n\n // Moving into the portal, or from one portal target to another, remounts\n // the Modal's subtree, these buttons included, so the focus effect below\n // has to re-run against the new nodes, exactly as the Modal's own focus\n // effect does, on the same inputs.\n const { isPortaled, defaultTarget } = usePortalProp(portal);\n\n // Focus management — Dialog picks a specific button rather than the\n // Modal's default (first focusable/root); this effect runs after the\n // inner Modal's own focus-on-open effect, so it wins.\n useEffect(() => {\n if (isOpen) {\n const buttonToFocus =\n focusCancel && showCancel ? cancelRef.current : confirmRef.current;\n buttonToFocus?.focus();\n }\n }, [isOpen, focusCancel, showCancel, isPortaled, portal, defaultTarget]);\n\n // Use combined ref\n const combinedRef = useCallback(\n (node: HTMLDivElement | null) => {\n (dialogRef as React.MutableRefObject<HTMLDivElement | null>).current =\n node;\n if (typeof ref === 'function') {\n // React 19 lets a callback ref return a cleanup function and detaches by\n // running it instead of calling the ref with `null`; React 18 discards the\n // return value entirely. Returning it from here would be a React-19-only\n // contract, so we hold the cleanup and run it ourselves on detach — the\n // same shape as `Dropdown`, `Modal`, `Sidebar`, `Toast` and `Carousel`.\n // The form controls that merge a forwarded ref still discard the cleanup\n // and detach with `ref(null)`, so this is not yet library-wide — grep\n // `typeof ref === 'function'` for the current split.\n if (node === null) {\n const consumerCleanup = consumerCleanupRef.current;\n consumerCleanupRef.current = null;\n if (consumerCleanup) {\n consumerCleanup();\n } else {\n ref(null);\n }\n return;\n }\n const cleanup: unknown = ref(node);\n consumerCleanupRef.current =\n typeof cleanup === 'function' ? (cleanup as () => void) : null;\n } else if (ref) {\n (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;\n }\n },\n [ref]\n );\n\n // Generate classes\n const dialogClasses = usePrefixedClassNames('dialog', {\n [`is-${type}`]: type !== 'default',\n });\n const headerClass = usePrefixedClassNames('dialog-header');\n const iconClass = usePrefixedClassNames('dialog-icon');\n const titleClass = usePrefixedClassNames('dialog-title');\n const bodyClass = usePrefixedClassNames('dialog-body');\n const footerClass = usePrefixedClassNames('dialog-footer');\n const cancelButtonClass = usePrefixedClassNames('button');\n const confirmButtonClass = usePrefixedClassNames('button', {\n 'is-success': type === 'success',\n 'is-danger': type === 'danger',\n 'is-warning': type === 'warning',\n 'is-info': type === 'info',\n 'is-primary': type === 'default',\n });\n\n const combinedClasses = classNames(\n dialogClasses,\n bulmaHelperClasses,\n className\n );\n\n // Get default icon based on type\n const getDefaultIcon = () => {\n switch (type) {\n case 'success':\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <path d=\"M20 6L9 17l-5-5\" />\n </svg>\n );\n case 'danger':\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"15\" y1=\"9\" x2=\"9\" y2=\"15\" />\n <line x1=\"9\" y1=\"9\" x2=\"15\" y2=\"15\" />\n </svg>\n );\n case 'warning':\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"currentColor\"\n stroke=\"none\"\n >\n <path d=\"M12 2L1 21h22L12 2zm0 3.99L19.53 19H4.47L12 5.99zM11 16h2v2h-2zm0-6h2v4h-2z\" />\n </svg>\n );\n case 'info':\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"currentColor\"\n stroke=\"none\"\n >\n <path d=\"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-9h2v6h-2zm0-4h2v2h-2z\" />\n </svg>\n );\n default:\n return null;\n }\n };\n\n const displayIcon = icon !== undefined ? icon : getDefaultIcon();\n\n if (!isOpen) {\n return null;\n }\n\n return (\n <Modal\n isActive={isOpen}\n onClose={handleCancel}\n role=\"presentation\"\n portal={portal}\n >\n <Modal.Background onClick={handleBackgroundClick} />\n <div\n ref={combinedRef}\n className={combinedClasses}\n role=\"alertdialog\"\n aria-modal=\"true\"\n aria-labelledby={title ? 'dialog-title' : undefined}\n aria-describedby=\"dialog-message\"\n {...rest}\n >\n {title && (\n <div className={headerClass}>\n {displayIcon && <span className={iconClass}>{displayIcon}</span>}\n <h3 id=\"dialog-title\" className={titleClass}>\n {title}\n </h3>\n </div>\n )}\n <div id=\"dialog-message\" className={bodyClass}>\n {message}\n </div>\n <div className={footerClass}>\n {showCancel && (\n <button\n ref={cancelRef}\n type=\"button\"\n className={cancelButtonClass}\n onClick={handleCancel}\n >\n {cancelText}\n </button>\n )}\n <button\n ref={confirmRef}\n type=\"button\"\n className={confirmButtonClass}\n onClick={handleConfirm}\n >\n {confirmText}\n </button>\n </div>\n </div>\n </Modal>\n );\n }\n);\n\nDialog.displayName = 'Dialog';\n\n// Dialog Manager for programmatic dialogs\n\n/**\n * Options for showing a programmatic alert dialog.\n */\nexport interface AlertOptions {\n /** Dialog title. */\n title?: string;\n /** Dialog message/content. */\n message: string | React.ReactNode;\n /** Dialog type/color. */\n type?: DialogType;\n /** Text for the confirm button. */\n confirmText?: string;\n /** Custom icon to display. */\n icon?: React.ReactNode;\n}\n\n/**\n * Options for showing a programmatic confirm dialog.\n */\nexport interface ConfirmOptions extends AlertOptions {\n /** Text for the cancel button. */\n cancelText?: string;\n /** Focus cancel button instead of confirm. */\n focusCancel?: boolean;\n}\n\n/**\n * Options for showing a programmatic prompt dialog.\n */\nexport interface PromptOptions extends ConfirmOptions {\n /** Input placeholder text. */\n placeholder?: string;\n /** Default input value. */\n defaultValue?: string;\n}\n\ntype DialogResolve = (value?: void | boolean | string) => void;\n\ntype DialogState = {\n type: 'alert' | 'confirm' | 'prompt';\n options: PromptOptions;\n resolve: DialogResolve;\n};\n\nlet dialogListeners: Set<(dialog: DialogState | null) => void> = new Set();\nlet currentDialog: DialogState | null = null;\n\n// DialogContainer renders from the open dialog rather than from updates alone,\n// so a dialog raised before it mounted still opens once it does.\nconst getCurrentDialog = () => currentDialog;\n\n// The server renders no dialog: its copy of this module is shared by every\n// request, so the dialog it holds may belong to another page. Hydration reads\n// the same empty value, which keeps the first client render matching the\n// server's, and the dialog opens right after.\nconst getServerDialog = (): DialogState | null => null;\n\nconst notifyDialogListeners = () => {\n dialogListeners.forEach(listener => listener(currentDialog));\n};\n\n/**\n * Programmatic dialog API for showing dialogs from anywhere.\n */\nexport const dialog = {\n /**\n * Show an alert dialog. Returns a promise that resolves when closed.\n */\n alert: (options: AlertOptions | string): Promise<void> => {\n return new Promise<void>(resolve => {\n const opts = typeof options === 'string' ? { message: options } : options;\n currentDialog = {\n type: 'alert',\n options: opts,\n resolve: () => resolve(),\n };\n notifyDialogListeners();\n });\n },\n\n /**\n * Show a confirm dialog. Returns a promise that resolves to true/false.\n */\n confirm: (options: ConfirmOptions | string): Promise<boolean> => {\n return new Promise<boolean>(resolve => {\n const opts = typeof options === 'string' ? { message: options } : options;\n currentDialog = {\n type: 'confirm',\n options: opts,\n resolve: value => resolve(Boolean(value)),\n };\n notifyDialogListeners();\n });\n },\n\n /**\n * Close the current dialog.\n */\n close: (value?: void | boolean | string): void => {\n if (currentDialog) {\n currentDialog.resolve(value);\n currentDialog = null;\n notifyDialogListeners();\n }\n },\n\n /**\n * Subscribe to dialog changes.\n */\n subscribe: (listener: (dialog: DialogState | null) => void): (() => void) => {\n dialogListeners.add(listener);\n return () => dialogListeners.delete(listener);\n },\n};\n\n/**\n * DialogContainer component to render programmatic dialogs.\n * Place this once at the root of your app.\n *\n * @function\n * @returns {JSX.Element | null} The rendered dialog, or null if none is active.\n */\nexport const DialogContainer: React.FC = () => {\n // Starts from the dialog already open instead of none, then follows changes.\n const current = useSyncExternalStore(\n dialog.subscribe,\n getCurrentDialog,\n getServerDialog\n );\n\n if (!current) {\n return null;\n }\n\n const { type, options } = current;\n\n return (\n <Dialog\n isOpen\n title={options.title}\n message={options.message}\n type={options.type}\n confirmText={options.confirmText}\n cancelText={options.cancelText}\n icon={options.icon}\n showCancel={type === 'confirm'}\n focusCancel={options.focusCancel}\n onConfirm={() => dialog.close(type === 'confirm' ? true : undefined)}\n onCancel={() => dialog.close(type === 'confirm' ? false : undefined)}\n />\n );\n};\n\nexport default Dialog;\n"],"names":["_jsx","_jsxs"],"mappings":";;;;;;;;;AAwDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BG;AACI,MAAM,MAAM,GAAG,UAAU,CAC9B,CACE,EACE,MAAM,EACN,KAAK,EACL,OAAO,EACP,IAA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AAC;;AAGH;;;;;;AAMG;AACI,MAAM,eAAe,GAAa,MAAK;;AAE5C,IAAA,MAAM,OAAO,GAAG,oBAAoB,CAClC,MAAM,CAAC,SAAS,EAChB,gBAAgB,EAChB,eAAe,CAChB;IAED,IAAI,CAAC,OAAO,EAAE;AACZ,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO;IAEjC,QACEA,IAAC,MAAM,EAAA,EACL,MAAM,EAAA,IAAA,EACN,KAAK,EAAE,OAAO,CAAC,KAAK,EACpB,OAAO,EAAE,OAAO,CAAC,OAAO,EACxB,IAAI,EAAE,OAAO,CAAC,IAAI,EAClB,WAAW,EAAE,OAAO,CAAC,WAAW,EAChC,UAAU,EAAE,OAAO,CAAC,UAAU,EAC9B,IAAI,EAAE,OAAO,CAAC,IAAI,EAClB,UAAU,EAAE,IAAI,KAAK,SAAS,EAC9B,WAAW,EAAE,OAAO,CAAC,WAAW,EAChC,SAAS,EAAE,MAAM,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,GAAG,IAAI,GAAG,SAAS,CAAC,EACpE,QAAQ,EAAE,MAAM,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,GAAG,KAAK,GAAG,SAAS,CAAC,EAAA,CACpE;AAEN;;"}
|
|
1
|
+
{"version":3,"file":"Dialog.js","sources":["../../../src/components/Dialog.tsx"],"sourcesContent":["import React, {\n forwardRef,\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { classNames, usePrefixedClassNames } from '../helpers/classNames';\nimport { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses';\nimport { PortalScope, usePortalProp } from '../helpers/portal';\nimport { Modal } from './Modal';\n\n/** Valid dialog type/color values. */\nexport type DialogType = 'default' | 'success' | 'danger' | 'warning' | 'info';\n\n/**\n * Props for the Dialog component.\n * @extraProp {string} [className] - Additional CSS classes.\n * @extraProp {React.Ref<HTMLElement>} [ref] - Ref forwarded to the dialog element.\n */\nexport interface DialogProps\n extends\n Omit<React.HTMLAttributes<HTMLDivElement>, 'color'>,\n Omit<BulmaClassesProps, 'color'> {\n /** Whether the dialog is open (required). */\n isOpen: boolean;\n /** Dialog title. */\n title?: string;\n /** Dialog message/content (required). */\n message: string | React.ReactNode;\n /** The type/color of the dialog. Default: 'default'. */\n type?: DialogType;\n /** Text for confirm button. Default: 'OK'. */\n confirmText?: string;\n /** Text for cancel button. Default: 'Cancel'. */\n cancelText?: string;\n /** Callback when confirm button is clicked. */\n onConfirm?: () => void;\n /** Callback when cancel button is clicked or dismissed. */\n onCancel?: () => void;\n /** Whether to show cancel button. Default: true for confirm dialogs. */\n showCancel?: boolean;\n /** Whether the dialog can be dismissed. Default: true. */\n canCancel?: boolean;\n /** Focus cancel button instead of confirm. Default: false. */\n focusCancel?: boolean;\n /** Custom icon to display. */\n icon?: React.ReactNode;\n /**\n * Renders the dialog into a portal target instead of inline. Forwarded to\n * the underlying `Modal`; see its `portal` prop for the accepted values.\n * @defaultValue false\n */\n portal?: boolean | string | HTMLElement;\n}\n\n/**\n * The `Dialog` component provides ready-made confirm and alert dialogs, so a destructive action stays one `await dialog.confirm()` call away.\n *\n * @function\n * @param {DialogProps} props - Props for the Dialog component.\n * @param {React.Ref<HTMLDivElement>} ref - Forwarded ref to the dialog element.\n * @returns {JSX.Element | null} The rendered dialog component.\n *\n * @example\n * // Alert dialog\n * <Dialog\n * isOpen={showAlert}\n * title=\"Success\"\n * message=\"Operation completed successfully!\"\n * type=\"success\"\n * onConfirm={() => setShowAlert(false)}\n * showCancel={false}\n * />\n *\n * @example\n * // Confirm dialog\n * <Dialog\n * isOpen={showConfirm}\n * title=\"Delete Item?\"\n * message=\"This action cannot be undone.\"\n * type=\"danger\"\n * confirmText=\"Delete\"\n * onConfirm={handleDelete}\n * onCancel={() => setShowConfirm(false)}\n * />\n */\nexport const Dialog = forwardRef<HTMLDivElement, DialogProps>(\n (\n {\n isOpen,\n title,\n message,\n type = 'default',\n confirmText = 'OK',\n cancelText = 'Cancel',\n onConfirm,\n onCancel,\n showCancel = true,\n canCancel = true,\n focusCancel = false,\n icon,\n portal,\n className,\n ...props\n },\n ref\n ) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n const dialogRef = useRef<HTMLDivElement>(null);\n // Cleanup returned by a consumer's callback ref on attach, held until detach.\n const consumerCleanupRef = useRef<(() => void) | null>(null);\n // The box, as state, for the popups in the message to portal into. It's\n // what carries `aria-modal`, rather than the Modal's root around it.\n const [scopeNode, setScopeNode] = useState<HTMLDivElement | null>(null);\n const confirmRef = useRef<HTMLButtonElement>(null);\n const cancelRef = useRef<HTMLButtonElement>(null);\n\n // Handle cancel\n const handleCancel = useCallback(() => {\n if (canCancel) {\n onCancel?.();\n }\n }, [canCancel, onCancel]);\n\n // Handle confirm\n const handleConfirm = useCallback(() => {\n onConfirm?.();\n }, [onConfirm]);\n\n // Handle background click\n const handleBackgroundClick = useCallback(() => {\n if (canCancel) {\n handleCancel();\n }\n }, [canCancel, handleCancel]);\n\n // Moving into the portal, or from one portal target to another, remounts\n // the Modal's subtree, these buttons included, so the focus effect below\n // has to re-run against the new nodes, exactly as the Modal's own focus\n // effect does, on the same inputs.\n const { isPortaled, defaultTarget } = usePortalProp(portal);\n\n // Focus management — Dialog picks a specific button rather than the\n // Modal's default (first focusable/root); this effect runs after the\n // inner Modal's own focus-on-open effect, so it wins.\n useEffect(() => {\n if (isOpen) {\n const buttonToFocus =\n focusCancel && showCancel ? cancelRef.current : confirmRef.current;\n buttonToFocus?.focus();\n }\n }, [isOpen, focusCancel, showCancel, isPortaled, portal, defaultTarget]);\n\n // Use combined ref\n const combinedRef = useCallback(\n (node: HTMLDivElement | null) => {\n (dialogRef as React.MutableRefObject<HTMLDivElement | null>).current =\n node;\n setScopeNode(node);\n if (typeof ref === 'function') {\n // React 19 lets a callback ref return a cleanup function and detaches by\n // running it instead of calling the ref with `null`; React 18 discards the\n // return value entirely. Returning it from here would be a React-19-only\n // contract, so we hold the cleanup and run it ourselves on detach — the\n // same shape as `Dropdown`, `Modal`, `Sidebar`, `Toast` and `Carousel`.\n // The form controls that merge a forwarded ref still discard the cleanup\n // and detach with `ref(null)`, so this is not yet library-wide — grep\n // `typeof ref === 'function'` for the current split.\n if (node === null) {\n const consumerCleanup = consumerCleanupRef.current;\n consumerCleanupRef.current = null;\n if (consumerCleanup) {\n consumerCleanup();\n } else {\n ref(null);\n }\n return;\n }\n const cleanup: unknown = ref(node);\n consumerCleanupRef.current =\n typeof cleanup === 'function' ? (cleanup as () => void) : null;\n } else if (ref) {\n (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;\n }\n },\n [ref]\n );\n\n // Generate classes\n const dialogClasses = usePrefixedClassNames('dialog', {\n [`is-${type}`]: type !== 'default',\n });\n const headerClass = usePrefixedClassNames('dialog-header');\n const iconClass = usePrefixedClassNames('dialog-icon');\n const titleClass = usePrefixedClassNames('dialog-title');\n const bodyClass = usePrefixedClassNames('dialog-body');\n const footerClass = usePrefixedClassNames('dialog-footer');\n const cancelButtonClass = usePrefixedClassNames('button');\n const confirmButtonClass = usePrefixedClassNames('button', {\n 'is-success': type === 'success',\n 'is-danger': type === 'danger',\n 'is-warning': type === 'warning',\n 'is-info': type === 'info',\n 'is-primary': type === 'default',\n });\n\n const combinedClasses = classNames(\n dialogClasses,\n bulmaHelperClasses,\n className\n );\n\n // Get default icon based on type\n const getDefaultIcon = () => {\n switch (type) {\n case 'success':\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <path d=\"M20 6L9 17l-5-5\" />\n </svg>\n );\n case 'danger':\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"15\" y1=\"9\" x2=\"9\" y2=\"15\" />\n <line x1=\"9\" y1=\"9\" x2=\"15\" y2=\"15\" />\n </svg>\n );\n case 'warning':\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"currentColor\"\n stroke=\"none\"\n >\n <path d=\"M12 2L1 21h22L12 2zm0 3.99L19.53 19H4.47L12 5.99zM11 16h2v2h-2zm0-6h2v4h-2z\" />\n </svg>\n );\n case 'info':\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"currentColor\"\n stroke=\"none\"\n >\n <path d=\"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-9h2v6h-2zm0-4h2v2h-2z\" />\n </svg>\n );\n default:\n return null;\n }\n };\n\n const displayIcon = icon !== undefined ? icon : getDefaultIcon();\n\n if (!isOpen) {\n return null;\n }\n\n return (\n <Modal\n isActive={isOpen}\n onClose={handleCancel}\n role=\"presentation\"\n portal={portal}\n >\n <Modal.Background onClick={handleBackgroundClick} />\n <PortalScope node={scopeNode}>\n <div\n ref={combinedRef}\n className={combinedClasses}\n role=\"alertdialog\"\n aria-modal=\"true\"\n aria-labelledby={title ? 'dialog-title' : undefined}\n aria-describedby=\"dialog-message\"\n {...rest}\n >\n {title && (\n <div className={headerClass}>\n {displayIcon && (\n <span className={iconClass}>{displayIcon}</span>\n )}\n <h3 id=\"dialog-title\" className={titleClass}>\n {title}\n </h3>\n </div>\n )}\n <div id=\"dialog-message\" className={bodyClass}>\n {message}\n </div>\n <div className={footerClass}>\n {showCancel && (\n <button\n ref={cancelRef}\n type=\"button\"\n className={cancelButtonClass}\n onClick={handleCancel}\n >\n {cancelText}\n </button>\n )}\n <button\n ref={confirmRef}\n type=\"button\"\n className={confirmButtonClass}\n onClick={handleConfirm}\n >\n {confirmText}\n </button>\n </div>\n </div>\n </PortalScope>\n </Modal>\n );\n }\n);\n\nDialog.displayName = 'Dialog';\n\n// Dialog Manager for programmatic dialogs\n\n/**\n * Options for showing a programmatic alert dialog.\n */\nexport interface AlertOptions {\n /** Dialog title. */\n title?: string;\n /** Dialog message/content. */\n message: string | React.ReactNode;\n /** Dialog type/color. */\n type?: DialogType;\n /** Text for the confirm button. */\n confirmText?: string;\n /** Custom icon to display. */\n icon?: React.ReactNode;\n}\n\n/**\n * Options for showing a programmatic confirm dialog.\n */\nexport interface ConfirmOptions extends AlertOptions {\n /** Text for the cancel button. */\n cancelText?: string;\n /** Focus cancel button instead of confirm. */\n focusCancel?: boolean;\n}\n\n/**\n * Options for showing a programmatic prompt dialog.\n */\nexport interface PromptOptions extends ConfirmOptions {\n /** Input placeholder text. */\n placeholder?: string;\n /** Default input value. */\n defaultValue?: string;\n}\n\ntype DialogResolve = (value?: void | boolean | string) => void;\n\ntype DialogState = {\n type: 'alert' | 'confirm' | 'prompt';\n options: PromptOptions;\n resolve: DialogResolve;\n};\n\nlet dialogListeners: Set<(dialog: DialogState | null) => void> = new Set();\nlet currentDialog: DialogState | null = null;\n\n// DialogContainer renders from the open dialog rather than from updates alone,\n// so a dialog raised before it mounted still opens once it does.\nconst getCurrentDialog = () => currentDialog;\n\n// The server renders no dialog: its copy of this module is shared by every\n// request, so the dialog it holds may belong to another page. Hydration reads\n// the same empty value, which keeps the first client render matching the\n// server's, and the dialog opens right after.\nconst getServerDialog = (): DialogState | null => null;\n\nconst notifyDialogListeners = () => {\n dialogListeners.forEach(listener => listener(currentDialog));\n};\n\n/**\n * Programmatic dialog API for showing dialogs from anywhere.\n */\nexport const dialog = {\n /**\n * Show an alert dialog. Returns a promise that resolves when closed.\n */\n alert: (options: AlertOptions | string): Promise<void> => {\n return new Promise<void>(resolve => {\n const opts = typeof options === 'string' ? { message: options } : options;\n currentDialog = {\n type: 'alert',\n options: opts,\n resolve: () => resolve(),\n };\n notifyDialogListeners();\n });\n },\n\n /**\n * Show a confirm dialog. Returns a promise that resolves to true/false.\n */\n confirm: (options: ConfirmOptions | string): Promise<boolean> => {\n return new Promise<boolean>(resolve => {\n const opts = typeof options === 'string' ? { message: options } : options;\n currentDialog = {\n type: 'confirm',\n options: opts,\n resolve: value => resolve(Boolean(value)),\n };\n notifyDialogListeners();\n });\n },\n\n /**\n * Close the current dialog.\n */\n close: (value?: void | boolean | string): void => {\n if (currentDialog) {\n currentDialog.resolve(value);\n currentDialog = null;\n notifyDialogListeners();\n }\n },\n\n /**\n * Subscribe to dialog changes.\n */\n subscribe: (listener: (dialog: DialogState | null) => void): (() => void) => {\n dialogListeners.add(listener);\n return () => dialogListeners.delete(listener);\n },\n};\n\n/**\n * DialogContainer component to render programmatic dialogs.\n * Place this once at the root of your app.\n *\n * @function\n * @returns {JSX.Element | null} The rendered dialog, or null if none is active.\n */\nexport const DialogContainer: React.FC = () => {\n // Starts from the dialog already open instead of none, then follows changes.\n const current = useSyncExternalStore(\n dialog.subscribe,\n getCurrentDialog,\n getServerDialog\n );\n\n if (!current) {\n return null;\n }\n\n const { type, options } = current;\n\n return (\n <Dialog\n isOpen\n title={options.title}\n message={options.message}\n type={options.type}\n confirmText={options.confirmText}\n cancelText={options.cancelText}\n icon={options.icon}\n showCancel={type === 'confirm'}\n focusCancel={options.focusCancel}\n onConfirm={() => dialog.close(type === 'confirm' ? true : undefined)}\n onCancel={() => dialog.close(type === 'confirm' ? false : undefined)}\n />\n );\n};\n\nexport default Dialog;\n"],"names":["_jsx","_jsxs"],"mappings":";;;;;;;;;AAyDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BG;AACI,MAAM,MAAM,GAAG,UAAU,CAC9B,CACE,EACE,MAAM,EACN,KAAK,EACL,OAAO,EACP,IAAI,GAAG,SAAS,EAChB,WAAW,GAAG,IAAI,EAClB,UAAU,GAAG,QAAQ,EACrB,SAAS,EACT,QAAQ,EACR,UAAU,G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AO,MAAM,eAAe,CAAC,MAAM,CAAC,QAAQ,CAAC;IAC/C,CAAC;;AAGH;;;;;;AAMG;AACI,MAAM,eAAe,GAAa,MAAK;;AAE5C,IAAA,MAAM,OAAO,GAAG,oBAAoB,CAClC,MAAM,CAAC,SAAS,EAChB,gBAAgB,EAChB,eAAe,CAChB;IAED,IAAI,CAAC,OAAO,EAAE;AACZ,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO;IAEjC,QACEA,IAAC,MAAM,EAAA,EACL,MAAM,EAAA,IAAA,EACN,KAAK,EAAE,OAAO,CAAC,KAAK,EACpB,OAAO,EAAE,OAAO,CAAC,OAAO,EACxB,IAAI,EAAE,OAAO,CAAC,IAAI,EAClB,WAAW,EAAE,OAAO,CAAC,WAAW,EAChC,UAAU,EAAE,OAAO,CAAC,UAAU,EAC9B,IAAI,EAAE,OAAO,CAAC,IAAI,EAClB,UAAU,EAAE,IAAI,KAAK,SAAS,EAC9B,WAAW,EAAE,OAAO,CAAC,WAAW,EAChC,SAAS,EAAE,MAAM,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,GAAG,IAAI,GAAG,SAAS,CAAC,EACpE,QAAQ,EAAE,MAAM,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,GAAG,KAAK,GAAG,SAAS,CAAC,EAAA,CACpE;AAEN;;"}
|
|
@@ -4,7 +4,7 @@ import { jsxs, jsx } from 'react/jsx-runtime';
|
|
|
4
4
|
import { useRef, useId, useState, useCallback, useMemo, useEffect, cloneElement } from 'react';
|
|
5
5
|
import { classNames, usePrefixedClassNames } from '../helpers/classNames.js';
|
|
6
6
|
import { useBulmaClasses } from '../helpers/useBulmaClasses.js';
|
|
7
|
-
import {
|
|
7
|
+
import { PopupPortal } from '../helpers/portal.js';
|
|
8
8
|
import { useIsHydrated } from '../helpers/useIsHydrated.js';
|
|
9
9
|
import { useAnchoredPosition, marginGap } from '../helpers/useAnchoredPosition.js';
|
|
10
10
|
import { useHoverOpen, chain } from '../helpers/useHoverOpen.js';
|
|
@@ -108,7 +108,7 @@ const HoverCard = ({ trigger, children, open: controlledOpen, defaultOpen = fals
|
|
|
108
108
|
[`is-${resolved.position}`]: true,
|
|
109
109
|
'is-portal': appendToBody,
|
|
110
110
|
}), contentClassName);
|
|
111
|
-
return (jsxs("span", { className: rootClasses, ...attrs, onPointerEnter: chain(onPointerEnter, hover.onPointerEnter), onPointerOver: chain(onPointerOver, hover.onPointerOver), onPointerLeave: chain(onPointerLeave, hover.onPointerLeave), onFocus: chain(onFocus, hover.onFocus), onBlur: chain(onBlur, hover.onBlur), onPointerDown: chain(onPointerDown, hover.onPointerDown), onPointerUp: chain(onPointerUp, hover.onPointerUp), ref: rootRef, children: [clonedTrigger, isOpen && (jsx(
|
|
111
|
+
return (jsxs("span", { className: rootClasses, ...attrs, onPointerEnter: chain(onPointerEnter, hover.onPointerEnter), onPointerOver: chain(onPointerOver, hover.onPointerOver), onPointerLeave: chain(onPointerLeave, hover.onPointerLeave), onFocus: chain(onFocus, hover.onFocus), onBlur: chain(onBlur, hover.onBlur), onPointerDown: chain(onPointerDown, hover.onPointerDown), onPointerUp: chain(onPointerUp, hover.onPointerUp), ref: rootRef, children: [clonedTrigger, isOpen && (jsx(PopupPortal, { disabled: !appendToBody, children: jsx("div", { ref: cardRef, id: cardId, className: cardClasses, style: appendToBody
|
|
112
112
|
? {
|
|
113
113
|
position: 'fixed',
|
|
114
114
|
top: resolved.top,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HoverCard.js","sources":["../../../src/components/HoverCard.tsx"],"sourcesContent":["import React, {\n cloneElement,\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { classNames, usePrefixedClassNames } from '../helpers/classNames';\nimport { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses';\nimport { Portal } from '../helpers/portal';\nimport { useIsHydrated } from '../helpers/useIsHydrated';\nimport { marginGap, useAnchoredPosition } from '../helpers/useAnchoredPosition';\nimport { chain, useHoverOpen } from '../helpers/useHoverOpen';\nimport { isTabbableKind } from '../helpers/useFocusTrap';\nimport { isDev, warnOnce } from '../helpers/devWarnings';\nimport type { PickerPosition } from '../form/_pickerInternals/pickerTypes';\n\n/**\n * Where the card opens against its trigger: below (`bottom-*`) or above\n * (`top-*`), lined up with the trigger's left or right edge. `auto` picks the\n * one that keeps the card in the viewport, preferring below and lined up on\n * the left. The same union `Popover` and the date and time pickers take.\n */\nexport type HoverCardPosition = PickerPosition;\n\n/**\n * Props for the HoverCard component. `className`, `id`, the other HTML\n * attributes and the helper props land on the `span` around the trigger, not\n * on the card; `contentClassName` reaches the card.\n * @extraProp {string} [className] - Additional classes for the `span` around the trigger. The card takes `contentClassName`.\n */\nexport interface HoverCardProps\n extends\n Omit<React.HTMLAttributes<HTMLSpanElement>, 'color' | 'children'>,\n Omit<BulmaClassesProps, 'color' | 'backgroundColor'> {\n /**\n * The element the card previews, such as a link or a `Button`. The element\n * itself has to take focus, so keyboard users can open the card too: a\n * link inside a `<span>` doesn't do, since focus comes back to the trigger\n * and its ARIA is on it. HoverCard gives it no role and no tab stop, since\n * it can't know what the element is, and a development build warns when\n * it can't take focus: use a link or a button, or give the element\n * `tabIndex={0}`. A disabled button can't take focus either. HoverCard adds\n * `aria-expanded` and `aria-controls`, both naming the card only while it\n * is on the page, so it has to be a single element that passes those to\n * its DOM node. Its own click and keys stay its own, and the card doesn't\n * toggle on them, except Escape while the card is open, which closes the\n * card before the trigger sees it.\n */\n trigger: React.ReactElement;\n /**\n * The card's content: a preview whose links and buttons are fine, but not a\n * form, which belongs in a `Popover`. The card pads itself, so content goes\n * straight in.\n */\n children?: React.ReactNode;\n /**\n * Controlled open state. When set, hover, focus and Escape only report\n * through `onOpenChange`, so an action inside the card can close it. While\n * the card is open, Escape is reported, and when focus is in the card, on\n * its trigger or nowhere, the key stops there even if you keep the card\n * open, so a `Modal` around it doesn't close from the keyboard until the\n * card does.\n */\n open?: boolean;\n /**\n * Initial open state when uncontrolled. A card that starts open stays open\n * until the pointer or focus has been and gone, or Escape closes it.\n * @defaultValue false\n */\n defaultOpen?: boolean;\n /**\n * Called with the state asked for: when `openDelay` or `closeDelay` runs\n * out, and right away on Escape. Fires in both controlled and uncontrolled\n * use. An Escape it reports stops at the card when focus is in the card,\n * on its trigger or nowhere, so nothing around it sees that key. With\n * focus anywhere else, the card still closes and the key goes on to\n * whatever has focus.\n */\n onOpenChange?: (open: boolean) => void;\n /**\n * How long the pointer or keyboard focus waits on the trigger before the\n * card opens, in milliseconds.\n * @defaultValue 600\n */\n openDelay?: number;\n /**\n * How long the card stays after the pointer and focus have left the trigger\n * and the card, in milliseconds. It is the time the pointer has to cross\n * the gap between the trigger and the card: with `0` the card closes as the\n * pointer leaves the trigger, before the pointer can reach it.\n * @defaultValue 300\n */\n closeDelay?: number;\n /**\n * Where the card opens against the trigger.\n * @defaultValue 'bottom-left'\n */\n position?: HoverCardPosition;\n /**\n * Render the card through `Portal`, into the `portalContainer` a\n * `ConfigProvider` sets, `document.body` by default, fixed to the viewport,\n * so an ancestor's `overflow`, `transform` or stacking context can't clip\n * it. A trigger in running text needs it too, since the card's block\n * content can't sit inside a `<p>`. The card then shows from the commit\n * after hydration, never in server markup, and it sits in the Tab order\n * where its container is. At the end of `<body>`, the default, Tab reaches\n * it only after the rest of the page, and focus leaving the trigger on the\n * way closes it, so keyboard users can open it, read it and close it with\n * Escape, and whatever it links to has to be reachable from the page as\n * well. Theming variables set on an ancestor of the trigger reach it only\n * when its container is inside that ancestor.\n * @defaultValue false\n */\n appendToBody?: boolean;\n /**\n * Open the card with a tap on a touch screen. Touch has no hover, so\n * without this a phone or tablet never opens the card. With it, a tap on\n * the trigger opens the card at once, and it stays until a second tap on\n * the trigger, a tap outside the trigger and the card, or Escape. The tap\n * still does whatever the trigger does, so turn this on only for a trigger\n * with no tap action of its own, such as a `Button` with no `onClick`: on\n * a link, the first tap would follow the link rather than show the card.\n * Mouse and pen work the same either way.\n * @defaultValue false\n */\n openOnTap?: boolean;\n /** Additional classes for the card (`.hover-card-content`). */\n contentClassName?: string;\n}\n\n/**\n * The `HoverCard` component shows a card previewing what's behind a link or a button while the pointer rests on it or keyboard focus is on it.\n *\n * Nothing moves focus when the card opens, and nothing traps it. In place,\n * the card comes right after the trigger, so Tab goes from the trigger into\n * its links and tabbing past them closes it. The pointer can move onto the\n * card, Escape closes it from anywhere, and by default touch doesn't open it,\n * so tapping the trigger just does what the trigger does. `openOnTap` opens\n * it with a tap, for a trigger with no tap action of its own. For hints with nothing to\n * click use `Tooltip`, and for content opened on purpose, such as a form,\n * use `Popover`.\n *\n * @function\n * @param {HoverCardProps} props - Props for the HoverCard component.\n * @returns {JSX.Element} The trigger in its wrapper, and the card while open.\n *\n * @example\n * <HoverCard trigger={<a href=\"/people/ada\">Ada Lovelace</a>}>\n * <Title as=\"p\" size=\"6\">Ada Lovelace</Title>\n * <SubTitle as=\"p\" size=\"6\">Analytical Engine team</SubTitle>\n * </HoverCard>\n */\nexport const HoverCard: React.FC<HoverCardProps> = ({\n trigger,\n children,\n open: controlledOpen,\n defaultOpen = false,\n onOpenChange,\n openDelay = 600,\n closeDelay = 300,\n position = 'bottom-left',\n appendToBody = false,\n openOnTap = false,\n className,\n contentClassName,\n ...props\n}) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n const {\n onPointerEnter,\n onPointerOver,\n onPointerLeave,\n onPointerDown,\n onPointerUp,\n onFocus,\n onBlur,\n ...attrs\n } = rest;\n const rootRef = useRef<HTMLSpanElement>(null);\n const cardRef = useRef<HTMLDivElement>(null);\n const cardId = `${useId()}-card`;\n\n const isControlled = controlledOpen !== undefined;\n const [internalOpen, setInternalOpen] = useState(defaultOpen);\n const isOpen = controlledOpen ?? internalOpen;\n\n const requestOpen = useCallback(\n (next: boolean) => {\n onOpenChange?.(next);\n if (!isControlled) setInternalOpen(next);\n },\n [isControlled, onOpenChange]\n );\n\n // A portaled card has no server markup, so it only exists from the commit\n // after hydration, and nothing measures it before then.\n const hydrated = useIsHydrated();\n const cardMounted = isOpen && (hydrated || !appendToBody);\n\n const resolved = useAnchoredPosition(rootRef, cardRef, {\n active: cardMounted,\n position,\n fixed: appendToBody,\n // The gap comes from `--bulma-hover-card-offset` in the stylesheet, so\n // the coordinates leave it out and `auto` reads it off the card.\n offset: 0,\n styledGap: marginGap,\n });\n\n // The trigger renders first inside the wrapper. Read when needed rather\n // than held, so a trigger that remounted is still the one found.\n const triggerRef = useMemo(\n () => ({\n get current() {\n const first = (rootRef.current as HTMLSpanElement).firstElementChild;\n return first && first !== cardRef.current\n ? (first as HTMLElement)\n : null;\n },\n }),\n []\n );\n\n const hover = useHoverOpen({\n open: isOpen,\n onOpenChange: requestOpen,\n openDelay,\n closeDelay,\n triggerRef,\n floatingRef: cardRef,\n openOnTap,\n });\n\n // A trigger that can't take focus leaves keyboard users no way to open the\n // card. It has to be the trigger element itself, not something inside it,\n // since focus comes back to it and its ARIA is on it. Judged by what the\n // element is rather than by its styles, which can hide it for now. After\n // every commit, since the trigger can change, and only in development.\n useEffect(() => {\n if (!isDev()) return;\n const triggerNode = triggerRef.current;\n if (!triggerNode) return;\n if (!triggerNode.matches(':disabled') && isTabbableKind(triggerNode)) {\n return;\n }\n warnOnce(\n 'HoverCard:unfocusable-trigger',\n \"[bestax-bulma] <HoverCard> has a trigger that can't take focus, so \" +\n \"keyboard users can't open the card. Use a link or a button as the \" +\n 'trigger, or give it tabIndex={0}.'\n );\n });\n\n // Expanded only while the card is on the page, so a portaled card that\n // waits for hydration isn't announced before it exists.\n const clonedTrigger = cloneElement(\n trigger as React.ReactElement<Record<string, unknown>>,\n {\n 'aria-expanded': cardMounted,\n 'aria-controls': cardMounted ? cardId : undefined,\n }\n );\n\n const rootClasses = classNames(\n usePrefixedClassNames('hover-card', { 'is-active': cardMounted }),\n bulmaHelperClasses,\n className\n );\n const cardClasses = classNames(\n usePrefixedClassNames('hover-card-content', {\n [`is-${resolved.position}`]: true,\n 'is-portal': appendToBody,\n }),\n contentClassName\n );\n\n return (\n // The ref after the spread: React 19 hands a function component a `ref`\n // prop like any other, and the wrapper has to stay ours. The card is in\n // the wrapper's React tree even when portaled, so the hover and focus\n // handlers here hear from both.\n <span\n className={rootClasses}\n {...attrs}\n onPointerEnter={chain(onPointerEnter, hover.onPointerEnter)}\n onPointerOver={chain(onPointerOver, hover.onPointerOver)}\n onPointerLeave={chain(onPointerLeave, hover.onPointerLeave)}\n onFocus={chain(onFocus, hover.onFocus)}\n onBlur={chain(onBlur, hover.onBlur)}\n onPointerDown={chain(onPointerDown, hover.onPointerDown)}\n onPointerUp={chain(onPointerUp, hover.onPointerUp)}\n ref={rootRef}\n >\n {clonedTrigger}\n {isOpen && (\n <Portal disabled={!appendToBody}>\n <div\n ref={cardRef}\n id={cardId}\n className={cardClasses}\n style={\n appendToBody\n ? {\n position: 'fixed',\n top: resolved.top,\n left: resolved.left,\n }\n : undefined\n }\n >\n {children}\n </div>\n </Portal>\n )}\n </span>\n );\n};\n\nexport default HoverCard;\n"],"names":["_jsxs","_jsx"],"mappings":";;;;;;;;;;;;;AAqIA;;;;;;;;;;;;;;;;;;;;;AAqBG;MACU,SAAS,GAA6B,CAAC,EAClD,OAAO,EACP,QAAQ,EACR,IAAI,EAAE,cAAc,EACpB,WAAW,GAAG,KAAK,EACnB,YAAY,EACZ,SAAS,GAAG,GAAG,EACf,UAAU,GAAG,GAAG,EAChB,QAAQ,GAAG,aAAa,EACxB,YAAY,GAAG,KAAK,EACpB,SAAS,GAAG,KAAK,EACjB,SAAS,EACT,gBAAgB,EAChB,GAAG,KAAK,EACT,KAAI;IACH,MAAM,EAAE,kBAAkB,EAAE,IAAI,EAAE,GAAG,eAAe,CAAC,KAAK,CAAC;IAC3D,MAAM,EACJ,cAAc,EACd,aAAa,EACb,cAAc,EACd,aAAa,EACb,WAAW,EACX,OAAO,EACP,MAAM,EACN,GAAG,KAA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AE,KAAK,CAAC,cAAc,CAAC,EAC3D,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACtC,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,EACnC,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE,KAAK,CAAC,aAAa,CAAC,EACxD,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,WAAW,CAAC,EAClD,GAAG,EAAE,OAAO,aAEX,aAAa,EACb,MAAM,KACLC,GAAA,CAAC,MAAM,EAAA,EAAC,QAAQ,EAAE,CAAC,YAAY,EAAA,QAAA,EAC7BA,GAAA,CAAA,KAAA,EAAA,EACE,GAAG,EAAE,OAAO,EACZ,EAAE,EAAE,MAAM,EACV,SAAS,EAAE,WAAW,EACtB,KAAK,EACH;AACE,0BAAE;AACE,4BAAA,QAAQ,EAAE,OAAO;4BACjB,GAAG,EAAE,QAAQ,CAAC,GAAG;4BACjB,IAAI,EAAE,QAAQ,CAAC,IAAI;AACpB;0BACD,SAAS,EAAA,QAAA,EAGd,QAAQ,GACL,EAAA,CACC,CACV,CAAA,EAAA,CACI;AAEX;;"}
|
|
1
|
+
{"version":3,"file":"HoverCard.js","sources":["../../../src/components/HoverCard.tsx"],"sourcesContent":["import React, {\n cloneElement,\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { classNames, usePrefixedClassNames } from '../helpers/classNames';\nimport { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses';\nimport { PopupPortal } from '../helpers/portal';\nimport { useIsHydrated } from '../helpers/useIsHydrated';\nimport { marginGap, useAnchoredPosition } from '../helpers/useAnchoredPosition';\nimport { chain, useHoverOpen } from '../helpers/useHoverOpen';\nimport { isTabbableKind } from '../helpers/useFocusTrap';\nimport { isDev, warnOnce } from '../helpers/devWarnings';\nimport type { PickerPosition } from '../form/_pickerInternals/pickerTypes';\n\n/**\n * Where the card opens against its trigger: below (`bottom-*`) or above\n * (`top-*`), lined up with the trigger's left or right edge. `auto` picks the\n * one that keeps the card in the viewport, preferring below and lined up on\n * the left. The same union `Popover` and the date and time pickers take.\n */\nexport type HoverCardPosition = PickerPosition;\n\n/**\n * Props for the HoverCard component. `className`, `id`, the other HTML\n * attributes and the helper props land on the `span` around the trigger, not\n * on the card; `contentClassName` reaches the card.\n * @extraProp {string} [className] - Additional classes for the `span` around the trigger. The card takes `contentClassName`.\n */\nexport interface HoverCardProps\n extends\n Omit<React.HTMLAttributes<HTMLSpanElement>, 'color' | 'children'>,\n Omit<BulmaClassesProps, 'color' | 'backgroundColor'> {\n /**\n * The element the card previews, such as a link or a `Button`. The element\n * itself has to take focus, so keyboard users can open the card too: a\n * link inside a `<span>` doesn't do, since focus comes back to the trigger\n * and its ARIA is on it. HoverCard gives it no role and no tab stop, since\n * it can't know what the element is, and a development build warns when\n * it can't take focus: use a link or a button, or give the element\n * `tabIndex={0}`. A disabled button can't take focus either. HoverCard adds\n * `aria-expanded` and `aria-controls`, both naming the card only while it\n * is on the page, so it has to be a single element that passes those to\n * its DOM node. Its own click and keys stay its own, and the card doesn't\n * toggle on them, except Escape while the card is open, which closes the\n * card before the trigger sees it.\n */\n trigger: React.ReactElement;\n /**\n * The card's content: a preview whose links and buttons are fine, but not a\n * form, which belongs in a `Popover`. The card pads itself, so content goes\n * straight in.\n */\n children?: React.ReactNode;\n /**\n * Controlled open state. When set, hover, focus and Escape only report\n * through `onOpenChange`, so an action inside the card can close it. While\n * the card is open, Escape is reported, and when focus is in the card, on\n * its trigger or nowhere, the key stops there even if you keep the card\n * open, so a `Modal` around it doesn't close from the keyboard until the\n * card does.\n */\n open?: boolean;\n /**\n * Initial open state when uncontrolled. A card that starts open stays open\n * until the pointer or focus has been and gone, or Escape closes it.\n * @defaultValue false\n */\n defaultOpen?: boolean;\n /**\n * Called with the state asked for: when `openDelay` or `closeDelay` runs\n * out, and right away on Escape. Fires in both controlled and uncontrolled\n * use. An Escape it reports stops at the card when focus is in the card,\n * on its trigger or nowhere, so nothing around it sees that key. With\n * focus anywhere else, the card still closes and the key goes on to\n * whatever has focus.\n */\n onOpenChange?: (open: boolean) => void;\n /**\n * How long the pointer or keyboard focus waits on the trigger before the\n * card opens, in milliseconds.\n * @defaultValue 600\n */\n openDelay?: number;\n /**\n * How long the card stays after the pointer and focus have left the trigger\n * and the card, in milliseconds. It is the time the pointer has to cross\n * the gap between the trigger and the card: with `0` the card closes as the\n * pointer leaves the trigger, before the pointer can reach it.\n * @defaultValue 300\n */\n closeDelay?: number;\n /**\n * Where the card opens against the trigger.\n * @defaultValue 'bottom-left'\n */\n position?: HoverCardPosition;\n /**\n * Render the card through `Portal`, into the `portalContainer` a\n * `ConfigProvider` sets, else the `Modal`, `Dialog` or `Command.Dialog`\n * it's in, else `document.body`, fixed to the viewport, so an ancestor's\n * `overflow`, `transform` or stacking context can't clip it. A trigger in\n * running text needs it too, since the card's block content can't sit\n * inside a `<p>`. The card then shows from the commit after hydration,\n * never in server markup, and it sits in the Tab order where its container\n * is. At the end of `<body>` or of a dialog, Tab reaches it only after the\n * rest of the page or the dialog, and focus leaving the trigger on the way\n * closes it, so keyboard users can open it, read it and close it with\n * Escape, and whatever it links to has to be reachable from the page as\n * well. Theming variables set on an ancestor of the trigger reach it only\n * when its container is inside that ancestor.\n * @defaultValue false\n */\n appendToBody?: boolean;\n /**\n * Open the card with a tap on a touch screen. Touch has no hover, so\n * without this a phone or tablet never opens the card. With it, a tap on\n * the trigger opens the card at once, and it stays until a second tap on\n * the trigger, a tap outside the trigger and the card, or Escape. The tap\n * still does whatever the trigger does, so turn this on only for a trigger\n * with no tap action of its own, such as a `Button` with no `onClick`: on\n * a link, the first tap would follow the link rather than show the card.\n * Mouse and pen work the same either way.\n * @defaultValue false\n */\n openOnTap?: boolean;\n /** Additional classes for the card (`.hover-card-content`). */\n contentClassName?: string;\n}\n\n/**\n * The `HoverCard` component shows a card previewing what's behind a link or a button while the pointer rests on it or keyboard focus is on it.\n *\n * Nothing moves focus when the card opens, and nothing traps it. In place,\n * the card comes right after the trigger, so Tab goes from the trigger into\n * its links and tabbing past them closes it. The pointer can move onto the\n * card, Escape closes it from anywhere, and by default touch doesn't open it,\n * so tapping the trigger just does what the trigger does. `openOnTap` opens\n * it with a tap, for a trigger with no tap action of its own. For hints with nothing to\n * click use `Tooltip`, and for content opened on purpose, such as a form,\n * use `Popover`.\n *\n * @function\n * @param {HoverCardProps} props - Props for the HoverCard component.\n * @returns {JSX.Element} The trigger in its wrapper, and the card while open.\n *\n * @example\n * <HoverCard trigger={<a href=\"/people/ada\">Ada Lovelace</a>}>\n * <Title as=\"p\" size=\"6\">Ada Lovelace</Title>\n * <SubTitle as=\"p\" size=\"6\">Analytical Engine team</SubTitle>\n * </HoverCard>\n */\nexport const HoverCard: React.FC<HoverCardProps> = ({\n trigger,\n children,\n open: controlledOpen,\n defaultOpen = false,\n onOpenChange,\n openDelay = 600,\n closeDelay = 300,\n position = 'bottom-left',\n appendToBody = false,\n openOnTap = false,\n className,\n contentClassName,\n ...props\n}) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n const {\n onPointerEnter,\n onPointerOver,\n onPointerLeave,\n onPointerDown,\n onPointerUp,\n onFocus,\n onBlur,\n ...attrs\n } = rest;\n const rootRef = useRef<HTMLSpanElement>(null);\n const cardRef = useRef<HTMLDivElement>(null);\n const cardId = `${useId()}-card`;\n\n const isControlled = controlledOpen !== undefined;\n const [internalOpen, setInternalOpen] = useState(defaultOpen);\n const isOpen = controlledOpen ?? internalOpen;\n\n const requestOpen = useCallback(\n (next: boolean) => {\n onOpenChange?.(next);\n if (!isControlled) setInternalOpen(next);\n },\n [isControlled, onOpenChange]\n );\n\n // A portaled card has no server markup, so it only exists from the commit\n // after hydration, and nothing measures it before then.\n const hydrated = useIsHydrated();\n const cardMounted = isOpen && (hydrated || !appendToBody);\n\n const resolved = useAnchoredPosition(rootRef, cardRef, {\n active: cardMounted,\n position,\n fixed: appendToBody,\n // The gap comes from `--bulma-hover-card-offset` in the stylesheet, so\n // the coordinates leave it out and `auto` reads it off the card.\n offset: 0,\n styledGap: marginGap,\n });\n\n // The trigger renders first inside the wrapper. Read when needed rather\n // than held, so a trigger that remounted is still the one found.\n const triggerRef = useMemo(\n () => ({\n get current() {\n const first = (rootRef.current as HTMLSpanElement).firstElementChild;\n return first && first !== cardRef.current\n ? (first as HTMLElement)\n : null;\n },\n }),\n []\n );\n\n const hover = useHoverOpen({\n open: isOpen,\n onOpenChange: requestOpen,\n openDelay,\n closeDelay,\n triggerRef,\n floatingRef: cardRef,\n openOnTap,\n });\n\n // A trigger that can't take focus leaves keyboard users no way to open the\n // card. It has to be the trigger element itself, not something inside it,\n // since focus comes back to it and its ARIA is on it. Judged by what the\n // element is rather than by its styles, which can hide it for now. After\n // every commit, since the trigger can change, and only in development.\n useEffect(() => {\n if (!isDev()) return;\n const triggerNode = triggerRef.current;\n if (!triggerNode) return;\n if (!triggerNode.matches(':disabled') && isTabbableKind(triggerNode)) {\n return;\n }\n warnOnce(\n 'HoverCard:unfocusable-trigger',\n \"[bestax-bulma] <HoverCard> has a trigger that can't take focus, so \" +\n \"keyboard users can't open the card. Use a link or a button as the \" +\n 'trigger, or give it tabIndex={0}.'\n );\n });\n\n // Expanded only while the card is on the page, so a portaled card that\n // waits for hydration isn't announced before it exists.\n const clonedTrigger = cloneElement(\n trigger as React.ReactElement<Record<string, unknown>>,\n {\n 'aria-expanded': cardMounted,\n 'aria-controls': cardMounted ? cardId : undefined,\n }\n );\n\n const rootClasses = classNames(\n usePrefixedClassNames('hover-card', { 'is-active': cardMounted }),\n bulmaHelperClasses,\n className\n );\n const cardClasses = classNames(\n usePrefixedClassNames('hover-card-content', {\n [`is-${resolved.position}`]: true,\n 'is-portal': appendToBody,\n }),\n contentClassName\n );\n\n return (\n // The ref after the spread: React 19 hands a function component a `ref`\n // prop like any other, and the wrapper has to stay ours. The card is in\n // the wrapper's React tree even when portaled, so the hover and focus\n // handlers here hear from both.\n <span\n className={rootClasses}\n {...attrs}\n onPointerEnter={chain(onPointerEnter, hover.onPointerEnter)}\n onPointerOver={chain(onPointerOver, hover.onPointerOver)}\n onPointerLeave={chain(onPointerLeave, hover.onPointerLeave)}\n onFocus={chain(onFocus, hover.onFocus)}\n onBlur={chain(onBlur, hover.onBlur)}\n onPointerDown={chain(onPointerDown, hover.onPointerDown)}\n onPointerUp={chain(onPointerUp, hover.onPointerUp)}\n ref={rootRef}\n >\n {clonedTrigger}\n {isOpen && (\n <PopupPortal disabled={!appendToBody}>\n <div\n ref={cardRef}\n id={cardId}\n className={cardClasses}\n style={\n appendToBody\n ? {\n position: 'fixed',\n top: resolved.top,\n left: resolved.left,\n }\n : undefined\n }\n >\n {children}\n </div>\n </PopupPortal>\n )}\n </span>\n );\n};\n\nexport default HoverCard;\n"],"names":["_jsxs","_jsx"],"mappings":";;;;;;;;;;;;;AAsIA;;;;;;;;;;;;;;;;;;;;;AAqBG;MACU,SAAS,GAA6B,CAAC,EAClD,OAAO,EACP,QAAQ,EACR,IAAI,EAAE,cAAc,EACpB,WAAW,GAAG,KAAK,EACnB,YAAY,EACZ,SAAS,GAAG,GAAG,EACf,UAAU,GAAG,GAAG,EAChB,QAAQ,GAAG,aAAa,EACxB,YAAY,GAAG,KAAK,EACpB,SAAS,GAAG,KAAK,EACjB,SAAS,EACT,gBAAgB,EAChB,GAAG,KAAK,EACT,KAAI;IACH,MAAM,EAAE,kBAAkB,EAAE,IAAI,EAAE,GAAG,eAAe,CAAC,KAAK,CAAC;IAC3D,MAAM,EACJ,cAAc,EACd,aAAa,EACb,cAAc,EACd,aAAa,EACb,WAAW,EACX,OAAO,EACP,MAAM,EACN,GAAG,KAAK,EACT,GAAG,IAAI;AACR,IAAA,MAAM,OAAO,GAAG,MAAM,CAAkB,IAAI,CAAC;AAC7C,IAAA,MAAM,OAAO,GAAG,MAAM,CAAiB,IAAI,CAAC;AAC5C,IAAA,MAAM,MAAM,GAAG,CAAA,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aAAa,EAAE,KAAK,CAAC,aAAa,EAAE,KAAK,CAAC,aAAa,CAAC,EACxD,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,WAAW,CAAC,EAClD,GAAG,EAAE,OAAO,aAEX,aAAa,EACb,MAAM,KACLC,GAAA,CAAC,WAAW,EAAA,EAAC,QAAQ,EAAE,CAAC,YAAY,EAAA,QAAA,EAClCA,GAAA,CAAA,KAAA,EAAA,EACE,GAAG,EAAE,OAAO,EACZ,EAAE,EAAE,MAAM,EACV,SAAS,EAAE,WAAW,EACtB,KAAK,EACH;AACE,0BAAE;AACE,4BAAA,QAAQ,EAAE,OAAO;4BACjB,GAAG,EAAE,QAAQ,CAAC,GAAG;4BACjB,IAAI,EAAE,QAAQ,CAAC,IAAI;AACpB;0BACD,SAAS,EAAA,QAAA,EAGd,QAAQ,GACL,EAAA,CACM,CACf,CAAA,EAAA,CACI;AAEX;;"}
|
|
@@ -5,6 +5,7 @@ import React, { createContext, forwardRef, useContext, useId, useRef, useState }
|
|
|
5
5
|
import { classNames, usePrefixedClassNames } from '../helpers/classNames.js';
|
|
6
6
|
import { useBulmaClasses } from '../helpers/useBulmaClasses.js';
|
|
7
7
|
import { withSubComponents } from '../helpers/withSubComponents.js';
|
|
8
|
+
import { isElementOf } from '../helpers/elementType.js';
|
|
8
9
|
import { omitAttrs } from '../helpers/anchorAttrs.js';
|
|
9
10
|
import { buttonType } from '../helpers/buttonType.js';
|
|
10
11
|
import { inertProps } from '../helpers/inertProps.js';
|
|
@@ -109,7 +110,7 @@ const MenuItem = forwardRef(function MenuItem(itemProps, ref) {
|
|
|
109
110
|
const labelChildren = [];
|
|
110
111
|
const nestedMenuLists = [];
|
|
111
112
|
React.Children.forEach(children, child => {
|
|
112
|
-
if (
|
|
113
|
+
if (isElementOf(child, MenuList)) {
|
|
113
114
|
nestedMenuLists.push(child);
|
|
114
115
|
}
|
|
115
116
|
else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Menu.js","sources":["../../../src/components/Menu.tsx"],"sourcesContent":["import React, {\n createContext,\n forwardRef,\n useContext,\n useId,\n useRef,\n useState,\n} from 'react';\nimport { classNames, usePrefixedClassNames } from '../helpers/classNames';\nimport { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses';\nimport { withSubComponents } from '../helpers/withSubComponents';\nimport { omitAttrs } from '../helpers/anchorAttrs';\nimport { buttonType } from '../helpers/buttonType';\nimport { inertProps } from '../helpers/inertProps';\nimport { getActiveElementInTree } from '../helpers/shadowDom';\nimport { useClientLayoutEffect } from '../helpers/useClientLayoutEffect';\nimport {\n isCustomElement,\n type PolymorphicComponent,\n} from '../helpers/polymorphic';\n\n// Context to track MenuList nesting level\nconst MenuListLevelContext = createContext(0);\n\n/**\n * Props for the Menu component.\n */\nexport interface MenuProps\n extends\n Omit<React.HTMLAttributes<HTMLElement>, keyof BulmaClassesProps>,\n BulmaClassesProps {\n /** Additional CSS classes. */\n className?: string;\n /** Menu content (labels, lists, items, etc). */\n children: React.ReactNode;\n}\n\n/**\n * The `Menu` component provides Bulma's vertical navigation menu: a simple, accessible sidebar or section menu for your Bulma React UI.\n *\n * @function\n * @param {MenuProps} props - Props for the Menu component.\n * @returns {JSX.Element} The rendered menu.\n * @see {@link https://bulma.io/documentation/components/menu/ | Bulma Menu documentation}\n */\nconst MenuComponent: React.FC<MenuProps> = ({\n className,\n children,\n ...props\n}) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n\n // Generate Bulma classes with prefix\n const bulmaClasses = usePrefixedClassNames('menu');\n\n return (\n <aside\n className={classNames(bulmaClasses, bulmaHelperClasses, className)}\n {...rest}\n >\n {children}\n </aside>\n );\n};\n\n/**\n * Props for the MenuLabel component.\n */\nexport interface MenuLabelProps\n extends\n Omit<React.HTMLAttributes<HTMLParagraphElement>, keyof BulmaClassesProps>,\n BulmaClassesProps {\n /** Additional CSS classes. */\n className?: string;\n /** Label content. */\n children: React.ReactNode;\n}\n\n/**\n * Bulma Menu label component.\n *\n * @function\n * @param {MenuLabelProps} props - Props for the MenuLabel component.\n * @returns {JSX.Element} The rendered menu label.\n */\nexport const MenuLabel: React.FC<MenuLabelProps> = ({\n className,\n children,\n ...props\n}) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n\n return (\n <p\n className={classNames(\n usePrefixedClassNames('menu-label'),\n className,\n bulmaHelperClasses\n )}\n {...rest}\n >\n {children}\n </p>\n );\n};\n\n/**\n * Props for the MenuList component.\n * @extraProp {React.AriaRole} [role] - Ignored: every level renders `role=\"list\"` in its place, so a menu or tree role can't go here.\n */\nexport interface MenuListProps\n extends\n Omit<React.HTMLAttributes<HTMLUListElement>, keyof BulmaClassesProps>,\n BulmaClassesProps {\n /** Additional CSS classes. */\n className?: string;\n /** List items. */\n children: React.ReactNode;\n}\n\n/**\n * MenuList applies `menu-list` class only at the top level (not for nested lists).\n *\n * Every level renders `role=\"list\"`, which Safari needs: WebKit stops\n * exposing a `<ul>` as a list once its markers are hidden, and Bulma's reset\n * hides them.\n *\n * @function\n * @param {MenuListProps} props - Props for the MenuList component.\n * @returns {JSX.Element} The rendered menu list.\n */\nexport const MenuList: React.FC<MenuListProps> = ({\n className,\n children,\n ...props\n}) => {\n const level = useContext(MenuListLevelContext);\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n\n const ulClass = classNames(className, bulmaHelperClasses, {\n [usePrefixedClassNames('menu-list')]: level === 0,\n });\n\n // Increment level for nested MenuLists. role=\"list\" restates the <ul>'s\n // own role, for Safari: WebKit stops exposing a list as one once its\n // markers are hidden, as Bulma's reset hides them, unless the role is set\n // explicitly. After the spread, so a caller's role can't take it away.\n return (\n <MenuListLevelContext.Provider value={level + 1}>\n <ul className={ulClass || undefined} {...rest} role=\"list\">\n {children}\n </ul>\n </MenuListLevelContext.Provider>\n );\n};\n\n/**\n * The MenuItem component's own props.\n *\n * A menu item is two elements: a wrapping `<li>` and, inside it, the element\n * `as` names. The props here are the ones the `<li>` consumes; everything else\n * follows `as` onto the inner element.\n */\nexport interface MenuItemOwnProps extends BulmaClassesProps {\n /** Additional CSS classes for the wrapping `<li>`. */\n className?: string;\n /** Item content and optional nested MenuList. */\n children: React.ReactNode;\n /**\n * Marks the item as the current one. It adds Bulma's `is-active` class, and\n * `aria-current=\"page\"` on the element `as` renders, so assistive tech can\n * tell which item is current too. An `aria-current` you pass wins, even\n * `undefined`: use it to say something else (`\"location\"` for a section of\n * one page, say), or `aria-current={false}` to turn it off. A menu should\n * mark one page, so when the section above the current page is `active` too,\n * give it `aria-current=\"location\"`, and give an `active` item that isn't\n * navigation, such as an `as=\"button\"` filter, `aria-current={false}`.\n */\n active?: boolean;\n /** Inline styles for the wrapping `<li>`. */\n style?: React.CSSProperties;\n /** `id` for the wrapping `<li>`. */\n id?: string;\n /** `title` for the wrapping `<li>`. */\n title?: string;\n /** ARIA role for the wrapping `<li>`. */\n role?: React.AriaRole;\n /** Tab index for the wrapping `<li>`. */\n tabIndex?: number;\n /** Test id for the wrapping `<li>`. */\n 'data-testid'?: string;\n}\n\n/**\n * Props for the MenuItem component. Everything the `<li>` does not consume\n * follows `as` onto the inner element: with the default `'a'` that means `href`\n * and the other anchor attributes, and with `as={Link}` it means that\n * component's own props.\n *\n * @extraProp {PolymorphicRef<React.ElementType>} [ref] - Ref forwarded to the inner element `as` renders, not the wrapping `<li>`, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes.\n */\nexport type MenuItemProps<T extends React.ElementType = 'a'> =\n MenuItemOwnProps &\n Omit<React.ComponentPropsWithoutRef<T>, keyof MenuItemOwnProps | 'as'> & {\n /**\n * Custom link component (e.g. `Link` from router).\n *\n * `'button'` renders `type=\"button\"` unless you pass `type=\"submit\"` or `type=\"reset\"`, so\n * an item inside a form does not submit it.\n */\n as?: T;\n };\n\n/**\n * `href` alone — annotated so a typo is a compile error rather than a silent\n * no-op, the way both siblings' sets are.\n */\nconst STRIP_FROM_NON_LINK: Readonly<Record<'href', true>> = { href: true };\n\n/**\n * The shape the implementation destructures. The public contract is the generic\n * `MenuItemProps<T>` above — the body cannot see through `T`.\n */\ntype MenuItemImplProps = MenuItemOwnProps & {\n as?: React.ElementType;\n type?: React.ButtonHTMLAttributes<HTMLButtonElement>['type'];\n};\n\n/**\n * MenuItem supports `as` prop for custom link components, e.g., react-router-dom Link.\n *\n * Give each item an `href`, a router link through `as`, or `as=\"button\"`, so\n * the keyboard can reach it: an `<a>` with no `href` isn't a link, and Tab\n * skips it.\n *\n * @function\n * @param {MenuItemProps} props - Props for the MenuItem component.\n * @param {React.Ref} ref - Forwarded ref to the inner element `as` renders.\n * @returns {JSX.Element} The rendered menu item.\n */\nexport const MenuItem = forwardRef(function MenuItem(\n itemProps: MenuItemProps,\n ref: React.Ref<HTMLElement>\n) {\n const {\n className,\n children,\n active,\n as: Component = 'a',\n 'data-testid': testId,\n style,\n id,\n title,\n role,\n tabIndex,\n ...rest\n } = itemProps as MenuItemImplProps;\n const { bulmaHelperClasses, rest: forwarded } = useBulmaClasses(rest);\n // `href` reaches an anchor or a custom component (which owns its own prop\n // contract), but not another intrinsic tag — `<span href>` is invalid HTML.\n // The same rule Avatar applies through `isLinkLike` and Button through its\n // intrinsic-only strip. Before #641 `href` was an own prop re-applied only\n // for `as=\"a\"`; deriving it from `as` must not quietly widen that.\n const isLinkLike =\n Component === 'a' ||\n typeof Component !== 'string' ||\n isCustomElement(Component);\n // `href` ALONE. `Dropdown.Item` strips every anchor-only attribute except\n // `type`; `Level.Item` strips all of them, plus `rel`.\n //\n // Not because nothing else can arrive: `as` here is an open `React.ElementType`,\n // and a non-fresh spread skips excess-property checking, so a typed caller\n // CAN deliver `target` or `download` and they are forwarded. The set stays at\n // `href` because widening it would be wrong for an open `as` — `referrerPolicy`\n // on `as=\"img\"`, `target` on `as=\"form\"` and `media` on `as=\"source\"` are all\n // legal, and a flat strip would delete them. Getting that right needs a\n // per-attribute-per-element rule, which `bestax-migrate` already models in\n // `LINK_ATTR_ELEMENTS`.\n const linkProps = isLinkLike\n ? forwarded\n : omitAttrs(forwarded, STRIP_FROM_NON_LINK);\n const itemClass = classNames(\n { [usePrefixedClassNames('is-active')]: active },\n bulmaHelperClasses\n );\n\n // Split children into label and nested MenuList(s)\n const labelChildren: React.ReactNode[] = [];\n const nestedMenuLists: React.ReactNode[] = [];\n React.Children.forEach(children, child => {\n if (React.isValidElement(child) && child.type === MenuList) {\n nestedMenuLists.push(child);\n } else {\n labelChildren.push(child);\n }\n });\n\n return (\n <li\n className={className}\n data-testid={testId}\n style={style}\n id={id}\n title={title}\n role={role}\n tabIndex={tabIndex}\n >\n <Component\n ref={ref}\n className={itemClass || undefined}\n // The active item is the current page, the way Pagination marks its\n // page. Before the spread, so an `aria-current` the caller passes\n // decides, `false` and `undefined` included. bestax-migrate converts\n // `is-active` to `active` only beside an `aria-current` of the\n // element's own, and relies on that to render the same markup.\n aria-current={active ? 'page' : undefined}\n {...linkProps}\n // A menu item inside a form must not submit it, and `<button>` defaults\n // to type=\"submit\". A sidebar menu sitting in a form is ordinary. A\n // caller's `submit` or `reset` still wins. Anything else becomes\n // `button`, since HTML reads a value it does not define for a button as\n // submit too; `buttonType` says more.\n //\n // After `linkProps`, reading through it rather than before it: React\n // treats `type={undefined}` as \"remove the attribute\", and a spread\n // carrying the key with no value is how that arrives, so a default\n // spread first would be erased by it. `Dropdown.Item` and `Avatar`\n // apply their button type after the spread too.\n {...(Component === 'button'\n ? { type: buttonType(linkProps.type) }\n : {})}\n >\n {labelChildren}\n </Component>\n {nestedMenuLists}\n </li>\n );\n}) as PolymorphicComponent<MenuItemOwnProps, 'a'>;\n\nMenuItem.displayName = 'MenuItem';\n\n/**\n * Props for the MenuSection component. The helper props and the other\n * attributes land on the wrapping `<div>`.\n */\nexport interface MenuSectionProps\n extends\n Omit<React.HTMLAttributes<HTMLDivElement>, keyof BulmaClassesProps>,\n BulmaClassesProps {\n /** Additional CSS classes for the wrapping `<div>`. */\n className?: string;\n /** **Required.** The section's heading, drawn like `Menu.Label` inside the button that opens and closes it. Keep links and buttons out of it, since it's inside one. */\n label: React.ReactNode;\n /**\n * The `Menu.List` of links the section shows while it's open. The section\n * itself goes directly in `Menu`, beside its labels and lists: inside a\n * `Menu.Item` it would render inside the item's link, and inside a\n * `Menu.List` it wouldn't be a list item.\n */\n children: React.ReactNode;\n /** Controlled open state. If provided, the section is controlled, and its button only reports through `onOpenChange`. */\n open?: boolean;\n /** Initial open state for uncontrolled usage. Open the section that holds the current page, so the reader sees where they are. */\n defaultOpen?: boolean;\n /** Called with the state the button asks for (`true` to open) each time it is clicked or activated with Enter or Space, in every mode. Pair it with `open` to let the button drive a controlled section. */\n onOpenChange?: (open: boolean) => void;\n}\n\n/**\n * A section of the menu that opens and closes: its heading is a button drawn like `Menu.Label`, and its `Menu.List` of links shows while it's open.\n *\n * It's APG's disclosure navigation, for a sidebar of link groups: the links\n * stay ordinary links, each its own tab stop, and a closed section's list is\n * `hidden` and `inert`, so Tab and assistive tech skip it. It goes directly in\n * `Menu`, holding a `Menu.List`. Closing it while focus is on one of its links\n * moves focus to its heading.\n *\n * @function\n * @param {MenuSectionProps} props - Props for the MenuSection component.\n * @returns {JSX.Element} The rendered menu section.\n * @see {@link https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/examples/disclosure-navigation/ | APG Disclosure Navigation Menu example}\n *\n * @example\n * <Menu>\n * <Menu.Section label=\"Components\" defaultOpen>\n * <Menu.List>\n * <Menu.Item href=\"/button\" active>Button</Menu.Item>\n * <Menu.Item href=\"/card\">Card</Menu.Item>\n * </Menu.List>\n * </Menu.Section>\n * </Menu>\n */\nexport const MenuSection: React.FC<MenuSectionProps> = ({\n className,\n label,\n children,\n open: controlledOpen,\n defaultOpen = false,\n onOpenChange,\n ...props\n}) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n const sectionClass = usePrefixedClassNames('menu-section');\n const toggleClass = usePrefixedClassNames('menu-section-toggle');\n const labelClass = usePrefixedClassNames('menu-section-label');\n const chevronClass = usePrefixedClassNames('menu-section-chevron');\n const listId = useId();\n const toggleRef = useRef<HTMLButtonElement>(null);\n const listRef = useRef<HTMLDivElement>(null);\n\n // The caller owns the state when `open` is set, and the section does\n // otherwise, as with Collapse. The button reports in both modes.\n const isControlled = controlledOpen !== undefined;\n const [internalOpen, setInternalOpen] = useState(defaultOpen);\n const isOpen = controlledOpen ?? internalOpen;\n\n const handleClick = () => {\n const next = !isOpen;\n onOpenChange?.(next);\n if (!isControlled) setInternalOpen(next);\n };\n\n // An app holding `open` can close a section while focus is on one of its\n // links, as a sidebar that keeps only the current route's section open\n // does after a link is followed. The browser then drops focus to <body>\n // a frame later, and the next Tab starts from the top of the page. The\n // heading is where the reader was, so focus goes there. A layout effect,\n // because it runs in the same task as the commit that hid the list, while\n // the link still has focus. A close from the button itself finds focus on\n // the button and leaves it.\n useClientLayoutEffect(() => {\n if (isOpen) return;\n const list = listRef.current!;\n if (list.contains(getActiveElementInTree(list))) {\n toggleRef.current!.focus();\n }\n }, [isOpen]);\n\n // A real button, so Enter and Space work with no key handler, and\n // `type=\"button\"`, so a menu inside a form isn't submitted by it.\n //\n // A closed list is `hidden`, so it isn't drawn and find-in-page doesn't\n // reach it, and `inert`, so its links stay out of Tab and assistive tech\n // even if a stylesheet sets `display` on it and shows it anyway. The markup\n // is the same from the server and on both React majors, which `inertProps`\n // sees to. It stays mounted, so `aria-controls` always names an element\n // that exists.\n return (\n <div\n className={classNames(sectionClass, bulmaHelperClasses, className)}\n {...rest}\n >\n <button\n ref={toggleRef}\n type=\"button\"\n className={toggleClass}\n aria-expanded={isOpen}\n aria-controls={listId}\n onClick={handleClick}\n >\n <span className={labelClass}>{label}</span>\n <span className={chevronClass} aria-hidden=\"true\" />\n </button>\n <div ref={listRef} id={listId} hidden={!isOpen} {...inertProps(!isOpen)}>\n {children}\n </div>\n </div>\n );\n};\n\n// Attach static subcomponents\nexport const Menu = withSubComponents(\n MenuComponent,\n {\n Label: MenuLabel,\n List: MenuList,\n Item: MenuItem,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,WAAW,aAEpBD,GAAA,CAAA,MAAA,EAAA,EAAM,SAAS,EAAE,UAAU,YAAG,KAAK,EAAA,CAAQ,EAC3CA,GAAA,CAAA,MAAA,EAAA,EAAM,SAAS,EAAE,YAAY,EAAA,aAAA,EAAc,MAAM,GAAG,CAAA,EAAA,CAC7C,EACTA,GAAA,CAAA,KAAA,EAAA,EAAK,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,MAAM,EAAA,GAAM,UAAU,CAAC,CAAC,MAAM,CAAC,EAAA,QAAA,EACpE,QAAQ,EAAA,CACL,CAAA,EAAA,CACF;AAEV;AAEA;AACO,MAAM,IAAI,GAAG,iBAAiB,CACnC,aAAa,EACb;AACE,IAAA,KAAK,EAAE,SAAS;AAChB,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,OAAO,EAAE,WAAW;CACrB,EACD,MAAM;;"}
|
|
1
|
+
{"version":3,"file":"Menu.js","sources":["../../../src/components/Menu.tsx"],"sourcesContent":["import React, {\n createContext,\n forwardRef,\n useContext,\n useId,\n useRef,\n useState,\n} from 'react';\nimport { classNames, usePrefixedClassNames } from '../helpers/classNames';\nimport { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses';\nimport { withSubComponents } from '../helpers/withSubComponents';\nimport { isElementOf } from '../helpers/elementType';\nimport { omitAttrs } from '../helpers/anchorAttrs';\nimport { buttonType } from '../helpers/buttonType';\nimport { inertProps } from '../helpers/inertProps';\nimport { getActiveElementInTree } from '../helpers/shadowDom';\nimport { useClientLayoutEffect } from '../helpers/useClientLayoutEffect';\nimport {\n isCustomElement,\n type PolymorphicComponent,\n} from '../helpers/polymorphic';\n\n// Context to track MenuList nesting level\nconst MenuListLevelContext = createContext(0);\n\n/**\n * Props for the Menu component.\n */\nexport interface MenuProps\n extends\n Omit<React.HTMLAttributes<HTMLElement>, keyof BulmaClassesProps>,\n BulmaClassesProps {\n /** Additional CSS classes. */\n className?: string;\n /** Menu content (labels, lists, items, etc). */\n children: React.ReactNode;\n}\n\n/**\n * The `Menu` component provides Bulma's vertical navigation menu: a simple, accessible sidebar or section menu for your Bulma React UI.\n *\n * @function\n * @param {MenuProps} props - Props for the Menu component.\n * @returns {JSX.Element} The rendered menu.\n * @see {@link https://bulma.io/documentation/components/menu/ | Bulma Menu documentation}\n */\nconst MenuComponent: React.FC<MenuProps> = ({\n className,\n children,\n ...props\n}) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n\n // Generate Bulma classes with prefix\n const bulmaClasses = usePrefixedClassNames('menu');\n\n return (\n <aside\n className={classNames(bulmaClasses, bulmaHelperClasses, className)}\n {...rest}\n >\n {children}\n </aside>\n );\n};\n\n/**\n * Props for the MenuLabel component.\n */\nexport interface MenuLabelProps\n extends\n Omit<React.HTMLAttributes<HTMLParagraphElement>, keyof BulmaClassesProps>,\n BulmaClassesProps {\n /** Additional CSS classes. */\n className?: string;\n /** Label content. */\n children: React.ReactNode;\n}\n\n/**\n * Bulma Menu label component.\n *\n * @function\n * @param {MenuLabelProps} props - Props for the MenuLabel component.\n * @returns {JSX.Element} The rendered menu label.\n */\nexport const MenuLabel: React.FC<MenuLabelProps> = ({\n className,\n children,\n ...props\n}) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n\n return (\n <p\n className={classNames(\n usePrefixedClassNames('menu-label'),\n className,\n bulmaHelperClasses\n )}\n {...rest}\n >\n {children}\n </p>\n );\n};\n\n/**\n * Props for the MenuList component.\n * @extraProp {React.AriaRole} [role] - Ignored: every level renders `role=\"list\"` in its place, so a menu or tree role can't go here.\n */\nexport interface MenuListProps\n extends\n Omit<React.HTMLAttributes<HTMLUListElement>, keyof BulmaClassesProps>,\n BulmaClassesProps {\n /** Additional CSS classes. */\n className?: string;\n /** List items. */\n children: React.ReactNode;\n}\n\n/**\n * MenuList applies `menu-list` class only at the top level (not for nested lists).\n *\n * Every level renders `role=\"list\"`, which Safari needs: WebKit stops\n * exposing a `<ul>` as a list once its markers are hidden, and Bulma's reset\n * hides them.\n *\n * @function\n * @param {MenuListProps} props - Props for the MenuList component.\n * @returns {JSX.Element} The rendered menu list.\n */\nexport const MenuList: React.FC<MenuListProps> = ({\n className,\n children,\n ...props\n}) => {\n const level = useContext(MenuListLevelContext);\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n\n const ulClass = classNames(className, bulmaHelperClasses, {\n [usePrefixedClassNames('menu-list')]: level === 0,\n });\n\n // Increment level for nested MenuLists. role=\"list\" restates the <ul>'s\n // own role, for Safari: WebKit stops exposing a list as one once its\n // markers are hidden, as Bulma's reset hides them, unless the role is set\n // explicitly. After the spread, so a caller's role can't take it away.\n return (\n <MenuListLevelContext.Provider value={level + 1}>\n <ul className={ulClass || undefined} {...rest} role=\"list\">\n {children}\n </ul>\n </MenuListLevelContext.Provider>\n );\n};\n\n/**\n * The MenuItem component's own props.\n *\n * A menu item is two elements: a wrapping `<li>` and, inside it, the element\n * `as` names. The props here are the ones the `<li>` consumes; everything else\n * follows `as` onto the inner element.\n */\nexport interface MenuItemOwnProps extends BulmaClassesProps {\n /** Additional CSS classes for the wrapping `<li>`. */\n className?: string;\n /** Item content and optional nested MenuList. */\n children: React.ReactNode;\n /**\n * Marks the item as the current one. It adds Bulma's `is-active` class, and\n * `aria-current=\"page\"` on the element `as` renders, so assistive tech can\n * tell which item is current too. An `aria-current` you pass wins, even\n * `undefined`: use it to say something else (`\"location\"` for a section of\n * one page, say), or `aria-current={false}` to turn it off. A menu should\n * mark one page, so when the section above the current page is `active` too,\n * give it `aria-current=\"location\"`, and give an `active` item that isn't\n * navigation, such as an `as=\"button\"` filter, `aria-current={false}`.\n */\n active?: boolean;\n /** Inline styles for the wrapping `<li>`. */\n style?: React.CSSProperties;\n /** `id` for the wrapping `<li>`. */\n id?: string;\n /** `title` for the wrapping `<li>`. */\n title?: string;\n /** ARIA role for the wrapping `<li>`. */\n role?: React.AriaRole;\n /** Tab index for the wrapping `<li>`. */\n tabIndex?: number;\n /** Test id for the wrapping `<li>`. */\n 'data-testid'?: string;\n}\n\n/**\n * Props for the MenuItem component. Everything the `<li>` does not consume\n * follows `as` onto the inner element: with the default `'a'` that means `href`\n * and the other anchor attributes, and with `as={Link}` it means that\n * component's own props.\n *\n * @extraProp {PolymorphicRef<React.ElementType>} [ref] - Ref forwarded to the inner element `as` renders, not the wrapping `<li>`, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes.\n */\nexport type MenuItemProps<T extends React.ElementType = 'a'> =\n MenuItemOwnProps &\n Omit<React.ComponentPropsWithoutRef<T>, keyof MenuItemOwnProps | 'as'> & {\n /**\n * Custom link component (e.g. `Link` from router).\n *\n * `'button'` renders `type=\"button\"` unless you pass `type=\"submit\"` or `type=\"reset\"`, so\n * an item inside a form does not submit it.\n */\n as?: T;\n };\n\n/**\n * `href` alone — annotated so a typo is a compile error rather than a silent\n * no-op, the way both siblings' sets are.\n */\nconst STRIP_FROM_NON_LINK: Readonly<Record<'href', true>> = { href: true };\n\n/**\n * The shape the implementation destructures. The public contract is the generic\n * `MenuItemProps<T>` above — the body cannot see through `T`.\n */\ntype MenuItemImplProps = MenuItemOwnProps & {\n as?: React.ElementType;\n type?: React.ButtonHTMLAttributes<HTMLButtonElement>['type'];\n};\n\n/**\n * MenuItem supports `as` prop for custom link components, e.g., react-router-dom Link.\n *\n * Give each item an `href`, a router link through `as`, or `as=\"button\"`, so\n * the keyboard can reach it: an `<a>` with no `href` isn't a link, and Tab\n * skips it.\n *\n * @function\n * @param {MenuItemProps} props - Props for the MenuItem component.\n * @param {React.Ref} ref - Forwarded ref to the inner element `as` renders.\n * @returns {JSX.Element} The rendered menu item.\n */\nexport const MenuItem = forwardRef(function MenuItem(\n itemProps: MenuItemProps,\n ref: React.Ref<HTMLElement>\n) {\n const {\n className,\n children,\n active,\n as: Component = 'a',\n 'data-testid': testId,\n style,\n id,\n title,\n role,\n tabIndex,\n ...rest\n } = itemProps as MenuItemImplProps;\n const { bulmaHelperClasses, rest: forwarded } = useBulmaClasses(rest);\n // `href` reaches an anchor or a custom component (which owns its own prop\n // contract), but not another intrinsic tag — `<span href>` is invalid HTML.\n // The same rule Avatar applies through `isLinkLike` and Button through its\n // intrinsic-only strip. Before #641 `href` was an own prop re-applied only\n // for `as=\"a\"`; deriving it from `as` must not quietly widen that.\n const isLinkLike =\n Component === 'a' ||\n typeof Component !== 'string' ||\n isCustomElement(Component);\n // `href` ALONE. `Dropdown.Item` strips every anchor-only attribute except\n // `type`; `Level.Item` strips all of them, plus `rel`.\n //\n // Not because nothing else can arrive: `as` here is an open `React.ElementType`,\n // and a non-fresh spread skips excess-property checking, so a typed caller\n // CAN deliver `target` or `download` and they are forwarded. The set stays at\n // `href` because widening it would be wrong for an open `as` — `referrerPolicy`\n // on `as=\"img\"`, `target` on `as=\"form\"` and `media` on `as=\"source\"` are all\n // legal, and a flat strip would delete them. Getting that right needs a\n // per-attribute-per-element rule, which `bestax-migrate` already models in\n // `LINK_ATTR_ELEMENTS`.\n const linkProps = isLinkLike\n ? forwarded\n : omitAttrs(forwarded, STRIP_FROM_NON_LINK);\n const itemClass = classNames(\n { [usePrefixedClassNames('is-active')]: active },\n bulmaHelperClasses\n );\n\n // Split children into label and nested MenuList(s)\n const labelChildren: React.ReactNode[] = [];\n const nestedMenuLists: React.ReactNode[] = [];\n React.Children.forEach(children, child => {\n if (isElementOf(child, MenuList)) {\n nestedMenuLists.push(child);\n } else {\n labelChildren.push(child);\n }\n });\n\n return (\n <li\n className={className}\n data-testid={testId}\n style={style}\n id={id}\n title={title}\n role={role}\n tabIndex={tabIndex}\n >\n <Component\n ref={ref}\n className={itemClass || undefined}\n // The active item is the current page, the way Pagination marks its\n // page. Before the spread, so an `aria-current` the caller passes\n // decides, `false` and `undefined` included. bestax-migrate converts\n // `is-active` to `active` only beside an `aria-current` of the\n // element's own, and relies on that to render the same markup.\n aria-current={active ? 'page' : undefined}\n {...linkProps}\n // A menu item inside a form must not submit it, and `<button>` defaults\n // to type=\"submit\". A sidebar menu sitting in a form is ordinary. A\n // caller's `submit` or `reset` still wins. Anything else becomes\n // `button`, since HTML reads a value it does not define for a button as\n // submit too; `buttonType` says more.\n //\n // After `linkProps`, reading through it rather than before it: React\n // treats `type={undefined}` as \"remove the attribute\", and a spread\n // carrying the key with no value is how that arrives, so a default\n // spread first would be erased by it. `Dropdown.Item` and `Avatar`\n // apply their button type after the spread too.\n {...(Component === 'button'\n ? { type: buttonType(linkProps.type) }\n : {})}\n >\n {labelChildren}\n </Component>\n {nestedMenuLists}\n </li>\n );\n}) as PolymorphicComponent<MenuItemOwnProps, 'a'>;\n\nMenuItem.displayName = 'MenuItem';\n\n/**\n * Props for the MenuSection component. The helper props and the other\n * attributes land on the wrapping `<div>`.\n */\nexport interface MenuSectionProps\n extends\n Omit<React.HTMLAttributes<HTMLDivElement>, keyof BulmaClassesProps>,\n BulmaClassesProps {\n /** Additional CSS classes for the wrapping `<div>`. */\n className?: string;\n /** **Required.** The section's heading, drawn like `Menu.Label` inside the button that opens and closes it. Keep links and buttons out of it, since it's inside one. */\n label: React.ReactNode;\n /**\n * The `Menu.List` of links the section shows while it's open. The section\n * itself goes directly in `Menu`, beside its labels and lists: inside a\n * `Menu.Item` it would render inside the item's link, and inside a\n * `Menu.List` it wouldn't be a list item.\n */\n children: React.ReactNode;\n /** Controlled open state. If provided, the section is controlled, and its button only reports through `onOpenChange`. */\n open?: boolean;\n /** Initial open state for uncontrolled usage. Open the section that holds the current page, so the reader sees where they are. */\n defaultOpen?: boolean;\n /** Called with the state the button asks for (`true` to open) each time it is clicked or activated with Enter or Space, in every mode. Pair it with `open` to let the button drive a controlled section. */\n onOpenChange?: (open: boolean) => void;\n}\n\n/**\n * A section of the menu that opens and closes: its heading is a button drawn like `Menu.Label`, and its `Menu.List` of links shows while it's open.\n *\n * It's APG's disclosure navigation, for a sidebar of link groups: the links\n * stay ordinary links, each its own tab stop, and a closed section's list is\n * `hidden` and `inert`, so Tab and assistive tech skip it. It goes directly in\n * `Menu`, holding a `Menu.List`. Closing it while focus is on one of its links\n * moves focus to its heading.\n *\n * @function\n * @param {MenuSectionProps} props - Props for the MenuSection component.\n * @returns {JSX.Element} The rendered menu section.\n * @see {@link https://www.w3.org/WAI/ARIA/apg/patterns/disclosure/examples/disclosure-navigation/ | APG Disclosure Navigation Menu example}\n *\n * @example\n * <Menu>\n * <Menu.Section label=\"Components\" defaultOpen>\n * <Menu.List>\n * <Menu.Item href=\"/button\" active>Button</Menu.Item>\n * <Menu.Item href=\"/card\">Card</Menu.Item>\n * </Menu.List>\n * </Menu.Section>\n * </Menu>\n */\nexport const MenuSection: React.FC<MenuSectionProps> = ({\n className,\n label,\n children,\n open: controlledOpen,\n defaultOpen = false,\n onOpenChange,\n ...props\n}) => {\n const { bulmaHelperClasses, rest } = useBulmaClasses(props);\n const sectionClass = usePrefixedClassNames('menu-section');\n const toggleClass = usePrefixedClassNames('menu-section-toggle');\n const labelClass = usePrefixedClassNames('menu-section-label');\n const chevronClass = usePrefixedClassNames('menu-section-chevron');\n const listId = useId();\n const toggleRef = useRef<HTMLButtonElement>(null);\n const listRef = useRef<HTMLDivElement>(null);\n\n // The caller owns the state when `open` is set, and the section does\n // otherwise, as with Collapse. The button reports in both modes.\n const isControlled = controlledOpen !== undefined;\n const [internalOpen, setInternalOpen] = useState(defaultOpen);\n const isOpen = controlledOpen ?? internalOpen;\n\n const handleClick = () => {\n const next = !isOpen;\n onOpenChange?.(next);\n if (!isControlled) setInternalOpen(next);\n };\n\n // An app holding `open` can close a section while focus is on one of its\n // links, as a sidebar that keeps only the current route's section open\n // does after a link is followed. The browser then drops focus to <body>\n // a frame later, and the next Tab starts from the top of the page. The\n // heading is where the reader was, so focus goes there. A layout effect,\n // because it runs in the same task as the commit that hid the list, while\n // the link still has focus. A close from the button itself finds focus on\n // the button and leaves it.\n useClientLayoutEffect(() => {\n if (isOpen) return;\n const list = listRef.current!;\n if (list.contains(getActiveElementInTree(list))) {\n toggleRef.current!.focus();\n }\n }, [isOpen]);\n\n // A real button, so Enter and Space work with no key handler, and\n // `type=\"button\"`, so a menu inside a form isn't submitted by it.\n //\n // A closed list is `hidden`, so it isn't drawn and find-in-page doesn't\n // reach it, and `inert`, so its links stay out of Tab and assistive tech\n // even if a stylesheet sets `display` on it and shows it anyway. The markup\n // is the same from the server and on both React majors, which `inertProps`\n // sees to. It stays mounted, so `aria-controls` always names an element\n // that exists.\n return (\n <div\n className={classNames(sectionClass, bulmaHelperClasses, className)}\n {...rest}\n >\n <button\n ref={toggleRef}\n type=\"button\"\n className={toggleClass}\n aria-expanded={isOpen}\n aria-controls={listId}\n onClick={handleClick}\n >\n <span className={labelClass}>{label}</span>\n <span className={chevronClass} aria-hidden=\"true\" />\n </button>\n <div ref={listRef} id={listId} hidden={!isOpen} {...inertProps(!isOpen)}>\n {children}\n </div>\n </div>\n );\n};\n\n// Attach static subcomponents\nexport const Menu = withSubComponents(\n MenuComponent,\n {\n Label: MenuLabel,\n List: MenuList,\n Item: MenuItem,\n Section: MenuSection,\n },\n 'Menu'\n);\n\nexport default Menu;\n"],"names":["_jsx","_jsxs"],"mappings":";;;;;;;;;;;;;;;AAsBA;AACA,MAAM,oBAAoB,GAAG,aAAa,CAAC,CAAC,CAAC;AAe7C;;;;;;;AAOG;AACH,MAAM,aAAa,GAAwB,CAAC,EAC1C,SAAS,EACT,QAAQ,EACR,GAAG,KAAK,EACT,KAAI;IACH,MAAM,EAAE,kBAAkB,EAAE,IAAI,EAAE,GAAG,eAAe,CAAC,KAAK,CAAC;;AAG3D,IAAA,MAAM,YAAY,GAAG,qBAAqB,CAAC,MAAM,CAAC;AAElD,IAAA,QACEA,GAAA,CAAA,OAAA,EAAA,EACE,SAAS,EAAE,UAAU,CAAC,YAAY,EAAE,kBAAkB,EAAE,SAAS,CAAC,EAAA,GAC9D,IAAI,YAEP,QAAQ,EAAA,CACH;AAEZ,CAAC;AAeD;;;;;;AAMG;AACI,MAAM,SAAS,GAA6B,CA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