{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"highlighter-text","type":"registry:ui","title":"Highlighter Text","description":"A marker stroke draws behind the words you choose when they scroll into view, with an uneven hand-drawn edge and text that changes color under the pen.","dependencies":[],"registryDependencies":["https://ui.mekaigames.com/r/theme.json"],"files":[{"path":"components/ui/highlighter-text.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { Fragment, useEffect, useMemo, useRef } from \"react\";\n\nexport type HighlighterTextProps = {\n  /** The full text. */\n  text: string;\n  /** Words or short phrases to mark, matched without case or punctuation. */\n  highlight: string[];\n  /** Color of the marker. */\n  color?: string;\n  /** Color of the marked words while the marker is behind them. Used by the \"full\" variant. */\n  markedTextColor?: string;\n  /** \"full\" covers the whole word, \"underline\" draws a stroke along its lower half. */\n  variant?: \"full\" | \"underline\";\n  /** Milliseconds the pen spends on each letter. */\n  pace?: number;\n  /** Milliseconds before the first stroke starts. */\n  delay?: number;\n  /** Draw only the first time the words enter the viewport. */\n  once?: boolean;\n  className?: string;\n};\n\ntype Token = {\n  lead: string;\n  core: string;\n  tail: string;\n  marked: boolean;\n  /** The next word is marked too, so this stroke runs on across the space. */\n  joins: boolean;\n  /** Which continuous stroke this word belongs to. */\n  run: number;\n  /** Letters drawn in this stroke before this word, so joined words share one edge. */\n  offset: number;\n};\n\n/** Room the stroke sticks out past a word on each side, in em. */\nconst OVERHANG = 0.14;\nconst SEPARATOR = \"\\u0000\";\nconst HIDDEN = \"inset(-30% 100% -30% 0)\";\nconst SHOWN = \"inset(-30% 0% -30% 0)\";\n\n/** Repeatable 0 to 1 value, so strokes match between server and client. */\nfunction noise(seed: number) {\n  const x = Math.sin(seed * 127.1 + 311.7) * 43758.5453;\n  return x - Math.floor(x);\n}\n\nconst clean = (word: string) => word.toLowerCase().replace(/[^\\p{L}\\p{N}]+/gu, \"\");\n\nfunction tokenize(text: string, phrases: string[]) {\n  const words = text.split(/\\s+/).filter(Boolean);\n  const cleaned = words.map(clean);\n  const marked = words.map(() => false);\n  for (const phrase of phrases) {\n    const parts = phrase.split(/\\s+/).map(clean).filter(Boolean);\n    if (!parts.length) continue;\n    for (let i = 0; i + parts.length <= words.length; i++) {\n      if (parts.every((part, k) => cleaned[i + k] === part)) {\n        for (let k = 0; k < parts.length; k++) marked[i + k] = true;\n      }\n    }\n  }\n  let run = -1;\n  let drawn = 0;\n  return words.map((word, i): Token => {\n    const joins = marked[i] && Boolean(marked[i + 1]);\n    if (marked[i] && !marked[i - 1]) {\n      run++;\n      drawn = 0;\n    }\n    // Punctuation at the end of a stroke stays outside it, as it would with a real pen.\n    const edges = /^([^\\p{L}\\p{N}]*)(.*?)([^\\p{L}\\p{N}]*)$/u.exec(word);\n    const lead = marked[i] && !marked[i - 1] ? (edges?.[1] ?? \"\") : \"\";\n    const tail = marked[i] && !joins ? (edges?.[3] ?? \"\") : \"\";\n    const core = word.slice(lead.length, word.length - tail.length);\n    const offset = drawn;\n    drawn += Array.from(core).length + 1;\n    return { lead, core, tail, marked: marked[i], joins, run, offset };\n  });\n}\n\ntype Band = { seed: number; from: number; letters: number; top: number; bottom: number; wobble: number; openLeft: boolean; openRight: boolean };\n\n/** Curve through the midpoints of a list of points, so edges wander instead of looking torn. */\nfunction curve(points: [number, number][]) {\n  let d = \"\";\n  for (let i = 0; i < points.length - 1; i++) {\n    const [x, y] = points[i];\n    const [nx, ny] = points[i + 1];\n    d += ` Q ${x.toFixed(1)} ${y.toFixed(1)} ${((x + nx) / 2).toFixed(1)} ${((y + ny) / 2).toFixed(1)}`;\n  }\n  const [lx, ly] = points[points.length - 1];\n  return `${d} L ${lx.toFixed(1)} ${ly.toFixed(1)}`;\n}\n\n/**\n * A stroke with independently uneven top and bottom edges. Edges are sampled per letter of the whole stroke,\n * so joined words meet at the same height. Free ends get the slant of a chisel tip.\n */\nfunction bandPath({ seed, from, letters, top, bottom, wobble, openLeft, openRight }: Band) {\n  const steps = letters + 1;\n  const upper: [number, number][] = [];\n  const lower: [number, number][] = [];\n  for (let i = 0; i <= steps; i++) {\n    const x = (i / steps) * 100;\n    upper.push([i === 0 && !openLeft ? 3 + noise(seed + 1) * 2 : x, top + noise(seed + from + i) * wobble]);\n    lower.push([i === steps && !openRight ? 96.5 - noise(seed + 2) * 2 : x, bottom - noise(seed + 50 + from + i) * wobble]);\n  }\n  lower.reverse();\n  return `M ${upper[0][0].toFixed(1)} ${upper[0][1].toFixed(1)}${curve(upper)} L ${lower[0][0].toFixed(1)} ${lower[0][1].toFixed(1)}${curve(lower)} Z`;\n}\n\n/** A marker stroke draws behind chosen words when they scroll into view, with an uneven hand-drawn edge. */\nexport function HighlighterText({\n  text,\n  highlight,\n  color = \"#ff784f\",\n  markedTextColor = \"#070606\",\n  variant = \"full\",\n  pace = 34,\n  delay = 150,\n  once = true,\n  className = \"\",\n}: HighlighterTextProps) {\n  const root = useRef<HTMLSpanElement>(null);\n  const phrasesKey = highlight.join(SEPARATOR);\n  const tokens = useMemo(() => tokenize(text, phrasesKey.split(SEPARATOR)), [text, phrasesKey]);\n\n  useEffect(() => {\n    const el = root.current;\n    if (!el) return;\n    const wipes = Array.from(el.querySelectorAll<HTMLElement>(\"[data-wipe]\"));\n    if (!wipes.length) return;\n\n    wipes.forEach((wipe) => {\n      wipe.style.clipPath = HIDDEN;\n    });\n    if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) {\n      wipes.forEach((wipe) => {\n        wipe.style.clipPath = \"none\";\n      });\n      return;\n    }\n\n    const runs = new Map<string, HTMLElement[]>();\n    wipes.forEach((wipe) => {\n      const key = wipe.dataset.wipe ?? \"\";\n      runs.set(key, [...(runs.get(key) ?? []), wipe]);\n    });\n\n    const playing = new Map<string, Animation[]>();\n    // Only one pen: strokes that enter the view together are drawn one after another.\n    let penFreeAt = 0;\n\n    const draw = (key: string, group: HTMLElement[]) => {\n      const now = performance.now();\n      let at = Math.max(now + delay, penFreeAt) - now;\n      const animations = group.map((wipe, i) => {\n        const letters = Number(wipe.dataset.letters) || 1;\n        const time = Math.max(90, letters * Math.max(5, pace)) + (i === group.length - 1 ? 90 : 0);\n        const first = i === 0;\n        const last = i === group.length - 1;\n        const easing = first && last ? \"cubic-bezier(0.4, 0, 0.3, 1)\" : first ? \"cubic-bezier(0.5, 0, 1, 1)\" : last ? \"cubic-bezier(0, 0, 0.3, 1)\" : \"linear\";\n        wipe.style.clipPath = SHOWN;\n        const animation = wipe.animate([{ clipPath: HIDDEN }, { clipPath: SHOWN }], { duration: time, delay: at, easing, fill: \"backwards\" });\n        at += time;\n        return animation;\n      });\n      playing.set(key, animations);\n      penFreeAt = now + at + 140;\n    };\n\n    const observer = new IntersectionObserver(\n      (entries) => {\n        for (const entry of entries) {\n          const key = (entry.target as HTMLElement).dataset.mark ?? \"\";\n          const group = runs.get(key);\n          if (!group) continue;\n          if (entry.isIntersecting && !playing.has(key)) {\n            draw(key, group);\n            if (once) observer.unobserve(entry.target);\n          } else if (!entry.isIntersecting && !once && playing.has(key)) {\n            playing.get(key)?.forEach((animation) => animation.cancel());\n            playing.delete(key);\n            group.forEach((wipe) => {\n              wipe.style.clipPath = HIDDEN;\n            });\n          }\n        }\n      },\n      { rootMargin: \"0px 0px -12% 0px\" },\n    );\n    el.querySelectorAll(\"[data-mark]\").forEach((node) => observer.observe(node));\n\n    return () => {\n      observer.disconnect();\n      playing.forEach((animations) => animations.forEach((animation) => animation.cancel()));\n    };\n  }, [tokens, pace, delay, once]);\n\n  return (\n    <span ref={root} className={className}>\n      {tokens.map((token, i) => (\n        <Fragment key={i}>\n          {i > 0 ? \" \" : null}\n          {token.marked ? (\n            <span className=\"whitespace-nowrap\">\n              {token.lead}\n              <Mark token={token} index={i} color={color} markedTextColor={markedTextColor} variant={variant} first={i === 0 || !tokens[i - 1].marked} />\n              {token.tail}\n            </span>\n          ) : (\n            token.core\n          )}\n        </Fragment>\n      ))}\n    </span>\n  );\n}\n\nfunction Mark({\n  token,\n  index,\n  color,\n  markedTextColor,\n  variant,\n  first,\n}: {\n  token: Token;\n  index: number;\n  color: string;\n  markedTextColor: string;\n  variant: \"full\" | \"underline\";\n  first: boolean;\n}) {\n  const letters = Array.from(token.core).length;\n  const seed = token.run * 37 + 11;\n  const full = variant === \"full\";\n  const shape = { from: token.offset, letters, openLeft: !first, openRight: token.joins };\n  // A joined word reaches across the space, so a phrase reads as one stroke. Only lone words get a slight tilt.\n  const right = token.joins ? 0.3 : OVERHANG;\n  const tilt = first && !token.joins ? `${((noise(index * 13 + 7) - 0.5) * 1.2).toFixed(2)}deg` : undefined;\n\n  return (\n    <mark\n      {...(first ? { \"data-mark\": String(token.run) } : null)}\n      className=\"relative inline-block bg-transparent text-inherit\"\n    >\n      {token.core}\n      <span\n        aria-hidden=\"true\"\n        data-wipe={token.run}\n        data-letters={letters}\n        className=\"pointer-events-none absolute inset-y-0 select-none\"\n        style={{ left: `-${OVERHANG}em`, right: `-${right}em`, clipPath: HIDDEN }}\n      >\n        <svg\n          viewBox=\"0 0 100 100\"\n          preserveAspectRatio=\"none\"\n          className=\"absolute left-0 w-full overflow-visible\"\n          style={{\n            top: \"50%\",\n            height: full ? \"1.24em\" : \"0.42em\",\n            marginTop: full ? \"-0.6em\" : \"0.16em\",\n            rotate: tilt,\n          }}\n        >\n          <path d={bandPath({ ...shape, seed, top: 0, bottom: 100, wobble: full ? 5 : 16 })} fill={color} />\n          {/* Lighter and darker passes, the streaks a chisel tip leaves behind. */}\n          <path d={bandPath({ ...shape, seed: seed + 200, top: 9, bottom: 30, wobble: 6 })} fill=\"#fff\" opacity=\"0.1\" />\n          <path d={bandPath({ ...shape, seed: seed + 300, top: 70, bottom: 90, wobble: 6 })} fill=\"#000\" opacity=\"0.08\" />\n        </svg>\n        {/* The word again on top of the stroke, so it stays readable and flips color under the pen. */}\n        <span className=\"absolute inset-y-0 whitespace-pre\" style={{ left: `${OVERHANG}em`, color: full ? markedTextColor : \"inherit\" }}>\n          {token.core}\n        </span>\n      </span>\n    </mark>\n  );\n}\n"}]}