{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "edit-sheet",
  "title": "EditSheet",
  "description": "Edits something in a form inside a dialog: the whole interaction, done right.",
  "registryDependencies": [
    "@ouro/button",
    "@ouro/dialog",
    "@ouro/form",
    "@ouro/lib-class-name-check",
    "@ouro/lib-dev",
    "@ouro/lib-env",
    "@ouro/lib-form-answer",
    "@ouro/lib-open-mode",
    "@ouro/lib-use-dev-messages",
    "@ouro/sheet"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/form/edit-sheet.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type FormEvent, type JSX, type MouseEvent, type ReactElement, type ReactNode } from \"react\";\nimport { useAppearanceClassNameCheck } from \"@/registry/ouro/lib/ouro/class-name-check\";\nimport { devWarn } from \"@/registry/ouro/lib/ouro/dev\";\nimport { checkOpenMode, type TriggerOrOpen } from \"@/registry/ouro/lib/ouro/open-mode\";\nimport { useDevWarnings } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\nimport { Button } from \"@/registry/ouro/components/ouro/button/button\";\nimport { DialogFrame } from \"@/registry/ouro/components/ouro/dialog/dialog\";\nimport { Form, type ReadonlyFormErrors } from \"@/registry/ouro/components/ouro/form/form\";\nimport { sheetHint } from \"@/registry/ouro/components/ouro/sheet/sheet-styles\";\nimport { formErrors } from \"@/registry/ouro/lib/ouro/form-answer\";\n\n/**\n * Pressing Save or Cancel leaves focus in the field. On a phone, focus leaving the field\n * drops the software keyboard and its inset, which moves the footer down before the click\n * lands, so the tap would miss. A tap moves focus on its compatibility `mousedown`, so\n * cancelling that is enough, and `pointerdown` is left alone.\n */\nconst keepFieldFocus = {\n  onMouseDown: (event: MouseEvent<HTMLButtonElement>) => event.preventDefault(),\n};\n\n/** What `onSubmit` may return: nothing (saved), or errors by field name (not saved). */\nexport type EditSheetResult = void | undefined | ReadonlyFormErrors;\n\n/** Props shared by both ways of opening an EditSheet. */\nexport interface EditSheetBaseProps {\n  /** Names the sheet for screen readers and shows at its top: `title=\"Edit recipe\"`. Hide it with `hideTitle`. */\n  title: string;\n  /** Hides the title visually. It still names the sheet for screen readers. */\n  hideTitle?: boolean | undefined;\n  /** A short line under the title, read out when the sheet opens. */\n  description?: ReactNode;\n  /**\n   * Saves the form. It gets the fields as `FormData`, after the browser's own checks\n   * (`required`, `type=\"email\"`) pass. Return nothing to close the sheet and return focus to\n   * the trigger, or errors by field name (`{ name: \"That name is taken.\" }`) to keep it open\n   * with each message on its field and focus on the first; a `form` key, or a key no field\n   * is named, shows in an alert at the top of the form. Return a promise to show `loading`\n   * on the save button until it settles; meanwhile Cancel is disabled and the sheet cannot\n   * be dismissed. If it rejects (or throws), the sheet stays open with `failureMessage`.\n   */\n  onSubmit: (data: FormData) => EditSheetResult | Promise<EditSheetResult>;\n  /** The save button's label: the action, such as `\"Save recipe\"`. Translate it with your app. @default \"Save\" */\n  submitLabel?: string | undefined;\n  /** The cancel button's label. Translate it with your app. @default \"Cancel\" */\n  cancelLabel?: string | undefined;\n  /** The label of the close button in the corner. Translate it with your app. @default \"Close\" */\n  closeLabel?: string | undefined;\n  /**\n   * What the sheet shows, at the top of the form, when `onSubmit` rejects or throws. Translate it with your app.\n   * By default it shows the rejected error's own message, so reject with one a person can read.\n   * @default \"Your changes were not saved: <the error's message>. Press <submitLabel> to try again.\", or, for an error without a message, \"Your changes were not saved. The save stopped without saying why. Press <submitLabel> to try again.\"\n   */\n  failureMessage?: string | undefined;\n  /**\n   * The question the sheet asks, in place of its buttons, when the user dismisses it (Escape,\n   * a tap outside, a swipe down, Cancel or the close button) after changing a field.\n   * Translate it with your app. @default \"Discard your changes?\"\n   */\n  discardMessage?: string | undefined;\n  /** The button that discards the edits and closes the sheet. @default \"Discard\" */\n  discardLabel?: string | undefined;\n  /** The button that goes back to the form with the edits kept; it takes focus. @default \"Keep editing\" */\n  keepEditingLabel?: string | undefined;\n  /**\n   * Called when the user confirms Discard, before the sheet closes. With controlled fields\n   * (`value` and `onValueChange`), reset your state here: the sheet cannot reset values it\n   * does not own, so they would come back on the next opening:\n   * `<TextField name=\"name\" value={name} onValueChange={setName} />` with\n   * `onDiscard={() => setName(recipe.name)}`. Not called for a save, or a dismissal with\n   * nothing changed.\n   */\n  onDiscard?: (() => void) | undefined;\n  /** The fields: `TextField`, `Select` and other controls with a `name`. */\n  children: ReactNode;\n  /**\n   * Layout only, applied to the panel: margins (`mt-4`). Your classes win over Ouro UI's.\n   * Appearance classes warn in development.\n   */\n  className?: string | undefined;\n\n  /** Not a prop. Ouro UI uses `onSubmit`: `<EditSheet onSubmit={(data) => save(data)}>`. */\n  onSave?: { 'Use <EditSheet onSubmit={(data) => save(data)}>': never };\n  /** Not a prop. Ouro UI uses `submitLabel`: `<EditSheet submitLabel=\"Save\">`. */\n  saveLabel?: { 'Use <EditSheet submitLabel=\"Save\">': never };\n  /** Not a prop. Ouro UI uses `submitLabel`: `<EditSheet submitLabel=\"Save\">`. */\n  submitText?: { 'Use <EditSheet submitLabel=\"Save\">': never };\n  /** Not a prop. Return errors from `onSubmit`: `onSubmit={async (data) => (await save(data)).errors}`. */\n  errors?: { 'Return errors from onSubmit: onSubmit={async (data) => (await save(data)).errors}': never };\n  /** Not a prop. Ouro UI uses `open` with `onOpenChange`: `<EditSheet open={open} onOpenChange={setOpen}>`. */\n  isOpen?: { 'Use <EditSheet open={open} onOpenChange={setOpen}>': never };\n  /** Not a prop. `onOpenChange(false)` fires on close: `<EditSheet open={open} onOpenChange={setOpen}>`. */\n  onClose?: { 'Use <EditSheet open={open} onOpenChange={setOpen}>': never };\n}\n\n/** An uncontrolled EditSheet: `trigger` opens it. */\nexport type EditSheetWithTriggerProps = EditSheetBaseProps & {\n  /** The element that opens the sheet, usually a Button: `trigger={<Button>Edit</Button>}`. */\n  trigger: ReactElement;\n  /** Not with `trigger`. Remove `trigger` to control the sheet with `open` and `onOpenChange`. */\n  open?: TriggerOrOpen;\n  /** Not with `trigger`. Remove `trigger` to control the sheet with `open` and `onOpenChange`. */\n  onOpenChange?: never;\n};\n\n/** A controlled EditSheet: you own `open` and update it in `onOpenChange`. */\nexport type EditSheetControlledProps = EditSheetBaseProps & {\n  /** Whether the sheet is open. */\n  open: boolean;\n  /** Called with `false` when the user cancels or dismisses the sheet (after confirming, with edits), and when a save succeeds. */\n  onOpenChange: (open: boolean) => void;\n  /** Not with `open`. Remove `open` and `onOpenChange` to let a trigger open the sheet. */\n  trigger?: never;\n};\n\n/** Props for {@link EditSheet}: either `trigger`, or `open` with `onOpenChange`. */\nexport type EditSheetProps = EditSheetWithTriggerProps | EditSheetControlledProps;\n\n/** The form's fields as text, to compare with how they were when the sheet opened. */\nconst serialize = (form: HTMLFormElement) =>\n  [...new FormData(form)].map(([name, value]) => `${name}=${typeof value === \"string\" ? value : value.name}`).join(\"&\");\n\n/**\n * The confirmation that takes the buttons' place: the question, then Keep editing and\n * Discard, wrapping on a narrow sheet.\n */\nconst discardClass = \"flex w-full flex-wrap items-center justify-end gap-2\";\n\n/** What a rejected save says by default: the error's own message where it has one, and the way on, by the save button's label. */\nconst failureText = (error: unknown, submitLabel: string): string => {\n  const reason = (error instanceof Error ? error.message : typeof error === \"string\" ? error : \"\").trim().replace(/\\.$/, \"\");\n  const retry = `Press ${submitLabel} to try again.`;\n  return reason ? `Your changes were not saved: ${reason}. ${retry}` : `Your changes were not saved. The save stopped without saying why. ${retry}`;\n};\n\n/** Whether `onSubmit` returned errors to show, rather than nothing or an empty object. */\nconst hasErrors = (result: EditSheetResult): result is ReadonlyFormErrors => Boolean(result) && Object.keys(result!).length > 0;\n\n/**\n * Edits something in a form inside a dialog: the whole interaction, done right. It opens\n * from `trigger` as a centered dialog, or a bottom sheet on phones, with your fields, Cancel\n * and a save button. Saving runs the browser's checks, then `onSubmit` with the fields as\n * `FormData`; a promise shows `loading` on the save button and keeps the sheet open (it\n * cannot be dismissed meanwhile). Errors it returns land on the matching fields, with focus\n * on the first; a failed save shows `failureMessage` at the top of the form; success closes\n * the sheet and returns focus to the trigger. Dismissing it after changing a field (Escape,\n * a tap outside, a swipe down, Cancel) asks inside the sheet before the edits are lost.\n * With controlled fields, reset your state in `onDiscard`, or the discarded values come back\n * on the next opening.\n *\n * Use `Form` instead for a form on the page, `Dialog` for a dialog that is not a form, and\n * `ConfirmDialog` to confirm one action.\n *\n * @group Overlays\n * @see https://ui.ouroboros.bot/docs/edit-sheet\n *\n * @example\n * <EditSheet\n *   title=\"Edit recipe\"\n *   trigger={<Button variant=\"outline\">Edit</Button>}\n *   onSubmit={async (data) => (await saveRecipe(data)).errors}\n * >\n *   <TextField label=\"Name\" name=\"name\" defaultValue={recipe.name} required />\n *   <Select label=\"Course\" name=\"course\" defaultValue={recipe.course} options={courses} />\n * </EditSheet>\n */\nexport function EditSheet(props: EditSheetProps): JSX.Element {\n  const {\n    title,\n    hideTitle,\n    description,\n    onSubmit,\n    submitLabel = \"Save\",\n    cancelLabel = \"Cancel\",\n    closeLabel = \"Close\",\n    failureMessage,\n    discardMessage = \"Discard your changes?\",\n    discardLabel = \"Discard\",\n    keepEditingLabel = \"Keep editing\",\n    onDiscard,\n    children,\n    className,\n    trigger,\n    open,\n    onOpenChange,\n    // Guard props (hint types), dropped here so they never reach the DOM.\n    onSave,\n    saveLabel,\n    submitText,\n    errors: errorsGuess,\n    isOpen,\n    onClose,\n  } = props as EditSheetBaseProps & {\n    trigger?: ReactElement;\n    open?: boolean;\n    onOpenChange?: (open: boolean) => void;\n  };\n\n  checkOpenMode(\"EditSheet\", \"edit sheet\", trigger !== undefined, open, onOpenChange);\n\n  useAppearanceClassNameCheck(\n    \"EditSheet\",\n    className,\n    process.env.NODE_ENV !== \"production\"\n      ? sheetHint('<EditSheet title=\"…\">', \"</EditSheet>\")\n      : /* istanbul ignore next @preserve -- production only */ \"\",\n  );\n  useDevWarnings(\n    \"EditSheet\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => {\n          const controlFix = \"<EditSheet open={open} onOpenChange={setOpen}>\";\n          return [\n            !title && [\"title is required; it names the sheet for screen readers\", '<EditSheet title=\"Edit recipe\">'],\n            onSave !== undefined && [\"onSave is not a prop\", \"<EditSheet onSubmit={(data) => save(data)}>\"],\n            saveLabel !== undefined && [\"saveLabel is not a prop\", '<EditSheet submitLabel=\"Save\">'],\n            submitText !== undefined && [\"submitText is not a prop\", '<EditSheet submitLabel=\"Save\">'],\n            errorsGuess !== undefined && [\n              \"errors is not a prop; return them from onSubmit\",\n              \"<EditSheet onSubmit={async (data) => (await save(data)).errors}>\",\n            ],\n            isOpen !== undefined && [\"isOpen is not a prop\", controlFix],\n            onClose !== undefined && [\"onClose is not a prop\", controlFix],\n          ];\n        }\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n\n  const formId = useId();\n  const [ownOpen, setOwnOpen] = useState(false);\n  const controlled = open !== undefined;\n  const shown = controlled ? open : ownOpen;\n  const [answer, setAnswer] = useState<{ key: number; errors: ReadonlyFormErrors | undefined }>({ key: 0, errors: undefined });\n  const [pending, setPending] = useState(false);\n  const [confirming, setConfirming] = useState(false);\n  // Each opening starts clean, however it opened (the app may set `open` itself).\n  const [wasShown, setWasShown] = useState(shown);\n  // Each opening gets a fresh form: Base UI keeps the old one mounted through the close\n  // animation, and a reopen inside it would otherwise keep an edit the user discarded.\n  const [opening, setOpening] = useState(0);\n  if (shown !== wasShown) {\n    setWasShown(shown);\n    if (shown) setOpening(opening + 1);\n    setAnswer((previous) => ({ ...previous, errors: undefined }));\n    setPending(false);\n    setConfirming(false);\n  }\n  // The fields as the sheet opened, to tell whether the user changed any (a Select's value\n  // is in its hidden input, so every control counts). Taken once per opening, when that\n  // opening's form first mounts, so a render after an edit (a controlled field, a save that\n  // failed) keeps the opening's values; a resize that swaps the dialog for the sheet mounts\n  // a new form without retaking it. Closing clears it for the next opening.\n  const initial = useRef<{ opening: number; values: string } | undefined>(undefined);\n  const formRef = useCallback((form: HTMLFormElement | null) => {\n    if (form && initial.current?.opening !== opening) initial.current = { opening, values: serialize(form) };\n  }, [opening]);\n  const edited = () => {\n    const form = document.getElementById(formId) as HTMLFormElement | null;\n    return form !== null && serialize(form) !== initial.current?.values;\n  };\n  const keepRef = useRef<HTMLButtonElement>(null);\n  useEffect(() => {\n    if (confirming) keepRef.current!.focus({ preventScroll: true });\n  }, [confirming]);\n  // Each open and close bumps the attempt, so a save that settles after the user left\n  // (Cancel, Escape) neither closes nor marks a sheet they have since reopened.\n  const attempt = useRef(0);\n  useLayoutEffect(() => {\n    const lifetime = attempt;\n    lifetime.current++;\n    return () => { lifetime.current++; };\n  }, [shown]);\n  const warnKey = useRef({});\n\n  const setOpen = (next: boolean) => {\n    if (controlled) onOpenChange!(next);\n    else setOwnOpen(next);\n  };\n\n  // A dismissal (Escape, a tap outside, a swipe, Cancel, the close button) does nothing while\n  // a save runs, asks first when a field changed, and goes back to the form while asking.\n  const dismiss = () => {\n    if (pending) return;\n    if (confirming) setConfirming(false);\n    else if (edited()) setConfirming(true);\n    else setOpen(false);\n  };\n  const onFrameOpenChange = (next: boolean) => {\n    if (next) setOpen(true);\n    else dismiss();\n  };\n\n  // Nothing (or no errors) closes the sheet; errors stay on the fields, focus on the first.\n  const refuse = (errors: ReadonlyFormErrors) => setAnswer((previous) => ({ key: previous.key + 1, errors }));\n  const finish = (result: EditSheetResult) => {\n    if (hasErrors(result)) refuse(result);\n    else setOpen(false);\n  };\n\n  const submit = (event: FormEvent<HTMLFormElement>) => {\n    event.preventDefault();\n    if (pending) return;\n    const current = attempt.current;\n    let result: EditSheetResult | Promise<EditSheetResult>;\n    try {\n      result = onSubmit(new FormData(event.currentTarget));\n    } catch (error) {\n      // A synchronous throw takes the rejection path: the sheet stays open and the error is reported.\n      result = Promise.reject(error);\n    }\n    if (!(result instanceof Promise)) {\n      if (attempt.current === current) finish(result);\n      return;\n    }\n    if (attempt.current === current) setPending(true);\n    result.then(\n      (value) => {\n        if (attempt.current !== current) return;\n        setPending(false);\n        finish(value);\n      },\n      (error: unknown) => {\n        const stale = attempt.current !== current;\n        if (!stale) {\n          setPending(false);\n          refuse({ form: failureMessage ?? failureText(error, submitLabel) });\n        }\n        /* istanbul ignore else @preserve -- the else path exists only in production bundles; scripts/dev-strip.test.mjs covers it */\n        if (process.env.NODE_ENV !== \"production\") {\n          const message = error instanceof Error ? error.message : String(error);\n          devWarn(\n            \"EditSheet\",\n            stale ? `onSubmit rejected with \"${message}\" after the user had left that edit` : `onSubmit rejected with \"${message}\", so the sheet stayed open`,\n            \"return the message as an error for a field: onSubmit={async (data) => (await save(data)).errors}\",\n            warnKey.current,\n          );\n        }\n      },\n    );\n  };\n\n  return (\n    <DialogFrame\n      title={title}\n      hideTitle={hideTitle}\n      closeLabel={closeLabel}\n      description={description}\n      presentation=\"auto\"\n      size=\"md\"\n      className={className}\n      trigger={trigger}\n      open={shown}\n      onOpenChange={onFrameOpenChange}\n      closeDisabled={pending}\n      footer={\n        confirming ? (\n          <div data-ouro=\"edit-sheet-discard\" role=\"group\" aria-labelledby={`${formId}-discard`} className={discardClass}>\n            <p id={`${formId}-discard`} role=\"alert\" className=\"m-0 me-auto text-sm leading-5 font-medium text-foreground\">\n              {discardMessage}\n            </p>\n            <Button ref={keepRef} variant=\"outline\" tone=\"secondary\" data-ouro-control=\"edit-sheet\" data-ouro-part=\"keep-editing\" onClick={() => setConfirming(false)}>\n              {keepEditingLabel}\n            </Button>\n            <Button\n              tone=\"destructive\"\n              data-ouro-control=\"edit-sheet\"\n              data-ouro-part=\"discard\"\n              onClick={() => {\n                onDiscard?.();\n                setOpen(false);\n              }}\n            >\n              {discardLabel}\n            </Button>\n          </div>\n        ) : (\n          <>\n            <Button variant=\"outline\" tone=\"secondary\" disabled={pending} data-ouro-control=\"edit-sheet\" data-ouro-part=\"cancel\" onClick={dismiss} {...keepFieldFocus}>\n              {cancelLabel}\n            </Button>\n            <Button type=\"submit\" form={formId} loading={pending} data-ouro-control=\"edit-sheet\" data-ouro-part=\"submit\" {...keepFieldFocus}>\n              {submitLabel}\n            </Button>\n          </>\n        )\n      }\n    >\n      <Form key={opening} ref={formRef} id={formId} errors={formErrors(undefined, answer.errors, { key: answer.key })} onSubmit={submit}>\n        {children}\n      </Form>\n    </DialogFrame>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/form/edit-sheet.tsx"
    }
  ],
  "docs": "Edits something in a form inside a dialog: the whole interaction, done right. Import: import { EditSheet } from \"@/components/ouro/form/edit-sheet\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: button, dialog, form, sheet, the helpers they import in lib/ouro. Needs ouro-base in your stylesheet: add that item once per app, from the same place as this one, if you have not. Docs: https://ui.ouroboros.bot/docs/edit-sheet.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}