@doist/reactist 22.0.0-beta → 22.0.1-beta
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/reactist.cjs.development.js +190 -482
- package/dist/reactist.cjs.development.js.map +1 -1
- package/dist/reactist.cjs.production.min.js +1 -1
- package/dist/reactist.cjs.production.min.js.map +1 -1
- package/es/checkbox-field/checkbox-field.js +1 -1
- package/es/checkbox-field/checkbox-field.js.map +1 -1
- package/es/checkbox-field/use-fork-ref.js +35 -0
- package/es/checkbox-field/use-fork-ref.js.map +1 -0
- package/es/index.js +1 -1
- package/es/menu/menu.js +89 -337
- package/es/menu/menu.js.map +1 -1
- package/es/modal/modal.js +3 -4
- package/es/modal/modal.js.map +1 -1
- package/es/tabs/tabs.js +40 -47
- package/es/tabs/tabs.js.map +1 -1
- package/es/toast/use-toasts.js +1 -1
- package/es/toast/use-toasts.js.map +1 -1
- package/es/tooltip/tooltip.js +20 -62
- package/es/tooltip/tooltip.js.map +1 -1
- package/lib/checkbox-field/checkbox-field.js +1 -1
- package/lib/checkbox-field/checkbox-field.js.map +1 -1
- package/lib/checkbox-field/use-fork-ref.d.ts +11 -0
- package/lib/checkbox-field/use-fork-ref.js +2 -0
- package/lib/checkbox-field/use-fork-ref.js.map +1 -0
- package/lib/index.js +1 -1
- package/lib/menu/index.d.ts +2 -1
- package/lib/menu/menu.d.ts +27 -167
- package/lib/menu/menu.js +1 -1
- package/lib/menu/menu.js.map +1 -1
- package/lib/modal/modal.d.ts +1 -2
- package/lib/modal/modal.js +1 -1
- package/lib/modal/modal.js.map +1 -1
- package/lib/tabs/tabs.d.ts +10 -8
- package/lib/tabs/tabs.js +1 -1
- package/lib/tabs/tabs.js.map +1 -1
- package/lib/toast/use-toasts.js +1 -1
- package/lib/toast/use-toasts.js.map +1 -1
- package/lib/tooltip/tooltip.d.ts +2 -4
- package/lib/tooltip/tooltip.js +1 -1
- package/lib/tooltip/tooltip.js.map +1 -1
- package/lib/utils/test-helpers.d.ts +13 -2
- package/package.json +2 -4
- package/styles/menu.css +1 -8
- package/styles/reactist.css +2 -2
- package/es/hooks/use-previous/use-previous.js +0 -26
- package/es/hooks/use-previous/use-previous.js.map +0 -1
- package/es/menu/menu.module.css.js +0 -4
- package/es/menu/menu.module.css.js.map +0 -1
- package/lib/hooks/use-previous/use-previous.js +0 -2
- package/lib/hooks/use-previous/use-previous.js.map +0 -1
- package/lib/menu/menu.module.css.js +0 -2
- package/lib/menu/menu.module.css.js.map +0 -1
- package/styles/menu.module.css.css +0 -1
package/lib/menu/menu.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=require("../_virtual/_rollupPluginBabelHelpers.js"),
|
|
1
|
+
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=require("../_virtual/_rollupPluginBabelHelpers.js"),n=require("react"),o=(e(n),e(require("classnames"))),r=require("../utils/polymorphism.js"),l=require("@ariakit/react");const c=["children","onItemSelect"],a=["exceptionallySetClassName"],u=["as"],s=["exceptionallySetClassName","modal"],i=["value","children","onSelect","hideOnSelect","onClick","exceptionallySetClassName","as"],m=["label","children","exceptionallySetClassName"],p=n.createContext({});function d(e){let{children:o,onItemSelect:r}=e,a=t.objectWithoutProperties(e,c);const[u,s]=n.useState(null),i=n.useMemo(()=>u?()=>u:null,[u]),m=l.useMenuStore(t.objectSpread2({focusLoop:!0},a)),d=n.useCallback((function(e){null==r||r(e)}),[r]),S=n.useMemo(()=>({menuStore:m,handleItemSelect:d,getAnchorRect:i,setAnchorRect:s}),[m,d,i,s]);return n.createElement(p.Provider,{value:S},o)}const S=r.polymorphicComponent((function(e,r){let{exceptionallySetClassName:c}=e,u=t.objectWithoutProperties(e,a);const{menuStore:s}=n.useContext(p);return n.createElement(l.MenuButton,t.objectSpread2(t.objectSpread2({},u),{},{store:s,ref:r,className:o("reactist_menubutton",c)}))})),h=r.polymorphicComponent((function(e,o){let{as:r="div"}=e,l=t.objectWithoutProperties(e,u);const{setAnchorRect:c,menuStore:a}=n.useContext(p),s=n.useCallback((function(e){e.preventDefault(),c({x:e.clientX,y:e.clientY}),a.show()}),[c,a]);return n.createElement(r,t.objectSpread2(t.objectSpread2({},l),{},{onContextMenu:s,ref:o}))})),C=r.polymorphicComponent((function(e,r){let{exceptionallySetClassName:c,modal:a=!0}=e,u=t.objectWithoutProperties(e,s);const{menuStore:i,getAnchorRect:m}=n.useContext(p);return i.useState("open")?n.createElement(l.Portal,{preserveTabOrder:!0},n.createElement(l.Menu,t.objectSpread2(t.objectSpread2({},u),{},{store:i,gutter:8,shift:4,ref:r,className:o("reactist_menulist",c),getAnchorRect:null!=m?m:void 0,modal:a}))):null})),b=r.polymorphicComponent((function(e,o){let{value:r,children:c,onSelect:a,hideOnSelect:u=!0,onClick:s,exceptionallySetClassName:m,as:d="button"}=e,S=t.objectWithoutProperties(e,i);const{handleItemSelect:h,menuStore:C}=n.useContext(p),{hide:b}=C,f=n.useCallback((function(e){null==s||s(e);const t=!1!==(a&&!e.defaultPrevented?a():void 0)&&u;h(r),t&&b()}),[a,s,h,u,b,r]);return n.createElement(l.MenuItem,t.objectSpread2(t.objectSpread2({},S),{},{as:d,store:C,ref:o,onClick:f,className:m,hideOnClick:!1}),c)})),f=n.forwardRef((function({children:e,onItemSelect:t},o){const{handleItemSelect:r,menuStore:c}=n.useContext(p),{hide:a}=c,u=n.useCallback((function(e){t&&t(e),r(e),a()}),[a,r,t]),[s,i]=n.Children.toArray(e),m=n.useCallback((function(e){return n.cloneElement(s,e)}),[s]);return n.createElement(d,{onItemSelect:u},n.createElement(l.MenuItem,{as:"div",store:c,ref:o,hideOnClick:!1},m),i)})),x=r.polymorphicComponent((function(e,o){let{label:r,children:c,exceptionallySetClassName:a}=e,u=t.objectWithoutProperties(e,m);const{menuStore:s}=n.useContext(p);return n.createElement(l.MenuGroup,t.objectSpread2(t.objectSpread2({},u),{},{ref:o,store:s,className:a}),r?n.createElement("div",{role:"presentation",className:"reactist_menugroup__label"},r):null,c)}));exports.ContextMenuTrigger=h,exports.Menu=d,exports.MenuButton=S,exports.MenuGroup=x,exports.MenuItem=b,exports.MenuList=C,exports.SubMenu=f;
|
|
2
2
|
//# sourceMappingURL=menu.js.map
|
package/lib/menu/menu.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"menu.js","sources":["../../src/menu/menu.tsx"],"sourcesContent":["import * as React from 'react'\nimport classNames from 'classnames'\n\nimport { polymorphicComponent } from '../utils/polymorphism'\n\n//\n// Reactist menu is a thin wrapper around Ariakit's menu components. This may or may not be\n// temporary. Our goal is to make it transparent for the users of Reactist of this implementation\n// detail. We may change in the future the external lib we use, or even implement it all internally,\n// as long as we keep the same outer interface as intact as possible.\n//\n// Around the heavy lifting of the external lib we just add some features to better integrate the\n// menu to Reactist's more opinionated approach (e.g. using our button with its custom variants and\n// other features, easily show keyboard shortcuts in menu items, etc.)\n//\nimport * as Ariakit from 'ariakit/menu'\nimport { Portal } from 'ariakit/portal'\n\nimport { Box } from '../box'\nimport { Text } from '../text'\nimport { useId } from '../utils/common-helpers'\n\nimport styles from './menu.module.css'\nimport { Tooltip } from '../tooltip'\n\ntype NativeProps<E extends HTMLElement> = React.DetailedHTMLProps<React.HTMLAttributes<E>, E>\n\ntype MenuContextState = {\n state: Ariakit.MenuState\n handleItemSelect: (value: string | null | undefined) => void\n handleAnchorRectChange: (value: { x: number; y: number } | null) => void\n}\n\nconst MenuContext = React.createContext<MenuContextState>(\n // Ariakit gives us no means to obtain a valid initial/default value of type MenuStateReturn\n // (it is normally obtained by calling useMenuState but we can't call hooks outside components).\n // This is however of little consequence since this value is only used if some of the components\n // are used outside Menu, something that should not happen and we do not support.\n // @ts-expect-error\n {},\n)\n\n//\n// Menu\n//\n\ntype MenuProps = Omit<Ariakit.MenuStateProps, 'visible'> & {\n /**\n * The `Menu` must contain a `MenuList` that defines the menu options. It must also contain a\n * `MenuButton` that triggers the menu to be opened or closed.\n */\n children: React.ReactNode\n\n /**\n * An optional callback that will be called back whenever a menu item is selected. It receives\n * the `value` of the selected `MenuItem`.\n *\n * If you pass down this callback, it is recommended that you properly memoize it so it does not\n * change on every render.\n */\n onItemSelect?: (value: string | null | undefined) => void\n}\n\ntype MenuHandle = {\n open: () => void\n}\n\n/**\n * Wrapper component to control a menu. It does not render anything, only providing the state\n * management for the menu components inside it.\n */\nconst Menu = React.forwardRef<MenuHandle, MenuProps>(function Menu(\n { children, onItemSelect, ...props },\n ref,\n) {\n const [anchorRect, handleAnchorRectChange] = React.useState<{ x: number; y: number } | null>(\n null,\n )\n const getAnchorRect = React.useMemo(() => {\n return anchorRect ? () => anchorRect : undefined\n }, [anchorRect])\n\n const state = Ariakit.useMenuState({\n focusLoop: true,\n gutter: 8,\n shift: 4,\n getAnchorRect,\n ...props,\n })\n\n React.useEffect(() => {\n if (!state.open) handleAnchorRectChange(null)\n }, [state.open])\n\n React.useImperativeHandle(ref, () => ({ open: state.show }))\n\n const handleItemSelect = React.useCallback(\n function handleItemSelect(value: string | null | undefined) {\n if (onItemSelect) onItemSelect(value)\n },\n [onItemSelect],\n )\n\n const value: MenuContextState = React.useMemo(\n () => ({\n state,\n handleItemSelect,\n handleAnchorRectChange,\n }),\n [state, handleItemSelect],\n )\n\n return <MenuContext.Provider value={value}>{children}</MenuContext.Provider>\n})\n\n//\n// MenuButton\n//\n\ntype MenuButtonProps = Omit<Ariakit.MenuButtonProps, 'state' | 'className' | 'as'>\n\n/**\n * A button to toggle a dropdown menu open or closed.\n */\nconst MenuButton = polymorphicComponent<'button', MenuButtonProps>(function MenuButton(\n { exceptionallySetClassName, ...props },\n ref,\n) {\n const { state } = React.useContext(MenuContext)\n return (\n <Ariakit.MenuButton\n {...props}\n state={state}\n ref={ref}\n className={exceptionallySetClassName}\n />\n )\n})\n\n//\n// MenuItemContent\n//\n\ntype MenuItemContentProps = {\n id: string\n\n /**\n * The menu item's label.\n */\n label?: NonNullable<React.ReactNode>\n\n /**\n * The menu item's description, typically used to provide additional information about what the\n * menu item does.\n *\n * When used, it is rendered below the label. The label is also shown more prominently (e.g.\n * using bold text), while the description is rendered using text in secondary tone.\n *\n * Therefore, for the description to be rendered, you must also provide a `label`.\n */\n description?: React.ReactNode\n\n /**\n * An optional icon to render next to the menu item's label.\n *\n * For the icon to be rendered, you must also provide a `label`.\n */\n icon?: React.ReactNode\n\n /**\n * An optional element to render to the right of the menu item's label. It is often used to\n * show a keyboard shortcut for the menu item.\n *\n * For the shortcut to be rendered, you must also provide a `label`.\n */\n shortcut?: React.ReactNode\n}\n\n/**\n * Renders the content inside a standard MenuItem. It is extracted into a component for reuse in\n * the SubMenuItem, which is a MenuItem visually, but semantically it's closer to be a MenuButton.\n * @private\n */\nfunction MenuItemContent({ label, description, icon, shortcut, id }: MenuItemContentProps) {\n if (!label) return null\n return (\n <Box\n display=\"flex\"\n gap=\"small\"\n alignItems=\"center\"\n width=\"full\"\n aria-hidden // the menu item is labelled via aria-labelledby and aria-describedby\n >\n {icon ? <div className={styles.menuItemIcon}>{icon}</div> : null}\n <Box\n display=\"inlineFlex\"\n flexDirection=\"column\"\n gap=\"xsmall\"\n paddingY=\"xsmall\"\n alignItems=\"flexStart\"\n overflow=\"hidden\"\n flexGrow={1}\n >\n <Text\n id={`${id}-label`}\n weight={description ? 'semibold' : 'regular'}\n size=\"copy\"\n lineClamp={1}\n exceptionallySetClassName={styles.menuItemLabel}\n >\n {label}\n </Text>\n {description ? (\n <Text\n id={`${id}-description`}\n size=\"copy\"\n tone=\"secondary\"\n exceptionallySetClassName={styles.menuItemDescription}\n >\n {description}\n </Text>\n ) : null}\n </Box>\n {shortcut ? <div>{shortcut}</div> : null}\n </Box>\n )\n}\n\n//\n// SubMenuItem\n//\n\nfunction ArrowRightIcon() {\n return (\n <svg width=\"24\" height=\"24\">\n <path\n d=\"M14.243 12L9.646 7.404a.5.5 0 1 1 .708-.707l4.95 4.95a.5.5 0 0 1 0 .707l-4.95 4.95a.5.5 0 0 1-.708-.708L14.243 12z\"\n fill=\"currentColor\"\n fillRule=\"evenodd\"\n />\n </svg>\n )\n}\n\ntype SubMenuItemProps = Omit<Ariakit.MenuButtonProps, 'state' | 'className' | 'as' | 'children'> &\n Pick<MenuItemProps, 'label' | 'icon'>\n\n/**\n * A menu item to toggle a sub-menu open or closed.\n */\nconst SubMenuItem = polymorphicComponent<'button', SubMenuItemProps>(function SubMenuItem(\n { exceptionallySetClassName, label, icon, ...props },\n ref,\n) {\n const id = useId(props.id)\n const { state } = React.useContext(MenuContext)\n return (\n <Ariakit.MenuButton\n aria-labelledby={label && !props['aria-label'] ? `${id}-label` : undefined}\n {...props}\n state={state}\n ref={ref}\n className={classNames(styles.menuItem, exceptionallySetClassName)}\n >\n <MenuItemContent id={id} icon={icon} label={label} shortcut={<ArrowRightIcon />} />\n </Ariakit.MenuButton>\n )\n})\n\n//\n// ContextMenuTrigger\n//\nconst ContextMenuTrigger = polymorphicComponent<'div', unknown>(function ContextMenuTrigger(\n { as: component = 'div', ...props },\n ref,\n) {\n const { handleAnchorRectChange, state } = React.useContext(MenuContext)\n const handleContextMenu = React.useCallback(\n (event: React.MouseEvent) => {\n event.preventDefault()\n handleAnchorRectChange({ x: event.clientX, y: event.clientY })\n state.show()\n },\n [handleAnchorRectChange, state],\n )\n\n return React.createElement(component, { ...props, onContextMenu: handleContextMenu, ref })\n})\n\n//\n// MenuList and SubMenuList\n//\n\ntype MenuListProps = Omit<Ariakit.MenuProps, 'state' | 'className'>\n\n/**\n * The dropdown menu itself, containing a list of menu items.\n */\nconst MenuList = polymorphicComponent<'div', MenuListProps>(function MenuList(\n { exceptionallySetClassName, modal = true, ...props },\n ref,\n) {\n const { state } = React.useContext(MenuContext)\n if (!state.open) return null\n\n return (\n <Portal preserveTabOrder>\n <Ariakit.Menu\n {...props}\n state={state}\n ref={ref}\n className={classNames(styles.menuList, exceptionallySetClassName)}\n modal={modal}\n />\n </Portal>\n )\n})\n\n/**\n * Mostly equivalent to the `MenuList`, but to be used inside a `SubMenu`.\n */\nconst SubMenuList = polymorphicComponent<'div', MenuListProps>(function SubMenuList(\n { exceptionallySetClassName, modal = true, ...props },\n ref,\n) {\n const { state } = React.useContext(MenuContext)\n if (!state.open) return null\n\n return (\n <Portal preserveTabOrder>\n <Ariakit.Menu\n {...props}\n state={state}\n ref={ref}\n className={classNames(\n styles.menuList,\n styles.subMenuList,\n exceptionallySetClassName,\n )}\n modal={modal}\n />\n </Portal>\n )\n})\n\n//\n// MenuItem\n//\n\nfunction useMenuItemClickHandler({\n value,\n hideOnSelect,\n onClick,\n onSelect,\n}: Pick<MenuItemProps, 'value' | 'hideOnSelect' | 'onClick' | 'onSelect'>) {\n const { handleItemSelect, state } = React.useContext(MenuContext)\n const { hide } = state\n\n return React.useCallback(\n function handleClick(event: React.MouseEvent<HTMLButtonElement>) {\n onClick?.(event)\n const onSelectResult: unknown =\n onSelect && !event.defaultPrevented ? onSelect() : undefined\n const shouldClose = onSelectResult !== false && hideOnSelect\n handleItemSelect(value)\n if (shouldClose) hide()\n },\n [onSelect, onClick, handleItemSelect, hideOnSelect, hide, value],\n )\n}\n\ntype MenuItemProps = {\n /**\n * An optional value given to this menu item.\n *\n * It is passed on to the parent `Menu`'s `onItemSelect` when you provide that instead of (or\n * alongside) providing individual `onSelect` callbacks to each menu item.\n */\n value?: string\n\n /**\n * The menu item's content.\n *\n * Prefer using `label` instead. In addition to `label`, you can also use `description`, `icon`\n * and `shortcut`, to provide richer content inside the menu item.\n *\n * However, you can still use `children` to provide arbitrary content inside the menu item. You\n * can even combine `children` with the other props to provide a richer menu item. The\n * `children` content will be rendered first, followed by the regular menu item content\n * generated using the `label`, `description`, `icon` and `shortcut` props (if the `label` is\n * present).\n */\n children?: React.ReactNode\n\n /**\n * The menu item's label.\n */\n label?: NonNullable<React.ReactNode>\n\n /**\n * The menu item's description, typically used to provide additional information about what the\n * menu item does.\n *\n * When used, it is rendered below the label. The label is also shown more prominently (e.g.\n * using bold text), while the description is rendered using text in secondary tone.\n *\n * Therefore, for the description to be rendered, you must also provide a `label`.\n */\n description?: React.ReactNode\n\n /**\n * An optional icon to render next to the menu item's label.\n *\n * For the icon to be rendered, you must also provide a `label`.\n */\n icon?: NonNullable<React.ReactNode>\n\n /**\n * An optional element to render to the right of the menu item's label. It is often used to\n * show a keyboard shortcut for the menu item.\n *\n * For the shortcut to be rendered, you must also provide a `label`.\n */\n shortcut?: React.ReactNode\n\n /**\n * The tone to use for the menu item.\n */\n tone?: 'normal' | 'destructive'\n\n /**\n * When `true` the menu item is disabled and won't be selectable or be part of the keyboard\n * navigation across the menu options.\n *\n * @default true\n */\n disabled?: boolean\n\n /**\n * When `true` the menu will close when the menu item is selected, in addition to performing the\n * action that the menu item is set out to do.\n *\n * Set this to `false` to make sure that a given menu item does not auto-closes the menu when\n * selected. This should be the exception and not the norm, as the default is to auto-close.\n *\n * @default true\n */\n hideOnSelect?: boolean\n\n /**\n * The action to perform when the menu item is selected.\n *\n * If you return `false` from this function, the menu will not auto-close when this menu item\n * is selected. Though you should use `hideOnSelect` for this purpose, this allows you to\n * achieve the same effect conditionally and dynamically deciding at run time.\n */\n onSelect?: () => unknown\n\n /**\n * The event handler called when the menu item is clicked.\n *\n * This is similar to `onSelect`, but a bit different. You can certainly use it to trigger the\n * action that the menu item represents. But in general you should prefer `onSelect` for that.\n *\n * The main use for this handler is to get access to the click event. This can be used, for\n * example, to call `event.preventDefault()`, which will effectively prevent the rest of the\n * consequences of the click, including preventing `onSelect` from being called. In particular,\n * this is useful in menu items that are links, and you want the click to not trigger navigation\n * under some circumstances.\n */\n onClick?: (event: React.MouseEvent) => void\n}\n\n/**\n * A menu item inside a menu list. It can be selected by the user, triggering the `onSelect`\n * callback.\n */\nconst MenuItem = polymorphicComponent<'button', MenuItemProps>(function MenuItem(\n {\n value,\n label,\n description,\n icon,\n shortcut,\n tone,\n children,\n onSelect,\n hideOnSelect = true,\n onClick,\n exceptionallySetClassName,\n as = 'button',\n ...props\n },\n ref,\n) {\n const id = useId(props.id)\n const { state } = React.useContext(MenuContext)\n const handleClick = useMenuItemClickHandler({ value, onSelect, onClick, hideOnSelect })\n\n return (\n <Ariakit.MenuItem\n aria-labelledby={label && !props['aria-label'] ? `${id}-label` : undefined}\n aria-describedby={label && description ? `${id}-description` : undefined}\n {...props}\n as={as}\n state={state}\n ref={ref}\n onClick={handleClick}\n className={classNames(\n styles.menuItem,\n tone === 'destructive' ? styles.destructive : null,\n exceptionallySetClassName,\n )}\n hideOnClick={false}\n >\n {children ? (\n <Box width=\"full\" className={label ? undefined : styles.legacyLayout}>\n {children}\n </Box>\n ) : null}\n\n <MenuItemContent\n id={id}\n icon={icon}\n label={label}\n description={description}\n shortcut={shortcut}\n />\n </Ariakit.MenuItem>\n )\n})\n\n//\n// SubMenu\n//\n\ntype SubMenuProps = Pick<MenuProps, 'children' | 'onItemSelect'>\n\n/**\n * This component can be rendered alongside other `MenuItem` elements inside a `MenuList` to show a\n * sub-menu.\n *\n * Its children are expected to be exactly two elements, in the following order:\n *\n * 1. A `SubMenuItem` element: the menu item that triggers the sub-menu to open.\n * 2. A `SubMenuList` element: the list of menu items that will be shown when the sub-menu is open.\n *\n * ## Usage\n *\n * ```jsx\n * <Menu>\n * <MenuButton>Menu</MenuButton>\n * <MenuList>\n * <MenuItem label=\"Item 1\" />\n * <MenuItem label=\"Item 2\" />\n * <SubMenu>\n * <SubMenuItem label=\"Submenu\" />\n * <SubMenuList>\n * <MenuItem label=\"Submenu Item 1\" />\n * <MenuItem label=\"Submenu Item 2\" />\n * </SubMenuList>\n * </SubMenu>\n * </MenuList>\n * </Menu>\n * ```\n */\nconst SubMenu = React.forwardRef<HTMLDivElement, SubMenuProps>(function SubMenu(\n { children, onItemSelect },\n ref,\n) {\n const { handleItemSelect: parentMenuItemSelect, state } = React.useContext(MenuContext)\n const { hide: parentMenuHide } = state\n\n const handleSubItemSelect = React.useCallback(\n function handleSubItemSelect(value: string | null | undefined) {\n if (onItemSelect) onItemSelect(value)\n parentMenuItemSelect(value)\n parentMenuHide()\n },\n [parentMenuHide, parentMenuItemSelect, onItemSelect],\n )\n\n const [button, list] = React.Children.toArray(children)\n\n // Ariakit needs to be able to pass props to the MenuButton\n // and combine it with the MenuItem component\n const renderMenuButton = React.useCallback(\n function renderMenuButton(props: MenuButtonProps) {\n return React.cloneElement(button as React.ReactElement, props)\n },\n [button],\n )\n\n return (\n <Menu onItemSelect={handleSubItemSelect}>\n <Ariakit.MenuItem as=\"div\" state={state} ref={ref} hideOnClick={false}>\n {renderMenuButton}\n </Ariakit.MenuItem>\n <div className={styles.subMenuContainer}>{list}</div>\n </Menu>\n )\n})\n\n//\n// MenuGroup\n//\n\ntype MenuGroupProps = Omit<NativeProps<HTMLDivElement>, 'className'> & {\n /**\n * A label to be shown visually and also used to semantically label the group.\n */\n label: NonNullable<React.ReactNode>\n\n /**\n * An optional info element to be shown to the right of the label.\n *\n * This is useful and often used to:\n * - Provide a link to any documentation related to the menu items in the group\n * - Show a keyboard shortcut that triggers the menu items in the group\n *\n * It is strongly recommended that this should be a icon-only element. It is also strongly\n * recommended that, when using it to provide a link, you use the very `IconMenuItem` component\n * to make the link be yet another menu item accessible in the menu via keyboard navigation.\n * Here's an example of how to do that:\n *\n * ```jsx\n * <MenuGroup\n * label=\"A group of related options\"\n * info={\n * <IconMenuItem\n * label=\"Help about this group of options\"\n * icon=\"ℹ️\"\n * as=\"a\"\n * href=\"http://help.example.com\"\n * target=\"_blank\"\n * rel=\"noreferrer noopener\"\n * />\n * }\n * >\n * <MenuItem label=\"First option\" icon={<FirstIcon />} />\n * <MenuItem label=\"Second option\" icon={<SecondIcon />} />\n * </MenuGroup>\n * ```\n */\n info?: React.ReactNode\n}\n\n/**\n * A way to semantically group some menu items.\n *\n * This group does not add any visual separator. You can do that yourself adding `<hr />` elements\n * before and/or after the group if you so wish.\n */\nconst MenuGroup = polymorphicComponent<'div', MenuGroupProps>(function MenuGroup(\n { label, info, children, exceptionallySetClassName, ...props },\n ref,\n) {\n const id = useId(props.id)\n const { state } = React.useContext(MenuContext)\n return (\n <Ariakit.MenuGroup\n aria-labelledby={`menugroup-label-${id}`}\n {...props}\n id={id}\n ref={ref}\n state={state}\n className={exceptionallySetClassName}\n >\n <Box display=\"flex\" alignItems=\"center\" gap=\"small\" className={styles.menuGroupLabel}>\n <Text id={`menugroup-label-${id}`} size=\"copy\" weight=\"semibold\">\n {label}\n </Text>\n {info ? (\n <Box\n flexShrink={0}\n display=\"flex\"\n alignItems=\"center\"\n justifyContent=\"center\"\n className={styles.menuGroupInfo}\n >\n {info}\n </Box>\n ) : null}\n </Box>\n {children}\n </Ariakit.MenuGroup>\n )\n})\n\n//\n// IconMenuItem & IconsMenuGroup\n//\n\ntype IconMenuItemProps = Pick<MenuItemProps, 'value' | 'hideOnSelect' | 'onSelect' | 'onClick'> & {\n /**\n * A label for assistive technologies to describe the menu item.\n *\n * When not provided, the `label` is used. But this is useful when you want the tooltip label\n * to be different from the label for assistive technologies.\n */\n 'aria-label'?: string\n\n /**\n * The menu item's label, which is not shown visually on the menu item, but it is used to\n * show a tooltip for the menu item when hovered or focused.\n *\n * It is also used as the semantic label for assistive technologies, unless you provide an\n * `aria-label` as well.\n */\n label: string\n\n /**\n * A description for assistive technologies to describe the menu item.\n */\n description?: React.ReactNode\n\n /**\n * The icon to show on the menu item.\n */\n icon: NonNullable<React.ReactNode>\n}\n\n/**\n * A menu item that visually only shows as an icon. It must be used inside an `IconsMenuGroup`.\n */\nconst IconMenuItem = polymorphicComponent<'button', IconMenuItemProps>(function IconMenuItem(\n {\n value,\n label,\n description,\n icon,\n onSelect,\n hideOnSelect = true,\n onClick,\n exceptionallySetClassName,\n as = 'button',\n ...props\n },\n ref,\n) {\n const id = useId(props.id)\n const { state } = React.useContext(MenuContext)\n const handleClick = useMenuItemClickHandler({ value, onSelect, onClick, hideOnSelect })\n\n return (\n <Tooltip content={label}>\n <Ariakit.MenuItem\n aria-label={label}\n aria-describedby={`${id}-description`}\n {...props}\n as={as}\n state={state}\n ref={ref}\n onClick={handleClick}\n className={classNames(styles.iconMenuItem, exceptionallySetClassName)}\n hideOnClick={false}\n >\n {icon}\n </Ariakit.MenuItem>\n </Tooltip>\n )\n})\n\n/**\n * Semantically equivalent to `MenuGroup`, but meant to group `IconMenuItem`s only.\n */\nconst IconsMenuGroup = polymorphicComponent<'div', MenuGroupProps>(function IconsMenuGroup(\n { children, ...props },\n ref,\n) {\n return (\n <MenuGroup {...props} ref={ref}>\n <div className={styles.iconsMenuGroup}>{children}</div>\n </MenuGroup>\n )\n})\n\nexport {\n ContextMenuTrigger,\n IconMenuItem,\n IconsMenuGroup,\n Menu,\n MenuButton,\n MenuGroup,\n MenuItem,\n MenuList,\n SubMenu,\n SubMenuItem,\n SubMenuList,\n}\n\nexport type {\n IconMenuItemProps,\n MenuButtonProps,\n MenuGroupProps,\n MenuHandle,\n MenuItemProps,\n MenuListProps,\n MenuProps,\n SubMenuItemProps,\n SubMenuProps,\n}\n"],"names":["MenuContext","React","Menu","ref","children","onItemSelect","props","anchorRect","handleAnchorRectChange","getAnchorRect","undefined","state","Ariakit","focusLoop","gutter","shift","open","show","handleItemSelect","value","Provider","MenuButton","polymorphicComponent","exceptionallySetClassName","className","MenuItemContent","label","description","icon","shortcut","id","Box","display","gap","alignItems","width","styles","menuItemIcon","flexDirection","paddingY","overflow","flexGrow","Text","weight","size","lineClamp","menuItemLabel","tone","menuItemDescription","ArrowRightIcon","height","d","fill","fillRule","SubMenuItem","useId","classNames","menuItem","ContextMenuTrigger","as","component","handleContextMenu","event","preventDefault","x","clientX","y","clientY","onContextMenu","MenuList","modal","Portal","preserveTabOrder","menuList","SubMenuList","subMenuList","useMenuItemClickHandler","hideOnSelect","onClick","onSelect","hide","shouldClose","defaultPrevented","MenuItem","handleClick","destructive","hideOnClick","legacyLayout","SubMenu","parentMenuItemSelect","parentMenuHide","handleSubItemSelect","button","list","toArray","renderMenuButton","subMenuContainer","MenuGroup","info","menuGroupLabel","flexShrink","justifyContent","menuGroupInfo","IconMenuItem","Tooltip","content","iconMenuItem","IconsMenuGroup","iconsMenuGroup"],"mappings":"wgCAiCMA,EAAcC,gBAMhB,IAgCEC,EAAOD,cAAwC,WAEjDE,OADAC,SAAEA,EAAFC,aAAYA,KAAiBC,iCAG7B,MAAOC,EAAYC,GAA0BP,WACzC,MAEEQ,EAAgBR,UAAc,IACzBM,EAAa,IAAMA,OAAaG,EACxC,CAACH,IAEEI,EAAQC,gCACVC,WAAW,EACXC,OAAQ,EACRC,MAAO,EACPN,cAAAA,GACGH,IAGPL,YAAgB,KACPU,EAAMK,MAAMR,EAAuB,OACzC,CAACG,EAAMK,OAEVf,sBAA0BE,EAAK,MAASa,KAAML,EAAMM,QAEpD,MAAMC,EAAmBjB,eACrB,SAA0BkB,GAClBd,GAAcA,EAAac,KAEnC,CAACd,IAGCc,EAA0BlB,UAC5B,MACIU,MAAAA,EACAO,iBAAAA,EACAV,uBAAAA,IAEJ,CAACG,EAAOO,IAGZ,OAAOjB,gBAACD,EAAYoB,UAASD,MAAOA,GAAQf,MAY1CiB,EAAaC,wBAAgD,WAE/DnB,OADAoB,0BAAEA,KAA8BjB,iCAGhC,MAAMK,MAAEA,GAAUV,aAAiBD,GACnC,OACIC,gBAACW,gDACON,OACJK,MAAOA,EACPR,IAAKA,EACLqB,UAAWD,QAiDvB,SAASE,GAAgBC,MAAEA,EAAFC,YAASA,EAATC,KAAsBA,EAAtBC,SAA4BA,EAA5BC,GAAsCA,IAC3D,OAAKJ,EAEDzB,gBAAC8B,OACGC,QAAQ,OACRC,IAAI,QACJC,WAAW,SACXC,MAAM,yBAGLP,EAAO3B,uBAAKuB,UAAWY,UAAOC,cAAeT,GAAc,KAC5D3B,gBAAC8B,OACGC,QAAQ,aACRM,cAAc,SACdL,IAAI,SACJM,SAAS,SACTL,WAAW,YACXM,SAAS,SACTC,SAAU,GAEVxC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AI,QAAQT,UAAWY,UAAO+D,gBAClElG,gBAACyC,QAAKZ,sBAAuBA,EAAMc,KAAK,OAAOD,OAAO,YACjDjB,GAEJwE,EACGjG,gBAAC8B,OACGqE,WAAY,EACZpE,QAAQ,OACRE,WAAW,SACXmE,eAAe,SACf7E,UAAWY,UAAOkE,eAEjBJ,GAEL,MAEP9F,MAyCPmG,EAAejF,wBAAkD,WAanEnB,OAZAgB,MACIA,EADJO,MAEIA,EAFJE,KAIIA,EAJJmD,SAKIA,EALJF,aAMIA,GAAe,EANnBC,QAOIA,EAPJvD,0BAQIA,EARJoC,GASIA,EAAK,YACFrD,iCAIP,MAAMwB,EAAKyB,QAAMjD,EAAMwB,KACjBnB,MAAEA,GAAUV,aAAiBD,GAC7BoF,EAAcR,EAAwB,CAAEzD,MAAAA,EAAO4D,SAAAA,EAAUD,QAAAA,EAASD,aAAAA,IAExE,OACI5E,gBAACuG,WAAQC,QAAS/E,GACdzB,gBAACW,yDACec,qBACSI,kBACjBxB,OACJqD,GAAIA,EACJhD,MAAOA,EACPR,IAAKA,EACL2E,QAASM,EACT5D,UAAWgC,EAAWpB,UAAOsE,aAAcnF,GAC3C+D,aAAa,IAEZ1D,OASX+E,EAAiBrF,wBAA4C,WAE/DnB,OADAC,SAAEA,KAAaE,iCAGf,OACIL,gBAACgG,qCAAc3F,OAAOH,IAAKA,IACvBF,uBAAKuB,UAAWY,UAAOwE,gBAAiBxG"}
|
|
1
|
+
{"version":3,"file":"menu.js","sources":["../../src/menu/menu.tsx"],"sourcesContent":["import * as React from 'react'\nimport classNames from 'classnames'\n\nimport { polymorphicComponent } from '../utils/polymorphism'\n\n//\n// Reactist menu is a thin wrapper around Ariakit's menu components. This may or may not be\n// temporary. Our goal is to make it transparent for the users of Reactist of this implementation\n// detail. We may change in the future the external lib we use, or even implement it all internally,\n// as long as we keep the same outer interface as intact as possible.\n//\n// Around the heavy lifting of the external lib we just add some features to better integrate the\n// menu to Reactist's more opinionated approach (e.g. using our button with its custom variants and\n// other features, easily show keyboard shortcuts in menu items, etc.)\n//\nimport {\n Portal,\n MenuStore,\n MenuStoreProps,\n useMenuStore,\n MenuProps as AriakitMenuProps,\n Menu as AriakitMenu,\n MenuGroup as AriakitMenuGroup,\n MenuItem as AriakitMenuItem,\n MenuButton as AriakitMenuButton,\n MenuButtonProps as AriakitMenuButtonProps,\n} from '@ariakit/react'\n\nimport './menu.less'\n\ntype NativeProps<E extends HTMLElement> = React.DetailedHTMLProps<React.HTMLAttributes<E>, E>\n\ntype MenuContextState = {\n menuStore: MenuStore\n handleItemSelect: (value: string | null | undefined) => void\n getAnchorRect: (() => { x: number; y: number }) | null\n setAnchorRect: (rect: { x: number; y: number } | null) => void\n}\n\nconst MenuContext = React.createContext<MenuContextState>(\n // Ariakit gives us no means to obtain a valid initial/default value of type MenuStateReturn\n // (it is normally obtained by calling useMenuState but we can't call hooks outside components).\n // This is however of little consequence since this value is only used if some of the components\n // are used outside Menu, something that should not happen and we do not support.\n // @ts-expect-error\n {},\n)\n\n//\n// Menu\n//\n\ntype MenuProps = Omit<MenuStoreProps, 'visible'> & {\n /**\n * The `Menu` must contain a `MenuList` that defines the menu options. It must also contain a\n * `MenuButton` that triggers the menu to be opened or closed.\n */\n children: React.ReactNode\n\n /**\n * An optional callback that will be called back whenever a menu item is selected. It receives\n * the `value` of the selected `MenuItem`.\n *\n * If you pass down this callback, it is recommended that you properly memoize it so it does not\n * change on every render.\n */\n onItemSelect?: (value: string | null | undefined) => void\n}\n\n/**\n * Wrapper component to control a menu. It does not render anything, only providing the state\n * management for the menu components inside it.\n */\nfunction Menu({ children, onItemSelect, ...props }: MenuProps) {\n const [anchorRect, setAnchorRect] = React.useState<{ x: number; y: number } | null>(null)\n const getAnchorRect = React.useMemo(() => (anchorRect ? () => anchorRect : null), [anchorRect])\n const menuStore = useMenuStore({ focusLoop: true, ...props })\n\n const handleItemSelect = React.useCallback(\n function handleItemSelect(value: string | null | undefined) {\n onItemSelect?.(value)\n },\n [onItemSelect],\n )\n\n const value: MenuContextState = React.useMemo(\n () => ({ menuStore, handleItemSelect, getAnchorRect, setAnchorRect }),\n [menuStore, handleItemSelect, getAnchorRect, setAnchorRect],\n )\n\n return <MenuContext.Provider value={value}>{children}</MenuContext.Provider>\n}\n\n//\n// MenuButton\n//\n\ntype MenuButtonProps = Omit<AriakitMenuButtonProps, 'store' | 'className' | 'as'>\n\n/**\n * A button to toggle a dropdown menu open or closed.\n */\nconst MenuButton = polymorphicComponent<'button', MenuButtonProps>(function MenuButton(\n { exceptionallySetClassName, ...props },\n ref,\n) {\n const { menuStore } = React.useContext(MenuContext)\n return (\n <AriakitMenuButton\n {...props}\n store={menuStore}\n ref={ref}\n className={classNames('reactist_menubutton', exceptionallySetClassName)}\n />\n )\n})\n\n//\n// ContextMenuTrigger\n//\nconst ContextMenuTrigger = polymorphicComponent<'div', unknown>(function ContextMenuTrigger(\n { as: component = 'div', ...props },\n ref,\n) {\n const { setAnchorRect, menuStore } = React.useContext(MenuContext)\n\n const handleContextMenu = React.useCallback(\n function handleContextMenu(event: React.MouseEvent) {\n event.preventDefault()\n setAnchorRect({ x: event.clientX, y: event.clientY })\n menuStore.show()\n },\n [setAnchorRect, menuStore],\n )\n\n return React.createElement(component, { ...props, onContextMenu: handleContextMenu, ref })\n})\n\n//\n// MenuList\n//\n\ntype MenuListProps = Omit<AriakitMenuProps, 'store' | 'className'>\n\n/**\n * The dropdown menu itself, containing a list of menu items.\n */\nconst MenuList = polymorphicComponent<'div', MenuListProps>(function MenuList(\n { exceptionallySetClassName, modal = true, ...props },\n ref,\n) {\n const { menuStore, getAnchorRect } = React.useContext(MenuContext)\n const isOpen = menuStore.useState('open')\n\n return isOpen ? (\n <Portal preserveTabOrder>\n <AriakitMenu\n {...props}\n store={menuStore}\n gutter={8}\n shift={4}\n ref={ref}\n className={classNames('reactist_menulist', exceptionallySetClassName)}\n getAnchorRect={getAnchorRect ?? undefined}\n modal={modal}\n />\n </Portal>\n ) : null\n})\n\n//\n// MenuItem\n//\n\ntype MenuItemProps = {\n /**\n * An optional value given to this menu item. It is passed on to the parent `Menu`'s\n * `onItemSelect` when you provide that instead of (or alongside) providing individual\n * `onSelect` callbacks to each menu item.\n */\n value?: string\n /**\n * The content inside the menu item.\n */\n children: React.ReactNode\n /**\n * When `true` the menu item is disabled and won't be selectable or be part of the keyboard\n * navigation across the menu options.\n *\n * @default true\n */\n disabled?: boolean\n /**\n * When `true` the menu will close when the menu item is selected, in addition to performing the\n * action that the menu item is set out to do.\n *\n * Set this to `false` to make sure that a given menu item does not auto-closes the menu when\n * selected. This should be the exception and not the norm, as the default is to auto-close.\n *\n * @default true\n */\n hideOnSelect?: boolean\n /**\n * The action to perform when the menu item is selected.\n *\n * If you return `false` from this function, the menu will not auto-close when this menu item\n * is selected. Though you should use `hideOnSelect` for this purpose, this allows you to\n * achieve the same effect conditionally and dynamically deciding at run time.\n */\n onSelect?: () => unknown\n /**\n * The event handler called when the menu item is clicked.\n *\n * This is similar to `onSelect`, but a bit different. You can certainly use it to trigger the\n * action that the menu item represents. But in general you should prefer `onSelect` for that.\n *\n * The main use for this handler is to get access to the click event. This can be used, for\n * example, to call `event.preventDefault()`, which will effectively prevent the rest of the\n * consequences of the click, including preventing `onSelect` from being called. In particular,\n * this is useful in menu items that are links, and you want the click to not trigger navigation\n * under some circumstances.\n */\n onClick?: (event: React.MouseEvent) => void\n}\n\n/**\n * A menu item inside a menu list. It can be selected by the user, triggering the `onSelect`\n * callback.\n */\nconst MenuItem = polymorphicComponent<'button', MenuItemProps>(function MenuItem(\n {\n value,\n children,\n onSelect,\n hideOnSelect = true,\n onClick,\n exceptionallySetClassName,\n as = 'button',\n ...props\n },\n ref,\n) {\n const { handleItemSelect, menuStore } = React.useContext(MenuContext)\n const { hide } = menuStore\n\n const handleClick = React.useCallback(\n function handleClick(event: React.MouseEvent<HTMLButtonElement>) {\n onClick?.(event)\n const onSelectResult: unknown =\n onSelect && !event.defaultPrevented ? onSelect() : undefined\n const shouldClose = onSelectResult !== false && hideOnSelect\n handleItemSelect(value)\n if (shouldClose) hide()\n },\n [onSelect, onClick, handleItemSelect, hideOnSelect, hide, value],\n )\n\n return (\n <AriakitMenuItem\n {...props}\n as={as}\n store={menuStore}\n ref={ref}\n onClick={handleClick}\n className={exceptionallySetClassName}\n hideOnClick={false}\n >\n {children}\n </AriakitMenuItem>\n )\n})\n\n//\n// SubMenu\n//\n\ntype SubMenuProps = Pick<MenuProps, 'children' | 'onItemSelect'>\n\n/**\n * This component can be rendered alongside other `MenuItem` inside a `MenuList` in order to have\n * a sub-menu.\n *\n * Its children are expected to have the structure of a first level menu (a `MenuButton` and a\n * `MenuList`).\n *\n * ```jsx\n * <MenuItem label=\"Edit profile\" />\n * <SubMenu>\n * <MenuButton>More options</MenuButton>\n * <MenuList>\n * <MenuItem label=\"Preferences\" />\n * <MenuItem label=\"Sign out\" />\n * </MenuList>\n * </SubMenu>\n * ```\n *\n * The `MenuButton` will become a menu item in the current menu items list, and it will lead to\n * opening a sub-menu with the menu items list below it.\n */\nconst SubMenu = React.forwardRef<HTMLDivElement, SubMenuProps>(function SubMenu(\n { children, onItemSelect },\n ref,\n) {\n const { handleItemSelect: parentMenuItemSelect, menuStore } = React.useContext(MenuContext)\n const { hide: parentMenuHide } = menuStore\n\n const handleSubItemSelect = React.useCallback(\n function handleSubItemSelect(value: string | null | undefined) {\n if (onItemSelect) onItemSelect(value)\n parentMenuItemSelect(value)\n parentMenuHide()\n },\n [parentMenuHide, parentMenuItemSelect, onItemSelect],\n )\n\n const [button, list] = React.Children.toArray(children)\n\n // Ariakit needs to be able to pass props to the MenuButton\n // and combine it with the MenuItem component\n const renderMenuButton = React.useCallback(\n function renderMenuButton(props: MenuButtonProps) {\n return React.cloneElement(button as React.ReactElement, props)\n },\n [button],\n )\n\n return (\n <Menu onItemSelect={handleSubItemSelect}>\n <AriakitMenuItem as=\"div\" store={menuStore} ref={ref} hideOnClick={false}>\n {renderMenuButton}\n </AriakitMenuItem>\n {list}\n </Menu>\n )\n})\n\n//\n// MenuGroup\n//\n\ntype MenuGroupProps = Omit<NativeProps<HTMLDivElement>, 'className'> & {\n /**\n * A label to be shown visually and also used to semantically label the group.\n */\n label: string\n}\n\n/**\n * A way to semantically group some menu items.\n *\n * This group does not add any visual separator. You can do that yourself adding `<hr />` elements\n * before and/or after the group if you so wish.\n */\nconst MenuGroup = polymorphicComponent<'div', MenuGroupProps>(function MenuGroup(\n { label, children, exceptionallySetClassName, ...props },\n ref,\n) {\n const { menuStore } = React.useContext(MenuContext)\n return (\n <AriakitMenuGroup\n {...props}\n ref={ref}\n store={menuStore}\n className={exceptionallySetClassName}\n >\n {label ? (\n <div role=\"presentation\" className=\"reactist_menugroup__label\">\n {label}\n </div>\n ) : null}\n {children}\n </AriakitMenuGroup>\n )\n})\n\nexport { ContextMenuTrigger, Menu, MenuButton, MenuList, MenuItem, SubMenu, MenuGroup }\nexport type { MenuButtonProps, MenuListProps, MenuItemProps, MenuGroupProps }\n"],"names":["MenuContext","React","Menu","children","onItemSelect","props","anchorRect","setAnchorRect","getAnchorRect","menuStore","useMenuStore","focusLoop","handleItemSelect","value","Provider","MenuButton","polymorphicComponent","ref","exceptionallySetClassName","AriakitMenuButton","store","className","classNames","ContextMenuTrigger","as","component","handleContextMenu","event","preventDefault","x","clientX","y","clientY","show","onContextMenu","MenuList","modal","useState","Portal","preserveTabOrder","AriakitMenu","gutter","shift","undefined","MenuItem","onSelect","hideOnSelect","onClick","hide","handleClick","shouldClose","defaultPrevented","AriakitMenuItem","hideOnClick","SubMenu","parentMenuItemSelect","parentMenuHide","handleSubItemSelect","button","list","toArray","renderMenuButton","MenuGroup","label","AriakitMenuGroup","role"],"mappings":"+jBAuCMA,EAAcC,gBAMhB,IA4BJ,SAASC,SAAKC,SAAEA,EAAFC,aAAYA,KAAiBC,iCACvC,MAAOC,EAAYC,GAAiBN,WAAgD,MAC9EO,EAAgBP,UAAc,IAAOK,EAAa,IAAMA,EAAa,KAAO,CAACA,IAC7EG,EAA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D"}
|
package/lib/modal/modal.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import * as React from 'react';
|
|
2
|
-
import { DialogOptions } from 'ariakit/
|
|
3
|
-
import { PortalOptions } from 'ariakit/portal';
|
|
2
|
+
import { DialogOptions, PortalOptions } from '@ariakit/react';
|
|
4
3
|
import { ButtonProps } from '../button';
|
|
5
4
|
declare type ModalWidth = 'small' | 'medium' | 'large' | 'xlarge' | 'full';
|
|
6
5
|
declare type ModalHeightMode = 'expand' | 'fitContent';
|
package/lib/modal/modal.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=require("../_virtual/_rollupPluginBabelHelpers.js"),a=require("react"),l=(e(a),e(require("classnames"))),n=require("../box/box.js"),o=require("../columns/columns.js"),r=require("../divider/divider.js"),i=require("../inline/inline.js"),s=require("../button/button.js"),u=require("../icons/close-icon.js"),
|
|
1
|
+
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=require("../_virtual/_rollupPluginBabelHelpers.js"),a=require("react"),l=(e(a),e(require("classnames"))),n=require("../box/box.js"),o=require("../columns/columns.js"),r=require("../divider/divider.js"),i=require("../inline/inline.js"),s=require("@ariakit/react"),c=require("../button/button.js"),u=require("../icons/close-icon.js"),d=e(require("react-focus-lock")),m=require("aria-hidden"),p=require("./modal.module.css.js");const h=["isOpen","onDismiss","height","width","exceptionallySetClassName","exceptionallySetOverlayClassName","autoFocus","hideOnEscape","hideOnInteractOutside","children","portalElement"],f=["children","button","withDivider","exceptionallySetClassName"],x=["exceptionallySetClassName","children"],b=["exceptionallySetClassName","withDivider"],g=["children"],E=a.createContext({onDismiss:void 0,height:"fitContent"});function v(e){return!(e.ownerDocument===document&&"iframe"===e.tagName.toLowerCase())}function C(e){const{onDismiss:l}=a.useContext(E),[n,o]=a.useState(!1),[r,i]=a.useState(!1);return a.useEffect((function(){r?o(!0):i(!0)}),[r]),a.createElement(c.Button,t.objectSpread2(t.objectSpread2({},e),{},{variant:"quaternary",onClick:l,icon:a.createElement(u.CloseIcon,null),tabIndex:n?0:-1}))}function S(e){let{exceptionallySetClassName:l,withDivider:o=!1}=e,i=t.objectWithoutProperties(e,b);return a.createElement(a.Fragment,null,o?a.createElement(r.Divider,null):null,a.createElement(n.Box,t.objectSpread2(t.objectSpread2({as:"footer"},i),{},{className:l,padding:"large"})))}exports.Modal=function(e){let{isOpen:o,onDismiss:r,height:i="fitContent",width:c="medium",exceptionallySetClassName:u,exceptionallySetOverlayClassName:f,autoFocus:x=!0,hideOnEscape:b=!0,hideOnInteractOutside:g=!0,children:C,portalElement:S}=e,j=t.objectWithoutProperties(e,h);const y=a.useCallback(e=>{e||null==r||r()},[r]),N=s.useDialogStore({open:o,setOpen:y}),O=a.useMemo(()=>({onDismiss:r,height:i}),[r,i]),w=a.useRef(null),D=a.useRef(null),q=a.useRef(null),B=a.useCallback(e=>{var t,a;null!=(t=D.current)&&t.contains(e.target)||null==(a=q.current)||!a.contains(e.target)||(e.stopPropagation(),null==r||r())},[r]);return a.useLayoutEffect((function(){if(o&&w.current)return m.hideOthers(w.current)}),[o]),o?a.createElement(s.Portal,{portalRef:w,portalElement:S},a.createElement(n.Box,{"data-testid":"modal-overlay","data-overlay":!0,className:l(p.default.overlay,p.default[i],p.default[c],f),onPointerDown:g?B:void 0,ref:q},a.createElement(d,{autoFocus:x,whiteList:v,returnFocus:!0},a.createElement(s.Dialog,t.objectSpread2(t.objectSpread2({},j),{},{ref:D,as:n.Box,store:N,hideOnEscape:b,preventBodyScroll:!0,borderRadius:"full",background:"default",display:"flex",flexDirection:"column",overflow:"hidden",height:"expand"===i?"full":void 0,flexGrow:"expand"===i?1:0,className:[u,p.default.container],modal:!1,autoFocus:!1,autoFocusOnShow:!1,autoFocusOnHide:!1,portal:!1,backdrop:!1,hideOnInteractOutside:!1}),a.createElement(E.Provider,{value:O},C))))):null},exports.ModalActions=function(e){let{children:l}=e,n=t.objectWithoutProperties(e,g);return a.createElement(S,t.objectSpread2({},n),a.createElement(i.Inline,{align:"right",space:"large"},l))},exports.ModalBody=function(e){let{exceptionallySetClassName:l,children:o}=e,r=t.objectWithoutProperties(e,x);const{height:i}=a.useContext(E);return a.createElement(n.Box,t.objectSpread2(t.objectSpread2({},r),{},{className:l,flexGrow:"expand"===i?1:0,height:"expand"===i?"full":void 0,overflow:"auto"}),a.createElement(n.Box,{padding:"large",paddingBottom:"xxlarge"},o))},exports.ModalCloseButton=C,exports.ModalFooter=S,exports.ModalHeader=function(e){let{children:l,button:i=!0,withDivider:s=!1,exceptionallySetClassName:c}=e,u=t.objectWithoutProperties(e,f);return a.createElement(a.Fragment,null,a.createElement(n.Box,t.objectSpread2(t.objectSpread2({},u),{},{as:"header",paddingLeft:"large",paddingRight:!1===i||null===i?"large":"small",paddingY:"small",className:c}),a.createElement(o.Columns,{space:"large",alignY:"center"},a.createElement(o.Column,{width:"auto"},l),!1===i||null===i?a.createElement("div",{className:p.default.headerContent}):a.createElement(o.Column,{width:"content",exceptionallySetClassName:p.default.buttonContainer,"data-testid":"button-container"},"boolean"==typeof i?a.createElement(C,{"aria-label":"Close modal",autoFocus:!1}):i))),s?a.createElement(r.Divider,null):null)};
|
|
2
2
|
//# sourceMappingURL=modal.js.map
|
package/lib/modal/modal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modal.js","sources":["../../src/modal/modal.tsx"],"sourcesContent":["import * as React from 'react'\nimport classNames from 'classnames'\nimport FocusLock from 'react-focus-lock'\nimport { hideOthers } from 'aria-hidden'\n\nimport { Dialog, DialogOptions, useDialogState } from 'ariakit/dialog'\nimport { Portal, PortalOptions } from 'ariakit/portal'\n\nimport { CloseIcon } from '../icons/close-icon'\nimport { Column, Columns } from '../columns'\nimport { Inline } from '../inline'\nimport { Divider } from '../divider'\nimport { Box } from '../box'\nimport { Button, ButtonProps } from '../button'\n\nimport styles from './modal.module.css'\n\ntype ModalWidth = 'small' | 'medium' | 'large' | 'xlarge' | 'full'\ntype ModalHeightMode = 'expand' | 'fitContent'\n\n//\n// ModalContext\n//\n\ntype ModalContextValue = {\n onDismiss?(this: void): void\n height: ModalHeightMode\n}\n\nconst ModalContext = React.createContext<ModalContextValue>({\n onDismiss: undefined,\n height: 'fitContent',\n})\n\n//\n// Modal container\n//\n\ntype DivProps = Omit<\n React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLDivElement>, HTMLDivElement>,\n 'className' | 'children' | `aria-label` | `aria-labelledby`\n>\n\nexport type ModalProps = DivProps & {\n /**\n * The content of the modal.\n */\n children: React.ReactNode\n /**\n * Whether the modal is open and visible or not.\n */\n isOpen: boolean\n /**\n * Called when the user triggers closing the modal.\n */\n onDismiss?(): void\n /**\n * A descriptive setting for how wide the modal should aim to be, depending on how much space\n * it has on screen.\n * @default 'medium'\n */\n width?: ModalWidth\n /**\n * A descriptive setting for how tall the modal should aim to be.\n *\n * - 'expand': the modal aims to fill most of the available screen height, leaving only a small\n * padding above and below.\n * - 'fitContent': the modal shrinks to the smallest size that allow it to fit its content.\n *\n * In either case, if content does not fit, the content of the main body is set to scroll\n * (provided you use `ModalBody`) so that the modal never has to strech vertically beyond the\n * viewport boundaries.\n *\n * If you do not use `ModalBody`, the modal still prevents overflow, and you are in charge of\n * the inner layout to ensure scroll, or whatever other strategy you may want.\n */\n height?: ModalHeightMode\n /**\n * Whether to set or not the focus initially to the first focusable element inside the modal.\n */\n autoFocus?: boolean\n /**\n * Controls if the modal is dismissed when pressing \"Escape\".\n */\n hideOnEscape?: DialogOptions['hideOnEscape']\n /**\n * Controls if the modal is dismissed when clicking outside the modal body, on the overlay.\n */\n hideOnInteractOutside?: DialogOptions['hideOnInteractOutside']\n /**\n * An escape hatch in case you need to provide a custom class name to the container element.\n */\n exceptionallySetClassName?: string\n /**\n * An escape hatch in case you need to provide a custom class name to the overlay element.\n */\n exceptionallySetOverlayClassName?: string\n /** Defines a string value that labels the current modal for assistive technologies. */\n 'aria-label'?: string\n /** Identifies the element (or elements) that labels the current modal for assistive technologies. */\n 'aria-labelledby'?: string\n /**\n * An HTML element or a memoized callback function that returns an HTML element to be used as\n * the portal element. By default, the portal element will be a `div` element appended to the\n * `document.body`.\n *\n * @default HTMLDivElement\n *\n * @example\n * const [portal, setPortal] = useState(null);\n * <Portal portalElement={portal} />;\n * <div ref={setPortal} />;\n *\n * @example\n * const getPortalElement = useCallback(() => {\n * const div = document.createElement(\"div\");\n * const portalRoot = document.getElementById(\"portal-root\");\n * portalRoot.appendChild(div);\n * return div;\n * }, []);\n * <Portal portalElement={getPortalElement} />;\n */\n portalElement?: PortalOptions['portalElement']\n}\n\nfunction isNotInternalFrame(element: HTMLElement) {\n return !(element.ownerDocument === document && element.tagName.toLowerCase() === 'iframe')\n}\n\n/**\n * Renders a modal that sits on top of the rest of the content in the entire page.\n *\n * Follows the WAI-ARIA Dialog (Modal) Pattern.\n *\n * @see ModalHeader\n * @see ModalFooter\n * @see ModalBody\n */\nexport function Modal({\n isOpen,\n onDismiss,\n height = 'fitContent',\n width = 'medium',\n exceptionallySetClassName,\n exceptionallySetOverlayClassName,\n autoFocus = true,\n hideOnEscape = true,\n hideOnInteractOutside = true,\n children,\n portalElement,\n ...props\n}: ModalProps) {\n const setOpen = React.useCallback(\n (visible: boolean) => {\n if (!visible) {\n onDismiss?.()\n }\n },\n [onDismiss],\n )\n const state = useDialogState({ open: isOpen, setOpen })\n\n const contextValue: ModalContextValue = React.useMemo(() => ({ onDismiss, height }), [\n onDismiss,\n height,\n ])\n\n const portalRef = React.useRef<HTMLElement | null>(null)\n const dialogRef = React.useRef<HTMLDivElement | null>(null)\n const backdropRef = React.useRef<HTMLDivElement | null>(null)\n const handleBackdropClick = React.useCallback(\n (event: React.MouseEvent) => {\n if (\n // The focus lock element takes up the same space as the backdrop and is where the event bubbles up from,\n // so instead of checking the backdrop as the event target, we need to make sure it's just above the dialog\n !dialogRef.current?.contains(event.target as Node) &&\n // Events fired from other portals will bubble up to the backdrop, even if it isn't a child in the DOM\n backdropRef.current?.contains(event.target as Node)\n ) {\n event.stopPropagation()\n onDismiss?.()\n }\n },\n [onDismiss],\n )\n\n React.useLayoutEffect(\n function disableAccessibilityTreeOutside() {\n if (!isOpen || !portalRef.current) {\n return\n }\n\n return hideOthers(portalRef.current)\n },\n [isOpen],\n )\n\n if (!isOpen) {\n return null\n }\n\n return (\n <Portal portalRef={portalRef} portalElement={portalElement}>\n <Box\n data-testid=\"modal-overlay\"\n data-overlay\n className={classNames(\n styles.overlay,\n styles[height],\n styles[width],\n exceptionallySetOverlayClassName,\n )}\n /**\n * We're using `onPointerDown` instead of `onClick` to prevent\n * the modal from closing when the click starts inside the modal\n * and ends on the backdrop.\n */\n onPointerDown={hideOnInteractOutside ? handleBackdropClick : undefined}\n ref={backdropRef}\n >\n <FocusLock autoFocus={autoFocus} whiteList={isNotInternalFrame} returnFocus={true}>\n <Dialog\n {...props}\n ref={dialogRef}\n as={Box}\n state={state}\n hideOnEscape={hideOnEscape}\n preventBodyScroll\n borderRadius=\"full\"\n background=\"default\"\n display=\"flex\"\n flexDirection=\"column\"\n overflow=\"hidden\"\n height={height === 'expand' ? 'full' : undefined}\n flexGrow={height === 'expand' ? 1 : 0}\n className={[exceptionallySetClassName, styles.container]}\n // Disable focus lock as we set up our own using ReactFocusLock\n modal={false}\n autoFocus={false}\n autoFocusOnShow={false}\n autoFocusOnHide={false}\n // Disable portal and backdrop as we control their markup\n portal={false}\n backdrop={false}\n hideOnInteractOutside={false}\n >\n <ModalContext.Provider value={contextValue}>\n {children}\n </ModalContext.Provider>\n </Dialog>\n </FocusLock>\n </Box>\n </Portal>\n )\n}\n\n//\n// ModalCloseButton\n//\n\nexport type ModalCloseButtonProps = Omit<\n ButtonProps,\n | 'type'\n | 'children'\n | 'variant'\n | 'icon'\n | 'startIcon'\n | 'endIcon'\n | 'disabled'\n | 'loading'\n | 'tabIndex'\n | 'width'\n | 'align'\n> & {\n /**\n * The descriptive label of the button.\n */\n 'aria-label': string\n}\n\n/**\n * The close button rendered by ModalHeader. Provided independently so that consumers can customize\n * the button's label.\n *\n * @see ModalHeader\n */\nexport function ModalCloseButton(props: ModalCloseButtonProps) {\n const { onDismiss } = React.useContext(ModalContext)\n const [includeInTabOrder, setIncludeInTabOrder] = React.useState(false)\n const [isMounted, setIsMounted] = React.useState(false)\n\n React.useEffect(\n function skipAutoFocus() {\n if (isMounted) {\n setIncludeInTabOrder(true)\n } else {\n setIsMounted(true)\n }\n },\n [isMounted],\n )\n\n return (\n <Button\n {...props}\n variant=\"quaternary\"\n onClick={onDismiss}\n icon={<CloseIcon />}\n tabIndex={includeInTabOrder ? 0 : -1}\n />\n )\n}\n\n//\n// ModalHeader\n//\n\nexport type ModalHeaderProps = DivProps & {\n /**\n * The content of the header.\n */\n children: React.ReactNode\n /**\n * Allows to provide a custom button element, or to omit the close button if set to false.\n * @see ModalCloseButton\n */\n button?: React.ReactNode | boolean\n /**\n * Whether to render a divider line below the header.\n * @default false\n */\n withDivider?: boolean\n /**\n * A escape hatch in case you need to provide a custom class name to the container element.\n */\n exceptionallySetClassName?: string\n}\n\n/**\n * Renders a standard modal header area with an optional close button.\n *\n * @see Modal\n * @see ModalFooter\n * @see ModalBody\n */\nexport function ModalHeader({\n children,\n button = true,\n withDivider = false,\n exceptionallySetClassName,\n ...props\n}: ModalHeaderProps) {\n return (\n <>\n <Box\n {...props}\n as=\"header\"\n paddingLeft=\"large\"\n paddingRight={button === false || button === null ? 'large' : 'small'}\n paddingY=\"small\"\n className={exceptionallySetClassName}\n >\n <Columns space=\"large\" alignY=\"center\">\n <Column width=\"auto\">{children}</Column>\n {button === false || button === null ? (\n <div className={styles.headerContent} />\n ) : (\n <Column\n width=\"content\"\n exceptionallySetClassName={styles.buttonContainer}\n data-testid=\"button-container\"\n >\n {typeof button === 'boolean' ? (\n <ModalCloseButton aria-label=\"Close modal\" autoFocus={false} />\n ) : (\n button\n )}\n </Column>\n )}\n </Columns>\n </Box>\n {withDivider ? <Divider /> : null}\n </>\n )\n}\n\n//\n// ModalBody\n//\n\nexport type ModalBodyProps = DivProps & {\n /**\n * The content of the modal body.\n */\n children: React.ReactNode\n /**\n * A escape hatch in case you need to provide a custom class name to the container element.\n */\n exceptionallySetClassName?: string\n}\n\n/**\n * Renders the body of a modal.\n *\n * Convenient to use alongside ModalHeader and/or ModalFooter as needed. It ensures, among other\n * things, that the contet of the modal body expands or contracts depending on the modal height\n * setting or the size of the content. The body content also automatically scrolls when it's too\n * large to fit the available space.\n *\n * @see Modal\n * @see ModalHeader\n * @see ModalFooter\n */\nexport function ModalBody({ exceptionallySetClassName, children, ...props }: ModalBodyProps) {\n const { height } = React.useContext(ModalContext)\n return (\n <Box\n {...props}\n className={exceptionallySetClassName}\n flexGrow={height === 'expand' ? 1 : 0}\n height={height === 'expand' ? 'full' : undefined}\n overflow=\"auto\"\n >\n <Box padding=\"large\" paddingBottom=\"xxlarge\">\n {children}\n </Box>\n </Box>\n )\n}\n\n//\n// ModalFooter\n//\n\nexport type ModalFooterProps = DivProps & {\n /**\n * The contant of the modal footer.\n */\n children: React.ReactNode\n /**\n * Whether to render a divider line below the footer.\n * @default false\n */\n withDivider?: boolean\n /**\n * A escape hatch in case you need to provide a custom class name to the container element.\n */\n exceptionallySetClassName?: string\n}\n\n/**\n * Renders a standard modal footer area.\n *\n * @see Modal\n * @see ModalHeader\n * @see ModalBody\n */\nexport function ModalFooter({\n exceptionallySetClassName,\n withDivider = false,\n ...props\n}: ModalFooterProps) {\n return (\n <>\n {withDivider ? <Divider /> : null}\n <Box as=\"footer\" {...props} className={exceptionallySetClassName} padding=\"large\" />\n </>\n )\n}\n\n//\n// ModalActions\n//\n\nexport type ModalActionsProps = ModalFooterProps\n\n/**\n * A specific version of the ModalFooter, tailored to showing an inline list of actions (buttons).\n * @see ModalFooter\n */\nexport function ModalActions({ children, ...props }: ModalActionsProps) {\n return (\n <ModalFooter {...props}>\n <Inline align=\"right\" space=\"large\">\n {children}\n </Inline>\n </ModalFooter>\n )\n}\n"],"names":["ModalContext","React","onDismiss","undefined","height","isNotInternalFrame","element","ownerDocument","document","tagName","toLowerCase","ModalCloseButton","props","includeInTabOrder","setIncludeInTabOrder","isMounted","setIsMounted","Button","variant","onClick","icon","CloseIcon","tabIndex","ModalFooter","exceptionallySetClassName","withDivider","Divider","Box","as","className","padding","isOpen","width","exceptionallySetOverlayClassName","autoFocus","hideOnEscape","hideOnInteractOutside","children","portalElement","setOpen","visible","state","useDialogState","open","contextValue","portalRef","dialogRef","backdropRef","handleBackdropClick","event","current","_dialogRef$current","contains","target","_backdropRef$current","stopPropagation","hideOthers","Portal","classNames","styles","overlay","onPointerDown","ref","FocusLock","whiteList","returnFocus","Dialog","preventBodyScroll","borderRadius","background","display","flexDirection","overflow","flexGrow","container","modal","autoFocusOnShow","autoFocusOnHide","portal","backdrop","Provider","value","Inline","align","space","paddingBottom","button","paddingLeft","paddingRight","paddingY","Columns","alignY","Column","headerContent","buttonContainer"],"mappings":"47BA6BMA,EAAeC,gBAAuC,CACxDC,eAAWC,EACXC,OAAQ,eA8FZ,SAASC,EAAmBC,GACxB,QAASA,EAAQC,gBAAkBC,UAA8C,WAAlCF,EAAQG,QAAQC,wBAgKnDC,EAAiBC,GAC7B,MAAMV,UAAEA,GAAcD,aAAiBD,IAChCa,EAAmBC,GAAwBb,YAAe,IAC1Dc,EAAWC,GAAgBf,YAAe,GAajD,OAXAA,aACI,WACQc,EACAD,GAAqB,GAErBE,GAAa,KAGrB,CAACD,IAIDd,gBAACgB,4CACOL,OACJM,QAAQ,aACRC,QAASjB,EACTkB,KAAMnB,gBAACoB,kBACPC,SAAUT,EAAoB,GAAK,cAqJ/BU,SAAYC,0BACxBA,EADwBC,YAExBA,GAAc,KACXb,iCAEH,OACIX,gCACKwB,EAAcxB,gBAACyB,gBAAa,KAC7BzB,gBAAC0B,uCAAIC,GAAG,UAAahB,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,EAAsB,EAAI,EACpCyB,UAAW,CAACL,EAA2BmC,UAAOe,WAE9CC,OAAO,EACPzC,WAAW,EACX0C,iBAAiB,EACjBC,iBAAiB,EAEjBC,QAAQ,EACRC,UAAU,EACV3C,uBAAuB,IAEvBnC,gBAACD,EAAagF,UAASC,MAAOrC,GACzBP,OAjDd,2CA0RcA,SAAEA,KAAazB,iCACxC,OACIX,gBAACsB,qBAAgBX,GACbX,gBAACiF,UAAOC,MAAM,QAAQC,MAAM,SACvB/C,uCAvESb,0BAAEA,EAAFa,SAA6BA,KAAazB,iCAChE,MAAMR,OAAEA,GAAWH,aAAiBD,GACpC,OACIC,gBAAC0B,yCACOf,OACJiB,UAAWL,EACXiD,SAAqB,WAAXrE,EAAsB,EAAI,EACpCA,OAAmB,WAAXA,EAAsB,YAASD,EACvCqE,SAAS,SAETvE,gBAAC0B,OAAIG,QAAQ,QAAQuD,cAAc,WAC9BhD,0FA/EWA,SACxBA,EADwBiD,OAExBA,GAAS,EAFe7D,YAGxBA,GAAc,EAHUD,0BAIxBA,KACGZ,iCAEH,OACIX,gCACIA,gBAAC0B,yCACOf,OACJgB,GAAG,SACH2D,YAAY,QACZC,cAAyB,IAAXF,GAA+B,OAAXA,EAAkB,QAAU,QAC9DG,SAAS,QACT5D,UAAWL,IAEXvB,gBAACyF,WAAQN,MAAM,QAAQO,OAAO,UAC1B1F,gBAAC2F,UAAO5D,MAAM,QAAQK,IACV,IAAXiD,GAA+B,OAAXA,EACjBrF,uBAAK4B,UAAW8B,UAAOkC,gBAEvB5F,gBAAC2F,UACG5D,MAAM,UACNR,0BAA2BmC,UAAOmC,8BACtB,oBAEO,kBAAXR,EACJrF,gBAACU,gBAA4B,cAAcuB,WAAW,IAEtDoD,KAMnB7D,EAAcxB,gBAACyB,gBAAa"}
|
|
1
|
+
{"version":3,"file":"modal.js","sources":["../../src/modal/modal.tsx"],"sourcesContent":["import * as React from 'react'\nimport classNames from 'classnames'\nimport FocusLock from 'react-focus-lock'\nimport { hideOthers } from 'aria-hidden'\n\nimport { Dialog, DialogOptions, useDialogStore, Portal, PortalOptions } from '@ariakit/react'\n\nimport { CloseIcon } from '../icons/close-icon'\nimport { Column, Columns } from '../columns'\nimport { Inline } from '../inline'\nimport { Divider } from '../divider'\nimport { Box } from '../box'\nimport { Button, ButtonProps } from '../button'\n\nimport styles from './modal.module.css'\n\ntype ModalWidth = 'small' | 'medium' | 'large' | 'xlarge' | 'full'\ntype ModalHeightMode = 'expand' | 'fitContent'\n\n//\n// ModalContext\n//\n\ntype ModalContextValue = {\n onDismiss?(this: void): void\n height: ModalHeightMode\n}\n\nconst ModalContext = React.createContext<ModalContextValue>({\n onDismiss: undefined,\n height: 'fitContent',\n})\n\n//\n// Modal container\n//\n\ntype DivProps = Omit<\n React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLDivElement>, HTMLDivElement>,\n 'className' | 'children' | `aria-label` | `aria-labelledby`\n>\n\nexport type ModalProps = DivProps & {\n /**\n * The content of the modal.\n */\n children: React.ReactNode\n /**\n * Whether the modal is open and visible or not.\n */\n isOpen: boolean\n /**\n * Called when the user triggers closing the modal.\n */\n onDismiss?(): void\n /**\n * A descriptive setting for how wide the modal should aim to be, depending on how much space\n * it has on screen.\n * @default 'medium'\n */\n width?: ModalWidth\n /**\n * A descriptive setting for how tall the modal should aim to be.\n *\n * - 'expand': the modal aims to fill most of the available screen height, leaving only a small\n * padding above and below.\n * - 'fitContent': the modal shrinks to the smallest size that allow it to fit its content.\n *\n * In either case, if content does not fit, the content of the main body is set to scroll\n * (provided you use `ModalBody`) so that the modal never has to strech vertically beyond the\n * viewport boundaries.\n *\n * If you do not use `ModalBody`, the modal still prevents overflow, and you are in charge of\n * the inner layout to ensure scroll, or whatever other strategy you may want.\n */\n height?: ModalHeightMode\n /**\n * Whether to set or not the focus initially to the first focusable element inside the modal.\n */\n autoFocus?: boolean\n /**\n * Controls if the modal is dismissed when pressing \"Escape\".\n */\n hideOnEscape?: DialogOptions['hideOnEscape']\n /**\n * Controls if the modal is dismissed when clicking outside the modal body, on the overlay.\n */\n hideOnInteractOutside?: DialogOptions['hideOnInteractOutside']\n /**\n * An escape hatch in case you need to provide a custom class name to the container element.\n */\n exceptionallySetClassName?: string\n /**\n * An escape hatch in case you need to provide a custom class name to the overlay element.\n */\n exceptionallySetOverlayClassName?: string\n /** Defines a string value that labels the current modal for assistive technologies. */\n 'aria-label'?: string\n /** Identifies the element (or elements) that labels the current modal for assistive technologies. */\n 'aria-labelledby'?: string\n /**\n * An HTML element or a memoized callback function that returns an HTML element to be used as\n * the portal element. By default, the portal element will be a `div` element appended to the\n * `document.body`.\n *\n * @default HTMLDivElement\n *\n * @example\n * const [portal, setPortal] = useState(null);\n * <Portal portalElement={portal} />;\n * <div ref={setPortal} />;\n *\n * @example\n * const getPortalElement = useCallback(() => {\n * const div = document.createElement(\"div\");\n * const portalRoot = document.getElementById(\"portal-root\");\n * portalRoot.appendChild(div);\n * return div;\n * }, []);\n * <Portal portalElement={getPortalElement} />;\n */\n portalElement?: PortalOptions['portalElement']\n}\n\nfunction isNotInternalFrame(element: HTMLElement) {\n return !(element.ownerDocument === document && element.tagName.toLowerCase() === 'iframe')\n}\n\n/**\n * Renders a modal that sits on top of the rest of the content in the entire page.\n *\n * Follows the WAI-ARIA Dialog (Modal) Pattern.\n *\n * @see ModalHeader\n * @see ModalFooter\n * @see ModalBody\n */\nexport function Modal({\n isOpen,\n onDismiss,\n height = 'fitContent',\n width = 'medium',\n exceptionallySetClassName,\n exceptionallySetOverlayClassName,\n autoFocus = true,\n hideOnEscape = true,\n hideOnInteractOutside = true,\n children,\n portalElement,\n ...props\n}: ModalProps) {\n const setOpen = React.useCallback(\n (visible: boolean) => {\n if (!visible) {\n onDismiss?.()\n }\n },\n [onDismiss],\n )\n const store = useDialogStore({ open: isOpen, setOpen })\n\n const contextValue: ModalContextValue = React.useMemo(() => ({ onDismiss, height }), [\n onDismiss,\n height,\n ])\n\n const portalRef = React.useRef<HTMLElement | null>(null)\n const dialogRef = React.useRef<HTMLDivElement | null>(null)\n const backdropRef = React.useRef<HTMLDivElement | null>(null)\n const handleBackdropClick = React.useCallback(\n (event: React.MouseEvent) => {\n if (\n // The focus lock element takes up the same space as the backdrop and is where the event bubbles up from,\n // so instead of checking the backdrop as the event target, we need to make sure it's just above the dialog\n !dialogRef.current?.contains(event.target as Node) &&\n // Events fired from other portals will bubble up to the backdrop, even if it isn't a child in the DOM\n backdropRef.current?.contains(event.target as Node)\n ) {\n event.stopPropagation()\n onDismiss?.()\n }\n },\n [onDismiss],\n )\n\n React.useLayoutEffect(\n function disableAccessibilityTreeOutside() {\n if (!isOpen || !portalRef.current) {\n return\n }\n\n return hideOthers(portalRef.current)\n },\n [isOpen],\n )\n\n if (!isOpen) {\n return null\n }\n\n return (\n <Portal portalRef={portalRef} portalElement={portalElement}>\n <Box\n data-testid=\"modal-overlay\"\n data-overlay\n className={classNames(\n styles.overlay,\n styles[height],\n styles[width],\n exceptionallySetOverlayClassName,\n )}\n /**\n * We're using `onPointerDown` instead of `onClick` to prevent\n * the modal from closing when the click starts inside the modal\n * and ends on the backdrop.\n */\n onPointerDown={hideOnInteractOutside ? handleBackdropClick : undefined}\n ref={backdropRef}\n >\n <FocusLock autoFocus={autoFocus} whiteList={isNotInternalFrame} returnFocus={true}>\n <Dialog\n {...props}\n ref={dialogRef}\n as={Box}\n store={store}\n hideOnEscape={hideOnEscape}\n preventBodyScroll\n borderRadius=\"full\"\n background=\"default\"\n display=\"flex\"\n flexDirection=\"column\"\n overflow=\"hidden\"\n height={height === 'expand' ? 'full' : undefined}\n flexGrow={height === 'expand' ? 1 : 0}\n className={[exceptionallySetClassName, styles.container]}\n // Disable focus lock as we set up our own using ReactFocusLock\n modal={false}\n autoFocus={false}\n autoFocusOnShow={false}\n autoFocusOnHide={false}\n // Disable portal and backdrop as we control their markup\n portal={false}\n backdrop={false}\n hideOnInteractOutside={false}\n >\n <ModalContext.Provider value={contextValue}>\n {children}\n </ModalContext.Provider>\n </Dialog>\n </FocusLock>\n </Box>\n </Portal>\n )\n}\n\n//\n// ModalCloseButton\n//\n\nexport type ModalCloseButtonProps = Omit<\n ButtonProps,\n | 'type'\n | 'children'\n | 'variant'\n | 'icon'\n | 'startIcon'\n | 'endIcon'\n | 'disabled'\n | 'loading'\n | 'tabIndex'\n | 'width'\n | 'align'\n> & {\n /**\n * The descriptive label of the button.\n */\n 'aria-label': string\n}\n\n/**\n * The close button rendered by ModalHeader. Provided independently so that consumers can customize\n * the button's label.\n *\n * @see ModalHeader\n */\nexport function ModalCloseButton(props: ModalCloseButtonProps) {\n const { onDismiss } = React.useContext(ModalContext)\n const [includeInTabOrder, setIncludeInTabOrder] = React.useState(false)\n const [isMounted, setIsMounted] = React.useState(false)\n\n React.useEffect(\n function skipAutoFocus() {\n if (isMounted) {\n setIncludeInTabOrder(true)\n } else {\n setIsMounted(true)\n }\n },\n [isMounted],\n )\n\n return (\n <Button\n {...props}\n variant=\"quaternary\"\n onClick={onDismiss}\n icon={<CloseIcon />}\n tabIndex={includeInTabOrder ? 0 : -1}\n />\n )\n}\n\n//\n// ModalHeader\n//\n\nexport type ModalHeaderProps = DivProps & {\n /**\n * The content of the header.\n */\n children: React.ReactNode\n /**\n * Allows to provide a custom button element, or to omit the close button if set to false.\n * @see ModalCloseButton\n */\n button?: React.ReactNode | boolean\n /**\n * Whether to render a divider line below the header.\n * @default false\n */\n withDivider?: boolean\n /**\n * A escape hatch in case you need to provide a custom class name to the container element.\n */\n exceptionallySetClassName?: string\n}\n\n/**\n * Renders a standard modal header area with an optional close button.\n *\n * @see Modal\n * @see ModalFooter\n * @see ModalBody\n */\nexport function ModalHeader({\n children,\n button = true,\n withDivider = false,\n exceptionallySetClassName,\n ...props\n}: ModalHeaderProps) {\n return (\n <>\n <Box\n {...props}\n as=\"header\"\n paddingLeft=\"large\"\n paddingRight={button === false || button === null ? 'large' : 'small'}\n paddingY=\"small\"\n className={exceptionallySetClassName}\n >\n <Columns space=\"large\" alignY=\"center\">\n <Column width=\"auto\">{children}</Column>\n {button === false || button === null ? (\n <div className={styles.headerContent} />\n ) : (\n <Column\n width=\"content\"\n exceptionallySetClassName={styles.buttonContainer}\n data-testid=\"button-container\"\n >\n {typeof button === 'boolean' ? (\n <ModalCloseButton aria-label=\"Close modal\" autoFocus={false} />\n ) : (\n button\n )}\n </Column>\n )}\n </Columns>\n </Box>\n {withDivider ? <Divider /> : null}\n </>\n )\n}\n\n//\n// ModalBody\n//\n\nexport type ModalBodyProps = DivProps & {\n /**\n * The content of the modal body.\n */\n children: React.ReactNode\n /**\n * A escape hatch in case you need to provide a custom class name to the container element.\n */\n exceptionallySetClassName?: string\n}\n\n/**\n * Renders the body of a modal.\n *\n * Convenient to use alongside ModalHeader and/or ModalFooter as needed. It ensures, among other\n * things, that the contet of the modal body expands or contracts depending on the modal height\n * setting or the size of the content. The body content also automatically scrolls when it's too\n * large to fit the available space.\n *\n * @see Modal\n * @see ModalHeader\n * @see ModalFooter\n */\nexport function ModalBody({ exceptionallySetClassName, children, ...props }: ModalBodyProps) {\n const { height } = React.useContext(ModalContext)\n return (\n <Box\n {...props}\n className={exceptionallySetClassName}\n flexGrow={height === 'expand' ? 1 : 0}\n height={height === 'expand' ? 'full' : undefined}\n overflow=\"auto\"\n >\n <Box padding=\"large\" paddingBottom=\"xxlarge\">\n {children}\n </Box>\n </Box>\n )\n}\n\n//\n// ModalFooter\n//\n\nexport type ModalFooterProps = DivProps & {\n /**\n * The contant of the modal footer.\n */\n children: React.ReactNode\n /**\n * Whether to render a divider line below the footer.\n * @default false\n */\n withDivider?: boolean\n /**\n * A escape hatch in case you need to provide a custom class name to the container element.\n */\n exceptionallySetClassName?: string\n}\n\n/**\n * Renders a standard modal footer area.\n *\n * @see Modal\n * @see ModalHeader\n * @see ModalBody\n */\nexport function ModalFooter({\n exceptionallySetClassName,\n withDivider = false,\n ...props\n}: ModalFooterProps) {\n return (\n <>\n {withDivider ? <Divider /> : null}\n <Box as=\"footer\" {...props} className={exceptionallySetClassName} padding=\"large\" />\n </>\n )\n}\n\n//\n// ModalActions\n//\n\nexport type ModalActionsProps = ModalFooterProps\n\n/**\n * A specific version of the ModalFooter, tailored to showing an inline list of actions (buttons).\n * @see ModalFooter\n */\nexport function ModalActions({ children, ...props }: ModalActionsProps) {\n return (\n <ModalFooter {...props}>\n <Inline align=\"right\" space=\"large\">\n {children}\n </Inline>\n </ModalFooter>\n )\n}\n"],"names":["ModalContext","React","onDismiss","undefined","height","isNotInternalFrame","element","ownerDocument","document","tagName","toLowerCase","ModalCloseButton","props","includeInTabOrder","setIncludeInTabOrder","isMounted","setIsMounted","Button","variant","onClick","icon","CloseIcon","tabIndex","ModalFooter","exceptionallySetClassName","withDivider","Divider","Box","as","className","padding","isOpen","width","exceptionallySetOverlayClassName","autoFocus","hideOnEscape","hideOnInteractOutside","children","portalElement","setOpen","visible","store","useDialogStore","open","contextValue","portalRef","dialogRef","backdropRef","handleBackdropClick","event","current","_dialogRef$current","contains","target","_backdropRef$current","stopPropagation","hideOthers","Portal","classNames","styles","overlay","onPointerDown","ref","FocusLock","whiteList","returnFocus","Dialog","preventBodyScroll","borderRadius","background","display","flexDirection","overflow","flexGrow","container","modal","autoFocusOnShow","autoFocusOnHide","portal","backdrop","Provider","value","Inline","align","space","paddingBottom","button","paddingLeft","paddingRight","paddingY","Columns","alignY","Column","headerContent","buttonContainer"],"mappings":"g6BA4BMA,EAAeC,gBAAuC,CACxDC,eAAWC,EACXC,OAAQ,eA8FZ,SAASC,EAAmBC,GACxB,QAASA,EAAQC,gBAAkBC,UAA8C,WAAlCF,EAAQG,QAAQC,wBAgKnDC,EAAiBC,GAC7B,MAAMV,UAAEA,GAAcD,aAAiBD,IAChCa,EAAmBC,GAAwBb,YAAe,IAC1Dc,EAAWC,GAAgBf,YAAe,GAajD,OAXAA,aACI,WACQc,EACAD,GAAqB,GAErBE,GAAa,KAGrB,CAACD,IAIDd,gBAACgB,4CACOL,OACJM,QAAQ,aACRC,QAASjB,EACTkB,KA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cAAcuB,WAAW,IAEtDoD,KAMnB7D,EAAcxB,gBAACyB,gBAAa"}
|
package/lib/tabs/tabs.d.ts
CHANGED
|
@@ -70,28 +70,30 @@ declare type TabPanelProps = {
|
|
|
70
70
|
/** The tabPanel's identifier. This must match its corresponding `<Tab>`'s id */
|
|
71
71
|
id: string;
|
|
72
72
|
/**
|
|
73
|
-
* By default, the tab panel's content is always rendered even when they are not active. This
|
|
74
|
-
* 'active', which renders only when the tab is active, and 'lazy',
|
|
75
|
-
*
|
|
73
|
+
* By default, the tab panel's content is always rendered even when they are not active. This
|
|
74
|
+
* behaviour can be changed to 'active', which renders only when the tab is active, and 'lazy',
|
|
75
|
+
* meaning while inactive tab panels will not be rendered initially, they will remain mounted
|
|
76
|
+
* once they are active until the entire Tabs tree is unmounted.
|
|
76
77
|
*/
|
|
77
78
|
render?: 'always' | 'active' | 'lazy';
|
|
78
79
|
};
|
|
79
80
|
/**
|
|
80
|
-
* Used to define the content to be rendered when a tab is active. Each `<TabPanel>` must have a
|
|
81
|
+
* Used to define the content to be rendered when a tab is active. Each `<TabPanel>` must have a
|
|
82
|
+
* corresponding `<Tab>` component.
|
|
81
83
|
*/
|
|
82
84
|
declare const TabPanel: import("../utils/polymorphism").PolymorphicComponent<"div", TabPanelProps, "omitClassName">;
|
|
83
85
|
declare type TabAwareSlotProps = {
|
|
84
86
|
/**
|
|
85
|
-
* Render prop used to provide the content to be rendered inside the slot. The render prop will
|
|
86
|
-
* called with the current `selectedId`
|
|
87
|
+
* Render prop used to provide the content to be rendered inside the slot. The render prop will
|
|
88
|
+
* be called with the current `selectedId`
|
|
87
89
|
*/
|
|
88
90
|
children: (provided: {
|
|
89
91
|
selectedId?: string | null;
|
|
90
92
|
}) => React.ReactElement | null;
|
|
91
93
|
};
|
|
92
94
|
/**
|
|
93
|
-
* Allows content to be rendered based on the current tab being selected while outside of the
|
|
94
|
-
* component. Can be placed freely within the main `<Tabs>` component.
|
|
95
|
+
* Allows content to be rendered based on the current tab being selected while outside of the
|
|
96
|
+
* TabPanel component. Can be placed freely within the main `<Tabs>` component.
|
|
95
97
|
*/
|
|
96
98
|
declare function TabAwareSlot({ children }: TabAwareSlotProps): React.ReactElement | null;
|
|
97
99
|
export { Tab, Tabs, TabList, TabPanel, TabAwareSlot };
|
package/lib/tabs/tabs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=require("../_virtual/_rollupPluginBabelHelpers.js"),
|
|
1
|
+
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=require("../_virtual/_rollupPluginBabelHelpers.js"),r=require("react"),a=(e(r),e(require("classnames"))),l=require("../utils/polymorphism.js"),n=require("../box/box.js"),o=require("../inline/inline.js"),s=require("@ariakit/react"),c=require("./tabs.module.css.js");const i=["as","children","id","exceptionallySetClassName"],u=["children","space"],d=["children","id","as","render"],b=r.createContext(null),p=l.polymorphicComponent((function(e,l){let{as:n,children:o,id:u,exceptionallySetClassName:d}=e,p=t.objectWithoutProperties(e,i);const f=r.useContext(b);if(!f)return null;const{variant:S,tabStore:m}=f,x=a(d,c.default.tab,c.default["tab-"+S]);return r.createElement(s.Tab,t.objectSpread2(t.objectSpread2({},p),{},{as:n,className:x,id:u,store:m,ref:l}),o)})),f=l.polymorphicComponent((function(e,a){let{children:l,id:n,as:o,render:c="always"}=e,i=t.objectWithoutProperties(e,d);const u=r.useContext(b),[p,f]=r.useState(!1),S=(null==u?void 0:u.tabStore.useState("selectedId"))===n;if(r.useEffect((function(){!p&&S&&f(!0)}),[p,S]),!u)return null;const{tabStore:m}=u;return"always"===c||"active"===c&&S||"lazy"===c&&(S||p)?r.createElement(s.TabPanel,t.objectSpread2(t.objectSpread2({},i),{},{tabId:n,store:m,as:o,ref:a}),l):null}));exports.Tab=p,exports.TabAwareSlot=function({children:e}){const t=r.useContext(b),a=null==t?void 0:t.tabStore.useState("selectedId");return t?e({selectedId:a}):null},exports.TabList=function(e){let{children:a,space:l}=e,i=t.objectWithoutProperties(e,u);const d=r.useContext(b);if(!d)return null;const{tabStore:p,variant:f}=d;return r.createElement(n.Box,null,r.createElement(s.TabList,t.objectSpread2({store:p,as:n.Box,position:"relative",width:"maxContent"},i),r.createElement(n.Box,{className:[c.default.track,c.default["track-"+f]]}),r.createElement(o.Inline,{space:l},a)))},exports.TabPanel=f,exports.Tabs=function({children:e,selectedId:t,defaultSelectedId:a,variant:l="neutral",onSelectedIdChange:n}){const o=s.useTabStore({defaultSelectedId:a,selectedId:t,setSelectedId:n}),c=o.useState("selectedId"),i=r.useMemo(()=>{var e;return{tabStore:o,variant:l,selectedId:null!=(e=null!=t?t:c)?e:null}},[l,o,t,c]);return r.createElement(b.Provider,{value:i},e)};
|
|
2
2
|
//# sourceMappingURL=tabs.js.map
|
package/lib/tabs/tabs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tabs.js","sources":["../../src/tabs/tabs.tsx"],"sourcesContent":["import * as React from 'react'\nimport classNames from 'classnames'\nimport {\n useTabState,\n Tab as BaseTab,\n TabList as BaseTabList,\n TabPanel as BaseTabPanel,\n TabState,\n} from 'ariakit/tab'\nimport { Inline } from '../inline'\nimport { usePrevious } from '../hooks/use-previous'\nimport { polymorphicComponent } from '../utils/polymorphism'\nimport type { Space } from '../utils/common-types'\n\nimport styles from './tabs.module.css'\nimport { Box } from '../box'\n\ntype TabsContextValue = {\n tabState: TabState\n} & Required<Pick<TabsProps, 'variant'>>\n\nconst TabsContext = React.createContext<TabsContextValue | null>(null)\n\ntype TabsProps = {\n /** The `<Tabs>` component must be composed from a `<TabList>` and corresponding `<TabPanel>` components */\n children: React.ReactNode\n /**\n * Determines the look and feel of the tabs.\n */\n variant?: 'themed' | 'neutral'\n /**\n * The id of the selected tab. Assigning a value makes this a\n * controlled component\n */\n selectedId?: string | null\n /**\n * The tab to initially select. This can be used if the component should not\n * be a controlled component but needs to have a tab selected\n */\n defaultSelectedId?: string | null\n /**\n * Called with the tab id when a tab is selected\n */\n onSelectedIdChange?: (selectedId: string | null | undefined) => void\n}\n\n/**\n * Used to group components that compose a set of tabs. There can only be one active tab within the same `<Tabs>` group.\n */\nfunction Tabs({\n children,\n selectedId,\n defaultSelectedId,\n variant = 'neutral',\n onSelectedIdChange,\n}: TabsProps): React.ReactElement {\n const tabState = useTabState({ selectedId, setSelectedId: onSelectedIdChange })\n const previousDefaultSelectedId = usePrevious(defaultSelectedId)\n const { selectedId: actualSelectedId, select } = tabState\n\n React.useEffect(\n function selectDefaultTab() {\n if (\n !selectedId &&\n defaultSelectedId !== previousDefaultSelectedId &&\n defaultSelectedId !== actualSelectedId &&\n defaultSelectedId !== undefined\n ) {\n select(defaultSelectedId)\n }\n },\n [selectedId, defaultSelectedId, actualSelectedId, select, previousDefaultSelectedId],\n )\n\n const memoizedTabState = React.useMemo(\n function memoizeTabState() {\n return {\n tabState,\n variant,\n }\n },\n [variant, tabState],\n )\n\n return <TabsContext.Provider value={memoizedTabState}>{children}</TabsContext.Provider>\n}\n\ntype TabProps = {\n /** The content to render inside of the tab button */\n children: React.ReactNode\n\n /** The tab's identifier. This must match its corresponding `<TabPanel>`'s id */\n id: string\n}\n\n/**\n * Represents the individual tab elements within the group. Each `<Tab>` must have a corresponding `<TabPanel>` component.\n */\nconst Tab = polymorphicComponent<'button', TabProps>(function Tab(\n { as, children, id, exceptionallySetClassName, ...props },\n ref,\n): React.ReactElement | null {\n const tabContextValue = React.useContext(TabsContext)\n\n if (!tabContextValue) {\n return null\n }\n\n const { variant, tabState } = tabContextValue\n\n return (\n <BaseTab\n {...props}\n as={as}\n className={classNames(exceptionallySetClassName, styles.tab, styles[`tab-${variant}`])}\n id={id}\n state={tabState}\n ref={ref}\n >\n {children}\n </BaseTab>\n )\n})\n\ntype TabListProps = (\n | {\n /** Labels the tab list for assistive technologies. This must be provided if `aria-labelledby` is omitted. */\n 'aria-label': string\n }\n | {\n /**\n * One or more element IDs used to label the tab list for assistive technologies. Required if\n * `aria-label` is omitted.\n */\n 'aria-labelledby': string\n }\n | {\n /**\n * For cases where multiple instances of the tab list exists, the duplicates may be marked as aria-hidden\n */\n 'aria-hidden': boolean\n }\n) & {\n /**\n * A list of `<Tab>` elements\n */\n children: React.ReactNode\n\n /**\n * Controls the spacing between tabs\n */\n space?: Space\n}\n\n/**\n * A component used to group `<Tab>` elements together.\n */\nfunction TabList({ children, space, ...props }: TabListProps): React.ReactElement | null {\n const tabContextValue = React.useContext(TabsContext)\n\n if (!tabContextValue) {\n return null\n }\n\n const { tabState, variant } = tabContextValue\n\n return (\n // The extra <Box> prevents <Inline>'s negative margins from collapsing when used in a flex container\n // which will render the track with the wrong height\n <Box>\n <BaseTabList\n state={tabState}\n as={Box}\n position=\"relative\"\n width=\"maxContent\"\n {...props}\n >\n <Box className={[styles.track, styles[`track-${variant}`]]} />\n <Inline space={space}>{children}</Inline>\n </BaseTabList>\n </Box>\n )\n}\n\ntype TabPanelProps = {\n /** The content to be rendered inside the tab */\n children?: React.ReactNode\n\n /** The tabPanel's identifier. This must match its corresponding `<Tab>`'s id */\n id: string\n\n /**\n * By default, the tab panel's content is always rendered even when they are not active. This behaviour can be changed to\n * 'active', which renders only when the tab is active, and 'lazy', meaning while inactive tab panels will not be rendered\n * initially, they will remain mounted once they are active until the entire Tabs tree is unmounted.\n */\n render?: 'always' | 'active' | 'lazy'\n}\n\n/**\n * Used to define the content to be rendered when a tab is active. Each `<TabPanel>` must have a corresponding `<Tab>` component.\n */\nconst TabPanel = polymorphicComponent<'div', TabPanelProps, 'omitClassName'>(function TabPanel(\n { children, id, as, render = 'always', ...props },\n ref,\n): React.ReactElement | null {\n const tabContextValue = React.useContext(TabsContext)\n const [tabRendered, setTabRendered] = React.useState(false)\n const tabIsActive = tabContextValue?.tabState.selectedId === id\n\n React.useEffect(\n function trackTabRenderedState() {\n if (!tabRendered && tabIsActive) {\n setTabRendered(true)\n }\n },\n [tabRendered, tabIsActive],\n )\n\n if (!tabContextValue) {\n return null\n }\n\n const { tabState } = tabContextValue\n const shouldRender =\n render === 'always' ||\n (render === 'active' && tabIsActive) ||\n (render === 'lazy' && (tabIsActive || tabRendered))\n\n return shouldRender ? (\n <BaseTabPanel tabId={id} {...props} state={tabState} as={as} ref={ref}>\n {children}\n </BaseTabPanel>\n ) : null\n})\n\ntype TabAwareSlotProps = {\n /**\n * Render prop used to provide the content to be rendered inside the slot. The render prop will be\n * called with the current `selectedId`\n */\n children: (provided: { selectedId?: string | null }) => React.ReactElement | null\n}\n\n/**\n * Allows content to be rendered based on the current tab being selected while outside of the TabPanel\n * component. Can be placed freely within the main `<Tabs>` component.\n */\nfunction TabAwareSlot({ children }: TabAwareSlotProps): React.ReactElement | null {\n const tabContextValue = React.useContext(TabsContext)\n return tabContextValue ? children({ selectedId: tabContextValue?.tabState.selectedId }) : null\n}\n\nexport { Tab, Tabs, TabList, TabPanel, TabAwareSlot }\n"],"names":["TabsContext","React","Tab","polymorphicComponent","ref","as","children","id","exceptionallySetClassName","props","tabContextValue","variant","tabState","BaseTab","className","classNames","styles","tab","state","TabPanel","render","tabRendered","setTabRendered","tabIsActive","selectedId","BaseTabPanel","tabId","space","Box","BaseTabList","position","width","track","Inline","defaultSelectedId","onSelectedIdChange","useTabState","setSelectedId","previousDefaultSelectedId","usePrevious","actualSelectedId","select","undefined","memoizedTabState","Provider","value"],"mappings":"6jBAqBMA,EAAcC,gBAA6C,MA6E3DC,EAAMC,wBAAyC,WAEjDC,OADAC,GAAEA,EAAFC,SAAMA,EAANC,GAAgBA,EAAhBC,0BAAoBA,KAA8BC,iCAGlD,MAAMC,EAAkBT,aAAiBD,GAEzC,IAAKU,EACD,OAAO,KAGX,MAAMC,QAAEA,EAAFC,SAAWA,GAAaF,EAE9B,OACIT,gBAACY,yCACOJ,OACJJ,GAAIA,EACJS,UAAWC,EAAWP,EAA2BQ,UAAOC,IAAKD,iBAAc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7B,EAEjDX,aACI,WAESuB,GACDU,IAAsBI,GACtBJ,IAAsBM,QACAE,IAAtBR,GAEAO,EAAOP,KAGf,CAACV,EAAYU,EAAmBM,EAAkBC,EAAQH,IAG9D,MAAMK,EAAmB1C,WACrB,WACI,MAAO,CACHW,SAAAA,EACAD,QAAAA,KAGR,CAACA,EAASC,IAGd,OAAOX,gBAACD,EAAY4C,UAASC,MAAOF,GAAmBrC"}
|
|
1
|
+
{"version":3,"file":"tabs.js","sources":["../../src/tabs/tabs.tsx"],"sourcesContent":["import * as React from 'react'\nimport classNames from 'classnames'\nimport {\n useTabStore,\n Tab as BaseTab,\n TabList as BaseTabList,\n TabPanel as BaseTabPanel,\n TabStore,\n} from '@ariakit/react'\nimport { Inline } from '../inline'\nimport { polymorphicComponent } from '../utils/polymorphism'\nimport type { Space } from '../utils/common-types'\n\nimport styles from './tabs.module.css'\nimport { Box } from '../box'\n\ntype TabsContextValue = Required<Pick<TabsProps, 'variant'>> & {\n tabStore: TabStore\n}\n\nconst TabsContext = React.createContext<TabsContextValue | null>(null)\n\ntype TabsProps = {\n /** The `<Tabs>` component must be composed from a `<TabList>` and corresponding `<TabPanel>` components */\n children: React.ReactNode\n /**\n * Determines the look and feel of the tabs.\n */\n variant?: 'themed' | 'neutral'\n /**\n * The id of the selected tab. Assigning a value makes this a\n * controlled component\n */\n selectedId?: string | null\n /**\n * The tab to initially select. This can be used if the component should not\n * be a controlled component but needs to have a tab selected\n */\n defaultSelectedId?: string | null\n /**\n * Called with the tab id when a tab is selected\n */\n onSelectedIdChange?: (selectedId: string | null | undefined) => void\n}\n\n/**\n * Used to group components that compose a set of tabs. There can only be one active tab within the same `<Tabs>` group.\n */\nfunction Tabs({\n children,\n selectedId,\n defaultSelectedId,\n variant = 'neutral',\n onSelectedIdChange,\n}: TabsProps): React.ReactElement {\n const tabStore = useTabStore({\n defaultSelectedId,\n selectedId,\n setSelectedId: onSelectedIdChange,\n })\n const actualSelectedId = tabStore.useState('selectedId')\n\n const memoizedTabState = React.useMemo(\n () => ({ tabStore, variant, selectedId: selectedId ?? actualSelectedId ?? null }),\n [variant, tabStore, selectedId, actualSelectedId],\n )\n return <TabsContext.Provider value={memoizedTabState}>{children}</TabsContext.Provider>\n}\n\ntype TabProps = {\n /** The content to render inside of the tab button */\n children: React.ReactNode\n\n /** The tab's identifier. This must match its corresponding `<TabPanel>`'s id */\n id: string\n}\n\n/**\n * Represents the individual tab elements within the group. Each `<Tab>` must have a corresponding `<TabPanel>` component.\n */\nconst Tab = polymorphicComponent<'button', TabProps>(function Tab(\n { as, children, id, exceptionallySetClassName, ...props },\n ref,\n): React.ReactElement | null {\n const tabContextValue = React.useContext(TabsContext)\n if (!tabContextValue) return null\n\n const { variant, tabStore } = tabContextValue\n const className = classNames(exceptionallySetClassName, styles.tab, styles[`tab-${variant}`])\n\n return (\n <BaseTab {...props} as={as} className={className} id={id} store={tabStore} ref={ref}>\n {children}\n </BaseTab>\n )\n})\n\ntype TabListProps = (\n | {\n /** Labels the tab list for assistive technologies. This must be provided if `aria-labelledby` is omitted. */\n 'aria-label': string\n }\n | {\n /**\n * One or more element IDs used to label the tab list for assistive technologies. Required if\n * `aria-label` is omitted.\n */\n 'aria-labelledby': string\n }\n | {\n /**\n * For cases where multiple instances of the tab list exists, the duplicates may be marked as aria-hidden\n */\n 'aria-hidden': boolean\n }\n) & {\n /**\n * A list of `<Tab>` elements\n */\n children: React.ReactNode\n\n /**\n * Controls the spacing between tabs\n */\n space?: Space\n}\n\n/**\n * A component used to group `<Tab>` elements together.\n */\nfunction TabList({ children, space, ...props }: TabListProps): React.ReactElement | null {\n const tabContextValue = React.useContext(TabsContext)\n\n if (!tabContextValue) {\n return null\n }\n\n const { tabStore, variant } = tabContextValue\n\n return (\n // The extra <Box> prevents <Inline>'s negative margins from collapsing when used in a flex container\n // which will render the track with the wrong height\n <Box>\n <BaseTabList\n store={tabStore}\n as={Box}\n position=\"relative\"\n width=\"maxContent\"\n {...props}\n >\n <Box className={[styles.track, styles[`track-${variant}`]]} />\n <Inline space={space}>{children}</Inline>\n </BaseTabList>\n </Box>\n )\n}\n\ntype TabPanelProps = {\n /** The content to be rendered inside the tab */\n children?: React.ReactNode\n\n /** The tabPanel's identifier. This must match its corresponding `<Tab>`'s id */\n id: string\n\n /**\n * By default, the tab panel's content is always rendered even when they are not active. This\n * behaviour can be changed to 'active', which renders only when the tab is active, and 'lazy',\n * meaning while inactive tab panels will not be rendered initially, they will remain mounted\n * once they are active until the entire Tabs tree is unmounted.\n */\n render?: 'always' | 'active' | 'lazy'\n}\n\n/**\n * Used to define the content to be rendered when a tab is active. Each `<TabPanel>` must have a\n * corresponding `<Tab>` component.\n */\nconst TabPanel = polymorphicComponent<'div', TabPanelProps, 'omitClassName'>(function TabPanel(\n { children, id, as, render = 'always', ...props },\n ref,\n): React.ReactElement | null {\n const tabContextValue = React.useContext(TabsContext)\n const [tabRendered, setTabRendered] = React.useState(false)\n const selectedId = tabContextValue?.tabStore.useState('selectedId')\n const tabIsActive = selectedId === id\n\n React.useEffect(\n function trackTabRenderedState() {\n if (!tabRendered && tabIsActive) {\n setTabRendered(true)\n }\n },\n [tabRendered, tabIsActive],\n )\n\n if (!tabContextValue) {\n return null\n }\n\n const { tabStore } = tabContextValue\n const shouldRender =\n render === 'always' ||\n (render === 'active' && tabIsActive) ||\n (render === 'lazy' && (tabIsActive || tabRendered))\n\n return shouldRender ? (\n <BaseTabPanel {...props} tabId={id} store={tabStore} as={as} ref={ref}>\n {children}\n </BaseTabPanel>\n ) : null\n})\n\ntype TabAwareSlotProps = {\n /**\n * Render prop used to provide the content to be rendered inside the slot. The render prop will\n * be called with the current `selectedId`\n */\n children: (provided: { selectedId?: string | null }) => React.ReactElement | null\n}\n\n/**\n * Allows content to be rendered based on the current tab being selected while outside of the\n * TabPanel component. Can be placed freely within the main `<Tabs>` component.\n */\nfunction TabAwareSlot({ children }: TabAwareSlotProps): React.ReactElement | null {\n const tabContextValue = React.useContext(TabsContext)\n const selectedId = tabContextValue?.tabStore.useState('selectedId')\n return tabContextValue ? children({ selectedId }) : null\n}\n\nexport { Tab, Tabs, TabList, TabPanel, TabAwareSlot }\n"],"names":["TabsContext","React","Tab","polymorphicComponent","ref","as","children","id","exceptionallySetClassName","props","tabContextValue","variant","tabStore","className","classNames","styles","tab","BaseTab","store","TabPanel","render","tabRendered","setTabRendered","tabIsActive","useState","BaseTabPanel","tabId","selectedId","space","Box","BaseTabList","position","width","track","Inline","defaultSelectedId","onSelectedIdChange","useTabStore","setSelectedId","actualSelectedId","memoizedTabState","Provider","value"],"mappings":"6gBAoBMA,EAAcC,gBAA6C,MA4D3DC,EAAMC,wBAAyC,WAEjDC,OADAC,GAAEA,EAAFC,SAAMA,EAANC,GAAgBA,EAAhBC,0BAAoBA,KAA8BC,iCAGlD,MAAMC,EAAkBT,aAAiBD,GACzC,IAAKU,EAAiB,OAAO,KAE7B,MAAMC,QAAEA,EAAFC,SAAWA,GAAaF,EACxBG,EAAYC,EAAWN,EAA2BO,UAAOC,IAAKD,iBAAcJ,IAElF,OACIV,gBAACgB,yCAAYR,OAAOJ,GAAIA,EAAIQ,UAAWA,EAAWN,GAAIA,EAAIW,MAAON,EAAUR,IAAKA,IAC3EE,MAqFPa,EAAWhB,wBAA4D,WAEzEC,OADAE,SAAEA,EAAFC,GAAYA,EAAZF,GAAgBA,EAAhBe,OAAoBA,EAAS,YAAaX,iCAG1C,MAAMC,EAAkBT,aAAiBD,IAClCqB,EAAaC,GAAkBrB,YAAe,GAE/CsB,SADab,SAAAA,EAAiBE,SAASY,SAAS,iBACnBjB,EAWnC,GATAN,aACI,YACSoB,GAAeE,GAChBD,GAAe,KAGvB,CAACD,EAAaE,KAGbb,EACD,OAAO,KAGX,MAAME,SAAEA,GAAaF,EAMrB,MAJe,WAAXU,GACY,WAAXA,GAAuBG,GACZ,SAAXH,IAAsBG,GAAeF,GAGtCpB,gBAACwB,8CAAiBhB,OAAOiB,MAAOnB,EAAIW,MAAON,EAAUP,GAAIA,EAAID,IAAKA,IAC7DE,GAEL,2CAeR,UAAsBA,SAAEA,IACpB,MAAMI,EAAkBT,aAAiBD,GACnC2B,QAAajB,SAAAA,EAAiBE,SAASY,SAAS,cACtD,OAAOd,EAAkBJ,EAAS,CAAEqB,WAAAA,IAAgB,sBAjGxD,gBAAiBrB,SAAEA,EAAFsB,MAAYA,KAAUnB,iCACnC,MAAMC,EAAkBT,aAAiBD,GAEzC,IAAKU,EACD,OAAO,KAGX,MAAME,SAAEA,EAAFD,QAAYA,GAAYD,EAE9B,OAGIT,gBAAC4B,WACG5B,gBAAC6B,2BACGZ,MAAON,EACPP,GAAIwB,MACJE,SAAS,WACTC,MAAM,cACFvB,GAEJR,gBAAC4B,OAAIhB,UAAW,CAACE,UAAOkB,MAAOlB,mBAAgBJ,MAC/CV,gBAACiC,UAAON,MAAOA,GAAQtB,sCAvGvC,UAAcA,SACVA,EADUqB,WAEVA,EAFUQ,kBAGVA,EAHUxB,QAIVA,EAAU,UAJAyB,mBAKVA,IAEA,MAAMxB,EAAWyB,cAAY,CACzBF,kBAAAA,EACAR,WAAAA,EACAW,cAAeF,IAEbG,EAAmB3B,EAASY,SAAS,cAErCgB,EAAmBvC,UACrB,KAAA,MAAA,MAAO,CAAEW,SAAAA,EAAUD,QAAAA,EAASgB,0BAAYA,EAAAA,EAAcY,KAAoB,OAC1E,CAAC5B,EAASC,EAAUe,EAAYY,IAEpC,OAAOtC,gBAACD,EAAYyC,UAASC,MAAOF,GAAmBlC"}
|
package/lib/toast/use-toasts.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("../_virtual/_rollupPluginBabelHelpers.js"),s=(e=require("react"))&&"object"==typeof e&&"default"in e?e.default:e,o=require("../box/box.js"),a=require("../stack/stack.js"),n=require("../utils/common-helpers.js"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("../_virtual/_rollupPluginBabelHelpers.js"),s=(e=require("react"))&&"object"==typeof e&&"default"in e?e.default:e,o=require("../box/box.js"),a=require("../stack/stack.js"),n=require("@ariakit/react"),i=require("../utils/common-helpers.js"),r=require("./toast.module.css.js"),u=require("./static-toast.js"),c=require("./toast-animation.js");const l=["toastId"],d=s.forwardRef((function({message:e,description:o,icon:a,action:n,autoDismissDelay:i,dismissLabel:r,showDismissButton:c=!0,toastId:l,onDismiss:d,onRemoveToast:m},f){const[p,b]=s.useState(Boolean(i)),j=s.useRef(),k=s.useCallback((function(){b(!0)}),[]),v=s.useCallback((function(){b(!1),clearTimeout(j.current),j.current=void 0}),[]),x=s.useCallback((function(){m(l),null==d||d()}),[d,m,l]);s.useEffect((function(){if(p&&i)return j.current=window.setTimeout(x,1e3*i),v}),[i,x,v,p]);const C=s.useMemo(()=>u.isActionObject(n)?t.objectSpread2(t.objectSpread2({},n),{},{onClick:function(){n&&(n.onClick(),x())}}):n,[n,x]);return s.createElement(u.StaticToast,{ref:f,message:e,description:o,icon:a,action:C,onDismiss:c?x:void 0,dismissLabel:r,onMouseEnter:v,onMouseLeave:k})})),m=s.createContext(()=>()=>{});function f(){return s.useContext(m)}exports.Toast=function(e){const t=f(),o=s.useRef(e);return s.useEffect(()=>t(o.current),[t]),null},exports.ToastsProvider=function({children:e,padding:u="large",defaultAutoDismissDelay:f=10,defaultDismissLabel:p="Close"}){const[b,j]=s.useState([]),{mappedRef:k,animateRemove:v}=c.useToastsAnimation(),x=s.useCallback((function(e){v(e,()=>{j(t=>{const s=t.findIndex(t=>t.toastId===e);if(s<0)return t;const o=[...t];return o.splice(s,1),o})})}),[v]),C=s.useCallback((function(e){const s=i.generateElementId("toast"),o=t.objectSpread2(t.objectSpread2({autoDismissDelay:f,dismissLabel:p},e),{},{toastId:s});return j(e=>[...e,o]),()=>x(s)}),[f,p,x]);return s.createElement(m.Provider,{value:C},e,s.createElement(n.Portal,null,0===b.length?null:s.createElement(o.Box,{className:r.default.stackedToastsView,position:"fixed",width:"full",paddingX:u,paddingBottom:u},s.createElement(a.Stack,{space:"medium"},b.map(e=>{let{toastId:o}=e,a=t.objectWithoutProperties(e,l);return s.createElement(d,t.objectSpread2({key:o,ref:k(o),toastId:o,onRemoveToast:x},a))})))))},exports.useToasts=f;
|
|
2
2
|
//# sourceMappingURL=use-toasts.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-toasts.js","sources":["../../src/toast/use-toasts.tsx"],"sourcesContent":["import React from 'react'\nimport { Portal } from 'ariakit/portal'\n\nimport { generateElementId } from '../utils/common-helpers'\nimport { Box } from '../box'\nimport { Stack } from '../stack'\nimport { isActionObject, StaticToast, StaticToastProps } from './static-toast'\n\nimport styles from './toast.module.css'\n\nimport type { Space } from '../utils/common-types'\nimport { useToastsAnimation } from './toast-animation'\n\n/**\n * The props needed to fire up a new notification toast.\n */\ntype ToastProps = StaticToastProps & {\n /**\n * The number of seconds the toast is expected to be shown before it is dismissed automatically,\n * or false to disable auto-dismiss.\n *\n * It defaults to whatever is the autoDismissDelay set in the ToastsProvider.\n */\n autoDismissDelay?: number | false\n\n /**\n * The label for the button that dismisses the toast.\n *\n * It defaults to the value set in the ToastsProvider, but individual toasts can have a\n * different value if needed.\n */\n dismissLabel?: string\n\n /**\n * Whether to show the dismiss button or not.\n *\n * Use this value with care. If combined with disabling `autoDismissDelay`, it may leave you\n * with toasts that the user won't be able to dismiss at will. It then is your responsibility to\n * dismiss the toast by calling the function returned by `showToast`.\n */\n showDismissButton?: boolean\n}\n\n//\n// InternalToast component and its props\n//\n\ntype InternalToastProps = Omit<ToastProps, 'autoDismissDelay' | 'dismissLabel'> &\n Required<Pick<ToastProps, 'autoDismissDelay' | 'dismissLabel'>> & {\n toastId: string\n onRemoveToast: (toastId: string) => void\n }\n\n/** @private */\nconst InternalToast = React.forwardRef<HTMLDivElement, InternalToastProps>(function InternalToast(\n {\n message,\n description,\n icon,\n action,\n autoDismissDelay,\n dismissLabel,\n showDismissButton = true,\n toastId,\n onDismiss,\n onRemoveToast,\n },\n ref,\n) {\n const [timeoutRunning, setTimeoutRunning] = React.useState(Boolean(autoDismissDelay))\n const timeoutRef = React.useRef<number | undefined>()\n\n const startTimeout = React.useCallback(function startTimeout() {\n setTimeoutRunning(true)\n }, [])\n\n const stopTimeout = React.useCallback(function stopTimeout() {\n setTimeoutRunning(false)\n clearTimeout(timeoutRef.current)\n timeoutRef.current = undefined\n }, [])\n\n const removeToast = React.useCallback(\n function removeToast() {\n onRemoveToast(toastId)\n onDismiss?.()\n },\n [onDismiss, onRemoveToast, toastId],\n )\n\n React.useEffect(\n function setupAutoDismiss() {\n if (!timeoutRunning || !autoDismissDelay) return\n timeoutRef.current = window.setTimeout(removeToast, autoDismissDelay * 1000)\n return stopTimeout\n },\n [autoDismissDelay, removeToast, stopTimeout, timeoutRunning],\n )\n\n /**\n * If the action is toast action object and not a custom element,\n * the `onClick` property is wrapped in another handler responsible\n * for removing the toast when the action is triggered.\n */\n const actionWithCustomActionHandler = React.useMemo(() => {\n if (!isActionObject(action)) {\n return action\n }\n\n return {\n ...action,\n onClick: function handleActionClick() {\n if (!action) {\n return\n }\n\n action.onClick()\n removeToast()\n },\n }\n }, [action, removeToast])\n\n return (\n <StaticToast\n ref={ref}\n message={message}\n description={description}\n icon={icon}\n action={actionWithCustomActionHandler}\n onDismiss={showDismissButton ? removeToast : undefined}\n dismissLabel={dismissLabel}\n // @ts-expect-error\n onMouseEnter={stopTimeout}\n onMouseLeave={startTimeout}\n />\n )\n})\n\n//\n// Internal state and context\n//\n\ntype InternalToastEntry = Omit<InternalToastProps, 'onRemoveToast'>\ntype ToastsList = readonly InternalToastEntry[]\n\ntype ShowToastAction = (props: ToastProps) => () => void\nconst ToastsContext = React.createContext<ShowToastAction>(() => () => undefined)\n\n/**\n * The props needed by the ToastsProvider component.\n *\n * @see ToastsProvider\n */\ntype ToastsProviderProps = {\n /**\n * The default label to apply to toast dismiss buttons.\n *\n * This is useful in environments that need locatization, so you do not need to pass the same\n * translated label every time you trigger a toast.\n *\n * However, you can still apply a different label to a specific toast, by passing a different\n * value when calling showToast.\n *\n * @default 'Close'\n */\n defaultDismissLabel?: string\n\n /**\n * The default number of seconds after which the toast will be dismissed automatically.\n *\n * You can pass a different value to a specific toast when calling `showToast`. You can even\n * pass `false` if you want a certain toast to never be dismissed automatically.\n *\n * @default 10 (seconds)\n */\n defaultAutoDismissDelay?: number\n\n /**\n * The padding used to separate the toasts from the viewport borders.\n *\n * @default 'large'\n */\n padding?: Space\n\n /**\n * The app wrapped by the provider.\n */\n children: NonNullable<React.ReactNode>\n}\n\n/**\n * Provides the state management and rendering of the toasts currently active.\n *\n * You need to render this near the top of your app components tree, in order to `useToasts`.\n *\n * @see useToasts\n */\nfunction ToastsProvider({\n children,\n padding = 'large',\n defaultAutoDismissDelay = 10 /* seconds */,\n defaultDismissLabel = 'Close',\n}: ToastsProviderProps) {\n const [toasts, setToasts] = React.useState<ToastsList>([])\n const { mappedRef, animateRemove } = useToastsAnimation()\n\n const removeToast = React.useCallback(\n function onRemoveToast(toastId: string) {\n animateRemove(toastId, () => {\n setToasts((list) => {\n const index = list.findIndex((n) => n.toastId === toastId)\n if (index < 0) return list\n const copy = [...list]\n copy.splice(index, 1)\n return copy\n })\n })\n },\n [animateRemove],\n )\n\n const showToast = React.useCallback(\n function showToast(props: ToastProps) {\n const toastId = generateElementId('toast')\n const newToast: InternalToastEntry = {\n autoDismissDelay: defaultAutoDismissDelay,\n dismissLabel: defaultDismissLabel,\n ...props,\n toastId,\n }\n setToasts((list) => [...list, newToast])\n return () => removeToast(toastId)\n },\n [defaultAutoDismissDelay, defaultDismissLabel, removeToast],\n )\n\n return (\n <ToastsContext.Provider value={showToast}>\n {children}\n <Portal>\n {toasts.length === 0 ? null : (\n <Box\n className={styles.stackedToastsView}\n position=\"fixed\"\n width=\"full\"\n paddingX={padding}\n paddingBottom={padding}\n >\n <Stack space=\"medium\">\n {toasts.map(({ toastId, ...props }) => (\n <InternalToast\n key={toastId}\n ref={mappedRef(toastId)}\n toastId={toastId}\n onRemoveToast={removeToast}\n {...props}\n />\n ))}\n </Stack>\n </Box>\n )}\n </Portal>\n </ToastsContext.Provider>\n )\n}\n\n/**\n * Provides a function `showToast` that shows a new toast every time you call it.\n *\n * ```jsx\n * const showToast = useToasts()\n *\n * <button onClick={() => showToast({ message: 'Hello' })}>\n * Say hello\n * </button>\n * ```\n *\n * All toasts fired via this function are rendered in a global fixed location, and stacked one on\n * top of the other.\n *\n * When called, `showToast` returns a function that dismisses the toast when called.\n *\n * @see ToastsProvider\n */\nfunction useToasts() {\n return React.useContext(ToastsContext)\n}\n\n/**\n * Adds a toast to be rendered, stacked alongside any other currently active toasts.\n *\n * For most situations, you should prefer to use the `showToast` function obtained from `useToasts`.\n * This component is provided for convenience to render toasts in the markup, but it has some\n * peculiarities, which are discussed below.\n *\n * Internally, this calls `showToast`. It is provided for two reasons:\n *\n * 1. Convenience, when you want to fire a toast in markup/jsx code. Keep in mind, though, that\n * toasts rendered in this way will be removed from view when the context where it is rendered\n * is unmounted. Unlike toasts fired with `showToast`, which will normally be dismissed, either\n * by the user or after a delay. They'll still be animated on their way out, though.\n * 2. When combined with disabling dismissing it (e.g. `showDismissButton={false}` and\n * `autoDismissDelay={false}` it provides a way to show \"permanent\" toasts that only go away when\n * the component ceases to be rendered).\n *\n * This is useful for cases when the consumer wants to control when a toast is visible, and to keep\n * it visible based on an app-specific condition.\n *\n * Something important to note about this component is that it triggers the toast based on the props\n * passed when first rendered, and it does not update the toast if these props change on subsequent\n * renders. In this sense, this is an imperative component, more than a descriptive one. This is\n * done to simplify the internals, and to keep it in line with how `showToast` works: you fire up a\n * toast imperatively, and you loose control over it. It remains rendered according to the props you\n * first passed.\n *\n * @see useToasts\n */\nfunction Toast(props: ToastProps) {\n const showToast = useToasts()\n const propsRef = React.useRef<ToastProps>(props)\n React.useEffect(() => {\n const dismissToast = showToast(propsRef.current)\n return dismissToast\n }, [showToast])\n return null\n}\n\nexport { Toast, ToastsProvider, useToasts }\nexport type { ToastProps, ToastsProviderProps }\n"],"names":["InternalToast","React","forwardRef","message","description","icon","action","autoDismissDelay","dismissLabel","showDismissButton","toastId","onDismiss","onRemoveToast","ref","timeoutRunning","setTimeoutRunning","useState","Boolean","timeoutRef","useRef","startTimeout","useCallback","stopTimeout","clearTimeout","current","undefined","removeToast","useEffect","window","setTimeout","actionWithCustomActionHandler","useMemo","isActionObject","onClick","StaticToast","onMouseEnter","onMouseLeave","ToastsContext","createContext","useToasts","useContext","props","showToast","propsRef","children","padding","defaultAutoDismissDelay","defaultDismissLabel","toasts","setToasts","mappedRef","animateRemove","useToastsAnimation","list","index","findIndex","n","copy","splice","generateElementId","newToast","Provider","value","Portal","length","Box","className","styles","stackedToastsView","position","width","paddingX","paddingBottom","Stack","space","map","_ref","key"],"mappings":"4bAsDMA,EAAgBC,EAAMC,YAA+C,UACvEC,QACIA,EADJC,YAEIA,EAFJC,KAGIA,EAHJC,OAIIA,EAJJC,iBAKIA,EALJC,aAMIA,EANJC,kBAOIA,GAAoB,EAPxBC,QAQIA,EARJC,UASIA,EATJC,cAUIA,GAEJC,GAEA,MAAOC,EAAgBC,GAAqBd,EAAMe,SAASC,QAAQV,IAC7DW,EAAajB,EAAMkB,SAEnBC,EAAenB,EAAMoB,aAAY,WACnCN,GAAkB,KACnB,IAEGO,EAAcrB,EAAMoB,aAAY,WAClCN,GAAkB,GAClBQ,aAAaL,EAAWM,SACxBN,EAAWM,aAAUC,IACtB,IAEGC,EAAczB,EAAMoB,aACtB,WACIT,EAAcF,SACdC,GAAAA,MAEJ,CAACA,EAAWC,EAAeF,IAG/BT,EAAM0B,WACF,WACI,GAAKb,GAAmBP,EAExB,OADAW,EAAWM,QAAUI,OAAOC,WAAWH,EAAgC,IAAnBnB,GAC7Ce,IAEX,CAACf,EAAkBmB,EAAaJ,EAAaR,IAQjD,MAAMgB,EAAgC7B,EAAM8B,QAAQ,IAC3CC,iBAAe1B,sCAKbA,OACH2B,QAAS,WACA3B,IAILA,E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,QACTC,MAAM,OACNC,SAAU1B,EACV2B,cAAe3B,GAEf5C,gBAACwE,SAAMC,MAAM,UACR1B,EAAO2B,IAAIC,IAAA,IAAClE,QAAEA,KAAY+B,iCAAf,OACRxC,gBAACD,mBACG6E,IAAKnE,EACLG,IAAKqC,EAAUxC,GACfA,QAASA,EACTE,cAAec,GACXe"}
|
|
1
|
+
{"version":3,"file":"use-toasts.js","sources":["../../src/toast/use-toasts.tsx"],"sourcesContent":["import React from 'react'\nimport { Portal } from '@ariakit/react'\n\nimport { generateElementId } from '../utils/common-helpers'\nimport { Box } from '../box'\nimport { Stack } from '../stack'\nimport { isActionObject, StaticToast, StaticToastProps } from './static-toast'\n\nimport styles from './toast.module.css'\n\nimport type { Space } from '../utils/common-types'\nimport { useToastsAnimation } from './toast-animation'\n\n/**\n * The props needed to fire up a new notification toast.\n */\ntype ToastProps = StaticToastProps & {\n /**\n * The number of seconds the toast is expected to be shown before it is dismissed automatically,\n * or false to disable auto-dismiss.\n *\n * It defaults to whatever is the autoDismissDelay set in the ToastsProvider.\n */\n autoDismissDelay?: number | false\n\n /**\n * The label for the button that dismisses the toast.\n *\n * It defaults to the value set in the ToastsProvider, but individual toasts can have a\n * different value if needed.\n */\n dismissLabel?: string\n\n /**\n * Whether to show the dismiss button or not.\n *\n * Use this value with care. If combined with disabling `autoDismissDelay`, it may leave you\n * with toasts that the user won't be able to dismiss at will. It then is your responsibility to\n * dismiss the toast by calling the function returned by `showToast`.\n */\n showDismissButton?: boolean\n}\n\n//\n// InternalToast component and its props\n//\n\ntype InternalToastProps = Omit<ToastProps, 'autoDismissDelay' | 'dismissLabel'> &\n Required<Pick<ToastProps, 'autoDismissDelay' | 'dismissLabel'>> & {\n toastId: string\n onRemoveToast: (toastId: string) => void\n }\n\n/** @private */\nconst InternalToast = React.forwardRef<HTMLDivElement, InternalToastProps>(function InternalToast(\n {\n message,\n description,\n icon,\n action,\n autoDismissDelay,\n dismissLabel,\n showDismissButton = true,\n toastId,\n onDismiss,\n onRemoveToast,\n },\n ref,\n) {\n const [timeoutRunning, setTimeoutRunning] = React.useState(Boolean(autoDismissDelay))\n const timeoutRef = React.useRef<number | undefined>()\n\n const startTimeout = React.useCallback(function startTimeout() {\n setTimeoutRunning(true)\n }, [])\n\n const stopTimeout = React.useCallback(function stopTimeout() {\n setTimeoutRunning(false)\n clearTimeout(timeoutRef.current)\n timeoutRef.current = undefined\n }, [])\n\n const removeToast = React.useCallback(\n function removeToast() {\n onRemoveToast(toastId)\n onDismiss?.()\n },\n [onDismiss, onRemoveToast, toastId],\n )\n\n React.useEffect(\n function setupAutoDismiss() {\n if (!timeoutRunning || !autoDismissDelay) return\n timeoutRef.current = window.setTimeout(removeToast, autoDismissDelay * 1000)\n return stopTimeout\n },\n [autoDismissDelay, removeToast, stopTimeout, timeoutRunning],\n )\n\n /**\n * If the action is toast action object and not a custom element,\n * the `onClick` property is wrapped in another handler responsible\n * for removing the toast when the action is triggered.\n */\n const actionWithCustomActionHandler = React.useMemo(() => {\n if (!isActionObject(action)) {\n return action\n }\n\n return {\n ...action,\n onClick: function handleActionClick() {\n if (!action) {\n return\n }\n\n action.onClick()\n removeToast()\n },\n }\n }, [action, removeToast])\n\n return (\n <StaticToast\n ref={ref}\n message={message}\n description={description}\n icon={icon}\n action={actionWithCustomActionHandler}\n onDismiss={showDismissButton ? removeToast : undefined}\n dismissLabel={dismissLabel}\n // @ts-expect-error\n onMouseEnter={stopTimeout}\n onMouseLeave={startTimeout}\n />\n )\n})\n\n//\n// Internal state and context\n//\n\ntype InternalToastEntry = Omit<InternalToastProps, 'onRemoveToast'>\ntype ToastsList = readonly InternalToastEntry[]\n\ntype ShowToastAction = (props: ToastProps) => () => void\nconst ToastsContext = React.createContext<ShowToastAction>(() => () => undefined)\n\n/**\n * The props needed by the ToastsProvider component.\n *\n * @see ToastsProvider\n */\ntype ToastsProviderProps = {\n /**\n * The default label to apply to toast dismiss buttons.\n *\n * This is useful in environments that need locatization, so you do not need to pass the same\n * translated label every time you trigger a toast.\n *\n * However, you can still apply a different label to a specific toast, by passing a different\n * value when calling showToast.\n *\n * @default 'Close'\n */\n defaultDismissLabel?: string\n\n /**\n * The default number of seconds after which the toast will be dismissed automatically.\n *\n * You can pass a different value to a specific toast when calling `showToast`. You can even\n * pass `false` if you want a certain toast to never be dismissed automatically.\n *\n * @default 10 (seconds)\n */\n defaultAutoDismissDelay?: number\n\n /**\n * The padding used to separate the toasts from the viewport borders.\n *\n * @default 'large'\n */\n padding?: Space\n\n /**\n * The app wrapped by the provider.\n */\n children: NonNullable<React.ReactNode>\n}\n\n/**\n * Provides the state management and rendering of the toasts currently active.\n *\n * You need to render this near the top of your app components tree, in order to `useToasts`.\n *\n * @see useToasts\n */\nfunction ToastsProvider({\n children,\n padding = 'large',\n defaultAutoDismissDelay = 10 /* seconds */,\n defaultDismissLabel = 'Close',\n}: ToastsProviderProps) {\n const [toasts, setToasts] = React.useState<ToastsList>([])\n const { mappedRef, animateRemove } = useToastsAnimation()\n\n const removeToast = React.useCallback(\n function onRemoveToast(toastId: string) {\n animateRemove(toastId, () => {\n setToasts((list) => {\n const index = list.findIndex((n) => n.toastId === toastId)\n if (index < 0) return list\n const copy = [...list]\n copy.splice(index, 1)\n return copy\n })\n })\n },\n [animateRemove],\n )\n\n const showToast = React.useCallback(\n function showToast(props: ToastProps) {\n const toastId = generateElementId('toast')\n const newToast: InternalToastEntry = {\n autoDismissDelay: defaultAutoDismissDelay,\n dismissLabel: defaultDismissLabel,\n ...props,\n toastId,\n }\n setToasts((list) => [...list, newToast])\n return () => removeToast(toastId)\n },\n [defaultAutoDismissDelay, defaultDismissLabel, removeToast],\n )\n\n return (\n <ToastsContext.Provider value={showToast}>\n {children}\n <Portal>\n {toasts.length === 0 ? null : (\n <Box\n className={styles.stackedToastsView}\n position=\"fixed\"\n width=\"full\"\n paddingX={padding}\n paddingBottom={padding}\n >\n <Stack space=\"medium\">\n {toasts.map(({ toastId, ...props }) => (\n <InternalToast\n key={toastId}\n ref={mappedRef(toastId)}\n toastId={toastId}\n onRemoveToast={removeToast}\n {...props}\n />\n ))}\n </Stack>\n </Box>\n )}\n </Portal>\n </ToastsContext.Provider>\n )\n}\n\n/**\n * Provides a function `showToast` that shows a new toast every time you call it.\n *\n * ```jsx\n * const showToast = useToasts()\n *\n * <button onClick={() => showToast({ message: 'Hello' })}>\n * Say hello\n * </button>\n * ```\n *\n * All toasts fired via this function are rendered in a global fixed location, and stacked one on\n * top of the other.\n *\n * When called, `showToast` returns a function that dismisses the toast when called.\n *\n * @see ToastsProvider\n */\nfunction useToasts() {\n return React.useContext(ToastsContext)\n}\n\n/**\n * Adds a toast to be rendered, stacked alongside any other currently active toasts.\n *\n * For most situations, you should prefer to use the `showToast` function obtained from `useToasts`.\n * This component is provided for convenience to render toasts in the markup, but it has some\n * peculiarities, which are discussed below.\n *\n * Internally, this calls `showToast`. It is provided for two reasons:\n *\n * 1. Convenience, when you want to fire a toast in markup/jsx code. Keep in mind, though, that\n * toasts rendered in this way will be removed from view when the context where it is rendered\n * is unmounted. Unlike toasts fired with `showToast`, which will normally be dismissed, either\n * by the user or after a delay. They'll still be animated on their way out, though.\n * 2. When combined with disabling dismissing it (e.g. `showDismissButton={false}` and\n * `autoDismissDelay={false}` it provides a way to show \"permanent\" toasts that only go away when\n * the component ceases to be rendered).\n *\n * This is useful for cases when the consumer wants to control when a toast is visible, and to keep\n * it visible based on an app-specific condition.\n *\n * Something important to note about this component is that it triggers the toast based on the props\n * passed when first rendered, and it does not update the toast if these props change on subsequent\n * renders. In this sense, this is an imperative component, more than a descriptive one. This is\n * done to simplify the internals, and to keep it in line with how `showToast` works: you fire up a\n * toast imperatively, and you loose control over it. It remains rendered according to the props you\n * first passed.\n *\n * @see useToasts\n */\nfunction Toast(props: ToastProps) {\n const showToast = useToasts()\n const propsRef = React.useRef<ToastProps>(props)\n React.useEffect(() => {\n const dismissToast = showToast(propsRef.current)\n return dismissToast\n }, [showToast])\n return null\n}\n\nexport { Toast, ToastsProvider, useToasts }\nexport type { ToastProps, ToastsProviderProps }\n"],"names":["InternalToast","React","forwardRef","message","description","icon","action","autoDismissDelay","dismissLabel","showDismissButton","toastId","onDismiss","onRemoveToast","ref","timeoutRunning","setTimeoutRunning","useState","Boolean","timeoutRef","useRef","startTimeout","useCallback","stopTimeout","clearTimeout","current","undefined","removeToast","useEffect","window","setTimeout","actionWithCustomActionHandler","useMemo","isActionObject","onClick","StaticToast","onMouseEnter","onMouseLeave","ToastsContext","createContext","useToasts","useContext","props","showToast","propsRef","children","padding","defaultAutoDismissDelay","defaultDismissLabel","toasts","setToasts","mappedRef","animateRemove","useToastsAnimation","list","index","findIndex","n","copy","splice","generateElementId","newToast","Provider","value","Portal","length","Box","className","styles","stackedToastsView","position","width","paddingX","paddingBottom","Stack","space","map","_ref","key"],"mappings":"4bAsDMA,EAAgBC,EAAMC,YAA+C,UACvEC,QACIA,EADJC,YAEIA,EAFJC,KAGIA,EAHJC,OAIIA,EAJJC,iBAKIA,EALJC,aAMIA,EANJC,kBAOIA,GAAoB,EAPxBC,QAQIA,EARJC,UASIA,EATJC,cAUIA,GAEJC,GAEA,MAAOC,EAAgBC,GAAqBd,EAAMe,SAASC,QAAQV,IAC7DW,EAAajB,EAAMkB,SAEnBC,EAAenB,EAAMoB,aAAY,WACnCN,GAAkB,KACnB,IAEGO,EAAcrB,EAAMoB,aAAY,WAClCN,GAAkB,GAClBQ,aAAaL,EAAWM,SACxBN,EAAWM,aAAUC,IACtB,IAEGC,EAAczB,EAAMoB,aACtB,WACIT,EAAcF,SACdC,GAAAA,MAEJ,CAACA,EAAWC,EAAeF,IAG/BT,EAAM0B,WACF,WACI,GAAKb,GAAmBP,EAExB,OADAW,EAAWM,QAAUI,OAAOC,WAAWH,EAAgC,IAAnBnB,GAC7Ce,IAEX,CAACf,EAAkBmB,EAAaJ,EAAaR,IAQjD,MAAMgB,EAAgC7B,EAAM8B,QAAQ,IAC3CC,iBAAe1B,sCAKbA,OACH2B,QAAS,WACA3B,IAILA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AS,QACTC,MAAM,OACNC,SAAU1B,EACV2B,cAAe3B,GAEf5C,gBAACwE,SAAMC,MAAM,UACR1B,EAAO2B,IAAIC,IAAA,IAAClE,QAAEA,KAAY+B,iCAAf,OACRxC,gBAACD,mBACG6E,IAAKnE,EACLG,IAAKqC,EAAUxC,GACfA,QAASA,EACTE,cAAec,GACXe"}
|
package/lib/tooltip/tooltip.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as React from 'react';
|
|
2
|
-
import type {
|
|
2
|
+
import type { TooltipStoreState } from '@ariakit/react';
|
|
3
3
|
declare type TooltipProps = {
|
|
4
4
|
/**
|
|
5
5
|
* The element that triggers the tooltip. Generally a button or link.
|
|
@@ -37,7 +37,7 @@ declare type TooltipProps = {
|
|
|
37
37
|
*
|
|
38
38
|
* @default 'top'
|
|
39
39
|
*/
|
|
40
|
-
position?:
|
|
40
|
+
position?: TooltipStoreState['placement'];
|
|
41
41
|
/**
|
|
42
42
|
* The separation (in pixels) between the trigger element and the tooltip.
|
|
43
43
|
* @default 3
|
|
@@ -54,8 +54,6 @@ declare type TooltipProps = {
|
|
|
54
54
|
*/
|
|
55
55
|
exceptionallySetClassName?: string;
|
|
56
56
|
};
|
|
57
|
-
export declare const SHOW_DELAY = 500;
|
|
58
|
-
export declare const HIDE_DELAY = 100;
|
|
59
57
|
declare function Tooltip({ children, content, position, gapSize, withArrow, exceptionallySetClassName, }: TooltipProps): JSX.Element | null;
|
|
60
58
|
export type { TooltipProps };
|
|
61
59
|
export { Tooltip };
|
package/lib/tooltip/tooltip.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../_virtual/_rollupPluginBabelHelpers.js"),t=require("react"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../_virtual/_rollupPluginBabelHelpers.js"),t=require("react"),o=require("../box/box.js"),r=require("@ariakit/react"),n=require("./tooltip.module.css.js");exports.Tooltip=function({children:l,content:i,position:u="top",gapSize:a=3,withArrow:s=!1,exceptionallySetClassName:c}){const p=r.useTooltipStore({placement:u,showTimeout:500,hideTimeout:100}),d=p.useState("open"),f=t.Children.only(l);if(!f)return f;if("string"==typeof f.ref)throw new Error("Tooltip: String refs cannot be used as they cannot be forwarded");function m(e){var t;e.currentTarget.addEventListener("keyup",(function(e){const t=e.key;"Escape"!==t&&"Enter"!==t&&"Space"!==t&&p.show()}),{once:!0}),e.preventDefault(),null==f||null==(t=f.props)||null==t.onFocus||t.onFocus(e)}function h(e){var t;p.hide(),null==f||null==(t=f.props)||null==t.onBlur||t.onBlur(e)}return t.createElement(t.Fragment,null,t.createElement(r.TooltipAnchor,{render:o=>t.cloneElement(f,e.objectSpread2(e.objectSpread2(e.objectSpread2({},f.props),o),{},{onFocus:m,onBlur:h})),store:p,ref:f.ref}),d&&i?t.createElement(o.Box,{as:r.Tooltip,gutter:a,store:p,className:[n.default.tooltip,c],background:"toast",borderRadius:"standard",paddingX:"small",paddingY:"xsmall",maxWidth:"medium",width:"fitContent",overflow:"hidden",textAlign:"center"},s?t.createElement(r.TooltipArrow,null):null,"function"==typeof i?i():i):null)};
|
|
2
2
|
//# sourceMappingURL=tooltip.js.map
|