{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"edge-invert-headline","type":"registry:component","title":"Edge Invert Headline","description":"A caps headline that inverts exactly at the edges of the plates under it; drag a plate and the inversion follows 1:1, then snaps to a lattice cell, and on column 3, 6 or 9 the plate breaks by the rule.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/edge-invert-headline.tsx","content":"\"use client\";\n\nimport { useEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport type { CSSProperties, KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent, RefObject } from \"react\";\n\n/**\n * EdgeInvertHeadline — a headline that turns over exactly where a plate sits under it, and plates that obey the rule.\n *\n * Each plate under the caps headline carries an aligned copy in the opposite\n * colour, clipped to the plate, so the words invert at the plates' edges to\n * the pixel, with no blend mode. Plates live on lattice cells: drag one (or\n * use the arrow keys) and the inversion follows 1:1, then snaps; on column\n * 3, 6 or 9 a plate breaks by the rule. Field or paper; a p, h1 or h2.\n *\n * Part of the Broken Grid kit: a Klein-blue field #2416f0, paper plates\n * #f1f0e8, ink #0a0a1f, and acid #e2ff3a only where a rule fires. One rule,\n * \"The Third\": every third module in a run overshoots its leading edge by two\n * gutters (overlapping its neighbour by one) and wears the acid bracket; the\n * ends never break. Radius 0, no shadows; reflows in 380ms, no bounce. Big\n * Shoulders through var(--font-big-shoulders) for display over Geist.\n * Respects prefers-reduced-motion. No dependencies beyond React. Paste it as\n * its own file: it repeats the kit's small helpers, which would clash in one\n * module. Load Big Shoulders with next/font (variable:\n * \"--font-big-shoulders\") on a parent, or from Google Fonts or @fontsource.\n * Needs Tailwind v4 (on v3.4, add the @tailwindcss/container-queries plugin).\n */\n\nconst MONO = 'var(--font-mono, \"Geist Mono\", ui-monospace, \"SFMono-Regular\", Menlo, Consolas, monospace)';\n\nconst DISPLAY = 'var(--font-big-shoulders, \"Big Shoulders\", \"Big Shoulders Display\", \"Arial Narrow\", \"Roboto Condensed\", sans-serif)';\n\n/**\n * A Klein-blue field, paper plates, blue-black ink, and acid for a rule firing.\n * Secondary and tertiary text clear 4.5:1 on their grounds (ink2 7.4, ink3 5.0\n * on paper; onField2 5.9, onField3 4.8 on the field); `edgeOnPaper` is the 3:1\n * boundary for inputs.\n */\nconst FIELD = {\n  field: \"#2416f0\",\n  raised: \"#3a2ff5\",\n  pressed: \"#1a0ec4\",\n  paper: \"#f1f0e8\",\n  ink: \"#0a0a1f\",\n  ink2: \"rgba(10,10,31,0.72)\",\n  ink3: \"rgba(10,10,31,0.6)\",\n  onField2: \"rgba(241,240,232,0.86)\",\n  onField3: \"rgba(241,240,232,0.76)\",\n  lineOnField: \"rgba(241,240,232,0.22)\",\n  lineOnPaper: \"rgba(10,10,31,0.14)\",\n  edgeOnPaper: \"rgba(10,10,31,0.5)\",\n  edgeOnField: \"rgba(241,240,232,0.6)\",\n  acid: \"#e2ff3a\",\n} as const;\n\n/** The mark (bracket, tag, focus ring) for a ground: acid on the field, ink on paper. */\nfunction bgMark(ground: \"field\" | \"paper\"): CSSProperties {\n  const c = ground === \"field\" ? FIELD.acid : FIELD.ink;\n  return { [\"--bg-mark\" as string]: c, [\"--bg-ring\" as string]: c } as CSSProperties;\n}\n\n/** Layout changes: 380ms, no stagger, no bounce. Role hand-offs take 240ms. */\nconst BG_EASE = \"cubic-bezier(.2,.8,.2,1)\";\n\nconst BG_HANDOFF_MS = 240;\n\nfunction clamp(v: number, lo: number, hi: number): number {\n  return v < lo ? lo : v > hi ? hi : v;\n}\n\nfunction subscribeMotion(cb: () => void) {\n  const m = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n  m.addEventListener(\"change\", cb);\n  return () => m.removeEventListener(\"change\", cb);\n}\n\n/** True when the visitor asked for reduced motion. False on the server. */\nfunction useReducedMotion(): boolean {\n  return useSyncExternalStore(\n    subscribeMotion,\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/**\n * The rule, \"The Third\": in a run of `count` modules, module `index` (from 0)\n * breaks when it is every `every`th (3, 6, 9...) and is neither end of the run.\n * Use it for your own runs, so the break is computed and never placed by hand.\n */\nexport function bgBreaks(index: number, count: number, every = 3): boolean {\n  if (every < 2 || index <= 0 || index >= count - 1) return false;\n  return (index + 1) % every === 0;\n}\n\n/**\n * The lattice at a width: 12 columns from 768px (48rem; gutter 1.875%, 24px at\n * 1280), else 4 (8px gutters). The margin is two gutters and 8px (56px at\n * 1280, 24px on a phone): room for a first-column breaker's overshoot and its\n * bracket. `pitch` is a column plus a gutter; the drawn hairlines run through\n * the gutter centres.\n */\nfunction bgGrid(width: number) {\n  const wide = width >= 768;\n  const cols = wide ? 12 : 4;\n  const gutter = wide ? width * 0.01875 : 8;\n  const margin = gutter * 2 + 8;\n  const col = (width - margin * 2 - gutter * (cols - 1)) / cols;\n  return { cols, gutter, margin, col, pitch: col + gutter };\n}\n\n// Each part carries only the CSS it needs, so any one of them works on its own.\n// revert-layer keeps an element's own corners when a host page's focus rule rounds or flattens them.\nconst FOCUS_CSS = \".bg-scope :focus-visible,.bg-scope:focus-visible{outline:2px solid var(--bg-ring,#e2ff3a)!important;outline-offset:3px;border-radius:revert-layer}\";\n\n/**\n * The bracket a module wears when the rule breaks it: an L of 2px, one gutter\n * long, 6px outside its leading corner, so it reads against the ground. Its\n * colour is --bg-mark (acid on the field, ink on paper; see bgMark).\n */\nfunction BgBracket({ on, size = 24, className = \"\" }: { on: boolean; size?: number; className?: string }) {\n  const reduced = useReducedMotion();\n  return (\n    <span\n      aria-hidden\n      className={\"pointer-events-none absolute left-0 top-0 block \" + className}\n      style={{\n        width: size,\n        height: size,\n        borderTop: `2px solid var(--bg-mark, ${FIELD.acid})`,\n        borderLeft: `2px solid var(--bg-mark, ${FIELD.acid})`,\n        transform: \"translate(-6px, -6px)\",\n        opacity: on ? 1 : 0,\n        transition: reduced ? \"none\" : `opacity ${BG_HANDOFF_MS}ms ${BG_EASE}`,\n      }}\n    />\n  );\n}\n\n/** Where a plate sits: its first column and row on the lattice (from 1). */\ntype BgCell = { col: number; row: number };\n\nconst BG_INVERT_TONES = {\n  field: { ground: FIELD.field, text: FIELD.paper, plate: FIELD.paper, copy: FIELD.ink, hint: FIELD.ink2, line: FIELD.lineOnPaper, tick: \"rgba(241,240,232,0.34)\" },\n  paper: { ground: FIELD.paper, text: FIELD.ink, plate: FIELD.field, copy: FIELD.paper, hint: FIELD.onField2, line: FIELD.lineOnField, tick: \"rgba(10,10,31,0.3)\" },\n} as const;\n\n/**\n * EdgeInvertHeadline — a headline that turns over exactly where a plate\n * sits under it, and plates that obey the rule.\n *\n * The caps headline sits on the lattice, its columns ticked along the top.\n * The plates under it carry an aligned copy of the same headline in the\n * opposite colour, clipped to each plate, so the words invert at the plates'\n * edges to the pixel (no blend mode, no contrast gamble). The plates live on\n * lattice cells: drag one (or focus it and use the arrow keys) and the\n * inversion follows 1:1, then it snaps to the nearest cell in 320ms. The\n * columns are a run, so a plate that starts on column 3, 6 or 9 breaks by\n * the rule: two gutters out at its leading edge with the bracket, and the\n * inverted slice widens with it. The real text is read once; the copies are\n * hidden. Field (paper plates) or paper (blue plates).\n */\nexport function EdgeInvertHeadline({\n  text = \"We break the grid by exactly as much as makes it look right.\",\n  plates = [\n    { col: 3, row: 2 },\n    { col: 5, row: 4 },\n  ],\n  as: Tag = \"p\",\n  tone = \"field\",\n  size = \"clamp(40px, 8.6cqw, 128px)\",\n  measure = \"14ch\",\n  hint = \"Drag\",\n  className = \"\",\n  style,\n}: {\n  text?: string;\n  /** Where the plates start: the lattice cell of each one's top-left corner (from 1). */\n  plates?: BgCell[];\n  /** The headline's element: make it the page's h1 or a section's h2 when it is one. */\n  as?: \"p\" | \"h1\" | \"h2\" | \"h3\";\n  tone?: keyof typeof BG_INVERT_TONES;\n  size?: string;\n  /** The headline's maximum width. */\n  measure?: string;\n  /** The small label on each plate. */\n  hint?: string;\n  className?: string;\n  style?: CSSProperties;\n}) {\n  const t = BG_INVERT_TONES[tone] ?? BG_INVERT_TONES.field;\n  const hostRef = useRef<HTMLDivElement>(null);\n  const headRef = useRef<HTMLElement>(null);\n  const plateRefs = useRef<(HTMLDivElement | null)[]>([]);\n  const copyRefs = useRef<(HTMLParagraphElement | null)[]>([]);\n  const reduced = useReducedMotion();\n  const [box, setBox] = useState({ w: 0, h: 0, hx: 0, hy: 0, hw: 0 });\n  // The plates' cells. A default array is a new object every render, so the start is read by value.\n  const plateKey = plates.map((p) => `${p.col},${p.row}`).join(\";\");\n  const [cells, setCells] = useState<BgCell[]>(plates);\n  const [seen, setSeen] = useState(plateKey);\n  if (seen !== plateKey) {\n    setSeen(plateKey);\n    setCells(plates);\n  }\n  const [said, setSaid] = useState(\"\");\n  const drag = useRef({ i: -1, x0: 0, y0: 0, dx: 0, dy: 0 });\n\n  // Measure the frame and the headline (an empty first measure is skipped).\n  useEffect(() => {\n    const host = hostRef.current;\n    const head = headRef.current;\n    if (!host || !head) return;\n    const read = () => {\n      const w = host.clientWidth;\n      const h = host.clientHeight;\n      if (!w || !h) return;\n      const next = { w, h, hx: head.offsetLeft, hy: head.offsetTop, hw: head.offsetWidth };\n      setBox((b) => (b.w === next.w && b.h === next.h && b.hx === next.hx && b.hy === next.hy && b.hw === next.hw ? b : next));\n    };\n    read();\n    const ro = new ResizeObserver(read);\n    ro.observe(host);\n    ro.observe(head);\n    return () => ro.disconnect();\n  }, []);\n\n  const g = bgGrid(box.w || 1280);\n  const span = g.cols === 12 ? 4 : 2;\n  const pw = g.pitch * span - g.gutter;\n  const ph = g.pitch * 2 - g.gutter;\n  const maxCol = Math.max(1, g.cols - span + 1);\n  const maxRow = Math.max(1, Math.floor((box.h - g.margin - ph) / g.pitch) + 1);\n  // Cells stay legal at any width: a narrower frame pulls plates back onto it.\n  const fit = (c: BgCell): BgCell => ({ col: clamp(Math.round(c.col), 1, maxCol), row: clamp(Math.round(c.row), 1, maxRow) });\n  const breaksAt = (c: BgCell) => bgBreaks(c.col - 1, g.cols);\n  // Where a plate draws: its cell, grown two gutters to the left when it breaks.\n  const geom = (c: BgCell) => {\n    const lead = breaksAt(c) ? g.gutter * 2 : 0;\n    return { x: g.margin + (c.col - 1) * g.pitch - lead, y: g.margin + (c.row - 1) * g.pitch, w: pw + lead };\n  };\n  const nearest = (x: number, y: number): BgCell => fit({ col: (x - g.margin) / g.pitch + 1, row: (y - g.margin) / g.pitch + 1 });\n  const placed = cells.map(fit);\n\n  // During a drag the plate and its copy are written directly, every move, so the inversion tracks 1:1.\n  const paint = (i: number, x: number, y: number) => {\n    const p = plateRefs.current[i];\n    const c = copyRefs.current[i];\n    if (p) p.style.transform = `translate(${x}px, ${y}px)`;\n    if (c) c.style.transform = `translate(${box.hx - x}px, ${box.hy - y}px)`;\n  };\n  const moveTo = (i: number, from: { x: number; y: number; w: number }, to: BgCell) => {\n    const end = geom(to);\n    const p = plateRefs.current[i];\n    const c = copyRefs.current[i];\n    // Write the destination first: React skips a style it thinks is unchanged, and a drag wrote over it.\n    paint(i, end.x, end.y);\n    if (p) p.style.width = `${end.w}px`;\n    setCells((old) => old.map((cl, j) => (j === i ? to : fit(cl))));\n    setSaid(`Plate ${i + 1} at column ${to.col}, row ${to.row}${breaksAt(to) ? \": a third column, so it breaks the grid by the rule\" : \"\"}.`);\n    if (reduced) return;\n    const opts = { duration: 320, easing: BG_EASE };\n    p?.animate([{ transform: `translate(${from.x}px, ${from.y}px)`, width: `${from.w}px` }, { transform: `translate(${end.x}px, ${end.y}px)`, width: `${end.w}px` }], opts);\n    c?.animate([{ transform: `translate(${box.hx - from.x}px, ${box.hy - from.y}px)` }, { transform: `translate(${box.hx - end.x}px, ${box.hy - end.y}px)` }], opts);\n  };\n  const onDown = (e: ReactPointerEvent<HTMLDivElement>, i: number) => {\n    if (e.button !== 0) return;\n    // A grab during a snap starts from the snap's destination, with nothing still animating over it.\n    plateRefs.current[i]?.getAnimations().forEach((a) => a.cancel());\n    copyRefs.current[i]?.getAnimations().forEach((a) => a.cancel());\n    drag.current = { i, x0: e.clientX, y0: e.clientY, dx: 0, dy: 0 };\n    try {\n      e.currentTarget.setPointerCapture(e.pointerId);\n    } catch {\n      // A synthetic pointer can't be captured; the drag still follows moves.\n    }\n    e.preventDefault();\n  };\n  const onMove = (e: ReactPointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    const cl = placed[d.i];\n    if (d.i < 0 || !cl) return;\n    const r = hostRef.current?.getBoundingClientRect();\n    const k = r && hostRef.current?.offsetWidth ? r.width / hostRef.current.offsetWidth : 1;\n    d.dx = (e.clientX - d.x0) / (k || 1);\n    d.dy = (e.clientY - d.y0) / (k || 1);\n    const at = geom(cl);\n    paint(d.i, at.x + d.dx, at.y + d.dy);\n  };\n  const onUp = () => {\n    const d = drag.current;\n    const cl = placed[d.i];\n    if (d.i < 0 || !cl) return;\n    const i = d.i;\n    d.i = -1;\n    const at = geom(cl);\n    const from = { x: at.x + d.dx, y: at.y + d.dy, w: at.w };\n    const lead = breaksAt(cl) ? g.gutter * 2 : 0;\n    moveTo(i, from, nearest(from.x + lead, from.y));\n  };\n  const onKey = (e: ReactKeyboardEvent<HTMLDivElement>, i: number) => {\n    const step: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] };\n    const s = step[e.key];\n    const cl = placed[i];\n    if (!s || !cl) return;\n    e.preventDefault();\n    moveTo(i, geom(cl), fit({ col: cl.col + s[0], row: cl.row + s[1] }));\n  };\n\n  const type: CSSProperties = { fontFamily: DISPLAY, fontWeight: 800, fontSize: size, lineHeight: 0.86, letterSpacing: \"-0.005em\", textTransform: \"uppercase\", maxWidth: measure };\n  // The headline and its copies share one box: the lattice's margin on every side but the bottom.\n  const frame = \"m-0 px-6 pb-8 pt-6 @3xl:px-[calc(3.75cqw_+_8px)] @3xl:pb-[4cqw] @3xl:pt-[calc(3.75cqw_+_8px)]\";\n  return (\n    <div ref={hostRef} className={\"bg-scope relative isolate w-full overflow-hidden @container \" + className} style={{ background: t.ground, color: t.text, ...bgMark(tone), ...style }}>\n      <style>{FOCUS_CSS}</style>\n      {/* The lattice's columns, ticked along the top: 6px hairlines through the gutter centres. */}\n      {box.w\n        ? Array.from({ length: g.cols + 1 }, (_, i) => (\n            <span key={i} aria-hidden className=\"pointer-events-none absolute top-0 block h-1.5 w-px\" style={{ left: g.margin + i * g.pitch - g.gutter / 2, background: t.tick }} />\n          ))\n        : null}\n      <Tag ref={headRef as RefObject<HTMLHeadingElement & HTMLParagraphElement>} className={\"relative select-none \" + frame} style={type}>\n        {text}\n      </Tag>\n      {box.w\n        ? placed.map((cl, i) => {\n            const at = geom(cl);\n            const brk = breaksAt(cl);\n            return (\n              <div\n                key={i}\n                ref={(el) => void (plateRefs.current[i] = el)}\n                role=\"button\"\n                tabIndex={0}\n                aria-roledescription=\"movable plate\"\n                aria-label={`Plate ${i + 1}, at column ${cl.col}, row ${cl.row}. Arrow keys move it by one cell.`}\n                onPointerDown={(e) => onDown(e, i)}\n                onPointerMove={onMove}\n                onPointerUp={onUp}\n                onPointerCancel={onUp}\n                onKeyDown={(e) => onKey(e, i)}\n                className=\"absolute left-0 top-0 cursor-grab touch-none select-none active:cursor-grabbing\"\n                style={{ width: at.w, height: ph, transform: `translate(${at.x}px, ${at.y}px)`, transition: \"none\", zIndex: brk ? 2 : 1 }}\n              >\n                <BgBracket on={brk} />\n                <div className=\"absolute inset-0 overflow-hidden\" style={{ background: t.plate, boxShadow: `inset 0 0 0 1px ${t.line}` }}>\n                  {/* The same headline, in the opposite colour, placed so it lines up with the real one: the plate shows only its slice. */}\n                  <p\n                    ref={(el) => void (copyRefs.current[i] = el)}\n                    aria-hidden\n                    className={\"pointer-events-none absolute left-0 top-0 \" + frame}\n                    style={{ ...type, color: t.copy, width: box.hw || undefined, transform: `translate(${box.hx - at.x}px, ${box.hy - at.y}px)`, transition: \"none\" }}\n                  >\n                    {text}\n                  </p>\n                  <span aria-hidden className=\"absolute bottom-2 right-3 text-[11px] uppercase\" style={{ fontFamily: MONO, letterSpacing: \"0.08em\", color: t.hint }}>\n                    {hint}\n                  </span>\n                </div>\n              </div>\n            );\n          })\n        : null}\n      <p aria-live=\"polite\" className=\"sr-only\">\n        {said}\n      </p>\n    </div>\n  );\n}\n","type":"registry:component","target":"components/viberdy/edge-invert-headline.tsx"}],"meta":{"tier":"free","tags":["text effect","headline","invert","knockout","drag","broken grid","typography"],"href":"https://viberdy.dev/library/edge-invert-headline","aiPrompt":"Build a React + Tailwind text effect, `EdgeInvertHeadline({ text, plates, as, tone, size, measure, hint, className, style })` where plates are lattice cells { col, row }.\n\nBroken Grid grammar: a visible grid that holds, and one rule that breaks it the same way everywhere. A Klein-blue field #2416f0 as the ground (raised #3a2ff5, pressed #1a0ec4), paper plates #f1f0e8, blue-black ink #0a0a1f; secondary and tertiary text at 72/60% ink on paper and 86/76% paper on the field (all 4.5:1 or better), input boundaries at 50% ink (3:1). The mark means one thing, a rule firing or the current state (the bracket on a breaking module, an index tag, a selected chip): acid #e2ff3a on the field, ink on paper, where acid would vanish; never a wash, a gradient or text on paper. The lattice: twelve columns from a 48rem container (gutter 1.875%, 24px at 1280), four on a phone (8px gutters); the margin is two gutters and 8px (56px at 1280, 24px on a phone), so a breaker in the first column runs into the margin with its bracket still on the page; rows square with the columns; hairlines through the gutter centres (paper at 22% on the field), small crosses where they meet; drawn in full only at the anchors (hero, footer), elsewhere as column ticks. THE RULE, \"The Third\": in every run of modules, module 3, 6, 9... (never the first or the last) overshoots its leading edge by two gutters, one closing the gap and one overlapping its neighbour, rides one layer above it, wears the bracket (a 2px L one gutter long, 6px outside its leading corner, read against the ground) and gets a firmer leading edge (half-strength text colour) so the overlap reads as two plates; its padding grows by the same so its content never moves, and the module it overlaps keeps a gutter of trailing padding clear. Type follows the same law with one column pitch as the unit. The break belongs to the position: reorder a run and the break passes to whichever module is now third; compute it, never place it. Radius 0, no shadows, no grain; depth is overlap and a 1px hairline (inset box-shadow, never a border). Type: Big Shoulders at 800 in capitals through var(--font-big-shoulders, \"Big Shoulders\", ...) for display (up to 164px, leading 0.84-0.86), Geist Mono 11px uppercase +0.08em for labels (never smaller), Geist 16-17px/1.5 for reading. Motion: layouts change in 380ms on cubic-bezier(.2,.8,.2,1), all at once, no stagger, no spring, no overshoot (the layout overshoots, the motion never does); a role hand-off (breaking or letting go) takes 240ms; a drag follows 1:1 and snaps in 320ms; controls press in 120ms, release in 200ms, labels step in 160ms; tags step (steps(4)), never glide; scroll only ever changes a layout at checkpoints (never a continuous scrub); no ambient loops; reduced motion makes every change instant.\n\nA host (field or paper) with 6px column ticks along the top and the headline (Big Shoulders 800 caps at clamp(40px, 8.6cqw, 128px), leading 0.86, max 14ch, padded by the lattice margin) and, after it, absolutely positioned plates (four columns by two rows of the lattice, two columns on a phone; paper on the field, blue on paper), each with an overflow-hidden inner box containing an aria-hidden copy of the headline in the other ink with the same font, padding and width, translated by (headline.offsetLeft - plate.x, headline.offsetTop - plate.y) so it lines up with the real one. A plate on column c breaks when bgBreaks(c - 1, columns): it is drawn two gutters further left and wider, with the bracket, and its copy shifts to match. Dragging writes the plate's and the copy's transforms directly on every move; release writes the destination to the DOM first (React would skip a style it thinks unchanged), then snaps with a 320ms Web Animation on both, from the drop point. Grabbing a plate cancels its running animations. Cells are clamped to the frame on every render; arrow keys move one cell and a polite live region announces it.","license":"https://viberdy.dev/license"}}