{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "shared-form-control",
  "type": "registry:lib",
  "title": "shared/form-control",
  "description": "Internal module shared by the ui-* components (form-control). 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/shared-field",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/shared/form-control.ts",
      "type": "registry:lib",
      "target": "components/ui/primitives/shared/form-control.ts",
      "content": "import { isServer, type ReactiveController, type ReactiveControllerHost } from 'lit';\nimport { inDisabledFieldset, inDisabledGroup } from './field.ts';\n\n/** A form-associated element the controller serves (its own `disabled`, and `form` as natively). */\nexport type FormControlHost = ReactiveControllerHost &\n    HTMLElement & {\n        disabled: boolean;\n        readonly form: HTMLFormElement | null;\n        requestUpdate(name?: PropertyKey, oldValue?: unknown): void;\n    };\n\nexport interface FormControlOptions {\n    /**\n     * Interactive validation (a submit attempt, `reportValidity()`) found the field invalid: show its error now.\n     * Not called for `checkValidity()`, which stays silent as natively.\n     */\n    reveal?: () => void;\n    /** Focus for the field when it is the form's first invalid one (default: the host's `focus()`). */\n    focus?: () => void;\n    /** Enter in its text box submits the form (a text-like field): it counts for implicit submission. */\n    implicitSubmission?: boolean;\n}\n\n/**\n * Forms (and fields) that are being validated interactively in this task: a submitter was clicked, Enter was\n * pressed, `requestSubmit()` / `reportValidity()` was called. `invalid` fires for `checkValidity()` too, where a\n * native control shows nothing; only these show the error and move focus. The page's one store, shared with the\n * React fields (headless/form-validation.ts): one form can hold both.\n */\ninterface Store {\n    validating: Set<EventTarget>;\n    wrapped: WeakSet<HTMLFormElement>;\n    listening: boolean;\n}\n\nconst KEY = Symbol.for('@purpurabog/ui:form-validation');\n\nfunction validationStore(): Store {\n    const holder = globalThis as typeof globalThis & { [KEY]?: Store };\n    holder[KEY] ??= { validating: new Set(), wrapped: new WeakSet(), listening: false };\n    return holder[KEY];\n}\n\n/** Marks a form (or a field) as being validated interactively until the end of this task. */\nexport function markValidating(target: EventTarget) {\n    const { validating } = validationStore();\n    if (validating.size === 0) setTimeout(() => validating.clear());\n    validating.add(target);\n}\n\n/** The forms along an event's path: each element's own form, a native control's or a form-associated host's. */\nfunction formsOnPath(event: Event) {\n    const forms = new Set<HTMLFormElement>();\n    for (const node of event.composedPath()) {\n        if (node instanceof HTMLFormElement) forms.add(node);\n        else if (node instanceof HTMLElement && 'form' in node && node.form instanceof HTMLFormElement) forms.add(node.form);\n    }\n    return forms;\n}\n\n/** Clicks on a submitter and Enter in a field start interactive validation of their form (capturing, before the browser's). */\nfunction listenOnce() {\n    const store = validationStore();\n    if (store.listening || isServer) return;\n    store.listening = true;\n    const mark = (event: Event) => {\n        for (const form of formsOnPath(event)) markValidating(form);\n    };\n    document.addEventListener('click', mark, true);\n    document.addEventListener('keydown', (event) => {\n        if (event.key === 'Enter') mark(event);\n    }, true);\n}\n\n/**\n * The app's own `form.requestSubmit()` / `form.reportValidity()` validate interactively too: the form's instance\n * methods mark it first, then do what the browser's do. Only forms holding these elements are wrapped.\n */\nfunction wrapForm(form: HTMLFormElement) {\n    const { wrapped } = validationStore();\n    if (wrapped.has(form)) return;\n    wrapped.add(form);\n    form.requestSubmit = (submitter?: HTMLElement | null) => {\n        markValidating(form);\n        HTMLFormElement.prototype.requestSubmit.call(form, submitter);\n    };\n    form.reportValidity = () => {\n        markValidating(form);\n        return HTMLFormElement.prototype.reportValidity.call(form);\n    };\n}\n\n/** Text-like fields of ours that count for implicit submission (as native text inputs do). */\nconst implicitFields = new WeakSet<Element>();\n\n/** The form's first invalid field, in the form's own order (`form.elements` also holds fields tied by `form=\"id\"`). */\nconst firstInvalid = (form: HTMLFormElement) => [...form.elements].find((el) => el.matches(':invalid'));\n\n/**\n * The form plumbing every form-associated element shares:\n * - `disabled` as natively: its own, an ancestor `<fieldset disabled>` (`formDisabledCallback`) or a disabled\n *   `<ui-form-group>`;\n * - the values `form.reset()` goes back to, captured on the first connection only (moving the element keeps them);\n * - `invalid` handled as a native control: a submit attempt or `reportValidity()` shows the error and focuses the\n *   form's first invalid field; `checkValidity()` stays silent (an app checking validity on every keystroke must not\n *   pull the focus away or show errors in untouched fields). The browser's own bubble is always suppressed (the\n *   element renders its message);\n * - the host's accessible name from outside (`aria-label`, `aria-labelledby`, a `<label for>`), for the inner control\n *   that takes the focus when the element has no `label` of its own.\n */\nexport class FormControlController implements ReactiveController {\n    private captured = false;\n    private names?: MutationObserver;\n    private readonly host: FormControlHost;\n    private readonly options: FormControlOptions;\n\n    constructor(host: FormControlHost, options: FormControlOptions = {}) {\n        this.host = host;\n        this.options = options;\n        host.addController(this);\n    }\n\n    /**\n     * Disabled in any of the native ways: its own `disabled`, a disabled `<fieldset>` or `<ui-form-group>`. The fieldset\n     * is read from the page, as the group is: the browser calls `formDisabledCallback` for the element's own `disabled`\n     * attribute too, mid-update (after render), so a copy kept from it went stale and left the inner control disabled.\n     */\n    get disabled() {\n        return this.host.disabled || inDisabledFieldset(this.host) || inDisabledGroup(this.host);\n    }\n\n    /** Call from the element's `formDisabledCallback`: renders again for a fieldset that changed. */\n    setFieldsetDisabled(disabled: boolean) {\n        this.host.requestUpdate('fieldsetDisabled', !disabled); // under that name: updates that follow it still see it\n    }\n\n    /** Runs `capture` (what `form.reset()` returns to) on the element's first connection only. */\n    captureDefaults(capture: () => void) {\n        if (this.captured) return;\n        this.captured = true;\n        capture();\n    }\n\n    /** The element's `reportValidity()`: interactive, so an invalid field shows its error (and focuses, as natively). */\n    reportValidity(internals: ElementInternals) {\n        markValidating(this.host);\n        return internals.reportValidity();\n    }\n\n    hostConnected() {\n        listenOnce();\n        if (this.options.implicitSubmission) implicitFields.add(this.host);\n        this.host.addEventListener('invalid', this.onInvalid);\n        if (isServer) return;\n        const form = this.host.form;\n        if (form) wrapForm(form);\n        // a name given from outside re-renders the inner control's\n        this.names ??= new MutationObserver(() => this.host.requestUpdate());\n        this.names.observe(this.host, { attributes: true, attributeFilter: ['aria-label', 'aria-labelledby'] });\n    }\n\n    hostDisconnected() {\n        this.host.removeEventListener('invalid', this.onInvalid);\n        this.names?.disconnect();\n    }\n\n    private readonly onInvalid = (event: Event) => {\n        event.preventDefault(); // no browser bubble: the element shows its own message\n        const form = this.host.form;\n        const { validating } = validationStore();\n        if (!validating.has(this.host) && !(form && validating.has(form))) return; // checkValidity(): silent\n        this.options.reveal?.();\n        // cancelling also cancelled the browser's focus jump: the form's first invalid field focuses itself\n        if (form && firstInvalid(form) === this.host) (this.options.focus ?? (() => this.host.focus()))();\n    };\n\n    /** The name for an element with no `label` of its own: the one given from outside (see `outsideName`), else ''. */\n    fallbackName(label: string, internals: ElementInternals) {\n        return label ? '' : this.outsideName(internals);\n    }\n\n    /**\n     * The host's accessible name as the page gives it: `aria-label`, else the text of its `aria-labelledby`\n     * elements, else of the `<label>`s that point at it. '' when there is none. For the inner control's\n     * `aria-label` when the element has no `label` of its own.\n     */\n    outsideName(internals: ElementInternals): string {\n        if (isServer) return '';\n        const own = this.host.getAttribute('aria-label')?.trim();\n        if (own) return own;\n        const root = this.host.getRootNode() as Document | ShadowRoot;\n        const ids = this.host.getAttribute('aria-labelledby')?.trim().split(/\\s+/) ?? [];\n        const byId = ids.map((id) => textOutside(root.getElementById?.(id) ?? null, this.host)).filter(Boolean);\n        if (byId.length) return byId.join(' ');\n        return [...(internals.labels ?? [])].map((label) => textOutside(label, this.host)).filter(Boolean).join(' ');\n    }\n}\n\n/** An element's text without the field itself (a wrapping `<label>` holds the field and its options). */\nfunction textOutside(el: Node | null, field: Element): string {\n    if (!el) return '';\n    if (!el.contains(field)) return el.textContent?.replaceAll(/\\s+/g, ' ').trim() ?? '';\n    let text = '';\n    for (const child of el.childNodes) if (child !== field) text += ` ${textOutside(child, field)}`;\n    return text.replaceAll(/\\s+/g, ' ').trim();\n}\n\nconst BLOCKING = new Set(['text', 'search', 'url', 'tel', 'email', 'password', 'date', 'month', 'week', 'time', 'datetime-local', 'number']);\n\n/** A submit button of the form: native, or a `<ui-button type=\"submit\">`. */\nfunction isSubmitter(el: Element): el is HTMLElement {\n    if (el instanceof HTMLButtonElement) return el.type === 'submit';\n    if (el instanceof HTMLInputElement) return el.type === 'submit' || el.type === 'image';\n    return el.localName === 'ui-button' && (el as HTMLElement & { type?: string }).type === 'submit';\n}\n\n/** A field that blocks implicit submission (HTML): a text-like native input, or one of ours. */\nconst blocksImplicitSubmission = (el: Element) => (el instanceof HTMLInputElement && BLOCKING.has(el.type)) || implicitFields.has(el);\n\n/**\n * Implicit submission (HTML): Enter in a field submits through the form's default button (its first submit button)\n * — nothing when that button is disabled; without one, only a form with a single text-like field submits.\n */\nexport function implicitlySubmit(form: HTMLFormElement) {\n    const elements = [...form.elements];\n    const submitter = elements.find(isSubmitter);\n    if (submitter) {\n        if (submitter.matches(':disabled') || inDisabledGroup(submitter)) return;\n        // a click at the default button, as the browser fires; ours sits inside a shadow root\n        const target = submitter.localName === 'ui-button' ? (submitter.shadowRoot?.querySelector<HTMLElement>('button') ?? submitter) : submitter;\n        target.click();\n        return;\n    }\n    if (elements.filter(blocksImplicitSubmission).length > 1) return;\n    markValidating(form);\n    form.requestSubmit();\n}\n"
    }
  ]
}
