{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "rhf-advanced-01",
  "title": "Dynamic Field Array",
  "description": "Start from an empty state, then add and remove teammate rows with per-item validation.",
  "dependencies": [
    "react-hook-form",
    "@hookform/resolvers",
    "zod",
    "sonner",
    "lucide-react"
  ],
  "registryDependencies": [
    "card",
    "badge",
    "empty",
    "field",
    "input",
    "select",
    "button"
  ],
  "files": [
    {
      "path": "registry/forms/react-hook-form/advanced/rhf-advanced-01.tsx",
      "content": "'use client'\n\nimport { useState } from 'react'\nimport { useFieldArray, useForm } from 'react-hook-form'\nimport { zodResolver } from '@hookform/resolvers/zod'\nimport {\n  CheckIcon,\n  CopyIcon,\n  PencilIcon,\n  Trash2Icon,\n  UserPlusIcon,\n  UsersIcon,\n} from 'lucide-react'\nimport { toast } from 'sonner'\nimport * as z from 'zod'\n\nimport { Badge } from '@/components/ui/badge'\nimport { Button } from '@/components/ui/button'\nimport {\n  Card,\n  CardContent,\n  CardDescription,\n  CardFooter,\n  CardHeader,\n  CardTitle,\n} from '@/components/ui/card'\nimport {\n  Empty,\n  EmptyContent,\n  EmptyDescription,\n  EmptyHeader,\n  EmptyMedia,\n  EmptyTitle,\n} from '@/components/ui/empty'\nimport {\n  Field,\n  FieldError,\n  FieldGroup,\n  FieldLabel,\n} from '@/components/ui/field'\nimport { Input } from '@/components/ui/input'\nimport {\n  Select,\n  SelectContent,\n  SelectGroup,\n  SelectItem,\n  SelectLabel,\n  SelectTrigger,\n  SelectValue,\n} from '@/components/ui/select'\n\nconst ROLES = [\n  { value: 'owner', label: 'Owner' },\n  { value: 'admin', label: 'Admin' },\n  { value: 'member', label: 'Member' },\n  { value: 'viewer', label: 'Viewer' },\n]\n\nconst memberSchema = z.object({\n  name: z.string().min(1, 'Name is required.'),\n  email: z.email('Enter a valid email.'),\n  role: z.string().min(1, 'Pick a role.'),\n})\n\nconst formSchema = z.object({\n  members: z.array(memberSchema).min(1, 'Add at least one teammate.'),\n})\n\ntype Member = z.infer<typeof memberSchema>\ntype FormValues = z.infer<typeof formSchema>\ntype RowErrors = Partial<Record<keyof Member, string>>\n\nconst emptyMember: Member = { name: '', email: '', role: '' }\n\nfunction initials(name: string) {\n  const parts = name.trim().split(/\\s+/).filter(Boolean)\n  if (parts.length === 0) return '?'\n  return parts\n    .slice(0, 2)\n    .map((p) => p[0]?.toUpperCase())\n    .join('')\n}\n\nfunction roleLabel(value: string) {\n  return ROLES.find((r) => r.value === value)?.label ?? value\n}\n\nexport function RhfAdvanced01() {\n  const form = useForm<FormValues>({\n    resolver: zodResolver(formSchema),\n    defaultValues: { members: [] },\n  })\n\n  const { fields, append, remove } = useFieldArray({\n    control: form.control,\n    name: 'members',\n  })\n\n  const [editingIndex, setEditingIndex] = useState<number | null>(null)\n  const [rowErrors, setRowErrors] = useState<RowErrors>({})\n\n  function startAdd() {\n    append(emptyMember)\n    setRowErrors({})\n    setEditingIndex(fields.length)\n  }\n\n  function commit(index: number) {\n    const result = memberSchema.safeParse(form.getValues(`members.${index}`))\n    if (!result.success) {\n      const next: RowErrors = {}\n      for (const issue of result.error.issues) {\n        const key = issue.path[0] as keyof Member\n        if (key && !next[key]) next[key] = issue.message\n      }\n      setRowErrors(next)\n      return\n    }\n    setRowErrors({})\n    setEditingIndex(null)\n  }\n\n  function edit(index: number) {\n    setRowErrors({})\n    setEditingIndex(index)\n  }\n\n  function duplicate(index: number) {\n    append({ ...form.getValues(`members.${index}`) })\n    setRowErrors({})\n    setEditingIndex(null)\n  }\n\n  function deleteRow(index: number) {\n    remove(index)\n    setRowErrors({})\n    setEditingIndex(null)\n  }\n\n  function onSubmit(data: FormValues) {\n    if (editingIndex !== null) {\n      toast.error('Finish the open teammate before sending.')\n      return\n    }\n    toast.success('Invites sent', {\n      description: `${data.members.length} teammate(s)`,\n    })\n  }\n\n  return (\n    <Card className=\"w-full max-w-lg\">\n      <CardHeader>\n        <CardTitle>Invite your team</CardTitle>\n        <CardDescription>\n          Fill in a teammate, confirm it, then manage each one in place.\n        </CardDescription>\n      </CardHeader>\n      <form\n        onSubmit={form.handleSubmit(onSubmit)}\n        className=\"flex flex-col gap-3\"\n      >\n        <CardContent className=\"flex flex-col gap-3\">\n          {fields.length === 0 ? (\n            <Empty className=\"border\">\n              <EmptyHeader>\n                <EmptyMedia variant=\"icon\">\n                  <UsersIcon />\n                </EmptyMedia>\n                <EmptyTitle>No teammates yet</EmptyTitle>\n                <EmptyDescription>\n                  Invite people by email and assign each one a role.\n                </EmptyDescription>\n              </EmptyHeader>\n              <EmptyContent>\n                <Button\n                  type=\"button\"\n                  variant=\"outline\"\n                  size=\"sm\"\n                  onClick={startAdd}\n                >\n                  <UserPlusIcon className=\"size-4\" />\n                  Add teammate\n                </Button>\n              </EmptyContent>\n            </Empty>\n          ) : (\n            <>\n              {fields.map((field, index) => {\n                if (editingIndex === index) {\n                  return (\n                    <div\n                      key={field.id}\n                      className=\"bg-muted/30 flex flex-col gap-4 rounded-lg border p-4\"\n                    >\n                      <FieldGroup className=\"gap-4\">\n                        <Field data-invalid={!!rowErrors.name}>\n                          <FieldLabel htmlFor={`rhf-advanced-01-name-${index}`}>\n                            Name\n                          </FieldLabel>\n                          <Input\n                            id={`rhf-advanced-01-name-${index}`}\n                            placeholder=\"Ada Lovelace\"\n                            aria-invalid={!!rowErrors.name}\n                            {...form.register(`members.${index}.name`)}\n                          />\n                          {rowErrors.name && (\n                            <FieldError\n                              errors={[{ message: rowErrors.name }]}\n                            />\n                          )}\n                        </Field>\n                        <Field data-invalid={!!rowErrors.email}>\n                          <FieldLabel\n                            htmlFor={`rhf-advanced-01-email-${index}`}\n                          >\n                            Email\n                          </FieldLabel>\n                          <Input\n                            id={`rhf-advanced-01-email-${index}`}\n                            type=\"email\"\n                            placeholder=\"ada@example.com\"\n                            aria-invalid={!!rowErrors.email}\n                            {...form.register(`members.${index}.email`)}\n                          />\n                          {rowErrors.email && (\n                            <FieldError\n                              errors={[{ message: rowErrors.email }]}\n                            />\n                          )}\n                        </Field>\n                        <Field data-invalid={!!rowErrors.role}>\n                          <FieldLabel htmlFor={`rhf-advanced-01-role-${index}`}>\n                            Role\n                          </FieldLabel>\n                          <Select\n                            value={form.watch(`members.${index}.role`)}\n                            onValueChange={(value) =>\n                              form.setValue(\n                                `members.${index}.role`,\n                                value ?? '',\n                                {\n                                  shouldDirty: true,\n                                },\n                              )\n                            }\n                          >\n                            <SelectTrigger\n                              id={`rhf-advanced-01-role-${index}`}\n                              className=\"w-full\"\n                              aria-invalid={!!rowErrors.role}\n                            >\n                              <SelectValue placeholder=\"Select a role\" />\n                            </SelectTrigger>\n                            <SelectContent>\n                              <SelectGroup>\n                                <SelectLabel>Workspace role</SelectLabel>\n                                {ROLES.map((role) => (\n                                  <SelectItem\n                                    key={role.value}\n                                    value={role.value}\n                                  >\n                                    {role.label}\n                                  </SelectItem>\n                                ))}\n                              </SelectGroup>\n                            </SelectContent>\n                          </Select>\n                          {rowErrors.role && (\n                            <FieldError\n                              errors={[{ message: rowErrors.role }]}\n                            />\n                          )}\n                        </Field>\n                      </FieldGroup>\n                      <div className=\"flex items-center justify-between\">\n                        <Button\n                          type=\"button\"\n                          variant=\"destructive\"\n                          size=\"sm\"\n                          onClick={() => deleteRow(index)}\n                        >\n                          <Trash2Icon className=\"size-4\" />\n                          Remove\n                        </Button>\n                        <Button\n                          type=\"button\"\n                          size=\"sm\"\n                          onClick={() => commit(index)}\n                        >\n                          <CheckIcon className=\"size-4\" />\n                          Done\n                        </Button>\n                      </div>\n                    </div>\n                  )\n                }\n\n                const member = form.getValues(`members.${index}`)\n                return (\n                  <div\n                    key={field.id}\n                    className=\"flex items-center gap-3 rounded-lg border p-3\"\n                  >\n                    <div className=\"bg-primary/10 text-primary flex size-9 shrink-0 items-center justify-center rounded-full text-xs font-medium\">\n                      {initials(member.name)}\n                    </div>\n                    <div className=\"min-w-0 flex-1\">\n                      <div className=\"flex items-center gap-2\">\n                        <span className=\"truncate text-sm font-medium\">\n                          {member.name}\n                        </span>\n                        <Badge variant=\"secondary\">\n                          {roleLabel(member.role)}\n                        </Badge>\n                      </div>\n                      <p className=\"text-muted-foreground truncate text-sm\">\n                        {member.email}\n                      </p>\n                    </div>\n                    <div className=\"flex items-center gap-1\">\n                      <Button\n                        type=\"button\"\n                        variant=\"ghost\"\n                        size=\"icon-sm\"\n                        aria-label=\"Edit teammate\"\n                        onClick={() => edit(index)}\n                        title=\"Edit teammate\"\n                      >\n                        <PencilIcon className=\"size-4\" />\n                      </Button>\n                      <Button\n                        type=\"button\"\n                        variant=\"ghost\"\n                        size=\"icon-sm\"\n                        aria-label=\"Duplicate teammate\"\n                        onClick={() => duplicate(index)}\n                        title=\"Duplicate teammate\"\n                      >\n                        <CopyIcon className=\"size-4\" />\n                      </Button>\n                      <Button\n                        type=\"button\"\n                        variant=\"ghost\"\n                        size=\"icon-sm\"\n                        aria-label=\"Delete teammate\"\n                        onClick={() => deleteRow(index)}\n                        title=\"Delete teammate\"\n                      >\n                        <Trash2Icon className=\"size-4\" />\n                      </Button>\n                    </div>\n                  </div>\n                )\n              })}\n              <Button\n                type=\"button\"\n                variant=\"outline\"\n                size=\"sm\"\n                className=\"w-full\"\n                onClick={startAdd}\n              >\n                <UserPlusIcon className=\"size-4\" />\n                Add another teammate\n              </Button>\n            </>\n          )}\n        </CardContent>\n        <CardFooter className=\"justify-end\">\n          <Button\n            type=\"submit\"\n            size=\"sm\"\n            disabled={fields.length === 0 || editingIndex !== null}\n          >\n            Send invites\n          </Button>\n        </CardFooter>\n      </form>\n    </Card>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/flx/forms/react-hook-form/rhf-advanced-01.tsx"
    }
  ],
  "type": "registry:block"
}