{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-field",
  "type": "registry:ui",
  "title": "react-tw/field.tsx",
  "description": "The parts every Carbon field shares, as in the Lit `fieldTextStyles`: the label, the one message 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-field",
    "@kanok-ui/tw-i18n",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/field.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/field.tsx",
      "content": "import { createContext, useCallback, useContext, useEffect, useId, useMemo, useState, type FocusEvent, type ReactNode, type RefObject, type ComponentProps } from 'react';\nimport { characterCount, countOf, pickMessage, valueText, type CounterMode, type FieldMessage } from '../core/field.ts';\nimport { useLanguage, useTranslation } from './lib/i18n.ts';\nimport { cn } from './lib/utils.ts';\n\n/**\n * The parts every Carbon field shares, as in the Lit `fieldTextStyles`: the label, the one message\n * line under the field (error > warning > helper, core/field `pickMessage`) and the in-field\n * status icon, so errors aren't signalled by colour alone (WCAG 1.4.1).\n */\n\n/** Carbon label-01 (caption type, secondary text); the label settings (--ui-label-font / -color) let a design make it bolder, as in the Lit fields. */\nexport const fieldLabelFont = 'ui-label-type'; // theme.css: --ui-label-font, else Carbon's caption\nexport const fieldLabelInk = 'text-[color:var(--ui-label-color,var(--ui-ink-muted))]';\nexport const fieldLabelClasses = `mb-2 inline-block ${fieldLabelFont} ${fieldLabelInk}`;\n\n/**\n * The field box's edge (`ui-field-edge`, theme.css), corners and fill, as the Lit fields: Carbon's underline on the layer's\n * field colour. The field settings (--ui-field-border on every side, --ui-field-radius, --ui-field-background; Kanok: a 1px outline, 6px\n * corners, no fill) outline the box instead; the fallbacks are Carbon's.\n */\nexport const fieldBoxClasses = 'ui-field-edge rounded-[var(--ui-field-radius,0px)] bg-[color:var(--ui-field-background,var(--ui-surface-1))]';\n/** The text size of a typed field or a native select: --ui-field-font-size (Kanok: 16px; Carbon: 16px on a phone's Safari only), else Carbon's 14px. */\nexport const fieldTextSize = '[font-size:var(--ui-field-font-size,14px)]!';\n/** A native control's edge when disabled (Carbon: no underline) or read-only (Carbon: a hairline underline). */\nexport const fieldDisabledState = 'disabled:[border-color:var(--ui-field-disabled-border-color,currentColor_currentColor_transparent)]';\nexport const fieldStateEdges = `${fieldDisabledState} read-only:not-disabled:[border-color:var(--ui-field-readonly-border-color,currentColor_currentColor_var(--ui-hairline))]`;\n/** The box's edge when disabled (Carbon: no underline), for a box that isn't the native control. */\nexport const fieldDisabledEdge = '[border-color:var(--ui-field-disabled-border-color,currentColor_currentColor_transparent)]';\n/** The box's edge when read-only (Carbon: a hairline underline), for a box that isn't the native control. */\nexport const fieldReadOnlyEdge = '[border-color:var(--ui-field-readonly-border-color,currentColor_currentColor_var(--ui-hairline))]';\n/** A disabled box keeps the field fill (Carbon: the layer's field colour), hovered too. */\nexport const fieldDisabledFill = 'bg-[color:var(--ui-field-background,var(--ui-surface-1))] hover:bg-[color:var(--ui-field-background,var(--ui-surface-1))]';\n/** An inline field's edge (Carbon: no underline). */\nexport const fieldInlineEdge = '[border-color:var(--ui-field-inline-border-color,currentColor_currentColor_transparent)]';\n/**\n * An invalid box's ring, as the Lit fields: Carbon's red outline (the focus ring while focused) and a design's error halo\n * (--ui-field-invalid-halo; Kanok: Pixiv's red ring), which stays while focused. Put it after the box's focus classes.\n */\nexport const fieldInvalidRing =\n    'outline-error [box-shadow:var(--ui-field-invalid-halo,none)] focus:outline-focus focus:[box-shadow:var(--ui-field-invalid-halo,var(--ui-field-focus-halo,none))]';\n/** The same for a box whose focus sits on a control inside it. */\nexport const fieldInvalidRingWithin =\n    'outline-error [box-shadow:var(--ui-field-invalid-halo,none)] focus-within:outline-focus focus-within:[box-shadow:var(--ui-field-invalid-halo,var(--ui-field-focus-halo,none))]';\n\n// ---- disabled groups (FormGroup), as the Lit fields' inDisabledGroup ----\n\nconst GroupDisabledContext = createContext(false);\n\n/** Internal: a disabled FormGroup tells the fields inside. */\nexport const GroupDisabledProvider = GroupDisabledContext.Provider;\n\n/** A field's disabled state: its own `disabled`, or a disabled FormGroup around it (as the Lit fields). */\nexport function useFieldDisabled(disabled?: boolean) {\n    const inGroup = useContext(GroupDisabledContext);\n    return !!disabled || inGroup;\n}\n\n// ---- Carbon fluid fields (FluidForm / fluid), as the Lit fluidFieldStyles ----\n\nconst FluidContext = createContext(false);\n\n/**\n * Carbon `FluidForm`: the fields inside render fluid, as if each had `fluid` — the label inside a\n * 64px box, an error / warning inside the box under a divider, no helper line. Only a context, like\n * Carbon's: it doesn't lay the fields out and isn't a `<form>` (wrap it in yours).\n */\nexport function FluidForm({ children, className, ...rest }: Readonly<Omit<ComponentProps<'div'>, 'children' | 'className'> & { children: ReactNode; className?: string }>) {\n    return (\n        <div {...rest} className={cn('block', className)}>\n            <FluidContext.Provider value={true}>{children}</FluidContext.Provider>\n        </div>\n    );\n}\n\n/** Whether a field renders fluid: its own `fluid`, or a FluidForm around it. */\nexport function useFluid(fluid?: boolean) {\n    const inForm = useContext(FluidContext);\n    return !!fluid || inForm;\n}\n\n/**\n * The fluid box (measured on react.carbondesignsystem.com): the field colour, a 2px outline that is\n * red for an error and blue while focus is inside; read-only drops the colour. The control inside\n * draws no outline or underline of its own (`fluidControlClasses`).\n */\nexport function fluidBoxClasses(status: FieldMessage['kind'] | undefined, readOnly?: boolean) {\n    return cn(\n        // --ui-fluid-background / -gap: a design can keep its fields' own fill and space stacked boxes apart (Carbon: they touch)\n        'relative flow-root mb-[var(--ui-fluid-gap,0px)] rounded-[var(--ui-field-radius,0px)] bg-[var(--ui-fluid-background,var(--ui-surface-1))] outline-solid outline-[length:var(--ui-field-focus-width,2px)] [outline-offset:calc(-1*var(--ui-field-focus-width,2px))] outline-transparent focus-within:outline-focus focus-within:[box-shadow:var(--ui-field-focus-halo,none)] forced-colors:focus-within:outline-[Highlight]',\n        status === 'error' && 'outline-error',\n        readOnly && 'bg-[var(--ui-field-readonly-background,transparent)]',\n    );\n}\n\n/** The control in a fluid box: no outline and no fill of its own; no underline while an error or warning shows. */\nexport function fluidControlClasses(status: FieldMessage['kind'] | undefined, readOnly = false) {\n    const message = status === 'error' || status === 'warn';\n    return cn(\n        'bg-transparent read-only:not-disabled:bg-transparent outline-none focus:outline-none focus:[box-shadow:none]', // the box draws the halo\n        // a design whose control draws the box's visible edge (Kanok's outlined fields) colours it while focused (Carbon: the underline stays)\n        // read-only (a button or a select, which :read-only can't tell) and a status keep their own edge, as the Lit box\n        message ? 'border-b-transparent' : !readOnly && 'focus:border-[color:var(--ui-fluid-focus-border-color,var(--ui-ink-subtle))]',\n    );\n}\n\n/** The label inside the fluid box: 16px in, 13px down, one line. */\nexport const fluidLabelClasses = 'pointer-events-none absolute start-4 top-[13px] z-1 m-0 max-w-[calc(100%-32px)] overflow-hidden text-ellipsis whitespace-nowrap';\n\n/** Carbon label: caption type, 8px above the field; `hidden` keeps it for screen readers only; `fluid` puts it inside the box. */\nexport function FieldLabel({ htmlFor, hidden, disabled, fluid, className, children }: Readonly<{ htmlFor: string; hidden?: boolean; disabled?: boolean; fluid?: boolean; className?: string; children: ReactNode }>) {\n    return (\n        <label htmlFor={htmlFor} className={hidden ? 'sr-only' : cn(fieldLabelClasses, disabled && 'text-ink-disabled', fluid && fluidLabelClasses, className)}>\n            {children}\n        </label>\n    );\n}\n\nconst messageColour = { helper: 'text-ink-muted', warn: 'text-ink', error: 'text-error-text' } as const;\n\n/**\n * The message line: 4px under the field, caption type; warning text stays ink (yellow fails\n * contrast), the icon carries the colour. `withIcon` puts the status icon in front, for controls\n * without a box to hold it (checkbox, radio group); `className` e.g. indents it under the label.\n */\nexport function FieldMessageLine({\n    id,\n    message,\n    content,\n    disabled,\n    withIcon,\n    fluid,\n    className,\n}: Readonly<{\n    id: string;\n    message: FieldMessage | null;\n    content?: ReactNode;\n    disabled?: boolean;\n    withIcon?: boolean;\n    /** Inside the fluid box: no helper line; an error / warning under a 1px divider inset 16px, a warning underlining the box. */\n    fluid?: boolean;\n    className?: string;\n}>) {\n    if (!message) return null;\n    const text = content ?? message.text;\n    return (\n        <p\n            id={id}\n            className={cn(\n                'mt-1 mb-0 type-caption',\n                messageColour[message.kind],\n                disabled && message.kind === 'helper' && 'text-ink-disabled',\n                withIcon && 'flex items-start gap-1',\n                fluid && message.kind === 'helper' && 'hidden',\n                fluid && message.kind !== 'helper' && \"relative mt-px py-2 ps-4 pe-10 before:absolute before:inset-x-4 before:-top-px before:box-content before:border-0 before:border-t before:border-solid before:border-hairline before:content-['']\",\n                fluid && message.kind === 'warn' && 'border-0 border-b border-solid border-ink-subtle',\n                className,\n            )}\n        >\n            {withIcon ? (\n                <>\n                    <StatusIcon kind={message.kind} />\n                    <span>{text}</span>\n                </>\n            ) : (\n                text\n            )}\n        </p>\n    );\n}\n\n/** Error / warning icon inside the field (16px, Carbon's shapes); `className` places it (a fluid field puts it in the message row). */\nexport function StatusIcon({ kind, className }: Readonly<{ kind: FieldMessage['kind'] | undefined; className?: string }>) {\n    if (kind === 'error') {\n        return (\n            <svg className={cn('pointer-events-none size-4 shrink-0 fill-error forced-colors:fill-[CanvasText]', className)} 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        );\n    }\n    if (kind === 'warn') {\n        return (\n            <svg className={cn('pointer-events-none size-4 shrink-0', className)} viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n                <path className=\"fill-warning forced-colors:fill-[CanvasText]\" d=\"M8 1.5 15.2 14.5H.8Z\" />\n                <path className=\"fill-ink forced-colors:fill-[Canvas]\" 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    }\n    return null;\n}\n\nexport interface TextFieldOptions {\n    id?: string;\n    value?: unknown;\n    defaultValue?: unknown;\n    maxCount?: number;\n    /** What `maxCount` counts: characters (default) or words (Carbon `counterMode`, Thai-aware). */\n    counterMode?: CounterMode;\n    tooLongText?: string;\n    nearLimitText?: string;\n    invalid?: boolean;\n    invalidText?: ReactNode;\n    warn?: boolean;\n    warnText?: ReactNode;\n    helperText?: ReactNode;\n    disabled?: boolean;\n    readOnly?: boolean;\n    lang?: string;\n}\n\nconst asText = (node: ReactNode) => (typeof node === 'string' ? node : '');\n\nexport interface FieldMessageProps {\n    /** Not disabled or read-only: only then do errors and warnings show. */\n    interactive: boolean;\n    invalid?: boolean;\n    invalidText?: ReactNode;\n    warn?: boolean;\n    warnText?: ReactNode;\n    helperText?: ReactNode;\n    /** The error to show when `invalid` comes without an `invalidText` (a radio group's \"choose one\"). */\n    fallbackError?: string;\n}\n\n/**\n * `required` with nothing chosen, found by a submit attempt (the headless Root's `onInvalid`): the field shows the\n * required message until a choice is made, as the web components do. Hand `onInvalid` and `onValueChange` to the Root.\n */\nexport function useRequiredError<T>(onChange?: (value: T) => void) {\n    const [missing, setMissing] = useState(false);\n    const onInvalid = useCallback(() => setMissing(true), []);\n    const onValueChange = useCallback(\n        (value: T) => {\n            setMissing(false);\n            onChange?.(value);\n        },\n        [onChange],\n    );\n    return { missing, onInvalid, onValueChange };\n}\n\n/**\n * Whether a group (RadioGroup, CheckboxGroup) has been touched, as the Lit groups: focus left it, an option changed, or a\n * submit found it empty (the native `invalid` reaches the group, React's `onInvalid` bubbles); a form reset clears it.\n * `box` is the element around the options; hand it the handlers.\n */\nexport function useGroupTouched(box: RefObject<HTMLElement | null>) {\n    const [touched, setTouched] = useState(false);\n    useEffect(() => {\n        const form = box.current?.closest('form');\n        if (!form) return;\n        const onReset = () => setTouched(false);\n        form.addEventListener('reset', onReset);\n        return () => form.removeEventListener('reset', onReset);\n    }, [box]);\n    const handlers = useMemo(() => {\n        const touch = () => setTouched(true);\n        return {\n            onChange: touch,\n            onInvalid: touch,\n            onBlur: (event: FocusEvent<HTMLElement>) => {\n                if (!event.currentTarget.contains(event.relatedTarget)) touch();\n            },\n        };\n    }, []);\n    return { touched, handlers };\n}\n\n/**\n * A field's message line from its props (error > warning > helper, core/field `pickMessage`) and what\n * it renders: a message given as markup renders as given, its text decides which one shows.\n */\nexport function fieldMessage({ interactive, invalid, invalidText, warn, warnText, helperText, fallbackError = '' }: FieldMessageProps) {\n    const message = pickMessage({\n        showError: interactive && !!invalid,\n        errorText: typeof invalidText === 'string' ? invalidText : fallbackError,\n        showWarn: !!warn && interactive,\n        warnText: asText(warnText),\n        helperText: asText(helperText),\n        hasWarn: !!warnText,\n        hasHelper: !!helperText,\n    });\n    const content = message ? { error: invalidText ?? (fallbackError || undefined), warn: warnText, helper: helperText }[message.kind] : null;\n    return { message, content };\n}\n\n/**\n * State of a text field (TextInput, TextArea): its id, the soft `maxCount` counter (core/field\n * `characterCount`; over the limit is an error by itself), the one message to show (core/field\n * `pickMessage`) and what the counter announces. Call `onTyped` from the control's onChange.\n */\nexport function useTextField(o: TextFieldOptions) {\n    const t = useTranslation(o.lang).field;\n    const language = useLanguage(o.lang);\n    const words = o.counterMode === 'word';\n    const autoId = useId();\n    const id = o.id ?? autoId;\n    const [typed, setTyped] = useState(valueText(o.defaultValue));\n    const length = countOf(valueText(o.value ?? typed), o.counterMode, language);\n    const count = characterCount(length, o.maxCount);\n    const interactive = !o.disabled && !o.readOnly;\n    const tooLong = (o.tooLongText ?? (words ? t.tooManyWords : t.tooLong)).replace('{max}', String(o.maxCount));\n    const showError = interactive && (!!o.invalid || count.over);\n    const message = pickMessage({\n        showError,\n        errorText: asText(o.invalidText),\n        showWarn: !!o.warn && interactive,\n        warnText: asText(o.warnText),\n        helperText: asText(o.helperText),\n        hasWarn: !!o.warnText,\n        hasHelper: !!o.helperText,\n    });\n    const contents = { error: o.invalidText ?? (count.over ? tooLong : ''), warn: o.warnText, helper: o.helperText };\n    let announcement = '';\n    if (count.over) announcement = tooLong;\n    else if (count.near) announcement = o.nearLimitText ?? (words ? t.nearWordLimit : t.nearLimit);\n    return {\n        id,\n        t,\n        length,\n        count,\n        showError,\n        message,\n        messageContent: message ? contents[message.kind] : null,\n        messageId: message ? `${id}-message` : undefined,\n        announcement,\n        onTyped: setTyped,\n    };\n}\n\n/** The `12/100` counter after the label (Carbon `maxCount`), red past the limit, with a polite live region for the announcement. */\nexport function FieldCounter({ length, max, over, announcement, fluid }: Readonly<{ length: number; max: number | undefined; over: boolean; announcement: string; fluid?: boolean }>) {\n    if (max === undefined) return null;\n    return (\n        <>\n            <span className={cn('ms-auto type-caption text-ink-muted', over && 'text-error', fluid && 'absolute end-4 top-[13px] z-1')} aria-hidden=\"true\">\n                {length}/{max}\n            </span>\n            <span className=\"sr-only\" aria-live=\"polite\">\n                {announcement}\n            </span>\n        </>\n    );\n}\n"
    }
  ]
}
