{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"testimonial-highlight","type":"registry:component","title":"Testimonial highlight","description":"Swipes a highlighter across the line that sold the customer, one line at a time.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/testimonial-highlight.tsx","type":"registry:component","content":"\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { AnimatePresence, motion, useInView } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type Testimonial = {\n  quote: string;\n  // The phrase to mark: must appear in `quote` exactly as written.\n  highlight: string;\n  name: string;\n  role: string;\n  // Falls back to initials.\n  avatar?: string;\n};\n\ntype Line = { x: number; y: number; w: number; h: number };\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// A marker covers about this many pixels a second: slow enough to watch the\n// stroke travel, quick enough that a long phrase is done in about a second.\nconst MARKER_SPEED = 620;\n// Where the swipe starts after the quote begins fading up, so the stroke\n// lands on text you can already read.\nconst MARK_DELAY = 380;\n// The stroke covers the middle of the line box, not all of it, the way a\n// real highlighter sits over the x-height and leaves the leading clear.\nconst COVER_TOP = 0.2;\nconst COVER = 0.7;\n// Ink runs slightly past the words at both ends, like a hand that starts a\n// hair early and lifts a hair late.\nconst OVERSHOOT = 4;\n\n// Seeded so the same line always gets the same ragged edge, on the server\n// and the client alike.\nfunction random(seed: number) {\n  let s = seed >>> 0 || 1;\n  return () => {\n    s = (s * 1664525 + 1013904223) >>> 0;\n    return s / 4294967296;\n  };\n}\n\n// A highlighter stroke: a chisel tip leaves slanted ends, and the edges\n// wobble a little along the way, top and bottom independently.\nfunction strokePath(w: number, h: number, seed: number) {\n  const next = random(seed);\n  const step = 10;\n  const wobble = () => (next() - 0.5) * 2.2;\n  const top: string[] = [];\n  const bottom: string[] = [];\n  const slant = h * 0.28;\n  for (let x = slant; x <= w; x += step) {\n    top.push(`${x.toFixed(1)} ${(1.2 + wobble()).toFixed(1)}`);\n  }\n  top.push(`${w.toFixed(1)} ${(1 + wobble()).toFixed(1)}`);\n  for (let x = w - slant; x >= 0; x -= step) {\n    bottom.push(`${x.toFixed(1)} ${(h - 1.2 + wobble()).toFixed(1)}`);\n  }\n  bottom.push(`0 ${(h - 1 + wobble()).toFixed(1)}`);\n  return `M${top.join(\" L\")} L${bottom.join(\" L\")} Z`;\n}\n\nexport function TestimonialHighlight({\n  testimonials,\n  interval = 7000,\n  className,\n}: {\n  testimonials: Testimonial[];\n  // How long each quote stays, in ms, once its highlight is drawn.\n  interval?: number;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion() ?? false;\n  const rootRef = useRef<HTMLElement>(null);\n  const inView = useInView(rootRef, { amount: 0.5 });\n  const [index, setIndex] = useState(0);\n  const [hovered, setHovered] = useState(false);\n  const [focused, setFocused] = useState(false);\n  const [paused, setPaused] = useState(false);\n  const [hidden, setHidden] = useState(false);\n  // The swipe for the current quote has finished, so the author can come in\n  // and the countdown can start.\n  const [marked, setMarked] = useState(false);\n  const barRef = useRef<HTMLSpanElement>(null);\n  const timer = useRef<Animation | null>(null);\n  const n = testimonials.length;\n\n  useEffect(() => {\n    const onVisibility = () => setHidden(document.hidden);\n    document.addEventListener(\"visibilitychange\", onVisibility);\n    return () => document.removeEventListener(\"visibilitychange\", onVisibility);\n  }, []);\n\n  const go = useCallback(\n    (i: number) => {\n      setMarked(false);\n      setIndex(((i % n) + n) % n);\n    },\n    [n],\n  );\n\n  // The countdown is an animation on the progress bar itself, so pausing it\n  // pauses the bar and the timer together and they can never drift apart.\n  useEffect(() => {\n    const bar = barRef.current;\n    if (!bar || !marked) return;\n    const run = bar.animate(\n      [{ transform: \"scaleX(0)\" }, { transform: \"scaleX(1)\" }],\n      {\n        duration: interval,\n        easing: \"linear\",\n        fill: \"forwards\",\n      },\n    );\n    run.onfinish = () => go(index + 1);\n    timer.current = run;\n    return () => {\n      run.onfinish = null;\n      run.cancel();\n      timer.current = null;\n    };\n  }, [marked, index, interval, go]);\n\n  const holding = hovered || focused || paused || hidden || !inView;\n  useEffect(() => {\n    const run = timer.current;\n    if (!run) return;\n    if (holding) run.pause();\n    else run.play();\n  }, [holding, marked, index]);\n\n  const current = testimonials[index];\n\n  return (\n    <section\n      ref={rootRef}\n      aria-roledescription=\"carousel\"\n      aria-label=\"Customer testimonials\"\n      onPointerEnter={(e) => e.pointerType !== \"touch\" && setHovered(true)}\n      onPointerLeave={() => setHovered(false)}\n      // Keyboard focus holds the rotation; a mouse click on a dot shouldn't\n      // leave it paused until the next click elsewhere.\n      onFocus={(e) => setFocused(e.target.matches(\":focus-visible\"))}\n      onBlur={(e) => {\n        if (!e.currentTarget.contains(e.relatedTarget as Node | null))\n          setFocused(false);\n      }}\n      onKeyDown={(e) => {\n        if (e.key === \"ArrowRight\") go(index + 1);\n        else if (e.key === \"ArrowLeft\") go(index - 1);\n      }}\n      className={cn(\n        \"flex w-[min(540px,100%)] flex-col gap-6 rounded-[22px] bg-background p-5 shadow-raised sm:gap-7 sm:p-7\",\n        className,\n      )}\n    >\n      {/* Every quote shares one grid cell, so the card is always as tall as\n          the longest and never jumps between quotes. */}\n      <div className=\"grid gap-4\">\n        {/* A plain opening mark, quiet enough to leave the ink the only\n            colour in the card. */}\n        <svg\n          aria-hidden\n          viewBox=\"0 0 32 24\"\n          className=\"h-5 w-[27px] fill-foreground/15\"\n        >\n          <path d=\"M0 24V14.4C0 6.6 4.2 1.8 12.4 0l1.4 3.4C9.4 4.8 7.3 7.6 7 11.2h6.2V24H0Zm18.2 0V14.4C18.2 6.6 22.4 1.8 30.6 0L32 3.4c-4.4 1.4-6.5 4.2-6.8 7.8h6.2V24H18.2Z\" />\n        </svg>\n        <div className=\"grid\">\n          {testimonials.map((t, i) => (\n            <Quote\n              key={t.name}\n              testimonial={t}\n              state={\n                i === index\n                  ? \"active\"\n                  : i === (index - 1 + n) % n\n                    ? \"past\"\n                    : \"future\"\n              }\n              play={i === index && inView}\n              reduceMotion={reduceMotion}\n              onMarked={() => i === index && setMarked(true)}\n            />\n          ))}\n        </div>\n      </div>\n\n      <div className=\"flex items-center justify-between gap-4\">\n        <div className=\"relative h-11 min-w-0 flex-1\">\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            {marked && (\n              <motion.figcaption\n                key={current.name}\n                initial={{ opacity: 0, x: -10, filter: \"blur(4px)\" }}\n                animate={{ opacity: 1, x: 0, filter: \"blur(0px)\" }}\n                exit={{\n                  opacity: 0,\n                  filter: \"blur(2px)\",\n                  transition: { duration: 0.15 },\n                }}\n                transition={{\n                  duration: reduceMotion ? 0 : 0.35,\n                  ease: EASE_OUT,\n                }}\n                className=\"absolute inset-0 flex items-center gap-3\"\n              >\n                <Avatar testimonial={current} />\n                <span className=\"flex min-w-0 flex-col\">\n                  <span className=\"truncate text-[15px] font-semibold\">\n                    {current.name}\n                  </span>\n                  <span className=\"truncate text-[13px] text-muted-foreground\">\n                    {current.role}\n                  </span>\n                </span>\n              </motion.figcaption>\n            )}\n          </AnimatePresence>\n        </div>\n\n        <div className=\"flex shrink-0 items-center gap-1\">\n          <div\n            role=\"group\"\n            aria-label=\"Choose a testimonial\"\n            className=\"flex items-center\"\n          >\n            {testimonials.map((t, i) => {\n              const on = i === index;\n              return (\n                <button\n                  key={t.name}\n                  type=\"button\"\n                  onClick={() => go(i)}\n                  aria-label={`Testimonial from ${t.name}`}\n                  aria-current={on ? \"true\" : undefined}\n                  className=\"group flex h-9 w-5 touch-manipulation items-center justify-center rounded-full outline-hidden transition-[scale] duration-150 ease-out focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\"\n                >\n                  <span\n                    className={cn(\n                      \"relative h-1.5 overflow-hidden rounded-full transition-[width,background-color] duration-300 ease-[cubic-bezier(0.77,0,0.175,1)]\",\n                      on\n                        ? \"w-5 bg-border\"\n                        : \"w-1.5 bg-border group-hover:bg-muted-foreground\",\n                    )}\n                  >\n                    {on && (\n                      <span\n                        ref={barRef}\n                        className=\"absolute inset-0 origin-left rounded-full bg-foreground\"\n                        style={{ transform: \"scaleX(0)\" }}\n                      />\n                    )}\n                  </span>\n                </button>\n              );\n            })}\n          </div>\n          <button\n            type=\"button\"\n            onClick={() => setPaused((p) => !p)}\n            aria-label={paused ? \"Resume rotation\" : \"Pause rotation\"}\n            aria-pressed={paused}\n            className=\"flex size-9 touch-manipulation items-center justify-center rounded-full text-muted-foreground outline-hidden transition-[scale,color] duration-150 ease-out hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\"\n          >\n            <PlayPause paused={paused} />\n          </button>\n        </div>\n      </div>\n\n      <p className=\"sr-only\" aria-live={holding ? \"polite\" : \"off\"}>\n        {`${current.quote} ${current.name}, ${current.role}`}\n      </p>\n    </section>\n  );\n}\n\nfunction Quote({\n  testimonial,\n  state,\n  play,\n  reduceMotion,\n  onMarked,\n}: {\n  testimonial: Testimonial;\n  state: \"active\" | \"past\" | \"future\";\n  play: boolean;\n  reduceMotion: boolean;\n  onMarked: () => void;\n}) {\n  const textRef = useRef<HTMLParagraphElement>(null);\n  const markRef = useRef<HTMLElement>(null);\n  const strokes = useRef<(SVGSVGElement | null)[]>([]);\n  const [lines, setLines] = useState<Line[]>([]);\n  const drawn = useRef(false);\n  const done = useRef(onMarked);\n  const filterId = useId().replace(/:/g, \"\");\n  useEffect(() => {\n    done.current = onMarked;\n  });\n\n  const { quote, highlight } = testimonial;\n  const at = quote.indexOf(highlight);\n  const before = at >= 0 ? quote.slice(0, at) : quote;\n  const after = at >= 0 ? quote.slice(at + highlight.length) : \"\";\n\n  // One rect per line the phrase wraps onto, in the paragraph's own space.\n  // Remeasured on resize, since a new width rewraps the words.\n  useLayoutEffect(() => {\n    const text = textRef.current;\n    const mark = markRef.current;\n    if (!text || !mark) return;\n    const measure = () => {\n      const base = text.getBoundingClientRect();\n      // Client rects are in screen pixels, after every ancestor's transform.\n      // Dividing by the on-screen scale puts them back in the paragraph's own\n      // space, so the marks still land when the whole card is scaled, as in\n      // the index preview. Subtracting the paragraph's rect removes the\n      // fade-up's offset.\n      const scale = base.width / text.offsetWidth || 1;\n      const rects = [...mark.getClientRects()].filter((r) => r.width > 1);\n      setLines(\n        rects.map((r) => ({\n          x: (r.left - base.left) / scale - OVERSHOOT,\n          y: (r.top - base.top) / scale + (r.height / scale) * COVER_TOP,\n          w: r.width / scale + OVERSHOOT * 2,\n          h: (r.height / scale) * COVER,\n        })),\n      );\n    };\n    measure();\n    const ro = new ResizeObserver(measure);\n    ro.observe(text);\n    return () => ro.disconnect();\n  }, []);\n\n  // Draws line by line, left to right, each at the same pen speed so a\n  // short last line takes less time than a long first one.\n  useEffect(() => {\n    const svgs = strokes.current\n      .slice(0, lines.length)\n      .filter(Boolean) as SVGSVGElement[];\n    if (state !== \"active\") {\n      drawn.current = false;\n      // Wiped only once the quote has faded, so it never visibly un-draws.\n      const t = setTimeout(\n        () => svgs.forEach((s) => (s.style.clipPath = \"inset(0 100% 0 0)\")),\n        300,\n      );\n      return () => clearTimeout(t);\n    }\n    if (!play || !svgs.length) return;\n    if (drawn.current || reduceMotion) {\n      svgs.forEach((s) => (s.style.clipPath = \"inset(0 0 0 0)\"));\n      if (!drawn.current) {\n        drawn.current = true;\n        done.current();\n      }\n      return;\n    }\n    let delay = MARK_DELAY;\n    const runs = svgs.map((svg, i) => {\n      const duration = (lines[i].w / MARKER_SPEED) * 1000;\n      const first = i === 0;\n      const last = i === svgs.length - 1;\n      // The pen accelerates off the first word and slows onto the last;\n      // lines in between run at an even speed so the stroke reads as one.\n      const easing =\n        first && last\n          ? \"cubic-bezier(0.45, 0, 0.3, 1)\"\n          : first\n            ? \"cubic-bezier(0.45, 0, 1, 1)\"\n            : last\n              ? \"cubic-bezier(0, 0, 0.3, 1)\"\n              : \"linear\";\n      const run = svg.animate(\n        [{ clipPath: \"inset(0 100% 0 0)\" }, { clipPath: \"inset(0 0 0 0)\" }],\n        { duration, delay, easing, fill: \"forwards\" },\n      );\n      delay += duration;\n      return run;\n    });\n    const lastRun = runs[runs.length - 1];\n    lastRun.onfinish = () => {\n      svgs.forEach((s) => (s.style.clipPath = \"inset(0 0 0 0)\"));\n      runs.forEach((r) => r.cancel());\n      drawn.current = true;\n      done.current();\n    };\n    return () => {\n      lastRun.onfinish = null;\n      runs.forEach((r) => r.cancel());\n    };\n  }, [state, play, lines, reduceMotion]);\n\n  return (\n    <blockquote\n      aria-hidden={state !== \"active\"}\n      className={cn(\n        \"[grid-area:1/1] transition-[opacity,translate,filter,visibility] motion-reduce:translate-y-0 motion-reduce:filter-none\",\n        state === \"active\" &&\n          \"translate-y-0 opacity-100 filter-none duration-500 ease-[cubic-bezier(0.23,1,0.32,1)]\",\n        // Leaving is quicker and quieter than arriving.\n        state === \"past\" &&\n          \"-translate-y-1 opacity-0 blur-[2px] duration-200 ease-out\",\n        state === \"future\" && \"translate-y-3 opacity-0 blur-[4px] duration-0\",\n        // Hidden from pointers and find-in-page once faded; visibility flips\n        // at the end of the fade, so the fade itself still shows.\n        state !== \"active\" && \"invisible\",\n      )}\n    >\n      <p\n        ref={textRef}\n        className=\"relative isolate text-[18px] leading-[1.55] font-medium tracking-[-0.01em] text-pretty sm:text-[20px]\"\n      >\n        <svg aria-hidden className=\"absolute size-0\">\n          {/* Highlighter ink is uneven: a little streaking along the stroke\n              and edges that bleed into the paper fibres. */}\n          <filter id={filterId} x=\"-2%\" y=\"-20%\" width=\"104%\" height=\"140%\">\n            <feTurbulence\n              type=\"fractalNoise\"\n              baseFrequency=\"0.05 0.3\"\n              numOctaves={2}\n              seed={3}\n              result=\"grain\"\n            />\n            <feDisplacementMap\n              in=\"SourceGraphic\"\n              in2=\"grain\"\n              scale={1.6}\n              result=\"edge\"\n            />\n            <feTurbulence\n              type=\"fractalNoise\"\n              baseFrequency=\"0.006 0.5\"\n              numOctaves={1}\n              seed={9}\n              result=\"streak\"\n            />\n            <feColorMatrix\n              in=\"streak\"\n              type=\"matrix\"\n              values=\"0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 -0.45 1.15\"\n              result=\"mask\"\n            />\n            <feComposite in=\"edge\" in2=\"mask\" operator=\"in\" />\n          </filter>\n        </svg>\n        {lines.map((line, i) => (\n          <svg\n            key={`${i}-${Math.round(line.w)}`}\n            ref={(el) => void (strokes.current[i] = el)}\n            aria-hidden\n            className=\"pointer-events-none absolute -z-10 overflow-visible\"\n            style={{\n              left: line.x,\n              top: line.y,\n              width: line.w,\n              height: line.h,\n              // Always mounts undrawn; the draw effect reveals it, instantly\n              // if this quote was already marked before a rewrap.\n              clipPath: \"inset(0 100% 0 0)\",\n            }}\n            viewBox={`0 0 ${line.w} ${line.h}`}\n          >\n            <path\n              d={strokePath(line.w, line.h, (i + 1) * 97 + quote.length)}\n              filter={`url(#${filterId})`}\n              // Highlighter ink is a physical material, so it keeps its\n              // colour: bright fluorescent yellow on paper, a deep gold in\n              // dark mode so light text on it stays readable.\n              className=\"fill-[oklch(0.91_0.17_100)] opacity-80 dark:fill-[oklch(0.5_0.11_88)] dark:opacity-90\"\n            />\n          </svg>\n        ))}\n        <span>{before}</span>\n        <mark ref={markRef} className=\"bg-transparent text-inherit\">\n          {highlight}\n        </mark>\n        <span>{after}</span>\n      </p>\n    </blockquote>\n  );\n}\n\nfunction Avatar({ testimonial }: { testimonial: Testimonial }) {\n  const initials = testimonial.name\n    .split(\" \")\n    .map((w) => w[0])\n    .slice(0, 2)\n    .join(\"\");\n  return (\n    <span className=\"flex size-11 shrink-0 items-center justify-center overflow-hidden rounded-full bg-[oklch(0.97_0_0)] text-[14px] font-semibold text-[oklch(0.3_0_0)] outline-1 -outline-offset-1 outline-[oklch(0_0_0/0.1)] dark:outline-[oklch(1_0_0/0.1)]\">\n      {testimonial.avatar ? (\n        // eslint-disable-next-line @next/next/no-img-element\n        <img\n          src={testimonial.avatar}\n          alt=\"\"\n          className=\"size-full\"\n          draggable={false}\n        />\n      ) : (\n        initials\n      )}\n    </span>\n  );\n}\n\nfunction PlayPause({ paused }: { paused: boolean }) {\n  return (\n    <span className=\"relative size-4\">\n      <AnimatePresence initial={false}>\n        <motion.svg\n          key={paused ? \"play\" : \"pause\"}\n          viewBox=\"0 0 16 16\"\n          className=\"absolute inset-0 size-4\"\n          fill=\"currentColor\"\n          aria-hidden\n          initial={{ opacity: 0, scale: 0.25, filter: \"blur(4px)\" }}\n          animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n          exit={{ opacity: 0, scale: 0.25, filter: \"blur(4px)\" }}\n          transition={{ type: \"spring\", duration: 0.3, bounce: 0 }}\n        >\n          {paused ? (\n            <path d=\"M5 3.2v9.6a.6.6 0 0 0 .9.5l7.4-4.8a.6.6 0 0 0 0-1L5.9 2.7a.6.6 0 0 0-.9.5Z\" />\n          ) : (\n            <path d=\"M4.5 3h2v10h-2zM9.5 3h2v10h-2z\" />\n          )}\n        </motion.svg>\n      </AnimatePresence>\n    </span>\n  );\n}\n\nconst TESTIMONIALS: Testimonial[] = [\n  {\n    quote:\n      \"We moved our month-end close into Ledgerly in March. What used to eat the first week of every month now takes an afternoon, and nobody on the team misses the spreadsheets.\",\n    highlight: \"now takes an afternoon\",\n    name: \"Ava Chen\",\n    role: \"Controller, Northwind Traders\",\n    avatar: \"/avatars/ava.svg\",\n  },\n  {\n    quote:\n      \"I was braced for a six month migration. Our books were live in eleven days, and the auditors signed off on the first try.\",\n    highlight: \"the auditors signed off on the first try\",\n    name: \"Ben Ortiz\",\n    role: \"CFO, Globex Retail\",\n    avatar: \"/avatars/ben.svg\",\n  },\n  {\n    quote:\n      \"The payout view is the first screen I open every morning. When a transfer is late I know which customer it is before our bank does.\",\n    highlight: \"I know which customer it is before our bank does\",\n    name: \"Cara Lindqvist\",\n    role: \"Head of Finance Ops, Initech\",\n    avatar: \"/avatars/cara.svg\",\n  },\n  {\n    quote:\n      \"Three entities, two currencies, one login. Consolidation used to need a consultant, and now it's a button.\",\n    highlight: \"now it's a button\",\n    name: \"Dev Raman\",\n    role: \"Founder, Parcel & Pine\",\n    avatar: \"/avatars/dev.svg\",\n  },\n];\n\nexport default function TestimonialHighlightDemo() {\n  return <TestimonialHighlight testimonials={TESTIMONIALS} />;\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":{"marker":"#d93d31","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":{"marker":"#ff6b5f","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":{"color-marker":"var(--marker)","shadow-raised":"var(--shadow-raised)"}},"categories":["cards"],"docs":"From ui lab: https://lab.xevrion.dev/lab/testimonial-highlight"}