{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "highlighter-text",
  "title": "Highlighter Text",
  "description": "A mark drawn over text that is already readable, line by line, as a marker band, an underline or a hand-drawn stroke or outline.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "utils",
    "https://miseui.junsu4621.workers.dev/r/motion.json"
  ],
  "files": [
    {
      "path": "registry/miseui/ui/highlighter-text.tsx",
      "content": "import type * as React from \"react\"\nimport { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\"\nimport { useInView, useReducedMotion } from \"motion/react\"\nimport { ANCHOR_CLASS, LINE_MARK, type HighlighterVariant } from \"@/registry/miseui/ui/highlighter-marks\"\nimport { lineSchedule, mergeLineRects, sameLines, scheduleSeconds, seedFromText, type LineRect } from \"@/registry/miseui/ui/highlighter-math\"\nimport { cn } from \"@/registry/miseui/lib/utils\"\n\ntype HighlighterEffect = \"sequence\"\ntype HighlighterTrigger = \"view\" | \"mount\"\ntype HighlighterGroupTag = \"p\" | \"div\" | \"li\" | \"blockquote\" | \"span\"\n\nconst VIEW_MARGIN = \"0px 0px -10% 0px\"\nconst INLINE_DISPLAYS: ReadonlySet<string> = new Set([\"inline\", \"contents\"])\nconst DEFAULT_SEED_TEXT = \"mise\"\n/** A little past the last line's end, so a slow settle is never cut to a stop when marks switch to instant placement. */\nconst SETTLE_MARGIN_SECONDS = 0.6\n\ninterface GroupContextValue {\n  /** Adds a mark and returns how to take it out again. */\n  join: (element: HTMLElement) => () => void\n  finish: (element: HTMLElement) => void\n  started: boolean\n  /** The mark whose turn it is. */\n  current: HTMLElement | null\n  finished: ReadonlySet<HTMLElement>\n}\n\nconst GroupContext = createContext<GroupContextValue | null>(null)\n\n/** A ResizeObserver reports nothing for an inline box, so it watches the block that decides where lines break. */\nfunction closestBlock(element: HTMLElement): HTMLElement {\n  const parent = element.parentElement\n  if (!parent) return element\n  return INLINE_DISPLAYS.has(getComputedStyle(parent).display) ? closestBlock(parent) : parent\n}\n\n/** The anchor is measured too: a Range gives viewport coordinates and the marks are placed from the anchor. */\nfunction measureLines(anchor: HTMLElement, text: HTMLElement) {\n  const range = document.createRange()\n  range.selectNodeContents(text)\n  return mergeLineRects(Array.from(range.getClientRects()), anchor.getBoundingClientRect())\n}\n\nfunction useMeasuredLines(mark: HTMLElement | null, anchorRef: React.RefObject<HTMLElement | null>, textRef: React.RefObject<HTMLElement | null>) {\n  const [lines, setLines] = useState<readonly LineRect[]>([])\n  useLayoutEffect(() => {\n    const anchor = anchorRef.current\n    const text = textRef.current\n    if (!mark || !anchor || !text) return\n    const measure = () => {\n      const next = measureLines(anchor, text)\n      setLines((current) => (sameLines(current, next) ? current : next))\n    }\n    measure()\n    const observer = new ResizeObserver(measure)\n    observer.observe(closestBlock(mark))\n    // Lines rebreak when a web font arrives, without the block changing size.\n    const fonts = document.fonts\n    fonts?.addEventListener(\"loadingdone\", measure)\n    return () => {\n      observer.disconnect()\n      fonts?.removeEventListener(\"loadingdone\", measure)\n    }\n  }, [mark, anchorRef, textRef])\n  return lines\n}\n\n/** Joins the surrounding group, if any, and reports when this mark's turn has run. */\nfunction useGroupTurn(mark: HTMLElement | null, totalSeconds: number) {\n  const group = useContext(GroupContext)\n  const join = group?.join\n  const finish = group?.finish\n  useLayoutEffect(() => {\n    if (!join || !mark) return\n    return join(mark)\n  }, [join, mark])\n  const active = group !== null && mark !== null && group.started && (group.current === mark || group.finished.has(mark))\n  useEffect(() => {\n    if (!finish || !mark || !active) return\n    const timer = setTimeout(() => finish(mark), totalSeconds * 1000)\n    return () => clearTimeout(timer)\n  }, [finish, mark, active, totalSeconds])\n  return { inGroup: group !== null, active }\n}\n\ntype HighlighterTextProps = Omit<React.ComponentProps<\"mark\">, \"ref\"> & {\n  /** `marker` a soft band swiped line by line, `underline` a thin line under each line, `sketch` a hand-drawn stroke, `box` a hand-drawn outline per line. */\n  variant?: HighlighterVariant\n  /** `view` draws once when first seen, `mount` right away. Inside a HighlighterGroup the group decides. */\n  trigger?: HighlighterTrigger\n  /** Seconds before drawing starts. */\n  delay?: number\n  /** Picks the shape of the hand-drawn strokes. Defaults to one derived from the text. */\n  seed?: number\n}\n\nfunction HighlighterText({ variant = \"marker\", trigger = \"view\", delay = 0, seed, className, children, ...props }: HighlighterTextProps) {\n  const reduceMotion = useReducedMotion() ?? false\n  const markRef = useRef<HTMLElement>(null)\n  // Also in state: the group and the measuring both have to run again once the element exists.\n  const [mark, setMark] = useState<HTMLElement | null>(null)\n  const attachMark = useCallback((element: HTMLElement | null) => {\n    markRef.current = element\n    setMark(element)\n  }, [])\n  const anchorRef = useRef<HTMLSpanElement>(null)\n  const textRef = useRef<HTMLSpanElement>(null)\n  const lines = useMeasuredLines(mark, anchorRef, textRef)\n  const timings = useMemo(() => lineSchedule(lines).map((timing) => ({ ...timing, delay: timing.delay + delay })), [lines, delay])\n  const seen = useInView(markRef, { once: true, margin: VIEW_MARGIN })\n  const total = scheduleSeconds(timings)\n  const { inGroup, active } = useGroupTurn(mark, total)\n  const shown = reduceMotion || (inGroup ? active : trigger === \"mount\" || seen)\n  // Once drawn, a resize only moves the marks. A line that appears from a rewrap must not draw itself again.\n  const [settled, setSettled] = useState(false)\n  useEffect(() => {\n    if (!shown || settled || lines.length === 0) return\n    const timer = setTimeout(() => setSettled(true), (total + SETTLE_MARGIN_SECONDS) * 1000)\n    return () => clearTimeout(timer)\n  }, [shown, settled, total, lines.length])\n  const textSeed = seed ?? seedFromText(typeof children === \"string\" ? children : DEFAULT_SEED_TEXT)\n  const LineMark = LINE_MARK[variant]\n  return (\n    <mark\n      {...props}\n      ref={attachMark}\n      data-slot=\"highlighter-text\"\n      data-variant={variant}\n      data-drawn={shown ? \"true\" : \"false\"}\n      // Isolate gives the marks a stacking context of their own, so -z-10 lands behind these letters and not behind the page.\n      className={cn(\"isolate bg-transparent text-inherit forced-colors:bg-[Mark] forced-colors:text-[MarkText]\", className)}\n    >\n      <span ref={anchorRef} aria-hidden=\"true\" data-slot=\"highlighter-marks\" className={ANCHOR_CLASS}>\n        {lines.map((line, index) => (\n          <LineMark key={index} line={line} timing={timings[index]} shown={shown} settled={settled || reduceMotion} seed={textSeed} index={index} />\n        ))}\n      </span>\n      <span ref={textRef} data-slot=\"highlighter-words\">\n        {children}\n      </span>\n    </mark>\n  )\n}\n\n/** Document order, not join order: a mark added later in the paragraph still takes its turn where it stands. */\nfunction inDocumentOrder(elements: readonly HTMLElement[]) {\n  return [...elements].sort((a, b) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1))\n}\n\ntype HighlighterGroupProps = React.HTMLAttributes<HTMLElement> & {\n  as?: HighlighterGroupTag\n  /** `view` starts the first mark when the group is seen, `mount` right away. */\n  trigger?: HighlighterTrigger\n}\n\n/** The `sequence` effect: the marks inside draw one after another, in reading order, starting when the group is seen. */\nfunction HighlighterGroup({ as: Tag = \"p\", trigger = \"view\", className, children, ...props }: HighlighterGroupProps) {\n  const ref = useRef<HTMLElement>(null)\n  const seen = useInView(ref, { once: true, margin: VIEW_MARGIN })\n  const started = trigger === \"mount\" || seen\n  const [members, setMembers] = useState<readonly HTMLElement[]>([])\n  const [finished, setFinished] = useState<ReadonlySet<HTMLElement>>(new Set())\n  const join = useCallback((element: HTMLElement) => {\n    setMembers((current) => inDocumentOrder([...current, element]))\n    return () => setMembers((current) => current.filter((member) => member !== element))\n  }, [])\n  const finish = useCallback((element: HTMLElement) => setFinished((current) => new Set([...current, element])), [])\n  const current = members.find((member) => !finished.has(member)) ?? null\n  const context = useMemo<GroupContextValue>(() => ({ join, finish, started, current, finished }), [join, finish, started, current, finished])\n  return (\n    <GroupContext.Provider value={context}>\n      {/* TypeScript cannot match one ref to a union of tags, and every tag here is an HTMLElement. */}\n      <Tag {...props} ref={ref as React.RefObject<never>} data-slot=\"highlighter-group\" data-effect=\"sequence\" className={className}>\n        {children}\n      </Tag>\n    </GroupContext.Provider>\n  )\n}\n\nexport { HighlighterGroup, HighlighterText, type HighlighterEffect, type HighlighterGroupProps, type HighlighterTextProps, type HighlighterTrigger, type HighlighterVariant }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/miseui/ui/highlighter-marks.tsx",
      "content": "import type * as React from \"react\"\nimport { motion } from \"motion/react\"\nimport { SPRING_DEFAULT } from \"@/registry/miseui/lib/motion\"\nimport { sketchBoxPath, sketchStrokePath, type LineRect, type LineTiming } from \"@/registry/miseui/ui/highlighter-math\"\n\ntype HighlighterVariant = \"marker\" | \"underline\" | \"sketch\" | \"box\"\n\nconst INSTANT = { duration: 0 } as const\n/** Room around the words for the outline, so it does not touch the letters. */\nconst BOX_PADDING_X = 3\nconst BOX_PADDING_Y = 2\n/** How far past the bounding box a stroke may wander, so the svg never cuts it. */\nconst STROKE_ROOM = 8\nconst STROKE_WIDTH = 2\n\ninterface LineMarkProps {\n  line: LineRect\n  timing: LineTiming\n  /** False holds the mark undrawn. */\n  shown: boolean\n  /** Already drawn once: a re-measure places it at once instead of drawing it again. */\n  settled: boolean\n  /** Picks the hand-drawn shape. Each line adds its index, so two lines of one mark never share a stroke. */\n  seed: number\n  index: number\n}\n\nfunction drawTransition({ timing, settled }: Pick<LineMarkProps, \"timing\" | \"settled\">) {\n  return settled ? INSTANT : { ...SPRING_DEFAULT, duration: timing.duration, delay: timing.delay }\n}\n\nconst hiddenBand = { scaleX: 0 }\nconst shownBand = { scaleX: 1 }\n\n/** Swiped across, not faded: the eye follows the band along the words, which is the reading order. */\nfunction MarkerBand({ line, timing, shown, settled }: LineMarkProps) {\n  return (\n    <motion.span\n      data-slot=\"highlighter-line\"\n      className=\"absolute block origin-left rounded-[0.16em] bg-mise-soft rtl:origin-right\"\n      style={{ left: line.left - 2, top: line.top + line.height * 0.06, width: line.width + 4, height: line.height * 0.88 }}\n      initial={settled ? false : hiddenBand}\n      animate={shown ? shownBand : hiddenBand}\n      transition={drawTransition({ timing, settled })}\n    />\n  )\n}\n\nfunction UnderlineStroke({ line, timing, shown, settled }: LineMarkProps) {\n  return (\n    <motion.span\n      data-slot=\"highlighter-line\"\n      className=\"absolute block h-0.5 origin-left rounded-full bg-mise rtl:origin-right\"\n      style={{ left: line.left, top: line.top + line.height - 1, width: line.width }}\n      initial={settled ? false : hiddenBand}\n      animate={shown ? shownBand : hiddenBand}\n      transition={drawTransition({ timing, settled })}\n    />\n  )\n}\n\ninterface DrawnPathProps extends LineMarkProps {\n  path: string\n  /** Where the path's 0,0 sits relative to the anchor. */\n  x: number\n  y: number\n  width: number\n  height: number\n}\n\nconst hiddenPath = { pathLength: 0, opacity: 0 }\nconst shownPath = { pathLength: 1, opacity: 1 }\n\nfunction DrawnPath({ path, x, y, width, height, timing, shown, settled }: DrawnPathProps) {\n  const transition = drawTransition({ timing, settled })\n  return (\n    <svg\n      data-slot=\"highlighter-line\"\n      className=\"absolute block overflow-visible fill-none stroke-mise\"\n      style={{ left: x - STROKE_ROOM, top: y - STROKE_ROOM }}\n      width={width + STROKE_ROOM * 2}\n      height={height + STROKE_ROOM * 2}\n      viewBox={`${-STROKE_ROOM} ${-STROKE_ROOM} ${width + STROKE_ROOM * 2} ${height + STROKE_ROOM * 2}`}\n    >\n      <motion.path\n        d={path}\n        strokeWidth={STROKE_WIDTH}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        initial={settled ? false : hiddenPath}\n        animate={shown ? shownPath : hiddenPath}\n        // A round cap at length zero is still a visible dot, so opacity holds it back until the stroke actually starts.\n        transition={settled ? INSTANT : { pathLength: transition, opacity: { duration: 0.01, delay: timing.delay } }}\n      />\n    </svg>\n  )\n}\n\nfunction SketchStroke(props: LineMarkProps) {\n  const { line, seed, index } = props\n  return (\n    <DrawnPath\n      {...props}\n      path={sketchStrokePath(line.width, seed + index)}\n      x={line.left}\n      y={line.top + line.height}\n      width={line.width}\n      height={0}\n    />\n  )\n}\n\nfunction SketchBox(props: LineMarkProps) {\n  const { line, seed, index } = props\n  const width = line.width + BOX_PADDING_X * 2\n  const height = line.height + BOX_PADDING_Y * 2\n  return (\n    <DrawnPath\n      {...props}\n      path={sketchBoxPath(width, height, seed + index)}\n      x={line.left - BOX_PADDING_X}\n      y={line.top - BOX_PADDING_Y}\n      width={width}\n      height={height}\n    />\n  )\n}\n\nconst LINE_MARK: Record<HighlighterVariant, (props: LineMarkProps) => React.JSX.Element> = {\n  marker: MarkerBand,\n  underline: UnderlineStroke,\n  sketch: SketchStroke,\n  box: SketchBox,\n}\n\n/** Behind the text, in the stacking context of the mark, so no stroke ever lowers the contrast of a letter. */\nconst ANCHOR_CLASS = \"pointer-events-none absolute -z-10 size-0 overflow-visible select-none forced-colors:hidden\"\n\nexport { ANCHOR_CLASS, LINE_MARK, type HighlighterVariant, type LineMarkProps }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/miseui/ui/highlighter-math.ts",
      "content": "/** One drawn line of text, in pixels from the mark's anchor. */\ninterface LineRect {\n  left: number\n  top: number\n  width: number\n  height: number\n}\n\ninterface BoxLike {\n  left: number\n  top: number\n  right: number\n  bottom: number\n}\n\ninterface LineTiming {\n  /** Seconds after the mark starts. */\n  delay: number\n  /** Seconds for this line. */\n  duration: number\n}\n\nconst MIN_LINE_SECONDS = 0.28\nconst MAX_LINE_SECONDS = 0.6\n/** A hand crosses roughly this many pixels in a second, so short lines do not take as long as long ones. */\nconst DRAW_PIXELS_PER_SECOND = 620\n/** The next line starts as the last one is nearly done: a spring has done most of its travel by then. */\nconst LINE_HANDOVER = 0.72\n\nconst round = (value: number) => Math.round(value * 10) / 10\n\n/**\n * A Range reports one box per inline fragment, so a phrase with a <strong> inside gives several boxes on one line and\n * the same line twice when text and element both report. Whatever overlaps vertically by half is one line.\n */\nfunction mergeLineRects(boxes: readonly BoxLike[], origin: { left: number; top: number }): readonly LineRect[] {\n  const visible = boxes.filter((box) => box.right > box.left && box.bottom > box.top)\n  const lines = visible.reduce<readonly BoxLike[]>((merged, box) => {\n    const last = merged[merged.length - 1]\n    if (!last) return [box]\n    const overlap = Math.min(last.bottom, box.bottom) - Math.max(last.top, box.top)\n    const sameLine = overlap > Math.min(last.bottom - last.top, box.bottom - box.top) / 2\n    if (!sameLine) return [...merged, box]\n    const joined = {\n      left: Math.min(last.left, box.left),\n      top: Math.min(last.top, box.top),\n      right: Math.max(last.right, box.right),\n      bottom: Math.max(last.bottom, box.bottom),\n    }\n    return [...merged.slice(0, -1), joined]\n  }, [])\n  return lines.map((line) => ({\n    left: round(line.left - origin.left),\n    top: round(line.top - origin.top),\n    width: round(line.right - line.left),\n    height: round(line.bottom - line.top),\n  }))\n}\n\nfunction sameLines(a: readonly LineRect[], b: readonly LineRect[]) {\n  return a.length === b.length && a.every((line, index) => line.left === b[index].left && line.top === b[index].top && line.width === b[index].width && line.height === b[index].height)\n}\n\n/** Reading order, one line handing over to the next, each taking time for its own width. */\nfunction lineSchedule(lines: readonly LineRect[]): readonly LineTiming[] {\n  return lines.reduce<{ timings: readonly LineTiming[]; next: number }>(\n    ({ timings, next }, line) => {\n      const duration = Math.min(MAX_LINE_SECONDS, Math.max(MIN_LINE_SECONDS, line.width / DRAW_PIXELS_PER_SECOND))\n      return { timings: [...timings, { delay: next, duration }], next: next + duration * LINE_HANDOVER }\n    },\n    { timings: [], next: 0 },\n  ).timings\n}\n\n/** Seconds until a group may start the next mark. */\nfunction scheduleSeconds(timings: readonly LineTiming[]) {\n  const last = timings[timings.length - 1]\n  return last ? last.delay + last.duration * LINE_HANDOVER : 0\n}\n\n/** The same text always gets the same stroke, so a server render, a re-measure and a replay all agree. */\nfunction seedFromText(text: string) {\n  return Array.from(text).reduce((hash, character) => Math.imul(hash ^ (character.codePointAt(0) ?? 0), 16777619) >>> 0, 2166136261)\n}\n\n/** A pure step of mulberry32, returning a value in 0..1 for this seed and position. */\nfunction seededUnit(seed: number, position: number) {\n  const mixed = (seed + Math.imul(position + 1, 0x6d2b79f5)) >>> 0\n  const first = Math.imul(mixed ^ (mixed >>> 15), mixed | 1)\n  const second = (first + Math.imul(first ^ (first >>> 7), first | 61)) ^ first\n  return ((second ^ (second >>> 14)) >>> 0) / 4294967296\n}\n\n/** Signed wobble within -reach..reach. */\nconst wobble = (seed: number, position: number, reach: number) => round((seededUnit(seed, position) * 2 - 1) * reach)\n\nconst SEGMENT_PIXELS = 110\nconst STROKE_WOBBLE = 1.4\n\n/** A single confident stroke along y = 0: a little past each end, never quite straight, with one small lean over its length. */\nfunction sketchStrokePath(width: number, seed: number) {\n  const segments = Math.max(1, Math.min(6, Math.round(width / SEGMENT_PIXELS)))\n  const startX = wobble(seed, 0, 2)\n  const endX = round(width + wobble(seed, 1, 2))\n  const lean = wobble(seed, 2, 1.5)\n  const span = (endX - startX) / segments\n  const steps = Array.from({ length: segments }, (_, step) => {\n    const x = startX + span * (step + 1)\n    const y = step === segments - 1 ? lean : wobble(seed, 3 + step * 2, STROKE_WOBBLE)\n    const controlX = round(x - span / 2)\n    const controlY = wobble(seed, 4 + step * 2, STROKE_WOBBLE * 1.6)\n    return `Q${controlX} ${controlY} ${round(x)} ${y}`\n  })\n  return `M${startX} ${wobble(seed, 3, 1)} ${steps.join(\" \")}`\n}\n\nconst CORNER = 6\nconst BOX_WOBBLE = 1.2\n/** Past the starting corner, the way a pen closes a circle by running over its own start. */\nconst BOX_OVERRUN = 14\n\n/** A loop drawn clockwise around a box from 0,0 to width,height, with soft corners and an end that overruns its start. */\nfunction sketchBoxPath(width: number, height: number, seed: number) {\n  const corner = Math.min(CORNER, height / 2, width / 2)\n  const shift = (position: number) => wobble(seed, position, BOX_WOBBLE)\n  const right = round(width + shift(0))\n  const bottom = round(height + shift(1))\n  const overrun = Math.min(BOX_OVERRUN, width / 3)\n  return [\n    `M${round(corner + shift(2))} ${shift(3)}`,\n    `Q${round(width / 2)} ${shift(4)} ${round(right - corner)} ${shift(5)}`,\n    `Q${right} 0 ${right} ${round(corner)}`,\n    `L${round(right + shift(6))} ${round(bottom - corner)}`,\n    `Q${right} ${bottom} ${round(right - corner)} ${bottom}`,\n    `Q${round(width / 2)} ${round(bottom + shift(7))} ${round(corner)} ${round(bottom + shift(8))}`,\n    `Q0 ${bottom} ${shift(9)} ${round(bottom - corner)}`,\n    `L${shift(10)} ${round(corner)}`,\n    `Q0 ${shift(11)} ${round(corner)} ${shift(12)}`,\n    `L${round(corner + overrun)} ${shift(13)}`,\n  ].join(\" \")\n}\n\nexport {\n  lineSchedule,\n  mergeLineRects,\n  sameLines,\n  scheduleSeconds,\n  seededUnit,\n  seedFromText,\n  sketchBoxPath,\n  sketchStrokePath,\n  type BoxLike,\n  type LineRect,\n  type LineTiming,\n}\n",
      "type": "registry:ui"
    }
  ],
  "categories": [
    "text"
  ],
  "type": "registry:ui"
}