{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-number-input",
  "type": "registry:ui",
  "title": "react-tw/number-input.tsx",
  "description": "Carbon `NumberInput` as a React + Tailwind component, the look and rules of `<ui-number-input>` 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": [
    "@purpurabog/ui@^2.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/core-field",
    "@kanok-ui/tw-affix",
    "@kanok-ui/tw-field",
    "@kanok-ui/tw-i18n",
    "@kanok-ui/tw-refs",
    "@kanok-ui/tw-skeleton",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/number-input.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/number-input.tsx",
      "content": "import { useId, useLayoutEffect, useRef, useState, type ComponentProps, type CSSProperties, type ReactNode } from 'react';\nimport { pickMessage } from '../core/field.ts';\nimport { NumberInput as NumberInputPrimitive } from '@purpurabog/ui/headless';\nimport { FieldLabel, FieldMessageLine, StatusIcon, fluidBoxClasses, fluidControlClasses, useFluid, useFieldDisabled, fieldBoxClasses, fieldStateEdges, fieldInvalidRing, fieldTextSize } from './field.tsx';\nimport { useLanguage, useTranslation } from './lib/i18n.ts';\nimport type { FieldMessage } from '../core/field.ts';\nimport { cn } from './lib/utils.ts';\nimport { Affix, useAffixes } from './affix.tsx';\nimport { useMergedRefs } from './lib/refs.ts';\nimport { FieldSkeleton, type FieldSkeletonProps } from './skeleton.tsx';\n\n/**\n * Carbon `NumberInput` as a React + Tailwind component, the look and rules of `<ui-number-input>`\n * on the headless `NumberInput` (core/number-format): a number field with Carbon's two 40px steppers (− then +) at the end\n * instead of the browser spinner; ↑ / ↓ step too. Steppers clamp to `min` / `max` and round to the\n * precision of the value or `step`; from an empty field they start at `stepStartValue`, else ±1,\n * else `min`. Out of range is invalid, so is an empty field unless `allowEmpty` — through the\n * input's own constraint validation, so forms block submit; the error shows once the field was\n * left (or a submit was tried).\n *\n * `type=\"text\"` formats the number for `locale` (default: the page language) with\n * `formatOptions` (`Intl.NumberFormat`: currency, percent, units…): free text while typing,\n * reformatted on blur; `onChange` and the submitted value stay a plain number (`1234.5` for\n * `฿1,234.50`; a percent gives the fraction). `fluid` (or a `FluidForm`) is Carbon `FluidNumberInput`.\n * `prefixText` / `suffixText` (a currency, a unit that stays in view and is not part of the value)\n * have no Carbon counterpart, as `<ui-number-input>` / `TextInput`.\n */\nexport interface NumberInputProps extends Omit<ComponentProps<'input'>, 'size' | 'type' | 'value' | 'defaultValue' | 'onChange' | 'min' | 'max' | 'step'> {\n    label?: ReactNode;\n    hideLabel?: boolean;\n    helperText?: ReactNode;\n    /** Forces the error state, e.g. after server-side validation. */\n    invalid?: boolean;\n    /** The error text (default: the browser's or the translation's message for what is wrong). */\n    invalidText?: ReactNode;\n    warn?: boolean;\n    warnText?: ReactNode;\n    /** The value as plain number text ('' = empty); a number is accepted too. */\n    value?: string | number;\n    defaultValue?: string | number;\n    /** The new value (plain number text, '' when empty) after typing, a stepper, an arrow key or a blur that rounded it. */\n    onChange?: (value: string) => void;\n    min?: number;\n    max?: number;\n    /** Step of the steppers and ↑ / ↓; with `type=\"number\"` also the allowed precision. */\n    step?: number;\n    /** Where the steppers start from an empty field (Carbon `stepStartValue`); 0 = ±1, or `min` when only a minimum is set. */\n    stepStartValue?: number;\n    type?: 'number' | 'text';\n    /** BCP 47 locale of `type=\"text\"`; default the page language. */\n    locale?: string;\n    /** `Intl.NumberFormat` options of `type=\"text\"`. */\n    formatOptions?: Intl.NumberFormatOptions;\n    /** An empty field is valid (Carbon `allowEmpty`). */\n    allowEmpty?: boolean;\n    /** No − / + buttons (the arrow keys still step). */\n    hideSteppers?: boolean;\n    /** Ignore the mouse wheel while focused (Carbon `disableWheel`). */\n    disableWheel?: boolean;\n    /** Heights: sm 32px · md 40px (Carbon default) · lg 48px. */\n    size?: 'sm' | 'md' | 'lg';\n    decrementLabel?: string;\n    incrementLabel?: string;\n    lang?: string;\n    /** Carbon `FluidNumberInput` (also set by `FluidForm`). */\n    fluid?: boolean;\n    /** Text inside the field before the value, e.g. a currency (`฿`); not part of the value. Part of the field's description for screen readers. */\n    prefixText?: ReactNode;\n    /** Text inside the field after the value, e.g. a unit (`kg`); not part of the value. Part of the field's description for screen readers. */\n    suffixText?: ReactNode;\n}\n\nconst HEIGHT = { sm: 'var(--ui-field-height-sm, 32px)', md: 'var(--ui-field-height-md, 40px)', lg: 'var(--ui-field-height-lg, 48px)' } as const;\n\nconst subtractIcon = (\n    <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n        <path d=\"M3 7.5h10v1H3z\" />\n    </svg>\n);\nconst addIcon = (\n    <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n        <path d=\"M8.5 3v4.5H13v1H8.5V13h-1V8.5H3v-1h4.5V3z\" />\n    </svg>\n);\n\nconst asText = (node: ReactNode) => (typeof node === 'string' ? node : '');\n\n/** The message under the field: the author's error or the field's own validity, a warning, or the helper. */\nfunction numberMessage(o: { showError: boolean; invalidText?: ReactNode; validation: string; showWarn: boolean; warnText?: ReactNode; helperText?: ReactNode }) {\n    const message = pickMessage({\n        showError: o.showError,\n        errorText: asText(o.invalidText) || o.validation,\n        showWarn: o.showWarn,\n        warnText: asText(o.warnText),\n        helperText: asText(o.helperText),\n        hasWarn: !!o.warnText,\n        hasHelper: !!o.helperText,\n    });\n    const content = message ? { error: o.invalidText || message.text, warn: o.warnText, helper: o.helperText }[message.kind] : null;\n    return { message, content };\n}\n\n/** Carbon: 96px end padding for the steppers (+32 with a status icon); 16 without steppers (+32 with an icon); fluid 80 / 16. */\nfunction endPadding(status: string | undefined, hideSteppers: boolean, fluid: boolean) {\n    if (fluid) return hideSteppers ? 'pe-4' : 'pe-20';\n    if (hideSteppers) return status ? 'pe-12' : 'pe-4';\n    return status ? 'pe-32' : 'pe-24';\n}\n\n/** Where the suffix ends: 16px before the steppers (80px, none when hidden), and before the status icon (16px + 8) unless fluid (its icon is in the message row). */\nfunction suffixEnd(status: string | undefined, hideSteppers: boolean, fluid: boolean) {\n    const icon = !!status && !fluid;\n    if (hideSteppers) return icon ? 'end-10' : 'end-4';\n    return icon ? 'end-[120px]' : 'end-24';\n}\n\n/** The value 8px clear of the prefix / suffix (widths measured by useAffixes). */\nfunction affixPadding(hasPrefix: boolean, hasSuffix: boolean, status: string | undefined, hideSteppers: boolean, fluid: boolean) {\n    const icon = !!status && !fluid;\n    const end = { '0': 'pe-[calc(16px_+_var(--suffix-width,0px)_+_8px)]', '24': 'pe-[calc(40px_+_var(--suffix-width,0px)_+_8px)]', '80': 'pe-[calc(96px_+_var(--suffix-width,0px)_+_8px)]', '104': 'pe-[calc(120px_+_var(--suffix-width,0px)_+_8px)]' }[(hideSteppers ? 0 : 80) + (icon ? 24 : 0)];\n    return cn(hasPrefix && 'ps-[calc(16px_+_var(--prefix-width,0px)_+_8px)]', hasSuffix && end);\n}\n\n/** Secondary text over the input, clicks going through; on the value's line when fluid. */\nconst affixClasses = (fluid: boolean) => cn('pointer-events-none absolute inset-y-0 flex items-center [input:disabled~&]:text-ink-disabled', fluid && 'top-8 bottom-auto h-[18px]');\n\nfunction inputClasses({ status, hideSteppers, fluid, showError }: { status: FieldMessage['kind'] | undefined; hideSteppers: boolean; fluid: boolean; showError: boolean }) {\n    return cn(\n        'm-0 box-border h-(--_h) w-full min-w-[150px] py-0 ps-4',\n        endPadding(status, hideSteppers, fluid),\n        fieldBoxClasses,\n        'text-ink type-body-sm [appearance:textfield]',\n        fieldTextSize,\n        '[&::-webkit-inner-spin-button]:m-0 [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:m-0 [&::-webkit-outer-spin-button]:appearance-none',\n        'outline-[length:var(--ui-field-focus-width,2px)] [outline-offset:calc(-1*var(--ui-field-focus-width,2px))] outline-transparent transition-[background-color,outline-color] duration-(--ui-duration-fast) ease-carbon',\n        'placeholder:text-ink-placeholder placeholder:opacity-100 focus:outline-focus focus:[box-shadow:var(--ui-field-focus-halo,none)]',\n        showError && fieldInvalidRing,\n        'disabled:cursor-not-allowed disabled:text-ink-disabled',\n        'read-only:not-disabled:bg-[var(--ui-field-readonly-background,transparent)]',\n        fieldStateEdges,\n        'forced-colors:border forced-colors:border-[FieldText] forced-colors:focus:outline-[Highlight]',\n        // fluid: the value under the label, the steppers level with it\n        fluid && cn('pt-8 pb-[13px]', fluidControlClasses(status)),\n    );\n}\n\n/** A 40px stepper with Carbon's 16px rule at its start edge (over the button, so it stays 40px). */\nconst stepClasses = (disabled: boolean) =>\n    cn(\n        'relative m-0 inline-flex h-full w-10 cursor-pointer items-center justify-center rounded-[var(--ui-icon-control-radius,0px)] border-0 bg-transparent p-0 text-ink [&_svg]:size-4 [&_svg]:fill-current',\n        'enabled:hover:bg-ghost-hover enabled:hover:shadow-[inset_0_-1px_0_var(--ui-ink-subtle)]',\n        // the field focused, a hovered stepper keeps its 2px focus line: the fill inside it, under the icon (as <ui-number-input>)\n        \"[&_svg]:relative [&_svg]:z-[1] after:pointer-events-none after:absolute after:inset-x-0 after:inset-y-0.5 after:content-[''] last:after:end-0.5\",\n        '[input:focus~*_&]:enabled:hover:bg-transparent [input:focus~*_&]:enabled:hover:shadow-none [input:focus~*_&]:enabled:hover:after:bg-ghost-hover',\n        'outline-none focus-visible:outline-[length:var(--ui-focus-width,2px)] focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-focus',\n        'disabled:cursor-not-allowed disabled:text-ink-disabled',\n        \"before:absolute before:start-0 before:top-1/2 before:h-4 before:w-px before:-translate-y-1/2 before:bg-hairline before:content-['']\",\n        disabled && 'before:bg-transparent',\n        'forced-colors:border forced-colors:border-solid forced-colors:border-[ButtonText]',\n    );\n\ninterface SteppersProps {\n    fluid: boolean;\n    disabled: boolean;\n    labels: { decrement: string; increment: string };\n}\n\n/** − and + (out of the tab order: the arrow keys step from the field); each off at its end of the range. */\nfunction Steppers({ fluid, disabled, labels }: Readonly<SteppersProps>) {\n    return (\n        <span className={cn('absolute inset-y-0 end-0 flex w-20 items-center', fluid && 'top-[23px] bottom-auto h-10')}>\n            <NumberInputPrimitive.Decrement aria-label={labels.decrement} className={stepClasses(disabled)}>\n                {subtractIcon}\n            </NumberInputPrimitive.Decrement>\n            <NumberInputPrimitive.Increment aria-label={labels.increment} className={stepClasses(disabled)}>\n                {addIcon}\n            </NumberInputPrimitive.Increment>\n        </span>\n    );\n}\n\nconst hasLabel = (label: ReactNode) => label !== undefined && label !== '';\n\ninterface FieldEndProps {\n    kind: FieldMessage['kind'] | undefined;\n    fluid: boolean;\n    hideSteppers: boolean;\n    disabled: boolean;\n    labels: SteppersProps['labels'];\n}\n\n/** The end of the field: the status icon (fluid: in the message row), then − and + unless hidden. */\nfunction FieldEnd({ kind, fluid, hideSteppers, disabled, labels }: Readonly<FieldEndProps>) {\n    return (\n        <>\n            <span className={cn('pointer-events-none absolute inset-y-0 flex items-center pe-4', hideSteppers || fluid ? 'end-0' : 'end-20')}>\n                <StatusIcon kind={kind} className={fluid ? 'absolute end-4 top-[calc(100%+8px)]' : undefined} />\n            </span>\n            {hideSteppers ? null : <Steppers fluid={fluid} disabled={disabled} labels={labels} />}\n        </>\n    );\n}\n\n/** The steppers' names: yours, else the translation's. */\nconst stepperLabels = (decrement: string | undefined, increment: string | undefined, t: { decrement: string; increment: string }) => ({ decrement: decrement || t.decrement, increment: increment || t.increment });\n\n/** The props the field below the headless `Root` reads (the value, limits and format go to `Root`). */\ntype FieldProps = Omit<NumberInputProps, 'value' | 'defaultValue' | 'onChange' | 'min' | 'max' | 'step' | 'stepStartValue' | 'type' | 'locale' | 'formatOptions' | 'disabled' | 'readOnly' | 'name'>;\n\nexport function NumberInput({ value, defaultValue, onChange, min, max, step = 1, stepStartValue = 0, type = 'number', locale, formatOptions, lang, disabled: ownDisabled, readOnly = false, name, ...field }: Readonly<NumberInputProps>) {\n    const disabled = useFieldDisabled(ownDisabled);\n    // type=\"text\" formats for `locale`, else the page language\n    const language = useLanguage(locale || lang);\n    return (\n        <NumberInputPrimitive.Root\n            value={value}\n            defaultValue={defaultValue}\n            onValueChange={onChange}\n            min={min}\n            max={max}\n            step={step}\n            stepStartValue={stepStartValue}\n            type={type}\n            locale={language}\n            formatOptions={formatOptions}\n            disabled={disabled}\n            readOnly={readOnly}\n            name={name}\n        >\n            <NumberInputField {...field} lang={lang} />\n        </NumberInputPrimitive.Root>\n    );\n}\n\nfunction NumberInputField({\n    label,\n    hideLabel,\n    helperText,\n    invalid = false,\n    invalidText,\n    warn = false,\n    warnText,\n    allowEmpty = false,\n    hideSteppers = false,\n    disableWheel = false,\n    size = 'md',\n    decrementLabel,\n    incrementLabel,\n    lang,\n    fluid: fluidProp,\n    prefixText,\n    suffixText,\n    className,\n    id,\n    placeholder,\n    required = false,\n    ref,\n    ...rest\n}: Readonly<FieldProps>) {\n    const ctx = NumberInputPrimitive.useNumberInputContext();\n    const { disabled, readOnly, interactive, format, number, isEmpty, badText, min, max } = ctx;\n    const t = useTranslation(lang).field;\n    const autoId = useId();\n    const inputId = id ?? autoId;\n    const input = useRef<HTMLInputElement>(null);\n    const row = useRef<HTMLDivElement>(null);\n    const inputRef = useMergedRefs(input, ref);\n    const fluid = useFluid(fluidProp);\n    const [validation, setValidation] = useState('');\n\n    // the field's own validity, as <ui-number-input>: forced error, unparsable text, empty, out of range, then the browser's\n    // the box's validity, set on the element after every render\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    useLayoutEffect(() => {\n        const el = input.current;\n        if (!el) return;\n        el.setCustomValidity('');\n        let message = invalid ? asText(invalidText) || ' ' : '';\n        if (!message && badText) message = asText(invalidText) || t.enterNumber;\n        else if (!message && isEmpty && !allowEmpty && !required) message = asText(invalidText) || t.enterNumber;\n        else if (!message && format && !Number.isNaN(number)) {\n            if (min !== undefined && number < min) message = asText(invalidText) || t.rangeUnderflow.replace('{min}', format.format(min));\n            else if (max !== undefined && number > max) message = asText(invalidText) || t.rangeOverflow.replace('{max}', format.format(max));\n        }\n        if (message) el.setCustomValidity(message);\n        setValidation(disabled ? '' : message.trim() || el.validationMessage);\n    });\n\n    const showError = interactive && (invalid || (ctx.touched && validation !== ''));\n    const { message, content } = numberMessage({ showError, invalidText, validation, showWarn: warn && interactive, warnText, helperText });\n    const status = message && message.kind !== 'helper' ? message.kind : undefined;\n    const { hasPrefix, hasSuffix, describedBy } = useAffixes(row, inputId, prefixText, suffixText, message ? `${inputId}-message` : undefined);\n\n    return (\n        <div className={cn('block font-sans', fluid && fluidBoxClasses(status, readOnly), className)} style={{ '--_h': fluid ? '64px' : HEIGHT[size] } as CSSProperties}>\n            {hasLabel(label) ? (\n                <FieldLabel htmlFor={inputId} hidden={hideLabel} disabled={disabled} fluid={fluid}>\n                    {label}\n                </FieldLabel>\n            ) : null}\n            <div ref={row} className=\"relative flex items-center\">\n                <NumberInputPrimitive.Input\n                    {...rest}\n                    ref={inputRef}\n                    id={inputId}\n                    disableWheel={disableWheel}\n                    placeholder={placeholder}\n                    required={required}\n                    aria-invalid={showError}\n                    aria-describedby={describedBy}\n                    className={cn(inputClasses({ status, hideSteppers, fluid, showError }), affixPadding(hasPrefix, hasSuffix, status, hideSteppers, fluid))}\n                />\n                <Affix id={inputId} kind=\"prefix\" className={cn(affixClasses(fluid), 'start-4')}>\n                    {prefixText}\n                </Affix>\n                <Affix id={inputId} kind=\"suffix\" className={cn(affixClasses(fluid), suffixEnd(status, hideSteppers, fluid))}>\n                    {suffixText}\n                </Affix>\n                <NumberInputPrimitive.HiddenInput />\n                <FieldEnd kind={message?.kind} fluid={fluid} hideSteppers={hideSteppers} disabled={disabled} labels={stepperLabels(decrementLabel, incrementLabel, t)} />\n            </div>\n            <FieldMessageLine id={`${inputId}-message`} message={message} content={content} disabled={disabled} fluid={fluid} />\n        </div>\n    );\n}\n\n/** Carbon `NumberInputSkeleton`: the shape of the field while its data loads (label bar, 8px, the field's bar). Hidden from assistive tech. */\nexport function NumberInputSkeleton(props: Readonly<FieldSkeletonProps>) {\n    return <FieldSkeleton {...props} />;\n}\n"
    }
  ]
}
