{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "core-popup",
  "type": "registry:lib",
  "title": "core/popup",
  "description": "Framework-free behaviour shared by the ui-* components (popup); no DOM, no lit. Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [],
  "registryDependencies": [
    "@kanok-ui/core-position"
  ],
  "files": [
    {
      "path": "src/core/popup.ts",
      "type": "registry:lib",
      "target": "components/ui/core/popup.ts",
      "content": "/**\n * What every popup (dropdown, combobox, multi-select, menu, date picker calendar, tooltip, toggletip, popover) does\n * while it is open, shared by the Lit elements and the headless React parts: follow its anchor, dismiss on a press\n * outside, and scroll its own list. The renderers pass in the DOM objects; this module needs no DOM itself.\n */\n\n/** The DOM members these helpers touch (a DOM `Element` / `ShadowRoot` / `Document` fits). */\nexport interface PopupNode {\n    readonly nodeType: number;\n    readonly parentNode: PopupNode | null;\n    /** A shadow root's host. */\n    readonly host?: PopupNode;\n    /** The slot an element is shown in (it is laid out, and scrolls, with that slot's tree). */\n    readonly assignedSlot?: PopupNode | null;\n    addEventListener(type: string, listener: Listener, options?: boolean | { capture?: boolean; passive?: boolean }): void;\n    removeEventListener(type: string, listener: Listener, options?: boolean | { capture?: boolean }): void;\n    getBoundingClientRect?(): Rect;\n}\n\n/** An event listener (a DOM `EventListener` takes any `Event`, which is an object). */\ntype Listener = (event: object) => void;\n\ninterface Rect {\n    readonly top: number;\n    readonly left: number;\n    readonly width: number;\n    readonly height: number;\n}\n\ninterface Observer {\n    observe(target: PopupNode): void;\n    disconnect(): void;\n}\n\n/** The window members `trackAnchor` uses (a DOM `Window` fits). */\nexport interface PopupWindow {\n    getComputedStyle(element: never): { overflowX: string; overflowY: string };\n    addEventListener(type: string, listener: () => void, options?: boolean | { capture?: boolean; passive?: boolean }): void;\n    removeEventListener(type: string, listener: () => void, options?: boolean | { capture?: boolean }): void;\n    requestAnimationFrame?(callback: () => void): number;\n    cancelAnimationFrame?(handle: number): void;\n    ResizeObserver?: new (callback: () => void) => Observer;\n    visualViewport?: { addEventListener(type: string, listener: () => void): void; removeEventListener(type: string, listener: () => void): void } | null;\n}\n\nimport { computePosition, type Box, type Placement, type Position, type Side } from './position.ts';\n\nconst ELEMENT = 1;\nconst FRAGMENT = 11; // a shadow root\n\n/**\n * The elements around `node` that can scroll, nearest first, through shadow roots (a modal's or side panel's body, a\n * micro app's container): `scroll` events don't cross a shadow boundary, so a listener on the window misses them.\n */\nexport function scrollAncestors(node: PopupNode, win: PopupWindow): PopupNode[] {\n    const found: PopupNode[] = [];\n    // the flat tree, as layout sees it: a slotted element sits in its slot (a ui-modal's scrolling body), a shadow root in its host\n    const up = (at: PopupNode) => at.assignedSlot ?? at.parentNode ?? null;\n    let at = up(node);\n    while (at) {\n        if (at.nodeType === FRAGMENT) {\n            at = at.host ?? null;\n            continue;\n        }\n        if (at.nodeType === ELEMENT) {\n            const { overflowX, overflowY } = win.getComputedStyle(at as never);\n            if (/auto|scroll|overlay|hidden/.test(overflowX + overflowY)) found.push(at);\n        }\n        at = up(at);\n    }\n    return found;\n}\n\n/**\n * Keeps an open popup on its anchor (Floating UI's autoUpdate, in short): `update` runs when the page or any scrolling\n * ancestor scrolls, the window or the visual viewport (an on-screen keyboard) changes, the anchor or the popup changes\n * size, and when the anchor moves for any other reason (content inserted above it, an animation): its box is checked\n * once a frame while open. Returns the function that stops it all.\n */\nexport function trackAnchor(anchor: PopupNode, floating: PopupNode, update: () => void, win: PopupWindow = globalThis as unknown as PopupWindow): () => void {\n    const passive = { passive: true };\n    const scrollers = scrollAncestors(anchor, win);\n    // placePopup reads them (the boxes that clip the anchor) instead of walking the tree again on every update\n    stateOf(floating).scrollers = scrollers;\n    for (const scroller of scrollers) scroller.addEventListener('scroll', update, passive);\n    // the page's own scroll (a scroll event bubbles from the document to the window; an element's doesn't bubble)\n    win.addEventListener('scroll', update, passive);\n    win.addEventListener('resize', update);\n    win.visualViewport?.addEventListener('resize', update);\n    win.visualViewport?.addEventListener('scroll', update);\n    const resized = win.ResizeObserver ? new win.ResizeObserver(update) : null;\n    resized?.observe(anchor);\n    resized?.observe(floating);\n    let last = anchor.getBoundingClientRect?.();\n    let frame: number | undefined;\n    const watch = () => {\n        const now = anchor.getBoundingClientRect?.();\n        if (now && last && (now.top !== last.top || now.left !== last.left || now.width !== last.width || now.height !== last.height)) update();\n        last = now;\n        frame = win.requestAnimationFrame?.(watch);\n    };\n    frame = win.requestAnimationFrame?.(watch);\n    return () => {\n        for (const scroller of scrollers) scroller.removeEventListener('scroll', update);\n        win.removeEventListener('scroll', update);\n        win.removeEventListener('resize', update);\n        win.visualViewport?.removeEventListener('resize', update);\n        win.visualViewport?.removeEventListener('scroll', update);\n        resized?.disconnect();\n        if (frame !== undefined) win.cancelAnimationFrame?.(frame);\n        // closed: the next opening starts fresh (the side asked for, the direction read again)\n        releasePopup(floating as PopupBox);\n    };\n}\n\n/** What `outsidePress` reads of a pointer event (a DOM `PointerEvent` fits). */\nexport interface PressEvent {\n    readonly pointerType: string;\n    readonly pointerId: number;\n    readonly clientX: number;\n    readonly clientY: number;\n}\n\n/** How far a finger may move between touching and lifting for it still to be a tap, in CSS pixels. */\nconst TAP_SLOP = 10;\n\n/**\n * Calls `onPress` for every press on the page (the popup's own outside-dismiss check decides what it means). A mouse or\n * a pen counts on `pointerdown`, as before. A finger counts only once it lifts, close to where it touched, as a tap: a\n * touch that starts a scroll (the browser sends `pointercancel`) or a drag doesn't close the popup. That is the\n * Popover API's light dismiss rule. Returns the function that stops listening.\n */\nexport function outsidePress<E extends PressEvent>(doc: PopupNode, onPress: (event: E) => void): () => void {\n    let touch: { id: number; x: number; y: number } | null = null;\n    const down = (event: E) => {\n        if (event.pointerType === 'touch') touch = { id: event.pointerId, x: event.clientX, y: event.clientY };\n        else onPress(event);\n    };\n    const up = (event: E) => {\n        const start = touch;\n        if (!start || event.pointerId !== start.id) return;\n        touch = null;\n        if (Math.hypot(event.clientX - start.x, event.clientY - start.y) <= TAP_SLOP) onPress(event);\n    };\n    const cancel = () => {\n        touch = null;\n    };\n    const onDown = down as Listener;\n    const onUp = up as Listener;\n    doc.addEventListener('pointerdown', onDown, true);\n    doc.addEventListener('pointerup', onUp, true);\n    doc.addEventListener('pointercancel', cancel, true);\n    return () => {\n        doc.removeEventListener('pointerdown', onDown, true);\n        doc.removeEventListener('pointerup', onUp, true);\n        doc.removeEventListener('pointercancel', cancel, true);\n    };\n}\n\n/** What `scrollIntoList` reads and sets (a DOM `Element` fits). */\nexport interface ListBox {\n    readonly parentElement: ListBox | null;\n    readonly scrollHeight: number;\n    readonly clientHeight: number;\n    readonly clientTop: number;\n    scrollTop: number;\n    getBoundingClientRect(): { top: number; bottom: number };\n}\n\n/**\n * Scrolls `item` into view inside its list (the nearest box between it and `list` that scrolls, `list` included)\n * and nothing else: `scrollIntoView` would also scroll the page whenever the popup sits partly outside the viewport (an\n * on-screen keyboard, zoom), which then moves the popup.\n */\nexport function scrollIntoList(item: ListBox, list: ListBox) {\n    let box: ListBox | null = item.parentElement;\n    while (box && box !== list && box.scrollHeight <= box.clientHeight) box = box.parentElement;\n    const scroller = box ?? list;\n    const view = scroller.getBoundingClientRect();\n    const top = view.top + scroller.clientTop;\n    const bottom = top + scroller.clientHeight;\n    const rect = item.getBoundingClientRect();\n    if (rect.top < top) scroller.scrollTop -= top - rect.top;\n    else if (rect.bottom > bottom) scroller.scrollTop += rect.bottom - bottom;\n}\n\n/** What `placePopup` reads and writes on the popup (a DOM `HTMLElement` fits). */\nexport interface PopupBox extends PopupNode {\n    getBoundingClientRect(): Rect;\n    readonly style: { setProperty(name: string, value: string): void; removeProperty(name: string): string };\n}\n\n/** A scrolling ancestor, as `placePopup` reads its visible part (a DOM `Element` fits). */\ninterface ClipBox {\n    getBoundingClientRect?(): Rect;\n    readonly clientTop?: number;\n    readonly clientLeft?: number;\n    readonly clientWidth?: number;\n    readonly clientHeight?: number;\n    readonly nodeName?: string;\n    matches?(selector: string): boolean;\n}\n\n/** In the top layer (an open popover, a modal dialog): nothing around it clips it. */\nfunction inTopLayer(node: ClipBox) {\n    try {\n        return !!node.matches?.(':popover-open, :modal');\n    } catch {\n        return false; // a browser without one of the selectors\n    }\n}\n\n/** The window members `placePopup` reads (a DOM `Window` fits). */\nexport interface PlaceWindow {\n    readonly scrollX: number;\n    readonly scrollY: number;\n    readonly devicePixelRatio?: number;\n    readonly document: { readonly documentElement: { readonly clientWidth: number; readonly clientHeight: number } };\n    readonly visualViewport?: { readonly width: number; readonly height: number; readonly offsetTop: number; readonly offsetLeft: number } | null;\n    readonly CSS?: { supports(condition: string): boolean };\n    getComputedStyle(element: never): { direction: string };\n}\n\nexport interface PlaceOptions {\n    /** Distance from the anchor (default 8). */\n    gap?: number;\n    /** Moves the popup down by this much once placed (a submenu sits 2px below its item's top, Carbon). */\n    nudgeY?: number;\n    /**\n     * Writes the room on its side as `--ui-available-height` / `--ui-available-width` (px), for a list or menu whose\n     * `max-height` takes `min(…, var(--ui-available-height))`: it scrolls instead of running past the screen.\n     */\n    size?: boolean;\n}\n\n/** What `placePopup` keeps about an open popup (cleared when `trackAnchor` stops). */\ninterface PopupState {\n    side?: Side;\n    rtl?: boolean;\n    scrollers?: PopupNode[];\n    hidden?: boolean;\n    /** Anchored with CSS anchor positioning: the anchor that carries `anchor-name`. */\n    anchored?: AnchorBox;\n}\n\n/** An anchor as the CSS anchor positioning fast path touches it (a DOM `Element` fits). */\ninterface AnchorBox {\n    readonly style?: { setProperty(name: string, value: string): void; removeProperty(name: string): string };\n    getRootNode?(): unknown;\n}\n\nlet anchorPositioning = false;\nlet anchorSeq = 0;\n\n/**\n * CSS anchor positioning for popups, opt-in (`setAnchorPositioning(true)`, for popups placed from then on) where the\n * browser has it (Chromium 125+, Safari 26+): the popup's top / left become `anchor()` offsets from its anchor, so the\n * browser itself keeps it on the anchor as a box around it scrolls, a scroll the compositor shows before any script\n * hears of it included. The engine still decides everything (side, shift, size, hide) and writes the same offsets each\n * update; where `anchor()` can't resolve, its fallback is the engine's own coordinate. Off by default: in Chromium an\n * anchor inside a modal dialog's scrolling body, or a submenu's item, resolves a few pixels from where the engine\n * measures it, so the script engine alone stays the default until the two agree everywhere.\n */\nexport function setAnchorPositioning(on: boolean) {\n    anchorPositioning = on;\n}\n\n/** Whether anchor() can reach `anchor` from `floating`: an anchor name is seen in its own tree and the trees inside it. */\nfunction canAnchor(anchor: AnchorBox, floating: PopupBox, win: PlaceWindow) {\n    if (!anchorPositioning || !anchor.style || !win.CSS?.supports('top: anchor(top)')) return false;\n    const target = anchor.getRootNode?.();\n    for (let root = (floating as AnchorBox).getRootNode?.() as { host?: AnchorBox } | undefined; root; root = root.host?.getRootNode?.() as { host?: AnchorBox } | undefined) {\n        if (root === target) return true;\n    }\n    return false;\n}\n\nconst states = new WeakMap<object, PopupState>();\nfunction stateOf(floating: object): PopupState {\n    let state = states.get(floating);\n    if (!state) {\n        state = {};\n        states.set(floating, state);\n    }\n    return state;\n}\n\n/** The visible area: the visual viewport (an on-screen keyboard or a zoom makes it smaller), within the layout viewport. */\nfunction visibleViewport(win: PlaceWindow) {\n    const root = win.document.documentElement;\n    const vv = win.visualViewport;\n    if (!vv) return { top: 0, left: 0, width: root.clientWidth, height: root.clientHeight };\n    const top = Math.max(0, vv.offsetTop);\n    const left = Math.max(0, vv.offsetLeft);\n    return { top, left, width: Math.min(vv.width, root.clientWidth - left), height: Math.min(vv.height, root.clientHeight - top) };\n}\n\n/**\n * The part of the viewport the scrolling ancestors leave visible (their padding boxes, overlapped), or undefined. It\n * stops at the first one in the top layer (a submenu's menu): the boxes around that one don't clip what is inside it.\n */\nfunction clipOf(scrollers: readonly PopupNode[]): Box | undefined {\n    let clip: Box | undefined;\n    for (const node of scrollers as readonly ClipBox[]) {\n        // the page's own scroller is the viewport, which the geometry has already\n        if (node.nodeName === 'HTML' || node.nodeName === 'BODY' || !node.getBoundingClientRect) continue;\n        const r = node.getBoundingClientRect();\n        const box = { top: r.top + (node.clientTop ?? 0), left: r.left + (node.clientLeft ?? 0), width: node.clientWidth ?? r.width, height: node.clientHeight ?? r.height };\n        if (!clip) {\n            clip = box;\n            if (inTopLayer(node)) break; // a submenu's item: its own menu clips it, the menus below that don't\n            continue;\n        }\n        const top = Math.max(clip.top, box.top);\n        const left = Math.max(clip.left, box.left);\n        const bottom = Math.min(clip.top + clip.height, box.top + box.height);\n        const right = Math.min(clip.left + clip.width, box.left + box.width);\n        clip = { top, left, width: Math.max(0, right - left), height: Math.max(0, bottom - top) };\n        if (inTopLayer(node)) break;\n    }\n    return clip;\n}\n\n/** `value` rounded to the device's pixels: a popup lands on whole pixels, so it doesn't shimmer as it follows a scroll. */\nconst toDevice = (value: number, dpr: number) => Math.round(value * dpr) / dpr;\n\n/**\n * Places an open popup (`position: absolute` in the top layer, so in document coordinates) beside `anchor` with\n * core/position: flip (keeping its side while open), shift along the anchor, the room left on its side (`size`), hidden\n * while the anchor is out of view; in the visual viewport, on whole device pixels. Run it again on every change\n * `trackAnchor` reports. Returns the position used (its `side` for carets and side-specific styles).\n */\nexport function placePopup(anchor: PopupNode & { getBoundingClientRect(): Rect }, floating: PopupBox, placement: Placement, options: PlaceOptions = {}, win: PlaceWindow = globalThis as unknown as PlaceWindow): Position {\n    const state = stateOf(floating);\n    state.rtl ??= win.getComputedStyle(anchor as never).direction === 'rtl';\n    state.scrollers ??= scrollAncestors(anchor, win as unknown as PopupWindow);\n    // measured at its own size: the room written last time doesn't limit what it needs now\n    if (options.size) floating.style.removeProperty('--ui-available-height');\n    const a = anchor.getBoundingClientRect();\n    const placed = computePosition(a, floating.getBoundingClientRect(), visibleViewport(win), placement, {\n        gap: options.gap,\n        rtl: state.rtl,\n        current: state.side,\n        clip: clipOf(state.scrollers),\n    });\n    state.side = placed.side;\n    const dpr = win.devicePixelRatio || 1;\n    const top = toDevice(placed.top + win.scrollY + (options.nudgeY ?? 0), dpr);\n    const left = toDevice(placed.left + win.scrollX, dpr);\n    const fast = anchor as AnchorBox;\n    if (state.anchored && state.anchored !== fast) {\n        state.anchored.style?.removeProperty('anchor-name'); // another anchor now (a range picker's other box)\n        state.anchored = undefined;\n    }\n    if (state.anchored || canAnchor(fast, floating, win)) {\n        // the same place as an offset from the anchor, which the browser then keeps between updates\n        if (!state.anchored) {\n            state.anchored = fast;\n            const name = `--ui-popup-anchor-${++anchorSeq}`;\n            fast.style!.setProperty('anchor-name', name);\n            floating.style.setProperty('position-anchor', name);\n        }\n        const ay = a.top + win.scrollY;\n        const ax = a.left + win.scrollX;\n        floating.style.setProperty('top', `calc(anchor(top, ${ay}px) + ${top - ay}px)`);\n        floating.style.setProperty('left', `calc(anchor(left, ${ax}px) + ${left - ax}px)`);\n    } else {\n        floating.style.setProperty('top', `${top}px`);\n        floating.style.setProperty('left', `${left}px`);\n    }\n    if (options.size) {\n        floating.style.setProperty('--ui-available-height', `${Math.floor(placed.availableHeight)}px`);\n        floating.style.setProperty('--ui-available-width', `${Math.floor(placed.availableWidth)}px`);\n    }\n    if (placed.anchorHidden !== !!state.hidden) {\n        state.hidden = placed.anchorHidden;\n        if (placed.anchorHidden) floating.style.setProperty('visibility', 'hidden');\n        else floating.style.removeProperty('visibility');\n    }\n    return placed;\n}\n\n/** Forgets what `placePopup` kept about `floating` (it closed), so its next opening starts fresh and it isn't left hidden. */\nexport function releasePopup(floating: PopupBox) {\n    const state = states.get(floating);\n    if (state?.hidden) floating.style.removeProperty('visibility');\n    if (state?.anchored) {\n        state.anchored.style?.removeProperty('anchor-name');\n        floating.style.removeProperty('position-anchor');\n    }\n    states.delete(floating);\n}\n"
    }
  ]
}
