{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"star-button","type":"registry:component","title":"Star button","description":"Spins once and throws off tiny sparks when starred, then rolls the count.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/star-button.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport {\n  animate,\n  AnimatePresence,\n  motion,\n  type AnimationPlaybackControls,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst STAR =\n  \"M12 3.2l2.63 5.33 5.88.86-4.26 4.15 1 5.86L12 16.63l-5.25 2.77 1-5.86-4.25-4.15 5.88-.86Z\";\n// One full turn that lands hard and eases in: longer than a UI transition\n// because it is a rare, once-per-repo moment that never blocks input.\nconst SPIN = { duration: 0.6, ease: EASE_OUT } as const;\n// A kick on the same spring as the lab's like button: up to ~1.2, one dip.\nconst POP = { type: \"spring\", stiffness: 500, damping: 20 } as const;\nconst POP_VELOCITY = 8;\nconst SPARKS = 8;\n// GitHub's own star yellow (Primer --button-star-iconColor). A raw colour on\n// purpose: it is the brand meaning of \"starred\", so it is data here.\nconst STAR_YELLOW = \"light-dark(#eac54f, #e3b341)\";\nconst SPARK = { duration: 0.42, ease: EASE_OUT } as const;\n\n// Fixed, so server and client agree; offset half a step so no spark lines\n// up with a star point and gets hidden behind it.\nconst SPARK_ANGLES = Array.from(\n  { length: SPARKS },\n  (_, i) => (i * 360) / SPARKS + 360 / SPARKS / 2,\n);\n\n// Locale independent, so the server and the browser print the same thing.\nfunction group(n: number) {\n  return String(n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n\nexport function StarButton({\n  starred,\n  count,\n  onStarredChange,\n  className,\n}: {\n  starred: boolean;\n  count: number;\n  onStarredChange: (starred: boolean) => void;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const glyph = useRef<HTMLSpanElement>(null);\n  const spin = useRef<AnimationPlaybackControls>(undefined);\n  const pop = useRef<AnimationPlaybackControls>(undefined);\n  const [burst, setBurst] = useState(0);\n  const [note, setNote] = useState(\"\");\n  const rulerA = useRef<HTMLSpanElement>(null);\n  const rulerB = useRef<HTMLSpanElement>(null);\n  const [widths, setWidths] = useState<[number, number] | null>(null);\n\n  useLayoutEffect(() => {\n    const measure = () => {\n      if (!rulerA.current || !rulerB.current) return;\n      setWidths([rulerA.current.offsetWidth, rulerB.current.offsetWidth]);\n    };\n    measure();\n    // Web fonts can land after the first measure and change both widths.\n    let live = true;\n    document.fonts?.ready.then(() => live && measure());\n    return () => {\n      live = false;\n    };\n  }, []);\n\n  useEffect(\n    () => () => {\n      spin.current?.stop();\n      pop.current?.stop();\n    },\n    [],\n  );\n\n  // The celebration follows the prop rather than the click, so a parent\n  // that stars on your behalf (or refuses to) still gets it right.\n  const [prevStarred, setPrevStarred] = useState(starred);\n  if (prevStarred !== starred) {\n    setPrevStarred(starred);\n    if (starred && !reduceMotion) setBurst((b) => b + 1);\n  }\n  const lastStarred = useRef(starred);\n  useEffect(() => {\n    const was = lastStarred.current;\n    lastStarred.current = starred;\n    // Unstarring stays quiet: a spin already running finishes on its own,\n    // and the fill just drains.\n    if (!starred || was || reduceMotion || !glyph.current) return;\n    spin.current?.stop();\n    spin.current = animate(glyph.current, { rotate: [0, 360] }, SPIN);\n    pop.current?.stop();\n    pop.current = animate(\n      glyph.current,\n      { scale: 1 },\n      { ...POP, velocity: POP_VELOCITY },\n    );\n  }, [starred, reduceMotion]);\n\n  const toggle = () => {\n    const next = !starred;\n    onStarredChange(next);\n    setNote(next ? \"Starred\" : \"Unstarred\");\n  };\n\n  return (\n    <span className=\"relative inline-flex\">\n      <button\n        type=\"button\"\n        aria-pressed={starred}\n        aria-label={`Star, ${group(count)} stars`}\n        onClick={toggle}\n        className={cn(\n          \"group inline-flex h-8 touch-manipulation items-stretch overflow-visible rounded-lg bg-muted text-[13px] font-medium text-foreground shadow-raised outline-hidden select-none\",\n          \"transition-[scale,background-color] duration-150 ease-out hover:bg-background active:scale-[0.96] motion-reduce:transition-[background-color]\",\n          \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground\",\n          className,\n        )}\n      >\n        {/* 2px less on the icon side: the star's own bearings fill it. */}\n        <span className=\"flex items-center gap-1.5 pr-3 pl-2.5\">\n          <span className=\"relative grid size-4 place-items-center\">\n            <span aria-hidden className=\"pointer-events-none absolute inset-0\">\n              {burst > 0 && !reduceMotion && <Sparks key={burst} />}\n            </span>\n            <span ref={glyph} aria-hidden className=\"relative block size-4\">\n              <svg\n                viewBox=\"0 0 24 24\"\n                className={cn(\n                  \"size-4 transition-[fill-opacity,color] ease-out\",\n                  starred\n                    ? \"[fill-opacity:1] delay-75 duration-200\"\n                    : \"text-muted-foreground [fill-opacity:0] duration-150 group-hover:text-foreground\",\n                )}\n                style={starred ? { color: STAR_YELLOW } : undefined}\n                fill=\"currentColor\"\n                stroke=\"currentColor\"\n                strokeWidth={1.75}\n                strokeLinejoin=\"round\"\n              >\n                <path d={STAR} />\n              </svg>\n            </span>\n          </span>\n          {/* Glides to the word's own width, so \"Star\" never sits beside a\n              gap reserved for \"Starred\". Width (not scale) so the letters\n              never stretch; the button's left edge stays put. */}\n          <span\n            aria-hidden\n            className=\"relative h-5 overflow-hidden leading-5 transition-[width] duration-[250ms] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\"\n            style={\n              widths ? { width: starred ? widths[1] : widths[0] } : undefined\n            }\n          >\n            {/* Sizes the cell in server HTML, before anything is measured. */}\n            <span className=\"invisible block whitespace-nowrap\">\n              {starred ? \"Starred\" : \"Star\"}\n            </span>\n            <Label visible={!starred}>Star</Label>\n            <Label visible={starred}>Starred</Label>\n            <span\n              ref={rulerA}\n              className=\"invisible absolute left-0 whitespace-nowrap\"\n            >\n              Star\n            </span>\n            <span\n              ref={rulerB}\n              className=\"invisible absolute left-0 whitespace-nowrap\"\n            >\n              Starred\n            </span>\n          </span>\n        </span>\n        <span aria-hidden className=\"my-1.5 w-px bg-border\" />\n        <span className=\"flex items-center px-2.5\">\n          <Count\n            text={group(count)}\n            direction={starred ? 1 : -1}\n            reduceMotion={reduceMotion}\n          />\n        </span>\n      </button>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {note}\n      </span>\n    </span>\n  );\n}\n\nfunction Sparks() {\n  return SPARK_ANGLES.map((angle) => (\n    // The wrapper holds the angle; the line only ever travels along its own\n    // axis, so the transform stays a simple translate plus scale.\n    <span\n      key={angle}\n      className=\"absolute inset-0\"\n      style={{ rotate: `${angle}deg` }}\n    >\n      <motion.span\n        className=\"absolute top-1/2 left-1/2 -ml-[0.75px] h-[5px] w-[1.5px] origin-bottom rounded-full\"\n        style={{ backgroundColor: STAR_YELLOW }}\n        // Leaves from just outside the star's points and shrinks as it goes,\n        // so it reads as a spark flying off rather than a line sliding.\n        initial={{ y: -12, scaleY: 1, opacity: 1 }}\n        animate={{ y: -17, scaleY: 0.2, opacity: [1, 1, 0] }}\n        transition={{\n          ...SPARK,\n          // Waits for the spin to get going, so the star seems to throw them.\n          delay: 0.05,\n          opacity: { ...SPARK, delay: 0.05, times: [0, 0.4, 1] },\n        }}\n      />\n    </span>\n  ));\n}\n\nfunction Label({\n  visible,\n  children,\n}: {\n  visible: boolean;\n  children: React.ReactNode;\n}) {\n  return (\n    <span\n      className={cn(\n        \"absolute top-0 left-0 whitespace-nowrap transition-[opacity,filter] ease-[cubic-bezier(0.23,1,0.32,1)]\",\n        visible\n          ? \"opacity-100 blur-[0px] duration-200\"\n          : \"opacity-0 blur-[3px] duration-100 motion-reduce:blur-[0px]\",\n      )}\n    >\n      {children}\n    </span>\n  );\n}\n\ntype Roll = { direction: number; reduceMotion: boolean | null };\n\nconst ROLL = {\n  enter: ({ direction, reduceMotion }: Roll) => ({\n    y: reduceMotion ? \"0%\" : `${direction * 100}%`,\n    opacity: 0,\n  }),\n  center: {\n    y: \"0%\",\n    opacity: 1,\n    transition: { duration: 0.26, ease: EASE_OUT },\n  },\n  // Exits go sooner and softer than entries.\n  exit: ({ direction, reduceMotion }: Roll) => ({\n    y: reduceMotion ? \"0%\" : `${direction * -100}%`,\n    opacity: 0,\n    transition: { duration: 0.18, ease: EASE_OUT },\n  }),\n};\n\nfunction Count({\n  text,\n  direction,\n  reduceMotion,\n}: {\n  text: string;\n  direction: number;\n  reduceMotion: boolean | null;\n}) {\n  const chars = text.split(\"\");\n  const custom = { direction, reduceMotion };\n  return (\n    <span aria-hidden className=\"flex tabular-nums\">\n      {chars.map((char, i) => (\n        // Keyed by place from the right: only the digits that change roll,\n        // so 1,299 to 1,300 rolls three and leaves the thousands alone.\n        <span key={chars.length - i} className=\"inline-grid overflow-hidden\">\n          <AnimatePresence initial={false} custom={custom}>\n            <motion.span\n              key={char}\n              custom={custom}\n              variants={ROLL}\n              initial=\"enter\"\n              animate=\"center\"\n              exit=\"exit\"\n              className=\"col-start-1 row-start-1\"\n            >\n              {char}\n            </motion.span>\n          </AnimatePresence>\n        </span>\n      ))}\n    </span>\n  );\n}\n\n// The index card's hover show: someone stars the repo, admires it for a\n// moment, then changes their mind. Waits in ms.\nconst SHOW_STAR = 350;\nconst SHOW_UNSTAR = 2600;\nconst SHOW_REST = 1500;\n\nexport default function StarButtonDemo() {\n  const [starred, setStarred] = useState(false);\n  const play = usePreviewPlay();\n\n  useEffect(() => {\n    if (play !== true) return;\n    let timer: ReturnType<typeof setTimeout>;\n    const cycle = (wait: number) => {\n      timer = setTimeout(() => {\n        setStarred(true);\n        timer = setTimeout(() => {\n          setStarred(false);\n          cycle(SHOW_REST);\n        }, SHOW_UNSTAR);\n      }, wait);\n    };\n    cycle(SHOW_STAR);\n    return () => {\n      clearTimeout(timer);\n      setStarred(false);\n    };\n  }, [play]);\n\n  return (\n    // On its own page the button is left aligned in a box sized for its\n    // starred width, so it grows rightward and never slides out from under\n    // the cursor. Nobody clicks the index card's copy, so there it stays\n    // centred and grows evenly both ways.\n    <div\n      className={cn(\"flex w-[148px]\", play !== null && \"justify-center\")}\n    >\n      <StarButton\n        starred={starred}\n        count={starred ? 1300 : 1299}\n        onStarredChange={setStarred}\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":["buttons"],"docs":"From ui lab: https://lab.xevrion.dev/lab/star-button"}