Ink marks

An inline wrapper that draws hand-made pen marks around words: a wavy underline, a slanted highlighter block, a loose circle that overshoots, a box, a strike, side brackets or a curved arrow pointing in from above. Each mark is an SVG sized to the words with ResizeObserver and shaped by a small seeded jitter, so it looks drawn by hand yet stays the same on every render. Marks draw in when they scroll into view, a roughness setting goes from neat to scribbly, highlight, underline and strike follow wrapped lines, and InkMarks.Group draws its marks one after another like someone annotating live. Meaning is kept in mark, s or em elements, and reduced motion shows the marks already drawn.

Animation & motionComponentTailwind v4

Source

"use client";

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type CSSProperties,
  type ReactNode,
} from "react";
import { cn } from "@/lib/utils";

export type InkVariant = "underline" | "highlight" | "circle" | "box" | "strike" | "bracket" | "arrow";

export type InkMarkProps = {
  variant?: InkVariant;
  /** Any CSS colour. Defaults to the first chart token; the highlight uses a 35% mix of it. */
  color?: string;
  strokeWidth?: number;
  /** 0 is neat, 1 is scribbly. */
  roughness?: number;
  /** Draw in when scrolled into view. Off shows the mark already drawn. */
  animate?: boolean;
  /** Wait before drawing, in milliseconds. Ignored inside a group, which sets its own pace. */
  delay?: number;
  /** Length of the stroke, in milliseconds. */
  duration?: number;
  /** Follow each wrapped line for highlight, underline and strike. On by default. */
  multiline?: boolean;
  /** Increase to draw the mark again. */
  play?: number;
  className?: string;
  children: ReactNode;
};

type Box = { x: number; y: number; w: number; h: number };
type Shape = { d: string; fill?: boolean };

/* ---------- geometry ---------- */

function rng(seed: number) {
  let s = seed >>> 0 || 7;
  return () => {
    s ^= s << 13;
    s ^= s >>> 17;
    s ^= s << 5;
    return (s >>> 0) / 4294967296;
  };
}

function hash(value: string) {
  let h = 2166136261;
  for (let i = 0; i < value.length; i++) h = Math.imul(h ^ value.charCodeAt(i), 16777619);
  return h >>> 0;
}

const f = (n: number) => Math.round(n * 10) / 10;

// A smooth curve through the points, written as cubic curve segments.
function smooth(points: [number, number][]) {
  if (points.length < 2) return "";
  let d = `M${f(points[0]![0])} ${f(points[0]![1])}`;
  for (let i = 0; i < points.length - 1; i++) {
    const p0 = points[i - 1] ?? points[i]!;
    const p1 = points[i]!;
    const p2 = points[i + 1]!;
    const p3 = points[i + 2] ?? p2;
    const c1 = [p1[0] + (p2[0] - p0[0]) / 6, p1[1] + (p2[1] - p0[1]) / 6];
    const c2 = [p2[0] - (p3[0] - p1[0]) / 6, p2[1] - (p3[1] - p1[1]) / 6];
    d += ` C${f(c1[0]!)} ${f(c1[1]!)} ${f(c2[0]!)} ${f(c2[1]!)} ${f(p2[0])} ${f(p2[1])}`;
  }
  return d;
}

function union(boxes: Box[]): Box {
  const x = Math.min(...boxes.map((b) => b.x));
  const y = Math.min(...boxes.map((b) => b.y));
  const r = Math.max(...boxes.map((b) => b.x + b.w));
  const b = Math.max(...boxes.map((b) => b.y + b.h));
  return { x, y, w: r - x, h: b - y };
}

