{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"autosave-status","type":"registry:component","title":"Autosave status","description":"A dot for unsaved changes splits into three while saving, then gathers into a check.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/autosave-status.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\nimport { cn } from \"@/lib/utils\";\n\nexport type SaveState = \"saved\" | \"unsaved\" | \"saving\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst MOVE = { type: \"spring\", duration: 0.4, bounce: 0.1 } as const;\nconst PAUSE = 800; // ms of stillness before saving starts\nconst MINUTE = 60_000;\n\nconst CSS = `\n@keyframes as-pulse { 0%, 100% { opacity: .25 } 40% { opacity: 1 } }\n`;\n\n// Says how long ago, in the words a person would use, and only changes\n// when those words would.\nfunction savedLabel(savedAt: number | null, now: number) {\n  if (savedAt === null) return \"Saved\";\n  const ago = now - savedAt;\n  if (ago < 45_000) return \"Saved just now\";\n  if (ago < 60 * MINUTE)\n    return `Saved ${Math.max(1, Math.floor(ago / MINUTE))} min ago`;\n  return `Saved at ${new Date(savedAt).toLocaleTimeString([], { hour: \"numeric\", minute: \"2-digit\" })}`;\n}\n\n// The icon is one set of three dots throughout: a single dot means there\n// are changes, it splits into three that pulse while saving, and the three\n// gather back into the middle as the check draws.\nexport function AutosaveStatus({\n  state,\n  savedAt = null,\n  now = 0,\n  className,\n}: {\n  state: SaveState;\n  savedAt?: number | null;\n  now?: number;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const label =\n    state === \"saving\"\n      ? \"Saving\"\n      : state === \"unsaved\"\n        ? \"Unsaved changes\"\n        : savedLabel(savedAt, now);\n  const move = reduceMotion ? { duration: 0 } : MOVE;\n\n  return (\n    <div\n      className={cn(\n        // A fixed width, as wide as the longest thing it says, so the icon\n        // never shifts and old and new words cross in the same spot.\n        \"flex w-[8.75rem] shrink-0 items-center gap-2 text-[13px] whitespace-nowrap text-muted-foreground\",\n        className,\n      )}\n    >\n      <style>{CSS}</style>\n      <span aria-hidden className=\"relative grid size-4 shrink-0 place-items-center\">\n        {[-5, 0, 5].map((x, i) => {\n          const middle = i === 1;\n          return (\n            <motion.span\n              key={i}\n              className=\"absolute size-[4px]\"\n              initial={false}\n              animate={\n                state === \"saving\"\n                  ? { x, opacity: 1, scale: 1 }\n                  : state === \"unsaved\"\n                    ? { x: 0, opacity: middle ? 1 : 0, scale: middle ? 1.5 : 1 }\n                    : { x: 0, opacity: 0, scale: 0.5 }\n              }\n              transition={move}\n            >\n              <span\n                className=\"block size-full rounded-full bg-current\"\n                style={{\n                  animation:\n                    state === \"saving\" && !reduceMotion\n                      ? `as-pulse 1s ease-in-out ${i * 0.16}s infinite`\n                      : \"none\",\n                }}\n              />\n            </motion.span>\n          );\n        })}\n        <svg viewBox=\"0 0 16 16\" className=\"absolute size-4 text-foreground\" fill=\"none\">\n          <motion.path\n            d=\"M3.75 8.25l2.75 2.75 5.75-6\"\n            stroke=\"currentColor\"\n            strokeWidth={1.6}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            initial={false}\n            animate={\n              state === \"saved\"\n                ? { pathLength: 1, opacity: 1 }\n                : { pathLength: 0, opacity: 0 }\n            }\n            transition={\n              reduceMotion\n                ? { duration: 0 }\n                : state === \"saved\"\n                  ? { duration: 0.35, delay: 0.12, ease: EASE_OUT }\n                  : { duration: 0.12 }\n            }\n          />\n        </svg>\n      </span>\n      <span className=\"relative flex min-w-0 flex-1\">\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          <motion.span\n            key={label}\n            initial={{ opacity: 0, y: 3, filter: \"blur(3px)\" }}\n            animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n            exit={{ opacity: 0, y: -3, filter: \"blur(3px)\", transition: { duration: 0.12 } }}\n            transition={reduceMotion ? { duration: 0 } : { duration: 0.22, ease: EASE_OUT }}\n          >\n            {label}\n          </motion.span>\n        </AnimatePresence>\n      </span>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {state === \"saved\" && savedAt !== null ? \"All changes saved\" : \"\"}\n      </span>\n    </div>\n  );\n}\n\nconst TITLE = \"Trip notes\";\nconst BODY =\n  \"Pack light this time. Two shirts, the grey jacket, and the charger that actually works.\";\nconst TYPED = \" Leave by seven.\";\n\nexport default function AutosaveStatusDemo() {\n  const play = usePreviewPlay();\n  const [title, setTitle] = useState(TITLE);\n  const [body, setBody] = useState(BODY);\n  const [state, setState] = useState<SaveState>(\"saved\");\n  const [savedAt, setSavedAt] = useState<number | null>(null);\n  const [now, setNow] = useState(0);\n  const pause = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const saving = useRef<ReturnType<typeof setTimeout>>(undefined);\n\n  // Every edit resets the clock; the save starts once typing pauses, and a\n  // new keystroke mid-save goes back to waiting.\n  const edited = () => {\n    clearTimeout(pause.current);\n    clearTimeout(saving.current);\n    setState(\"unsaved\");\n    pause.current = setTimeout(() => {\n      setState(\"saving\");\n      // Stands in for the request, which never takes the same time twice.\n      saving.current = setTimeout(\n        () => {\n          const t = Date.now();\n          setSavedAt(t);\n          setNow(t);\n          setState(\"saved\");\n        },\n        650 + Math.random() * 350,\n      );\n    }, PAUSE);\n  };\n  const editedRef = useRef(edited);\n  useEffect(() => {\n    editedRef.current = edited;\n  });\n\n  useEffect(\n    () => () => {\n      clearTimeout(pause.current);\n      clearTimeout(saving.current);\n    },\n    [],\n  );\n\n  // \"Saved just now\" ages on its own, checked twice a minute; idle cards\n  // never start the clock.\n  useEffect(() => {\n    if (state !== \"saved\" || savedAt === null || play === false) return;\n    const id = setInterval(() => setNow(Date.now()), 30_000);\n    return () => clearInterval(id);\n  }, [state, savedAt, play]);\n\n  // The card's hover show: someone adds a line, pauses, it saves; then they\n  // take it back out, and it saves again.\n  useEffect(() => {\n    if (play !== true) return;\n    const timers: ReturnType<typeof setTimeout>[] = [];\n    const at = (ms: number, fn: () => void) => timers.push(setTimeout(fn, ms));\n    const run = () => {\n      let t = 300;\n      for (let i = 1; i <= TYPED.length; i++, t += 55) {\n        const next = BODY + TYPED.slice(0, i);\n        at(t, () => {\n          setBody(next);\n          editedRef.current();\n        });\n      }\n      t += 3200;\n      for (let i = TYPED.length - 1; i >= 0; i--, t += 28) {\n        const next = BODY + TYPED.slice(0, i);\n        at(t, () => {\n          setBody(next);\n          editedRef.current();\n        });\n      }\n      at(t + 3200, run);\n    };\n    run();\n    return () => {\n      timers.forEach(clearTimeout);\n      clearTimeout(pause.current);\n      clearTimeout(saving.current);\n      setBody(BODY);\n      setState(\"saved\");\n      setSavedAt(null);\n    };\n  }, [play]);\n\n  return (\n    <div className=\"@container w-[min(440px,100%)] rounded-2xl bg-background p-6 shadow-raised\">\n      {/* Side by side when there's room; on a narrow card the status sits\n          above the title so the title keeps its full width. */}\n      <div className=\"flex flex-col-reverse items-start gap-1.5 @min-[360px]:flex-row @min-[360px]:items-center @min-[360px]:justify-between @min-[360px]:gap-4\">\n        <input\n          aria-label=\"Title\"\n          value={title}\n          onChange={(e) => {\n            setTitle(e.target.value);\n            edited();\n          }}\n          placeholder=\"Untitled\"\n          className=\"w-full min-w-0 flex-1 bg-transparent text-[18px] font-semibold tracking-tight text-foreground outline-hidden placeholder:text-muted-foreground\"\n        />\n        <AutosaveStatus state={state} savedAt={savedAt} now={now} />\n      </div>\n      <textarea\n        aria-label=\"Note\"\n        value={body}\n        onChange={(e) => {\n          setBody(e.target.value);\n          edited();\n        }}\n        rows={4}\n        placeholder=\"Start writing\"\n        // 16px on phones: iOS zooms into any smaller field it focuses.\n        className=\"mt-3 block w-full resize-none bg-transparent text-base leading-relaxed text-foreground/80 outline-hidden placeholder:text-muted-foreground sm:text-[15px]\"\n      />\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["feedback"],"docs":"From ui lab: https://lab.xevrion.dev/lab/autosave-status"}