{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "shared-element",
  "type": "registry:lib",
  "title": "shared/element",
  "description": "Internal module shared by the ui-* components (element). 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": [
    "lit@^3.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/shared/element.ts",
      "type": "registry:lib",
      "target": "components/ui/primitives/shared/element.ts",
      "content": "import { LitElement, adoptStyles, css, type CSSResultGroup } from 'lit';\n\nconst INTERNALS_PREFIX = 'hydrate-internals-';\n\n/** How many elements of each class are on the page (see UiElement.connectedCallback). */\nconst connectedCount = new WeakMap<typeof UiElement, number>();\n/** The viewport size when the last element of a class left the page. */\nconst leftAt = new WeakMap<typeof UiElement, string>();\nconst viewportSize = () => `${innerWidth}x${innerHeight}`;\n/** Whether a class's styles hold @media rules (see UiElement.connectedCallback). */\nconst mediaRules = new WeakMap<typeof UiElement, boolean>();\n/** Classes whose first element came back to a resized page in this task: its siblings connecting with it restyle too. */\nconst restyling = new Set<typeof UiElement>();\n\n/**\n * `hidden` hides every element, as it hides a native one: an element's own `:host { display }` would\n * otherwise beat the browser's `[hidden] { display: none }`. After the element's own styles, so it wins\n * over its `:host` / `:host([attr])` display; an element that keeps a hidden part in the layout says so\n * with a more specific rule (vertical tab panels: `:host([data-vertical][hidden])`).\n */\nconst hiddenHost = css`\n    :host([hidden]) {\n        display: none;\n    }\n`;\n\n/** What the user did in a server-rendered control before the element upgraded: typed, chose, ticked, focused. */\ninterface ServerInput {\n    index: number;\n    tag: string;\n    type: string;\n    value?: string;\n    checked?: boolean;\n    selected?: boolean[];\n    focused: boolean;\n    selection?: [number, number];\n}\n\nconst CONTROLS = 'input, textarea, select';\n\n/** The server-rendered controls the user changed or focused (by position, to find their re-rendered twins). */\nfunction readServerInput(root: ShadowRoot): ServerInput[] {\n    const found: ServerInput[] = [];\n    root.querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(CONTROLS).forEach((el, index) => {\n        const entry: ServerInput = { index, tag: el.localName, type: el.type, focused: root.activeElement === el };\n        if (el instanceof HTMLSelectElement) {\n            const selected = [...el.options].map((o) => o.selected);\n            if ([...el.options].some((o) => o.selected !== o.defaultSelected)) entry.selected = selected;\n        } else if (el instanceof HTMLInputElement && (el.type === 'checkbox' || el.type === 'radio')) {\n            if (el.checked !== el.defaultChecked) entry.checked = el.checked;\n        } else if (!(el instanceof HTMLInputElement && el.type === 'file') && el.value !== el.defaultValue) {\n            entry.value = el.value;\n            if (el.selectionStart !== null && el.selectionEnd !== null) entry.selection = [el.selectionStart, el.selectionEnd];\n        }\n        if (entry.focused || entry.value !== undefined || entry.checked !== undefined || entry.selected) found.push(entry);\n    });\n    return found;\n}\n\n/**\n * Hands it to the re-rendered controls as if the user did it now (input / change events, so the element takes the\n * value through its own handlers), and gives the focus back.\n */\nfunction restoreServerInput(root: ShadowRoot | HTMLElement | DocumentFragment, saved: ServerInput[]) {\n    const controls = [...root.querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(CONTROLS)];\n    for (const entry of saved) {\n        const el = controls[entry.index];\n        if (!el || el.localName !== entry.tag || el.type !== entry.type) continue;\n        if (entry.selected && el instanceof HTMLSelectElement) {\n            entry.selected.forEach((on, i) => {\n                if (el.options[i]) el.options[i].selected = on;\n            });\n            el.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n            el.dispatchEvent(new Event('change', { bubbles: true }));\n        } else if (entry.checked !== undefined && el instanceof HTMLInputElement) {\n            el.checked = entry.checked;\n            el.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n            el.dispatchEvent(new Event('change', { bubbles: true }));\n        } else if (entry.value !== undefined && !(el instanceof HTMLSelectElement)) {\n            el.value = entry.value;\n            el.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true, inputType: 'insertText' }));\n        }\n        if (entry.focused) {\n            el.focus();\n            if (entry.selection && !(el instanceof HTMLSelectElement)) {\n                try {\n                    el.setSelectionRange(...entry.selection);\n                } catch {\n                    // types without a selection (email, number)\n                }\n            }\n        }\n    }\n}\n\nfunction hasMediaRules(type: typeof UiElement) {\n    let has = mediaRules.get(type);\n    if (has === undefined) {\n        has = type.elementStyles.some((style) => {\n            const sheet = style instanceof CSSStyleSheet ? style : style.styleSheet;\n            return !!sheet && [...sheet.cssRules].some((rule) => rule instanceof CSSMediaRule);\n        });\n        mediaRules.set(type, has);\n    }\n    return has;\n}\n\nexport class UiElement extends LitElement {\n    protected static override finalizeStyles(styles?: CSSResultGroup) {\n        return [...super.finalizeStyles(styles), hiddenHost];\n    }\n\n    /**\n     * The element's public states (documented with `@cssstate`): each `data-<name>` attribute the element sets on\n     * itself is also a custom state, so app styles can use `ui-dropdown:state(open)` as well as\n     * `ui-dropdown[data-open]` (Web Awesome and native elements expose state this way).\n     */\n    static hostStates: readonly string[] = [];\n\n    private attachedInternals?: ElementInternals;\n\n    /** The element's ElementInternals, attached once on first use (subclasses use this, never attachInternals). */\n    protected get internals(): ElementInternals {\n        this.attachedInternals ??= this.attachInternals();\n        return this.attachedInternals;\n    }\n\n    override setAttribute(name: string, value: string) {\n        super.setAttribute(name, value);\n        this.syncState(name);\n    }\n\n    override removeAttribute(name: string) {\n        super.removeAttribute(name);\n        this.syncState(name);\n    }\n\n    override toggleAttribute(name: string, force?: boolean) {\n        const on = super.toggleAttribute(name, force);\n        this.syncState(name);\n        return on;\n    }\n\n    /** Mirrors a public state's `data-*` attribute into the custom state of the same name. */\n    private syncState(attribute: string) {\n        if (!attribute.startsWith('data-')) return;\n        const name = attribute.slice(5);\n        if (!(this.constructor as typeof UiElement).hostStates.includes(name)) return;\n        const states = this.internals.states as CustomStateSet | undefined; // absent in the server's DOM shim\n        if (!states) return;\n        const on = this.hasAttribute(attribute);\n        try {\n            if (on) states.add(name);\n            else states.delete(name);\n        } catch {\n            // Chrome before 125 only takes the old dashed form (`:--open`)\n            if (on) states.add(`--${name}`);\n            else states.delete(`--${name}`);\n        }\n    }\n\n    /**\n     * WebKit bug (Safari): a shared (adopted) stylesheet that is adopted again after every element using it\n     * had left the page keeps the @media results of when it was last in use — a notification or the shell\n     * added after the window was resized lays out for the old width until the next resize. What works:\n     * once the new shadow root has been styled, assign its sheets again (before that, WebKit ignores it).\n     * Styling it early gives transitions a starting point (states set just after the first render would\n     * animate), so this runs only in the case of the bug: the first element of a class with @media rules\n     * connecting while the viewport differs from when the last one left — and every other element of that\n     * class connecting in the same task (a grid's columns all come back at once). Before the next paint.\n     */\n    override connectedCallback() {\n        super.connectedCallback();\n        const type = this.constructor as typeof UiElement;\n        // states whose attribute was already there (in the HTML, or set before the element was defined)\n        for (const name of type.hostStates) this.syncState(`data-${name}`);\n        const count = connectedCount.get(type) ?? 0;\n        connectedCount.set(type, count + 1);\n        const left = leftAt.get(type);\n        if (count === 0 && left !== undefined && left !== viewportSize() && hasMediaRules(type)) {\n            restyling.add(type);\n            setTimeout(() => restyling.delete(type));\n        }\n        if (restyling.has(type)) void this.updateComplete.then(() => this.restyle());\n    }\n\n    /** Styles the shadow root once (reading a computed style), then assigns its sheets again. */\n    private restyle() {\n        const root = this.renderRoot as Partial<ShadowRoot>;\n        const first = root.firstElementChild;\n        if (!this.isConnected || !root.adoptedStyleSheets?.length || !first) return;\n        void getComputedStyle(first).display; // NOSONAR: reading a computed style is what forces the first style pass\n        root.adoptedStyleSheets = [...root.adoptedStyleSheets];\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        const type = this.constructor as typeof UiElement;\n        const count = Math.max(0, (connectedCount.get(type) ?? 1) - 1);\n        connectedCount.set(type, count);\n        if (count === 0) leftAt.set(type, viewportSize());\n    }\n\n    protected override createRenderRoot(): HTMLElement | DocumentFragment {\n        const root = this.shadowRoot;\n        return root ? this.reuseServerRoot(root) : super.createRenderRoot();\n    }\n\n    /**\n     * Empties a server-rendered shadow root and prepares it as LitElement prepares a new one. What the user already\n     * typed, chose or focused in it (a slow script) carries over to the new render.\n     */\n    private reuseServerRoot(root: ShadowRoot): HTMLElement | DocumentFragment {\n        const typed = readServerInput(root);\n        root.replaceChildren();\n        if (typed.length) void this.updateComplete.then(() => restoreServerInput(this.renderRoot, typed));\n        adoptStyles(root, (this.constructor as typeof LitElement).elementStyles);\n        // ElementInternals ARIA that the server wrote as attributes (Lit SSR's hydrate-internals-* convention)\n        for (const name of this.getAttributeNames()) {\n            if (!name.startsWith(INTERNALS_PREFIX)) continue;\n            this.removeAttribute(name.slice(INTERNALS_PREFIX.length));\n            this.removeAttribute(name);\n        }\n        this.renderOptions.renderBefore ??= root.firstChild;\n        return root;\n    }\n}\n"
    }
  ]
}