function shapes(variant: InkVariant, boxes: Box[], seed: number, rough: number): Shape[] {
  const rand = rng(seed);
  const j = (amount: number) => (rand() - 0.5) * 2 * amount * (0.35 + rough);
  const u = union(boxes);

  switch (variant) {
    case "underline":
      return boxes.map((b) => {
        const amp = 1 + rough * 2.6;
        const wave = 13 - rough * 4;
        const y = b.y + b.h + 1.5;
        const pts: [number, number][] = [];
        let k = 0;
        for (let x = b.x - 2; x <= b.x + b.w + 3; x += wave / 2, k++) pts.push([x + j(1), y + (k % 2 ? amp : -amp) * 0.6 + j(1.2)]);
        pts.push([b.x + b.w + 4, y + j(1)]);
        return { d: smooth(pts) };
      });
    case "highlight":
      return boxes.map((b) => {
        const pts: [number, number][] = [
          [b.x - 4 + j(2), b.y + b.h * 0.14 + j(2)],
          [b.x + b.w * 0.5, b.y + b.h * 0.08 + j(2)],
          [b.x + b.w + 4 + j(2), b.y + b.h * 0.02 + j(2)],
          [b.x + b.w + 2 + j(2), b.y + b.h * 0.92 + j(2)],
          [b.x + b.w * 0.5, b.y + b.h * 0.98 + j(2)],
          [b.x - 6 + j(2), b.y + b.h + j(2)],
        ];
        return { d: `M${pts.map(([x, y]) => `${f(x)} ${f(y)}`).join(" L")} Z`, fill: true };
      });
    case "strike":
      return boxes.map((b) => {
        const y = b.y + b.h * 0.56;
        let d = smooth([
          [b.x - 3, y + 1.5 + j(1.5)],
          [b.x + b.w * 0.5, y + j(2)],
          [b.x + b.w + 3, y - 1.5 + j(1.5)],
        ]);
        if (rough > 0.45) d += ` ${smooth([[b.x + b.w + 2, y + 2 + j(2)], [b.x + b.w * 0.45, y + 3 + j(2)], [b.x - 1, y + 1 + j(2)]])}`;
        return { d };
      });
    case "circle": {
      const cx = u.x + u.w / 2;
      const cy = u.y + u.h / 2;
      const rx = u.w / 2 + 10 + rough * 4;
      const ry = u.h / 2 + 7 + rough * 3;
      const p1 = rand() * 6;
      const p2 = rand() * 6;
      const start = -2.3 + j(0.3);
      const sweep = Math.PI * 2 + 0.45 + rough * 0.4;
      const pts: [number, number][] = [];
      const n = 44;
      for (let i = 0; i <= n; i++) {
        const t = i / n;
        const a = start + sweep * t;
        const wobble = 1 + (Math.sin(a * 2 + p1) * 0.035 + Math.sin(a * 3 + p2) * 0.025) * (0.5 + rough * 1.6);
        const drift = 1 + t * (0.05 + rough * 0.05);
        pts.push([cx + Math.cos(a) * rx * wobble * drift, cy + Math.sin(a) * ry * wobble * (2 - drift)]);
      }
      return [{ d: smooth(pts) }];
    }
    case "box": {
      const pad = 6;
      const l = u.x - pad;
      const t = u.y - pad + 1;
      const r = u.x + u.w + pad;
      const b = u.y + u.h + pad - 1;
      const o = 3 + rough * 4;
      const side = (x1: number, y1: number, x2: number, y2: number) =>
        smooth([[x1 + j(1.5), y1 + j(1.5)], [(x1 + x2) / 2 + j(2), (y1 + y2) / 2 + j(2)], [x2 + j(1.5), y2 + j(1.5)]]);
      return [{ d: [side(l - o, t, r + o, t - 1), side(r, t - o, r + 1, b + o), side(r + o, b, l - o, b + 1), side(l, b + o, l - 1, t - o)].join(" ") }];
    }
    case "bracket": {
      const l = u.x - 7;
      const r = u.x + u.w + 7;
      const t = u.y - 3;
      const b = u.y + u.h + 3;
      const arm = Math.min(9, u.w / 4);
      return [
        { d: smooth([[l + arm + j(1), t + j(1)], [l + j(1), t + 2 + j(1)], [l - 1 + j(1.5), (t + b) / 2], [l + j(1), b - 2 + j(1)], [l + arm + j(1), b + j(1)]]) },
        { d: smooth([[r - arm + j(1), t + j(1)], [r + j(1), t + 2 + j(1)], [r + 1 + j(1.5), (t + b) / 2], [r + j(1), b - 2 + j(1)], [r - arm + j(1), b + j(1)]]) },
      ];
    }
    case "arrow": {
      const tx = u.x - 8;
      const ty = u.y + u.h * 0.4;
      const sx = tx - 58 + j(4);
      const sy = ty - 46 + j(4);
      const cx = sx + 6 + j(4);
      const cy = ty + 4 + j(4);
      const dx = tx - cx;
      const dy = ty - cy;
      const len = Math.hypot(dx, dy) || 1;
      const ux = dx / len;
      const uy = dy / len;
      const wing = (angle: number) => {
        const c = Math.cos(angle);
        const s = Math.sin(angle);
        return [tx - (ux * c - uy * s) * 11, ty - (ux * s + uy * c) * 11] as const;
      };
      const [ax, ay] = wing(0.5 + j(0.08));
      const [bx, by] = wing(-0.5 + j(0.08));
      return [
        { d: `M${f(sx)} ${f(sy)} Q${f(cx)} ${f(cy)} ${f(tx)} ${f(ty)}` },
        { d: `M${f(ax)} ${f(ay)} L${f(tx)} ${f(ty)} L${f(bx)} ${f(by)}` },
      ];
    }
  }
}

