{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "forms",
  "title": "Forms",
  "description": "Primitives for forms without a form library: a form state hook with validation on blur and submit, server errors, dirty and submitting flags, a titled form section, a sticky save bar, wizard steps, a form in a side sheet, an inline edit field and an email check.",
  "registryDependencies": [
    "button",
    "input",
    "input-group",
    "sheet",
    "https://www.dashboardblocks.com/r/radix/checklist.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/forms.tsx",
      "content": "'use client'\n\nimport { StepIndicator } from '@/registry/components/dashboardblocks/checklist'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport {\n  type ChangeEvent,\n  type FocusEvent,\n  type FormEvent,\n  type KeyboardEvent,\n  type ReactNode,\n  startTransition,\n  useCallback,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n} from 'react'\nimport { flushSync } from 'react-dom'\n\nimport { Button } from '@/components/ui/button'\nimport { Input } from '@/components/ui/input'\nimport {\n  InputGroup,\n  InputGroupAddon,\n  InputGroupInput,\n  InputGroupText,\n} from '@/components/ui/input-group'\nimport {\n  Sheet,\n  SheetContent,\n  SheetDescription,\n  SheetFooter,\n  SheetHeader,\n  SheetTitle,\n} from '@/components/ui/sheet'\n\nimport { cn } from '@/lib/utils'\n\ntype FormValues = Record<string, string | number | boolean | readonly string[] | null>\n\ntype FormErrors<T extends FormValues> = Partial<Record<keyof T & string, string>>\n\ntype SubmitResult<T extends FormValues> = void | FormErrors<T>\n\ninterface UseSimpleFormOptions<T extends FormValues> {\n  /** The saved values. When one changes, its field follows unless it has an unsaved change. */\n  defaultValues: T\n  onSubmit: (values: T) => SubmitResult<T> | Promise<SubmitResult<T>>\n  validate?: (values: T) => FormErrors<T>\n}\n\nfunction focusFirstOf(ids: string[]) {\n  const elements = ids\n    .map((id) => document.getElementById(id))\n    .filter((element) => element !== null)\n  elements.sort((a, b) =>\n    a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1,\n  )\n  elements[0]?.focus()\n}\n\nfunction hasErrors(errors: Record<string, string | undefined>) {\n  return Object.values(errors).some(Boolean)\n}\n\nfunction sameValue(a: FormValues[string], b: FormValues[string]) {\n  if (Array.isArray(a) && Array.isArray(b)) {\n    return a.length === b.length && a.every((item) => b.includes(item))\n  }\n  return a === b\n}\n\nfunction useSimpleForm<T extends FormValues>({\n  defaultValues,\n  onSubmit,\n  validate,\n}: UseSimpleFormOptions<T>) {\n  const formId = useId()\n  const [values, setValues] = useState(defaultValues)\n  const [savedValues, setSavedValues] = useState(defaultValues)\n  const [touched, setTouched] = useState<Partial<Record<keyof T, boolean>>>({})\n  const [submitted, setSubmitted] = useState(false)\n  const [serverErrors, setServerErrors] = useState<FormErrors<T>>({})\n  const [isSubmitting, setIsSubmitting] = useState(false)\n  const [refusedIds, setRefusedIds] = useState<string[] | null>(null)\n  const focusedRefusal = useRef<string[] | null>(null)\n\n  useEffect(() => {\n    if (!refusedIds || refusedIds === focusedRefusal.current) return\n    focusedRefusal.current = refusedIds\n    focusFirstOf(refusedIds)\n  }, [refusedIds])\n\n  const names = Object.keys(defaultValues) as (keyof T & string)[]\n  const [lastDefaults, setLastDefaults] = useState(defaultValues)\n  const moved = names.filter(\n    (name) => !sameValue(defaultValues[name], lastDefaults[name]),\n  )\n  if (moved.length) {\n    setLastDefaults(defaultValues)\n    setValues((current) => {\n      const next = { ...current }\n      for (const name of moved) {\n        if (sameValue(current[name], savedValues[name])) next[name] = defaultValues[name]\n      }\n      return next\n    })\n    setSavedValues((current) => {\n      const next = { ...current }\n      for (const name of moved) next[name] = defaultValues[name]\n      return next\n    })\n  }\n  const clientErrors: FormErrors<T> = validate?.(values) ?? {}\n  const errors: FormErrors<T> = {}\n  for (const name of names) {\n    const error =\n      ((touched[name] || submitted) && clientErrors[name]) || serverErrors[name]\n    if (error) errors[name] = error\n  }\n  const changedFields = names.filter(\n    (name) => !sameValue(values[name], savedValues[name]),\n  )\n  const isDirty = changedFields.length > 0\n\n  const getId = (name: keyof T & string) => `${formId}-${name}`\n\n  function focusFirst(invalid: (keyof T & string)[]) {\n    focusFirstOf(invalid.map(getId))\n  }\n\n  function setValue<K extends keyof T & string>(name: K, value: T[K]) {\n    setValues((current) => ({ ...current, [name]: value }))\n    setServerErrors((current) => ({ ...current, [name]: undefined }))\n  }\n\n  function validateFields(fields: (keyof T & string)[]) {\n    flushSync(() =>\n      setTouched((current) => ({\n        ...current,\n        ...Object.fromEntries(fields.map((name) => [name, true])),\n      })),\n    )\n    const invalid = fields.filter((name) => clientErrors[name])\n    focusFirst(invalid)\n    return invalid.length === 0\n  }\n\n  function field(name: keyof T & string) {\n    const id = getId(name)\n    return {\n      'aria-describedby': errors[name] ? `${id}-error` : undefined,\n      'aria-invalid': errors[name] ? true : undefined,\n      id,\n      name,\n      onBlur: (event: FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n        const next = event.relatedTarget\n        if (\n          !event.currentTarget.value.trim() ||\n          (next instanceof HTMLButtonElement &&\n            next.type === 'submit' &&\n            next.form === event.currentTarget.form)\n        )\n          return\n        setTouched((current) => ({ ...current, [name]: true }))\n      },\n      onChange: (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>\n        setValue(name, event.target.value as T[typeof name]),\n      value: String(values[name]),\n    }\n  }\n\n  function select(name: keyof T & string) {\n    const id = getId(name)\n    return {\n      'aria-describedby': errors[name] ? `${id}-error` : undefined,\n      'aria-invalid': errors[name] ? true : undefined,\n      id,\n      name,\n      onValueChange: (value: string) => setValue(name, value as T[typeof name]),\n      value: String(values[name]),\n    }\n  }\n\n  /**\n   * For a field that holds a list, such as a multi-select. It's named by the element with the id\n   * `${getId(name)}-label`.\n   */\n  function list(name: keyof T & string) {\n    const id = getId(name)\n    const value = values[name]\n    return {\n      'aria-describedby': errors[name] ? `${id}-error` : undefined,\n      'aria-invalid': errors[name] ? true : undefined,\n      'aria-labelledby': `${id}-label`,\n      id,\n      name,\n      onValueChange: (next: string[]) =>\n        setValue(name, next as unknown as T[typeof name]),\n      value: Array.isArray(value) ? value : [],\n    }\n  }\n\n  /** For a number field: the value is a number, or `null` while the field is empty. */\n  function number(name: keyof T & string) {\n    const id = getId(name)\n    const value = values[name]\n    return {\n      'aria-describedby': errors[name] ? `${id}-error` : undefined,\n      'aria-invalid': errors[name] ? true : undefined,\n      id,\n      name,\n      onValueChange: (next: number | null) => setValue(name, next as T[typeof name]),\n      value: typeof value === 'number' ? value : null,\n    }\n  }\n\n  function error(name: keyof T & string) {\n    return { children: errors[name], id: `${getId(name)}-error` }\n  }\n\n  /**\n   * Validates, then saves in one transition, so a page the save refreshes and\n   * `onSaved`'s own updates show together. Resolves to `true` once saved;\n   * rejects when `onSubmit` throws.\n   */\n  async function submit(\n    event?: FormEvent<HTMLFormElement>,\n    { onSaved }: { onSaved?: () => void } = {},\n  ) {\n    event?.preventDefault()\n    flushSync(() => setSubmitted(true))\n    const invalid = names.filter((name) => clientErrors[name])\n    if (invalid.length) {\n      focusFirst(invalid)\n      return false\n    }\n    setIsSubmitting(true)\n    return new Promise<boolean>((resolve, reject) => {\n      startTransition(async () => {\n        try {\n          const result = await onSubmit(values)\n          if (result && hasErrors(result)) {\n            startTransition(() => {\n              setServerErrors(result)\n              setRefusedIds(names.filter((name) => result[name]).map(getId))\n            })\n            resolve(false)\n            return\n          }\n          startTransition(() => {\n            setSavedValues(values)\n            setSubmitted(false)\n            setTouched({})\n            onSaved?.()\n          })\n          resolve(true)\n        } catch (error) {\n          reject(error)\n        } finally {\n          startTransition(() => setIsSubmitting(false))\n        }\n      })\n    })\n  }\n\n  function reset(next: T = savedValues) {\n    setValues(next)\n    setSavedValues(next)\n    setTouched({})\n    setSubmitted(false)\n    setServerErrors({})\n  }\n\n  return {\n    changedFields,\n    error,\n    errors,\n    field,\n    getId,\n    isDirty,\n    isSubmitting,\n    list,\n    number,\n    reset,\n    select,\n    setValue,\n    submit,\n    validateFields,\n    values,\n  }\n}\n\ninterface FormSectionProps {\n  children: ReactNode\n  className?: string\n  description?: ReactNode\n  title: string\n}\n\nfunction FormSection({ children, className, description, title }: FormSectionProps) {\n  return (\n    <section className={cn('@container border-t pt-4', className)}>\n      <div className='grid gap-4 @3xl:grid-cols-[16rem_1fr] @3xl:gap-8'>\n        <div className='flex flex-col gap-0.5'>\n          <h3 className='text-sm font-medium'>{title}</h3>\n          {description && (\n            <p className='text-muted-foreground text-sm text-pretty'>{description}</p>\n          )}\n        </div>\n        <div className='min-w-0'>{children}</div>\n      </div>\n    </section>\n  )\n}\n\ninterface SaveBarProps {\n  className?: string\n  isDirty: boolean\n  isSubmitting: boolean\n  /** @default 'You have unsaved changes' */\n  message?: string\n  onDiscard: () => void\n  /** @default 'Save changes' */\n  saveLabel?: string\n}\n\nfunction SaveBar({\n  className,\n  isDirty,\n  isSubmitting,\n  message = 'You have unsaved changes',\n  onDiscard,\n  saveLabel = 'Save changes',\n}: SaveBarProps) {\n  if (!isDirty && !isSubmitting) return null\n  return (\n    <div\n      role='region'\n      aria-label='Unsaved changes'\n      data-floating-bar\n      className={cn(\n        'bg-popover text-popover-foreground animate-in fade-in slide-in-from-bottom-2 sticky bottom-4 z-10 mx-auto flex w-full max-w-xl items-center justify-between gap-3 rounded-xl p-2 pl-4 shadow-lg ring-1 ring-foreground/10',\n        className,\n      )}\n    >\n      <p className='text-sm'>{message}</p>\n      <div className='flex gap-2'>\n        <Button type='button' variant='ghost' disabled={isSubmitting} onClick={onDiscard}>\n          Discard\n        </Button>\n        <Button type='submit' disabled={isSubmitting}>\n          {isSubmitting ? 'Saving' : saveLabel}\n        </Button>\n      </div>\n    </div>\n  )\n}\n\ninterface FormStep {\n  description?: string\n  title: string\n}\n\ninterface FormStepsProps {\n  className?: string\n  current: number\n  steps: FormStep[]\n}\n\nfunction FormSteps({ className, current, steps }: FormStepsProps) {\n  return (\n    <ol className={cn('@container flex gap-3', className)}>\n      {steps.map((step, index) => {\n        const state =\n          index < current ? 'done' : index === current ? 'current' : 'upcoming'\n        return (\n          <li\n            key={step.title}\n            aria-current={state === 'current' ? 'step' : undefined}\n            data-state={state}\n            className='group/step data-[state=done]:border-chart-2 data-[state=upcoming]:border-border border-foreground flex min-w-0 flex-1 items-start gap-2 border-t-2 pt-3'\n          >\n            <StepIndicator\n              index={index + 1}\n              state={state === 'upcoming' ? 'todo' : state}\n            />\n            <span className='sr-only min-w-0 flex-col gap-0.5 @md:not-sr-only @md:flex'>\n              <span className='group-data-[state=upcoming]/step:text-muted-foreground text-sm font-medium break-words'>\n                {step.title}\n              </span>\n              <span className='sr-only'>\n                {state === 'done'\n                  ? ', done'\n                  : state === 'upcoming'\n                    ? ', not started'\n                    : ''}\n              </span>\n              {step.description && (\n                <span className='text-muted-foreground hidden text-xs break-words @md:block'>\n                  {step.description}\n                </span>\n              )}\n            </span>\n          </li>\n        )\n      })}\n    </ol>\n  )\n}\n\ninterface FormSheetProps {\n  children: ReactNode\n  className?: string\n  description?: ReactNode\n  footer: ReactNode\n  onOpenChange: (open: boolean) => void\n  onSubmit: (event: FormEvent<HTMLFormElement>) => void\n  open: boolean\n  title: string\n}\n\nfunction FormSheet({\n  children,\n  className,\n  description,\n  footer,\n  onOpenChange,\n  onSubmit,\n  open,\n  title,\n}: FormSheetProps) {\n  const [bodyInset, setBodyInset] = useState<string>()\n  const measureHeader = useCallback((header: HTMLDivElement | null) => {\n    if (header) setBodyInset(getComputedStyle(header).paddingInlineStart)\n  }, [])\n\n  return (\n    <Sheet open={open} onOpenChange={onOpenChange}>\n      <SheetContent className={cn('sm:max-w-md', className)}>\n        <form\n          method='post'\n          noValidate\n          onSubmit={onSubmit}\n          className='flex min-h-0 flex-1 flex-col'\n        >\n          <SheetHeader ref={measureHeader}>\n            <SheetTitle>{title}</SheetTitle>\n            {description && <SheetDescription>{description}</SheetDescription>}\n          </SheetHeader>\n          <div\n            className='min-h-0 flex-1 overflow-y-auto px-4 py-2 [scrollbar-width:thin]'\n            style={{ paddingInline: bodyInset }}\n          >\n            {children}\n          </div>\n          <SheetFooter>{footer}</SheetFooter>\n        </form>\n      </SheetContent>\n    </Sheet>\n  )\n}\n\ninterface InlineEditFieldProps {\n  className?: string\n  emptyLabel?: string\n  /** A sentence under the value saying what it changes, or a function that writes it from what's typed, so it follows the draft. */\n  hint?: ReactNode | ((value: string) => ReactNode)\n  label: string\n  /** Leave out to show the value only, with no Edit, for someone who may read it but not change it. */\n  onSave?: (value: string) => string | void | Promise<string | void>\n  /** Text the value always follows, such as `tandem.app/` before a workspace's address: shown before it, and not part of what's edited. */\n  prefix?: string\n  type?: 'email' | 'tel' | 'text' | 'url'\n  validate?: (value: string) => string | undefined\n  value: string\n}\n\nfunction InlineEditField({\n  className,\n  emptyLabel = 'Not set',\n  hint,\n  label,\n  onSave,\n  prefix,\n  type = 'text',\n  validate,\n  value,\n}: InlineEditFieldProps) {\n  const id = useId()\n  const [draft, setDraft] = useState<string | null>(null)\n  const [error, setError] = useState<string>()\n  const [isSaving, setIsSaving] = useState(false)\n  const [focusOn, setFocusOn] = useState({ count: 0, target: 'edit' })\n  const focusedFor = useRef(0)\n  const fieldRef = useRef<HTMLInputElement>(null)\n  const editRef = useRef<HTMLButtonElement>(null)\n  const editing = draft !== null\n  const shownHint = typeof hint === 'function' ? hint(draft ?? value) : hint\n\n  useEffect(() => {\n    if (focusOn.count === focusedFor.current) return\n    focusedFor.current = focusOn.count\n    ;(focusOn.target === 'field' ? fieldRef : editRef).current?.focus()\n  }, [focusOn])\n\n  const focusNext = (target: 'edit' | 'field') =>\n    setFocusOn((previous) => ({ count: previous.count + 1, target }))\n\n  function cancel() {\n    setDraft(null)\n    setError(undefined)\n    focusNext('edit')\n  }\n\n  async function save() {\n    if (draft === null) return\n    if (draft === value) return cancel()\n    const invalid = validate?.(draft)\n    if (invalid) return setError(invalid)\n    setIsSaving(true)\n    try {\n      const failed = await onSave?.(draft)\n      startTransition(() => {\n        if (!failed) return cancel()\n        setError(failed)\n        focusNext('field')\n      })\n    } finally {\n      startTransition(() => setIsSaving(false))\n    }\n  }\n\n  function onKeyDown(event: KeyboardEvent<HTMLInputElement>) {\n    if (event.key === 'Enter') {\n      event.preventDefault()\n      void save()\n    } else if (event.key === 'Escape') {\n      event.preventDefault()\n      cancel()\n    }\n  }\n\n  const FieldInput = prefix ? InputGroupInput : Input\n  const field = (\n    <FieldInput\n      // oxlint-disable-next-line jsx-a11y/no-autofocus -- the field replaces the Edit button the person just pressed\n      autoFocus\n      ref={fieldRef}\n      type={type}\n      aria-labelledby={`${id}-label`}\n      value={draft ?? ''}\n      aria-invalid={error ? true : undefined}\n      aria-describedby={\n        [error && `${id}-error`, shownHint && `${id}-hint`].filter(Boolean).join(' ') ||\n        undefined\n      }\n      readOnly={isSaving}\n      onChange={(event) => {\n        setDraft(event.target.value)\n        setError(undefined)\n      }}\n      onKeyDown={onKeyDown}\n    />\n  )\n\n  return (\n    <div className={cn('@container py-2.5', className)}>\n      <div className='grid gap-1.5 @md:grid-cols-[10rem_minmax(0,1fr)] @md:items-start @md:gap-x-4 @md:gap-y-1'>\n        <span id={`${id}-label`} className='text-muted-foreground pt-2 text-sm'>\n          {label}\n        </span>\n        {editing ? (\n          <div className='flex flex-col gap-1.5'>\n            <div className='flex gap-2'>\n              {prefix ? (\n                <InputGroup>\n                  <InputGroupAddon>\n                    <InputGroupText>{prefix}</InputGroupText>\n                  </InputGroupAddon>\n                  {field}\n                </InputGroup>\n              ) : (\n                field\n              )}\n              <Button type='button' disabled={isSaving} onClick={() => void save()}>\n                {isSaving ? 'Saving' : 'Save'}\n              </Button>\n              <Button type='button' variant='ghost' disabled={isSaving} onClick={cancel}>\n                Cancel\n              </Button>\n            </div>\n            {error && (\n              <p id={`${id}-error`} role='alert' className='text-destructive text-sm'>\n                {error}\n              </p>\n            )}\n          </div>\n        ) : (\n          <div className='flex min-h-9 min-w-0 items-center justify-between gap-2'>\n            <span\n              className={cn(\n                'min-w-0 truncate text-sm',\n                !value && 'text-muted-foreground',\n              )}\n            >\n              {value && prefix ? (\n                <span className='text-muted-foreground'>{prefix}</span>\n              ) : null}\n              {value || emptyLabel}\n            </span>\n            {onSave ? (\n              <Button\n                type='button'\n                variant='ghost'\n                size='sm'\n                ref={editRef}\n                aria-label={`Edit ${label.toLowerCase()}`}\n                onClick={() => setDraft(value)}\n              >\n                <IconPlaceholder\n                  lucide='PencilIcon'\n                  tabler='IconPencil'\n                  hugeicons='PencilEdit02Icon'\n                  phosphor='PencilSimpleIcon'\n                  remixicon='RiPencilLine'\n                />\n                Edit\n              </Button>\n            ) : null}\n          </div>\n        )}\n        {shownHint ? (\n          <p\n            id={`${id}-hint`}\n            className='text-muted-foreground text-sm text-pretty @md:col-start-2'\n          >\n            {shownHint}\n          </p>\n        ) : null}\n      </div>\n    </div>\n  )\n}\n\nfunction isEmail(value: string) {\n  return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value)\n}\n\nexport {\n  FormSection,\n  FormSheet,\n  FormSteps,\n  InlineEditField,\n  isEmail,\n  SaveBar,\n  useSimpleForm,\n}\n\nexport type {\n  FormErrors,\n  FormSectionProps,\n  FormSheetProps,\n  FormStep,\n  FormStepsProps,\n  FormValues,\n  InlineEditFieldProps,\n  SaveBarProps,\n  UseSimpleFormOptions,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/forms.tsx"
    }
  ],
  "type": "registry:component"
}
