{"version":3,"file":"GlobalModal.mjs","names":[],"sources":["../../../../src/components/Modal/GlobalModal.tsx"],"sourcesContent":["import clsx from 'clsx';\nimport React, {\n  type ComponentProps,\n  type ComponentType,\n  type PropsWithChildren,\n  useCallback,\n  useEffect,\n  useMemo,\n  useRef,\n} from 'react';\nimport { FocusScope } from '@react-aria/focus';\n\nimport { AriaLiveOutlet } from '../Accessibility';\nimport { NotificationList as DefaultNotificationList } from '../Notifications';\nimport {\n  DialogManagerProvider,\n  ModalContextProvider,\n  modalDialogManagerId,\n  useChatContext,\n  useComponentContext,\n} from '../../context';\nimport {\n  DialogPortalEntry,\n  modalDialogId,\n  useModalDialog,\n  useModalDialogIsOpen,\n  useModalDialogIsTopmost,\n} from '../Dialog';\nimport { useResolvedModalAriaProps } from '../../a11y/hooks/useResolvedModalAriaProps';\nimport { useStableId } from '../UtilityComponents/useStableId';\n\nexport type ModalCloseEvent =\n  | KeyboardEvent\n  | React.KeyboardEvent\n  | React.MouseEvent<HTMLButtonElement | HTMLDivElement>;\n\nexport type ModalCloseSource = 'overlay' | 'button' | 'escape';\nexport type ModalInitialFocusStrategy = 'dialog' | 'firstElement';\n\nexport type ModalProps = {\n  /** Whether the modal is open. */\n  open: boolean;\n  /** Class applied to the modal root div. */\n  className?: string;\n  /** Stable ID for this modal instance. Generated when omitted. */\n  dialogId?: string;\n  /**\n   * Props forwarded to the dialog surface div. `className` is merged; `onKeyDown` runs first, and\n   * `preventDefault()` in it skips the built-in Escape and Enter handling.\n   */\n  dialogRootProps?: Omit<\n    ComponentProps<'div'>,\n    'aria-label' | 'aria-labelledby' | 'aria-describedby' | 'role'\n  >;\n  /** Accessible label for the modal dialog. Ignored when aria-labelledby is provided. */\n  'aria-label'?: string;\n  /** ID of the element that labels the modal dialog. */\n  'aria-labelledby'?: string;\n  /** ID of the element that describes the modal dialog. */\n  'aria-describedby'?: string;\n  /** ARIA role for the modal dialog surface. */\n  role?: 'alertdialog' | 'dialog';\n  /**\n   * Whether the dialog surface (`'dialog'`) or its first focusable descendant (`'firstElement'`)\n   * receives initial focus. Defaults to `'firstElement'`.\n   */\n  initialFocusStrategy?: ModalInitialFocusStrategy;\n  /**\n   * Returns the element to focus initially. It overrides `initialFocusStrategy`, and the dialog\n   * surface is focused when it returns `null`.\n   */\n  getInitialFocusElement?: (dialogElement: HTMLDivElement) => HTMLElement | null;\n  /** Close button component rendered on the overlay when provided. */\n  CloseButtonOnOverlay?: ComponentType<ComponentProps<'button'>>;\n  /**\n   * Called when the modal closes itself (overlay click, close button, Escape or the modal\n   * context's `close`), not when `open` turns false.\n   */\n  onClose?: (event: ModalCloseEvent) => void;\n  /** Called before closing; return `false` to prevent closing and `onClose`. */\n  onCloseAttempt?: (source: ModalCloseSource, event: ModalCloseEvent) => boolean;\n};\n\nexport const GlobalModal = ({\n  'aria-describedby': ariaDescribedby,\n  'aria-label': ariaLabel,\n  'aria-labelledby': ariaLabelledby,\n  children,\n  className,\n  CloseButtonOnOverlay,\n  dialogId,\n  dialogRootProps,\n  getInitialFocusElement,\n  initialFocusStrategy,\n  onClose,\n  onCloseAttempt,\n  open,\n  role = 'dialog',\n}: PropsWithChildren<ModalProps>) => {\n  const generatedDialogId = useStableId();\n  const resolvedDialogId = dialogId ?? `${modalDialogId}-${generatedDialogId}`;\n  const dialog = useModalDialog(resolvedDialogId);\n  const isOpen = useModalDialogIsOpen(resolvedDialogId);\n  const isTopmost = useModalDialogIsTopmost(resolvedDialogId);\n  const overlayRef = useRef<HTMLDivElement | null>(null);\n  const dialogRef = useRef<HTMLDivElement | null>(null);\n  const closeButtonRef = useRef<HTMLButtonElement | null>(null);\n  const closingRef = useRef(false);\n  const { theme } = useChatContext();\n  const { NotificationList = DefaultNotificationList } = useComponentContext();\n  const {\n    className: dialogRootClassName,\n    onKeyDown: dialogRootOnKeyDown,\n    ...dialogRootPropsRest\n  } = dialogRootProps ?? {};\n  // The base for label and description IDs must be unique per modal: `resolvedDialogId` carries a\n  // per-instance suffix, while the shared `modalDialogId` would collide across stacked modals.\n  const dialogLabelingBaseId = resolvedDialogId;\n  const resolvedInitialFocusStrategy: ModalInitialFocusStrategy =\n    initialFocusStrategy ?? 'firstElement';\n  const resolvedModalAriaProps = useResolvedModalAriaProps({\n    ariaDescribedby,\n    ariaLabel,\n    ariaLabelledby,\n    dialogId: dialogLabelingBaseId,\n  });\n\n  const maybeClose = useCallback(\n    (source: ModalCloseSource, event: ModalCloseEvent) => {\n      const allow = onCloseAttempt?.(source, event);\n      if (allow !== false) {\n        dialog.close();\n        closingRef.current = true;\n        onClose?.(event);\n      }\n    },\n    [dialog, onClose, onCloseAttempt],\n  );\n\n  const modalContextValue = useMemo<{ close: () => void; dialogId?: string }>(\n    () => ({\n      close: () => maybeClose('button', {} as ModalCloseEvent),\n      dialogId: dialogLabelingBaseId,\n    }),\n    [dialogLabelingBaseId, maybeClose],\n  );\n\n  const handleOverlayClick = (event: React.MouseEvent<HTMLDivElement>) => {\n    if (!isTopmost) return;\n    const target = event.target as HTMLDivElement;\n    if (overlayRef.current === target) {\n      maybeClose('overlay', event);\n    }\n  };\n\n  const handleCloseButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {\n    if (!isTopmost) return;\n    maybeClose('button', event);\n  };\n\n  const handleDialogKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    dialogRootOnKeyDown?.(event);\n    if (event.defaultPrevented || !isTopmost) return;\n\n    if (event.key === 'Escape') {\n      maybeClose('escape', event);\n      return;\n    }\n\n    // Initial focus can land on the dialog surface so the screen reader announces the dialog. Enter\n    // there moves focus to the default field (`[data-autofocus]`); the target check ignores Enter\n    // bubbling up from a control inside.\n    if (event.key === 'Enter' && event.target === dialogRef.current) {\n      const target = dialogRef.current?.querySelector<HTMLElement>('[data-autofocus]');\n      if (target) {\n        event.preventDefault();\n        target.focus();\n      }\n    }\n  };\n\n  // Syncs the `open` prop to dialog state. `closingRef` blocks a re-open after closing until the\n  // parent sets `open` to false.\n  useEffect(() => {\n    if (!open) {\n      closingRef.current = false;\n      if (isOpen) {\n        dialog.close();\n      }\n      return;\n    }\n    if (open && !isOpen && !closingRef.current) {\n      dialog.open();\n    }\n  }, [dialog, isOpen, open]);\n\n  useEffect(() => {\n    if (\n      !open ||\n      !isOpen ||\n      // Only the topmost modal takes initial focus, so an inert stacked one does not pull it away.\n      !isTopmost ||\n      (!getInitialFocusElement && resolvedInitialFocusStrategy === 'firstElement')\n    )\n      return;\n\n    const frame = requestAnimationFrame(() => {\n      const dialogElement = dialogRef.current;\n      if (!dialogElement) return;\n\n      const target = getInitialFocusElement?.(dialogElement) ?? dialogElement;\n\n      target.focus();\n    });\n\n    return () => cancelAnimationFrame(frame);\n  }, [getInitialFocusElement, isOpen, isTopmost, open, resolvedInitialFocusStrategy]);\n\n  if (!open || !isOpen) return null;\n\n  return (\n    <DialogPortalEntry dialogId={resolvedDialogId} dialogManagerId={modalDialogManagerId}>\n      <ModalContextProvider value={modalContextValue}>\n        <div\n          className={clsx(\n            'str-chat',\n            theme,\n            'str-chat__modal str-chat-react__modal str-chat__modal--open',\n            className,\n          )}\n          onClick={handleOverlayClick}\n          ref={overlayRef}\n        >\n          <FocusScope\n            autoFocus={\n              isTopmost &&\n              !getInitialFocusElement &&\n              resolvedInitialFocusStrategy === 'firstElement'\n            }\n            contain={isTopmost}\n            restoreFocus\n          >\n            <div\n              {...dialogRootPropsRest}\n              aria-describedby={resolvedModalAriaProps['aria-describedby']}\n              aria-label={resolvedModalAriaProps['aria-label']}\n              aria-labelledby={resolvedModalAriaProps['aria-labelledby']}\n              aria-modal={isTopmost ? 'true' : undefined}\n              className={clsx('str-chat__modal__dialog', dialogRootClassName)}\n              inert={isTopmost ? undefined : true}\n              onKeyDown={handleDialogKeyDown}\n              ref={dialogRef}\n              role={role}\n              tabIndex={isTopmost ? 0 : -1}\n            >\n              <DialogManagerProvider\n                id={`${resolvedDialogId}-floating-dialog-manager`}\n                portalDestinationProps={{\n                  captureOutsideClicks: true,\n                  className: 'str-chat__modal__floating-dialog-overlay',\n                }}\n              >\n                {children}\n                {/* The live-region outlet sits inside the active modal subtree (only the topmost\n                  carries `aria-modal`) so assistive technologies do not suppress announcements. */}\n                {isTopmost && <AriaLiveOutlet layer={1} />}\n              </DialogManagerProvider>\n            </div>\n          </FocusScope>\n          <NotificationList\n            className='str-chat__modal__notification-list'\n            panel='modal'\n            verticalAlignment='top'\n          />\n          {CloseButtonOnOverlay && (\n            <CloseButtonOnOverlay onClick={handleCloseButtonClick} ref={closeButtonRef} />\n          )}\n        </div>\n      </ModalContextProvider>\n    </DialogPortalEntry>\n  );\n};\n"],"mappings":";;;;;;;;;;;;;;;AAmFA,IAAa,eAAe,EAC1B,oBAAoB,iBACpB,cAAc,WACd,mBAAmB,gBACnB,UACA,WACA,sBACA,UACA,iBACA,wBACA,sBACA,SACA,gBACA,MACA,OAAO,eAC4B;CACnC,MAAM,oBAAoB,YAAY;CACtC,MAAM,mBAAmB,YAAY,gBAAoB;CACzD,MAAM,SAAS,eAAe,gBAAgB;CAC9C,MAAM,SAAS,qBAAqB,gBAAgB;CACpD,MAAM,YAAY,wBAAwB,gBAAgB;CAC1D,MAAM,aAAa,OAA8B,IAAI;CACrD,MAAM,YAAY,OAA8B,IAAI;CACpD,MAAM,iBAAiB,OAAiC,IAAI;CAC5D,MAAM,aAAa,OAAO,KAAK;CAC/B,MAAM,EAAE,UAAU,eAAe;CACjC,MAAM,EAAE,kBAAA,qBAAmB,qBAA4B,oBAAoB;CAC3E,MAAM,EACJ,WAAW,qBACX,WAAW,qBACX,GAAG,wBACD,mBAAmB,CAAC;CAGxB,MAAM,uBAAuB;CAC7B,MAAM,+BACJ,wBAAwB;CAC1B,MAAM,yBAAyB,0BAA0B;EACvD;EACA;EACA;EACA,UAAU;CACZ,CAAC;CAED,MAAM,aAAa,aAChB,QAA0B,UAA2B;EAEpD,IADc,iBAAiB,QAAQ,KAAK,MAC9B,OAAO;GACnB,OAAO,MAAM;GACb,WAAW,UAAU;GACrB,UAAU,KAAK;EACjB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