{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "motion-highlighter",
  "title": "Highlighter",
  "description": "Hand-drawn marks on text, a marker band, an underline, a box, a circle or a strike, drawn in when the text comes into view.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "components/core/highlighter.tsx",
      "content": "'use client';\nimport { cn } from '@/lib/utils';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { motion, useInView, type TargetAndTransition } from 'motion/react';\nimport {\n  useEffect,\n  useId,\n  useRef,\n  useState,\n  type ReactNode,\n  type RefObject,\n} from 'react';\n\nexport type HighlighterAction =\n  'highlight' | 'underline' | 'box' | 'circle' | 'strike';\n\nexport type HighlighterTone =\n  'primary' | 'success' | 'warning' | 'info' | 'destructive';\n\ntype Point = {\n  x: number;\n  y: number;\n};\n\ntype Box = {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n};\n\ntype Random = () => number;\n\ntype Stroke = {\n  key: string;\n  path: string;\n  width: number;\n  delay: number;\n  duration: number;\n};\n\ntype StrokeShape = {\n  path: string;\n  width: number;\n};\n\ntype DrawSlot = {\n  start: number;\n  length: number;\n};\n\nconst MODULUS = 2147483647;\n\nconst LAST_STATE = MODULUS - 1;\n\nconst MULTIPLIER = 16807;\n\nconst EASE_PEN: [number, number, number, number] = [0.65, 0, 0.35, 1];\n\nconst EASE_OUT_STRONG: [number, number, number, number] = [0.23, 1, 0.32, 1];\n\n/** With two passes, the second starts while the first is still drawing, as a hand going over it again. */\nconst FIRST_PASS_SHARE = 0.7;\n\nconst SECOND_PASS_OFFSET = 0.3;\n\nconst ERASE_DURATION = 0.15;\n\nconst BAND_OPACITY = 0.35;\n\nconst BAND_THICKNESS = 0.8;\n\nconst BAND_CENTRE = 0.55;\n\nconst STRIKE_LINE = 0.52;\n\nconst CIRCLE_STEPS = 16;\n\nconst START_ANGLE = Math.PI * -0.62;\n\nconst FULL_TURN_AND_OVERLAP = Math.PI * 2.15;\n\nconst IN_VIEW_MARGIN = '0px 0px -10% 0px';\n\n/** Marker fills behind the text: the fill tokens at a low opacity read in both themes. */\nconst BAND_TONES: Record<HighlighterTone, string> = {\n  primary: 'text-primary',\n  success: 'text-success',\n  warning: 'text-warning',\n  info: 'text-info',\n  destructive: 'text-destructive',\n};\n\n/** Pen lines on the page: the text pairs of each status, measured for both themes. */\nconst LINE_TONES: Record<HighlighterTone, string> = {\n  primary: 'text-primary',\n  success: 'text-success-foreground',\n  warning: 'text-warning-foreground',\n  info: 'text-info-foreground',\n  destructive: 'text-destructive-ink',\n};\n\nconst DEFAULT_PADDING: Record<HighlighterAction, number> = {\n  highlight: 2,\n  underline: 2,\n  box: 5,\n  circle: 8,\n  strike: 2,\n};\n\nconst HIDDEN: TargetAndTransition = { pathLength: 0, opacity: 0 };\n\nfunction seedOf(text: string) {\n  let hash = 2166136261;\n  for (const character of text) {\n    const code = character.charCodeAt(0);\n    hash ^= code;\n    hash = Math.imul(hash, 16777619);\n  }\n  return hash >>> 0;\n}\n\n/** A seeded generator, so a mark keeps its shape when the text re-wraps. */\nfunction randomOf(seed: number): Random {\n  let state = seed % MODULUS;\n  if (state <= 0) {\n    state += LAST_STATE;\n  }\n  return () => {\n    const product = state * MULTIPLIER;\n    state = product % MODULUS;\n    const offset = state - 1;\n    return offset / LAST_STATE;\n  };\n}\n\nfunction jitterOf(random: Random, amount: number) {\n  const sample = random();\n  const doubled = sample * 2;\n  const centred = doubled - 1;\n  return centred * amount;\n}\n\nfunction roundedOf(value: number) {\n  const scaled = value * 100;\n  const rounded = Math.round(scaled);\n  return rounded / 100;\n}\n\nfunction pointTextOf(point: Point) {\n  const x = roundedOf(point.x);\n  const y = roundedOf(point.y);\n  return `${x} ${y}`;\n}\n\nfunction nudgedOf(point: Point, random: Random, amount: number): Point {\n  const offsetX = jitterOf(random, amount);\n  const offsetY = jitterOf(random, amount);\n  return { x: point.x + offsetX, y: point.y + offsetY };\n}\n\nfunction horizontalStrokeOf(\n  left: number,\n  right: number,\n  y: number,\n  random: Random,\n  wobble: number\n) {\n  const start = nudgedOf({ x: left, y }, random, wobble);\n  const end = nudgedOf({ x: right, y }, random, wobble);\n  const span = end.x - start.x;\n  const third = span / 3;\n  const firstX = start.x + third;\n  const secondX = end.x - third;\n  const firstLift = jitterOf(random, wobble);\n  const secondLift = jitterOf(random, wobble);\n  const firstY = y + firstLift;\n  const secondY = y + secondLift;\n  const startText = pointTextOf(start);\n  const firstText = pointTextOf({ x: firstX, y: firstY });\n  const secondText = pointTextOf({ x: secondX, y: secondY });\n  const endText = pointTextOf(end);\n  return `M ${startText} C ${firstText}, ${secondText}, ${endText}`;\n}\n\nfunction bowedSideOf(from: Point, to: Point, random: Random) {\n  const sumX = from.x + to.x;\n  const sumY = from.y + to.y;\n  const middle = { x: sumX / 2, y: sumY / 2 };\n  const control = nudgedOf(middle, random, 1.5);\n  const controlText = pointTextOf(control);\n  const endText = pointTextOf(to);\n  return `Q ${controlText} ${endText}`;\n}\n\nfunction boxPathOf(box: Box, padding: number, random: Random) {\n  const left = box.x - padding;\n  const top = box.y - padding;\n  const widthWithPadding = box.width + padding;\n  const heightWithPadding = box.height + padding;\n  const right = box.x + widthWithPadding;\n  const bottom = box.y + heightWithPadding;\n  const topLeft = nudgedOf({ x: left, y: top }, random, 1.5);\n  const topRight = nudgedOf({ x: right, y: top }, random, 1.5);\n  const bottomRight = nudgedOf({ x: right, y: bottom }, random, 1.5);\n  const bottomLeft = nudgedOf({ x: left, y: bottom }, random, 1.5);\n  const overshoot = top - 3;\n  const closing = nudgedOf({ x: left, y: overshoot }, random, 1.5);\n  const sides = [\n    `M ${pointTextOf(topLeft)}`,\n    bowedSideOf(topLeft, topRight, random),\n    bowedSideOf(topRight, bottomRight, random),\n    bowedSideOf(bottomRight, bottomLeft, random),\n    bowedSideOf(bottomLeft, closing, random),\n  ];\n  return sides.join(' ');\n}\n\nfunction controlAfterOf(previous: Point, current: Point, next: Point): Point {\n  const deltaX = next.x - previous.x;\n  const deltaY = next.y - previous.y;\n  const stepX = deltaX / 6;\n  const stepY = deltaY / 6;\n  return { x: current.x + stepX, y: current.y + stepY };\n}\n\nfunction controlBeforeOf(current: Point, next: Point, after: Point): Point {\n  const deltaX = after.x - current.x;\n  const deltaY = after.y - current.y;\n  const stepX = deltaX / 6;\n  const stepY = deltaY / 6;\n  return { x: next.x - stepX, y: next.y - stepY };\n}\n\n/** A curve through every point (Catmull-Rom written as cubic Bézier segments). */\nfunction smoothPathOf(points: readonly Point[]) {\n  const segments = [`M ${pointTextOf(points[0])}`];\n  const lastIndex = points.length - 1;\n  for (let index = 0; index < lastIndex; index += 1) {\n    const current = points[index];\n    const next = points[index + 1];\n    const previous = points[index - 1] ?? current;\n    const after = points[index + 2] ?? next;\n    const firstControl = controlAfterOf(previous, current, next);\n    const secondControl = controlBeforeOf(current, next, after);\n    const firstText = pointTextOf(firstControl);\n    const secondText = pointTextOf(secondControl);\n    const nextText = pointTextOf(next);\n    segments.push(`C ${firstText}, ${secondText}, ${nextText}`);\n  }\n  return segments.join(' ');\n}\n\n/** A loop that starts at the upper left, goes once around and runs a little past its start, slightly wider. */\nfunction circlePathOf(box: Box, padding: number, random: Random) {\n  const halfWidth = box.width / 2;\n  const halfHeight = box.height / 2;\n  const middleX = box.x + halfWidth;\n  const middleY = box.y + halfHeight;\n  const centre = nudgedOf({ x: middleX, y: middleY }, random, 1);\n  const widenedHalf = halfWidth * 1.08;\n  const radiusX = widenedHalf + padding;\n  const radiusY = halfHeight + padding;\n  const startJitter = jitterOf(random, 0.15);\n  const startAngle = START_ANGLE + startJitter;\n  const sweepJitter = jitterOf(random, 0.1);\n  const sweep = FULL_TURN_AND_OVERLAP + sweepJitter;\n  const points: Point[] = [];\n  for (let step = 0; step <= CIRCLE_STEPS; step += 1) {\n    const progress = step / CIRCLE_STEPS;\n    const turned = sweep * progress;\n    const angle = startAngle + turned;\n    const drift = progress * 0.07;\n    const wobble = jitterOf(random, 0.035);\n    const growth = drift + wobble;\n    const scale = 1 + growth;\n    const reachX = radiusX * scale;\n    const reachY = radiusY * scale;\n    const offsetX = Math.cos(angle) * reachX;\n    const offsetY = Math.sin(angle) * reachY;\n    const x = centre.x + offsetX;\n    const y = centre.y + offsetY;\n    points.push({ x, y });\n  }\n  return smoothPathOf(points);\n}\n\nfunction shapeOf(\n  action: HighlighterAction,\n  box: Box,\n  padding: number,\n  strokeWidth: number,\n  random: Random\n): StrokeShape {\n  const left = box.x - padding;\n  const rightEdge = box.x + box.width;\n  const right = rightEdge + padding;\n  if (action === 'highlight') {\n    const centreOffset = box.height * BAND_CENTRE;\n    const centre = box.y + centreOffset;\n    const thickness = box.height * BAND_THICKNESS;\n    const path = horizontalStrokeOf(left, right, centre, random, 1);\n    return { path, width: thickness };\n  }\n  if (action === 'underline') {\n    const bottom = box.y + box.height;\n    const line = bottom + padding;\n    const path = horizontalStrokeOf(left, right, line, random, 1.5);\n    return { path, width: strokeWidth };\n  }\n  if (action === 'strike') {\n    const lineOffset = box.height * STRIKE_LINE;\n    const line = box.y + lineOffset;\n    const path = horizontalStrokeOf(left, right, line, random, 1.2);\n    return { path, width: strokeWidth };\n  }\n  if (action === 'box') {\n    const path = boxPathOf(box, padding, random);\n    return { path, width: strokeWidth };\n  }\n  const path = circlePathOf(box, padding, random);\n  return { path, width: strokeWidth };\n}\n\n/** Wrapped lines are drawn one after the other, each for its share of the whole length. */\nfunction slotsOf(boxes: readonly Box[], duration: number, delay: number) {\n  let totalWidth = 0;\n  for (const box of boxes) {\n    totalWidth += box.width;\n  }\n  const slots: DrawSlot[] = [];\n  let cursor = delay;\n  for (const box of boxes) {\n    const share = box.width / totalWidth;\n    const length = duration * share;\n    slots.push({ start: cursor, length });\n    cursor += length;\n  }\n  return slots;\n}\n\nfunction passTimingOf(slot: DrawSlot, pass: number, passCount: number) {\n  if (passCount === 1) {\n    return { delay: slot.start, duration: slot.length };\n  }\n  const duration = slot.length * FIRST_PASS_SHARE;\n  const offset = slot.length * SECOND_PASS_OFFSET;\n  const passOffset = offset * pass;\n  const delay = slot.start + passOffset;\n  return { delay, duration };\n}\n\nfunction strokesOf(\n  action: HighlighterAction,\n  boxes: readonly Box[],\n  options: {\n    seed: number;\n    padding: number;\n    strokeWidth: number;\n    passCount: number;\n    duration: number;\n    delay: number;\n  }\n) {\n  const random = randomOf(options.seed);\n  const slots = slotsOf(boxes, options.duration, options.delay);\n  const strokes: Stroke[] = [];\n  boxes.forEach((box, boxIndex) => {\n    const slot = slots[boxIndex];\n    for (let pass = 0; pass < options.passCount; pass += 1) {\n      const shape = shapeOf(\n        action,\n        box,\n        options.padding,\n        options.strokeWidth,\n        random\n      );\n      const timing = passTimingOf(slot, pass, options.passCount);\n      strokes.push({\n        key: `${boxIndex}-${pass}`,\n        path: shape.path,\n        width: shape.width,\n        delay: timing.delay,\n        duration: timing.duration,\n      });\n    }\n  });\n  return strokes;\n}\n\nfunction isInlineDisplay(element: Element) {\n  const display = getComputedStyle(element).display;\n  return display.startsWith('inline');\n}\n\n/** The first block around the text: its size changes whenever the text may wrap differently. */\nfunction blockAncestorOf(element: HTMLElement) {\n  let current = element.parentElement;\n  while (current) {\n    if (!isInlineDisplay(current)) {\n      return current;\n    }\n    current = current.parentElement;\n  }\n  return document.body;\n}\n\nfunction boxesOf(root: HTMLElement, svg: SVGSVGElement) {\n  const origin = svg.getBoundingClientRect();\n  const fragments = Array.from(root.getClientRects());\n  const boxes: Box[] = [];\n  for (const fragment of fragments) {\n    const isEmpty = fragment.width < 1;\n    if (isEmpty) {\n      continue;\n    }\n    const x = fragment.left - origin.left;\n    const y = fragment.top - origin.top;\n    boxes.push({ x, y, width: fragment.width, height: fragment.height });\n  }\n  return boxes;\n}\n\nfunction isSameBox(first: Box, second: Box) {\n  const isSameX = first.x === second.x;\n  const isSameY = first.y === second.y;\n  const isSameWidth = first.width === second.width;\n  const isSameHeight = first.height === second.height;\n  return isSameX && isSameY && isSameWidth && isSameHeight;\n}\n\nfunction haveSameBoxes(first: readonly Box[], second: readonly Box[]) {\n  if (first.length !== second.length) {\n    return false;\n  }\n  return first.every((box, index) => isSameBox(box, second[index]));\n}\n\nfunction keepIfSame(current: Box[], next: Box[]) {\n  if (haveSameBoxes(current, next)) {\n    return current;\n  }\n  return next;\n}\n\n/** One box per line the text runs over, in the coordinates of the drawing layer. */\nfunction useLineBoxes(\n  rootRef: RefObject<HTMLElement | null>,\n  svgRef: RefObject<SVGSVGElement | null>\n) {\n  const [boxes, setBoxes] = useState<Box[]>([]);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    const svg = svgRef.current;\n    if (!root) {\n      return;\n    }\n    if (!svg) {\n      return;\n    }\n    let isMounted = true;\n    const measure = () => {\n      const next = boxesOf(root, svg);\n      setBoxes((current) => keepIfSame(current, next));\n    };\n    const observer = new ResizeObserver(measure);\n    observer.observe(blockAncestorOf(root));\n    document.fonts.ready.then(() => {\n      if (isMounted) {\n        measure();\n      }\n    });\n    return () => {\n      isMounted = false;\n      observer.disconnect();\n    };\n  }, [rootRef, svgRef]);\n\n  return boxes;\n}\n\nfunction toneOf(action: HighlighterAction, tone: HighlighterTone | undefined) {\n  if (tone) {\n    return tone;\n  }\n  if (action === 'highlight') {\n    return 'warning';\n  }\n  return 'primary';\n}\n\nfunction toneClassOf(action: HighlighterAction, tone: HighlighterTone) {\n  if (action === 'highlight') {\n    return BAND_TONES[tone];\n  }\n  return LINE_TONES[tone];\n}\n\nfunction passCountOf(action: HighlighterAction, passes: 1 | 2 | undefined) {\n  if (passes) {\n    return passes;\n  }\n  if (action === 'highlight') {\n    return 1;\n  }\n  return 2;\n}\n\nfunction strokeOpacityOf(action: HighlighterAction) {\n  if (action === 'highlight') {\n    return BAND_OPACITY;\n  }\n  return 1;\n}\n\nfunction lineCapOf(action: HighlighterAction) {\n  if (action === 'highlight') {\n    return 'butt';\n  }\n  return 'round';\n}\n\nfunction drawnOf(stroke: Stroke): TargetAndTransition {\n  return {\n    pathLength: 1,\n    opacity: 1,\n    transition: {\n      pathLength: {\n        duration: stroke.duration,\n        delay: stroke.delay,\n        ease: EASE_PEN,\n      },\n      opacity: { duration: 0.01, delay: stroke.delay },\n    },\n  };\n}\n\nfunction shownWithoutDrawingOf(stroke: Stroke): TargetAndTransition {\n  return {\n    pathLength: 1,\n    opacity: 1,\n    transition: {\n      pathLength: { duration: 0 },\n      opacity: { duration: 0.2, delay: stroke.delay, ease: EASE_OUT_STRONG },\n    },\n  };\n}\n\nconst ERASED: TargetAndTransition = {\n  pathLength: 0,\n  opacity: 0,\n  transition: {\n    opacity: { duration: ERASE_DURATION, ease: EASE_OUT_STRONG },\n    pathLength: { duration: 0, delay: ERASE_DURATION },\n  },\n};\n\nfunction targetOf(\n  stroke: Stroke,\n  isShown: boolean,\n  shouldReduceMotion: boolean | null\n) {\n  if (!isShown) {\n    return ERASED;\n  }\n  if (shouldReduceMotion) {\n    return shownWithoutDrawingOf(stroke);\n  }\n  return drawnOf(stroke);\n}\n\nexport type HighlighterProps = {\n  children: ReactNode;\n  action?: HighlighterAction;\n  tone?: HighlighterTone;\n  strokeWidth?: number;\n  padding?: number;\n  passes?: 1 | 2;\n  duration?: number;\n  delay?: number;\n  show?: boolean;\n  className?: string;\n};\n\nexport function Highlighter({\n  children,\n  action = 'highlight',\n  tone,\n  strokeWidth = 2,\n  padding,\n  passes,\n  duration = 0.8,\n  delay = 0,\n  show,\n  className,\n}: HighlighterProps) {\n  const rootRef = useRef<HTMLSpanElement>(null);\n  const svgRef = useRef<SVGSVGElement>(null);\n  const instanceId = useId();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const isInView = useInView(rootRef, { once: true, margin: IN_VIEW_MARGIN });\n  const boxes = useLineBoxes(rootRef, svgRef);\n  const isShown = show ?? isInView;\n  const isBehindText = action === 'highlight';\n  const resolvedTone = toneOf(action, tone);\n  const seed = seedOf(`${instanceId}-${action}`);\n  const resolvedPadding = padding ?? DEFAULT_PADDING[action];\n  const strokes = strokesOf(action, boxes, {\n    seed,\n    padding: resolvedPadding,\n    strokeWidth,\n    passCount: passCountOf(action, passes),\n    duration,\n    delay,\n  });\n\n  return (\n    <span\n      ref={rootRef}\n      className={cn('relative', isBehindText && 'isolate', className)}\n    >\n      {children}\n      <svg\n        ref={svgRef}\n        aria-hidden='true'\n        fill='none'\n        className={cn(\n          'pointer-events-none absolute top-0 left-0 size-px overflow-visible',\n          toneClassOf(action, resolvedTone),\n          isBehindText && '-z-10'\n        )}\n      >\n        {strokes.map((stroke) => (\n          <motion.path\n            key={stroke.key}\n            d={stroke.path}\n            stroke='currentColor'\n            strokeWidth={stroke.width}\n            strokeOpacity={strokeOpacityOf(action)}\n            strokeLinecap={lineCapOf(action)}\n            strokeLinejoin='round'\n            initial={HIDDEN}\n            animate={targetOf(stroke, isShown, shouldReduceMotion)}\n          />\n        ))}\n      </svg>\n    </span>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/core/highlighter.tsx"
    }
  ],
  "categories": [
    "motion"
  ],
  "type": "registry:component"
}