@doist/reactist 22.0.0 → 22.0.2-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.
Files changed (43) hide show
  1. package/dist/reactist.cjs.development.js +136 -182
  2. package/dist/reactist.cjs.development.js.map +1 -1
  3. package/dist/reactist.cjs.production.min.js +1 -1
  4. package/dist/reactist.cjs.production.min.js.map +1 -1
  5. package/es/checkbox-field/checkbox-field.js +1 -1
  6. package/es/checkbox-field/checkbox-field.js.map +1 -1
  7. package/es/checkbox-field/use-fork-ref.js +35 -0
  8. package/es/checkbox-field/use-fork-ref.js.map +1 -0
  9. package/es/menu/menu.js +35 -38
  10. package/es/menu/menu.js.map +1 -1
  11. package/es/modal/modal.js +3 -4
  12. package/es/modal/modal.js.map +1 -1
  13. package/es/tabs/tabs.js +40 -47
  14. package/es/tabs/tabs.js.map +1 -1
  15. package/es/toast/use-toasts.js +1 -1
  16. package/es/toast/use-toasts.js.map +1 -1
  17. package/es/tooltip/tooltip.js +20 -62
  18. package/es/tooltip/tooltip.js.map +1 -1
  19. package/lib/checkbox-field/checkbox-field.js +1 -1
  20. package/lib/checkbox-field/checkbox-field.js.map +1 -1
  21. package/lib/checkbox-field/use-fork-ref.d.ts +11 -0
  22. package/lib/checkbox-field/use-fork-ref.js +2 -0
  23. package/lib/checkbox-field/use-fork-ref.js.map +1 -0
  24. package/lib/menu/menu.d.ts +4 -4
  25. package/lib/menu/menu.js +1 -1
  26. package/lib/menu/menu.js.map +1 -1
  27. package/lib/modal/modal.d.ts +1 -2
  28. package/lib/modal/modal.js +1 -1
  29. package/lib/modal/modal.js.map +1 -1
  30. package/lib/tabs/tabs.d.ts +10 -8
  31. package/lib/tabs/tabs.js +1 -1
  32. package/lib/tabs/tabs.js.map +1 -1
  33. package/lib/toast/use-toasts.js +1 -1
  34. package/lib/toast/use-toasts.js.map +1 -1
  35. package/lib/tooltip/tooltip.d.ts +2 -4
  36. package/lib/tooltip/tooltip.js +1 -1
  37. package/lib/tooltip/tooltip.js.map +1 -1
  38. package/lib/utils/test-helpers.d.ts +13 -2
  39. package/package.json +4 -6
  40. package/es/hooks/use-previous/use-previous.js +0 -26
  41. package/es/hooks/use-previous/use-previous.js.map +0 -1
  42. package/lib/hooks/use-previous/use-previous.js +0 -2
  43. package/lib/hooks/use-previous/use-previous.js.map +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"),n=require("react"),o=(e(n),e(require("classnames"))),l=require("../utils/polymorphism.js"),r=require("ariakit/portal"),a=require("ariakit/menu");const c=["children","onItemSelect"],s=["exceptionallySetClassName"],u=["as"],i=["exceptionallySetClassName","modal"],p=["value","children","onSelect","hideOnSelect","onClick","exceptionallySetClassName","as"],m=["label","children","exceptionallySetClassName"],d=n.createContext({});function h(e){let{children:o,onItemSelect:l}=e,r=t.objectWithoutProperties(e,c);const[s,u]=n.useState(null),i=n.useMemo(()=>s?()=>s:void 0,[s]),p=a.useMenuState(t.objectSpread2({focusLoop:!0,gutter:8,shift:4,getAnchorRect:i},r));n.useEffect(()=>{p.open||u(null)},[p.open]);const m=n.useCallback((function(e){l&&l(e)}),[l]),h=n.useMemo(()=>({state:p,handleItemSelect:m,handleAnchorRectChange:u}),[p,m]);return n.createElement(d.Provider,{value:h},o)}const C=l.polymorphicComponent((function(e,l){let{exceptionallySetClassName:r}=e,c=t.objectWithoutProperties(e,s);const{state:u}=n.useContext(d);return n.createElement(a.MenuButton,t.objectSpread2(t.objectSpread2({},c),{},{state:u,ref:l,className:o("reactist_menubutton",r)}))})),S=l.polymorphicComponent((function(e,o){let{as:l="div"}=e,r=t.objectWithoutProperties(e,u);const{handleAnchorRectChange:a,state:c}=n.useContext(d),s=n.useCallback(e=>{e.preventDefault(),a({x:e.clientX,y:e.clientY}),c.show()},[a,c]);return n.createElement(l,t.objectSpread2(t.objectSpread2({},r),{},{onContextMenu:s,ref:o}))})),b=l.polymorphicComponent((function(e,l){let{exceptionallySetClassName:c,modal:s=!0}=e,u=t.objectWithoutProperties(e,i);const{state:p}=n.useContext(d);return p.open?n.createElement(r.Portal,{preserveTabOrder:!0},n.createElement(a.Menu,t.objectSpread2(t.objectSpread2({},u),{},{state:p,ref:l,className:o("reactist_menulist",c),modal:s}))):null})),f=l.polymorphicComponent((function(e,o){let{value:l,children:r,onSelect:c,hideOnSelect:s=!0,onClick:u,exceptionallySetClassName:i,as:m="button"}=e,h=t.objectWithoutProperties(e,p);const{handleItemSelect:C,state:S}=n.useContext(d),{hide:b}=S,f=n.useCallback((function(e){null==u||u(e);const t=!1!==(c&&!e.defaultPrevented?c():void 0)&&s;C(l),t&&b()}),[c,u,C,s,b,l]);return n.createElement(a.MenuItem,t.objectSpread2(t.objectSpread2({},h),{},{as:m,state:S,ref:o,onClick:f,className:i,hideOnClick:!1}),r)})),x=n.forwardRef((function({children:e,onItemSelect:t},o){const{handleItemSelect:l,state:r}=n.useContext(d),{hide:c}=r,s=n.useCallback((function(e){t&&t(e),l(e),c()}),[c,l,t]),[u,i]=n.Children.toArray(e),p=n.useCallback((function(e){return n.cloneElement(u,e)}),[u]);return n.createElement(h,{onItemSelect:s},n.createElement(a.MenuItem,{as:"div",state:r,ref:o,hideOnClick:!1},p),i)})),j=l.polymorphicComponent((function(e,o){let{label:l,children:r,exceptionallySetClassName:c}=e,s=t.objectWithoutProperties(e,m);const{state:u}=n.useContext(d);return n.createElement(a.MenuGroup,t.objectSpread2(t.objectSpread2({},s),{},{ref:o,state:u,className:c}),l?n.createElement("div",{role:"presentation",className:"reactist_menugroup__label"},l):null,r)}));exports.ContextMenuTrigger=S,exports.Menu=h,exports.MenuButton=C,exports.MenuGroup=j,exports.MenuItem=f,exports.MenuList=b,exports.SubMenu=x;
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
@@ -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 './menu.less'\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\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, 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 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={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 { 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\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\n return state.open ? (\n <Portal preserveTabOrder>\n <Ariakit.Menu\n {...props}\n state={state}\n ref={ref}\n className={classNames('reactist_menulist', exceptionallySetClassName)}\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, state } = React.useContext(MenuContext)\n const { hide } = state\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 <Ariakit.MenuItem\n {...props}\n as={as}\n state={state}\n ref={ref}\n onClick={handleClick}\n className={exceptionallySetClassName}\n hideOnClick={false}\n >\n {children}\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` 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, 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 {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 { state } = React.useContext(MenuContext)\n return (\n <Ariakit.MenuGroup {...props} ref={ref} state={state} className={exceptionallySetClassName}>\n {label ? (\n <div role=\"presentation\" className=\"reactist_menugroup__label\">\n {label}\n </div>\n ) : null}\n {children}\n </Ariakit.MenuGroup>\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","handleAnchorRectChange","getAnchorRect","undefined","state","Ariakit","focusLoop","gutter","shift","open","handleItemSelect","value","Provider","MenuButton","polymorphicComponent","ref","exceptionallySetClassName","className","classNames","ContextMenuTrigger","as","component","handleContextMenu","event","preventDefault","x","clientX","y","clientY","show","onContextMenu","MenuList","modal","Portal","preserveTabOrder","MenuItem","onSelect","hideOnSelect","onClick","hide","handleClick","shouldClose","defaultPrevented","hideOnClick","SubMenu","parentMenuItemSelect","parentMenuHide","handleSubItemSelect","button","list","toArray","renderMenuButton","MenuGroup","label","role"],"mappings":"ylBA4BMA,EAAcC,gBAMhB,IA4BJ,SAASC,SAAKC,SAAEA,EAAFC,aAAYA,KAAiBC,iCACvC,MAAOC,EAAYC,GAA0BN,WACzC,MAEEO,EAAgBP,UAAc,IACzBK,EAAa,IAAMA,OAAaG,EACxC,CAACH,IAEEI,EAAQC,gCACVC,WAAW,EACXC,OAAQ,EACRC,MAAO,EACPN,cAAAA,GACGH,IAGPJ,YAAgB,KACPS,EAAMK,MAAMR,EAAuB,OACzC,CAACG,EAAMK,OAEV,MAAMC,EAAmBf,eACrB,SAA0BgB,GAClBb,GAAcA,EAAaa,KAEnC,CAACb,IAGCa,EAA0BhB,UAC5B,MACIS,MAAAA,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ACb8B,GAAaF,MAErB,CAACH,EAAUE,EAAS5B,EAAkB2B,EAAcE,EAAM5B,IAG9D,OACIhB,gBAACU,8CACON,OACJqB,GAAIA,EACJhB,MAAOA,EACPW,IAAKA,EACLuB,QAASE,EACTvB,UAAWD,EACX2B,aAAa,IAEZ9C,MAgCP+C,EAAUjD,cAA+C,UAC3DE,SAAEA,EAAFC,aAAYA,GACZiB,GAEA,MAAQL,iBAAkBmC,EAApBzC,MAA0CA,GAAUT,aAAiBD,IACnE6C,KAAMO,GAAmB1C,EAE3B2C,EAAsBpD,eACxB,SAA6BgB,GACrBb,GAAcA,EAAaa,GAC/BkC,EAAqBlC,GACrBmC,MAEJ,CAACA,EAAgBD,EAAsB/C,KAGpCkD,EAAQC,GAAQtD,WAAeuD,QAAQrD,GAIxCsD,EAAmBxD,eACrB,SAA0BI,GACtB,OAAOJ,eAAmBqD,EAA8BjD,KAE5D,CAACiD,IAGL,OACIrD,gBAACC,GAAKE,aAAciD,GAChBpD,gBAACU,YAAiBe,GAAG,MAAMhB,MAAOA,EAAOW,IAAKA,EAAK4B,aAAa,GAC3DQ,GAEJF,MAsBPG,EAAYtC,wBAA4C,WAE1DC,OADAsC,MAAEA,EAAFxD,SAASA,EAATmB,0BAAmBA,KAA8BjB,iCAGjD,MAAMK,MAAEA,GAAUT,aAAiBD,GACnC,OACIC,gBAACU,+CAAsBN,OAAOgB,IAAKA,EAAKX,MAAOA,EAAOa,UAAWD,IAC5DqC,EACG1D,uBAAK2D,KAAK,eAAerC,UAAU,6BAC9BoC,GAEL,KACHxD"}
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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UAAWH,IAEV6C,EACG9D,uBAAKgE,KAAK,eAAe5C,UAAU,6BAC9B0C,GAEL,KACH5D"}
@@ -1,6 +1,5 @@
1
1
  import * as React from 'react';
2
- import { DialogOptions } from 'ariakit/dialog';
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';
@@ -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"),c=require("ariakit/portal"),d=e(require("react-focus-lock")),m=require("aria-hidden"),p=require("ariakit/dialog"),h=require("./modal.module.css.js");const f=["isOpen","onDismiss","height","width","exceptionallySetClassName","exceptionallySetOverlayClassName","autoFocus","hideOnEscape","hideOnInteractOutside","children","portalElement"],x=["children","button","withDivider","exceptionallySetClassName"],b=["exceptionallySetClassName","children"],g=["exceptionallySetClassName","withDivider"],E=["children"],v=a.createContext({onDismiss:void 0,height:"fitContent"});function C(e){return!(e.ownerDocument===document&&"iframe"===e.tagName.toLowerCase())}function S(e){const{onDismiss:l}=a.useContext(v),[n,o]=a.useState(!1),[r,i]=a.useState(!1);return a.useEffect((function(){r?o(!0):i(!0)}),[r]),a.createElement(s.Button,t.objectSpread2(t.objectSpread2({},e),{},{variant:"quaternary",onClick:l,icon:a.createElement(u.CloseIcon,null),tabIndex:n?0:-1}))}function j(e){let{exceptionallySetClassName:l,withDivider:o=!1}=e,i=t.objectWithoutProperties(e,g);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:s="medium",exceptionallySetClassName:u,exceptionallySetOverlayClassName:x,autoFocus:b=!0,hideOnEscape:g=!0,hideOnInteractOutside:E=!0,children:S,portalElement:j}=e,y=t.objectWithoutProperties(e,f);const N=a.useCallback(e=>{e||null==r||r()},[r]),O=p.useDialogState({open:o,setOpen:N}),w=a.useMemo(()=>({onDismiss:r,height:i}),[r,i]),D=a.useRef(null),q=a.useRef(null),B=a.useRef(null),F=a.useCallback(e=>{var t,a;null!=(t=q.current)&&t.contains(e.target)||null==(a=B.current)||!a.contains(e.target)||(e.stopPropagation(),null==r||r())},[r]);return a.useLayoutEffect((function(){if(o&&D.current)return m.hideOthers(D.current)}),[o]),o?a.createElement(c.Portal,{portalRef:D,portalElement:j},a.createElement(n.Box,{"data-testid":"modal-overlay","data-overlay":!0,className:l(h.default.overlay,h.default[i],h.default[s],x),onPointerDown:E?F:void 0,ref:B},a.createElement(d,{autoFocus:b,whiteList:C,returnFocus:!0},a.createElement(p.Dialog,t.objectSpread2(t.objectSpread2({},y),{},{ref:q,as:n.Box,state:O,hideOnEscape:g,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,h.default.container],modal:!1,autoFocus:!1,autoFocusOnShow:!1,autoFocusOnHide:!1,portal:!1,backdrop:!1,hideOnInteractOutside:!1}),a.createElement(v.Provider,{value:w},S))))):null},exports.ModalActions=function(e){let{children:l}=e,n=t.objectWithoutProperties(e,E);return a.createElement(j,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,b);const{height:i}=a.useContext(v);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=S,exports.ModalFooter=j,exports.ModalHeader=function(e){let{children:l,button:i=!0,withDivider:s=!1,exceptionallySetClassName:u}=e,c=t.objectWithoutProperties(e,x);return a.createElement(a.Fragment,null,a.createElement(n.Box,t.objectSpread2(t.objectSpread2({},c),{},{as:"header",paddingLeft:"large",paddingRight:!1===i||null===i?"large":"small",paddingY:"small",className:u}),a.createElement(o.Columns,{space:"large",alignY:"center"},a.createElement(o.Column,{width:"auto"},l),!1===i||null===i?a.createElement("div",{className:h.default.headerContent}):a.createElement(o.Column,{width:"content",exceptionallySetClassName:h.default.buttonContainer,"data-testid":"button-container"},"boolean"==typeof i?a.createElement(S,{"aria-label":"Close modal",autoFocus:!1}):i))),s?a.createElement(r.Divider,null):null)};
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
@@ -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,OAAOiB,UAAWL,EAA2BM,QAAQ,0CAvUhEC,OAClBA,EADkB7B,UAElBA,EAFkBE,OAGlBA,EAAS,aAHS4B,MAIlBA,EAAQ,SAJUR,0BA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Q,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,KAAMnB,gBAACoB,kBACPC,SAAUT,EAAoB,GAAK,cAqJ/BU,SAAYC,0BACxBA,EADwBC,YAExBA,GAAc,KACXb,iCAEH,OACIX,gCACKwB,EAAcxB,gBAAC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,OAAmB,WAAXA,EAAsB,YAASD,EACvCsE,SAAqB,WAAXrE,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"}
@@ -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 behaviour can be changed to
74
- * 'active', which renders only when the tab is active, and 'lazy', meaning while inactive tab panels will not be rendered
75
- * initially, they will remain mounted once they are active until the entire Tabs tree is unmounted.
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 corresponding `<Tab>` component.
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 be
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 TabPanel
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"),a=require("react"),r=(e(a),e(require("classnames"))),n=require("../utils/polymorphism.js"),s=require("../box/box.js"),l=require("../inline/inline.js"),o=require("ariakit/tab"),i=require("../hooks/use-previous/use-previous.js"),c=require("./tabs.module.css.js");const u=["as","children","id","exceptionallySetClassName"],d=["children","space"],p=["children","id","as","render"],b=a.createContext(null),f=n.polymorphicComponent((function(e,n){let{as:s,children:l,id:i,exceptionallySetClassName:d}=e,p=t.objectWithoutProperties(e,u);const f=a.useContext(b);if(!f)return null;const{variant:m,tabState:x}=f;return a.createElement(o.Tab,t.objectSpread2(t.objectSpread2({},p),{},{as:s,className:r(d,c.default.tab,c.default["tab-"+m]),id:i,state:x,ref:n}),l)})),m=n.polymorphicComponent((function(e,r){let{children:n,id:s,as:l,render:i="always"}=e,c=t.objectWithoutProperties(e,p);const u=a.useContext(b),[d,f]=a.useState(!1),m=(null==u?void 0:u.tabState.selectedId)===s;if(a.useEffect((function(){!d&&m&&f(!0)}),[d,m]),!u)return null;const{tabState:x}=u;return"always"===i||"active"===i&&m||"lazy"===i&&(m||d)?a.createElement(o.TabPanel,t.objectSpread2(t.objectSpread2({tabId:s},c),{},{state:x,as:l,ref:r}),n):null}));exports.Tab=f,exports.TabAwareSlot=function({children:e}){const t=a.useContext(b);return t?e({selectedId:null==t?void 0:t.tabState.selectedId}):null},exports.TabList=function(e){let{children:r,space:n}=e,i=t.objectWithoutProperties(e,d);const u=a.useContext(b);if(!u)return null;const{tabState:p,variant:f}=u;return a.createElement(s.Box,null,a.createElement(o.TabList,t.objectSpread2({state:p,as:s.Box,position:"relative",width:"maxContent"},i),a.createElement(s.Box,{className:[c.default.track,c.default["track-"+f]]}),a.createElement(l.Inline,{space:n},r)))},exports.TabPanel=m,exports.Tabs=function({children:e,selectedId:t,defaultSelectedId:r,variant:n="neutral",onSelectedIdChange:s}){const l=o.useTabState({selectedId:t,setSelectedId:s}),c=i.usePrevious(r),{selectedId:u,select:d}=l;a.useEffect((function(){t||r===c||r===u||void 0===r||d(r)}),[t,r,u,d,c]);const p=a.useMemo((function(){return{tabState:l,variant:n}}),[n,l]);return a.createElement(b.Provider,{value:p},e)};
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
@@ -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,iBAAcL,IAC3EJ,GAAIA,EACJW,MAAON,EACPR,IAAKA,IAEJE,MAmFPa,EAAWhB,wBAA4D,WAEzEC,OADAE,SAAEA,EAAFC,GAAYA,EAAZF,GAAgBA,EAAhBe,OAAoBA,EAAS,YAAaX,iCAG1C,MAAMC,EAAkBT,aAAiBD,IAClCqB,EAAaC,GAAkBrB,YAAe,GAC/CsB,SAAcb,SAAAA,EAAiBE,SAASY,cAAejB,EAW7D,GATAN,aACI,YACSoB,GAAeE,GAChBD,GAAe,KAGvB,CAACD,EAAa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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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AC4B,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"}
@@ -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"),i=require("./toast.module.css.js"),r=require("./static-toast.js"),u=require("ariakit/portal"),c=require("./toast-animation.js");const l=["toastId"],d=s.forwardRef((function({message:e,description:o,icon:a,action:n,autoDismissDelay:i,dismissLabel:u,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(()=>r.isActionObject(n)?t.objectSpread2(t.objectSpread2({},n),{},{onClick:function(){n&&(n.onClick(),x())}}):n,[n,x]);return s.createElement(r.StaticToast,{ref:f,message:e,description:o,icon:a,action:C,onDismiss:c?x:void 0,dismissLabel:u,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:r="large",defaultAutoDismissDelay:f=10,defaultDismissLabel:p="Close",containerClassName:b}){const[j,k]=s.useState([]),{mappedRef:v,animateRemove:x}=c.useToastsAnimation(),C=s.useCallback((function(e){x(e,()=>{k(t=>{const s=t.findIndex(t=>t.toastId===e);if(s<0)return t;const o=[...t];return o.splice(s,1),o})})}),[x]),D=s.useCallback((function(e){const s=n.generateElementId("toast"),o=t.objectSpread2(t.objectSpread2({autoDismissDelay:f,dismissLabel:p},e),{},{toastId:s});return k(e=>[...e,o]),()=>C(s)}),[f,p,C]);return s.createElement(m.Provider,{value:D},e,s.createElement(u.Portal,null,0===j.length?null:s.createElement(o.Box,{className:[i.default.stackedToastsView,b],position:"fixed",width:"full",paddingX:r,paddingBottom:r,"data-testid":"toasts-container"},s.createElement(a.Stack,{space:"medium"},j.map(e=>{let{toastId:o}=e,a=t.objectWithoutProperties(e,l);return s.createElement(d,t.objectSpread2({key:o,ref:v(o),toastId:o,onRemoveToast:C},a))})))))},exports.useToasts=f;
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",containerClassName:b}){const[j,k]=s.useState([]),{mappedRef:v,animateRemove:x}=c.useToastsAnimation(),C=s.useCallback((function(e){x(e,()=>{k(t=>{const s=t.findIndex(t=>t.toastId===e);if(s<0)return t;const o=[...t];return o.splice(s,1),o})})}),[x]),D=s.useCallback((function(e){const s=i.generateElementId("toast"),o=t.objectSpread2(t.objectSpread2({autoDismissDelay:f,dismissLabel:p},e),{},{toastId:s});return k(e=>[...e,o]),()=>C(s)}),[f,p,C]);return s.createElement(m.Provider,{value:D},e,s.createElement(n.Portal,null,0===j.length?null:s.createElement(o.Box,{className:[r.default.stackedToastsView,b],position:"fixed",width:"full",paddingX:u,paddingBottom:u,"data-testid":"toasts-container"},s.createElement(a.Stack,{space:"medium"},j.map(e=>{let{toastId:o}=e,a=t.objectWithoutProperties(e,l);return s.createElement(d,t.objectSpread2({key:o,ref:v(o),toastId:o,onRemoveToast:C},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 * Custom classname for the toasts container, if you need to fine-tune the position or other styles\n */\n containerClassName?: string\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 containerClassName,\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, containerClassName]}\n position=\"fixed\"\n width=\"full\"\n paddingX={padding}\n paddingBottom={padding}\n data-testid=\"toasts-container\"\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","containerClassName","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,EAAO2B,UACPP,QAXGpB,EAcZ,CAACA,EAAQoB,IAEZ,OACIzB,gBAACiC,eACGrB,IAAKA,EACLV,QAASA,EACTC,YAAaA,EACbC,KAAMA,EACNC,OAAQwB,EACRnB,UAAWF,EAAoBiB,OAAcD,EAC7CjB,aAAcA,EAEd2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,mBACG8E,IAAKpE,EACLG,IAAKsC,EAAUzC,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 * Custom classname for the toasts container, if you need to fine-tune the position or other styles\n */\n containerClassName?: string\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 containerClassName,\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, containerClassName]}\n position=\"fixed\"\n width=\"full\"\n paddingX={padding}\n paddingBottom={padding}\n data-testid=\"toasts-container\"\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","containerClassName","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,EAAO2B,UACPP,QAXGpB,EAcZ,CAACA,EAAQoB,IA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,OACNC,SAAU3B,EACV4B,cAAe5B,gBACH,oBAEZ5C,gBAACyE,SAAMC,MAAM,UACR1B,EAAO2B,IAAIC,IAAA,IAACnE,QAAEA,KAAY+B,iCAAf,OACRxC,gBAACD,mBACG8E,IAAKpE,EACLG,IAAKsC,EAAUzC,GACfA,QAASA,EACTE,cAAec,GACXe"}
@@ -1,5 +1,5 @@
1
1
  import * as React from 'react';
2
- import type { PopoverState } from 'ariakit/popover';
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?: PopoverState['placement'];
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 };
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../_virtual/_rollupPluginBabelHelpers.js"),t=require("react"),r=require("../box/box.js"),o=require("ariakit/tooltip"),n=require("./tooltip.module.css.js");exports.HIDE_DELAY=100,exports.SHOW_DELAY=500,exports.Tooltip=function({children:l,content:u,position:i="top",gapSize:a=3,withArrow:s=!1,exceptionallySetClassName:c}){const p=function(r){const n=o.useTooltipState(r),l=function(){const e=t.useRef(),r=t.useCallback((function(){null!=e.current&&clearTimeout(e.current)}),[]);return t.useEffect(()=>r,[r]),t.useCallback((function(t,o){return()=>{r(),e.current=setTimeout(t,o)}}),[r])}();return t.useMemo(()=>e.objectSpread2(e.objectSpread2({},n),{},{show:l(()=>n.show(),500),hide:l(()=>n.hide(),100)}),[l,n])}({placement:i,gutter:a}),d=t.Children.only(l);if(!d)return d;if("string"==typeof d.ref)throw new Error("Tooltip: String refs cannot be used as they cannot be forwarded");function f(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==d||null==(t=d.props)||null==t.onFocus||t.onFocus(e)}function m(e){var t;p.hide(),null==d||null==(t=d.props)||null==t.onBlur||t.onBlur(e)}return t.createElement(t.Fragment,null,t.createElement(o.TooltipAnchor,{state:p,ref:d.ref,described:!0},r=>t.cloneElement(d,e.objectSpread2(e.objectSpread2(e.objectSpread2({},r),d.props),{},{onFocus:f,onBlur:m}))),p.open&&u?t.createElement(r.Box,{as:o.Tooltip,state: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(o.TooltipArrow,null):null,"function"==typeof u?u():u):null)};
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
@@ -1 +1 @@
1
- {"version":3,"file":"tooltip.js","sources":["../../src/tooltip/tooltip.tsx"],"sourcesContent":["import * as React from 'react'\n\nimport {\n useTooltipState as useAriakitTooltipState,\n Tooltip as AriakitTooltip,\n TooltipAnchor,\n TooltipArrow,\n} from 'ariakit/tooltip'\nimport { Box } from '../box'\n\nimport type {\n TooltipStateProps as AriakitTooltipStateProps,\n TooltipAnchorProps,\n} from 'ariakit/tooltip'\nimport type { PopoverState } from 'ariakit/popover'\n\nimport styles from './tooltip.module.css'\n\ntype TooltipProps = {\n /**\n * The element that triggers the tooltip. Generally a button or link.\n *\n * It should be an interactive element accessible both via mouse and keyboard interactions.\n */\n children: React.ReactNode\n\n /**\n * The content to show in the tooltip.\n *\n * It can be rich content provided via React elements, or string content. It should not include\n * interactive elements inside it. This includes links or buttons.\n *\n * You can provide a function instead of the content itself. In this case, the function should\n * return the desired content. This is useful if the content is expensive to generate. It can\n * also be useful if the content dynamically changes often, so every time you trigger the\n * tooltip the content may have changed (e.g. if you show a ticking time clock in the tooltip).\n *\n * The trigger element will be associated to this content via `aria-describedby`. This means\n * that the tooltip content will be read by assistive technologies such as screen readers. It\n * will likely read this content right after reading the trigger element label.\n */\n content: React.ReactNode | (() => React.ReactNode)\n\n /**\n * How to place the tooltip relative to its trigger element.\n *\n * The possible values are \"top\", \"bottom\", \"left\", \"right\". Additionally, any of these values\n * can be combined with `-start` or `-end` for even more control. For instance `top-start` will\n * place the tooltip at the top, but with the start (e.g. left) side of the toolip and the\n * trigger aligned. If neither `-start` or `-end` are provided, the tooltip is centered along\n * the vertical or horizontal axis with the trigger.\n *\n * The position is enforced whenever possible, but tooltips can appear in different positions\n * if the specified one would make the tooltip intersect with the viewport edges.\n *\n * @default 'top'\n */\n position?: PopoverState['placement']\n\n /**\n * The separation (in pixels) between the trigger element and the tooltip.\n * @default 3\n */\n gapSize?: number\n\n /**\n * Whether to show an arrow-like element attached to the tooltip, and pointing towards the\n * trigger element.\n * @default false\n */\n withArrow?: boolean\n\n /**\n * An escape hatch, in case you need to provide a custom class name to the tooltip.\n */\n exceptionallySetClassName?: string\n}\n\n// These are exported to be used in the tests, they are not meant to be exported publicly\nexport const SHOW_DELAY = 500\nexport const HIDE_DELAY = 100\n\nfunction useDelayedTooltipState(initialState: AriakitTooltipStateProps) {\n const tooltipState = useAriakitTooltipState(initialState)\n const delay = useDelay()\n return React.useMemo(\n () => ({\n ...tooltipState,\n show: delay(() => tooltipState.show(), SHOW_DELAY),\n hide: delay(() => tooltipState.hide(), HIDE_DELAY),\n }),\n [delay, tooltipState],\n )\n}\n\nfunction Tooltip({\n children,\n content,\n position = 'top',\n gapSize = 3,\n withArrow = false,\n exceptionallySetClassName,\n}: TooltipProps) {\n const state = useDelayedTooltipState({ placement: position, gutter: gapSize })\n\n const child = React.Children.only(\n children as React.FunctionComponentElement<JSX.IntrinsicElements['div']> | null,\n )\n\n if (!child) {\n return child\n }\n\n if (typeof child.ref === 'string') {\n throw new Error('Tooltip: String refs cannot be used as they cannot be forwarded')\n }\n\n /**\n * Prevents the tooltip from automatically firing on focus all the time. This is to prevent\n * tooltips from showing when the trigger element is focused back after a popover or dialog that\n * it opened was closed. See link below for more details.\n * @see https://github.com/ariakit/ariakit/discussions/749\n */\n function handleFocus(event: React.FocusEvent<HTMLDivElement>) {\n // If focus is not followed by a key up event, does it mean that it's not an intentional\n // keyboard focus? Not sure but it seems to work.\n // This may be resolved soon in an upcoming version of ariakit:\n // https://github.com/ariakit/ariakit/issues/750\n function handleKeyUp(event: Event) {\n const eventKey = (event as KeyboardEvent).key\n if (eventKey !== 'Escape' && eventKey !== 'Enter' && eventKey !== 'Space') {\n state.show()\n }\n }\n event.currentTarget.addEventListener('keyup', handleKeyUp, { once: true })\n event.preventDefault() // Prevent tooltip.show from being called by TooltipReference\n child?.props?.onFocus?.(event)\n }\n\n function handleBlur(event: React.FocusEvent<HTMLDivElement>) {\n state.hide()\n child?.props?.onBlur?.(event)\n }\n\n return (\n <>\n <TooltipAnchor state={state} ref={child.ref} described>\n {(anchorProps: TooltipAnchorProps) => {\n // Let child props override anchor props so user can specify attributes like tabIndex\n // Also, do not apply the child's props to TooltipAnchor as props like `as` can create problems\n // by applying the replacement component/element twice\n return React.cloneElement(child, {\n ...anchorProps,\n ...child.props,\n onFocus: handleFocus,\n onBlur: handleBlur,\n })\n }}\n </TooltipAnchor>\n {state.open && content ? (\n <Box\n as={AriakitTooltip}\n state={state}\n className={[styles.tooltip, exceptionallySetClassName]}\n background=\"toast\"\n borderRadius=\"standard\"\n paddingX=\"small\"\n paddingY=\"xsmall\"\n maxWidth=\"medium\"\n width=\"fitContent\"\n overflow=\"hidden\"\n textAlign=\"center\"\n >\n {withArrow ? <TooltipArrow /> : null}\n {typeof content === 'function' ? content() : content}\n </Box>\n ) : null}\n </>\n )\n}\n\nexport type { TooltipProps }\nexport { Tooltip }\n\n//\n// Internal helpers\n//\n\n/**\n * Returns a function offering the same interface as setTimeout, but cleans up on unmount.\n *\n * The timeout state is shared, and only one delayed function can be active at any given time. If\n * a new delayed function is called while another one was waiting for its time to run, that older\n * invocation is cleared and it never runs.\n *\n * This is suitable for our use case here, but probably not the most intuitive thing in general.\n * That's why this is not made a shared util or something like it.\n */\nfunction useDelay() {\n const timeoutRef = React.useRef<ReturnType<typeof setTimeout>>()\n\n const clearTimeouts = React.useCallback(function clearTimeouts() {\n if (timeoutRef.current != null) {\n clearTimeout(timeoutRef.current)\n }\n }, [])\n\n // Runs clearTimeouts when the component is unmounted\n React.useEffect(() => clearTimeouts, [clearTimeouts])\n\n return React.useCallback(\n function delay(fn: () => void, delay: number) {\n return () => {\n clearTimeouts()\n timeoutRef.current = setTimeout(fn, delay)\n }\n },\n [clearTimeouts],\n )\n}\n"],"names":["children","content","position","gapSize","withArrow","exceptionallySetClassName","state","initialState","tooltipState","useAriakitTooltipState","delay","timeoutRef","React","clearTimeouts","current","clearTimeout","fn","setTimeout","useDelay","show","hide","useDelayedTooltipState","placement","gutter","child","only","ref","Error","handleFocus","event","currentTarget","addEventListener","eventKey","key","once","preventDefault","props","onFocus","handleBlur","onBlur","TooltipAnchor","described","anchorProps","open","Box","as","AriakitTooltip","className","styles","tooltip","background","borderRadius","paddingX","paddingY","maxWidth","width","overflow","textAlign","TooltipArrow"],"mappings":"iQAgF0B,uBADA,oBAgB1B,UAAiBA,SACbA,EADaC,QAEbA,EAFaC,SAGbA,EAAW,MAHEC,QAIbA,EAAU,EAJGC,UAKbA,GAAY,EALCC,0BAMbA,IAEA,MAAMC,EArBV,SAAgCC,GAC5B,MAAMC,EAAeC,kBAAuBF,GACtCG,EAkHV,WACI,MAAMC,EAAaC,WAEbC,EAAgBD,eAAkB,WACV,MAAtBD,EAAWG,SACXC,aAAaJ,EAAWG,WAE7B,IAKH,OAFAF,YAAgB,IAAMC,EAAe,CAACA,IAE/BD,eACH,SAAeI,EAAgBN,GAC3B,MAAO,KACHG,IACAF,EAAWG,QAAUG,WAAWD,EAAIN,MAG5C,CAACG,IArISK,GACd,OAAON,UACH,uCACOJ,OACHW,KAAMT,EAAM,IAAMF,EAAaW,OATjB,KAUdC,KAAMV,EAAM,IAAMF,EAAaY,OATjB,OAWlB,CAACV,EAAOF,IAYEa,CAAuB,CAAEC,UAAWpB,EAAUqB,OAAQpB,IAE9DqB,EAAQZ,WAAea,KACzBzB,GAGJ,IAAKwB,EACD,OAAOA,EAGX,GAAyB,iBAAdA,EAAME,IACb,MAAM,IAAIC,MAAM,mEASpB,SAASC,EAAYC,SAWjBA,EAAMC,cAAcC,iBAAiB,SANrC,SAAqBF,GACjB,MAAMG,EAAYH,EAAwBI,IACzB,WAAbD,GAAsC,UAAbA,GAAqC,UAAbA,GACjD1B,EAAMa,SAG6C,CAAEe,MAAM,IACnEL,EAAMM,uBACNX,YAAAA,EAAOY,gBAAOC,WAAAA,QAAUR,GAG5B,SAASS,EAAWT,SAChBvB,EAAMc,aACNI,YAAAA,EAAOY,gBAAOG,UAAAA,OAASV,GAG3B,OACIjB,gCACIA,gBAAC4B,iBAAclC,MAAOA,EAAOoB,IAAKF,EAAME,IAAKe,cACvCC,GAIS9B,eAAmBY,qDACnBkB,GACAlB,EAAMY,WACTC,QAAST,EACTW,OAAQD,MAInBhC,EAAMqC,MAAQ1C,EACXW,gBAACgC,OACGC,GAAIC,UACJxC,MAAOA,EACPyC,UAAW,CAACC,UAAOC,QAAS5C,GAC5B6C,WAAW,QACXC,aAAa,WACbC,SAAS,QACTC,SAAS,SACTC,SAAS,SACTC,MAAM,aACNC,SAAS,SACTC,UAAU,UAETrD,EAAYQ,gBAAC8C,qBAAkB,KACZ,mBAAZzD,EAAyBA,IAAYA,GAEjD"}
1
+ {"version":3,"file":"tooltip.js","sources":["../../src/tooltip/tooltip.tsx"],"sourcesContent":["import * as React from 'react'\n\nimport {\n useTooltipStore,\n Tooltip as AriakitTooltip,\n TooltipAnchor,\n TooltipArrow,\n} from '@ariakit/react'\nimport { Box } from '../box'\n\nimport type { TooltipStoreState } from '@ariakit/react'\n\nimport styles from './tooltip.module.css'\n\ntype TooltipProps = {\n /**\n * The element that triggers the tooltip. Generally a button or link.\n *\n * It should be an interactive element accessible both via mouse and keyboard interactions.\n */\n children: React.ReactNode\n\n /**\n * The content to show in the tooltip.\n *\n * It can be rich content provided via React elements, or string content. It should not include\n * interactive elements inside it. This includes links or buttons.\n *\n * You can provide a function instead of the content itself. In this case, the function should\n * return the desired content. This is useful if the content is expensive to generate. It can\n * also be useful if the content dynamically changes often, so every time you trigger the\n * tooltip the content may have changed (e.g. if you show a ticking time clock in the tooltip).\n *\n * The trigger element will be associated to this content via `aria-describedby`. This means\n * that the tooltip content will be read by assistive technologies such as screen readers. It\n * will likely read this content right after reading the trigger element label.\n */\n content: React.ReactNode | (() => React.ReactNode)\n\n /**\n * How to place the tooltip relative to its trigger element.\n *\n * The possible values are \"top\", \"bottom\", \"left\", \"right\". Additionally, any of these values\n * can be combined with `-start` or `-end` for even more control. For instance `top-start` will\n * place the tooltip at the top, but with the start (e.g. left) side of the toolip and the\n * trigger aligned. If neither `-start` or `-end` are provided, the tooltip is centered along\n * the vertical or horizontal axis with the trigger.\n *\n * The position is enforced whenever possible, but tooltips can appear in different positions\n * if the specified one would make the tooltip intersect with the viewport edges.\n *\n * @default 'top'\n */\n position?: TooltipStoreState['placement']\n\n /**\n * The separation (in pixels) between the trigger element and the tooltip.\n * @default 3\n */\n gapSize?: number\n\n /**\n * Whether to show an arrow-like element attached to the tooltip, and pointing towards the\n * trigger element.\n * @default false\n */\n withArrow?: boolean\n\n /**\n * An escape hatch, in case you need to provide a custom class name to the tooltip.\n */\n exceptionallySetClassName?: string\n}\n\nfunction Tooltip({\n children,\n content,\n position = 'top',\n gapSize = 3,\n withArrow = false,\n exceptionallySetClassName,\n}: TooltipProps) {\n const tooltip = useTooltipStore({ placement: position, showTimeout: 500, hideTimeout: 100 })\n const isOpen = tooltip.useState('open')\n\n const child = React.Children.only(\n children as React.FunctionComponentElement<JSX.IntrinsicElements['div']> | null,\n )\n\n if (!child) {\n return child\n }\n\n if (typeof child.ref === 'string') {\n throw new Error('Tooltip: String refs cannot be used as they cannot be forwarded')\n }\n\n /**\n * Prevents the tooltip from automatically firing on focus all the time. This is to prevent\n * tooltips from showing when the trigger element is focused back after a popover or dialog that\n * it opened was closed. See link below for more details.\n * @see https://github.com/ariakit/ariakit/discussions/749\n */\n function handleFocus(event: React.FocusEvent<HTMLDivElement>) {\n // If focus is not followed by a key up event, does it mean that it's not an intentional\n // keyboard focus? Not sure but it seems to work.\n // This may be resolved soon in an upcoming version of ariakit:\n // https://github.com/ariakit/ariakit/issues/750\n function handleKeyUp(event: Event) {\n const eventKey = (event as KeyboardEvent).key\n if (eventKey !== 'Escape' && eventKey !== 'Enter' && eventKey !== 'Space') {\n tooltip.show()\n }\n }\n event.currentTarget.addEventListener('keyup', handleKeyUp, { once: true })\n event.preventDefault() // Prevent tooltip.show from being called by TooltipReference\n child?.props?.onFocus?.(event)\n }\n\n function handleBlur(event: React.FocusEvent<HTMLDivElement>) {\n tooltip.hide()\n child?.props?.onBlur?.(event)\n }\n\n return (\n <>\n <TooltipAnchor\n render={(anchorProps) => {\n return React.cloneElement(child, {\n ...child.props,\n ...anchorProps,\n onFocus: handleFocus,\n onBlur: handleBlur,\n })\n }}\n store={tooltip}\n ref={child.ref}\n />\n {isOpen && content ? (\n <Box\n as={AriakitTooltip}\n gutter={gapSize}\n store={tooltip}\n className={[styles.tooltip, exceptionallySetClassName]}\n background=\"toast\"\n borderRadius=\"standard\"\n paddingX=\"small\"\n paddingY=\"xsmall\"\n maxWidth=\"medium\"\n width=\"fitContent\"\n overflow=\"hidden\"\n textAlign=\"center\"\n >\n {withArrow ? <TooltipArrow /> : null}\n {typeof content === 'function' ? content() : content}\n </Box>\n ) : null}\n </>\n )\n}\n\nexport type { TooltipProps }\nexport { Tooltip }\n"],"names":["children","content","position","gapSize","withArrow","exceptionallySetClassName","tooltip","useTooltipStore","placement","showTimeout","hideTimeout","isOpen","useState","child","React","only","ref","Error","handleFocus","event","currentTarget","addEventListener","eventKey","key","show","once","preventDefault","props","onFocus","handleBlur","hide","onBlur","TooltipAnchor","render","anchorProps","store","Box","as","AriakitTooltip","gutter","className","styles","background","borderRadius","paddingX","paddingY","maxWidth","width","overflow","textAlign","TooltipArrow"],"mappings":"6PA0EA,UAAiBA,SACbA,EADaC,QAEbA,EAFaC,SAGbA,EAAW,MAHEC,QAIbA,EAAU,EAJGC,UAKbA,GAAY,EALCC,0BAMbA,IAEA,MAAMC,EAAUC,kBAAgB,CAAEC,UAAWN,EAAUO,YAAa,IAAKC,YAAa,MAChFC,EAASL,EAAQM,SAAS,QAE1BC,EAAQC,WAAeC,KACzBf,GAGJ,IAAKa,EACD,OAAOA,EAGX,GAAyB,iBAAdA,EAAMG,IACb,MAAM,IAAIC,MAAM,mEASpB,SAASC,EAAYC,SAWjBA,EAAMC,cAAcC,iBAAiB,SANrC,SAAqBF,GACjB,MAAMG,EAAYH,EAAwBI,IACzB,WAAbD,GAAsC,UAAbA,GAAqC,UAAbA,GACjDhB,EAAQkB,SAG2C,CAAEC,MAAM,IACnEN,EAAMO,uBACNb,YAAAA,EAAOc,gBAAOC,WAAAA,QAAUT,GAG5B,SAASU,EAAWV,SAChBb,EAAQwB,aACRjB,YAAAA,EAAOc,gBAAOI,UAAAA,OAASZ,GAG3B,OACIL,gCACIA,gBAACkB,iBACGC,OAASC,GACEpB,eAAmBD,qDACnBA,EAAMc,OACNO,OACHN,QAASV,EACTa,OAAQF,KAGhBM,MAAO7B,EACPU,IAAKH,EAAMG,MAEdL,GAAUV,EACPa,gBAACsB,OACGC,GAAIC,UACJC,OAAQpC,EACRgC,MAAO7B,EACPkC,UAAW,CAACC,UAAOnC,QAASD,GAC5BqC,WAAW,QACXC,aAAa,WACbC,SAAS,QACTC,SAAS,SACTC,SAAS,SACTC,MAAM,aACNC,SAAS,SACTC,UAAU,UAET7C,EAAYU,gBAACoC,qBAAkB,KACZ,mBAAZjD,EAAyBA,IAAYA,GAEjD"}
@@ -6,6 +6,17 @@ declare type PropsWithSpace = {
6
6
  'data-testid'?: string;
7
7
  };
8
8
  declare function runSpaceTests<Props extends PropsWithSpace>(Component: React.ComponentType<Props>): void;
9
- declare function flushPromises(): Promise<void>;
9
+ /**
10
+ * Solves some issues with unwanted warnings in tests of ariakit components due to its internal
11
+ * usage of the event queue for asynchronous side-effects.
12
+ *
13
+ * Think of it as a special version of `act` that we need to call to make sure some async (but
14
+ * immediate) actions are taken care of. Mostly around the ariakit popover and combobox elements'
15
+ * state management.
16
+ *
17
+ * @see https://twitter.com/diegohaz/status/1560525455383461888
18
+ * @see https://github.com/ariakit/ariakit/issues/1800#issuecomment-1227862399
19
+ */
20
+ declare function flushMicrotasks(): Promise<undefined>;
10
21
  declare function TestIcon(): JSX.Element;
11
- export { runSpaceTests, flushPromises, TestIcon };
22
+ export { runSpaceTests, flushMicrotasks, TestIcon };