/* ---------- motion ---------- */

function useReducedMotion() {
  const [reduce, setReduce] = useState(false);
  useEffect(() => {
    const query = window.matchMedia?.("(prefers-reduced-motion: reduce)");
    if (!query) return;
    setReduce(query.matches);
    const on = () => setReduce(query.matches);
    query.addEventListener("change", on);
    return () => query.removeEventListener("change", on);
  }, []);
  return reduce;
}

const easeDraw = (t: number) => (t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2);

// Time since the mark started drawing. Frames drive it; a slow timer keeps it moving where frames are throttled.
function useDrawClock(active: boolean, instant: boolean, total: number) {
  const [elapsed, setElapsed] = useState(active ? Infinity : 0);
  useEffect(() => {
    if (!active) return setElapsed(0);
    if (instant) return setElapsed(Infinity);
    const start = performance.now();
    let frame = 0;
    let timer: ReturnType<typeof setTimeout> | undefined;
    const tick = () => {
      cancelAnimationFrame(frame);
      clearTimeout(timer);
      const value = performance.now() - start;
      if (value >= total) return setElapsed(Infinity);
      setElapsed(value);
      frame = requestAnimationFrame(tick);
      timer = setTimeout(tick, 40);
    };
    tick();
    return () => {
      cancelAnimationFrame(frame);
      clearTimeout(timer);
    };
  }, [active, instant, total]);
  return elapsed;
}

type GroupState = {
  register: (id: string, node: HTMLElement) => () => void;
  order: string[];
  step: number;
  instant: boolean;
  duration: number;
};
const GroupContext = createContext<GroupState | null>(null);

export type InkMarkGroupProps = {
  /** Pause between one mark finishing and the next starting, in milliseconds. */
  gap?: number;
  /** Stroke length for every mark in the group, in milliseconds. */
  duration?: number;
  /** Increase to replay the whole sequence. */
  play?: number;
  as?: "div" | "p" | "span" | "section";
  className?: string;
  children: ReactNode;
};

