{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"back-to-top","type":"registry:component","title":"Back to top","description":"Fills its ring as you read, and when you press it the arrow lifts off while the page glides back up.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/back-to-top.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, animate, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// A gentle start that keeps moving to the end, like something taking off.\nconst LIFT = [0.4, 0, 0.6, 1] as const;\n\nexport function BackToTop({\n  target,\n  showAfter = 0.12,\n  jump,\n  className,\n}: {\n  // The element that scrolls; the page itself when left out.\n  target?: React.RefObject<HTMLElement | null>;\n  // How far through (0 to 1) before the button offers itself.\n  showAfter?: number;\n  // Changing this number sends the reader to the top, as a click would.\n  jump?: number;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const [visible, setVisible] = useState(false);\n  // Set once the arrow has lifted off: it stays gone while the page rises and\n  // the button fades, and only returns if the trip is cut short.\n  const [launched, setLaunched] = useState(false);\n  const ring = useRef<SVGCircleElement | null>(null);\n  // Kept outside the ring, which only exists while the button shows, so a\n  // freshly shown button starts at the right fill instead of empty.\n  const progress = useRef(0);\n  // True while heading up: the button stays to show the ring draining, and\n  // bows out only once you've arrived.\n  const returning = useRef(false);\n  const trip_ = useRef<ReturnType<typeof animate> | undefined>(undefined);\n  const setRing = (el: SVGCircleElement | null) => {\n    ring.current = el;\n    el?.style.setProperty(\"stroke-dashoffset\", String(1 - progress.current));\n  };\n\n  // The ring follows the scroll directly, a style write per frame at most,\n  // so reading never re-renders anything; only crossing the threshold does.\n  useEffect(() => {\n    const el = target?.current;\n    const scroller: HTMLElement | Window = el ?? window;\n    let frame = 0;\n    const read = () => {\n      frame = 0;\n      const top = el ? el.scrollTop : window.scrollY;\n      const room = el\n        ? el.scrollHeight - el.clientHeight\n        : document.documentElement.scrollHeight - innerHeight;\n      const p = room > 0 ? Math.min(1, Math.max(0, top / room)) : 0;\n      progress.current = p;\n      ring.current?.style.setProperty(\"stroke-dashoffset\", String(1 - p));\n      if (returning.current) {\n        if (p > 0) return;\n        returning.current = false;\n      }\n      setVisible(p > showAfter);\n      // Hidden again: the next time it shows, it brings its arrow.\n      if (p <= showAfter) setLaunched(false);\n    };\n    const onScroll = () => {\n      if (!frame) frame = requestAnimationFrame(read);\n    };\n    read();\n    scroller.addEventListener(\"scroll\", onScroll, { passive: true });\n    return () => {\n      scroller.removeEventListener(\"scroll\", onScroll);\n      cancelAnimationFrame(frame);\n    };\n  }, [target, showAfter]);\n\n  // Driven here rather than by the browser's smooth scroll, whose speed\n  // varies wildly: longer trips take a little longer, never more than 0.9s.\n  // Any wheel or touch on the way hands control straight back.\n  const go = () => {\n    const el = target?.current;\n    const read = () => (el ? el.scrollTop : window.scrollY);\n    const write = (v: number) => (el ?? window).scrollTo(0, v);\n    setLaunched(true);\n    trip_.current?.stop();\n    const from = read();\n    if (reduceMotion) return write(0);\n    returning.current = true;\n    const scroller: HTMLElement | Window = el ?? window;\n    const stop = () => {\n      trip_.current?.stop();\n      returning.current = false;\n      setLaunched(false);\n    };\n    scroller.addEventListener(\"wheel\", stop, { once: true, passive: true });\n    scroller.addEventListener(\"touchstart\", stop, {\n      once: true,\n      passive: true,\n    });\n    trip_.current = animate(from, 0, {\n      duration: Math.min(0.9, 0.45 + from / 4000),\n      ease: [0.65, 0, 0.35, 1],\n      onUpdate: write,\n      onComplete: () => {\n        scroller.removeEventListener(\"wheel\", stop);\n        scroller.removeEventListener(\"touchstart\", stop);\n      },\n    });\n  };\n  useEffect(() => () => trip_.current?.stop(), []);\n\n  const goRef = useRef(go);\n  useEffect(() => {\n    goRef.current = go;\n  });\n  const lastJump = useRef(jump);\n  useEffect(() => {\n    if (jump === lastJump.current) return;\n    lastJump.current = jump;\n    goRef.current();\n  }, [jump]);\n\n  return (\n    <AnimatePresence>\n      {visible && (\n        <motion.button\n          type=\"button\"\n          aria-label=\"Back to top\"\n          onClick={go}\n          initial={{ opacity: 0, scale: 0.85, filter: \"blur(4px)\" }}\n          animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n          exit={{\n            opacity: 0,\n            scale: 0.85,\n            filter: \"blur(4px)\",\n            transition: { duration: 0.15 },\n          }}\n          transition={\n            reduceMotion ? { duration: 0 } : { duration: 0.25, ease: EASE_OUT }\n          }\n          className={cn(\n            \"group/top relative grid size-11 place-items-center overflow-hidden rounded-full bg-background text-foreground shadow-raised outline-hidden transition-[scale] duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\",\n            className,\n          )}\n        >\n          {/* How far you've read, drawn around the edge. */}\n          <svg\n            viewBox=\"0 0 44 44\"\n            className=\"pointer-events-none absolute inset-0 size-full -rotate-90\"\n            fill=\"none\"\n            aria-hidden\n          >\n            <circle\n              cx=\"22\"\n              cy=\"22\"\n              r=\"20.5\"\n              strokeWidth=\"1.5\"\n              className=\"stroke-border\"\n            />\n            <circle\n              ref={setRing}\n              cx=\"22\"\n              cy=\"22\"\n              r=\"20.5\"\n              strokeWidth=\"1.5\"\n              strokeLinecap=\"round\"\n              pathLength={1}\n              strokeDasharray=\"1\"\n              strokeDashoffset=\"1\"\n              className=\"stroke-foreground\"\n            />\n          </svg>\n          <AnimatePresence initial={false}>\n            {!launched && (\n              <motion.svg\n                key=\"arrow\"\n                viewBox=\"0 0 16 16\"\n                fill=\"none\"\n                stroke=\"currentColor\"\n                strokeWidth={1.7}\n                strokeLinecap=\"round\"\n                strokeLinejoin=\"round\"\n                aria-hidden\n                initial={{ y: 10, opacity: 0, filter: \"blur(2px)\" }}\n                animate={{\n                  y: 0,\n                  opacity: 1,\n                  filter: \"blur(0px)\",\n                  transition: reduceMotion\n                    ? { duration: 0 }\n                    : { duration: 0.3, ease: EASE_OUT },\n                }}\n                // Lifts off the way you're about to go: eases away rather\n                // than snapping, softening as it leaves.\n                exit={{\n                  y: -20,\n                  opacity: 0,\n                  filter: \"blur(2px)\",\n                  transition: reduceMotion\n                    ? { duration: 0 }\n                    : { duration: 0.4, ease: LIFT },\n                }}\n                className=\"absolute size-4 transition-[translate] duration-150 ease-out group-hover/top:-translate-y-0.5\"\n              >\n                <path d=\"M8 12.5v-9M4 7l4-4 4 4\" />\n              </motion.svg>\n            )}\n          </AnimatePresence>\n        </motion.button>\n      )}\n    </AnimatePresence>\n  );\n}\n\nconst ESSAY = [\n  \"Most tools try to do everything. The ones I keep coming back to do one thing, and they do it the same way every time.\",\n  \"A good pencil doesn't ask what you want to draw. It gets out of the way, and the line comes out where your hand meant it to.\",\n  \"Software rarely works like that. Every release adds a setting, every setting adds a question, and after a while the tool is mostly questions.\",\n  \"The alternative isn't fewer features for their own sake. It's deciding what the thing is for, and letting that answer most of the questions before anyone has to ask them.\",\n  \"When a tool knows what it's for, the details start to line up. The button is where your thumb already is. The default is the choice you would have made.\",\n  \"None of this shows up in a feature list. It shows up as the absence of friction, which is hard to sell and easy to feel.\",\n  \"It also shows up in what doesn't happen. No dialog asking if you're sure, because the action can be undone. No empty state, because the first screen already has something in it.\",\n  \"Restraint like this is slow work. Adding is quick and feels like progress; taking away means knowing the thing well enough to see what it doesn't need.\",\n  \"That's why the simplest tools are so often the oldest. They've had time to lose everything that wasn't carrying weight.\",\n  \"So the next time something feels simple, look closer. Somebody probably spent a long time deciding what to leave out.\",\n];\n\nexport default function BackToTopDemo() {\n  const play = usePreviewPlay();\n  const scroller = useRef<HTMLDivElement>(null);\n  const [jump, setJump] = useState(0);\n\n  // The card's hover show: read about two thirds of the way down, pause,\n  // then head back up.\n  useEffect(() => {\n    const el = scroller.current;\n    if (play !== true || !el) return;\n    let timer: ReturnType<typeof setTimeout>;\n    let scroll: ReturnType<typeof animate> | undefined;\n    const loop = () => {\n      scroll = animate(\n        el.scrollTop,\n        (el.scrollHeight - el.clientHeight) * 0.7,\n        {\n          duration: 2.2,\n          ease: [0.45, 0, 0.55, 1],\n          onUpdate: (v) => (el.scrollTop = v),\n        },\n      );\n      timer = setTimeout(() => {\n        setJump((j) => j + 1);\n        timer = setTimeout(loop, 1900);\n      }, 3000);\n    };\n    timer = setTimeout(loop, 300);\n    return () => {\n      clearTimeout(timer);\n      scroll?.stop();\n      el.scrollTop = 0;\n    };\n  }, [play]);\n\n  return (\n    <div className=\"relative h-[440px] w-[min(400px,100%)] overflow-hidden rounded-[20px] bg-background shadow-raised\">\n      <div\n        ref={scroller}\n        tabIndex={0}\n        role=\"region\"\n        aria-label=\"Back to top article\"\n        className=\"h-full overflow-y-auto overscroll-contain px-7 pt-8 pb-20 [scrollbar-width:none] outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-foreground [&::-webkit-scrollbar]:hidden\"\n      >\n        <p className=\"text-[12px] text-muted-foreground\">Essay · 4 min read</p>\n        <h3 className=\"mt-2 text-[20px] leading-tight font-semibold tracking-tight text-balance text-foreground\">\n          Notes on doing one thing well\n        </h3>\n        <div className=\"mt-5 flex flex-col gap-4 text-[15px] leading-relaxed text-pretty text-foreground/80\">\n          {ESSAY.map((p) => (\n            <p key={p}>{p}</p>\n          ))}\n        </div>\n      </div>\n      {/* Text slips under the button instead of colliding with it. */}\n      <div className=\"pointer-events-none absolute inset-x-0 bottom-0 h-20 bg-gradient-to-t from-background to-transparent\" />\n      <div className=\"absolute right-4 bottom-4\">\n        <BackToTop target={scroller} jump={jump} />\n      </div>\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":["navigation"],"docs":"From ui lab: https://lab.xevrion.dev/lab/back-to-top"}