paper-motion

Code type

code-type

Code writes itself in an editor in the brand's colours; the camera rides the caret close, then the line that matters lights up.

Install
$ npx paper-motion add code-type

Writes a scene to pieces/, wired to your brand folder.

Tune it, then add it to your kit
Parameters
file
highlight
format
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>code-type</title>
<!--
  Code · type (6.4 s). A block of code writes itself in an editor, coloured by the brand's palette; the camera rides
  the caret down the file, close, and when the last line lands the line that matters lights up while the rest steps
  back.
  Arrive 0–0.8 s · Type 0.8–4.8 s · Highlight 4.9 s · Hold to 6.4 s.
  Vertical/square: a narrower, taller editor sized from the short side; the close shot is fitted so the longest line
  spans the frame width (large, readable mono), the camera keeps the tab bar near the top while it rides the caret, and
  in vertical, lines longer than 26 columns wrap (continuations indent). For the highlight it pushes in on the line (instead of stepping back).
-->
<style>
  #stage { overflow: hidden; }
  .abs { position: absolute; box-sizing: border-box; }
  #ed { position: absolute; box-sizing: border-box; overflow: hidden; display: flex; flex-direction: column; }
  .tabs { display: flex; align-items: center; gap: 0.8em; padding: 0 1.4em; }
  .tab { padding: 0.9em 1.3em; border-radius: 0.6em 0.6em 0 0; }
  #body { position: relative; flex: 1; display: grid; grid-template-columns: 4.2em 1fr; padding-top: 1.6em; }
  #nums { text-align: right; padding-right: 1.4em; }
  #code { position: relative; white-space: pre; }
  .ln { height: 1.75em; line-height: 1.75em; position: relative; }
  #hl { position: absolute; left: -0.8em; right: 0; height: 1.75em; border-radius: 0.3em; }
  #caret { position: absolute; width: 0.12em; height: 1.3em; }
</style>
</head>
<body>
<main id="stage">
  <div id="bg" class="abs" style="inset:0"></div>
  <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>
</main>
<script type="module">
import { scene, progress, ease, spring } from 'paper-motion';
import { camera } from 'paper-motion/kit';
import { loadBrand } from 'paper-motion/brand';

const CONFIG = {
  background: null,
  file: 'scene.js',
  code: `import { scene } from 'paper-motion';
import { camera } from 'paper-motion/kit';

const cam = camera(stage, world);
cam.travel(t, [
  [0, { z: 900, yaw: -8 }],
  [2, { z: 400, yaw: 0 }],
]);`,
  highlight: 5,
  format: [1920, 1080],
};

const B = await loadBrand();
const [W, H] = CONFIG.format, SHORT = Math.min(W, H), D = 6.4;
const s = scene({ width: W, height: H, fps: 30, duration: D, background: B.color('ground') });
const bgId = CONFIG.background ?? B.set.entries.find((e) => e.shader && !e.image)?.id;
if (bgId) B.shader(s, '#bg', bgId);
document.querySelector('#bg').style.opacity = 0.3;
const $ = (id) => document.getElementById(id);

const DIST = SHORT * 0.62, K = 1 + DIST / (SHORT * 1.7);
const cam = camera($('stage'), $('world'), { perspective: SHORT * 1.7 });
const wide = W / H > 1.2, tall = H > W;
const FS = SHORT * (tall ? 0.034 : 0.026); // non-wide: the editor's type size in the world
const MAXC = tall ? 26 : Infinity;        // vertical: long lines wrap to this many columns
const 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;
const ground = B.color('ground'), muted = B.color('muted'), figure = B.color('figure'), accent = B.color('accent', '#E9E4D8');
const ramp = B.tokens?.ramp ?? [];
const C = { kw: accent, str: ramp[3] ?? '#8EA3AD', num: ramp[2] ?? '#5F7A86', fn: figure, punct: muted, id: '#cfcfcf' };
Object.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') });
$('tabs').style.background = ground; $('tabs').style.height = '3.4em';
$('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>`;

// tokens: a small highlighter, enough for JS-shaped snippets
const KW = /^(import|from|const|let|await|export|return|new|function)$/;
const tokens = (src) => {
  const out = []; const re = /('[^']*'|"[^"]*"|`[^`]*`)|(\d+(?:\.\d+)?)|([A-Za-z_$][\w$]*)|(\s+)|(.)/g; let m;
  while ((m = re.exec(src))) {
    const [tok, str, num, word, sp] = m;
    const kind = str ? 'str' : num ? 'num' : word ? (KW.test(word) ? 'kw' : src[re.lastIndex] === '(' ? 'fn' : 'id') : sp ? 'sp' : 'punct';
    out.push([tok, kind]);
  }
  return out;
};
const code = $('code'), nums = $('nums'), lines = CONFIG.code.split('\n');
const chars = [];                        // every visible character, in typing order, with its line
// visual rows: a logical line, wrapped at token boundaries when it is wider than MAXC (continuations indent two more)
const vrows = []; let hlRow = 0;
lines.forEach((ln, li) => {
  if (li === CONFIG.highlight - 1) hlRow = vrows.length;
  const lead = ln.match(/^\s*/)[0];
  let cur = { toks: [], len: 0, num: String(li + 1) };
  for (const [tok, kind] of tokens(ln)) {
    if (cur.len + tok.length > MAXC + (kind === 'punct' ? 2 : 0) && cur.len > lead.length + 2) {
      vrows.push(cur); cur = { toks: [[lead + '  ', 'sp']], len: lead.length + 2, num: '' };
      if (kind === 'sp') continue;
    }
    cur.toks.push([tok, kind]); cur.len += tok.length;
  }
  vrows.push(cur);
});
vrows.forEach((vr, li) => {
  const row = document.createElement('div'); row.className = 'ln';
  for (const [tok, kind] of vr.toks) for (const c of tok) {
    const sp = document.createElement('span'); sp.textContent = c; sp.style.color = C[kind] ?? figure; sp.style.visibility = 'hidden';
    row.append(sp); chars.push({ el: sp, li });
  }
  code.append(row);
  const n = document.createElement('div'); n.className = 'ln'; n.textContent = vr.num; n.style.color = `${muted}88`; n.style.opacity = 0; nums.append(n);
});
nums.style.paddingTop = code.style.paddingTop = '0';
const caret = $('caret'), hl = $('hl');
caret.style.background = accent;
hl.style.background = `${accent}1f`; hl.style.boxShadow = `inset 0.18em 0 0 ${accent}`;
cam.place(ed, { x: 0, y: 0, z: 0 });
await document.fonts.ready;

// the schedule: a steady hand, a beat longer at each line end, a breath at blank lines
const T = { type: 0.8, hl: 4.9 };
const at = []; let clock = T.type, prevLi = 0;
for (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); }
const end = clock;
const rows = [...code.querySelectorAll('.ln')], numRows = [...nums.children];
const lineH = rows[0].offsetHeight, codeTop = $('body').offsetTop + code.offsetTop;
// non-wide: fit the close shot to the code's widest line, and the arrival to the whole editor
const P = SHORT * 1.7, fs = parseFloat(ed.style.fontSize);
const codeW = Math.max(...rows.map((r) => { const c = r.lastElementChild; return c ? c.offsetLeft + c.offsetWidth : 0; }));
const leftX = $('body').offsetLeft - cw / 2;        // the gutter's left edge, from the editor's centre
const sClose = Math.min(tall ? 1.8 : 1.5, (W * 0.92) / (code.offsetLeft + codeW + fs * 0.6)), zClose = P / sClose - P;
const sFar = Math.min((W * 0.86) / cw, (H * 0.8) / Math.max(ch, cw * 0.6)), zFar = P / sFar - P;
if (!wide && tall) { ch = Math.max(ch, H / sClose + fs * 4); ed.style.height = `${ch}px`; }
const lineAt = (u) => { let k = 0; while (k < chars.length && at[k] <= u) k++; return k ? chars[k - 1].li : 0; };
// the ride is smoothed over the last half second, so the camera glides between lines instead of stepping
const 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]; };