/** Draws the marks inside it one after another, in reading order, once the group scrolls into view. */
export function InkMarkGroup({ gap = 180, duration = 650, play = 0, as: Comp = "div", className, children }: InkMarkGroupProps) {
  const ref = useRef<HTMLDivElement>(null);
  const nodes = useRef(new Map<string, HTMLElement>());
  const [order, setOrder] = useState<string[]>([]);
  const [step, setStep] = useState(0);
  const [instant, setInstant] = useState(false);
  const [started, setStarted] = useState(false);
  const reduce = useReducedMotion();

  const register = useCallback((id: string, node: HTMLElement) => {
    nodes.current.set(id, node);
    return () => {
      nodes.current.delete(id);
    };
  }, []);

  useEffect(() => {
    const node = ref.current;
    if (!node) return;
    if (typeof IntersectionObserver === "undefined") return setStarted(true);
    const observer = new IntersectionObserver(([entry]) => {
      if (!entry?.isIntersecting) return;
      observer.disconnect();
      setStarted(true);
    }, { threshold: 0.35 });
    observer.observe(node);
    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    if (!started) return;
    const sorted = [...nodes.current.entries()]
      .sort(([, a], [, b]) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1))
      .map(([id]) => id);
    setOrder(sorted);
    if (reduce) {
      setInstant(true);
      setStep(sorted.length);
      return;
    }
    setInstant(true);
    setStep(0);
    const timers: ReturnType<typeof setTimeout>[] = [];
    timers.push(setTimeout(() => setInstant(false), 40));
    sorted.forEach((_, i) => timers.push(setTimeout(() => setStep(i + 1), 80 + i * (duration + gap))));
    return () => timers.forEach(clearTimeout);
  }, [started, play, reduce, duration, gap]);

  const value = useMemo(() => ({ register, order, step, instant: instant || reduce, duration }), [register, order, step, instant, reduce, duration]);

  return (
    <GroupContext.Provider value={value}>
      <Comp ref={ref as React.Ref<HTMLDivElement>} className={className}>
        {children}
      </Comp>
    </GroupContext.Provider>
  );
}

