{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"rule-handoff-flip","type":"registry:component","title":"Rule Handoff Flip","description":"The kit's rule for any list: items become plates on the lattice and every third breaks; filter, sort or add and everything moves from where it was in 380ms while the break passes to whichever item is now third.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/rule-handoff-flip.tsx","content":"\"use client\";\n\nimport { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from \"react\";\nimport type { CSSProperties, ReactNode, RefObject } from \"react\";\n\n/**\n * RuleHandoffFlip — the kit's rule for any list, with reflows that hand the break on.\n *\n * Items become plates on the lattice and every third breaks. Filter, sort\n * or add and every item moves from where it was to where it is in 380ms,\n * all at once; the break is recomputed from the new order and passes on.\n * Items, a key and a render function. For your own markup it also exports\n * bgBreaks (the rule), BgPlate (the module) and useRuleFlip (the reflow).\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\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_REFLOW_MS = 380;\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 CSS half of the lattice: `.bg-grid` lays children on the same columns\n * as bgGrid (4 on a phone, 12 from 48rem, the same step as Tailwind's @3xl),\n * and sets --bg-g (the gutter) for the overshoots.\n */\nconst GRID_CSS =\n  \".bg-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));column-gap:8px;padding-inline:24px;--bg-g:8px}\" +\n  \"@container (min-width:48rem){.bg-grid{grid-template-columns:repeat(12,minmax(0,1fr));column-gap:1.875cqw;padding-inline:calc(3.75cqw + 8px);--bg-g:1.875cqw}}\";\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/**\n * Reflows that keep identity. After every change of `key`, each cell marked\n * `data-bg-flip` (with a stable id) moves from where it was to where it is\n * now, all at once, no stagger, in 380ms on the kit's curve (Web Animations,\n * transform only). A reflow that starts mid-flight starts from where the cell\n * is on screen, so a fast run of changes collapses into one clean move. New\n * cells rise 12px into place. A resize re-reads where everything rests, so\n * the next reflow never starts from an old layout. Reduced motion moves them\n * instantly. Use it on your own grid: mark the cells, pass what changed.\n */\nexport function useRuleFlip(ref: RefObject<HTMLElement | null>, key: string) {\n  const reduced = useReducedMotion();\n  const prev = useRef(new Map<string, { x: number; y: number }>());\n  useLayoutEffect(() => {\n    const root = ref.current;\n    if (!root) return;\n    const rr = root.getBoundingClientRect();\n    const k = root.offsetWidth ? rr.width / root.offsetWidth : 1;\n    const next = new Map<string, { x: number; y: number }>();\n    const first = prev.current.size === 0;\n    root.querySelectorAll<HTMLElement>(\"[data-bg-flip]\").forEach((el) => {\n      const id = el.dataset.bgFlip ?? \"\";\n      // Where it is on screen now: its last resting place plus whatever a running reflow has moved it.\n      let offX = 0;\n      let offY = 0;\n      const running = el.getAnimations();\n      if (running.length) {\n        const t = getComputedStyle(el).transform;\n        const m = new DOMMatrixReadOnly(t === \"none\" ? undefined : t);\n        offX = m.m41;\n        offY = m.m42;\n        running.forEach((a) => a.cancel());\n      }\n      const r = el.getBoundingClientRect();\n      const here = { x: (r.left - rr.left) / (k || 1), y: (r.top - rr.top) / (k || 1) };\n      next.set(id, here);\n      if (reduced || first) return;\n      const was = prev.current.get(id);\n      if (!was) {\n        el.animate([{ opacity: 0, transform: \"translateY(12px)\" }, { opacity: 1, transform: \"none\" }], { duration: BG_REFLOW_MS, easing: BG_EASE });\n        return;\n      }\n      const dx = was.x + offX - here.x;\n      const dy = was.y + offY - here.y;\n      if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) return;\n      el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: \"translate(0, 0)\" }], { duration: BG_REFLOW_MS, easing: BG_EASE });\n    });\n    prev.current = next;\n  }, [ref, key, reduced]);\n  // After a resize (or a font swap that reflows the grid), where things rest has changed: re-read it quietly.\n  useEffect(() => {\n    const root = ref.current;\n    if (!root) return;\n    const ro = new ResizeObserver(() => {\n      const cells = [...root.querySelectorAll<HTMLElement>(\"[data-bg-flip]\")];\n      if (cells.some((el) => el.getAnimations().length)) return;\n      const rr = root.getBoundingClientRect();\n      const k = root.offsetWidth ? rr.width / root.offsetWidth : 1;\n      const next = new Map<string, { x: number; y: number }>();\n      cells.forEach((el) => {\n        const r = el.getBoundingClientRect();\n        next.set(el.dataset.bgFlip ?? \"\", { x: (r.left - rr.left) / (k || 1), y: (r.top - rr.top) / (k || 1) });\n      });\n      prev.current = next;\n    });\n    ro.observe(root);\n    return () => ro.disconnect();\n  }, [ref]);\n}\n\n/**\n * One module of a run: a cell (what reflows move) holding a plate the rule\n * may break. Broken, the plate grows two gutters out at its leading edge (one\n * closes the gap, one overlaps the neighbour) while its padding grows by the\n * same, so its content never moves and never reaches the overlap; it rides\n * one layer up, wears the bracket and gets a firmer leading edge, so the\n * overlap reads as two plates, not one slab. The module before a breaker\n * `yields`: its trailing padding grows by a gutter, so nothing it holds sits\n * under the overlap. The hand-off (breaking, or letting go) takes 240ms.\n * Depth is the overlap and a 1px hairline, no shadow. Put runs in a `.bg-grid`\n * (or any grid whose column gap is --bg-g).\n */\nexport function BgPlate({\n  flip,\n  index,\n  breaks,\n  yields = false,\n  ground = FIELD.paper,\n  color = FIELD.ink,\n  line = FIELD.lineOnPaper,\n  edge,\n  pad = 24,\n  lift = 0,\n  itemRole,\n  className = \"\",\n  plateClassName = \"\",\n  style,\n  plateStyle,\n  children,\n}: {\n  /** A stable id, for reflows. */\n  flip?: string;\n  /** The module's number in its run, from 1 (shown by the inspector). */\n  index: number;\n  breaks: boolean;\n  /** The next module breaks: keep a gutter of trailing padding clear of its overlap. */\n  yields?: boolean;\n  ground?: string;\n  color?: string;\n  line?: string;\n  /** The breaker's leading edge; defaults to half-strength text colour. */\n  edge?: string;\n  /** Inner padding in px; the overshoot is added to it at the leading edge. */\n  pad?: number;\n  /** Extra layers up. */\n  lift?: number;\n  /** A role for the cell, such as listitem inside a list. */\n  itemRole?: string;\n  className?: string;\n  plateClassName?: string;\n  style?: CSSProperties;\n  plateStyle?: CSSProperties;\n  children?: ReactNode;\n}) {\n  const reduced = useReducedMotion();\n  const hand = `${BG_HANDOFF_MS}ms ${BG_EASE}`;\n  const rim = edge ?? (color === FIELD.paper ? FIELD.edgeOnField : FIELD.edgeOnPaper);\n  return (\n    <div data-bg-flip={flip} role={itemRole} className={\"relative \" + className} style={{ zIndex: (breaks ? 2 : 1) + lift, ...style }}>\n      <div\n        data-bg-module=\"\"\n        data-bg-index={index}\n        data-bg-break={breaks ? \"true\" : \"false\"}\n        data-bg-yield={yields ? \"true\" : undefined}\n        className={\"relative h-full \" + plateClassName}\n        style={{\n          background: ground,\n          color,\n          boxShadow: breaks ? `inset 1px 0 0 ${rim}, inset 0 0 0 1px ${line}` : `inset 0 0 0 1px ${line}`,\n          marginInlineStart: breaks ? \"calc(var(--bg-g, 24px) * -2)\" : \"0px\",\n          paddingInlineStart: breaks ? `calc(${pad}px + var(--bg-g, 24px) * 2)` : `${pad}px`,\n          paddingInlineEnd: yields ? `calc(${pad}px + var(--bg-g, 24px))` : `${pad}px`,\n          transition: reduced ? \"none\" : `margin-inline-start ${hand}, padding-inline-start ${hand}, padding-inline-end ${hand}, background-color ${hand}, box-shadow ${hand}`,\n          ...plateStyle,\n        }}\n      >\n        <BgBracket on={breaks} className=\"bg-own\" />\n        {children}\n      </div>\n    </div>\n  );\n}\n\nconst FLIP_CSS =\n  \".bg-flip-run>*{grid-column:span var(--bg-span-phone,2)}\" +\n  \"@container (min-width:48rem){.bg-flip-run>*{grid-column:span var(--bg-span,3)}}\";\n\n/**\n * RuleHandoffFlip — the kit's rule for any list, with reflows that hand the\n * break on.\n *\n * Give it items, a key and a render function: it lays them on the lattice\n * (each `span` columns of twelve, `spanPhone` of four) as plates, and every\n * third breaks by the rule, two gutters out at its leading edge with the\n * bracket, while the plate it overlaps keeps a gutter of padding clear.\n * Filter, sort or add, and every item moves from where it was to where it\n * is, all at once, in 380ms on the kit's curve; the break is recomputed from\n * the new order, so it passes to whichever item is now third (the old one\n * lets go in 240ms). Reduced motion moves them instantly. It brings its own\n * @container, so it lays out by its own width. It is a client component:\n * pass `getKey` and `render` from a client component (functions can't cross\n * from a server one). For your own markup, the same parts are exported:\n * bgBreaks (the rule), BgPlate (the module) and useRuleFlip (the reflow).\n */\nexport function RuleHandoffFlip<T>({\n  items,\n  getKey,\n  render,\n  every = 3,\n  span = 3,\n  spanPhone = 2,\n  surface = \"field\",\n  ground = FIELD.paper,\n  color = FIELD.ink,\n  pad = 16,\n  label,\n  className = \"\",\n}: {\n  items: T[];\n  getKey: (item: T) => string;\n  render: (item: T, index: number) => ReactNode;\n  every?: number;\n  /** Columns per item, of twelve. */\n  span?: number;\n  /** Columns per item on a phone, of four. */\n  spanPhone?: number;\n  /** The ground the list sits on, which sets the bracket's colour (acid on the field, ink on paper). */\n  surface?: \"field\" | \"paper\";\n  /** The plates' colour and their text colour. */\n  ground?: string;\n  color?: string;\n  pad?: number;\n  /** An accessible name for the list. */\n  label?: string;\n  className?: string;\n}) {\n  const ref = useRef<HTMLDivElement>(null);\n  const keys = items.map(getKey).join(\"|\");\n  useRuleFlip(ref, keys);\n  return (\n    <div className={\"bg-scope w-full @container \" + className} style={bgMark(surface)}>\n      <style>{GRID_CSS + FLIP_CSS + FOCUS_CSS}</style>\n      <div\n        ref={ref}\n        role=\"list\"\n        aria-label={label}\n        className=\"bg-grid bg-flip-run relative gap-y-6\"\n        style={{ [\"--bg-span\" as string]: String(clamp(span, 1, 12)), [\"--bg-span-phone\" as string]: String(clamp(spanPhone, 1, 4)) } as CSSProperties}\n      >\n        {items.map((it, i) => (\n          <BgPlate\n            key={getKey(it)}\n            flip={getKey(it)}\n            index={i + 1}\n            breaks={bgBreaks(i, items.length, every)}\n            yields={bgBreaks(i + 1, items.length, every)}\n            ground={ground}\n            color={color}\n            line={color === FIELD.paper ? FIELD.lineOnField : FIELD.lineOnPaper}\n            pad={pad}\n            itemRole=\"listitem\"\n            plateClassName=\"py-6\"\n          >\n            {render(it, i)}\n          </BgPlate>\n        ))}\n      </div>\n    </div>\n  );\n}\n","type":"registry:component","target":"components/viberdy/rule-handoff-flip.tsx"}],"meta":{"tier":"free","tags":["animation","flip","layout animation","list","grid","broken grid","filter"],"href":"https://viberdy.dev/library/rule-handoff-flip","aiPrompt":"Build a React component, `RuleHandoffFlip<T>({ items, getKey, render, every, span, spanPhone, surface, ground, color, pad, label, className })`, and export its parts: `bgBreaks(index, count, every)`, `BgPlate` and `useRuleFlip(ref, key)`.\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\nThe lattice (a 2D canvas behind the modules, no libraries): metrics from the host width (12 or 4 columns as above); vertical hairlines at margin + i * pitch - gutter / 2, rows at the same pitch from the margin (or lined up with the topmost module); every element marked data-bg-module is measured (data-bg-index for its number, data-bg-break for the rule, data-bg-over for a different overshoot such as a column pitch for type, data-bg-lead for an overshoot drawn outside its box). Where a breaking module's overshoot band crosses a vertical line, the line bends one gutter in the overshoot's direction over the module's height, easing back on a raised cosine over one pitch above and below; the pointer leans nearby lines away by up to three quarters of a gutter. Lines are sampled every 6px, each sample easing toward its target (time constant 90ms, settled in about 360ms); the canvas sleeps when nothing moves and wakes on resize (redrawing in the same frame), pointer, visibility and changes to the modules only (a MutationObserver that ignores other changes in the host); its backing store stays under 16M pixels. The inspector outlines every module with its number and reads each break out: the module, its overshoot (two gutters, or one column pitch for type) and which module on its left it covers, by how much. Reflows: useRuleFlip measures cells marked data-bg-flip after every change and plays a Web Animations transform from where each was to where it is, in 380ms; a reflow that starts mid-flight starts from where the cell is on screen, and a resize quietly re-reads where everything rests.\n\nAn @container wrapper (its mark colour from `surface`: acid on the field, ink on paper) around a role=list 12-column grid (4 on a phone) whose children span --bg-span (and --bg-span-phone) columns. Each item is a role=listitem cell holding a plate (ground, color, 1px hairline, padding `pad`) that breaks when bgBreaks(index, count, every), the one before a breaker adding a gutter of trailing padding. On every change of the keys, useRuleFlip measures each cell (data-bg-flip = key) and animates it from where it was (plus any running animation's offset, which it cancels) to where it is: transform translate, 380ms, cubic-bezier(.2,.8,.2,1). New cells rise 12px into place; a ResizeObserver re-reads resting places without animating. A client component: getKey and render are functions.","license":"https://viberdy.dev/license"}}