{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "field-control",
  "title": "Field control",
  "description": "A control that isn't one of ui-sdk's, joined to its Field as ui-sdk's controls are: the Field's id, label, description and check on the element its label names, a native input the Field checks for a control that keeps its value elsewhere, and its values sent with a form as hidden inputs. Kino's own controls share it, such as the Combobox's button, the Calendar and the File input. OutsideField keeps one of them inside another control, such as a profile photo's upload button, from being taken as its Field's control.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/refs.json"
  ],
  "files": [
    {
      "path": "registry/lib/field-control.tsx",
      "content": "'use client'\n\nimport { mergeRefs } from '@/registry/lib/refs'\nimport type { ChangeDetails, ChangeSource } from '@ui-sdk/core'\nimport { useFieldControl } from '@ui-sdk/react/field'\nimport {\n  createContext,\n  type ReactNode,\n  type Ref,\n  type RefCallback,\n  type RefObject,\n  use,\n  useEffect,\n  useEffectEvent,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from 'react'\n\n/*\n * What a control that isn't one of ui-sdk's fields needs to sit in its Field\n * like one: a part of ui-sdk's that joins no Field itself, or a control of our\n * own, such as the Listbox. `useFieldProps` puts the Field's id, label,\n * description and check on the element its label names; `FieldCheck` gives\n * the Field a native input to check when the control keeps no value of its\n * own in one; `FieldValues` sends its values with the form; `useLabelFocus`\n * hands a press on the label to the part that takes focus.\n */\n\n/** Whether the parts inside sit outside the Field around them. */\nconst OutsideContext = createContext(false)\n\n/**\n * Parts inside a control that aren't its Field's control, such as a phone\n * number's country picker: outside this, they would take the Field's label,\n * description and name as the control does.\n */\nfunction OutsideField({ children }: { children: ReactNode }) {\n  return <OutsideContext value>{children}</OutsideContext>\n}\n\n/**\n * The Field around a control, from ui-sdk's `useFieldControl`: its name,\n * whether it is off, and `props` for its control. Null outside a Field, and\n * inside an `OutsideField`.\n */\nfunction useField(own?: { id?: string }) {\n  const outside = use(OutsideContext)\n  const field = useFieldControl(own)\n  return outside ? null : field\n}\n\n/** What a Field puts on the element its label names. */\ninterface FieldAttributes {\n  id?: string\n  'aria-labelledby'?: string\n  'aria-describedby'?: string\n  /** Set while the Field shows its check failing. */\n  'aria-invalid'?: 'true'\n}\n\n/**\n * The Field around a control, and `props` with the Field's merged in for the\n * element its label names: the id, `aria-labelledby`, `aria-describedby` and\n * `aria-invalid` while its check fails, and its ref. `field` is null outside\n * a Field, with `props` as given; `invalid` says whether the Field shows its\n * control as invalid. A control whose component makes the id it renders\n * passes that id as `own`.\n */\nfunction useFieldProps<P extends object>(props: P, own?: { id?: string }) {\n  const field = useField(own)\n  const { ref, ...rest } = props as P & { ref?: Ref<Element> }\n  const merged = (field ? field.props(rest) : rest) as FieldAttributes & {\n    ref?: Ref<Element>\n    'data-slot'?: string\n  }\n  // ui-sdk hands back the slot it was given, undefined too, which would wipe a slot set before the spread.\n  if (merged['data-slot'] === undefined) delete merged['data-slot']\n  const fieldRef = merged.ref\n  const refs = useMemo(() => mergeRefs(ref, fieldRef), [ref, fieldRef])\n  return {\n    field,\n    invalid: merged['aria-invalid'] === 'true',\n    props: { ...merged, ref: refs } as Omit<P, 'ref'> &\n      FieldAttributes & { ref: RefCallback<RefTarget<P>> },\n  }\n}\n\n/** The element a control's `ref` takes. */\ntype RefTarget<P> = P extends { ref?: Ref<infer E> } ? E : Element\n\n/**\n * Whether a form's reset leaves a control as it is: a controlled one with no\n * default value, so its owner's state stays the only source of its value, as\n * ui-sdk's controls do. Any other goes back to its default value.\n */\nfunction keptOnReset(value: unknown, defaultValue: unknown) {\n  return value !== undefined && defaultValue === undefined\n}\n\n/** How a person made a change, from the event behind it, as ui-sdk tells it: none is code's. */\nfunction sourceOf(event: Event | undefined): ChangeSource {\n  if (!event) return 'programmatic'\n  if (event.type.startsWith('key')) return 'keyboard'\n  if (\n    'pointerType' in event &&\n    typeof event.pointerType === 'string' &&\n    event.pointerType\n  )\n    return event.pointerType as ChangeSource\n  if ('detail' in event && event.type === 'click')\n    return event.detail === 0 ? 'virtual' : 'mouse'\n  return 'programmatic'\n}\n\n/**\n * The details of a change a control of our own makes, in ui-sdk's shape, so\n * its owner reads `details.source` and calls `details.cancel()` as on any\n * of ui-sdk's: for a change no ui-sdk part reported, such as a form's reset.\n */\nfunction changeDetails<Reason extends string>(\n  reason: Reason,\n  event?: Event,\n): ChangeDetails<Reason> {\n  let canceled = false\n  return {\n    reason,\n    event,\n    source: sourceOf(event),\n    cancel: () => {\n      canceled = true\n    },\n    get canceled() {\n      return canceled\n    },\n  } as ChangeDetails<Reason>\n}\n\n/**\n * Each of `values` as a hidden input under `name`, sent with the form, or with\n * the form `form` names.\n */\nfunction FieldValues({\n  name,\n  form,\n  values,\n  many = false,\n}: {\n  name: string | undefined\n  form?: string\n  values: readonly string[]\n  /** Whether the control takes several values, so a Form's values hold a list under `name` even with one. */\n  many?: boolean\n}) {\n  if (!name) return null\n  // By place: two values can be the same.\n  return values.map((value, index) => (\n    <input\n      // oxlint-disable-next-line react/no-array-index-key -- the inputs hold no state, and two values may match\n      key={index}\n      type='hidden'\n      name={name}\n      form={form}\n      value={value}\n      data-many={many ? '' : undefined}\n    />\n  ))\n}\n\n/** The style ui-sdk gives the native input behind a checkbox: in the page, unseen and out of the way. */\nconst checkStyle = {\n  position: 'absolute',\n  width: 1,\n  height: 1,\n  margin: -1,\n  padding: 0,\n  border: 0,\n  overflow: 'hidden',\n  clipPath: 'inset(50%)',\n  whiteSpace: 'nowrap',\n  opacity: 0,\n  pointerEvents: 'none',\n} as const\n\n/**\n * A native input, unseen, that holds a control's check for its Field and the\n * form: empty while the control is, so `required` turns an empty one down,\n * and failing with `message` while there is one. It sends nothing unless it\n * has a `name`. The form's own check focuses it when it fails, and it hands\n * focus to `onFocus`, the control's own part. Each change to `value` or\n * `message` tells the Field, as typing in an input does, so it checks again\n * and a server's error for it goes. A Field's `validate` checks it, and\n * `onReset` puts the control back when the form is reset.\n */\nfunction FieldCheck({\n  value,\n  name,\n  required,\n  readOnly,\n  message = '',\n  disabled,\n  form,\n  onFocus,\n  onReset,\n  control,\n}: {\n  /** What the control holds, as text: empty while it holds nothing. */\n  value: string\n  name?: string\n  required?: boolean\n  readOnly?: boolean\n  /** Why it fails, beyond `required`; empty while it passes. */\n  message?: string\n  disabled?: boolean\n  form?: string\n  onFocus: () => void\n  /** Puts the control back to its default when its form is reset, as a native control goes back. */\n  onReset?: (event: Event) => void\n  /** The Field's props from `useFieldProps`, when this input is the element its label names. */\n  control?: FieldAttributes & { ref?: Ref<HTMLInputElement> }\n}) {\n  const input = useRef<HTMLInputElement>(null)\n  const controlRef = control?.ref\n  const refs = useMemo(() => mergeRefs(input, controlRef), [controlRef])\n  useFormReset(input, (event) => onReset?.(event), form)\n  useLayoutEffect(() => {\n    input.current?.setCustomValidity(disabled ? '' : message)\n  }, [message, disabled])\n  const told = useRef({ value, message })\n  useEffect(() => {\n    const last = told.current\n    told.current = { value, message }\n    if (last.value === value && last.message === message) return\n    input.current?.dispatchEvent(new Event('input', { bubbles: true }))\n  }, [value, message])\n  return (\n    <input\n      {...control}\n      ref={refs}\n      // Its own message, which a Field's `validate` keeps ahead of its own.\n      data-field-check={disabled ? '' : message}\n      aria-hidden\n      tabIndex={-1}\n      name={name}\n      form={form}\n      value={value}\n      required={required}\n      readOnly={readOnly}\n      disabled={disabled}\n      // Its value comes from the control; nothing types into it.\n      onChange={() => {}}\n      onFocus={onFocus}\n      style={checkStyle}\n    />\n  )\n}\n\n/**\n * Focuses the control with `focus` when its Field's label, by `labelId`, is\n * pressed, as a label does for an input, for a control whose focus goes to a\n * part inside it, such as a Calendar's day.\n */\nfunction useLabelFocus(\n  labelId: string | undefined,\n  disabled: boolean,\n  focus: () => void,\n) {\n  useEffect(() => {\n    const label = labelId ? document.getElementById(labelId) : null\n    if (!label || disabled) return\n    label.addEventListener('click', focus)\n    return () => label.removeEventListener('click', focus)\n  }, [labelId, disabled, focus])\n}\n\n/**\n * Calls `reset` when the form around `element`, or the one `form` names, is\n * reset, so a control that keeps its value in its own state goes back to its\n * default as a native one does.\n */\nfunction useFormReset(\n  element: RefObject<Element | null>,\n  reset: (event: Event) => void,\n  form?: string,\n) {\n  const onReset = useEffectEvent(reset)\n  useEffect(() => {\n    const own = element.current\n    const owner = form\n      ? own?.ownerDocument.getElementById(form)\n      : (own?.closest('form') ?? null)\n    if (!owner) return\n    const listener = (event: Event) => onReset(event)\n    owner.addEventListener('reset', listener)\n    return () => owner.removeEventListener('reset', listener)\n  }, [element, form])\n}\n\nexport {\n  changeDetails,\n  FieldCheck,\n  FieldValues,\n  keptOnReset,\n  OutsideField,\n  useField,\n  useFieldProps,\n  useFormReset,\n  useLabelFocus,\n}\n",
      "type": "registry:lib",
      "target": "@lib/field-control.tsx"
    }
  ],
  "type": "registry:lib"
}