{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "inline-edit",
  "title": "Inline edit",
  "description": "Text that becomes a field in place to rename something, such as a title or a table cell, without moving. Quiet saves at once with a mark after the text; Actions keeps Save and Cancel in the field until the save is done.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core",
    "class-variance-authority"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/field.json",
    "https://kinoui.com/r/input.json",
    "https://kinoui.com/r/input-group.json",
    "https://kinoui.com/r/spinner.json",
    "https://kinoui.com/r/announce.json",
    "https://kinoui.com/r/controllable.json",
    "https://kinoui.com/r/notice.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/settle.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/theme.json",
    "https://kinoui.com/r/field-control.json",
    "https://kinoui.com/r/edit-in-place.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/inline-edit.tsx",
      "content": "'use client'\n\nimport { Field, FieldError } from '@/registry/components/kino/field'\nimport {\n  focusControl,\n  InputInvalidIcon,\n  inputBoxClassName,\n} from '@/registry/components/kino/input'\nimport {\n  InputGroupAddon,\n  InputGroupButton,\n  inputGroupPresence,\n} from '@/registry/components/kino/input-group'\nimport { useSpinner } from '@/registry/components/kino/spinner'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { announce } from '@/registry/lib/announce'\nimport { useControllable } from '@/registry/lib/controllable'\nimport { editInPlace, type EditInPlaceReason } from '@/registry/lib/edit-in-place'\nimport { useFieldProps } from '@/registry/lib/field-control'\nimport { noticeIcon } from '@/registry/lib/notice'\nimport { mergeRefs } from '@/registry/lib/refs'\nimport { settle } from '@/registry/lib/settle'\nimport { Swap, SwapText } from '@/registry/lib/swap'\nimport { type ChangeDetails, isComposing } from '@ui-sdk/core'\nimport { type PartProps, usePart, usePrimitive } from '@ui-sdk/react/primitive'\nimport { cva } from 'class-variance-authority'\nimport {\n  type KeyboardEvent,\n  type MouseEvent,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/**\n * How the edit reads and saves. `quiet`: plain text at rest, and a save that\n * shows at once, with a mark after the text. `actions`: a pencil at rest,\n * Save and Cancel in the field, which stays open until the save is done.\n */\ntype InlineEditVariant = 'quiet' | 'actions'\n\n/**\n * Where a save is: none running, running, just saved (Quiet's tick), failed\n * (Quiet's old text back), or done and waiting for Save's spinner to have\n * shown long enough (Actions).\n */\ntype InlineEditStatus = 'idle' | 'saving' | 'saved' | 'failed' | 'closing'\n\n/** What a commit does with the text in the field. */\ntype InlineEditOutcome =\n  | { kind: 'unchanged' }\n  | { kind: 'invalid'; message: string }\n  | { kind: 'save'; value: string }\n\n/*\n * One box that holds the text at rest and the field while editing, so the\n * text never moves: only the Input's border, ring and surface fade in around\n * it. At rest the box is quiet, with a tint under the pointer and with focus.\n */\nconst inlineEditBoxVariants = cva(\n  [\n    inputBoxClassName,\n    '[grid-area:control] not-data-editing:border-transparent not-data-editing:bg-transparent not-data-editing:shadow-none forced-colors:not-data-editing:border-[Canvas] dark:not-data-editing:bg-transparent',\n    'not-data-editing:not-data-disabled:hover:bg-muted dark:not-data-editing:not-data-disabled:hover:bg-muted/50',\n    'not-data-editing:has-focus-visible:border-ring not-data-editing:has-focus-visible:bg-muted dark:not-data-editing:has-focus-visible:bg-muted/50 data-disabled:opacity-50',\n  ],\n  {\n    variants: {\n      variant: {\n        quiet: '',\n        // While editing, the field ends where Save and Cancel begin: two small buttons, their gap and the space after them.\n        actions: 'data-editing:pe-[calc(var(--control-height-xs)*2+--spacing(2))]',\n      },\n    },\n    defaultVariants: { variant: 'quiet' },\n  },\n)\n\n/*\n * The text at rest and in the field share these, so they sit at the same\n * place to the pixel. Below the `md` breakpoint the text is at least 16px,\n * as in the Input, or iOS zooms the page when the field takes focus; above\n * it, the text is the size of what surrounds it, such as a heading.\n */\nconst textClassName =\n  'min-h-(--field-height) w-full min-w-0 px-(--control-padding) max-md:text-[max(1rem,1em)]'\n\n/*\n * Actions' pencil sits at the box's end, where Save and Cancel arrive. It\n * leaves as they arrive, and comes back as they finish going, so the two never\n * show in one place. At rest it shows under the pointer and with focus, and\n * always on a touch screen, which has no pointer to rest.\n */\nconst pencilPresenceClassName =\n  'pointer-events-none absolute inset-y-0 end-0 flex items-center pe-(--control-padding) transition-[opacity,scale] duration-(--motion-exit-duration) ease-(--motion-exit-easing) not-data-shown:opacity-0 data-shown:delay-[calc(var(--motion-exit-duration)*0.9)] data-shown:duration-(--motion-enter-duration) data-shown:ease-(--motion-enter-easing) motion-safe:not-data-shown:scale-95'\nconst pencilClassName =\n  'text-muted-foreground flex opacity-0 transition-opacity duration-(--motion-press-duration) ease-(--motion-press-easing) group-hover/input:opacity-100 group-has-focus-visible/input:opacity-100 pointer-coarse:opacity-100 [&_svg]:size-4'\n\n/*\n * Quiet's mark sits right after the text, where the text ends, and rolls out\n * while the field is open; the text is only as wide as it needs, and a press\n * on the rest of the box edits it too.\n */\nconst markClassName =\n  'flex shrink-0 items-center ps-1.5 pe-(--control-padding) group-data-editing/input:px-0 [&_svg]:size-4'\n\n/*\n * Save and Cancel arrive with the field and leave with it, scaling where\n * they are and turning back from where they are, as the Input group's parts\n * show and hide. They sit over the box's end, where the pencil is at rest.\n */\nconst actionsClassName = cn(\n  inputGroupPresence,\n  // They wait a fifth of the pencil's exit, as Swap's content does, so the two never read at once.\n  'pointer-events-none absolute inset-y-0 end-0 gap-0.5 data-shown:pointer-events-auto data-shown:delay-[calc(var(--motion-exit-duration)*0.2)]',\n)\n\n/*\n * Text that becomes a field in place to rename something. A press, Enter or\n * F2 edits it with the whole text picked; Enter or a press elsewhere saves,\n * and Escape puts it back. Quiet saves at once: a spinner follows the text\n * while the save runs and a tick once it has saved, and a save that fails\n * puts the old text back with the error under it, and editing again offers\n * the text that failed. Actions keeps the field open with Save's spinner\n * until the save is done, and a save that fails keeps it open with the error.\n */\nfunction InlineEdit({\n  variant = 'quiet',\n  value: valueProp,\n  defaultValue = '',\n  onValueChange,\n  validate,\n  editing: editingProp,\n  defaultEditing = false,\n  onEditingChange,\n  label,\n  placeholder,\n  editLabel = `Edit ${label}`,\n  disabled = false,\n  saveLabel = 'Save',\n  cancelLabel = 'Cancel',\n  savedLabel = 'Saved',\n  failedLabel = variant === 'quiet'\n    ? 'Couldn’t save. Edit it to try again.'\n    : 'Couldn’t save. Try again.',\n  className,\n  readOnly = false,\n  ref,\n  ...props\n}: Omit<\n  PartProps<'input'>,\n  | 'value'\n  | 'defaultValue'\n  | 'onChange'\n  | 'className'\n  | 'placeholder'\n  | 'disabled'\n  | 'aria-label'\n  | 'render'\n  | 'children'\n> & {\n  variant?: InlineEditVariant\n  value?: string\n  defaultValue?: string\n  /**\n   * Saves a new value, trimmed, with who asked for it in `details.source`. A\n   * promise shows the save running until it settles; a rejection or a throw\n   * shows `failedLabel` and keeps the old value.\n   */\n  onValueChange?: (value: string, details: ChangeDetails<EditInPlaceReason>) => unknown\n  /** The message to show for a value that can't be saved, or nothing for one that can. */\n  validate?: (value: string) => string | null | undefined\n  /** Whether the field shows, for a Rename item elsewhere that opens it. */\n  editing?: boolean\n  defaultEditing?: boolean\n  onEditingChange?: (editing: boolean) => void\n  /** What the value is, such as \"Project name\": the field's name, and part of the text's description. */\n  label: string\n  /** Shown, muted, in place of an empty value. */\n  placeholder?: string\n  /** What pressing the text does, read after the text itself. `Edit {label}` by default. */\n  editLabel?: string\n  disabled?: boolean\n  /** Actions' Save button. */\n  saveLabel?: string\n  /** Actions' Cancel button. */\n  cancelLabel?: string\n  /** What a screen reader hears once a save that took a moment has worked. */\n  savedLabel?: string\n  failedLabel?: string\n  /** For layout: the field and its box take their parent's width. */\n  className?: string\n}) {\n  const quiet = variant === 'quiet'\n  const [own, setOwn] = useState(defaultValue)\n  const value = valueProp ?? own\n  const [editing, setEditing] = useControllable(\n    editingProp,\n    defaultEditing,\n    onEditingChange,\n  )\n  const [error, setError] = useState<string | null>(null)\n  const [status, setStatus] = useState<InlineEditStatus>('idle')\n  // Quiet: the value being saved, shown in place of the old one until the save ends.\n  const [pending, setPending] = useState<string | null>(null)\n  // Quiet: the value whose save failed, which the field offers again.\n  const [failed, setFailed] = useState<string | null>(null)\n  const spinning = useSpinner(status === 'saving')\n  // The text on show: Quiet's value being saved, or the value. A commit is compared with it, so\n  // a field opened again during a save neither saves the same text twice nor drops the old one put back.\n  const shown = pending ?? value\n  const rootRef = useRef<HTMLDivElement>(null)\n  const buttonRef = useRef<HTMLButtonElement>(null)\n  const hintId = useId()\n  // Focus goes back to the text after Enter or Escape; after a press elsewhere it stays there.\n  const returnFocus = useRef(false)\n  const run = useRef(0)\n  // The save that is running and had to wait, for an agent's rename to wait on too.\n  const saving = useRef<Promise<void> | undefined>(undefined)\n\n  const wasEditing = useRef(editing)\n  // A field open from the first paint doesn't take focus, as nothing moves then; one that opens later does.\n  const openSinceMount = useRef(editing)\n  useLayoutEffect(() => {\n    if (editing === wasEditing.current) return\n    wasEditing.current = editing\n    openSinceMount.current = false\n    if (!editing && returnFocus.current) buttonRef.current?.focus()\n    returnFocus.current = false\n  }, [editing])\n\n  // Quiet's tick shows for a moment, then the text stands alone again.\n  useEffect(() => {\n    if (status !== 'saved') return\n    const timer = setTimeout(() => setStatus('idle'), 2000)\n    return () => clearTimeout(timer)\n  }, [status])\n\n  // A save that ends after the component has gone changes nothing.\n  useEffect(() => () => void (run.current += 1), [])\n\n  // Actions' field waits for its save; Quiet's can be edited again while one runs.\n  const waiting = !quiet && status !== 'idle'\n\n  const save = (next: string, details: ChangeDetails<EditInPlaceReason>) => {\n    const id = ++run.current\n    const own = valueProp === undefined\n    setStatus('saving')\n    if (quiet) setPending(next)\n    let done: (failure?: Error) => void = () => {}\n    saving.current = undefined\n    settle(\n      () => {\n        const result = onValueChange?.(next, details)\n        if (result instanceof Promise) {\n          const wait = new Promise<void>((resolve, reject) => {\n            done = (failure) => (failure ? reject(failure) : resolve())\n          })\n          // Only an agent's rename waits on it: a person's save that fails says so in the field.\n          wait.catch(() => {})\n          saving.current = wait\n        }\n        return result\n      },\n      (ok, waited) => {\n        done(ok ? undefined : new Error(failedLabel))\n        if (run.current !== id) return\n        setPending(null)\n        setStatus(settledStatus(variant, ok, waited))\n        if (ok) {\n          if (own) setOwn(next)\n          if (waited) announce(savedLabel)\n        } else {\n          // The error line reads out a new message only; the same failure\n          // again, from a second try, is said here.\n          if (error === failedLabel) announce(failedLabel)\n          setError(failedLabel)\n          if (quiet) setFailed(next)\n        }\n      },\n    )\n  }\n\n  /** What closing the field puts back, before a save that follows starts. */\n  const closing = (follow: boolean) => {\n    setError(null)\n    setFailed(null)\n    setStatus((now) => (now === 'failed' ? 'idle' : now))\n    returnFocus.current = follow\n  }\n\n  /** Whether a commit of `text` closes the field, saving it when it changed. */\n  const commit = (text: string, details: { reason: EditInPlaceReason }) => {\n    if (waiting) return false\n    const follow = details.reason !== 'focus-out'\n    const outcome = inlineEditOutcome(text, shown, validate)\n    if (outcome.kind === 'invalid') {\n      // A value that can't be saved is put back when focus leaves: a field\n      // left open without focus could no longer be closed with Escape.\n      if (!follow) {\n        closing(false)\n        return true\n      }\n      setError(outcome.message)\n      return false\n    }\n    if (outcome.kind === 'unchanged') {\n      closing(follow)\n      return true\n    }\n    // Quiet closes at once and shows the save beside the text; Actions keeps the field open until it's done.\n    if (quiet) closing(follow)\n    else setError(null)\n    edit.api.save(outcome.value, details)\n    return quiet\n  }\n\n  const edit = usePrimitive(editInPlace, {\n    value: shown,\n    onValueChange: save,\n    editing,\n    onEditingChange: setEditing,\n    opening: () => (quiet ? openingText(failed, pending, value) : value),\n    commit,\n    saving: () => saving.current,\n    busy: waiting,\n    openSinceMount: () => openSinceMount.current,\n    disabled,\n  })\n\n  // Actions: a save that worked closes the field once the spinner has shown long enough to read.\n  useEffect(() => {\n    if (status !== 'closing' || spinning) return\n    // eslint-disable-next-line react-hooks/set-state-in-effect -- the spinner's hold ends on a timer, and the field closes after it\n    setStatus('idle')\n    // Focus follows the field closing only when it is still inside: a\n    // person who moved on while the save ran keeps their place.\n    returnFocus.current = rootRef.current?.contains(document.activeElement) ?? false\n    edit.api.edit.cancel()\n  }, [status, spinning, edit])\n\n  const cancel = () => {\n    if (waiting) return\n    closing(true)\n    edit.api.cancel()\n  }\n\n  const mark = inlineEditMark(status, spinning)\n  // The Field's control, once it opens.\n  const field = useFieldProps(props)\n  const fieldRef = field.props.ref\n  const inputRefs = useMemo(() => mergeRefs(ref, fieldRef), [ref, fieldRef])\n\n  // Save keeps its spinner or its tick while it leaves with the field, so\n  // nothing in it changes on the way out.\n  const saveLoading = status === 'saving' || spinning\n  const [heldLoading, setHeldLoading] = useState(saveLoading)\n  if (editing && heldLoading !== saveLoading) setHeldLoading(saveLoading)\n\n  return (\n    <Field\n      ref={rootRef}\n      data-inline-edit=''\n      data-variant={variant}\n      invalid={error !== null}\n      className={cn('min-w-0', className)}\n    >\n      {usePart(\n        edit,\n        'root',\n        {},\n        {\n          'aria-label': label,\n          // Escape puts the text back from anywhere in the field, through `cancel`, which waits for a save Actions keeps open.\n          onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => {\n            if (\n              !editing ||\n              waiting ||\n              event.key !== 'Escape' ||\n              isComposing(event.nativeEvent)\n            )\n              return\n            closing(true)\n          },\n          // A press on the box beside the text, such as on the invalid mark, keeps the caret in the field.\n          onPointerDown: editing ? focusControl : undefined,\n          // At rest, a press on the box beside the text edits it, as a press on the text does.\n          onClick: (event: MouseEvent<HTMLDivElement>) => {\n            if (!editing && !buttonRef.current?.contains(event.target as Node)) {\n              edit.api.open('imperative', event.nativeEvent)\n            }\n          },\n          className: inlineEditBoxVariants({ variant }),\n          children: (\n            <>\n              {editing ? (\n                <>\n                  <InlineEditInput\n                    {...field.props}\n                    ref={inputRefs}\n                    aria-label={label}\n                    placeholder={placeholder}\n                    readOnly={readOnly || waiting}\n                    onChange={() => setError(null)}\n                    className={cn(\n                      textClassName,\n                      'bg-transparent placeholder:text-muted-foreground focus-visible:outline-hidden',\n                    )}\n                  />\n                  <InputInvalidIcon />\n                </>\n              ) : (\n                <InlineEditText\n                  ref={buttonRef}\n                  aria-describedby={hintId}\n                  aria-busy={status === 'saving' || undefined}\n                  disabled={disabled}\n                  className={cn(\n                    textClassName,\n                    'flex cursor-text items-center text-start focus-visible:outline-hidden disabled:cursor-default',\n                    // Quiet's text is as wide as it needs, with its mark after it;\n                    // Actions' leaves room at its end for the pencil.\n                    quiet\n                      ? 'w-auto flex-initial pe-0'\n                      : 'pe-[calc(var(--control-padding)*2+--spacing(4))]',\n                  )}\n                >\n                  <SwapText\n                    text={shown || placeholder || ''}\n                    className={cn(!shown && 'text-muted-foreground')}\n                  />\n                </InlineEditText>\n              )}\n              {quiet ? (\n                // Said by the status region and the description, not as part of the text's name.\n                <span aria-hidden className={markClassName}>\n                  <Swap roll>\n                    {mark && !editing ? noticeIcon(mark, undefined) : null}\n                  </Swap>\n                </span>\n              ) : (\n                <span\n                  aria-hidden\n                  data-shown={editing ? undefined : ''}\n                  className={pencilPresenceClassName}\n                >\n                  <span className={pencilClassName}>\n                    <IconPlaceholder\n                      lucide='PencilIcon'\n                      tabler='IconPencil'\n                      hugeicons='PencilEdit01Icon'\n                      phosphor='PencilSimpleIcon'\n                      remixicon='RiPencilLine'\n                      aria-hidden\n                    />\n                  </span>\n                </span>\n              )}\n              {quiet ? null : (\n                <InputGroupAddon\n                  align='inline-end'\n                  data-shown={editing ? '' : undefined}\n                  // At rest they are gone from the tab order and from screen readers, and fade out where they are.\n                  inert={!editing}\n                  className={actionsClassName}\n                  // The field keeps focus through a press on Save or Cancel, so\n                  // the press is never a press elsewhere, which saves.\n                  onMouseDown={(event) => event.preventDefault()}\n                >\n                  <InputGroupButton\n                    size='icon-xs'\n                    aria-label={cancelLabel}\n                    disabled={waiting}\n                    onClick={cancel}\n                  >\n                    <IconPlaceholder\n                      lucide='XIcon'\n                      tabler='IconX'\n                      hugeicons='Cancel01Icon'\n                      phosphor='XIcon'\n                      remixicon='RiCloseLine'\n                      aria-hidden\n                    />\n                  </InputGroupButton>\n                  <InputGroupButton\n                    size='icon-xs'\n                    aria-label={saveLabel}\n                    loading={editing ? saveLoading : heldLoading}\n                    onClick={(event) =>\n                      edit.api.edit.end('imperative', event.nativeEvent)\n                    }\n                  >\n                    <IconPlaceholder\n                      lucide='CheckIcon'\n                      tabler='IconCheck'\n                      hugeicons='Tick02Icon'\n                      phosphor='CheckIcon'\n                      remixicon='RiCheckLine'\n                      aria-hidden\n                    />\n                  </InputGroupButton>\n                </InputGroupAddon>\n              )}\n            </>\n          ),\n        },\n        'div',\n      )}\n      <FieldError>{error}</FieldError>\n      <span id={hintId} hidden>\n        {status === 'failed' ? `${editLabel}. ${failedLabel}` : editLabel}\n      </span>\n    </Field>\n  )\n}\n\n/** The field, filled and focused with its text picked as it opens. */\nfunction InlineEditInput(props: PartProps<'input'>) {\n  return usePart(editInPlace, 'input', {}, props, 'input')\n}\n\n/** The text at rest, a button that opens the field: a press, Enter or F2. */\nfunction InlineEditText(props: PartProps<'button'>) {\n  return usePart(editInPlace, 'text', {}, props, 'button')\n}\n\n/** What a commit of `draft` over `value` does: nothing, an error to show, or a save of the trimmed text. */\nfunction inlineEditOutcome(\n  draft: string,\n  value: string,\n  validate?: (value: string) => string | null | undefined,\n): InlineEditOutcome {\n  const next = draft.trim()\n  if (next === value) return { kind: 'unchanged' }\n  const message = validate?.(next)\n  if (message) return { kind: 'invalid', message }\n  return { kind: 'save', value: next }\n}\n\n/** The status once a save has ended, by whether it worked and whether it had to wait. */\nfunction settledStatus(\n  variant: InlineEditVariant,\n  ok: boolean,\n  waited: boolean,\n): InlineEditStatus {\n  if (variant === 'actions') return ok ? 'closing' : 'idle'\n  if (!ok) return 'failed'\n  return waited ? 'saved' : 'idle'\n}\n\n/** What Quiet's field opens with: the text that failed, then the text being saved, then the value. */\nfunction openingText(failed: string | null, pending: string | null, value: string) {\n  return failed ?? pending ?? value\n}\n\n/**\n * Quiet's mark after the text: the spinner while it shows (it holds a moment\n * after a save ends), then the tick or the error.\n */\nfunction inlineEditMark(\n  status: InlineEditStatus,\n  spinning: boolean,\n): 'loading' | 'success' | 'error' | null {\n  if (spinning) return 'loading'\n  if (status === 'saved') return 'success'\n  if (status === 'failed') return 'error'\n  return null\n}\n\nexport {\n  InlineEdit,\n  inlineEditBoxVariants,\n  inlineEditMark,\n  inlineEditOutcome,\n  openingText,\n  settledStatus,\n}\nexport type { InlineEditOutcome, InlineEditStatus, InlineEditVariant }\n",
      "type": "registry:component",
      "target": "@components/kino/inline-edit.tsx"
    }
  ],
  "type": "registry:component"
}