/** Wraps a few words and draws a hand-made mark around them. */
export function InkMark({
  variant = "underline",
  color = "var(--chart-1)",
  strokeWidth = 2.25,
  roughness = 0.35,
  animate = true,
  delay = 0,
  duration = 650,
  multiline = true,
  play = 0,
  className,
  children,
}: InkMarkProps) {
  const id = useId();
  const group = useContext(GroupContext);
  const reduce = useReducedMotion();
  const ref = useRef<HTMLElement>(null);
  const anchor = useRef<HTMLSpanElement>(null);
  const [boxes, setBoxes] = useState<Box[]>([]);
  const [own, setOwn] = useState({ drawn: !animate, instant: !animate });

  useEffect(() => {
    if (!group || !ref.current) return;
    return group.register(id, ref.current);
  }, [group?.register, id]); // eslint-disable-line react-hooks/exhaustive-deps

  // Measure the words' line boxes against a zero-size anchor that shares the SVG's containing block.
  useLayoutEffect(() => {
    const node = ref.current;
    if (!node) return;
    const measure = () => {
      const origin = anchor.current?.getBoundingClientRect();
      if (!origin) return;
      const lines = multiline && (variant === "highlight" || variant === "underline" || variant === "strike");
      const rects = lines ? Array.from(node.getClientRects()) : [node.getBoundingClientRect()];
      const next = rects
        .filter((r) => r.width > 1)
        .map((r) => ({ x: r.left - origin.left, y: r.top - origin.top, w: r.width, h: r.height }));
      setBoxes((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next));
    };
    measure();
    const host = node.parentElement ?? node;
    const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
    observer?.observe(host);
    window.addEventListener("resize", measure);
    document.fonts?.ready.then(measure).catch(() => {});
    return () => {
      observer?.disconnect();
      window.removeEventListener("resize", measure);
    };
  }, [variant, multiline]);

  // Standalone marks draw when they scroll into view.
  useEffect(() => {
    if (group || !animate) return;
    const node = ref.current;
    if (!node) return;
    if (reduce) return setOwn({ drawn: true, instant: true });
    setOwn({ drawn: false, instant: true });
    let timer: ReturnType<typeof setTimeout> | undefined;
    const go = () => {
      timer = setTimeout(() => setOwn({ drawn: true, instant: false }), 40 + delay);
    };
    if (typeof IntersectionObserver === "undefined") {
      go();
      return () => clearTimeout(timer);
    }
    const observer = new IntersectionObserver(([entry]) => {
      if (!entry?.isIntersecting) return;
      observer.disconnect();
      go();
    }, { threshold: 0.6 });
    observer.observe(node);
    return () => {
      observer.disconnect();
      clearTimeout(timer);
    };
  }, [group, animate, delay, play, reduce]);

  const index = group ? group.order.indexOf(id) : -1;
  const drawn = !animate || (group ? index !== -1 && index < group.step : own.drawn);
  const instant = !animate || reduce || (group ? group.instant : own.instant);
  const length = group ? group.duration : duration;

  const seed = useMemo(() => hash(`${id}:${variant}`), [id, variant]);
  const paths = useMemo(() => (boxes.length ? shapes(variant, boxes, seed, Math.max(0, Math.min(1, roughness))) : []), [boxes, variant, seed, roughness]);

  const bounds = boxes.length ? union(boxes) : null;
  const pad = variant === "arrow" ? 90 : 24;
  const view = bounds && { x: bounds.x - pad, y: bounds.y - pad, w: bounds.w + pad * 2, h: bounds.h + pad * 2 };
  const timing = paths.map((_, i) => ({
    delay: i * length * (variant === "arrow" ? 0.9 : 0.55),
    duration: variant === "arrow" && i === 1 ? length * 0.35 : length,
  }));
  const total = Math.max(length, ...timing.map((t) => t.delay + t.duration));
  const elapsed = useDrawClock(drawn, instant, total);
  const progress = (i: number) => {
    const t = timing[i] ?? { delay: 0, duration: length };
    return easeDraw(Math.max(0, Math.min(1, (elapsed - t.delay) / t.duration)));
  };
  const highlight = variant === "highlight";
  const fill = `color-mix(in oklab, ${color} 35%, transparent)`;

  const Tag = (highlight ? "mark" : variant === "strike" ? "s" : "em") as "em";

  return (
    <Tag
      ref={ref}
      className={cn(
        "relative isolate not-italic [text-decoration:none]",
        highlight && "bg-transparent text-inherit",
        className,
      )}
    >
      <span ref={anchor} aria-hidden="true" className="pointer-events-none absolute left-0 top-0 size-0" />
      {children}
      {view && (
        <svg
          aria-hidden="true"
          focusable="false"
          className={cn("pointer-events-none absolute overflow-visible", highlight ? "-z-10" : "z-10")}
          style={{
            left: view.x,
            top: view.y,
            width: view.w,
            height: view.h,
            ...(highlight
              ? ({ clipPath: `inset(0 ${f((1 - easeDraw(Math.max(0, Math.min(1, elapsed / length)))) * 100)}% 0 0)` } as CSSProperties)
              : null),
          }}
          viewBox={`${view.x} ${view.y} ${view.w} ${view.h}`}
        >
          {paths.map((shape, i) =>
            shape.fill ? (
              <path key={i} d={shape.d} fill={fill} />
            ) : (
              <path
                key={i}
                d={shape.d}
                fill="none"
                stroke={color}
                strokeWidth={strokeWidth}
                strokeLinecap="round"
                strokeLinejoin="round"
                pathLength={1}
                strokeDasharray="1 1"
                strokeDashoffset={Math.round((1 - progress(i)) * 1000) / 1000}
              />
            ),
          )}
        </svg>
      )}
    </Tag>
  );
}

/** `<InkMarks variant="circle">` for one mark, `<InkMarks.Group>` to sequence several. */
export const InkMarks = Object.assign(InkMark, { Group: InkMarkGroup });