UNPKG

@wordpress/components

Version:
1 lines • 2.88 kB
{"version":3,"file":"use-menu-item-hide-on-click.mjs","names":[],"sources":["../../src/menu/use-menu-item-hide-on-click.ts"],"sourcesContent":["import type * as Ariakit from '@ariakit/react';\nimport { useCallback } from '@wordpress/element';\n\nfunction focusDisclosureElement( disclosureElement: HTMLElement ) {\n\tdisclosureElement.focus();\n\n\tif ( disclosureElement.ownerDocument.activeElement === disclosureElement ) {\n\t\treturn;\n\t}\n\n\t// A modal Ariakit menu disables the document tree outside the menu. Modern\n\t// browsers use `inert`; Ariakit's fallback replaces each element's `focus`\n\t// method. Ariakit restores either mechanism as soon as the menu hides.\n\tconst inertAncestor = disclosureElement.closest< HTMLElement >( '[inert]' );\n\tif ( inertAncestor ) {\n\t\tinertAncestor.inert = false;\n\t}\n\n\tdisclosureElement.ownerDocument.defaultView?.HTMLElement.prototype.focus.call(\n\t\tdisclosureElement\n\t);\n}\n\nexport function useMenuItemHideOnClick(\n\tstore: Ariakit.MenuItemProps[ 'store' ],\n\thideOnClick: Ariakit.MenuItemProps[ 'hideOnClick' ]\n) {\n\treturn useCallback(\n\t\t( event: React.MouseEvent< HTMLElement > ) => {\n\t\t\tconst shouldHide =\n\t\t\t\ttypeof hideOnClick === 'function'\n\t\t\t\t\t? hideOnClick( event )\n\t\t\t\t\t: hideOnClick;\n\n\t\t\tif ( ! shouldHide ) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif ( ! store || ! ( 'hideAll' in store ) ) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tconst menuElement = store.getState().contentElement;\n\t\t\tconst activeElement = menuElement?.ownerDocument.activeElement;\n\n\t\t\tif ( menuElement?.contains( activeElement ?? null ) ) {\n\t\t\t\tlet rootStore = store;\n\t\t\t\twhile ( rootStore.parent ) {\n\t\t\t\t\trootStore = rootStore.parent;\n\t\t\t\t}\n\n\t\t\t\tconst disclosureElement =\n\t\t\t\t\trootStore.getState().disclosureElement;\n\n\t\t\t\t// Ariakit calls this immediately before it hides and unmounts the\n\t\t\t\t// menu. Move focus first so an overlay opened by the item's onClick\n\t\t\t\t// captures the root trigger as its focus return target.\n\t\t\t\tif ( disclosureElement ) {\n\t\t\t\t\tfocusDisclosureElement( disclosureElement );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t},\n\t\t[ hideOnClick, store ]\n\t);\n}\n"],"mappings":";;AAGA,SAAS,uBAAwB,mBAAiC;CACjE,kBAAkB,MAAM;CAExB,IAAK,kBAAkB,cAAc,kBAAkB,mBACtD;CAMD,MAAM,gBAAgB,kBAAkB,QAAwB,SAAU;CAC1E,IAAK,eACJ,cAAc,QAAQ;CAGvB,kBAAkB,cAAc,aAAa,YAAY,UAAU,MAAM,KACxE,iBACD;AACD;AAEA,SAAgB,uBACf,OACA,aACC;CACD,OAAO,aACJ,UAA4C;EAM7C,IAAK,EAJJ,OAAO,gBAAgB,aACpB,YAAa,KAAM,IACnB,cAGH,OAAO;EAGR,IAAK,CAAE,SAAS,EAAI,aAAa,QAChC,OAAO;EAGR,MAAM,cAAc,MAAM,SAAS,CAAC,CAAC;EACrC,MAAM,gBAAgB,aAAa,cAAc;EAEjD,IAAK,aAAa,SAAU,iBAAiB,IAAK,GAAI;GACrD,IAAI,YAAY;GAChB,OAAQ,UAAU,QACjB,YAAY,UAAU;GAGvB,MAAM,oBACL,UAAU,SAAS,CAAC,CAAC;GAKtB,IAAK,mBACJ,uBAAwB,iBAAkB;EAE5C;EAEA,OAAO;CACR,GACA,CAAE,aAAa,KAAM,CACtB;AACD"}