{
  "$schema": "../../schema.json",
  "version": "1.0.0",
  "license": "MIT",
  "id": "code-diff",
  "type": "block",
  "title": "Code diff",
  "summary": "The old lines strike through and fold away, one new line opens in their place, the numbers close up and a −7 +1 count lands.",
  "tags": [
    "block",
    "code",
    "diff",
    "before-after",
    "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": "make-video.js",
      "description": "file",
      "group": "main",
      "control": "text"
    },
    {
      "name": "fps",
      "type": "number",
      "default": 30,
      "description": "fps",
      "group": "main"
    },
    {
      "name": "codec",
      "type": "string",
      "default": "libx264",
      "description": "codec",
      "group": "main",
      "control": "text"
    },
    {
      "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-diff/scene.html",
      "content": "<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>code-diff</title>\n<!--\n  Code · diff (6 s). The old way, struck out line by line, folds away; the new way opens in its place and the rest of\n  the file closes up around it on a spring. A count of what changed lands in the tab bar; the camera stays close on\n  the change and pushes in on the new line.\n  Arrive 0–0.8 s · Strike 1.1–1.9 s · Fold 2.1–2.9 s · Open 2.6–3.3 s · Count 3.4 s · Hold to 6 s.\n  Vertical/square: the editor is sized from the short side to the code's width (vertical wraps lines past 24 columns,\n  continuations indented) so the mono stays large; the camera fits the editor's width and pushes in, anchored left.\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; padding-top: 1.6em; }\n  .ln { position: relative; overflow: hidden; display: grid; grid-template-columns: 2.6em 1.6em 1fr; white-space: pre; }\n  .ln > span { line-height: 1.75em; height: 1.75em; }\n  .tx { vertical-align: top; }\n  .n { text-align: right; padding-right: 0.9em; }\n  .strike { position: absolute; left: -0.2em; right: -0.2em; top: 0.86em; height: 0.09em; transform-origin: 0 50%; }\n  #count { margin-left: 0.6em; display: flex; gap: 0.8em; font-size: 0.85em; }\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></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: 'make-video.js',\n  before: `import { render } from 'paper-motion';\n\nconst video = await ffmpeg({\n  input: frames,\n  fps: 30,\n  codec: 'libx264',\n  filters: buildFilters(opts),\n  audio: mixTracks(sfx, music),\n});\n\nawait video.save('launch.mp4');`,\n  remove: [3, 9],                        // the lines (1-based, inclusive) that go\n  add: [`const video = await render('scene.html');`],\n  format: [1920, 1080],\n};\n\nconst B = await loadBrand();\nconst [W, H] = CONFIG.format, SHORT = Math.min(W, H), D = 6;\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 MAXC = tall ? 24 : Infinity;                                    // vertical: long lines wrap to this many columns\nconst FS = SHORT * (tall ? 0.03 : 0.026);                             // non-wide: the editor's type size in the world\nconst COLS = Math.min(MAXC, Math.max(...[...CONFIG.before.split('\\n'), ...CONFIG.add].map((l) => l.length)));\nconst ed = $('ed'), cw = wide ? W * 0.66 * K : FS * (COLS * 0.6 + 7.5); let ch = wide ? cw * 0.56 : tall ? cw * 1.6 : cw * 0.8; 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' };\nconst RED = '#d0715f', GREEN = '#8fbf8f';                            // diff colours, kept soft\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 id=\"count\"><span id=\"cm\" style=\"color:${RED}\"></span><span id=\"cp\" style=\"color:${GREEN}\"></span></span>`;\n\nconst KW = /^(import|from|const|let|await|export|return|new|function)$/;\nconst paint = (src) => {\n  let 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 += `<span style=\"color:${C[kind] ?? figure}\">${tok.replace(/</g, '&lt;')}</span>`;\n  }\n  return out;\n};\nconst body = $('body'), [r0, r1] = CONFIG.remove;\nconst rows = [];\n// wraps a line at token boundaries past MAXC columns; continuations indent two more (punctuation may hang 2 over)\nconst wrap = (src) => {\n  if (src.length <= MAXC) return src;\n  const lead = src.match(/^\\s*/)[0], out = []; let cur = '';\n  for (const tok of src.match(/('[^']*'|\"[^\"]*\")|\\d+(?:\\.\\d+)?|[A-Za-z_$][\\w$]*|\\s+|./g)) {\n    const punct = /^[^\\w\\s'\"$]$/.test(tok);\n    if (cur.length + tok.length > MAXC + (punct ? 2 : 0) && cur.trim().length) { out.push(cur.replace(/\\s+$/, '')); cur = lead + '  '; if (!tok.trim()) continue; }\n    cur += tok;\n  }\n  out.push(cur); return out.join('\\n');\n};\nconst mkRow = (text, kind, num) => {\n  text = wrap(text);\n  const row = document.createElement('div'); row.className = 'ln'; row._k = text.split('\\n').length;\n  row.innerHTML = `<span class=\"n\" style=\"color:${muted}88\">${num ?? ''}</span><span class=\"g\"></span><span><span class=\"tx\" style=\"position:relative;display:inline-block\">${paint(text)}</span></span>`;\n  row.lastElementChild.style.height = `${1.75 * row._k}em`;\n  if (kind === 'del') { const st = document.createElement('div'); st.className = 'strike'; st.style.background = RED; row.querySelector('.tx').append(st); }\n  body.append(row); rows.push({ row, kind, num }); return row;\n};\nconst before = CONFIG.before.split('\\n');\nbefore.forEach((ln, i) => {\n  const n = i + 1;\n  if (n === r0) CONFIG.add.forEach((a) => mkRow(a, 'add', ''));\n  mkRow(ln, n >= r0 && n <= r1 ? 'del' : 'ctx', n);\n});\n// the added rows go before the removed block in the file, but read best after it while both are visible: move them\nconst adds = rows.filter((r) => r.kind === 'add'), dels = rows.filter((r) => r.kind === 'del');\ndels[dels.length - 1].row.after(...adds.map((r) => r.row));\ncam.place(ed, { x: 0, y: 0, z: 0 });\nawait document.fonts.ready;\nconst lineH = rows[0].row.offsetHeight / rows[0].row._k;\nconst P = SHORT * 1.7;\nif (tall) { ch = Math.max(body.offsetTop + body.scrollHeight + lineH * 2, Math.min(cw * 1.7, (H * 0.9) / ((W * 0.94) / cw))); ed.style.height = `${ch}px`; }\n\nconst T = { strike: [1.1, 1.9], fold: [2.0, 2.6], open: 2.25, count: 3.2 };\nconst bodyTop = body.offsetTop + parseFloat(getComputedStyle(body).paddingTop);\nconst delTop = dels[0].row.offsetTop - body.offsetTop - parseFloat(getComputedStyle(body).paddingTop);\n\ns.update((t) => {\n  // the old lines: tinted, struck one after another, then folded away bottom-first\n  dels.forEach(({ row }, i) => {\n    const k = (T.strike[1] - T.strike[0]) / dels.length;\n    const tint = progress(t, T.strike[0] - 0.2, T.strike[0] + 0.2);\n    row.style.background = tint ? `${RED}${Math.round(tint * 0x22).toString(16).padStart(2, '0')}` : 'transparent';\n    row.querySelector('.g').textContent = tint > 0.5 ? '−' : ''; row.querySelector('.g').style.color = RED;\n    const st = row.querySelector('.strike');\n    st.style.transform = `scaleX(${progress(t, T.strike[0] + i * k, T.strike[0] + (i + 1.6) * k, ease.inOutCubic)})`;\n    const fk = (T.fold[1] - T.fold[0]) / dels.length, j = dels.length - 1 - i;\n    const f = progress(t, T.fold[0] + j * fk * 0.6, T.fold[0] + j * fk * 0.6 + 0.45, ease.inOutCubic);\n    row.style.height = `${lineH * row._k * (1 - f)}px`;\n    row.style.opacity = String(1 - 0.5 * tint - 0.5 * f);\n  });\n  // the new line: opens on a spring, slides in from the gutter, glows green and settles\n  adds.forEach(({ row }, i) => {\n    const o = t >= T.open + i * 0.08 ? spring(t - T.open - i * 0.08, { stiffness: 170, damping: 15 }) : 0;\n    row.style.height = `${lineH * row._k * Math.max(0, Math.min(1.15, o))}px`;\n    row.style.background = `${GREEN}${Math.round(Math.min(1, o) * 0x24).toString(16).padStart(2, '0')}`;\n    row.style.boxShadow = o ? `inset 0.18em 0 0 ${GREEN}` : 'none';\n    row.lastElementChild.style.transform = `translateX(${(1 - Math.min(1, o)) * -2}em)`;\n    row.lastElementChild.style.opacity = String(Math.min(1, o * 1.4));\n    row.querySelector('.g').textContent = '+'; row.querySelector('.g').style.color = GREEN;\n  });\n  // the numbers close up once the change has landed\n  const renum = t >= T.fold[1];\n  let n = 0;\n  rows.forEach(({ row, kind, num }) => { if (kind === 'del') return; n++; row.querySelector('.n').textContent = renum ? String(n) : (num ?? ''); });\n  // the count in the tab bar\n  const c = progress(t, T.count, T.count + 0.4, ease.outBack);\n  $('cm').textContent = `−${dels.length}`; $('cp').textContent = `+${adds.length}`;\n  $('count').style.opacity = String(Math.min(1, c * 1.5)); $('count').style.transform = `translateY(${(1 - c) * 0.6}em)`;\n  // the camera: close on the change all along, pushing in once the new line has landed\n  const arrive = progress(t, 0, 0.8, ease.outCubic), push = progress(t, T.open, D, ease.inOutCubic);\n  const blockH = Math.max(lineH, dels.reduce((a, { row }) => a + row.offsetHeight, 0) + adds.reduce((a, { row }) => a + row.offsetHeight, 0));\n  const fy = bodyTop + delTop + blockH / 2 - ch / 2;\n  if (!wide) {\n    // fit the editor's width, then push in on the change, the editor's left edge held near the frame's left\n    const sFit = (W * 0.94) / cw, sNow = sFit * (0.72 + 0.28 * arrive) * (1 + (tall ? 0.1 : 0.1) * push), half = H / (2 * sNow);\n    const x = Math.min(0, -cw / 2 + (W / 2) / sNow - FS * 0.8);\n    const lo = -ch / 2 + half - H * 0.05 / sNow, hi = ch / 2 - half + H * 0.05 / sNow;\n    const y = lo <= hi ? Math.min(hi, Math.max(lo, fy)) : (fy + (lo + hi) / 2) / 2;\n    cam.at({ x, y, z: P / sNow - P, yaw: -6 * (1 - arrive) + 1.5 * push, pitch: 3 * (1 - arrive) });\n  } else\n  cam.at({ x: -cw * (0.14 + 0.16 * push), y: fy, z: DIST + SHORT * 0.3 * (1 - arrive) - SHORT * 0.7 - SHORT * 0.75 * push, yaw: -7 * (1 - arrive) + 2 * push, pitch: 3 * (1 - arrive) });\n  ed.style.opacity = String(progress(t, 0, 0.3));\n});\nB.cue(s, 'transition', 0); B.cue(s, 'text', T.strike[0]); B.cue(s, 'transition', T.fold[0]); B.cue(s, 'land', T.open + 0.2);\nB.sound(s);\nawait s.start();\n</script>\n</body>\n</html>\n"
    },
    {
      "path": "pieces/code-diff/brief.md",
      "content": "# Code diff\n\nBlock: code-diff (6 s), from paper-motion.app. The look, fonts and sound come from `brand/`.\n\nThe old lines strike through and fold away, one new line opens in their place, the numbers close up and a −7 +1 count lands.\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 1.9 s; render.\n"
    }
  ],
  "requires": {
    "engine": ">=0.2.6"
  },
  "usage": "npx paper-motion add code-diff --name my-code-diff\n# edit CONFIG in pieces/my-code-diff/scene.html, then:\nnpx paper-motion render pieces/my-code-diff/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-type",
    "before-after"
  ],
  "preview": {
    "video": "previews/code-diff.webm",
    "poster": "previews/code-diff.jpg",
    "at": 5.6,
    "values": {}
  },
  "mood": [
    "technical",
    "bold"
  ],
  "duration": 6,
  "formats": [
    "16:9",
    "9:16",
    "1:1"
  ],
  "beats": [
    {
      "name": "Arrive",
      "from": 0,
      "to": 0.8,
      "what": "arrive"
    },
    {
      "name": "Strike",
      "from": 1.1,
      "to": 1.9,
      "what": "strike"
    },
    {
      "name": "Fold",
      "from": 2.1,
      "to": 2.9,
      "what": "fold"
    },
    {
      "name": "Open",
      "from": 2.6,
      "to": 3.3,
      "what": "open"
    },
    {
      "name": "Count",
      "from": 3.4,
      "to": 4,
      "what": "count"
    },
    {
      "name": "Hold",
      "from": 4,
      "to": 6,
      "what": "hold"
    }
  ],
  "when": [
    "the old way against the new",
    "a refactor in one line"
  ],
  "needs": [
    {
      "kind": "rewrite",
      "fill": {
        "file": "$file",
        "before": "$before",
        "remove": "$remove",
        "add": "$add"
      }
    }
  ]
}