s.update((t) => {
  // how far the hand has got
  let n = 0; while (n < chars.length && at[n] <= t) n++;
  chars.forEach((c, i) => { c.el.style.visibility = i < n ? 'visible' : 'hidden'; });
  const li = n ? chars[n - 1].li : 0;
  numRows.forEach((r, i) => { r.style.opacity = i <= li && t >= T.type ? '1' : '0'; });
  // the caret sits after the last typed character, blinking only while it waits
  const last = n ? chars[n - 1].el : null;
  const cx = last ? last.offsetLeft + last.offsetWidth : 0, cy = rows[li].offsetTop + lineH * 0.12;
  caret.style.transform = `translate(${cx}px, ${cy}px)`;
  const typing = t < end + 0.1;
  caret.style.opacity = t < T.type - 0.3 ? '0' : typing ? '1' : String(Math.sin((t - end) * 9) > 0 ? 1 : 0) ;
  // the camera: arrives, then rides the caret down the file, close; eases back a step for the highlight
  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);
  const [ry] = ride(t);
  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;
  const hY = (codeTop + rows[hlRow].offsetTop + lineH / 2) - ch / 2;
  const camY = rideY + (hY - rideY) * back;
  if (!wide) {
    // the frame's left edge sits just before the gutter; the tab bar stays near the top until the caret runs lower
    const sNow = sClose * (1 + (tall ? 0.03 : 0.12) * back), half = H / (2 * sNow);
    const nx = leftX + (W / 2) / sNow - fs * 0.6;
    const topY = -ch / 2 + half - (tall ? H * 0.12 : H * 0.05) / sNow;
    const caretY = codeTop + ry + lineH / 2 - ch / 2, hy = codeTop + rows[hlRow].offsetTop + lineH / 2 - ch / 2;
    const followY = Math.max(topY, caretY - half * 0.1), y = followY + (Math.max(topY, hy - half * (tall ? 0.25 : 0.1)) - followY) * back;
    const zc = P / sNow - P;
    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) });
  } else
  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) });
  ed.style.opacity = String(progress(t, 0, 0.3));
  // the highlight: a bar sweeps in under the line that matters; the others step back
  const h = progress(t, T.hl, T.hl + 0.5, ease.outCubic);
  hl.style.top = `${rows[hlRow].offsetTop}px`;
  hl.style.clipPath = `inset(0 ${100 - h * 100}% 0 0)`;
  rows.forEach((r, i) => { r.style.opacity = String(i === hlRow ? 1 : 1 - 0.6 * h); });
});
B.cue(s, 'transition', 0); B.cue(s, 'text', T.type); B.cue(s, 'land', T.hl);
B.sound(s);
await s.start();
</script>
</body>
</html>
Defaults

Structure

Code type01 / 04
Arrive
arrive
0.0 / 6.4 s
01Arrive
02Type
04Hold
0 s6.4 s
  1. 010–0.8 sArrivearrive
  2. 020.8–4.8 sTypetype
  3. 034.9–5.5 sHighlighthighlight
  4. 045.5–6.4 sHoldhold

The script, sketched: the beats in order and their length, in the brand's colors and type. The clip above is the engine's render of the same recipe.

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.

Spec

Id
code-type
Type
Blocks
Version
1.0.0
Engine
>=0.2.6
License
MIT

Related