{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"marker-highlight-text","type":"registry:component","title":"Marker Highlight Text","description":"A felt-tip highlighter stroke with a ragged edge that draws itself behind a phrase when it scrolls into view.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/marker-highlight-text.tsx","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState, useSyncExternalStore } from \"react\";\n\n/**\n * MarkerHighlight — a felt-tip stroke drawn behind a few words when they\n * scroll into view.\n *\n * THE STROKE IS AN IMAGE, NOT A BOX. The highlight is an SVG rectangle whose\n * edges are pushed about by a turbulence displacement filter, painted as the\n * span's background image, so it has the ragged edge and the slightly uneven\n * ink of a real marker. A CSS box with a colour does not read as a pen.\n *\n * IT DRAWS FROM THE LEFT. The reveal is a transition on background-size from\n * 0% to 100%, which the browser can animate without touching layout. With\n * box-decoration-break: clone, a phrase that wraps gets its own stroke on\n * every line, and every line draws at once.\n *\n * IT WAITS FOR YOU. By default the stroke draws when 60% of the phrase is on\n * screen, once. Pass `active` to drive it yourself (a step in a tour, a form\n * error, a hover on the sentence). Under prefers-reduced-motion the stroke is\n * simply there, with no draw — and that is checked live, so a reader who\n * toggles the setting mid-page gets the change without a reload.\n *\n * Highlighter is a light-ground device: keep the text dark. On a dark theme,\n * put the phrase on a paper plate rather than fighting it with blend modes.\n */\n\nconst HEX = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;\nconst EASE = \"cubic-bezier(0.22, 1, 0.36, 1)\";\n\n/** The stroke: a rect with turbulence-displaced edges, stretched to any word length. */\nfunction strokeImage(colour: string, seed: number, opacity: number, tilt: number) {\n  const svg =\n    '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 200 40\" preserveAspectRatio=\"none\">' +\n    '<filter id=\"r\" x=\"-6%\" y=\"-25%\" width=\"112%\" height=\"150%\">' +\n    '<feTurbulence type=\"fractalNoise\" baseFrequency=\"0.03 0.11\" numOctaves=\"2\" seed=\"' +\n    seed +\n    '\"/>' +\n    '<feDisplacementMap in=\"SourceGraphic\" scale=\"8\" xChannelSelector=\"R\" yChannelSelector=\"G\"/>' +\n    \"</filter>\" +\n    '<rect x=\"3\" y=\"5\" width=\"194\" height=\"30\" rx=\"2\" fill=\"' +\n    colour +\n    '\" fill-opacity=\"' +\n    opacity +\n    '\" filter=\"url(#r)\" transform=\"skewX(' +\n    tilt +\n    ')\"/>' +\n    \"</svg>\";\n  return 'url(\"data:image/svg+xml,' + encodeURIComponent(svg) + '\")';\n}\n\nfunction subscribeReduced(onChange: () => void) {\n  const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n  mq.addEventListener(\"change\", onChange);\n  return () => mq.removeEventListener(\"change\", onChange);\n}\nconst readReduced = () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\nconst readReducedServer = () => false;\n\nexport function MarkerHighlight({\n  children,\n  colour = \"#d6ff00\",\n  opacity = 0.82,\n  duration = 900,\n  delay = 0,\n  active,\n  once = true,\n  className = \"\",\n}: {\n  children: React.ReactNode;\n  /** Ink colour of the stroke. Hex only. */\n  colour?: string;\n  /** 0–1. Real marker ink is translucent; 1 reads as a printed bar. */\n  opacity?: number;\n  /** Draw time in ms. */\n  duration?: number;\n  /** Delay before the draw starts, in ms — stagger several phrases. */\n  delay?: number;\n  /** Drive the stroke yourself. Leave undefined to draw on view. */\n  active?: boolean;\n  /** Draw once and stay (default), or undraw when the phrase leaves view. */\n  once?: boolean;\n  className?: string;\n}) {\n  const ref = useRef<HTMLSpanElement>(null);\n  const [seen, setSeen] = useState(false);\n  const reduced = useSyncExternalStore(subscribeReduced, readReduced, readReducedServer);\n\n  // A stable seed per instance, so two phrases on one page do not share the\n  // same ragged edge. useId is not a number, so it is folded into one.\n  const id = useId();\n  let seed = 7;\n  for (let i = 0; i < id.length; i++) seed = (seed * 31 + id.charCodeAt(i)) % 997;\n\n  useEffect(() => {\n    if (active !== undefined) return;\n    const el = ref.current;\n    if (!el) return;\n    const io = new IntersectionObserver(\n      (entries) => {\n        // The last entry is the current one; an observer can batch several.\n        const hit = entries[entries.length - 1].isIntersecting;\n        if (hit) {\n          setSeen(true);\n          if (once) io.disconnect();\n        } else if (!once) {\n          setSeen(false);\n        }\n      },\n      { threshold: 0.6 },\n    );\n    io.observe(el);\n    return () => io.disconnect();\n  }, [active, once]);\n\n  const on = active ?? seen;\n  const ink = HEX.test(colour) ? colour : \"#d6ff00\";\n  const alpha = Math.min(1, Math.max(0, opacity));\n\n  return (\n    <span\n      ref={ref}\n      className={\"relative \" + className}\n      data-highlighted={on ? \"true\" : \"false\"}\n      style={{\n        backgroundImage: strokeImage(ink, seed, alpha, -1.5),\n        backgroundRepeat: \"no-repeat\",\n        backgroundPosition: \"left center\",\n        backgroundSize: (on ? 100 : 0) + \"% 100%\",\n        transition: reduced ? \"none\" : \"background-size \" + duration + \"ms \" + EASE + \" \" + delay + \"ms\",\n        WebkitBoxDecorationBreak: \"clone\",\n        boxDecorationBreak: \"clone\",\n        padding: \"0.04em 0.14em\",\n        margin: \"0 -0.14em\",\n      }}\n    >\n      {children}\n    </span>\n  );\n}\n","type":"registry:component","target":"components/viberdy/marker-highlight-text.tsx"}],"meta":{"tier":"free","tags":["text","highlight","scroll","inline","svg-filter"],"href":"https://viberdy.dev/library/marker-highlight-text","aiPrompt":"Create a React + Tailwind component named MarkerHighlight: an inline span that draws a felt-tip highlighter stroke behind its children when they scroll into view.\n\nLook:\n- The stroke is NOT a CSS background colour. Build an SVG as a data URL: viewBox 0 0 200 40, preserveAspectRatio=\"none\", one rect (x 3, y 5, width 194, height 30, rx 2) filled with the highlight colour at the given opacity, skewed about -1.5 degrees, with a filter of feTurbulence (fractalNoise, baseFrequency \"0.03 0.11\", 2 octaves, a per-instance seed) feeding feDisplacementMap (scale 8) so the edges are ragged like a marker. Set it as background-image on the span with background-repeat no-repeat and background-position left center. Build the string with concatenation and encodeURIComponent; validate the colour with a strict hex regex and fall back to #d6ff00, since the string is a data URL.\n- The reveal is a transition on background-size from \"0% 100%\" to \"100% 100%\", duration 900ms (prop), delay prop, easing cubic-bezier(0.22, 1, 0.36, 1). Use box-decoration-break: clone (with the -webkit- prefix) so a phrase that wraps gets a stroke on every line. Pad the span 0.04em vertically and 0.14em horizontally with a matching negative horizontal margin so the ink overshoots the letters slightly.\n\nBehaviour:\n- Props: children, colour (hex), opacity (0–1, default 0.82), duration (ms), delay (ms), active (boolean | undefined), once (boolean, default true), className.\n- When `active` is undefined, observe the span with an IntersectionObserver at threshold 0.6; when it intersects, mark it seen and, if `once`, disconnect the observer. If `once` is false, unmark when it leaves. Read entries[entries.length - 1], not the first entry. Disconnect on unmount.\n- When `active` is a boolean, it drives the stroke directly and no observer is attached.\n- Derive a stable per-instance seed from useId (fold the characters into a number) so two phrases on one page do not share the same edge.\n- Respect prefers-reduced-motion live: read the media query through useSyncExternalStore (server snapshot false) and, when it matches, set transition to none so the stroke is simply present.\n- Expose data-highlighted=\"true|false\" on the span for styling hooks.\n- No React state written during render; no setState inside the effect body itself (only inside the observer callback).\n\nAccessibility: the stroke is a background image, so nothing is added to the accessibility tree and the text remains selectable and readable. Note in a comment that highlighter is a light-ground device and the text should stay dark.\n\nOutput one self-contained \"use client\" component with no dependencies beyond React.","license":"https://viberdy.dev/license"}}