{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tear",
  "title": "Tear",
  "description": "A sheet torn into strips along seams: controlled progress moves each strip to its own destination, with frayed, seeded edges at every seam.",
  "registryDependencies": [
    "@jbm/tokens",
    "@jbm/paper",
    "@jbm/register"
  ],
  "files": [
    {
      "path": "registry/jbm/ui/tear.tsx",
      "content": "import type { CSSProperties, ReactNode } from \"react\"\nimport { color, stroke } from \"../lib/tokens\"\nimport {\n  FRAY,\n  frayEdge,\n  frayReach,\n  paperFill,\n  paperShadow,\n  type PaperTone,\n} from \"./paper\"\nimport { sheetRadius } from \"./register\"\n\n/** Where one strip goes: an offset from its place in the whole sheet (stage px) and a turn (degrees). */\nexport type TearDestination = { x?: number; y?: number; rotate?: number }\nexport type TearPiece = { to?: TearDestination }\n/** What a render-prop child receives for each strip. Coordinates are the whole sheet's. */\nexport type TearPieceInfo = {\n  index: number\n  /** The seam above the strip (0 for the first). */\n  top: number\n  /** The seam below the strip (h for the last). */\n  bottom: number\n  /** This strip's own 0–1 travel after stagger. */\n  progress: number\n}\nexport type TearProps = {\n  /** Sheet width in stage px. */\n  w: number\n  /** Sheet height in stage px. */\n  h: number\n  /** Seam y positions in stage px from the top edge; n seams make n + 1 strips. */\n  seams: number[]\n  /** 0 = the whole sheet, 1 = every strip at its destination. Linear; ease it yourself. */\n  progress: number\n  /** Per-strip destinations, top to bottom. A missing entry stays put. */\n  pieces?: TearPiece[]\n  /** Delay between strips as a share of progress: strip i starts at i × stagger. */\n  stagger?: number\n  /** Fray pattern; Paper's starting tear with the same seed and seam continues the same edge. */\n  seed?: number\n  /** Fray amplitude in stage px. */\n  fray?: number\n  tone?: PaperTone\n  /** Outer corner radius in stage px; default sheetRadius(w), the same corner as a Register sheet of that width. */\n  radius?: number\n  edge?: boolean\n  shadow?: boolean\n  /**\n   * The sheet's writing, laid out on the whole w × h sheet and clipped to each strip. A function is\n   * called once per strip with that strip's info; a node is repeated in every strip.\n   */\n  children?: ReactNode | ((piece: TearPieceInfo) => ReactNode)\n  /** Styles for the w × h content layer each strip clips (padding, layout). */\n  contentStyle?: CSSProperties\n  style?: CSSProperties\n}\n\n/** How far past the sheet a strip's clip reaches, so it never trims a shadow or a turned corner. */\nconst FAR = 2000\nconst finite = (n: number, fallback = 0) => (Number.isFinite(n) ? n : fallback)\nconst clamp01 = (n: number) => Math.min(1, Math.max(0, finite(n)))\nconst r2 = (n: number) => Math.round(n * 100) / 100\n\n/**\n * The seams Tear actually uses: finite, sorted, at least one fray reach plus 4px inside the sheet,\n * and far enough apart that neighbouring frayed edges never cross.\n */\nexport function tearSeams(h: number, seams: number[], fray = FRAY) {\n  const margin = frayReach(fray) + 4\n  const out: number[] = []\n  for (const y of [...seams].filter(Number.isFinite).sort((a, b) => a - b)) {\n    if (y < margin || y > h - margin) continue\n    if (out.length && y - out[out.length - 1] < 2 * margin) continue\n    out.push(y)\n  }\n  return out\n}\n\n/** Strip i's own 0–1 travel: it starts at i × stagger and ends at progress 1. */\nexport function tearPieceProgress(\n  progress: number,\n  index: number,\n  count: number,\n  stagger = 0\n) {\n  const s = count > 1 ? Math.min(clamp01(stagger), 0.9 / (count - 1)) : 0\n  return clamp01((clamp01(progress) - index * s) / (1 - s * (count - 1)))\n}\n\ntype Pt = { x: number; y: number }\nexport type TearGeometry = {\n  index: number\n  top: number\n  bottom: number\n  /** Closed outline of the strip in sheet coordinates: straight sheet edges, frayed seams. */\n  outline: string\n  /** The straight (uncut) edges of the strip. */\n  edges: string\n  /** Frayed seam edges: above (null for the first strip) and below (null for the last). */\n  seamAbove: string | null\n  seamBelow: string | null\n  /** Rotation centre of the strip in sheet coordinates. */\n  center: Pt\n}\n\n/**\n * Outlines for every strip. Neighbouring strips share the identical frayed polyline at their seam, so\n * together the outlines cover the sheet exactly. Stroke-centred: with an edge, the uncut sides sit\n * half the shared outline inside the box, like Paper's border.\n */\nexport function tearGeometry({\n  w,\n  h,\n  seams,\n  seed = 1,\n  fray = FRAY,\n  radius,\n  edge = true,\n}: {\n  w: number\n  h: number\n  seams: number[]\n  seed?: number\n  fray?: number\n  radius?: number\n  edge?: boolean\n}): TearGeometry[] {\n  const W = Math.max(0, finite(w)),\n    H = Math.max(0, finite(h))\n  const e = edge ? stroke.outline / 2 : 0\n  const R = radius ?? sheetRadius(W)\n  const cuts = tearSeams(H, seams, fray)\n  const lines = cuts.map((y) =>\n    frayEdge({ width: W, y, seed, amplitude: fray }).map((p) => ({\n      x: Math.min(W - e, Math.max(e, p.x)),\n      y: p.y,\n    }))\n  )\n  const bounds = [0, ...cuts, H]\n  const poly = (pts: Pt[]) => pts.map((p) => `L${r2(p.x)} ${r2(p.y)}`).join(\"\")\n  return bounds.slice(0, -1).map((top, i) => {\n    const bottom = bounds[i + 1]\n    const above = i > 0 ? lines[i - 1] : null\n    const below = i < cuts.length ? lines[i] : null\n    const span = (above ? top : e) - (below ? bottom : H - e)\n    const r = Math.max(\n      0,\n      Math.min(finite(R) - e, W / 2 - e, Math.abs(span) / (above || below ? 1 : 2))\n    )\n    const arc = (x: number, y: number) => `A${r2(r)} ${r2(r)} 0 0 1 ${r2(x)} ${r2(y)}`\n    const topRun = above\n      ? `M${r2(above[0].x)} ${r2(above[0].y)}${poly(above.slice(1))}`\n      : `M${e} ${r2(e + r)}${arc(e + r, e)}H${r2(W - e - r)}${arc(W - e, e + r)}`\n    const bottomRun = below\n      ? `L${r2(below[below.length - 1].x)} ${r2(below[below.length - 1].y)}${poly([...below].reverse().slice(1))}`\n      : `V${r2(H - e - r)}${arc(W - e - r, H - e)}H${r2(e + r)}${arc(e, H - e - r)}`\n    const tL = above ? above[0].y : e + r,\n      tR = above ? above[above.length - 1].y : e + r\n    const bL = below ? below[0].y : H - e - r,\n      bR = below ? below[below.length - 1].y : H - e - r\n    let edges: string\n    if (!above && !below) edges = `${topRun}${bottomRun}Z`\n    else if (!above)\n      edges = `M${e} ${r2(bL)}V${r2(e + r)}${arc(e + r, e)}H${r2(W - e - r)}${arc(W - e, e + r)}V${r2(bR)}`\n    else if (!below)\n      edges = `M${r2(W - e)} ${r2(tR)}V${r2(H - e - r)}${arc(W - e - r, H - e)}H${r2(e + r)}${arc(e, H - e - r)}V${r2(tL)}`\n    else edges = `M${e} ${r2(tL)}V${r2(bL)}M${r2(W - e)} ${r2(tR)}V${r2(bR)}`\n    const line = (pts: Pt[] | null) =>\n      pts ? `M${r2(pts[0].x)} ${r2(pts[0].y)}${poly(pts.slice(1))}` : null\n    return {\n      index: i,\n      top,\n      bottom,\n      outline: `${topRun}${bottomRun}Z`,\n      edges,\n      seamAbove: line(above),\n      seamBelow: line(below),\n      center: { x: r2(W / 2), y: r2((top + bottom) / 2) },\n    }\n  })\n}\n\n/**\n * Where a strip is at its own progress p toward `to`: it parts along the seam first (y follows p)\n * and drifts and turns as it travels (x and rotate follow p²), so neighbouring torn edges separate\n * as parallel copies before they shift, and never cross while they are close.\n */\nexport function tearMotion(to: TearDestination = {}, progress: number) {\n  const p = clamp01(progress)\n  return {\n    x: finite(to.x ?? 0) * p * p,\n    y: finite(to.y ?? 0) * p,\n    rotate: finite(to.rotate ?? 0) * p * p,\n  }\n}\n\n/** Room the shadows take around a strip: the sheet's and each strip's drop shadow fall down. */\nconst SHADOW_ROOM = { top: 8, side: 16, bottom: 34 }\n\n/**\n * The box, in the sheet's px (origin at its top-left, so x and y can be negative), that every strip\n * stays inside at every progress: Tear's root is only w × h, and strips travel past it by their\n * destinations. With `shadow` (default true) it includes the room the shadows take. Reserve this box\n * (or give the stage at least this much room) so no strip or shadow is clipped.\n */\nexport function tearBounds({\n  w,\n  h,\n  seams,\n  pieces = [],\n  fray = FRAY,\n  shadow = true,\n}: Pick<TearProps, \"w\" | \"h\" | \"seams\" | \"pieces\" | \"fray\" | \"shadow\">) {\n  const W = Math.max(0, finite(w)),\n    H = Math.max(0, finite(h))\n  const bounds = [0, ...tearSeams(H, seams, fray), H]\n  const reach = frayReach(fray)\n  let x0 = 0,\n    y0 = 0,\n    x1 = W,\n    y1 = H\n  bounds.slice(0, -1).forEach((top, i) => {\n    const bottom = bounds[i + 1]\n    const t = i > 0 ? top - reach : 0\n    const b = i < bounds.length - 2 ? bottom + reach : H\n    const cx = W / 2,\n      cy = (top + bottom) / 2\n    const to = pieces[i]?.to ?? {}\n    // Translation and turn are both linear in the strip's own progress: sample the path.\n    for (let k = 0; k <= 32; k++) {\n      const p = k / 32\n      const m = tearMotion(to, p)\n      const a = (m.rotate * Math.PI) / 180\n      const dx = m.x,\n        dy = m.y\n      for (const [x, y] of [\n        [0, t],\n        [W, t],\n        [W, b],\n        [0, b],\n      ]) {\n        const px = cx + dx + (x - cx) * Math.cos(a) - (y - cy) * Math.sin(a)\n        const py = cy + dy + (x - cx) * Math.sin(a) + (y - cy) * Math.cos(a)\n        x0 = Math.min(x0, px)\n        x1 = Math.max(x1, px)\n        y0 = Math.min(y0, py)\n        y1 = Math.max(y1, py)\n      }\n    }\n  })\n  const pad = shadow === false ? { top: 0, side: 0, bottom: 0 } : SHADOW_ROOM\n  x0 = Math.floor(x0 - pad.side)\n  y0 = Math.floor(y0 - pad.top)\n  x1 = Math.ceil(x1 + pad.side)\n  y1 = Math.ceil(y1 + pad.bottom)\n  return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }\n}\n\n/**\n * A sheet torn into horizontal strips along seams. At progress 0 the strips tile the sheet exactly\n * and no seam shows; as progress rises each strip travels to its own destination and its torn edges\n * appear, frayed and deterministic. Pure React and controlled: the caller owns timing. The root is\n * w × h; strips move past it, so reserve tearBounds() around it.\n */\nexport function Tear({\n  w,\n  h,\n  seams,\n  progress,\n  pieces = [],\n  stagger = 0,\n  seed = 1,\n  fray = FRAY,\n  tone = \"paper\",\n  radius,\n  edge = true,\n  shadow = true,\n  children,\n  contentStyle,\n  style,\n}: TearProps) {\n  const W = Math.max(0, finite(w)),\n    H = Math.max(0, finite(h))\n  const R = radius ?? sheetRadius(W)\n  const strips = tearGeometry({ w: W, h: H, seams, seed, fray, radius: R, edge })\n  const local = strips.map((_, i) =>\n    tearPieceProgress(progress, i, strips.length, stagger)\n  )\n  // Shadows hand over from the whole sheet to the strips over the first 8% of travel.\n  const ramp = clamp01(Math.max(0, ...local) / 0.08)\n  const edgeColor = tone === \"paper\" ? color.ink : paperFill(tone)\n  // How far each seam has actually parted: the lower strip's drop past the upper one. Until a\n  // seam is open by more than the edge stroke, it draws one torn line (the upper strip's edge),\n  // never two coincident zig-zags; and the strips on either side of a seam that is still (almost)\n  // shut keep their sides flush, so the sheet's outline has no step. Sideways travel and turn\n  // come in as the seam opens.\n  const motion = strips.map((_, i) => tearMotion(pieces[i]?.to ?? {}, local[i]))\n  // A seam stays shut until its strips have parted 1.5px, then opens twice as fast to catch up\n  // at 3px: there is never a hairline gap with the sides broken across it.\n  const ease = (g: number) => (g < 1.5 ? 0 : g < 3 ? 2 * (g - 1.5) : g)\n  // Only seams whose strips are sent apart vertically (the lower one ends further down) ease this\n  // way; strips sent to the same height slide apart sideways as given.\n  const opens = (i: number) =>\n    finite(pieces[i]?.to?.y ?? 0) - finite(pieces[i - 1]?.to?.y ?? 0) > 0\n  const ys: number[] = []\n  motion.forEach((m, i) => {\n    ys.push(\n      i === 0 ? m.y : opens(i) ? ys[i - 1] + ease(m.y - motion[i - 1].y) : m.y\n    )\n  })\n  const gap = (i: number) => (i > 0 ? ys[i] - ys[i - 1] : Infinity)\n  const parted = (i: number) => (opens(i) ? clamp01(gap(i) / 6) : 1)\n  const joined = strips.map((_, i) =>\n    Math.min(i > 0 ? parted(i) : 1, i < strips.length - 1 ? parted(i + 1) : 1)\n  )\n  return (\n    <div\n      style={{\n        position: \"relative\",\n        width: W,\n        height: H,\n        ...style,\n      }}\n    >\n      {shadow && ramp < 1 && (\n        <div\n          aria-hidden\n          style={{\n            position: \"absolute\",\n            inset: 0,\n            borderRadius: R,\n            boxShadow: paperShadow,\n            opacity: 1 - ramp,\n          }}\n        />\n      )}\n      {strips.map((s, i) => {\n        const p = local[i]\n        const x = motion[i].x * joined[i],\n          y = ys[i],\n          rot = motion[i].rotate * joined[i]\n        // The lower edge of a seam (this strip's top) inks in only once the seam has opened past\n        // twice the stroke width; until then the upper strip's edge alone marks it.\n        const openAbove =\n          i > 0\n            ? opens(i)\n              ? clamp01((gap(i) - 2 * stroke.outline) / 2)\n              : clamp01(Math.max(p, local[i - 1]) / 0.05)\n            : 0\n        const openBelow =\n          i < strips.length - 1 ? clamp01(Math.max(p, local[i + 1]) / 0.05) : 0\n        const info: TearPieceInfo = { index: i, top: s.top, bottom: s.bottom, progress: p }\n        // While a seam is closed, the strips' shadows must not show along it (a line where no tear\n        // shows yet): clip the shadowed fill at the seam, 1px inside the strip below (the\n        // under-band covers that row), and let the clip recede 60px as the seam opens. Beside the\n        // sheet both strips' side shadows are cut on the same line, so they meet without a gap.\n        const run = (d: string | null, shift: number, lift: number) => {\n          const pts = d ? [...d.matchAll(/[ML](-?[\\d.]+) (-?[\\d.]+)/g)].map((m) => [+m[1], +m[2]]) : []\n          if (!pts.length) return []\n          const [x0, y0] = pts[0]\n          const [x1, y1] = pts[pts.length - 1]\n          return [\n            `-${FAR}px ${r2(y0 + lift)}px`,\n            `${x0}px ${r2(y0 + lift)}px`,\n            ...pts.map(([x, y]) => `${x}px ${r2(y + shift + lift)}px`),\n            `${x1}px ${r2(y1 + lift)}px`,\n            `${W + FAR}px ${r2(y1 + lift)}px`,\n          ]\n        }\n        const clipAbove = shadow && ramp > 0 && s.seamAbove !== null && openAbove < 1\n        const clipBelow = shadow && ramp > 0 && s.seamBelow !== null && openBelow < 1\n        const shadowClip =\n          clipAbove || clipBelow\n            ? `polygon(${[\n                ...(clipAbove ? run(s.seamAbove, 1, -61 * openAbove) : [`-${FAR}px -${FAR}px`, `${W + FAR}px -${FAR}px`]),\n                ...(clipBelow ? run(s.seamBelow, 0, 61 * openBelow).reverse() : [`${W + FAR}px ${H + FAR}px`, `-${FAR}px ${H + FAR}px`]),\n              ].join(\", \")})`\n            : undefined\n        const content = typeof children === \"function\" ? children(info) : children\n        return (\n          <div\n            key={i}\n            data-piece={i}\n            aria-hidden={i > 0 || undefined}\n            style={{\n              position: \"absolute\",\n              left: 0,\n              top: 0,\n              width: W,\n              height: H,\n              transform:\n                x || y || rot\n                  ? `translate(${r2(x)}px, ${r2(y)}px) rotate(${r2(rot)}deg)`\n                  : undefined,\n              transformOrigin: `${s.center.x}px ${s.center.y}px`,\n              pointerEvents: \"none\",\n            }}\n          >\n            <div\n              style={{\n                position: \"absolute\",\n                inset: 0,\n                filter:\n                  shadow && ramp > 0\n                    ? `drop-shadow(0 1px 1px rgba(32,36,31,${r2(0.1 * ramp)})) drop-shadow(0 8px 10px rgba(32,36,31,${r2(0.14 * ramp)}))`\n                    : undefined,\n                clipPath: shadowClip,\n              }}\n            >\n            <svg\n              width={W}\n              height={H}\n              aria-hidden\n              style={{ position: \"absolute\", inset: 0, overflow: \"visible\" }}\n            >\n              <path d={s.outline} fill={paperFill(tone)} />\n            </svg>\n            </div>\n            {/* While the seam is closed, a band of stock from half a pixel above the seam to 3px\n                below it runs under the next strip, so no antialiasing hairline shows where the two\n                fills (and the clipped shadows) meet. It sits outside the shadowed layer, so it\n                casts no shadow of its own. */}\n            {s.seamBelow && openBelow < 1 && (\n              <svg\n                width={W}\n                height={H}\n                aria-hidden\n                style={{ position: \"absolute\", inset: 0, overflow: \"visible\" }}\n              >\n                <path\n                  d={s.seamBelow}\n                  fill=\"none\"\n                  stroke={paperFill(tone)}\n                  strokeOpacity={r2(1 - openBelow)}\n                  strokeWidth={3.5}\n                  transform=\"translate(0 1.25)\"\n                />\n              </svg>\n            )}\n            {/* The writing, clipped to the strip, over the fill and the under-band. */}\n            {content != null && (\n              <div\n                style={{\n                  position: \"absolute\",\n                  inset: 0,\n                  boxSizing: \"border-box\",\n                  clipPath: `path(\"${s.outline}\")`,\n                  pointerEvents: \"auto\",\n                  ...contentStyle,\n                }}\n              >\n                {content}\n              </div>\n            )}\n            {/* The ink edges draw last. Like the writing they sit outside the clipped shadow layer,\n                so a closed seam never nicks the sheet's straight sides or its writing. */}\n            {edge && (\n              <svg\n                width={W}\n                height={H}\n                aria-hidden\n                style={{ position: \"absolute\", inset: 0, overflow: \"visible\" }}\n              >\n                <path\n                  d={s.edges}\n                  fill=\"none\"\n                  stroke={edgeColor}\n                  strokeWidth={stroke.outline}\n                  strokeLinejoin=\"round\"\n                  strokeLinecap=\"round\"\n                />\n                {[\n                  [s.seamAbove, openAbove],\n                  [s.seamBelow, openBelow],\n                ].map(([d, open], k) =>\n                  d && (open as number) > 0 ? (\n                    <path\n                      key={k}\n                      d={d as string}\n                      fill=\"none\"\n                      stroke={edgeColor}\n                      strokeOpacity={r2(open as number)}\n                      strokeWidth={stroke.outline}\n                      strokeLinejoin=\"round\"\n                      strokeLinecap=\"round\"\n                    />\n                  ) : null\n                )}\n              </svg>\n            )}\n          </div>\n        )\n      })}\n    </div>\n  )\n}\n",
      "type": "registry:ui",
      "target": "src/jbm/ui/tear.tsx"
    }
  ],
  "categories": [
    "UI Bits"
  ],
  "type": "registry:ui"
}