{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "shared-field",
  "type": "registry:lib",
  "title": "shared/field",
  "description": "Internal module shared by the ui-* components (field). 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/core-field",
    "@kanok-ui/shared-form-control",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/shared/field.ts",
      "type": "registry:lib",
      "target": "components/ui/primitives/shared/field.ts",
      "content": "import { css, html, isServer, nothing } from 'lit';\nimport { pickMessage as pickFieldMessage, type FieldMessage, type MessageKind } from '../../core/field.ts';\nimport { implicitlySubmit } from './form-control.ts';\n\nlet counter = 0;\n\n/** Unique id for wiring label / aria-describedby inside one shadow root. */\nexport const uid = (prefix: string) => `${prefix}-${counter++}`;\n\n/**\n * Inside a disabled `<ui-form-group>`: its slotted fields are light-DOM children, not descendants of\n * the group's shadow `<fieldset>`, so the browser doesn't disable them — each field asks instead.\n */\nexport const inDisabledGroup = (host: Element) => typeof host.closest === 'function' && host.closest('ui-form-group[disabled]') !== null; // no closest() under Lit SSR\n\n/** Inside a `<fieldset disabled>`, as natively: not within that fieldset's first `<legend>`. */\nexport function inDisabledFieldset(host: Element): boolean {\n    if (typeof host.closest !== 'function') return false; // no closest() under Lit SSR\n    for (let fieldset = host.closest('fieldset[disabled]'); fieldset; fieldset = fieldset.parentElement?.closest('fieldset[disabled]') ?? null) {\n        if (!fieldset.querySelector(':scope > legend')?.contains(host)) return true;\n    }\n    return false;\n}\n\n/**\n * The forced error of a field: `invalid` with its `invalid-text`, else a `setCustomValidity()` message.\n * '' when there is none (the field's own checks decide).\n */\nexport function customErrorMessage(invalid: boolean, invalidText: string, custom: string): string {\n    if (invalid) return invalidText || custom || ' ';\n    return custom;\n}\n\n/** A native control's validation message, with \"value missing\" in the page language (`required`) instead of the browser's. */\nexport const nativeValidationMessage = (control: { validity: ValidityState; validationMessage: string }, required: string) =>\n    control.validity.valueMissing ? required : control.validationMessage;\n\n/** Text of the error line: a `setCustomValidity()` message, unless `invalid` forces the author's `invalid-text`; else the field's own. */\nexport const pickErrorText = (invalid: boolean, custom: string, own: string) => (custom && !invalid ? custom : own);\n\n/**\n * A disabled control (own `disabled`, a disabled `<fieldset>` or `<ui-form-group>`) is not submitted\n * and is barred from constraint validation, as natively. Returns true when it applied that state.\n */\nexport function barWhenDisabled(internals: ElementInternals, disabled: boolean): boolean {\n    if (!disabled) return false;\n    internals.setFormValue(null);\n    internals.setValidity({});\n    return true;\n}\n\n/** Value of the `<option selected>` child, if any — a select's initial choice when no `value` was given. */\nexport const selectedOptionValue = (host: Element) => host.querySelector<HTMLOptionElement>('option[selected]')?.value;\n\n/** The focused element, following open shadow roots down (to return focus to it later). */\nexport function deepActiveElement(): HTMLElement | null {\n    let el = document.activeElement;\n    while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;\n    return el instanceof HTMLElement ? el : null;\n}\n\n/**\n * Converter for a boolean that is on by default (Carbon props like `caret`, `closeOnEscape`): plain HTML\n * can't remove a default, so `attr=\"false\"` turns it off; absent or any other value means on.\n * Reflects off as `attr=\"false\"`, so style it with `:host([attr='false'])`.\n */\nexport const defaultTrue = {\n    fromAttribute: (value: string | null) => value !== 'false',\n    toAttribute: (value: boolean) => (value ? '' : 'false'),\n};\n\n/** For an inner control's composed native event that must not reach the page as the component's own (it fires `ui-change`). */\nexport const stopEvent = (event: Event) => event.stopPropagation();\n\nconst managed = new WeakMap<Element, Map<string, string>>();\n\n/**\n * Sets or clears an attribute the component manages on its own host (aria-label, role…) without\n * overwriting a value the author put there: once the attribute holds something this function didn't\n * write, the author's value wins.\n */\nexport function setManagedAttribute(host: Element, name: string, value: string | null) {\n    const mine = managed.get(host) ?? new Map<string, string>();\n    managed.set(host, mine);\n    const current = host.getAttribute(name);\n    if (current !== null && current !== mine.get(name)) return;\n    if (value === null) {\n        host.removeAttribute(name);\n        mine.delete(name);\n    } else {\n        host.setAttribute(name, value);\n        mine.set(name, value);\n    }\n}\n\n/** True when a `<label for>` / wrapping `<label>` clicked the form-associated host itself (not something inside it). */\nexport const isLabelClick = (host: HTMLElement, event: Event) => event.composedPath()[0] === host;\n\nconst NOT_TEXT = new Set(['checkbox', 'radio', 'range', 'button', 'submit', 'reset', 'file', 'color', 'image']);\n\n/**\n * Implicit submission, as a native text box does (HTML's rules: through the form's default button, nothing when it\n * is disabled, and without one only when the form has a single text-like field): Enter in a field's text input —\n * unless a listener called `preventDefault()` (checked after the event finished propagating).\n */\nexport function submitOnEnter(host: HTMLElement & { form: HTMLFormElement | null }, event: KeyboardEvent) {\n    // an input method's Enter confirms its word (Safari's last one, after compositionend, is keyCode 229): not a submit\n    if (event.key !== 'Enter' || event.isComposing || event.keyCode === 229 || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return;\n    const origin = event.composedPath()[0];\n    if (!(origin instanceof HTMLInputElement) || NOT_TEXT.has(origin.type)) return;\n    setTimeout(() => {\n        const form = host.form;\n        if (!event.defaultPrevented && form) implicitlySubmit(form);\n    });\n}\n\nconst titleWarned = new Set<string>();\n\n/**\n * 0.x components took their heading from a `title` attribute, which also makes the browser show\n * its own tooltip over the whole element. Call from `attributeChangedCallback` (with `title` in\n * `observedAttributes`): the value moves to `heading` and the attribute is removed, once-per-tag\n * warning included. Returns true when it handled the attribute.\n */\nexport function moveTitleToHeading(host: HTMLElement & { heading: string }, name: string, value: string | null): boolean {\n    if (name !== 'title') return false;\n    if (value === null) return true;\n    host.heading = value;\n    host.removeAttribute('title');\n    if (!titleWarned.has(host.localName)) {\n        titleWarned.add(host.localName);\n        console.warn(`<${host.localName}>: the \"title\" attribute is deprecated (browsers show it as a tooltip); use \"heading\".`);\n    }\n    return true;\n}\n\n/** Hide visually but keep available to screen readers. */\nexport const srOnlyStyles = css`\n    .sr-only {\n        position: absolute;\n        width: 1px;\n        height: 1px;\n        margin: -1px;\n        padding: 0;\n        overflow: hidden;\n        clip-path: inset(50%);\n        white-space: nowrap;\n        border: 0;\n    }\n`;\n\n/**\n * Label, helper / warning / error text and in-field status icons shared by every\n * form field (Carbon's form field anatomy).\n * `:host(:disabled)` matches both the `disabled` attribute and a disabled `<fieldset>`.\n */\nexport const fieldTextStyles = css`\n    ${srOnlyStyles}\n\n    /* Carbon label-01: 12px, secondary text; --ui-label-font / --ui-label-color let a design make it bolder */\n    .label {\n        display: inline-block;\n        margin-bottom: var(--ui-space-xs);\n        font: var(--ui-label-font, var(--ui-font-caption));\n        letter-spacing: var(--ui-tracking-caption);\n        color: var(--ui-label-color, var(--ui-ink-muted));\n    }\n\n    .helper,\n    .warn,\n    .error {\n        margin: var(--ui-space-xxs) 0 0;\n        font: var(--ui-font-caption);\n        letter-spacing: var(--ui-tracking-caption);\n    }\n\n    .helper {\n        /* ink-muted, not ink-subtle: helper text must meet 4.5:1 */\n        color: var(--ui-ink-muted);\n    }\n\n    /* Yellow text fails contrast — warning text stays ink, the icon carries the colour */\n    .warn {\n        color: var(--ui-ink);\n    }\n\n    .error {\n        /* Carbon text-error: same as support-error in light themes, lighter in g90/g100 for contrast */\n        color: var(--ui-error-text, var(--ui-error));\n    }\n\n    /* a disabled <fieldset>, or a disabled <ui-form-group> (its fieldset is in its shadow root: the group marks the fields) — Carbon fieldset[disabled] .cds--label */\n    :host(:disabled) .label,\n    :host(:disabled) .helper,\n    :host([data-group-disabled]) .label,\n    :host([data-group-disabled]) .helper {\n        color: var(--ui-ink-disabled);\n    }\n\n    .with-icon {\n        display: flex;\n        align-items: flex-start;\n        gap: var(--ui-space-xxs);\n    }\n\n    .status-icon {\n        flex-shrink: 0;\n        width: 16px;\n        height: 16px;\n        pointer-events: none;\n    }\n\n    .status-icon.status-error {\n        fill: var(--ui-error);\n    }\n\n    .status-icon .warn-fill {\n        fill: var(--ui-warning);\n    }\n\n    .status-icon .warn-mark {\n        fill: var(--ui-ink);\n    }\n\n    @media (forced-colors: active) {\n        .status-icon.status-error,\n        .status-icon .warn-fill {\n            fill: CanvasText;\n        }\n        .status-icon .warn-mark {\n            fill: Canvas;\n        }\n    }\n`;\n\nexport type { FieldMessage, MessageKind } from '../../core/field.ts';\n\nexport interface MessageInput {\n    showError: boolean;\n    errorText: string;\n    showWarn: boolean;\n    warnText: string;\n    helperText: string;\n    /** Slot presence of the host: slotted `helper-text` / `warn-text` count as text. */\n    slots?: { has(name: string): boolean };\n}\n\n/** Slot names of the message line, by kind. Same names as the attributes they override (Carbon web components convention). */\nexport const MESSAGE_SLOT: Record<MessageKind, string> = { error: 'invalid-text', warn: 'warn-text', helper: 'helper-text' };\n\n/** The single message under a field, by priority: error > warning > helper (core/field); slotted text counts too. */\nexport function pickMessage(input: MessageInput): FieldMessage | null {\n    const { slots } = input;\n    return pickFieldMessage({ ...input, hasWarn: slots?.has(MESSAGE_SLOT.warn), hasHelper: slots?.has(MESSAGE_SLOT.helper) });\n}\n\n/** id for aria-describedby, or undefined when nothing is shown. */\nexport const messageId = (fieldId: string, message: FieldMessage | null) =>\n    message ? `${fieldId}-message` : undefined;\n\n/**\n * CSS part names of the message line, by kind. Shared by every field so `::part(error-text)` works everywhere;\n * `invalid-text` / `warn-text` name the same line after the attributes and slots that fill it.\n */\nexport const MESSAGE_PART: Record<MessageKind, string> = { error: 'error-text invalid-text', warn: 'warning-text warn-text', helper: 'helper-text' };\n\n/**\n * The attribute text is the fallback of a slot of the same kind, so authors can slot markup\n * (links, bold) and the text attribute keeps working for the plain case.\n * @param withIcon - prefix the status icon (for controls without an input box to hold it,\n *   e.g. checkbox and radio group).\n */\nexport function renderMessage(fieldId: string, message: FieldMessage | null, withIcon = false) {\n    if (!message) return nothing;\n    const icon = withIcon ? renderStatusIcon(message) : nothing;\n    return html`<p class=\"${message.kind} ${withIcon ? 'with-icon' : ''}\" part=${MESSAGE_PART[message.kind]} id=\"${fieldId}-message\">\n        ${icon}<span><slot name=${MESSAGE_SLOT[message.kind]}>${message.text}</slot></span>\n    </p>`;\n}\n\n/** Label content: the `label` slot with the `label` attribute as fallback. */\nexport const renderLabelText = (label: string, outside = '') =>\n    html`<slot name=\"label\">${label || (outside ? html`<span class=\"sr-only\">${outside}</span>` : nothing)}</slot>`;\n\nconst errorIcon = html`<svg class=\"status-icon status-error\" part=\"status-icon\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n    <path d=\"M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1Zm-.55 3h1.1v5h-1.1V4ZM8 12.25a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5Z\" />\n</svg>`;\n\nconst warnIcon = html`<svg class=\"status-icon status-warn\" part=\"status-icon\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n    <path class=\"warn-fill\" d=\"M8 1.5 15.2 14.5H.8Z\" />\n    <path class=\"warn-mark\" d=\"M7.45 6h1.1v4.5h-1.1zM8 13a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5Z\" />\n</svg>`;\n\n/** In-field icon so error/warning isn't signalled by colour alone (WCAG 1.4.1). */\nexport function renderStatusIcon(message: FieldMessage | null) {\n    if (message?.kind === 'error') return errorIcon;\n    if (message?.kind === 'warn') return warnIcon;\n    return nothing;\n}\n\n/**\n * Carbon fluid fields: a field is fluid with its own `fluid` attribute or inside `<ui-fluid-form>`\n * (Carbon `FluidForm`). Reflects that as `data-fluid` for the styles below; call on connect and update.\n */\nexport function syncFluid(host: Element, fluid: boolean): boolean {\n    const inForm = typeof host.closest === 'function' && host.closest('ui-fluid-form') !== null;\n    host.toggleAttribute('data-fluid', fluid || inForm);\n    return fluid || inForm;\n}\n\n/** Fluid fields outline / underline the whole box (field + message) by status: `data-status=\"error\" | \"warn\"`. */\nexport function markStatus(host: HTMLElement, message: FieldMessage | null) {\n    const kind = message && message.kind !== 'helper' ? message.kind : null;\n    // only on change: rewriting the same value is still a mutation, and fields that observe their own attributes would re-render forever\n    if (isServer) return; // Lit SSR's element shim has no `dataset`\n    if ((host.dataset.status ?? null) === kind) return;\n    if (kind) host.dataset.status = kind;\n    else delete host.dataset.status;\n}\n\n/**\n * Whether `data-<key>` is set (`key` camelCase, as in `dataset`). Never on the server: Lit SSR's\n * element shim has no `dataset`, and these flags are set in lifecycle callbacks the server doesn't run.\n */\nexport const hasData = (el: HTMLElement, key: string) => !isServer && el.dataset[key] !== undefined;\n\n/**\n * Carbon fluid layout shared by every fluid field (measured on react.carbondesignsystem.com): a\n * 64px box on the field colour with the label inside at 13px / 16px; the control pads 32px above its\n * text; an error or warning sits inside the box under a 1px divider inset 16px, the status icon at\n * its end; error outlines the whole box red, warning underlines it, focus outlines it blue.\n * Components add their control's sizes (`--ui-fluid-*` below) and icon positions.\n */\nexport const fluidFieldStyles = css`\n    /* --ui-fluid-background / -gap: a design can keep its fields' own fill and space stacked boxes apart (Carbon: they touch) */\n    :host([data-fluid]) {\n        display: flow-root; /* the box holds its children's margins (the text area's 32px) */\n        position: relative;\n        margin-block-end: var(--ui-fluid-gap, 0px);\n        background-color: var(--ui-fluid-background, var(--ui-surface-1));\n        border-radius: var(--ui-field-radius, 0); /* the box's ring follows the field's corners (Kanok: 6px) */\n        outline: var(--ui-field-focus-width, 2px) solid transparent; /* the ring's width (Kanok: 1.5px, on the field's own border) */\n        outline-offset: calc(-1 * var(--ui-field-focus-width, 2px));\n    }\n\n    :host([data-fluid]) .top {\n        display: contents;\n    }\n\n    :host([data-fluid]) .label {\n        position: absolute;\n        z-index: 1;\n        inset-block-start: 13px;\n        inset-inline-start: var(--ui-space-md);\n        max-inline-size: calc(100% - 2 * var(--ui-space-md));\n        margin: 0;\n        overflow: hidden;\n        text-overflow: ellipsis;\n        white-space: nowrap;\n        pointer-events: none;\n    }\n\n    :host([data-fluid]) .counter {\n        position: absolute;\n        z-index: 1;\n        inset-block-start: 13px;\n        inset-inline-end: var(--ui-space-md);\n    }\n\n    /* Carbon's fluid fields have no helper line */\n    :host([data-fluid]) .helper {\n        display: none;\n    }\n\n    :host([data-fluid]) :is(.error, .warn) {\n        position: relative;\n        margin: 1px 0 0; /* the divider's row (Carbon <hr>) */\n        padding: var(--ui-space-xs) 40px var(--ui-space-xs) var(--ui-space-md);\n    }\n\n    :host([data-fluid]) :is(.error, .warn)::before {\n        content: '';\n        position: absolute;\n        inset-block-start: -1px;\n        inset-inline: var(--ui-space-md);\n        border-block-start: 1px solid var(--ui-hairline);\n    }\n\n    :host([data-fluid]) .status-icon {\n        position: absolute;\n        inset-block-start: var(--ui-fluid-icon-top, calc(100% + var(--ui-space-xs)));\n        inset-inline-end: var(--ui-fluid-icon-end, 0);\n    }\n\n    :host([data-fluid][data-status='error']) {\n        outline-color: var(--ui-error);\n    }\n\n    /* the warning's underline closes the box; drawn by the message (the box's last row), not :host, which a page-wide CSS reset would strip */\n    :host([data-fluid][data-status='warn']) .warn {\n        border-block-end: 1px solid var(--ui-ink-subtle);\n    }\n\n    /* the box carries focus (and status), so the control inside draws no outline or underline of its own */\n    :host([data-fluid]:focus-within) {\n        outline-color: var(--ui-focus);\n        box-shadow: var(--ui-field-focus-halo, none); /* a design's halo outside the ring (Kanok: none) */\n    }\n\n    :host([data-fluid]) :is(input, textarea, select, .trigger) {\n        outline: none;\n        box-shadow: none; /* the box draws the halo */\n        background-color: transparent;\n    }\n\n    /* a design whose control draws the box's visible edge (Kanok's outlined fields) colours it while the box has focus:\n       the box's own ring lies under it (Carbon: the underline stays) */\n    :host([data-fluid]:focus-within:not([readonly], [data-status])) :is(input, textarea, select, .trigger) {\n        border-color: var(--ui-fluid-focus-border-color, var(--ui-ink-subtle)); /* read-only and a status keep their own edge */\n    }\n\n    :host([data-fluid][data-status]) :is(input, textarea, select, .trigger) {\n        border-block-end-color: transparent;\n    }\n\n    :host([data-fluid][readonly]) {\n        background-color: var(--ui-field-readonly-background, transparent);\n    }\n\n    @media (forced-colors: active) {\n        :host([data-fluid]:focus-within) {\n            outline-color: Highlight;\n        }\n    }\n`;\n"
    }
  ]
}
