{
  "$schema": "../../schema.json",
  "version": "1.0.0",
  "license": "MIT",
  "id": "code-type",
  "type": "block",
  "title": "Code type",
  "summary": "Code writes itself in an editor in the brand's colours; the camera rides the caret close, then the line that matters lights up.",
  "tags": [
    "block",
    "code",
    "editor",
    "typing",
    "developer"
  ],
  "params": [
    {
      "name": "background",
      "type": "string",
      "default": "",
      "description": "a background id from the registry; empty uses the brand's first",
      "group": "advanced",
      "control": "select"
    },
    {
      "name": "file",
      "type": "string",
      "default": "scene.js",
      "description": "file",
      "group": "main",
      "control": "text"
    },
    {
      "name": "highlight",
      "type": "number",
      "default": 5,
      "description": "the line (1-based) that lights up at the end",
      "group": "main"
    },
    {
      "name": "format",
      "type": "enum",
      "default": "1920x1080",
      "options": [
        "1920x1080",
        "1080x1920",
        "1080x1080"
      ],
      "description": "output size; the layout recomposes for each",
      "group": "main",
      "control": "segmented"
    }
  ],
  "install": {
    "kind": "scene"
  },
  "files": [
    {
      "path": "pieces/code-type/scene.html",
      "content": "<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>code-type</title>\n<!--\n  Code · type (6.4 s). A block of code writes itself in an editor, coloured by the brand's palette; the camera rides\n  the caret down the file, close, and when the last line lands the line that matters lights up while the rest steps\n  back.\n  Arrive 0–0.8 s · Type 0.8–4.8 s · Highlight 4.9 s · Hold to 6.4 s.\n  Vertical/square: a narrower, taller editor sized from the short side; the close shot is fitted so the longest line\n  spans the frame width (large, readable mono), the camera keeps the tab bar near the top while it rides the caret, and\n  in vertical, lines longer than 26 columns wrap (continuations indent). For the highlight it pushes in on the line (instead of stepping back).\n-->\n<style>\n  #stage { overflow: hidden; }\n  .abs { position: absolute; box-sizing: border-box; }\n  #ed { position: absolute; box-sizing: border-box; overflow: hidden; display: flex; flex-direction: column; }\n  .tabs { display: flex; align-items: center; gap: 0.8em; padding: 0 1.4em; }\n  .tab { padding: 0.9em 1.3em; border-radius: 0.6em 0.6em 0 0; }\n  #body { position: relative; flex: 1; display: grid; grid-template-columns: 4.2em 1fr; padding-top: 1.6em; }\n  #nums { text-align: right; padding-right: 1.4em; }\n  #code { position: relative; white-space: pre; }\n  .ln { height: 1.75em; line-height: 1.75em; position: relative; }\n  #hl { position: absolute; left: -0.8em; right: 0; height: 1.75em; border-radius: 0.3em; }\n  #caret { position: absolute; width: 0.12em; height: 1.3em; }\n</style>\n</head>\n<body>\n<main id=\"stage\">\n  <div id=\"bg\" class=\"abs\" style=\"inset:0\"></div>\n  <div id=\"world\"><div id=\"ed\"><div class=\"tabs\" id=\"tabs\"></div><div id=\"body\"><div id=\"nums\"></div><div id=\"code\"><div id=\"hl\"></div><div id=\"caret\"></div></div></div></div></div>\n</main>\n<script type=\"module\">\nimport { scene, progress, ease, spring } from 'paper-motion';\nimport { camera } from 'paper-motion/kit';\nimport { loadBrand } from 'paper-motion/brand';\n\nconst CONFIG = {\n  background: null,                      // a shader-set id, or null for the brand's first entry\n  file: 'scene.js',\n  code: `import { scene } from 'paper-motion';\nimport { camera } from 'paper-motion/kit';\n\nconst cam = camera(stage, world);\ncam.travel(t, [\n  [0, { z: 900, yaw: -8 }],\n  [2, { z: 400, yaw: 0 }],\n]);`,\n  highlight: 5,                          // the line (1-based) that lights up at the end\n  format: [1920, 1080],\n};\n\nconst B = await loadBrand();\nconst [W, H] = CONFIG.format, SHORT = Math.min(W, H), D = 6.4;\nconst s = scene({ width: W, height: H, fps: 30, duration: D, background: B.color('ground') });\nconst bgId = CONFIG.background ?? B.set.entries.find((e) => e.shader && !e.image)?.id;\nif (bgId) B.shader(s, '#bg', bgId);\ndocument.querySelector('#bg').style.opacity = 0.3;\nconst $ = (id) => document.getElementById(id);\n\nconst DIST = SHORT * 0.62, K = 1 + DIST / (SHORT * 1.7);\nconst cam = camera($('stage'), $('world'), { perspective: SHORT * 1.7 });\nconst wide = W / H > 1.2, tall = H > W;\nconst FS = SHORT * (tall ? 0.034 : 0.026); // non-wide: the editor's type size in the world\nconst MAXC = tall ? 26 : Infinity;        // vertical: long lines wrap to this many columns\nconst ed = $('ed'), cw = wide ? W * 0.66 * K : FS * (tall ? MAXC * 0.6 + 8 : 36); let ch = wide ? cw * 0.56 : cw * (tall ? 1.45 : 0.85); const R = (B.tokens?.shape?.radius ?? 12) * (SHORT / 1080) * K;\nconst ground = B.color('ground'), muted = B.color('muted'), figure = B.color('figure'), accent = B.color('accent', '#E9E4D8');\nconst ramp = B.tokens?.ramp ?? [];\nconst C = { kw: accent, str: ramp[3] ?? '#8EA3AD', num: ramp[2] ?? '#5F7A86', fn: figure, punct: muted, id: '#cfcfcf' };\nObject.assign(ed.style, { width: `${cw}px`, height: `${ch}px`, borderRadius: `${R}px`, background: B.surface(0.16), border: `1.5px solid ${muted}55`, boxShadow: `0 ${SHORT * 0.04}px ${SHORT * 0.12}px rgba(0,0,0,0.5)`, fontSize: `${wide ? cw * 0.0165 : FS}px`, fontFamily: B.font('mono') });\n$('tabs').style.background = ground; $('tabs').style.height = '3.4em';\n$('tabs').innerHTML = `<span style=\"display:flex;gap:0.45em;margin-right:1em\">${['#ffffff33', '#ffffff22', '#ffffff18'].map((c) => `<i style=\"display:block;width:0.75em;height:0.75em;border-radius:50%;background:${c}\"></i>`).join('')}</span><span class=\"tab\" style=\"background:${B.surface(0.16)};color:${figure};font-size:0.8em;align-self:flex-end\">${CONFIG.file}</span><span style=\"color:${muted};font-size:0.8em\">brand.json</span>`;\n\n// tokens: a small highlighter, enough for JS-shaped snippets\nconst KW = /^(import|from|const|let|await|export|return|new|function)$/;\nconst tokens = (src) => {\n  const out = []; const re = /('[^']*'|\"[^\"]*\"|`[^`]*`)|(\\d+(?:\\.\\d+)?)|([A-Za-z_$][\\w$]*)|(\\s+)|(.)/g; let m;\n  while ((m = re.exec(src))) {\n    const [tok, str, num, word, sp] = m;\n    const kind = str ? 'str' : num ? 'num' : word ? (KW.test(word) ? 'kw' : src[re.lastIndex] === '(' ? 'fn' : 'id') : sp ? 'sp' : 'punct';\n    out.push([tok, kind]);\n  }\n  return out;\n};\nconst code = $('code'), nums = $('nums'), lines = CONFIG.code.split('\\n');\nconst chars = [];                        // every visible character, in typing order, with its line\n// visual rows: a logical line, wrapped at token boundaries when it is wider than MAXC (continuations indent two more)\nconst vrows = []; let hlRow = 0;\nlines.forEach((ln, li) => {\n  if (li === CONFIG.highlight - 1) hlRow = vrows.length;\n  const lead = ln.match(/^\\s*/)[0];\n  let cur = { toks: [], len: 0, num: String(li + 1) };\n  for (const [tok, kind] of tokens(ln)) {\n    if (cur.len + tok.length > MAXC + (kind === 'punct' ? 2 : 0) && cur.len > lead.length + 2) {\n      vrows.push(cur); cur = { toks: [[lead + '  ', 'sp']], len: lead.length + 2, num: '' };\n      if (kind === 'sp') continue;\n    }\n    cur.toks.push([tok, kind]); cur.len += tok.length;\n  }\n  vrows.push(cur);\n});\nvrows.forEach((vr, li) => {\n  const row = document.createElement('div'); row.className = 'ln';\n  for (const [tok, kind] of vr.toks) for (const c of tok) {\n    const sp = document.createElement('span'); sp.textContent = c; sp.style.color = C[kind] ?? figure; sp.style.visibility = 'hidden';\n    row.append(sp); chars.push({ el: sp, li });\n  }\n  code.append(row);\n  const n = document.createElement('div'); n.className = 'ln'; n.textContent = vr.num; n.style.color = `${muted}88`; n.style.opacity = 0; nums.append(n);\n});\nnums.style.paddingTop = code.style.paddingTop = '0';\nconst caret = $('caret'), hl = $('hl');\ncaret.style.background = accent;\nhl.style.background = `${accent}1f`; hl.style.boxShadow = `inset 0.18em 0 0 ${accent}`;\ncam.place(ed, { x: 0, y: 0, z: 0 });\nawait document.fonts.ready;\n\n// the schedule: a steady hand, a beat longer at each line end, a breath at blank lines\nconst T = { type: 0.8, hl: 4.9 };\nconst at = []; let clock = T.type, prevLi = 0;\nfor (const c of chars) { if (c.li !== prevLi) { clock += c.li - prevLi > 1 ? 0.22 : 0.11; prevLi = c.li; } clock += 0.017; at.push(clock); }\nconst end = clock;\nconst rows = [...code.querySelectorAll('.ln')], numRows = [...nums.children];\nconst lineH = rows[0].offsetHeight, codeTop = $('body').offsetTop + code.offsetTop;\n// non-wide: fit the close shot to the code's widest line, and the arrival to the whole editor\nconst P = SHORT * 1.7, fs = parseFloat(ed.style.fontSize);\nconst codeW = Math.max(...rows.map((r) => { const c = r.lastElementChild; return c ? c.offsetLeft + c.offsetWidth : 0; }));\nconst leftX = $('body').offsetLeft - cw / 2;        // the gutter's left edge, from the editor's centre\nconst sClose = Math.min(tall ? 1.8 : 1.5, (W * 0.92) / (code.offsetLeft + codeW + fs * 0.6)), zClose = P / sClose - P;\nconst sFar = Math.min((W * 0.86) / cw, (H * 0.8) / Math.max(ch, cw * 0.6)), zFar = P / sFar - P;\nif (!wide && tall) { ch = Math.max(ch, H / sClose + fs * 4); ed.style.height = `${ch}px`; }\nconst lineAt = (u) => { let k = 0; while (k < chars.length && at[k] <= u) k++; return k ? chars[k - 1].li : 0; };\n// the ride is smoothed over the last half second, so the camera glides between lines instead of stepping\nconst ride = (u) => { let y = 0, x = 0; for (let j = 0; j < 10; j++) { const v = u - j * 0.05, l = lineAt(v); y += rows[l].offsetTop; x += Math.min(rows[l].offsetWidth > 0 ? [...rows[l].children].filter((c) => c.style.visibility !== 'hidden').length : 0, 40); } return [y / 10, x / 10]; };\n\ns.update((t) => {\n  // how far the hand has got\n  let n = 0; while (n < chars.length && at[n] <= t) n++;\n  chars.forEach((c, i) => { c.el.style.visibility = i < n ? 'visible' : 'hidden'; });\n  const li = n ? chars[n - 1].li : 0;\n  numRows.forEach((r, i) => { r.style.opacity = i <= li && t >= T.type ? '1' : '0'; });\n  // the caret sits after the last typed character, blinking only while it waits\n  const last = n ? chars[n - 1].el : null;\n  const cx = last ? last.offsetLeft + last.offsetWidth : 0, cy = rows[li].offsetTop + lineH * 0.12;\n  caret.style.transform = `translate(${cx}px, ${cy}px)`;\n  const typing = t < end + 0.1;\n  caret.style.opacity = t < T.type - 0.3 ? '0' : typing ? '1' : String(Math.sin((t - end) * 9) > 0 ? 1 : 0) ;\n  // the camera: arrives, then rides the caret down the file, close; eases back a step for the highlight\n  const arrive = progress(t, 0, 0.8, ease.outCubic), close = progress(t, 0.6, 1.6, ease.inOutCubic), back = progress(t, T.hl - 0.2, T.hl + 1.0, ease.inOutCubic);\n  const [ry] = ride(t);\n  const rideY = Math.max(codeTop + ry + lineH / 2, codeTop + lineH * 3.5) - ch / 2, rideX = $('body').offsetLeft + code.offsetLeft + cw * 0.24 + cw * 0.06 - cw / 2;\n  const hY = (codeTop + rows[hlRow].offsetTop + lineH / 2) - ch / 2;\n  const camY = rideY + (hY - rideY) * back;\n  if (!wide) {\n    // the frame's left edge sits just before the gutter; the tab bar stays near the top until the caret runs lower\n    const sNow = sClose * (1 + (tall ? 0.03 : 0.12) * back), half = H / (2 * sNow);\n    const nx = leftX + (W / 2) / sNow - fs * 0.6;\n    const topY = -ch / 2 + half - (tall ? H * 0.12 : H * 0.05) / sNow;\n    const caretY = codeTop + ry + lineH / 2 - ch / 2, hy = codeTop + rows[hlRow].offsetTop + lineH / 2 - ch / 2;\n    const followY = Math.max(topY, caretY - half * 0.1), y = followY + (Math.max(topY, hy - half * (tall ? 0.25 : 0.1)) - followY) * back;\n    const zc = P / sNow - P;\n    cam.at({ x: nx * close, y: y * close, z: zFar + SHORT * 0.3 * (1 - arrive) + (zc - zFar) * close, yaw: -6 * (1 - arrive) + 2 * close * (1 - back), pitch: 3 * (1 - arrive) });\n  } else\n  cam.at({ x: rideX * close, y: camY * close, z: DIST + SHORT * 0.3 * (1 - arrive) - SHORT * 1.05 * close + SHORT * 0.12 * back, yaw: -7 * (1 - arrive) + 3 * close * (1 - back), pitch: 3 * (1 - arrive) });\n  ed.style.opacity = String(progress(t, 0, 0.3));\n  // the highlight: a bar sweeps in under the line that matters; the others step back\n  const h = progress(t, T.hl, T.hl + 0.5, ease.outCubic);\n  hl.style.top = `${rows[hlRow].offsetTop}px`;\n  hl.style.clipPath = `inset(0 ${100 - h * 100}% 0 0)`;\n  rows.forEach((r, i) => { r.style.opacity = String(i === hlRow ? 1 : 1 - 0.6 * h); });\n});\nB.cue(s, 'transition', 0); B.cue(s, 'text', T.type); B.cue(s, 'land', T.hl);\nB.sound(s);\nawait s.start();\n</script>\n</body>\n</html>\n"
    },
    {
      "path": "pieces/code-type/brief.md",
      "content": "# Code type\n\nBlock: code-type (6.4 s), from paper-motion.app. The look, fonts and sound come from `brand/`.\n\nCode writes itself in an editor in the brand's colours; the camera rides the caret close, then the line that matters lights up.\n\nA block is one ready-made moment. Edit `CONFIG` (its words, numbers and format: 16:9, 9:16 or 1:1, the layout recomposes for each); check `npx paper-motion still` at 0.8 and 4.8 s; render.\n"
    }
  ],
  "requires": {
    "engine": ">=0.2.6"
  },
  "usage": "npx paper-motion add code-type --name my-code-type\n# edit CONFIG in pieces/my-code-type/scene.html, then:\nnpx paper-motion render pieces/my-code-type/scene.html --motion-blur 5",
  "notes": [
    "Wired to the brand folder: needs brand/tokens.json (a palette and a font pair work) and, for the field, a shader-set entry.",
    "Recomposes for 16:9, 9:16 and 1:1: set `format` and the layout and camera follow."
  ],
  "related": [
    "code-diff",
    "terminal-run"
  ],
  "preview": {
    "video": "previews/code-type.webm",
    "poster": "previews/code-type.jpg",
    "at": 5.4,
    "values": {}
  },
  "mood": [
    "technical"
  ],
  "duration": 6.4,
  "formats": [
    "16:9",
    "9:16",
    "1:1"
  ],
  "beats": [
    {
      "name": "Arrive",
      "from": 0,
      "to": 0.8,
      "what": "arrive"
    },
    {
      "name": "Type",
      "from": 0.8,
      "to": 4.8,
      "what": "type"
    },
    {
      "name": "Highlight",
      "from": 4.9,
      "to": 5.5,
      "what": "highlight"
    },
    {
      "name": "Hold",
      "from": 5.5,
      "to": 6.4,
      "what": "hold"
    }
  ],
  "when": [
    "show how little code it takes",
    "developer tools and APIs"
  ],
  "needs": [
    {
      "kind": "code",
      "fill": {
        "file": "$file",
        "code": "$code",
        "highlight": "$highlight"
      }
    }
  ]
}