{
  "name": "save-status",
  "type": "registry:component",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "files": [
    {
      "type": "registry:component",
      "content": "\"use client\";\n\n/**\n * @author: @kokonutui\n * @description: Save Status\n * @version: 1.0.0\n * @date: 2026-11-08\n * @license: MIT\n * @website: https://kokonutui.com\n * @github: https://github.com/kokonut-labs/kokonutui\n */\n\nimport { CloudOff, FileText, Wifi, WifiOff } from \"lucide-react\";\nimport { AnimatePresence, MotionConfig, motion } from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  type ReactNode,\n  useEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface SaveStatusProps {\n  title?: string;\n  defaultText?: string;\n  /** Pause after typing before a save starts, in ms. */\n  idleMs?: number;\n  /** Stand-in for your save call: resolve when the server has it. */\n  onSave?: (text: string) => Promise<void>;\n  className?: string;\n}\n\ntype State =\n  | { kind: \"saved\"; at: number; fresh: boolean }\n  | { kind: \"editing\" }\n  | { kind: \"saving\" }\n  | { kind: \"offline\"; queued: number }\n  | { kind: \"syncing\"; left: number };\n\nconst DEMO_TEXT =\n  \"Launch is Thursday at 10:00. Marketing sends the email first, then we flip the pricing page. Keep the old plans live for a week.\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst FRESH_MS = 1600;\nconst WORD = /\\S+/g;\n\nconst wait = (ms: number) =>\n  new Promise<void>((resolve) => window.setTimeout(resolve, ms));\n\nconst ago = (at: number, now: number) => {\n  const s = Math.max(0, Math.round((now - at) / 1000));\n  if (s < 10) {\n    return \"just now\";\n  }\n  if (s < 60) {\n    return `${Math.floor(s / 5) * 5}s ago`;\n  }\n  return `${Math.floor(s / 60)}m ago`;\n};\n\nexport default function SaveStatus({\n  title = \"Launch notes\",\n  defaultText = DEMO_TEXT,\n  idleMs = 700,\n  onSave = () => wait(650),\n  className,\n}: SaveStatusProps) {\n  const [text, setText] = useState(defaultText);\n  const [online, setOnline] = useState(true);\n  const [state, setState] = useState<State>({\n    kind: \"saved\",\n    at: 0,\n    fresh: false,\n  });\n  const [now, setNow] = useState(0);\n  const idle = useRef<number>(undefined);\n  const settle = useRef<number>(undefined);\n  const onlineRef = useRef(online);\n  onlineRef.current = online;\n  const textRef = useRef(text);\n  textRef.current = text;\n\n  // Start the clock after mount, so the server and client agree.\n  useEffect(() => {\n    const start = Date.now();\n    setNow(start);\n    setState((s) =>\n      s.kind === \"saved\" && s.at === 0 ? { ...s, at: start } : s\n    );\n    const id = window.setInterval(() => setNow(Date.now()), 5000);\n    return () => {\n      window.clearInterval(id);\n      window.clearTimeout(idle.current);\n      window.clearTimeout(settle.current);\n    };\n  }, []);\n\n  const save = async () => {\n    window.clearTimeout(idle.current);\n    setState({ kind: \"saving\" });\n    await onSave(textRef.current);\n    const at = Date.now();\n    setNow(at);\n    // Saved shows in green for a moment, then settles into a quiet timestamp.\n    setState({ kind: \"saved\", at, fresh: true });\n    window.clearTimeout(settle.current);\n    settle.current = window.setTimeout(() => {\n      setState((s) => (s.kind === \"saved\" ? { ...s, fresh: false } : s));\n    }, FRESH_MS);\n  };\n\n  const queue = () =>\n    // Each pause in typing is one change waiting to go up.\n    setState((s) => ({\n      kind: \"offline\",\n      queued: (s.kind === \"offline\" ? s.queued : 0) + 1,\n    }));\n\n  const onType = (value: string) => {\n    setText(value);\n    setState((s) => (s.kind === \"offline\" ? s : { kind: \"editing\" }));\n    window.clearTimeout(idle.current);\n    idle.current = window.setTimeout(() => {\n      if (onlineRef.current) {\n        save();\n      } else {\n        queue();\n      }\n    }, idleMs);\n  };\n\n  // Cmd/Ctrl+S saves now instead of waiting for the pause.\n  const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n    if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === \"s\") {\n      event.preventDefault();\n      if (onlineRef.current && state.kind === \"editing\") {\n        save();\n      }\n    }\n  };\n\n  const sync = async (count: number) => {\n    for (let left = count; left > 0; left--) {\n      setState({ kind: \"syncing\", left });\n      await wait(380);\n    }\n    await save();\n  };\n\n  const toggle = () => {\n    const next = !online;\n    setOnline(next);\n    window.clearTimeout(idle.current);\n    if (next) {\n      const queued = state.kind === \"offline\" ? state.queued : 0;\n      if (queued > 0) {\n        sync(queued);\n      } else {\n        setState({ kind: \"saved\", at: Date.now(), fresh: false });\n      }\n    } else {\n      setState({ kind: \"offline\", queued: 0 });\n    }\n  };\n\n  const words = text.match(WORD)?.length ?? 0;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        className={cn(\n          \"w-full max-w-md overflow-hidden rounded-[24px] border border-zinc-200 bg-white text-zinc-900 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100\",\n          className\n        )}\n      >\n        <div className=\"flex h-14 items-center gap-2 border-zinc-200 border-b px-4 dark:border-zinc-800\">\n          <FileText\n            aria-hidden=\"true\"\n            className=\"size-4 shrink-0 text-zinc-400 dark:text-zinc-500\"\n          />\n          <span className=\"min-w-0 truncate font-medium text-[14px]\">\n            {title}\n          </span>\n          <div className=\"ml-auto flex items-center gap-1.5\">\n            <Pill now={now} state={state} />\n            <button\n              aria-label={online ? \"Go offline\" : \"Go online\"}\n              aria-pressed={!online}\n              className={cn(\n                \"flex size-8 items-center justify-center rounded-full outline-hidden transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-zinc-400/50\",\n                online\n                  ? \"text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 active:bg-zinc-200 dark:text-zinc-400 dark:active:bg-zinc-800 dark:hover:bg-zinc-900 dark:hover:text-zinc-100\"\n                  : \"bg-orange-500/10 text-orange-600 dark:text-orange-400\"\n              )}\n              onClick={toggle}\n              title={online ? \"Go offline\" : \"Go online\"}\n              type=\"button\"\n            >\n              <AnimatePresence initial={false} mode=\"popLayout\">\n                <motion.span\n                  animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n                  exit={{ opacity: 0, scale: 0.8, filter: \"blur(2px)\" }}\n                  initial={{ opacity: 0, scale: 0.8, filter: \"blur(2px)\" }}\n                  key={online ? \"on\" : \"off\"}\n                  transition={{ duration: 0.18, ease: EASE_OUT }}\n                >\n                  {online ? (\n                    <Wifi aria-hidden=\"true\" className=\"size-4\" />\n                  ) : (\n                    <WifiOff aria-hidden=\"true\" className=\"size-4\" />\n                  )}\n                </motion.span>\n              </AnimatePresence>\n            </button>\n          </div>\n        </div>\n\n        <textarea\n          aria-label={title}\n          className=\"block h-36 w-full resize-none bg-transparent px-4 py-3 text-[16px] leading-relaxed outline-hidden placeholder:text-zinc-400 sm:text-[15px]\"\n          onChange={(event) => onType(event.target.value)}\n          onKeyDown={onKeyDown}\n          placeholder=\"Start typing…\"\n          value={text}\n        />\n\n        <div className=\"relative h-10 overflow-hidden border-zinc-100 border-t text-[12px] dark:border-zinc-900\">\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            {online ? (\n              <motion.div\n                animate={{ opacity: 1, y: 0 }}\n                className=\"flex h-10 items-center justify-between px-4 text-zinc-500 dark:text-zinc-400\"\n                exit={{ opacity: 0, y: -8 }}\n                initial={{ opacity: 0, y: 8 }}\n                key=\"words\"\n                transition={{ duration: 0.2, ease: EASE_OUT }}\n              >\n                <span className=\"flex items-center gap-1 tabular-nums\">\n                  <Roll value={words} /> words\n                </span>\n                <span className=\"flex items-center gap-1.5\">\n                  <Kbd>{\"⌘\"}</Kbd>\n                  <Kbd>S</Kbd>\n                  <span>save now</span>\n                </span>\n              </motion.div>\n            ) : (\n              <motion.div\n                animate={{ opacity: 1, y: 0 }}\n                className=\"flex h-10 items-center gap-2 bg-orange-500/[0.07] px-4 text-orange-700 dark:text-orange-300\"\n                exit={{ opacity: 0, y: -8 }}\n                initial={{ opacity: 0, y: 8 }}\n                key=\"offline\"\n                transition={{ duration: 0.2, ease: EASE_OUT }}\n              >\n                <CloudOff aria-hidden=\"true\" className=\"size-3.5 shrink-0\" />\n                Changes stay on this device until you're back online.\n              </motion.div>\n            )}\n          </AnimatePresence>\n        </div>\n      </div>\n    </MotionConfig>\n  );\n}\n\nfunction Kbd({ children }: { children: ReactNode }) {\n  return (\n    <kbd className=\"flex h-5 min-w-5 items-center justify-center rounded-md border border-zinc-200 bg-zinc-50 px-1 font-sans text-[11px] text-zinc-500 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-400\">\n      {children}\n    </kbd>\n  );\n}\n\nconst NEUTRAL = \"bg-zinc-100 text-zinc-600 dark:bg-zinc-900 dark:text-zinc-400\";\n\nfunction pillLook(state: State, now: number) {\n  switch (state.kind) {\n    case \"saved\":\n      return {\n        key: state.fresh ? \"fresh\" : \"saved\",\n        tone: state.fresh\n          ? \"bg-emerald-500/10 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300\"\n          : NEUTRAL,\n        icon: <DrawnCheck />,\n        label: state.fresh ? \"Saved\" : `Saved ${ago(state.at, now)}`,\n      };\n    case \"saving\":\n      return {\n        key: \"saving\",\n        tone: \"bg-sky-500/10 text-sky-700 dark:bg-sky-500/15 dark:text-sky-300\",\n        icon: <Spinner />,\n        label: \"Saving\",\n      };\n    case \"offline\":\n      return {\n        key: \"offline\",\n        tone: \"bg-orange-500/10 text-orange-700 dark:bg-orange-500/15 dark:text-orange-300\",\n        icon: <CloudOff aria-hidden=\"true\" className=\"size-3.5\" />,\n        label:\n          state.queued > 0 ? (\n            <>\n              <Roll value={state.queued} /> to sync\n            </>\n          ) : (\n            \"Offline\"\n          ),\n      };\n    case \"syncing\":\n      return {\n        key: \"syncing\",\n        tone: \"bg-sky-500/10 text-sky-700 dark:bg-sky-500/15 dark:text-sky-300\",\n        icon: <Spinner />,\n        label: (\n          <>\n            Syncing <Roll value={state.left} />\n          </>\n        ),\n      };\n    default:\n      return {\n        key: \"editing\",\n        tone: NEUTRAL,\n        icon: <span className=\"size-1.5 rounded-full bg-current opacity-70\" />,\n        label: \"Editing\",\n      };\n  }\n}\n\n/** One pill whose width follows its words, so every state change glides. */\nfunction Pill({ state, now }: { state: State; now: number }) {\n  const look = pillLook(state, now);\n  return (\n    <motion.div\n      aria-live=\"polite\"\n      className={cn(\n        \"flex h-8 items-center overflow-hidden px-3 font-medium text-[12.5px] transition-colors duration-300\",\n        look.tone\n      )}\n      layout\n      role=\"status\"\n      style={{ borderRadius: 999 }}\n      transition={{ type: \"spring\", stiffness: 500, damping: 40 }}\n    >\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        <motion.span\n          animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n          className=\"flex items-center gap-1.5 whitespace-nowrap tabular-nums\"\n          exit={{ opacity: 0, y: -8, filter: \"blur(2px)\" }}\n          initial={{ opacity: 0, y: 8, filter: \"blur(2px)\" }}\n          key={look.key}\n          layout=\"position\"\n          transition={{ duration: 0.2, ease: EASE_OUT }}\n        >\n          {look.icon}\n          {look.label}\n        </motion.span>\n      </AnimatePresence>\n    </motion.div>\n  );\n}\n\nfunction Spinner() {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      className=\"size-3.5 animate-spin\"\n      fill=\"none\"\n      viewBox=\"0 0 14 14\"\n    >\n      <circle\n        cx={7}\n        cy={7}\n        opacity={0.25}\n        r={5.5}\n        stroke=\"currentColor\"\n        strokeWidth={2}\n      />\n      <path\n        d=\"M7 1.5a5.5 5.5 0 0 1 5.5 5.5\"\n        stroke=\"currentColor\"\n        strokeLinecap=\"round\"\n        strokeWidth={2}\n      />\n    </svg>\n  );\n}\n\nfunction DrawnCheck() {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      className=\"size-3.5 text-emerald-500\"\n      fill=\"none\"\n      viewBox=\"0 0 14 14\"\n    >\n      <motion.path\n        animate={{ pathLength: 1 }}\n        d=\"M2.8 7.3l2.7 2.6 5.7-5.8\"\n        initial={{ pathLength: 0 }}\n        stroke=\"currentColor\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        strokeWidth={2}\n        transition={{ duration: 0.25, delay: 0.1, ease: EASE_OUT }}\n      />\n    </svg>\n  );\n}\n\n/** A number that rolls up when it grows and down when it shrinks. */\nfunction Roll({ value }: { value: number }) {\n  const previous = useRef(value);\n  const up = value >= previous.current;\n  useEffect(() => {\n    previous.current = value;\n  }, [value]);\n  return (\n    <span className=\"relative inline-flex overflow-hidden\">\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        <motion.span\n          animate={{ y: \"0%\", opacity: 1 }}\n          exit={{ y: up ? \"-70%\" : \"70%\", opacity: 0 }}\n          initial={{ y: up ? \"70%\" : \"-70%\", opacity: 0 }}\n          key={value}\n          transition={{ duration: 0.2, ease: EASE_OUT }}\n        >\n          {value}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n",
      "path": "/components/kokonutui/save-status.tsx",
      "target": "components/kokonutui/save-status.tsx"
    }
  ]
}