{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"punch-card-field","type":"registry:component","title":"Punch Card Field","description":"A background of 80-column punch cards whose holes spell real text in Hollerith code. Holes are punched in column by column on arrival; point at a column to decode it.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/punch-card-field.tsx","content":"\"use client\";\n\nimport { useId, useState } from \"react\";\nimport type { CSSProperties, PointerEvent as ReactPointerEvent, ReactNode } from \"react\";\n\n/**\n * PunchCardField — a neo-brutalist background of 80-column punch cards whose\n * holes spell real text.\n *\n * Each card encodes one line in Hollerith code, the way an IBM keypunch\n * would: twelve rows (12, 11, 0 to 9), a letter as a zone punch plus a digit\n * punch, digits as one punch, a few symbols as three. The typed line is\n * printed along the card's top edge, one character over each column, and the\n * unpunched positions carry their printed digits. Cards are cream with a\n * clipped corner, a 3px ink border and a 5px hard shadow, laid across the\n * ground at a tilt.\n *\n * On arrival the holes are punched column by column, 8ms apart, like the\n * punch head crossing the card; after that nothing moves on its own. Point at\n * a column (or tap it) and the decoder frames it and reads it back: the\n * character and its punches, e.g. \"R · 11-9\".\n *\n * Children render on top, above the field; the layer they sit in lets the\n * pointer through, and each direct child takes it back (add pointer-events-none\n * to a child that should let the decoder through). The field itself is\n * decoration and hidden from assistive technology.\n *\n * Needs Tailwind v4 (or v3.4+). No dependencies beyond React.\n */\n\nconst MONO = 'var(--font-mono, \"Geist Mono\", ui-monospace, \"SFMono-Regular\", Menlo, Consolas, monospace)';\nconst HEX = /^#[0-9a-fA-F]{6}$/;\n\nconst FILLS = {\n  yellow: \"#ffd23f\",\n  coral: \"#ff6b6b\",\n  blue: \"#74b9ff\",\n  lime: \"#b4f462\",\n  pink: \"#ff5fa2\",\n} as const;\n\nfunction own<T extends object>(map: T, key: string): key is Extract<keyof T, string> {\n  return Object.prototype.hasOwnProperty.call(map, key);\n}\n\n/** Row indices top to bottom: 12, 11, 0, 1 … 9. */\nconst ROW_NAMES = [\"12\", \"11\", \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"];\nconst row = (name: string) => ROW_NAMES.indexOf(name);\n\n/** Symbols in the IBM 029 code: the punched rows for each. */\nconst SYMBOLS: Record<string, string[]> = {\n  \"&\": [\"12\"],\n  \"-\": [\"11\"],\n  \"/\": [\"0\", \"1\"],\n  \".\": [\"12\", \"3\", \"8\"],\n  \",\": [\"0\", \"3\", \"8\"],\n  \":\": [\"2\", \"8\"],\n  \"'\": [\"5\", \"8\"],\n  \"#\": [\"3\", \"8\"],\n  \"@\": [\"4\", \"8\"],\n  \"?\": [\"0\", \"7\", \"8\"],\n  \"!\": [\"11\", \"2\", \"8\"],\n  \"(\": [\"12\", \"5\", \"8\"],\n  \")\": [\"11\", \"5\", \"8\"],\n  \"+\": [\"12\", \"6\", \"8\"],\n  \"=\": [\"6\", \"8\"],\n  \"*\": [\"11\", \"4\", \"8\"],\n  \"$\": [\"11\", \"3\", \"8\"],\n  \"%\": [\"0\", \"4\", \"8\"],\n};\n\n/** The punched rows for one character, or [] for a space or anything unknown. */\nfunction punches(ch: string): string[] {\n  const c = ch.toUpperCase();\n  if (c >= \"0\" && c <= \"9\") return [c];\n  if (c >= \"A\" && c <= \"I\") return [\"12\", String(c.charCodeAt(0) - 64)];\n  if (c >= \"J\" && c <= \"R\") return [\"11\", String(c.charCodeAt(0) - 73)];\n  if (c >= \"S\" && c <= \"Z\") return [\"0\", String(c.charCodeAt(0) - 81)];\n  return Object.prototype.hasOwnProperty.call(SYMBOLS, c) ? SYMBOLS[c] : [];\n}\n\n// Card geometry in SVG units: 80 columns 10 apart, 12 rows 28 apart.\nconst COLS = 80;\nconst PITCH_X = 10;\nconst PITCH_Y = 28;\nconst LEFT = 30;\nconst TOP = 46;\nconst W = LEFT * 2 + COLS * PITCH_X;\nconst H = TOP + 12 * PITCH_Y + 18;\nconst HOLE_W = 5.5;\nconst HOLE_H = 15;\nconst CUT = 26;\n\nexport type PunchCardFieldProps = {\n  /** One line per card, up to 80 characters; they repeat to fill the field. */\n  lines?: string[];\n  /** How many cards to lay out. */\n  count?: number;\n  /** Card width in px. */\n  cardWidth?: number;\n  /** Tilt of the whole field in degrees, -8 to 8. */\n  tilt?: number;\n  /** Punch the holes in on arrival. */\n  punchIn?: boolean;\n  /** Frame and read back the column under the pointer. */\n  decoder?: boolean;\n  /** The ground behind the cards: a kit fill, \"ink\", \"cream\" or #rrggbb. */\n  ground?: keyof typeof FILLS | \"ink\" | \"cream\" | string;\n  ink?: string;\n  children?: ReactNode;\n  className?: string;\n};\n\n/**\n * PLACEHOLDER lines for \"Hod\", the kit's fictional branch-preview tool. The\n * build figures in them are invented: pass your own lines before shipping.\n */\nconst DEFAULT_LINES = [\n  \"HOD BRANCH PREVIEWS\",\n  \"SHIP THE ROUGH DRAFT TODAY.\",\n  \"EVERY PUSH GETS A LINK - SHARE IT BEFORE YOU MERGE\",\n  \"PREVIEW #482 BUILD OK 38S CHECKS 12/12\",\n  \"COMMENTS PINNED TO THE ELEMENT\",\n  \"ROLL BACK IN ONE KEY: R\",\n];\n\nfunction Card({ text, n, ink, uid, punchIn, decoder, active, onCol }: {\n  text: string;\n  n: number;\n  ink: string;\n  uid: string;\n  punchIn: boolean;\n  decoder: boolean;\n  active: number;\n  onCol: (col: number) => void;\n}) {\n  const chars = [...text.toUpperCase()].slice(0, COLS);\n  const holes: { x: number; y: number; col: number }[] = [];\n  chars.forEach((ch, col) => {\n    punches(ch).forEach((r) => holes.push({ x: LEFT + col * PITCH_X + (PITCH_X - HOLE_W) / 2, y: TOP + row(r) * PITCH_Y + (PITCH_Y - HOLE_H) / 2, col }));\n  });\n  const shape = \"M\" + CUT + \" 0H\" + W + \"V\" + H + \"H0V\" + CUT + \"Z\";\n  const pick = (e: ReactPointerEvent<SVGSVGElement>) => {\n    if (!decoder) return;\n    const svg = e.currentTarget;\n    const m = svg.getScreenCTM();\n    if (!m) return;\n    // Screen to card units, through the field's tilt and any preview scaling.\n    const p = new DOMPoint(e.clientX, e.clientY).matrixTransform(m.inverse());\n    const col = Math.floor((p.x - LEFT) / PITCH_X);\n    onCol(col >= 0 && col < COLS && p.y > 0 && p.y < H ? col : -1);\n  };\n  const ch = active >= 0 ? chars[active] ?? \" \" : \"\";\n  const read = active >= 0 ? (ch === \" \" ? \"SPACE\" : ch) + \" · \" + (punches(ch).join(\"-\") || \"no punch\") : \"\";\n  return (\n    <svg\n      viewBox={\"-6 -6 \" + (W + 14) + \" \" + (H + 14)}\n      className=\"block h-auto w-full overflow-visible\"\n      onPointerMove={pick}\n      onPointerDown={pick}\n      onPointerLeave={() => onCol(-1)}\n    >\n      <path d={shape} fill={ink} transform=\"translate(5 5)\" />\n      <path d={shape} fill=\"#fffdf5\" stroke={ink} strokeWidth=\"3\" strokeLinejoin=\"miter\" />\n      {/* Printed digits in rows 0 to 9 of every column, as one pattern. */}\n      <rect x={LEFT} y={TOP + 2 * PITCH_Y} width={COLS * PITCH_X} height={10 * PITCH_Y} fill={\"url(#\" + uid + \"-digits)\"} />\n      {/* The interpreted line along the top edge, one character over each column. */}\n      <text\n        x={chars.map((_, i) => LEFT + i * PITCH_X + PITCH_X / 2).join(\" \")}\n        y={TOP - 14}\n        fontSize=\"9\"\n        textAnchor=\"middle\"\n        fill={ink}\n        style={{ fontFamily: MONO, fontWeight: 700 }}\n      >\n        {chars.map((c) => (c === \" \" ? String.fromCharCode(160) : c)).join(\"\")}\n      </text>\n      <text x={W - 14} y={H - 6} fontSize=\"8\" textAnchor=\"end\" fill={ink} opacity=\"0.6\" style={{ fontFamily: MONO }}>\n        {\"CARD \" + String(n + 1).padStart(3, \"0\")}\n      </text>\n      {holes.map((h, i) => (\n        <rect\n          key={i}\n          className={punchIn ? \"pcf-hole\" : undefined}\n          x={h.x}\n          y={h.y}\n          width={HOLE_W}\n          height={HOLE_H}\n          fill={ink}\n          style={punchIn ? ({ \"--pcf-at\": n * 90 + h.col * 8 + \"ms\" } as CSSProperties) : undefined}\n        />\n      ))}\n      {decoder && active >= 0 && (\n        <g pointerEvents=\"none\">\n          <rect x={LEFT + active * PITCH_X - 2} y={TOP - 3} width={PITCH_X + 4} height={12 * PITCH_Y + 6} fill=\"none\" stroke={ink} strokeWidth=\"3\" />\n          <g transform={\"translate(\" + Math.min(W - 118, Math.max(0, LEFT + active * PITCH_X - 50)) + \" \" + (TOP - 40) + \")\"}>\n            <rect width=\"118\" height=\"22\" fill={ink} />\n            <text x=\"59\" y=\"15\" fontSize=\"11\" textAnchor=\"middle\" fill=\"#fffdf5\" style={{ fontFamily: MONO, fontWeight: 700 }}>\n              {\"COL \" + (active + 1) + \" · \" + read}\n            </text>\n          </g>\n        </g>\n      )}\n    </svg>\n  );\n}\n\nexport function PunchCardField({\n  lines = DEFAULT_LINES,\n  count = 9,\n  cardWidth = 560,\n  tilt = -5,\n  punchIn = true,\n  decoder = true,\n  ground = \"yellow\",\n  ink = \"#000000\",\n  children,\n  className = \"\",\n}: PunchCardFieldProps) {\n  const uid = useId().replace(/[^a-zA-Z0-9]/g, \"\");\n  const [hot, setHot] = useState<{ card: number; col: number }>({ card: -1, col: -1 });\n  const line = HEX.test(ink) ? ink : \"#000000\";\n  const bg = ground === \"ink\" ? line : ground === \"cream\" ? \"#fffdf5\" : own(FILLS, ground) ? FILLS[ground] : HEX.test(ground) ? ground : FILLS.yellow;\n  const list = lines.length ? lines : DEFAULT_LINES;\n  const n = Math.max(1, Math.min(24, Math.round(Number.isFinite(count) ? count : 9)));\n  const width = Math.max(320, Math.min(900, Number.isFinite(cardWidth) ? cardWidth : 560));\n  const angle = Math.max(-8, Math.min(8, Number.isFinite(tilt) ? tilt : -5));\n\n  return (\n    <div className={\"relative isolate overflow-hidden \" + className} style={{ background: bg }}>\n      <style>\n        {\"@keyframes pcf-punch{from{visibility:hidden}to{visibility:visible}}\" +\n          \"@media (prefers-reduced-motion: no-preference){.pcf-hole{animation:pcf-punch 1ms steps(1,end) var(--pcf-at,0ms) backwards}}\"}\n      </style>\n      <svg aria-hidden width=\"0\" height=\"0\" className=\"absolute\">\n        <defs>\n          <pattern id={uid + \"-digits\"} width={PITCH_X} height={10 * PITCH_Y} patternUnits=\"userSpaceOnUse\" x={LEFT} y={TOP + 2 * PITCH_Y}>\n            {Array.from({ length: 10 }, (_, d) => (\n              <text key={d} x={PITCH_X / 2} y={d * PITCH_Y + PITCH_Y / 2 + 3} fontSize=\"7.5\" textAnchor=\"middle\" fill={line} opacity=\"0.42\" style={{ fontFamily: MONO }}>\n                {d}\n              </text>\n            ))}\n          </pattern>\n        </defs>\n      </svg>\n      <div aria-hidden className=\"pointer-events-none absolute inset-0 -z-10 flex items-center justify-center\">\n        <div\n          className=\"pointer-events-auto grid shrink-0 gap-x-10 gap-y-9\"\n          style={{\n            width: \"max(170%, \" + width * 3.4 + \"px)\",\n            gridTemplateColumns: \"repeat(auto-fill, minmax(\" + width + \"px, 1fr))\",\n            transform: \"rotate(\" + angle + \"deg)\",\n          }}\n        >\n          {Array.from({ length: n }, (_, i) => (\n            <Card\n              key={i}\n              n={i}\n              text={list[i % list.length]}\n              ink={line}\n              uid={uid}\n              punchIn={punchIn}\n              decoder={decoder}\n              active={hot.card === i ? hot.col : -1}\n              onCol={(col) =>\n                setHot((prev) =>\n                  col < 0 ? (prev.card === i ? { card: -1, col: -1 } : prev) : prev.card === i && prev.col === col ? prev : { card: i, col },\n                )\n              }\n            />\n          ))}\n        </div>\n      </div>\n      {/* The layer itself lets the pointer through to the cards; its direct children take it back. */}\n      {children && <div className=\"pointer-events-none relative [:where(&)>*]:pointer-events-auto\">{children}</div>}\n    </div>\n  );\n}\n","type":"registry:component","target":"components/viberdy/punch-card-field.tsx"}],"meta":{"tier":"free","tags":["background","punch card","hollerith","neo-brutalism","brutalist","retro computing","svg","pattern"],"href":"https://viberdy.dev/library/punch-card-field","aiPrompt":"Create a React + Tailwind background, PunchCardField: a neo-brutalist field of 80-column punch cards whose holes spell real text in Hollerith code, with children rendered on top.\n\nProps (export PunchCardFieldProps): lines (one line per card, up to 80 characters, repeating to fill the field), count (cards, 1-24, default 9), cardWidth (px, 320-900, default 560), tilt (-8 to 8 degrees, default -5), punchIn (default true), decoder (default true), ground (behind the cards: yellow #ffd23f default, coral #ff6b6b, blue #74b9ff, lime #b4f462, pink #ff5fa2, \"ink\", \"cream\" #fffdf5, or a regex-validated hex; own-key lookup), ink (#000), children (rendered above the field in a layer with pointer-events none whose direct children take pointer events back, so the decoder works around them), className (give it a height). Clamp numbers and fall back on NaN.\n\nThe code: twelve rows top to bottom 12, 11, 0, 1-9. Digits punch their own row; A-I punch 12 plus 1-9; J-R punch 11 plus 1-9; S-Z punch 0 plus 2-9; symbols from the IBM 029 table (& 12, - 11, / 0-1, . 12-3-8, , 0-3-8, : 2-8, ' 5-8, # 3-8, @ 4-8, ? 0-7-8, ! 11-2-8, ( 12-5-8, ) 11-5-8, + 12-6-8, = 6-8, * 11-4-8, $ 11-3-8, % 0-4-8); a space or anything unknown punches nothing. Look the symbol table up by own key.\n\nEach card is one SVG (viewBox units: columns 10 apart from x 30, rows 28 apart from y 46, so 860 x 400): a cream #fffdf5 body with its top-left corner cut at 45 degrees, a 3px ink border (miter joins) and a copy of the shape in ink offset 5,5 as the hard shadow; the printed digits 0-9 in rows 0-9 of every column drawn as ONE rect filled with a pattern (one column wide, ten digits in mono at 42% ink), defined once in a hidden SVG with a useId-based id stripped to alphanumerics; the typed line along the top edge as ONE text element with a list of x positions (one per column, spaces as non-breaking spaces from String.fromCharCode(160)); a mono \"CARD 001\" at the bottom right; and the punched positions as 5.5 x 15 ink rects. Lay the cards in a CSS grid (auto-fill, minmax(cardWidth, 1fr), 40px and 36px gaps) wider than the field (max(170%, cardWidth x 3.4)), centred and rotated by tilt, absolutely filling the container behind the children (isolate, overflow hidden, -z-10, aria-hidden, the grid itself takes pointer events).\n\nPunch-in: each hole has a 1ms steps(1, end) animation from visibility hidden with fill backwards and a delay of card index x 90ms plus column x 8ms, so the punch head crosses each card; only under prefers-reduced-motion: no-preference; nothing moves afterwards.\n\nDecoder: on pointer move or down over a card, map the pointer into card units with the SVG's getScreenCTM().inverse() (this goes through the tilt and any preview scaling), pick the column, and draw a 3px ink frame around that column's twelve rows plus an ink label above it reading \"COL 17 · R · 11-9\" (or \"SPACE · no punch\") in cream mono; clear on leave. Only update state when the card or column changes.\n\nOutput one self-contained \"use client\" TSX file with no dependencies beyond React. Build strings with + rather than template literals.","license":"https://viberdy.dev/license"}}