{"version":3,"sources":["jsdelivr-header.js","/npm/@radix-ui/react-focus-scope@1.3.1/src/index.ts","/npm/@radix-ui/react-focus-scope@1.3.1/src/focus-scope.tsx"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,kzBCNA,cAAA,GAAA,SAAA,cAAA,CAAA,WAAA,IAAA,WAAA,yBAAA,IAAA,yBAAA,KAAA,IAAA,WAAA,oBAAA,IAAA,oBAAA,4BAAA,IAAA,8BAAA,OAAA,QAAA,aAAA,eCAA,IAAA,MAAuB,QAAA,QAAA,UACvB,0BAAgC,QAAA,gCAChC,uBAA0B,QAAA,6BAC1B,8BAA+B,QAAA,oCA2OzB,mBAAA,QAAA,qBAzOA,mBAAqB,8BACrB,qBAAuB,gCACvB,cAAgB,CAAE,SAAS,EAAO,YAAY,GAgD9C,WAAmC,MAAA,WACvC,OAAA,SAAoB,EAAO,GACzB,MAAM,KACJ,GAAO,EAAA,QACP,GAAU,EAAA,SACV,EACA,iBAAkB,EAClB,mBAAoB,KACjB,GACD,GACG,EAAW,GAAsB,MAAA,SAA6B,MAC/D,GAAA,EAAmB,8BAAA,gBAAe,GAClC,GAAA,EAAqB,8BAAA,gBAAe,GACpC,EAA8B,MAAA,OAA2B,MACzD,GAAA,EAAe,0BAAA,iBAAgB,EAAc,GAO7C,EAAoB,MAAA,OAAO,GAC3B,MAAA,UAAU,KACd,EAAY,QAAU,IAExB,MAAM,EAAwB,MAAA,YAC3B,KACM,MACD,GAAW,SAAS,IACjB,QAAQ,EAAY,SAAS,KAAM,GAAW,EAAO,SAAS,MAEvE,CAAC,IAGG,EAAmB,MAAA,OAAO,CAC9B,QAAQ,EACR,KAAA,GACE,KAAK,QAAS,CAChB,EACA,MAAA,GACE,KAAK,QAAS,CAChB,IACC,QAGG,MAAA,UAAU,KACd,GAAI,EAAS,CACX,IAAS,EAAT,SAAuB,GACrB,GAAI,EAAW,SAAW,EAAW,OACrC,MAAM,EAAS,EAAM,OACjB,EAAgB,GAClB,EA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3B,IAAY,GAA4B,kBAAkB,IAAY,GACxE,EAAQ,QACZ,CACF,CAxJS,OAAA,yBAAA,4BASA,OAAA,4BAAA,+BAgBA,OAAA,oBAAA,uBAiBA,OAAA,WAAA,cAWA,OAAA,iBAAA,oBAiBA,OAAA,sBAAA,yBA8BA,OAAA,YAAA,eAqBA,OAAA,SAAA,YAWA,OAAA,kBAAA,qBAOA,OAAA,MAAA,SAoBT,IAAM,iBAAmB,yBAEzB,SAAS,yBAEP,IAAI,EAAyB,GAE7B,MAAO,CACL,GAAA,CAAI,GAEF,MAAM,EAAmB,EAAM,GAC3B,IAAe,GACjB,GAAkB,QAGpB,EAAQ,YAAY,EAAO,GAC3B,EAAM,QAAQ,EAChB,EAEA,MAAA,CAAO,GACL,EAAQ,YAAY,EAAO,GAC3B,EAAM,IAAI,QACZ,EAEJ,CAEA,SAAS,YAAe,EAAY,GAClC,MAAM,EAAe,IAAI,GACnB,EAAQ,EAAa,QAAQ,GAInC,OAHc,IAAV,GACF,EAAa,OAAO,EAAO,GAEtB,CACT,CAEA,SAAS,YAAY,GACnB,OAAO,EAAM,OAAQ,GAA0B,MAAjB,EAAK,QACrC,CAlCS,OAAA,uBAAA,0BAuBA,OAAA,YAAA,eASA,OAAA,YAAA","file":"/npm/@radix-ui/react-focus-scope@1.3.1/dist/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.48.0.\n * Original file: /npm/@radix-ui/react-focus-scope@1.3.1/dist/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","'use client';\nexport {\n  FocusScope,\n  FocusScopeBranchProvider,\n  useFocusScopeBranchRegistry,\n  useFocusScopeBranch,\n  //\n  Root,\n} from './focus-scope';\nexport type {\n  FocusScopeProps,\n  FocusScopeBranchProviderProps,\n  FocusScopeBranchRegistry,\n} from './focus-scope';\n","import * as React from 'react';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\n\nconst AUTOFOCUS_ON_MOUNT = 'focusScope.autoFocusOnMount';\nconst AUTOFOCUS_ON_UNMOUNT = 'focusScope.autoFocusOnUnmount';\nconst EVENT_OPTIONS = { bubbles: false, cancelable: true };\n\ntype FocusableTarget = HTMLElement | { focus(): void };\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope\n * -----------------------------------------------------------------------------------------------*/\n\ntype FocusScopeElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface FocusScopeProps extends PrimitiveDivProps {\n  /**\n   * When `true`, tabbing from last item will focus first tabbable\n   * and shift+tab from first item will focus last tababble.\n   * @defaultValue false\n   */\n  loop?: boolean | undefined;\n\n  /**\n   * When `true`, focus cannot escape the focus scope via keyboard,\n   * pointer, or a programmatic focus.\n   * @defaultValue false\n   */\n  trapped?: boolean | undefined;\n\n  /**\n   * A list of nodes that should be treated as part of the focus scope even\n   * though they don't live within the scope's DOM subtree (eg. portalled\n   * content of a nested, non-modal layer). When the scope is `trapped`, focus\n   * is allowed to move into these branches without being reclaimed.\n   *\n   * See: https://github.com/radix-ui/primitives/issues/3423\n   */\n  branches?: HTMLElement[] | undefined;\n\n  /**\n   * Event handler called when auto-focusing on mount.\n   * Can be prevented.\n   */\n  onMountAutoFocus?: { bivarianceHack(event: Event): void }['bivarianceHack'] | undefined;\n\n  /**\n   * Event handler called when auto-focusing on unmount.\n   * Can be prevented.\n   */\n  onUnmountAutoFocus?: { bivarianceHack(event: Event): void }['bivarianceHack'] | undefined;\n}\n\nconst FocusScope = /* @__PURE__ */ React.forwardRef<FocusScopeElement, FocusScopeProps>(\n  function FocusScope(props, forwardedRef) {\n    const {\n      loop = false,\n      trapped = false,\n      branches,\n      onMountAutoFocus: onMountAutoFocusProp,\n      onUnmountAutoFocus: onUnmountAutoFocusProp,\n      ...scopeProps\n    } = props;\n    const [container, setContainer] = React.useState<HTMLElement | null>(null);\n    const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);\n    const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);\n    const lastFocusedElementRef = React.useRef<HTMLElement | null>(null);\n    const composedRefs = useComposedRefs(forwardedRef, setContainer);\n\n    // Keep the latest branches in a ref so the trap effect below doesn't need to resubscribe its\n    // listeners whenever the branch list updates. We sync it in the commit phase (not during render)\n    // to stay safe under concurrent rendering, where a render can be discarded or replayed. The trap's\n    // focus event handlers only run in response to user interaction (well after commit), so reading\n    // the ref from them always sees the committed branch list.\n    const branchesRef = React.useRef(branches);\n    React.useEffect(() => {\n      branchesRef.current = branches;\n    });\n    const isTargetInScope = React.useCallback(\n      (target: HTMLElement | null) => {\n        if (!target) return false;\n        if (container?.contains(target)) return true;\n        return Boolean(branchesRef.current?.some((branch) => branch.contains(target)));\n      },\n      [container],\n    );\n\n    const focusScope = React.useRef({\n      paused: false,\n      pause() {\n        this.paused = true;\n      },\n      resume() {\n        this.paused = false;\n      },\n    }).current;\n\n    // Takes care of trapping focus if focus is moved outside programmatically for example\n    React.useEffect(() => {\n      if (trapped) {\n        function handleFocusIn(event: FocusEvent) {\n          if (focusScope.paused || !container) return;\n          const target = event.target as HTMLElement | null;\n          if (isTargetInScope(target)) {\n            lastFocusedElementRef.current = target;\n          } else {\n            focus(lastFocusedElementRef.current, { select: true });\n          }\n        }\n\n        function handleFocusOut(event: FocusEvent) {\n          if (focusScope.paused || !container) return;\n          const relatedTarget = event.relatedTarget as HTMLElement | null;\n\n          // A `focusout` event with a `null` `relatedTarget` will happen in at\n          // least two cases:\n          // 1. When the user switches app/tabs/windows/the browser itself loses\n          //    focus.\n          // 2. In Google Chrome, when the focused element is removed from the\n          //    DOM.\n          //\n          // We let the browser do its thing here because:\n          // 1. The browser already keeps a memory of what's focused for when\n          //    the page gets refocused.\n          // 2. In Google Chrome, if we try to focus the deleted focused element\n          //    (as per below), it throws the CPU to 100%, so we avoid doing\n          //    anything for this reason here too.\n          if (relatedTarget === null) return;\n\n          // If the focus has moved to an actual legitimate element\n          // (`relatedTarget !== null`) that is outside the container (and any\n          // registered branches), we move focus to the last valid focused\n          // element inside.\n          if (!isTargetInScope(relatedTarget)) {\n            focus(lastFocusedElementRef.current, { select: true });\n          }\n        }\n\n        // When the focused element gets removed from the DOM, browsers move focus\n        // back to the document.body. In this case, we move focus to the container\n        // to keep focus trapped correctly.\n        function handleMutations(mutations: MutationRecord[]) {\n          const focusedElement = document.activeElement as HTMLElement | null;\n          if (focusedElement !== document.body) return;\n          for (const mutation of mutations) {\n            if (mutation.removedNodes.length > 0) focus(container);\n          }\n        }\n\n        document.addEventListener('focusin', handleFocusIn);\n        document.addEventListener('focusout', handleFocusOut);\n        const mutationObserver = new MutationObserver(handleMutations);\n        if (container) mutationObserver.observe(container, { childList: true, subtree: true });\n\n        return () => {\n          document.removeEventListener('focusin', handleFocusIn);\n          document.removeEventListener('focusout', handleFocusOut);\n          mutationObserver.disconnect();\n        };\n      }\n    }, [trapped, container, focusScope.paused, isTargetInScope]);\n\n    React.useEffect(() => {\n      if (container) {\n        focusScopesStack.add(focusScope);\n        const previouslyFocusedElement = document.activeElement as HTMLElement | null;\n        const hasFocusedCandidate = container.contains(previouslyFocusedElement);\n\n        if (!hasFocusedCandidate) {\n          const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);\n          container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n          container.dispatchEvent(mountEvent);\n          if (!mountEvent.defaultPrevented) {\n            focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });\n            if (document.activeElement === previouslyFocusedElement) {\n              focus(container);\n            }\n          }\n        }\n\n        return () => {\n          container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);\n          const ownerDocument = container.ownerDocument;\n          const UnmountEvent = CustomEvent;\n\n          // We hit a react bug (fixed in v17) with focusing in unmount.\n          // We need to delay the focus a little to get around it for now.\n          // See: https://github.com/facebook/react/issues/17894\n          setTimeout(() => {\n            const unmountEvent = new UnmountEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);\n            container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n            container.dispatchEvent(unmountEvent);\n            if (!unmountEvent.defaultPrevented) {\n              focus(previouslyFocusedElement ?? ownerDocument.body, { select: true });\n            }\n            // we need to remove the listener after we `dispatchEvent`\n            container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);\n\n            focusScopesStack.remove(focusScope);\n          }, 0);\n        };\n      }\n    }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);\n\n    // Takes care of looping focus (when tabbing whilst at the edges)\n    const handleKeyDown = React.useCallback(\n      (event: React.KeyboardEvent) => {\n        if (!loop && !trapped) return;\n        if (focusScope.paused) return;\n\n        const isTabKey = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey;\n        const focusedElement = document.activeElement as HTMLElement | null;\n\n        if (isTabKey && focusedElement) {\n          const container = event.currentTarget as HTMLElement;\n          const [first, last] = getTabbableEdges(container);\n          const hasTabbableElementsInside = first && last;\n\n          // we can only wrap focus if we have tabbable edges\n          if (!hasTabbableElementsInside) {\n            if (focusedElement === container) event.preventDefault();\n          } else {\n            if (!event.shiftKey && focusedElement === last) {\n              event.preventDefault();\n              if (loop) focus(first, { select: true });\n            } else if (event.shiftKey && focusedElement === first) {\n              event.preventDefault();\n              if (loop) focus(last, { select: true });\n            }\n          }\n        }\n      },\n      [loop, trapped, focusScope.paused],\n    );\n\n    return (\n      <Primitive.div tabIndex={-1} {...scopeProps} ref={composedRefs} onKeyDown={handleKeyDown} />\n    );\n  },\n);\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope branch registry\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * Lets portalled content that is a React descendant of a (modal) layer — but rendered outside of\n * that layer's DOM subtree — register itself as a \"branch\" of the layer's focus scope.\n *\n * A modal container (eg. `Dialog`) creates a registry via `useFocusScopeBranchRegistry`, renders a\n * `FocusScopeBranchProvider` around its children, and passes the collected `nodes` to its trapped\n * `FocusScope` (so focus isn't reclaimed from the branch) and, if applicable, to its `RemoveScroll`\n * `shards` (so the branch remains scrollable). Nested layers (eg. a non-modal `Popover`) register\n * their content node with `useFocusScopeBranch`.\n *\n * See: https://github.com/radix-ui/primitives/issues/3423\n */\ninterface FocusScopeBranchRegistry {\n  add: (node: HTMLElement) => void;\n  remove: (node: HTMLElement) => void;\n}\n\nconst FocusScopeBranchContext = React.createContext<FocusScopeBranchRegistry | null>(null);\n\ninterface FocusScopeBranchProviderProps {\n  /**\n   * The registry nested layers should register themselves with. When nullish the provider is\n   * transparent, letting nested layers register against the next registry up the tree instead. This\n   * is the case for layers that don't trap focus or lock scroll, which have nothing to host.\n   */\n  registry: FocusScopeBranchRegistry | null | undefined;\n  children?: React.ReactNode | undefined;\n}\n\nfunction FocusScopeBranchProvider({ registry, children }: FocusScopeBranchProviderProps) {\n  if (!registry) {\n    return children;\n  }\n  return (\n    <FocusScopeBranchContext.Provider value={registry}>{children}</FocusScopeBranchContext.Provider>\n  );\n}\n\nfunction useFocusScopeBranchRegistry() {\n  const [nodes, setNodes] = React.useState<HTMLElement[]>([]);\n  const registry = React.useMemo<FocusScopeBranchRegistry>(\n    () => ({\n      add: (node) => setNodes((prev) => (prev.includes(node) ? prev : [...prev, node])),\n      remove: (node) => setNodes((prev) => prev.filter((current) => current !== node)),\n    }),\n    [],\n  );\n  return { nodes, registry } as const;\n}\n\n/**\n * Registers `node` as a branch of the nearest ancestor `FocusScopeBranchProvider`. No-ops when\n * there is no ancestor registry (eg. the layer isn't nested inside a modal layer).\n */\nfunction useFocusScopeBranch(node: HTMLElement | null) {\n  const registry = React.useContext(FocusScopeBranchContext);\n  React.useEffect(() => {\n    if (!node || !registry) return;\n    registry.add(node);\n    return () => registry.remove(node);\n  }, [node, registry]);\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Utils\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * Attempts focusing the first element in a list of candidates.\n * Stops when focus has actually moved.\n */\nfunction focusFirst(candidates: HTMLElement[], { select = false } = {}) {\n  const previouslyFocusedElement = document.activeElement;\n  for (const candidate of candidates) {\n    focus(candidate, { select });\n    if (document.activeElement !== previouslyFocusedElement) return;\n  }\n}\n\n/**\n * Returns the first and last tabbable elements inside a container.\n */\nfunction getTabbableEdges(container: HTMLElement) {\n  const candidates = getTabbableCandidates(container);\n  const first = findVisible(candidates, container);\n  const last = findVisible(candidates.reverse(), container);\n  return [first, last] as const;\n}\n\n/**\n * Returns a list of potential tabbable candidates.\n *\n * NOTE: This is only a close approximation. For example it doesn't take into account cases like when\n * elements are not visible. This cannot be worked out easily by just reading a property, but rather\n * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately.\n *\n * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker\n * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1\n */\nfunction getTabbableCandidates(container: HTMLElement) {\n  const nodes: HTMLElement[] = [];\n  const document = container.ownerDocument;\n  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {\n    acceptNode: (node: Element) => {\n      const isHiddenInput =\n        node.tagName === 'INPUT' && (node as HTMLInputElement).type === 'hidden';\n      if ((node as HTMLInputElement).disabled || (node as HTMLElement).hidden || isHiddenInput) {\n        return NodeFilter.FILTER_SKIP;\n      }\n      // `.tabIndex` is not the same as the `tabindex` attribute. It works on the\n      // runtime's understanding of tabbability, so this automatically accounts\n      // for any kind of element that could be tabbed to.\n      return (node as HTMLElement).tabIndex >= 0\n        ? NodeFilter.FILTER_ACCEPT\n        : NodeFilter.FILTER_SKIP;\n    },\n  });\n  while (walker.nextNode()) {\n    nodes.push(walker.currentNode as HTMLElement);\n  }\n  // we do not take into account the order of nodes with positive `tabIndex` as it\n  // hinders accessibility to have tab order different from visual order.\n  return nodes;\n}\n\n/**\n * Returns the first visible element in a list.\n * NOTE: Only checks visibility up to the `container`.\n */\nfunction findVisible(elements: HTMLElement[], container: HTMLElement) {\n  // `checkVisibility` performs a single native check for `visibility: hidden`\n  // and `display: none` across the ancestor chain. This avoids the repeated\n  // `getComputedStyle` calls per ancestor that the fallback path requires,\n  // which reduces the cost of style resolution triggered by earlier DOM writes\n  // (e.g. react-remove-scroll, DismissableLayer setting body styles).\n  const canUseCheckVisibility =\n    typeof container.checkVisibility === 'function' &&\n    container.checkVisibility({ checkVisibilityCSS: true });\n\n  for (const element of elements) {\n    const hidden = canUseCheckVisibility\n      ? !element.checkVisibility({ checkVisibilityCSS: true })\n      : isHidden(element, { upTo: container });\n    // we stop checking if it's hidden at the `container` level (excluding)\n    if (!hidden) {\n      return element;\n    }\n  }\n}\n\nfunction isHidden(node: HTMLElement, { upTo }: { upTo?: HTMLElement | undefined }) {\n  if (getComputedStyle(node).visibility === 'hidden') return true;\n  while (node) {\n    // we stop at `upTo` (excluding it)\n    if (upTo !== undefined && node === upTo) return false;\n    if (getComputedStyle(node).display === 'none') return true;\n    node = node.parentElement as HTMLElement;\n  }\n  return false;\n}\n\nfunction isSelectableInput(element: FocusableTarget): element is HTMLInputElement {\n  return (\n    (element as HTMLElement).tagName === 'INPUT' &&\n    typeof (element as HTMLInputElement).select === 'function'\n  );\n}\n\nfunction focus(element?: FocusableTarget | null, { select = false } = {}) {\n  // only focus if that element is focusable\n  if (element && element.focus) {\n    // Prefer the element's own document over the global one: they can differ for elements in\n    // another realm, and the global may no longer exist when this runs from the unmount timer.\n    const ownerDocument = (element as Partial<HTMLElement>).ownerDocument ?? document;\n    const previouslyFocusedElement = ownerDocument.activeElement;\n    // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users\n    element.focus({ preventScroll: true });\n    // only select if its not the same element, it supports selection and we need to select\n    if (element !== previouslyFocusedElement && isSelectableInput(element) && select)\n      element.select();\n  }\n}\n\n/* -------------------------------------------------------------------------------------------------\n * FocusScope stack\n * -----------------------------------------------------------------------------------------------*/\n\ntype FocusScopeAPI = { paused: boolean; pause(): void; resume(): void };\nconst focusScopesStack = createFocusScopesStack();\n\nfunction createFocusScopesStack() {\n  /** A stack of focus scopes, with the active one at the top */\n  let stack: FocusScopeAPI[] = [];\n\n  return {\n    add(focusScope: FocusScopeAPI) {\n      // pause the currently active focus scope (at the top of the stack)\n      const activeFocusScope = stack[0];\n      if (focusScope !== activeFocusScope) {\n        activeFocusScope?.pause();\n      }\n      // remove in case it already exists (because we'll re-add it at the top of the stack)\n      stack = arrayRemove(stack, focusScope);\n      stack.unshift(focusScope);\n    },\n\n    remove(focusScope: FocusScopeAPI) {\n      stack = arrayRemove(stack, focusScope);\n      stack[0]?.resume();\n    },\n  };\n}\n\nfunction arrayRemove<T>(array: T[], item: T) {\n  const updatedArray = [...array];\n  const index = updatedArray.indexOf(item);\n  if (index !== -1) {\n    updatedArray.splice(index, 1);\n  }\n  return updatedArray;\n}\n\nfunction removeLinks(items: HTMLElement[]) {\n  return items.filter((item) => item.tagName !== 'A');\n}\n\nexport {\n  FocusScope,\n  FocusScopeBranchProvider,\n  useFocusScopeBranchRegistry,\n  useFocusScopeBranch,\n  //\n  FocusScope as Root,\n};\nexport type { FocusScopeProps, FocusScopeBranchProviderProps, FocusScopeBranchRegistry };\n"]}