{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"promise-toast","type":"registry:component","title":"Promise toast","description":"One toast that morphs from saving to saved, or to an error with retry.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/promise-toast.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, animate, motion, useMotionValue } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\ntype Status = \"idle\" | \"loading\" | \"success\" | \"error\";\ntype Messages = { loading: string; success: string; error: string };\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n// The width follows the text with no bounce: a pill that overshoots would\n// look like it measured wrong.\nconst MORPH = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\nconst INSTANT = { duration: 0 };\n\nexport function PromiseToast({\n  action,\n  children,\n  messages = { loading: \"Saving…\", success: \"Saved\", error: \"Couldn't save\" },\n  // Enough to read one word. Errors wait longer because they ask for a\n  // decision, and hovering or focusing the toast holds either one open.\n  successDuration = 2000,\n  errorDuration = 6000,\n  className,\n}: {\n  action: (signal: AbortSignal) => Promise<unknown>;\n  children: React.ReactNode;\n  messages?: Messages;\n  successDuration?: number;\n  errorDuration?: number;\n  className?: string;\n}) {\n  const [status, setStatus] = useState<Status>(\"idle\");\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const controller = useRef<AbortController>(undefined);\n  const dismiss = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const held = useRef(false);\n\n  useEffect(\n    () => () => {\n      controller.current?.abort();\n      clearTimeout(dismiss.current);\n    },\n    [],\n  );\n\n  const schedule = (next: Status) => {\n    clearTimeout(dismiss.current);\n    if (held.current || (next !== \"success\" && next !== \"error\")) return;\n    dismiss.current = setTimeout(\n      () => setStatus(\"idle\"),\n      next === \"success\" ? successDuration : errorDuration,\n    );\n  };\n\n  // Replace, never stack: every click saves the same thing, so a newer save\n  // makes the older result meaningless. The one toast morphs back to loading\n  // in place instead of piling up stale outcomes.\n  const run = async () => {\n    controller.current?.abort();\n    const current = new AbortController();\n    controller.current = current;\n    clearTimeout(dismiss.current);\n    setStatus(\"loading\");\n    let next: Status;\n    try {\n      await action(current.signal);\n      next = \"success\";\n    } catch {\n      next = \"error\";\n    }\n    if (current.signal.aborted) return;\n    setStatus(next);\n    schedule(next);\n  };\n\n  const hold = (on: boolean) => {\n    held.current = on;\n    if (on) clearTimeout(dismiss.current);\n    else schedule(status);\n  };\n\n  const loading = status === \"loading\";\n\n  return (\n    <div className={cn(\"flex flex-col items-center gap-4\", className)}>\n      <button\n        ref={triggerRef}\n        type=\"button\"\n        // aria-disabled keeps focus on the button while a save is in flight;\n        // a second press there would only race the first.\n        aria-disabled={loading}\n        onClick={() => !loading && run()}\n        className={cn(\n          \"h-10 touch-manipulation rounded-full bg-foreground px-4 text-sm font-medium text-background outline-hidden transition-[scale,opacity] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[opacity]\",\n          loading && \"cursor-progress opacity-60 active:scale-100\",\n        )}\n      >\n        {children}\n      </button>\n\n      {/* A fixed 44px slot, so the toast coming and going never moves the\n          button above it. */}\n      <div className=\"flex h-11 items-start justify-center\">\n        <AnimatePresence initial={false}>\n          {status !== \"idle\" && (\n            <Toast\n              status={status}\n              messages={messages}\n              onRetry={() => {\n                // Retry unmounts itself, so hand focus to the trigger first\n                // instead of dropping it on the page.\n                triggerRef.current?.focus();\n                held.current = false;\n                run();\n              }}\n              onHold={hold}\n            />\n          )}\n        </AnimatePresence>\n      </div>\n\n      <span className=\"sr-only\" role=\"status\">\n        {status === \"idle\" ? \"\" : messages[status]}\n      </span>\n    </div>\n  );\n}\n\nfunction Toast({\n  status,\n  messages,\n  onRetry,\n  onHold,\n}: {\n  status: Exclude<Status, \"idle\">;\n  messages: Messages;\n  onRetry: () => void;\n  onHold: (on: boolean) => void;\n}) {\n  const reduceMotion = useReducedMotion();\n  const contentRef = useRef<HTMLDivElement>(null);\n  const width = useMotionValue<number | \"auto\">(\"auto\");\n\n  // The pill animates its real width to whatever the incoming content\n  // measures, rather than scaling, so the text inside never stretches.\n  useLayoutEffect(() => {\n    const el = contentRef.current;\n    if (!el) return;\n    let first = true;\n    const observer = new ResizeObserver(() => {\n      const next = el.offsetWidth;\n      if (first || reduceMotion) width.jump(next);\n      else animate(width, next, MORPH);\n      first = false;\n    });\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [width, reduceMotion]);\n\n  return (\n    <motion.div\n      // Drops out of the button above it and returns there on the way out.\n      initial={{ opacity: 0, y: reduceMotion ? 0 : -6, scale: reduceMotion ? 1 : 0.97 }}\n      animate={{ opacity: 1, y: 0, scale: 1 }}\n      exit={{\n        opacity: 0,\n        y: reduceMotion ? 0 : -4,\n        scale: reduceMotion ? 1 : 0.98,\n        transition: { duration: 0.15, ease: EASE_OUT },\n      }}\n      transition={{ duration: 0.25, ease: EASE_OUT }}\n      style={{ width }}\n      className=\"relative h-11 origin-top overflow-hidden rounded-full bg-background text-sm text-foreground shadow-raised\"\n      onPointerEnter={(e) => e.pointerType !== \"touch\" && onHold(true)}\n      onPointerLeave={(e) => e.pointerType !== \"touch\" && onHold(false)}\n      onFocus={() => onHold(true)}\n      onBlur={(e) => {\n        if (!e.currentTarget.contains(e.relatedTarget)) onHold(false);\n      }}\n    >\n      {/* w-max lets this report the incoming content's natural width; the\n          outgoing copy is popped out of flow so it never counts. */}\n      <div ref={contentRef} className=\"relative flex h-full w-max\">\n        <AnimatePresence mode=\"popLayout\" initial={false}>\n          <motion.div\n            key={status}\n            initial={{ opacity: 0, filter: \"blur(4px)\", y: reduceMotion ? 0 : 4 }}\n            animate={{ opacity: 1, filter: \"blur(0px)\", y: 0 }}\n            exit={{\n              opacity: 0,\n              filter: \"blur(4px)\",\n              y: reduceMotion ? 0 : -4,\n              transition: { duration: 0.12, ease: EASE_OUT },\n            }}\n            transition={{ duration: 0.25, ease: EASE_OUT }}\n            className={cn(\n              \"flex h-full items-center gap-2 pl-3.5 whitespace-nowrap\",\n              // 6px around the 32px Retry keeps the radii concentric: 22 = 16 + 6.\n              status === \"error\" ? \"pr-1.5\" : \"pr-4\",\n            )}\n          >\n            <motion.span\n              aria-hidden\n              className={cn(\"grid size-4 place-items-center\", status === \"error\" && \"text-destructive\")}\n              initial={reduceMotion ? { opacity: 0 } : { opacity: 0, scale: 0.25, filter: \"blur(4px)\" }}\n              animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n              transition={reduceMotion ? INSTANT : ICON_SWAP}\n            >\n              <StatusIcon status={status} />\n            </motion.span>\n            <span aria-hidden className=\"font-medium\">\n              {messages[status]}\n            </span>\n            {status === \"error\" && (\n              <button\n                type=\"button\"\n                onClick={onRetry}\n                className=\"ml-2 h-8 touch-manipulation rounded-full bg-muted px-3 text-sm font-medium text-foreground outline-hidden transition-[scale,background-color] duration-150 ease-out select-none hover:bg-border focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[background-color]\"\n              >\n                Retry\n              </button>\n            )}\n          </motion.div>\n        </AnimatePresence>\n      </div>\n    </motion.div>\n  );\n}\n\nfunction StatusIcon({ status }: { status: Exclude<Status, \"idle\"> }) {\n  const props = {\n    viewBox: \"0 0 16 16\",\n    className: \"size-4\",\n    fill: \"none\",\n    stroke: \"currentColor\",\n    strokeWidth: 1.5,\n    strokeLinecap: \"round\" as const,\n    strokeLinejoin: \"round\" as const,\n  };\n  if (status === \"loading\")\n    return (\n      // Spins fast on purpose: a quicker spinner makes the same wait feel\n      // shorter. Reduced motion slows it rather than freezing the only\n      // sign that work is happening.\n      <svg\n        {...props}\n        className=\"size-4 animate-[spin_700ms_linear_infinite] motion-reduce:animate-[spin_1.6s_linear_infinite]\"\n      >\n        <circle cx=\"8\" cy=\"8\" r=\"6\" opacity={0.2} />\n        <path d=\"M8 2a6 6 0 0 1 6 6\" />\n      </svg>\n    );\n  if (status === \"success\")\n    return (\n      <svg {...props}>\n        <path d=\"m3.5 8.5 3 3 6-7\" />\n      </svg>\n    );\n  return (\n    <svg {...props}>\n      <circle cx=\"8\" cy=\"8\" r=\"6.25\" />\n      <path d=\"M8 5v3.25\" />\n      <path d=\"M8 10.75h.01\" strokeWidth={2} />\n    </svg>\n  );\n}\n\n// How long the fake request takes: long enough to see the loading state\n// settle, short enough not to feel broken.\nconst FAKE_LATENCY = 1400;\n\nexport default function PromiseToastDemo() {\n  const attempt = useRef(0);\n\n  // Alternates so both outcomes show up, success first. A Retry after a\n  // failure is the next attempt, so it succeeds.\n  const save = (signal: AbortSignal) =>\n    new Promise<void>((resolve, reject) => {\n      const fail = attempt.current++ % 2 === 1;\n      const timer = setTimeout(() => (fail ? reject() : resolve()), FAKE_LATENCY);\n      signal.addEventListener(\"abort\", () => clearTimeout(timer), { once: true });\n    });\n\n  return <PromiseToast action={save}>Save changes</PromiseToast>;\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"}],"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/promise-toast"}