{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "form-autosave",
  "title": "Form Autosave",
  "description": "A useAutosave hook and a status indicator: debounced saves with a single request in flight, a queued follow-up for edits made while saving, retry on failure, and a polite Saving, Saved or Failed announcement.",
  "files": [
    {
      "path": "registry/tealmac/form-autosave.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport type AutosaveStatus = \"idle\" | \"pending\" | \"saving\" | \"saved\" | \"error\"\n\nexport interface UseAutosaveOptions<T> {\n  /** The current form value. Compared by JSON text, so keep it serialisable. */\n  value: T\n  /** Persist the value. Reject to enter the `error` state. */\n  onSave: (value: T) => void | Promise<void>\n  /** Wait this long after the last change. Default 800 ms. */\n  delay?: number\n  enabled?: boolean\n  /** Also save right away when the tab is hidden. Default true. */\n  saveOnHide?: boolean\n}\n\nexport interface UseAutosaveResult {\n  status: AutosaveStatus\n  /** When the last save finished. */\n  savedAt: Date | null\n  error: Error | null\n  /** Save now, skipping the delay. Resolves when no save is left to do. */\n  flush: () => Promise<void>\n  /** Try again after an error. */\n  retry: () => Promise<void>\n}\n\nconst snapshot = (v: unknown) => JSON.stringify(v)\n\n/**\n * Save when the value stops changing. Only one request runs at a time; edits\n * made during a save are saved once it ends, with the newest value. The value\n * present at mount counts as already saved.\n */\nexport function useAutosave<T>({\n  value,\n  onSave,\n  delay = 800,\n  enabled = true,\n  saveOnHide = true,\n}: UseAutosaveOptions<T>): UseAutosaveResult {\n  const [status, setStatus] = React.useState<AutosaveStatus>(\"idle\")\n  const [savedAt, setSavedAt] = React.useState<Date | null>(null)\n  const [error, setError] = React.useState<Error | null>(null)\n\n  const latest = React.useRef(value)\n  latest.current = value\n  const onSaveRef = React.useRef(onSave)\n  onSaveRef.current = onSave\n  const savedSnapshot = React.useRef(snapshot(value))\n  const inFlight = React.useRef<Promise<void> | null>(null)\n  const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n  const mounted = React.useRef(true)\n  React.useEffect(() => {\n    mounted.current = true\n    return () => {\n      mounted.current = false\n      if (timer.current) clearTimeout(timer.current)\n    }\n  }, [])\n\n  const run = React.useCallback((): Promise<void> => {\n    if (inFlight.current) return inFlight.current\n    const job = (async () => {\n      // Loop: edits made while saving are picked up by the next round.\n      while (snapshot(latest.current) !== savedSnapshot.current) {\n        const sent = latest.current\n        const sentSnapshot = snapshot(sent)\n        if (mounted.current) setStatus(\"saving\")\n        try {\n          await onSaveRef.current(sent)\n          savedSnapshot.current = sentSnapshot\n          if (mounted.current) {\n            setSavedAt(new Date())\n            setError(null)\n          }\n        } catch (e) {\n          if (mounted.current) {\n            setError(e instanceof Error ? e : new Error(String(e)))\n            setStatus(\"error\")\n          }\n          return\n        }\n      }\n      if (mounted.current) setStatus(\"saved\")\n    })().finally(() => {\n      inFlight.current = null\n    })\n    inFlight.current = job\n    return job\n  }, [])\n\n  const flush = React.useCallback(async () => {\n    if (timer.current) clearTimeout(timer.current)\n    timer.current = null\n    await run()\n  }, [run])\n\n  const encoded = snapshot(value)\n  React.useEffect(() => {\n    if (!enabled || encoded === savedSnapshot.current) return\n    if (!inFlight.current) setStatus(\"pending\")\n    if (timer.current) clearTimeout(timer.current)\n    timer.current = setTimeout(() => {\n      timer.current = null\n      void run()\n    }, delay)\n    return () => {\n      if (timer.current) clearTimeout(timer.current)\n    }\n  }, [encoded, enabled, delay, run])\n\n  React.useEffect(() => {\n    if (!enabled || !saveOnHide) return\n    const handler = () => {\n      if (document.visibilityState === \"hidden\") void flush()\n    }\n    document.addEventListener(\"visibilitychange\", handler)\n    return () => document.removeEventListener(\"visibilitychange\", handler)\n  }, [enabled, saveOnHide, flush])\n\n  return { status, savedAt, error, flush, retry: flush }\n}\n\nexport interface AutosaveIndicatorProps {\n  status: AutosaveStatus\n  savedAt?: Date | null\n  error?: Error | null\n  onRetry?: () => void\n  locale?: string\n  className?: string\n}\n\n/** \"Saving...\", \"Saved at 14:32\" or \"Could not save. Retry\". Always mounted so changes are announced. */\nexport function AutosaveIndicator({\n  status,\n  savedAt,\n  error,\n  onRetry,\n  locale,\n  className,\n}: AutosaveIndicatorProps) {\n  let text = \"\"\n  if (status === \"pending\") text = \"Unsaved changes\"\n  else if (status === \"saving\") text = \"Saving...\"\n  else if (status === \"saved\" && savedAt)\n    text = `Saved at ${savedAt.toLocaleTimeString(locale, { hour: \"2-digit\", minute: \"2-digit\" })}`\n  else if (status === \"error\")\n    text = `Could not save${error?.message ? `: ${error.message}` : \"\"}.`\n  return (\n    <span\n      data-status={status}\n      className={cn(\n        \"inline-flex min-h-5 items-center gap-2 text-xs\",\n        status === \"error\" ? \"text-destructive\" : \"text-muted-foreground\",\n        className\n      )}\n    >\n      <span\n        role={status === \"error\" ? \"alert\" : \"status\"}\n        aria-live={status === \"error\" ? \"assertive\" : \"polite\"}\n      >\n        {text}\n      </span>\n      {status === \"error\" && onRetry ? (\n        <button\n          type=\"button\"\n          onClick={onRetry}\n          className=\"underline underline-offset-4\"\n        >\n          Retry\n        </button>\n      ) : null}\n    </span>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}