{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "gulf-field",
  "type": "registry:ui",
  "title": "Gulf field",
  "description": "The label, note and caret handling the gulf inputs share.",
  "dependencies": [
    "@dualkit/format"
  ],
  "registryDependencies": [
    "label"
  ],
  "files": [
    {
      "path": "gulf/gulf-field.tsx",
      "type": "registry:ui",
      "target": "components/gulf/gulf-field.tsx",
      "content": "import { toArabicDigits, type Numerals, type Result } from '@dualkit/format'\nimport {\n  useId, useLayoutEffect, useRef, useState,\n  type ChangeEvent, type CSSProperties, type KeyboardEvent, type ReactNode, type RefObject,\n} from 'react'\nimport { Label } from '@/components/ui/label'\n\n/** Props every gulf field shares. All copy comes in from the app, so each language owns its own words. */\nexport type GulfFieldText<C extends string> = {\n  label: ReactNode\n  help?: ReactNode\n  /** Shown at once and marks the field invalid. Use it for errors the app finds, such as a required field. */\n  error?: ReactNode\n  /** Copy for each format error code, shown once the field loses focus. A code with no copy shows format's English message. */\n  errorMessages?: Partial<Record<C, ReactNode>>\n  id?: string\n  name?: string\n  placeholder?: string\n  disabled?: boolean\n  required?: boolean\n  className?: string\n}\n\nexport type FieldAria = {\n  id: string\n  'aria-invalid': true | undefined\n  'aria-describedby': string | undefined\n}\n\nexport const cx = (...parts: ReadonlyArray<string | false | null | undefined>): string => parts.filter(Boolean).join(' ')\n\n/** Arabic-Indic digits on screen when asked; the value underneath stays Western. */\nexport const withNumerals = (text: string, numerals: Numerals): string => (numerals === 'arab' ? toArabicDigits(text) : text)\n\ntype GulfFieldProps = {\n  id: string | undefined\n  label: ReactNode\n  help: ReactNode\n  error: ReactNode\n  className: string | undefined\n  children: (aria: FieldAria) => ReactNode\n}\n\n/** Label, control and one note under it. The label and note follow the page direction; each control sets its own. */\nexport function GulfField({ id, label, help, error, className, children }: GulfFieldProps) {\n  const auto = useId()\n  const inputId = id ?? auto\n  const noteId = `${inputId}-note`\n  const note = error ?? help\n  return (\n    <div data-slot=\"gulf-field\" className={cx('grid gap-2', className)}>\n      <Label htmlFor={inputId}>{label}</Label>\n      {children({\n        id: inputId,\n        'aria-invalid': error != null ? true : undefined,\n        'aria-describedby': note != null ? noteId : undefined,\n      })}\n      {note != null && (\n        <p id={noteId} role={error != null ? 'alert' : undefined}\n          className={cx('text-sm', error != null ? 'text-destructive' : 'text-muted-foreground')}>{note}</p>\n      )}\n    </div>\n  )\n}\n\n/** The error to show: the app's own at once, format's only after the person leaves the field, and never for an empty one. */\nexport function useShownError<C extends string>(\n  result: Result<unknown, C>,\n  error: ReactNode,\n  messages: Partial<Record<C, ReactNode>> | undefined,\n): { error: ReactNode; onBlur: () => void } {\n  const [touched, setTouched] = useState(false)\n  const fromFormat = touched && !result.ok && result.error.code !== 'empty'\n    ? (messages?.[result.error.code] ?? result.error.message)\n    : undefined\n  return { error: error ?? fromFormat, onBlur: () => setTouched(true) }\n}\n\nexport type Mask = {\n  /** Raw text from the field to the stored value. */\n  normalize: (raw: string) => string\n  /** Stored value to the text on screen. Each stored character shows as one character, plus separators. */\n  display: (value: string) => string\n  /** Characters the display adds, which the caret steps over. */\n  separator?: RegExp\n}\n\nconst countValue = (text: string, separator: RegExp | undefined): number =>\n  separator ? [...text].filter((ch) => !separator.test(ch)).length : text.length\n\n/** The first index in the shown text with n stored characters before it. */\nfunction positionAfter(text: string, n: number, separator: RegExp | undefined): number {\n  if (!separator) return Math.min(n, text.length)\n  let seen = 0\n  for (let i = 0; i < text.length; i++) {\n    if (seen === n) return i\n    if (!separator.test(text[i] ?? '')) seen++\n  }\n  return text.length\n}\n\n/**\n * Phones, IBANs, IDs, amounts and dates read left to right in every language. Arabic-Indic digits are Arabic numbers\n * to the bidi algorithm, so a space or hyphen between two groups would flip their order; overriding keeps typed order.\n */\nexport const LTR_VALUE: CSSProperties = { unicodeBidi: 'bidi-override' }\n/** The override is inherited by ::placeholder and would reverse an Arabic placeholder, so the placeholder opts out. */\nexport const LTR_PLACEHOLDER = 'placeholder:[unicode-bidi:normal]'\n\ntype MaskedInput = {\n  ref: RefObject<HTMLInputElement | null>\n  style: CSSProperties\n  value: string\n  onChange: (event: ChangeEvent<HTMLInputElement>) => void\n  onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => void\n}\n\n/** A controlled input whose screen text differs from its value, with the caret kept where the person put it. */\nexport function useMaskedInput(value: string, mask: Mask, commit: (next: string) => void): MaskedInput {\n  const ref = useRef<HTMLInputElement | null>(null)\n  const caret = useRef<number | null>(null)\n  const { normalize, display, separator } = mask\n\n  const place = (el: HTMLInputElement, n: number) => {\n    if (el.ownerDocument.activeElement !== el) return\n    const at = positionAfter(el.value, n, separator)\n    el.setSelectionRange(at, at)\n  }\n\n  useLayoutEffect(() => {\n    const el = ref.current\n    const n = caret.current\n    caret.current = null\n    if (n !== null && el) place(el, n)\n  })\n\n  const onChange = (event: ChangeEvent<HTMLInputElement>) => {\n    const el = event.currentTarget\n    const raw = el.value\n    const n = normalize(raw.slice(0, el.selectionStart ?? raw.length)).length\n    const next = normalize(raw)\n    if (next === value) {\n      // Nothing to store, so React skips the render and puts the old text back once this handler returns,\n      // which sends the caret to the end. Put it back after that.\n      caret.current = null\n      queueMicrotask(() => place(el, n))\n      return\n    }\n    caret.current = n\n    commit(next)\n  }\n\n  /** Backspace or Delete next to a separator removes the character beyond it, or the key would do nothing. */\n  const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {\n    const el = event.currentTarget\n    const at = el.selectionStart\n    if (!separator || at === null || at !== el.selectionEnd) return\n    const before = countValue(el.value.slice(0, at), separator)\n    if (event.key === 'Backspace' && at > 0 && separator.test(el.value[at - 1] ?? '')) {\n      event.preventDefault()\n      if (before === 0) return\n      caret.current = before - 1\n      commit(value.slice(0, before - 1) + value.slice(before))\n    } else if (event.key === 'Delete' && separator.test(el.value[at] ?? '')) {\n      event.preventDefault()\n      caret.current = before\n      commit(value.slice(0, before) + value.slice(before + 1))\n    }\n  }\n\n  return { ref, style: LTR_VALUE, value: display(value), onChange, onKeyDown }\n}\n"
    }
  ],
  "docs": "Needs a shadcn project (Tailwind and the shadcn CSS variables). Works with and without `shadcn init --rtl`: set dir=\"rtl\" on <html> or a parent for Arabic. Pass every label, help text and error message as props."
}
