{"version":3,"file":"Accordion.mjs","names":[],"sources":["../../../src/accordion/Accordion.tsx"],"sourcesContent":["/*!\n *\n *  Copyright (c) \"Neo4j\"\n *  Neo4j Sweden AB [http://neo4j.com]\n *\n *  This file is part of Neo4j.\n *\n *  Neo4j is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\nimport classNames from 'classnames';\nimport type React from 'react';\nimport { useCallback, useImperativeHandle, useRef } from 'react';\n\nimport { type PolymorphicCommonProps } from '../_common/types';\nimport { findUntil } from '../_common/utils';\nimport { Divider } from '../divider';\nimport { ChevronDownIconOutline } from '../icons/generated/heroIcons/ChevronDownIconOutline';\nimport { Typography } from '../typography';\nimport { AccordionContext, useAccordionContext } from './accordion-context';\nimport {\n  type AccordionItemId,\n  type AccordionItemProps,\n  type AccordionProps,\n  type ClassicItemProps,\n  type IsMultiple,\n  type IsNotMultiple,\n} from './accordion-types';\n\nenum AccordionSelector {\n  Item = '.ndl-accordion-item',\n  ItemNotDisabled = '.ndl-accordion-item:not(.ndl-accordion-item-disabled)',\n}\n\nconst getAccordionItem = (\n  accordionElement: Element,\n  selector: string,\n  direction: 'next' | 'prev' = 'next',\n): Element | null => {\n  const itemParent = accordionElement.closest(AccordionSelector.Item);\n  if (!itemParent) {\n    return null;\n  }\n\n  return findUntil(direction, itemParent, selector);\n};\n\nconst AccordionComponent = function AccordionComponent<\n  T extends AccordionItemId,\n  U extends React.ElementType = 'div',\n>({\n  children,\n  as,\n  isMultiple,\n  onChange,\n  className,\n  style,\n  htmlAttributes,\n  ref,\n  ...restProps\n}: PolymorphicCommonProps<U, AccordionProps<T>>) {\n  const accordionRef = useRef<U>(null);\n\n  useImperativeHandle(ref, () => accordionRef.current!);\n\n  const Component: React.ElementType = as || 'div';\n\n  // The following function includes code needed to be\n  // able to navigate with the arrow keys (not tab).\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const accordionElement = accordionRef.current;\n    if (!accordionElement) {\n      return;\n    }\n    const activeElement = document.activeElement as HTMLElement;\n    if (event.key === 'ArrowDown') {\n      event.preventDefault();\n      event.stopPropagation();\n      const newFocusedElement = getAccordionItem(\n        activeElement,\n        AccordionSelector.ItemNotDisabled,\n        'next',\n      );\n      const newHeader = newFocusedElement?.firstElementChild;\n\n      if (newHeader && newHeader instanceof HTMLElement) {\n        focusAccordionItem(newHeader as HTMLElement);\n      }\n    } else if (event.key === 'ArrowUp') {\n      event.preventDefault();\n      event.stopPropagation();\n      const newFocusedElement = getAccordionItem(\n        activeElement,\n        AccordionSelector.ItemNotDisabled,\n        'prev',\n      );\n      const newHeader = newFocusedElement?.firstElementChild;\n\n      if (newHeader && newHeader instanceof HTMLElement) {\n        focusAccordionItem(newHeader as HTMLElement);\n      }\n    } else if (event.key === ' ' || event.key === 'Enter') {\n      event.preventDefault();\n      event.stopPropagation();\n      activeElement.click();\n    }\n  };\n\n  const focusAccordionItem = (accordionHtmlElement: HTMLElement) => {\n    const accordionButton = accordionHtmlElement\n      .getElementsByClassName('ndl-accordion-item-header-button')\n      .item(0);\n\n    if (accordionButton !== null && accordionButton instanceof HTMLElement) {\n      accordionButton.focus();\n    }\n  };\n\n  const classes = classNames('ndl-accordion', className);\n\n  // Destructure and omit keys from DOM spread\n  const { expandedItemIds, expandedItemId, ...restAccordionProps } =\n    restProps as Record<string, unknown> as {\n      expandedItemIds?: T[];\n      expandedItemId?: T | null;\n      [key: string]: unknown;\n    };\n\n  const contextValue = isMultiple\n    ? ({\n        expandedItemIds,\n        isMultiple,\n        onChange,\n      } as IsMultiple<T>)\n    : ({\n        expandedItemId,\n        isMultiple,\n        onChange,\n      } as IsNotMultiple<T>);\n\n  return (\n    <Component\n      className={classes}\n      style={style}\n      ref={accordionRef}\n      onKeyDown={handleKeyDown}\n      role=\"presentation\"\n      {...restAccordionProps}\n      {...htmlAttributes}\n    >\n      <AccordionContext.Provider value={contextValue}>\n        {children}\n      </AccordionContext.Provider>\n    </Component>\n  );\n};\n\nconst createItemId = (type: string, id: AccordionItemId) =>\n  `ndl-accordionitem${type}id-${id}`;\n\nconst BaseAccordionItem = <\n  T extends AccordionItemId,\n  U extends React.ElementType = 'div',\n>({\n  itemId,\n  children,\n  title,\n  className = '',\n  arrowPosition = 'leading',\n  isDisabled = false,\n  onExpandedChange,\n  htmlAttributes,\n  style,\n  as,\n  titleTypographyVariant = 'subheading-medium',\n  hasDivider = true,\n  trailingContent,\n  headingLevel = 2,\n}: PolymorphicCommonProps<U, AccordionItemProps<T>>) => {\n  const contentRef = useRef<HTMLDivElement>(null);\n  const innerContentRef = useRef<HTMLDivElement>(null);\n  const itemElementId = createItemId('item', itemId);\n  const headerElementId = createItemId('header', itemId);\n  const buttonElementId = createItemId('button', itemId);\n  const panelElementId = createItemId('panel', itemId);\n  const Component: React.ElementType = as || 'div';\n\n  const context = useAccordionContext();\n  const { isMultiple } = context;\n\n  const isExpanded = isMultiple\n    ? context.expandedItemIds.includes(itemId)\n    : context.expandedItemId === itemId;\n\n  const handleOnClick = useCallback(() => {\n    if (isDisabled) {\n      return;\n    }\n\n    // Custom callback to call.\n    if (onExpandedChange !== undefined) {\n      onExpandedChange(!isExpanded);\n    }\n\n    if (isMultiple) {\n      const { expandedItemIds, onChange }: IsMultiple<T> = context;\n      // Multiple expanded.\n      if (isExpanded) {\n        // Remove from list.\n        const newArray: T[] = expandedItemIds.filter(\n          (activeId) => activeId !== itemId,\n        );\n        onChange(newArray);\n      } else if (!isExpanded) {\n        // Add to list.\n        const newArray = [...expandedItemIds];\n        newArray.push(itemId);\n        onChange(newArray);\n      }\n    } else {\n      const { onChange }: IsNotMultiple<T> = context;\n      // Single expanded.\n      if (isExpanded) {\n        // Set null.\n        onChange(null);\n      } else if (!isExpanded) {\n        // Set to id.\n        onChange(itemId);\n      }\n    }\n\n    // The W3 WAI-ARIA states that focus can only happen on the header not the header button.\n    document.activeElement?.parentElement?.focus();\n  }, [isExpanded, isMultiple, isDisabled, itemId, onExpandedChange, context]);\n\n  const classes = classNames('ndl-accordion-item', className, {\n    'ndl-accordion-item-disabled': isDisabled,\n    'ndl-accordion-item-expanded': isExpanded,\n  });\n\n  const headerClasses = classNames('ndl-accordion-item-header', {\n    'ndl-accordion-item-header-disabled': isDisabled,\n  });\n\n  const iconClasses = classNames('ndl-accordion-item-header-icon-wrapper', {\n    'ndl-accordion-item-header-icon-wrapper-leading':\n      arrowPosition === 'leading',\n  });\n\n  const buttonClasses = classNames('ndl-accordion-item-header-button', {\n    'ndl-accordion-item-header-button-disabled': isDisabled,\n  });\n\n  const titleClasses = classNames('ndl-accordion-item-header-button-title', {\n    'ndl-accordion-item-header-button-title': isDisabled,\n    'ndl-accordion-item-header-button-title-leading':\n      arrowPosition === 'leading',\n  });\n\n  const contentClasses = classNames('ndl-accordion-item-content', {\n    'ndl-accordion-item-content-expanded': isExpanded,\n    'ndl-accordion-item-content-leading': arrowPosition === 'leading',\n  });\n\n  return (\n    <Component\n      className={classes}\n      style={style}\n      id={itemElementId}\n      {...htmlAttributes}\n    >\n      <div className={headerClasses} id={headerElementId}>\n        <Typography\n          as={`h${headingLevel}`}\n          variant={titleTypographyVariant}\n          className=\"ndl-accordion-item-heading\"\n        >\n          <button\n            type=\"button\"\n            id={buttonElementId}\n            onClick={handleOnClick}\n            className={buttonClasses}\n            aria-expanded={isExpanded}\n            aria-disabled={isDisabled}\n            aria-controls={panelElementId}\n            disabled={isDisabled}\n          >\n            <span className={iconClasses}>\n              <span className={titleClasses}>{title}</span>\n\n              <ChevronDownIconOutline\n                className={classNames('ndl-accordion-item-header-icon', {\n                  'ndl-expanded': isExpanded,\n                })}\n              />\n            </span>\n          </button>\n        </Typography>\n        {trailingContent && (\n          <Typography as=\"div\" variant=\"body-medium\">\n            {trailingContent}\n          </Typography>\n        )}\n      </div>\n\n      <div\n        id={panelElementId}\n        ref={contentRef}\n        className={contentClasses}\n        aria-hidden={!isExpanded}\n        aria-labelledby={buttonElementId}\n        role=\"region\"\n      >\n        {/* The <div> element has a child <button> element that allows keyboard interaction */}\n        {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}\n        <div\n          ref={innerContentRef}\n          className=\"ndl-accordion-item-content-inner\"\n          onKeyDown={(event) => event.stopPropagation()}\n        >\n          <Typography\n            variant=\"body-medium\"\n            className=\"ndl-accordion-item-content-text\"\n            as=\"div\"\n          >\n            {children}\n          </Typography>\n        </div>\n      </div>\n      {hasDivider && <Divider />}\n    </Component>\n  );\n};\n\n/**\n * @remarks\n * Where `T` is of the type `string | number | undefined`.\n *\n * `TypographyVariants` is of the type `'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'subheading-large' | 'subheading-medium' | 'subheading-small' | 'body-large' | 'body-medium' | 'body-small' | 'code' | 'label'`.\n */\nconst AccordionItem = <\n  T extends AccordionItemId,\n  U extends React.ElementType = 'div',\n>({\n  className,\n  ...restProps\n}: PolymorphicCommonProps<U, ClassicItemProps<T>>) => {\n  const classes = classNames('ndl-accordion-item-classic', className);\n\n  return <BaseAccordionItem {...restProps} className={classes} />;\n};\nAccordionItem.displayName = 'Accordion.Item';\n\n/**\n * @remarks\n * Where `T` is of the type `string | number | undefined`.\n */\ntype CleanItemProps<T extends AccordionItemId> = Omit<\n  AccordionItemProps<T>,\n  'hasDivider'\n>;\n\nconst CleanItem = <\n  T extends AccordionItemId,\n  U extends React.ElementType = 'div',\n>({\n  className,\n  ...restProps\n}: PolymorphicCommonProps<U, CleanItemProps<T>>) => {\n  const classes = classNames('ndl-accordion-item-clean', className);\n\n  return (\n    <BaseAccordionItem {...restProps} className={classes} hasDivider={false} />\n  );\n};\n\nCleanItem.displayName = 'Accordion.CleanItem';\n\nconst Accordion = Object.assign(AccordionComponent, {\n  CleanItem: CleanItem,\n  Item: AccordionItem,\n});\n\nexport { Accordion };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6DE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;AA+DQ,MAAA,aAAA,CAAA,mBAAiB,gBAAA;AA+NzB,MAAA,aAAA,CAAA,WAAA;AAsBA,MAAA,aAAA,CAAA,WAAA;AA5UF,MAAM,oBACJ,kBACA,UACA,YAA6B,WACV;CACnB,MAAM,aAAa,iBAAiB,QAAA,qBAA8B;CAClE,IAAI,CAAC,YACH,OAAO;CAGT,OAAO,UAAU,WAAW,YAAY,QAAQ;AAClD;AAEA,MAAM,qBAAqB,SAAS,mBAGlC,MAU+C;CAV/C,IAAA,EACA,UACA,IACA,YACA,UACA,WACA,OACA,gBACA,QAAA,MACG,YAAA,yBAAA,MAAA,SAAA;CAEH,MAAM,eAAe,OAAU,IAAI;CAEnC,oBAAoB,WAAW,aAAa,OAAQ;CAEpD,MAAM,YAA+B,MAAM;CAI3C,MAAM,iBAAiB,UAA+C;EAEpE,IAAI,CADqB,aAAa,SAEpC;EAEF,MAAM,gBAAgB,SAAS;EAC/B,IAAI,MAAM,QAAQ,aAAa;GAC7B,MAAM,eAAe;GACrB,MAAM,gBAAgB;GACtB,MAAM,oBAAoB,iBACxB,eAAA,yDAEA,MACF;GACA,MAAM,YAAA,sBAAA,QAAA,sBAAA,KAAA,IAAA,KAAA,IAAY,kBAAmB;GAErC,IAAI,aAAa,qBAAqB,aACpC,mBAAmB,SAAwB;EAE/C,OAAO,IAAI,MAAM,QAAQ,WAAW;GAClC,MAAM,eAAe;GACrB,MAAM,gBAAgB;GACtB,MAAM,oBAAoB,iBACxB,eAAA,yDAEA,MACF;GACA,MAAM,YAAA,sBAAA,QAAA,sBAAA,KAAA,IAAA,KAAA,IAAY,kBAAmB;GAErC,IAAI,aAAa,qBAAqB,aACpC,mBAAmB,SAAw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