Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

Feed the code morph from the kernel tokenizer, and make matched tokens travel

nyblnetf0f3aaddb246
diff --git a/scripts/build-code-matrix.mjs b/scripts/build-code-matrix.mjs
new file mode 100644
index 00000000..c1bbbc85
--- /dev/null
+++ b/scripts/build-code-matrix.mjs
@@ -0,0 +1,94 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// A scenario matrix for the code morph (C implementation: HeckelDiff + kernel tokenizer). DEMO BUILD.
+//
+// node scripts/build-code-matrix.mjs
+//
+// One pair of slides per scenario, so each kind of edit can be watched on its
+// own. Measured offline first (scratchpad/anchor/matrix.mjs): every scenario
+// pairs its tokens cleanly EXCEPT a swap of two lines that share a prefix,
+// where the duplicated leading token cannot be disambiguated and one line ends
+// up assembled from two different origin lines. That is the one to watch.
+
+import { readFileSync, writeFileSync } from 'node:fs'
+import { join, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const shellPath = join(root, 'slides/dist-single/Bento_Slides.bento.html')
+const out = join(root, 'slides/dist-single/Code_Matrix_Demo.bento.html')
+
+const INK = '#0D1B2E', PAPER = '#F2F0EA', MIST = '#8FA0B4', PEACH = '#FF9E8A'
+let uid = 0
+const id = (p) => `${p}-${uid++}`
+
+const text = (html, x, y, w, h, o = {}) => ({
+ id: id('t'), type: 'text', x, y, w, h, rotation: 0, opacity: 1, html,
+ fontSize: o.size ?? 24, fontFamily: 'Instrument Sans, Helvetica Neue, sans-serif',
+ fontWeight: o.weight ?? 400, color: o.color ?? PAPER, align: 'left', valign: 'top', lineHeight: 1.35,
+})
+const code = (content, lang = 'ts') => ({
+ id: id('c'), type: 'code', morphId: 'm', x: 96, y: 210, w: 1088, h: 400,
+ rotation: 0, opacity: 1, content, grammarName: lang, color: '#DCE3EC',
+ fontSize: 26, lineHeight: 1.55, align: 'left', valign: 'top',
+ fontFamily: "ui-monospace, 'SFMono-Regular', 'Menlo', 'Consolas', monospace",
+})
+const slide = (elements, o = {}) => ({
+ id: id('s'), name: o.name ?? '', background: INK,
+ transition: o.transition ?? 'morph', notes: o.notes ?? '', elements,
+})
+
+// [label, what to expect, before, after]
+const CASES = [
+ ['1. Swap — distinct lines', 'clean: the two lines trade places',
+ `function f() {\n alpha(one)\n beta(two)\n done()\n}`,
+ `function f() {\n beta(two)\n alpha(one)\n done()\n}`],
+ ['2. Swap — shared prefix', 'TEARS: both lines start with const, so it cannot tell them apart',
+ `function f() {\n const a = one()\n const b = two()\n done()\n}`,
+ `function f() {\n const b = two()\n const a = one()\n done()\n}`],
+ ['3. Move a line far', 'first() travels to the bottom, the rest shift up',
+ `function f() {\n first()\n x()\n y()\n z()\n last()\n}`,
+ `function f() {\n x()\n y()\n z()\n last()\n first()\n}`],
+ ['4. Delete a middle line', 'two() goes, three() rises to meet one()',
+ `function f() {\n one()\n two()\n three()\n}`,
+ `function f() {\n one()\n three()\n}`],
+ ['5. Insert at the top', 'zero() arrives, everything below moves down',
+ `function f() {\n one()\n two()\n}`,
+ `function f() {\n zero()\n one()\n two()\n}`],
+ ['6. Rename', 'total becomes acc; nothing moves, two tokens change',
+ `function f() {\n const total = sum(xs)\n return total\n}`,
+ `function f() {\n const acc = sum(xs)\n return acc\n}`],
+ ['7. Indent — wrap in a block', 'the body shifts right and down together',
+ `function f() {\n one()\n two()\n}`,
+ `function f() {\n if (ok) {\n one()\n two()\n }\n}`],
+]
+
+const slides = [slide([
+ text('Seven ways to change code', 96, 250, 1088, 80, { size: 64, weight: 700 }),
+ text('Each pair is one edit. Watch what travels, and what tears.', 96, 350, 900, 50, { size: 22, color: MIST }),
+ text('Scenario 2 is the known-bad case — a swap of two lines sharing a prefix.', 96, 410, 950, 50, { size: 18, color: PEACH }),
+], { transition: 'fade', name: 'title' })]
+
+for (const [label, expect, A, B] of CASES) {
+ const head = (s) => text(s, 96, 96, 1088, 50, { size: 30, weight: 700 })
+ const sub = (s) => text(s, 96, 146, 1088, 40, { size: 18, color: MIST })
+ slides.push(slide([head(label), sub('before — ' + expect), code(A)], { transition: 'fade', name: label + ' (before)' }))
+ slides.push(slide([head(label), sub('after — ' + expect), code(B)], { name: label + ' (after)', notes: expect }))
+}
+
+const doc = {
+ format: 'bento/slides', version: 1, docId: 'code-matrix-demo-0001',
+ title: 'Seven ways to change code',
+ size: { width: 1280, height: 720 },
+ theme: { background: INK, color: PAPER, accent: PEACH, fontFamily: 'Instrument Sans, Helvetica Neue, sans-serif' },
+ present: { controls: false, morphSeconds: 1.4 }, slides, modified: new Date().toISOString(),
+}
+
+const shell = readFileSync(shellPath, 'utf8')
+const open = '<script type="application/bento+json" id="bento-doc">'
+const i = shell.indexOf(open)
+const j = shell.indexOf('</scr' + 'ipt>', i)
+writeFileSync(out, shell.slice(0, i + open.length) + JSON.stringify(doc).replace(/</g, '\\u003c') + shell.slice(j))
+console.log(`wrote ${out}`)
+console.log(` ${slides.length} slides — ${CASES.length} scenarios`)
diff --git a/slides/package-lock.json b/slides/package-lock.json
index 22fddacf..b361ff66 100644
--- a/slides/package-lock.json
+++ b/slides/package-lock.json
@@ -12,7 +12,6 @@
"moveable": "^0.53.0",
"reveal.js": "^5.2.1",
"selecto": "^1.26.3",
- "shiki": "4.3.1",
"temml": "^0.13.3"
},
"devDependencies": {
@@ -940,106 +939,6 @@
"@daybrush/utils": "^1.4.0"
}
},
- "node_modules/@shikijs/core": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.3.1.tgz",
- "integrity": "sha512-ANMDxuaPsNMdDC1m4vfvhlDmJweMwkE5XitTwrq2rWHx5jM+dlm4MmHt2PP6t0uejfR77SuhrhJ0zEijIF/uhA==",
- "license": "MIT",
- "dependencies": {
- "@shikijs/primitive": "4.3.1",
- "@shikijs/types": "4.3.1",
- "@shikijs/vscode-textmate": "^10.0.2",
- "@types/hast": "^3.0.4",
- "hast-util-to-html": "^9.0.5"
- },
- "engines": {
- "node": ">=20"
- }
- },
- "node_modules/@shikijs/engine-javascript": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.3.1.tgz",
- "integrity": "sha512-JBItcnPuYq7jVJdZo/vMj94r+szT7XEjHFX+mvFDGSEIbVAXAGyHAHzhbWzpGOwYidCZrErJLLgn2PVeiokHnQ==",
- "license": "MIT",
- "dependencies": {
- "@shikijs/types": "4.3.1",
- "@shikijs/vscode-textmate": "^10.0.2",
- "oniguruma-to-es": "^4.3.6"
- },
- "engines": {
- "node": ">=20"
- }
- },
- "node_modules/@shikijs/engine-oniguruma": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.3.1.tgz",
- "integrity": "sha512-OXyNMzg0pews+msMj4cHeqT4xiYKKvbnn6VbdAXxfoFl3SSx4fJTc8FadECuc5/H9p3BzhNAoAUXKwAu9rWYhg==",
- "license": "MIT",
- "dependencies": {
- "@shikijs/types": "4.3.1",
- "@shikijs/vscode-textmate": "^10.0.2"
- },
- "engines": {
- "node": ">=20"
- }
- },
- "node_modules/@shikijs/langs": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.3.1.tgz",
- "integrity": "sha512-m0l9nsDqgBHvbZbk7A0/kXz/impK3uB/c6rAn6Gpg/uPtdZRQ+alsN/17MU5thb68XTj/4DxkZAotrM0GGSpDQ==",
- "license": "MIT",
- "dependencies": {
- "@shikijs/types": "4.3.1"
- },
- "engines": {
- "node": ">=20"
- }
- },
- "node_modules/@shikijs/primitive": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.3.1.tgz",
- "integrity": "sha512-CXQRQOYy1leqQ8ceTeJdmXv/bsUY++6QyLpXJ94LZAAYj5X2SKRdc5ipguv4NPyGVKItB2PPwUpRNe0Sjh5S1A==",
- "license": "MIT",
- "dependencies": {
- "@shikijs/types": "4.3.1",
- "@shikijs/vscode-textmate": "^10.0.2",
- "@types/hast": "^3.0.4"
- },
- "engines": {
- "node": ">=20"
- }
- },
- "node_modules/@shikijs/themes": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.3.1.tgz",
- "integrity": "sha512-dgpoJ4WqNi2yTmizQHBJ5zcX6j2lE6icN/0yt4l1kkf16jrY/pwPLoTb1ETsWMz0OBLf9ZNvwmxft+cH+N9qSA==",
- "license": "MIT",
- "dependencies": {
- "@shikijs/types": "4.3.1"
- },
- "engines": {
- "node": ">=20"
- }
- },
- "node_modules/@shikijs/types": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.3.1.tgz",
- "integrity": "sha512-CHFxE0jztBIZRHH6gxXE7DXUCFXjReEGxZ/j0rfSLGKZuwp2xBYycEP14875DSa9KLL/6700oxIq6oO6ef9K2g==",
- "license": "MIT",
- "dependencies": {
- "@shikijs/vscode-textmate": "^10.0.2",
- "@types/hast": "^3.0.4"
- },
- "engines": {
- "node": ">=20"
- }
- },
- "node_modules/@shikijs/vscode-textmate": {
- "version": "10.0.2",
- "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz",
- "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==",
- "license": "MIT"
- },
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -1047,24 +946,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/@types/hast": {
- "version": "3.0.5",
- "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz",
- "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "*"
- }
- },
- "node_modules/@types/mdast": {
- "version": "4.0.4",
- "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",
- "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "*"
- }
- },
"node_modules/@types/node": {
"version": "24.13.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",
@@ -1082,18 +963,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/@types/unist": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
- "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
- "license": "MIT"
- },
- "node_modules/@ungap/structured-clone": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.3.tgz",
- "integrity": "sha512-60YRaenCQcVjYEKOcG824+DRGGIQ3VKErcBoAEDJZz5bKIs2ZG+X/H9Nk+Q6EVkwJk5QNApxbrc5QtBSwtrXAg==",
- "license": "ISC"
- },
"node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
@@ -1164,36 +1033,6 @@
"node": ">=6"
}
},
- "node_modules/ccount": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",
- "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/character-entities-html4": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz",
- "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
- "node_modules/character-entities-legacy": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
- "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/cliui": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
@@ -1226,16 +1065,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/comma-separated-tokens": {
- "version": "2.0.3",
- "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
- "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/croact": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/croact/-/croact-1.0.4.tgz",
@@ -1311,28 +1140,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/dequal": {
- "version": "2.0.3",
- "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
- "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/devlop": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",
- "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",
- "license": "MIT",
- "dependencies": {
- "dequal": "^2.0.0"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/dijkstrajs": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
@@ -1485,52 +1292,6 @@
"node": "6.* || 8.* || >= 10.*"
}
},
- "node_modules/hast-util-to-html": {
- "version": "9.0.5",
- "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",
- "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "@types/unist": "^3.0.0",
- "ccount": "^2.0.0",
- "comma-separated-tokens": "^2.0.0",
- "hast-util-whitespace": "^3.0.0",
- "html-void-elements": "^3.0.0",
- "mdast-util-to-hast": "^13.0.0",
- "property-information": "^7.0.0",
- "space-separated-tokens": "^2.0.0",
- "stringify-entities": "^4.0.0",
- "zwitch": "^2.0.4"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/hast-util-whitespace": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",
- "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/html-void-elements": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz",
- "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
@@ -1582,116 +1343,6 @@
"node": ">=8"
}
},
- "node_modules/mdast-util-to-hast": {
- "version": "13.2.1",
- "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",
- "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",
- "license": "MIT",
- "dependencies": {
- "@types/hast": "^3.0.0",
- "@types/mdast": "^4.0.0",
- "@ungap/structured-clone": "^1.0.0",
- "devlop": "^1.0.0",
- "micromark-util-sanitize-uri": "^2.0.0",
- "trim-lines": "^3.0.0",
- "unist-util-position": "^5.0.0",
- "unist-util-visit": "^5.0.0",
- "vfile": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/micromark-util-character": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",
- "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-symbol": "^2.0.0",
- "micromark-util-types": "^2.0.0"
- }
- },
- "node_modules/micromark-util-encode": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",
- "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT"
- },
- "node_modules/micromark-util-sanitize-uri": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",
- "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "micromark-util-character": "^2.0.0",
- "micromark-util-encode": "^2.0.0",
- "micromark-util-symbol": "^2.0.0"
- }
- },
- "node_modules/micromark-util-symbol": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",
- "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT"
- },
- "node_modules/micromark-util-types": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",
- "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",
- "funding": [
- {
- "type": "GitHub Sponsors",
- "url": "https://github.com/sponsors/unifiedjs"
- },
- {
- "type": "OpenCollective",
- "url": "https://opencollective.com/unified"
- }
- ],
- "license": "MIT"
- },
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
@@ -1751,23 +1402,6 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
- "node_modules/oniguruma-parser": {
- "version": "0.12.2",
- "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz",
- "integrity": "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==",
- "license": "MIT"
- },
- "node_modules/oniguruma-to-es": {
- "version": "4.3.6",
- "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.6.tgz",
- "integrity": "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==",
- "license": "MIT",
- "dependencies": {
- "oniguruma-parser": "^0.12.2",
- "regex": "^6.1.0",
- "regex-recursion": "^6.0.2"
- }
- },
"node_modules/overlap-area": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/overlap-area/-/overlap-area-1.1.0.tgz",
@@ -1885,16 +1519,6 @@
"node": "^10 || ^12 || >=14"
}
},
- "node_modules/property-information": {
- "version": "7.2.0",
- "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz",
- "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/qrcode": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
@@ -1953,30 +1577,6 @@
"selecto": "~1.26.3"
}
},
- "node_modules/regex": {
- "version": "6.1.0",
- "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz",
- "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==",
- "license": "MIT",
- "dependencies": {
- "regex-utilities": "^2.3.0"
- }
- },
- "node_modules/regex-recursion": {
- "version": "6.0.2",
- "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz",
- "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==",
- "license": "MIT",
- "dependencies": {
- "regex-utilities": "^2.3.0"
- }
- },
- "node_modules/regex-utilities": {
- "version": "2.3.0",
- "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz",
- "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==",
- "license": "MIT"
- },
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@@ -2073,25 +1673,6 @@
"dev": true,
"license": "ISC"
},
- "node_modules/shiki": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.3.1.tgz",
- "integrity": "sha512-oR+qDVi2OjX1tmDpyv+3KviX01KzO6Af+0NNnKnsp9491UEGz2YpxTuJboS/6VhYpTdqzmuJBuiTlrAWWJAssw==",
- "license": "MIT",
- "dependencies": {
- "@shikijs/core": "4.3.1",
- "@shikijs/engine-javascript": "4.3.1",
- "@shikijs/engine-oniguruma": "4.3.1",
- "@shikijs/langs": "4.3.1",
- "@shikijs/themes": "4.3.1",
- "@shikijs/types": "4.3.1",
- "@shikijs/vscode-textmate": "^10.0.2",
- "@types/hast": "^3.0.4"
- },
- "engines": {
- "node": ">=20"
- }
- },
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -2102,16 +1683,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/space-separated-tokens": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
- "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
@@ -2127,20 +1698,6 @@
"node": ">=8"
}
},
- "node_modules/stringify-entities": {
- "version": "4.0.4",
- "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
- "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",
- "license": "MIT",
- "dependencies": {
- "character-entities-html4": "^2.0.0",
- "character-entities-legacy": "^3.0.0"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
@@ -2193,16 +1750,6 @@
"node": ">=8.0"
}
},
- "node_modules/trim-lines": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
- "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
- },
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
@@ -2224,102 +1771,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/unist-util-is": {
- "version": "6.0.1",
- "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz",
- "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/unist-util-position": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz",
- "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/unist-util-stringify-position": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",
- "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/unist-util-visit": {
- "version": "5.1.0",
- "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz",
- "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "unist-util-is": "^6.0.0",
- "unist-util-visit-parents": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/unist-util-visit-parents": {
- "version": "6.0.2",
- "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",
- "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "unist-util-is": "^6.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/vfile": {
- "version": "6.0.3",
- "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",
- "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "vfile-message": "^4.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
- "node_modules/vfile-message": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",
- "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",
- "license": "MIT",
- "dependencies": {
- "@types/unist": "^3.0.0",
- "unist-util-stringify-position": "^4.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/unified"
- }
- },
"node_modules/vite": {
"version": "7.3.6",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz",
@@ -2482,16 +1933,6 @@
"engines": {
"node": ">=6"
}
- },
- "node_modules/zwitch": {
- "version": "2.0.4",
- "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
- "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",
- "license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
- }
}
}
}
diff --git a/slides/package.json b/slides/package.json
index 09356e7b..a512931e 100644
--- a/slides/package.json
+++ b/slides/package.json
@@ -14,8 +14,7 @@
"moveable": "^0.53.0",
"reveal.js": "^5.2.1",
"selecto": "^1.26.3",
- "temml": "^0.13.3",
- "shiki": "4.3.1"
+ "temml": "^0.13.3"
},
"devDependencies": {
"@gfx/zopfli": "^1.0.15",
diff --git a/slides/src/code.ts b/slides/src/code.ts
index fddb7a5a..2129b176 100644
--- a/slides/src/code.ts
+++ b/slides/src/code.ts
@@ -1,117 +1,104 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
+//
+// Render bridge for code elements: kernel tokens -> HeckelDiff identities ->
+// morphable spans. The diff engine (diff.ts) decides WHICH token on slide N is
+// the same token as on slide N-1; this file only turns that answer into DOM.
+//
+// Tokens are emitted as `data-sym` spans inside the element's own
+// `data-flip-id` host — the same sub-element channel the formula morph uses —
+// NOT as per-token flip ids. The morph engine is model-driven: a flip id with
+// no model entry is skipped by every matched-pair consumer, so per-token flip
+// ids animate insertions (the entering path needs no model) but let matched
+// tokens TELEPORT. data-sym offsets are measured per host on slide entry and
+// tweened on exit (present.ts cacheSlideSymbols/morphMathSymbols), which is
+// what makes a moved line travel.
-import { ThemedToken } from 'shiki'
-import { Element } from 'hast'
-import { BentoDoc, CodeElement } from './model';
-import { sanitizeHtml } from './render';
-import { getOrCreateHighlighter, HeckelDiff, Insert, State, Token, Delete, Match } from './diff';
-
-let diff: HeckelDiff | undefined = undefined
-
-export type RenderCodeResult = {
- /** The HTML representation when the `CodeElement` has a `grammar` and a `theme` defined. */
- html?: string,
-}
+import { BentoDoc, CodeElement } from './model'
+import { HeckelDiff, type Match, type Insert, type Delete } from './diff'
/**
- * This returns the HTML representation of the `CodeElement` when the corresponding `grammar` and `theme` is defined.
- * Otherwise, it returns undefined.
+ * Seven colours, not four hundred scopes — the zero-cost tier. When the
+ * signed-extension tier lands, grammarAssetId/themeAssetId select real
+ * TextMate rendering and this map becomes the fallback.
*/
-export function renderCode(el: CodeElement, doc: BentoDoc) {
- const mid = el.morphId
- let sanitized: string | undefined = undefined
- if (el.grammarAssetId && el.themeAssetId && el.grammarName && el.themeName) {
- const slideIdx = slideIndex(el, doc)
- const diff = getOrCreateDiff(doc)
- const map = diff.computeDiffs(mid)
- const states: State[] = map.get(slideIdx) ?? []
- const highlighter = getOrCreateHighlighter(doc, el.grammarAssetId, el.themeAssetId)
- const html = highlighter.codeToHtml(el.content, {
- // Bad typings here
- lang: el.grammarName as any,
- theme: el.themeName as any,
- includeExplanation: 'scopeName',
- mergeSameStyleTokens: false,
- transformers: [
- {
- // @ts-expect-error : We don't really need col, and lineElement
- span(hast: Element, line: number, col: number, lineElement: Element, token: ThemedToken) {
- // 0-indexed line number
- const lineNumber = line - 1
- // There should always be a matching state, but if we do intermediate renders then we
- // should still gracefully recover.
- const state = findMatchingState(states, lineNumber, token)
- if (state) {
- const id = morphId(state)
- hast.properties['data-flip-id'] = id
- } else {
- console.warn('Inconsistent States:', states, 'Line Number:', lineNumber, 'Token:', token)
- }
- },
- }
- ]
- })
- // sanitizeHtml(...) strips away all the skiki background styles.
- // That part, is great given the background no longer interferes with rendering.
- sanitized = sanitizeHtml(html)
- }
- return {
- html: sanitized
- }
-}
-
-function getOrCreateDiff(doc: BentoDoc): HeckelDiff {
- if (!diff) {
- diff = new HeckelDiff(doc)
- }
- return diff
+const CODE_COLORS: Record<string, string> = {
+ c: '#6b7f8f', // comment
+ s: '#c98a3e', // string
+ n: '#b0688f', // number
+ k: '#5b8def', // keyword
+ f: '#3fa9a0', // call
+ p: '#7c8794', // punctuation
+ a: '#3f9142', // diff: added
+ d: '#c25a43', // diff: removed
+ x: '', // plain: inherit the element colour
}
-/** Computes the slide index for the `CodeElement` being rendered. */
-function slideIndex(el: CodeElement, doc: BentoDoc): number {
- const slides = doc.slides
- for (let i = 0; i < slides.length; i += 1) {
- const slide = slides[i]
- const filtered = slide.elements.filter(element => element === el)
- if (filtered && filtered.length > 0) return i
- }
- // Should never really happen
- return -1
-}
+/**
+ * Memoized per (morph group, content). The previous module-level singleton was
+ * cached forever — built from the first document it saw and never invalidated,
+ * so live edits kept diffing yesterday's content. Identity-keyed caching does
+ * not work either: store.commit mutates the doc IN PLACE (verified — commit()
+ * runs mutate() on the live object), so no object identity changes on edit.
+ * The signature is the group's actual inputs, which is the only thing the
+ * diff depends on; unchanged content across present-mode's repeated renders
+ * still hits the cache, and any edit anywhere in the group busts it.
+ */
+const diffCache = new Map<string, ReturnType<HeckelDiff['computeDiffs']>>()
-function findMatchingState(states: State[], lineNumber: number, themedToken: ThemedToken): State | undefined {
- const token = Token.fromThemed(lineNumber, themedToken)
- const state = states.find((state) => {
- const kind = state.kind
- if (kind === 'empty') {
- return false
- } else if (kind === 'insert') {
- const insert = state as Insert
- return insert.token.key() === token.key() && insert.token.lineNumber === token.lineNumber && insert.token.offset === token.offset
- } else if (kind === 'delete') {
- const del = state as Delete
- return del.token.key() === token.key() && del.token.lineNumber === token.lineNumber && del.token.offset === token.offset
- } else if (kind === 'match') {
- const match = state as Match
- return match.current.key() === token.key() && match.current.lineNumber === token.lineNumber && match.current.offset === token.offset
+function diffFor(doc: BentoDoc, morphKey: string) {
+ const parts: string[] = [morphKey]
+ doc.slides.forEach((slide, i) => {
+ for (const el of slide.elements) {
+ if (el.type !== 'code') continue
+ const code = el as CodeElement
+ if ((code.morphId ?? code.id) !== morphKey) continue
+ parts.push(`${i}\u001f${code.grammarName ?? ''}\u001f${code.content ?? ''}`)
}
- return false
})
- return state
+ const sig = parts.join('\u001e')
+ let states = diffCache.get(sig)
+ if (!states) {
+ if (diffCache.size > 32) diffCache.clear() // decks have few groups; stay tiny
+ states = new HeckelDiff(doc).computeDiffs(morphKey)
+ diffCache.set(sig, states)
+ }
+ return states
}
-function morphId(state: State): string {
- let id = ''
- if (state.kind === 'insert') {
- const insert = state as Insert
- id = insert.token.morphId()
- } else if (state.kind === 'delete') {
- const del = state as Delete
- id = del.token.morphId()
- } else if (state.kind === 'match') {
- const match = state as Match
- id = match.current.morphId()
+/**
+ * Build the element's token spans into `pre`. Returns false when the element
+ * has no content (caller falls back to plain text).
+ */
+export function renderCodeInto(pre: HTMLElement, el: CodeElement, doc: BentoDoc): boolean {
+ const morphKey = el.morphId ?? el.id
+ const slideIdx = doc.slides.findIndex((s) => s.elements.some((e) => e.id === el.id))
+ if (slideIdx < 0) return false
+ const states = diffFor(doc, morphKey)
+ const slideStates = states.get(slideIdx)
+ if (!slideStates) return false
+ for (const state of slideStates) {
+ if (state.kind === 'empty') continue
+ // Empty is typed { kind: string }, so kind checks cannot discriminate the
+ // union — narrow by hand once it is excluded.
+ const st = state as Match | Insert | Delete
+ const token = st.kind === 'match' ? st.current : st.token
+ const span = document.createElement('span')
+ span.dataset.sym = token.morphId()
+ span.textContent = token.content
+ // Marks a token the morph may MOVE — styles.css gives these
+ // display:inline-block, because a transform does NOTHING to a non-replaced
+ // inline element (accepted, read back verbatim, zero pixels of movement).
+ // Newline and whitespace tokens must stay inline: a newline inside an
+ // atomic inline-level box stops breaking the line under white-space:pre.
+ // diff.ts fromTok has already split multiline tokens, so ink never
+ // carries a newline here.
+ if (/\S/.test(token.content)) span.dataset.tok = ''
+ const color = CODE_COLORS[token.scopes[0] ?? 'x']
+ if (color) span.style.color = color
+ const kind = token.scopes[0]
+ if (kind === 'k' || kind === 'f') span.style.fontWeight = '600'
+ pre.appendChild(span)
}
- return id
+ return pre.childNodes.length > 0
}
diff --git a/slides/src/diff.ts b/slides/src/diff.ts
index f1e1c478..b9eeea75 100644
--- a/slides/src/diff.ts
+++ b/slides/src/diff.ts
@@ -1,36 +1,13 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
-// https://shiki.style/guide/best-performance#fine-grained-bundle
-// When importing Shiki dependencies, be _very careful_ to not import things from the bundled namespaces.
-// Otherwise the runtime costs are huge.
-import { ThemedToken, createHighlighterCoreSync, HighlighterCore } from "shiki/core"
-import { createJavaScriptRegexEngine } from 'shiki/engine/javascript'
+// Tokens come from the kernel tokenizer — the zero-cost tier. The format still
+// carries the grammar/theme asset seam (CodeElement.grammarAssetId/themeAssetId)
+// for a future signed-extension tier with real TextMate grammars; the diff
+// below never cared where tokens come from, which is what makes both tiers
+// share one engine.
import { BentoDoc, Slide } from "./model"
-
-// Preamble
-
-const highlighters: Map<string, HighlighterCore> = new Map()
-
-const engine = createJavaScriptRegexEngine()
-
-/** Also used to render the actual code snippets. */
-export function getOrCreateHighlighter(doc: BentoDoc, grammarId: string, themeId: string): HighlighterCore {
- const key = `${themeId}/${grammarId}`
- let highlighter = highlighters.get(key)
- if (!!highlighter) return highlighter
- const assets = doc.assets ?? {}
- const grammar = JSON.parse(assets[grammarId])
- const theme = JSON.parse(assets[themeId])
- highlighter = createHighlighterCoreSync({
- langs: [grammar],
- themes: [theme],
- engine: engine
- })
- // Highlighters are expensive to create. Keep them around and call dispose() when done.
- highlighters.set(key, highlighter)
- return highlighter
-}
+import { tokenize, type Tok } from "../../kernel/src/tokenize.ts"
// The stable token that we can diff between slides.
@@ -38,13 +15,19 @@ export class Token {
/* The morph id. */
_id: string | undefined
-
- constructor(
- public readonly content: string,
- public readonly scopes: Array<string>,
- public readonly lineNumber: number,
- public readonly offset: number,
- ) {
+ // Explicit fields, not constructor parameter properties: the repo's test
+ // rigs run TypeScript sources under plain node, whose type stripping cannot
+ // execute parameter properties (scripts/test-codediff.ts imports this file).
+ readonly content: string
+ readonly scopes: Array<string>
+ readonly lineNumber: number
+ readonly offset: number
+
+ constructor(content: string, scopes: Array<string>, lineNumber: number, offset: number) {
+ this.content = content
+ this.scopes = scopes
+ this.lineNumber = lineNumber
+ this.offset = offset
this._id = undefined
}
@@ -69,19 +52,30 @@ export class Token {
return JSON.stringify(json)
}
- static fromThemed(lineNumber: number, token: ThemedToken): Token {
- const content = token.content
- const explanations = token.explanation
- const offset = token.offset
- const scopes = new Set<string>()
- if (explanations) {
- for (const explanation of explanations) {
- for (const scope of explanation.scopes) {
- scopes.add(scope.scopeName)
- }
- }
+ /**
+ * Adapt one kernel token, splitting multiline tokens at newlines FIRST.
+ *
+ * The tokenizer's contract allows block comments, triple-quoted strings and
+ * whitespace runs to carry newlines. Rendered tokens with ink must become
+ * atomic inline-level boxes to be animatable (a transform does nothing to a
+ * non-replaced inline element), and a newline inside an atomic box stops
+ * breaking the line under `white-space: pre` — a Python docstring would
+ * collapse its whole block to one rendered line. Splitting HERE, before
+ * identity assignment, keeps one diff token per rendered span; splitting in
+ * the renderer instead would put one morph id on several spans and corrupt
+ * the offset map. Concatenating the split pieces reproduces the original
+ * token exactly, so the tokenizer's lossless guarantee survives.
+ */
+ static fromTok(tok: Tok, lineNumber: number, offset: number): Token[] {
+ const out: Token[] = []
+ let line = lineNumber
+ let off = offset
+ for (const piece of tok.v.split(/(\n)/)) {
+ if (!piece) continue
+ out.push(new Token(piece, [tok.t], line, off))
+ if (piece === '\n') { line += 1; off = 0 } else off += piece.length
}
- return new Token(content, [...scopes], lineNumber, offset)
+ return out
}
}
@@ -127,8 +121,10 @@ export class HeckelDiff {
/** A counter for morph ids. */
static count: number = 0
- constructor(private readonly doc: BentoDoc) {
+ private readonly doc: BentoDoc
+ constructor(doc: BentoDoc) {
+ this.doc = doc
}
/**
@@ -148,7 +144,9 @@ export class HeckelDiff {
// For all the tokens in the first code slide, assign them stable ids.
const firstIdx = HeckelDiff.zipIndex(0, parsed)
let tokens: Token[] = []
- if (firstIdx) {
+ // !== undefined, not truthiness: slide index 0 is falsy, and a morph group
+ // whose first code slide is the deck's first slide got no ids at all.
+ if (firstIdx !== undefined) {
// Reset counts before recomputing stable ids
HeckelDiff.count = 0
tokens = parsed[firstIdx]
@@ -176,32 +174,22 @@ export class HeckelDiff {
return `m-code-token-${this.count}`
}
- private static parse(doc: BentoDoc, slide: Slide, mid: string|undefined): Token[] {
+ private static parse(_doc: BentoDoc, slide: Slide, mid: string|undefined): Token[] {
const tokens: Token[] = []
for (const el of slide.elements) {
- if (el.type === 'code' && el.grammarAssetId && el.themeAssetId && el.morphId === mid) {
- const highlighter = getOrCreateHighlighter(doc, el.grammarAssetId, el.themeAssetId)
- // We need to be able to parse the tokens in the *exact* same way in which we would when
- // calling codeToHtml() in the render step. So rather than call `codeToTokens()` or a similar
- // API here, we instead accumulate tokens using a transformer.
- let allTokens: ThemedToken[][] = []
- highlighter.codeToHtml(el.content, {
- lang: el.grammarName as any,
- theme: el.themeName as any,
- includeExplanation: 'scopeName',
- mergeSameStyleTokens: false,
- transformers: [
- {
- tokens(tokens: ThemedToken[][]) {
- allTokens = tokens
- },
- }
- ]
- })
- for (let i = 0; i < allTokens.length; i += 1) {
- const lineThemedTokens = allTokens[i]
- for (const themedToken of lineThemedTokens) {
- tokens.push(Token.fromThemed(i, themedToken))
+ // The effective morph key is morphId || id, matching render.ts — a lone
+ // code element with no explicit morphId still diffs against its
+ // duplicate-a-slide twins (the duplicate idiom shares ids).
+ if (el.type === 'code' && (el.morphId ?? el.id) === mid) {
+ let line = 0
+ let off = 0
+ for (const tok of tokenize(el.content ?? '', el.grammarName ?? 'js')) {
+ const split = Token.fromTok(tok, line, off)
+ tokens.push(...split)
+ const last = split[split.length - 1]
+ if (last) {
+ if (last.content === '\n') { line = last.lineNumber + 1; off = 0 }
+ else { line = last.lineNumber; off = last.offset + last.content.length }
}
}
}
@@ -244,6 +232,11 @@ export class HeckelDiff {
const matchState = state as Match
const nextToken: Token | undefined = current[i + 1]
const nextPreviousToken: Token | undefined = previous[matchState.previousIdx + 1]
+ // The previous side must be unclaimed too. Without this, duplicating a
+ // token beside an anchor (X B Y -> X B B Y) let the backward pass claim
+ // the same previous token a second time: two current-side tokens shared
+ // one morph id, and duplicate flip ids corrupt pairing downstream.
+ if (statesP[matchState.previousIdx + 1]?.kind !== 'empty') continue
if (nextToken && nextPreviousToken && nextToken.key() == nextPreviousToken.key()) {
const match: Match = {
kind: 'match',
@@ -267,6 +260,8 @@ export class HeckelDiff {
const matchState = state as Match
const priorToken = current[i - 1]
const priorPreviousToken = previous[matchState.previousIdx - 1]
+ // Same previous-side guard as Phase 2, mirrored.
+ if (statesP[matchState.previousIdx - 1]?.kind !== 'empty') continue
if (priorToken && priorPreviousToken && priorToken.key() == priorPreviousToken.key()) {
const match: Match = {
kind: 'match',
@@ -311,30 +306,34 @@ export class HeckelDiff {
return [statesP, statesC]
}
+ /**
+ * Keys occurring EXACTLY once, with their index. Counted over the full list:
+ * the previous add-then-delete dance re-added a key on its third occurrence,
+ * so any token repeating an odd number of times — a third `)` is enough —
+ * became a false "unique" anchor and Phase 1 paired wrong positions.
+ * Regression: scripts/test-codediff.ts.
+ */
private static anchors(tokens: Token[]): Map<string, { frequency: number, index: number }> {
- const map = new Map<string, { frequency: number, index: number }>()
+ const freq = new Map<string, { frequency: number, index: number }>()
for (let i = 0; i < tokens.length; i += 1) {
- const token = tokens[i]
- const key = token.key()
- const count = map.get(key) ?? 0
- if (count == 0) {
- map.set(key, { frequency: count + 1, index: i })
- } else {
- map.delete(key)
- }
+ const key = tokens[i].key()
+ const e = freq.get(key)
+ if (e) e.frequency += 1
+ else freq.set(key, { frequency: 1, index: i })
}
- return map
+ for (const [key, e] of freq) if (e.frequency !== 1) freq.delete(key)
+ return freq
}
private static zip(parsed: Array<Token[]>): Array<number[]> {
const pairs: Array<number[]> = []
let index = 0
let previousIdx = HeckelDiff.zipIndex(index, parsed)
- if (!previousIdx) return pairs
+ if (previousIdx === undefined) return pairs
let i = previousIdx + 1
while (i < parsed.length) {
let currentIdx = HeckelDiff.zipIndex(i, parsed)
- if (!currentIdx) break
+ if (currentIdx === undefined) break
else {
pairs.push([previousIdx, currentIdx])
previousIdx = currentIdx
diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.ts
index b5a9badc..b423e4a7 100644
--- a/slides/src/editor/panels.ts
+++ b/slides/src/editor/panels.ts
@@ -6,6 +6,7 @@
import type { Store } from '../store'
import { MEDIA_EMBED_BUDGET, applyChartPalette, defaultChart, internAsset, morphKey, tableStyleFor, uid, type ChartElement, type LineEnding, type MediaElement, type ShapeElement, type Slide, type SlideElement, type TableElement, type TextElement, type TransitionKind, type CodeElement } from '../model'
+import { LANGS } from '../../../kernel/src/tokenize.ts'
import { resolveAsset } from '../render'
import { measureElement } from '../measure'
import { isMacOS } from '../screens'
@@ -1103,62 +1104,6 @@ export class PropsPanel {
input.click()
}
- private embedGrammar(el: CodeElement) {
- const input = document.createElement('input')
- input.type = 'file'
- input.accept = '.json'
- input.addEventListener('change', () => {
- const file = input.files?.[0]
- if (!file) return
- const reader = new FileReader()
- reader.onload = () => {
- const contents = JSON.parse(String(reader.result))
- const name = contents['name']
- const assetId = `grammar:${name}`
- this.store.commit(() => {
- const doc = this.store.doc
- doc.assets = { ...(doc.assets ?? {}), [assetId]: JSON.stringify(contents) }
- this.mutate(el.id, (e) => {
- const el = e as CodeElement
- el.grammarName = name
- el.grammarAssetId = assetId
- }, true)
- })
- this.toast(`"Grammar ${name}" embedded into this file`)
- }
- reader.readAsText(file)
- })
- input.click()
- }
-
- private embedTheme(el: CodeElement) {
- const input = document.createElement('input')
- input.type = 'file'
- input.accept = '.json'
- input.addEventListener('change', () => {
- const file = input.files?.[0]
- if (!file) return
- const reader = new FileReader()
- reader.onload = () => {
- const contents = JSON.parse(String(reader.result))
- const name = contents['name']
- const assetId = `theme:${name}`
- this.store.commit(() => {
- const doc = this.store.doc
- doc.assets = { ...(doc.assets ?? {}), [assetId]: JSON.stringify(contents) }
- this.mutate(el.id, (e) => {
- const el = e as CodeElement
- el.themeAssetId = assetId
- el.themeName = name
- }, true)
- })
- this.toast(`"Theme ${name}" embedded into this file`)
- }
- reader.readAsText(file)
- })
- input.click()
- }
-
private buildShapeProps(el: ShapeElement) {
this.section(t('Fill & stroke'))
const grad = el.fillGradient
@@ -1818,102 +1763,17 @@ export class PropsPanel {
// Line height
this.row('Line height', this.number(el.lineHeight, 0.05, (v, fin) =>
this.mutate(el.id, (e) => { (e as CodeElement).lineHeight = Math.max(v, 0.5) }, fin)))
- const assets = this.store.doc.assets ?? {}
- const grammar = el.grammarAssetId ? assets[el.grammarAssetId] : ''
- const theme = el.themeAssetId ? assets[el.themeAssetId] : ''
- if (!grammar) status.textContent = t('Pick a TextMate Language')
- else if (!theme) status.textContent = t('Pick a TextMate Theme')
- else status.textContent = t('Ready')
- // Pickers
- this.grammarSelect(el)
- this.themeSelect(el)
- // Grammar
- const embedGrammar = document.createElement('button')
- embedGrammar.className = 'ed-btn ed-btn-block'
- embedGrammar.textContent = t('+ Add TextMate Grammar')
- embedGrammar.title = t('Bundle a TextMate Grammar and use it here')
- embedGrammar.addEventListener('click', () => this.embedGrammar(el))
- this.host.appendChild(embedGrammar)
- // Theme
- const embedTheme = document.createElement('button')
- embedTheme.className = 'ed-btn ed-btn-block'
- embedTheme.textContent = t('+ Add TextMate Theme')
- embedTheme.title = t('Bundle a TextMate Theme and use it here')
- embedTheme.addEventListener('click', () => this.embedTheme(el))
- this.host.appendChild(embedTheme)
+ // Language — selects the built-in tokenizer table. grammarName doubles as
+ // the language id; grammarAssetId/themeAssetId stay in the format as the
+ // seam for a future signed-extension tier carrying real TextMate grammars
+ // as deck assets, at which point pickers for them return here.
+ const langs = Object.keys(LANGS).sort().concat(['diff', 'md'])
+ this.row(t('Language'), this.select(langs, el.grammarName ?? 'js', (v) =>
+ this.mutate(el.id, (e) => { (e as CodeElement).grammarName = v }, true)))
+ status.textContent = t('{n} languages built in', { n: String(langs.length) })
this.host.appendChild(status)
}
- private grammarSelect(el: CodeElement) {
- const assets = this.store.doc.assets ?? {}
- const keys = Object.keys(assets)
- const grammars = keys.filter(k => k.startsWith('grammar:'))
- if (grammars && grammars.length > 0) {
- const sel = document.createElement('select')
- const add = (label: string, value: string, selected: boolean) => {
- const o = document.createElement('option')
- o.value = value
- o.textContent = label
- o.selected = selected
- sel.appendChild(o)
- return o
- }
- // Placeholder
- add('<select grammar>', '', !el.grammarAssetId)
- for (const grammar of grammars) {
- let matched = false
- if (el.grammarAssetId === grammar) matched = true
- const name = grammar.replace('grammar:', '')
- add(name, grammar, matched)
- }
- sel.addEventListener('change', () => {
- this.mutate(el.id, (e) => {
- // value is the actual grammar assetId
- const value = sel.value
- const el = e as CodeElement
- el.grammarName = value.replace('grammar:', '')
- el.grammarAssetId = value
- }, true)
- })
- this.row('Grammar', sel)
- }
- }
-
- private themeSelect(el: CodeElement) {
- const assets = this.store.doc.assets ?? {}
- const keys = Object.keys(assets)
- const themes = keys.filter(k => k.startsWith('theme:'))
- if (themes && themes.length > 0) {
- const sel = document.createElement('select')
- const add = (label: string, value: string, selected: boolean) => {
- const o = document.createElement('option')
- o.value = value
- o.textContent = label
- o.selected = selected
- sel.appendChild(o)
- return o
- }
- // Placeholder
- add('<select theme>', '', !el.themeAssetId)
- for (const theme of themes) {
- let matched = false
- if (el.themeAssetId === theme) matched = true
- const name = theme.replace('theme:', '')
- add(name, theme, matched)
- }
- sel.addEventListener('change', () => {
- this.mutate(el.id, (e) => {
- // value is the actual theme assetId
- const value = sel.value
- const el = e as CodeElement
- el.themeName = value.replace('theme:', '')
- el.themeAssetId = value
- }, true)
- })
- this.row('Theme', sel)
- }
- }
-
// --- element ops --------------------------------------------------------------
private opsRow(els: SlideElement[]) {
diff --git a/slides/src/preview.ts b/slides/src/preview.ts
index d1a4d42f..7de9562c 100644
--- a/slides/src/preview.ts
+++ b/slides/src/preview.ts
@@ -52,7 +52,7 @@ const BANNED = 'script,style,noscript,iframe,object,embed,link,video,audio,canva
const DROP_ATTRS = [
'data-el-id', 'data-flip-id', 'data-slide-id', 'data-link', 'data-group',
'data-show-on-hover', 'data-chart', 'data-table', 'data-autoplay',
- 'data-r', 'data-c', 'data-sym', 'contenteditable', 'draggable', 'tabindex',
+ 'data-r', 'data-c', 'data-sym', 'data-tok', 'contenteditable', 'draggable', 'tabindex',
]
/**
diff --git a/slides/src/render.ts b/slides/src/render.ts
index ad434f9e..10f2af20 100644
--- a/slides/src/render.ts
+++ b/slides/src/render.ts
@@ -8,7 +8,7 @@ import type { BentoDoc, ShapeElement, Slide, SlideElement, SvgElement, TableElem
import { morphKey, paginates } from './model'
import { chartSnapshotSvg } from './charts'
import temml from 'temml'
-import { renderCode } from './code'
+import { renderCodeInto } from './code'
const SVG_NS = 'http://www.w3.org/2000/svg'
@@ -1168,10 +1168,11 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOpts
inner.style.lineHeight = String(el.lineHeight)
inner.style.width = '100%'
inner.style.color = el.color
- const result = renderCode(el, doc)
- if (result.html) {
- inner.innerHTML = result.html
- } else {
+ inner.classList.add('bento-code')
+ inner.style.whiteSpace = 'pre'
+ inner.style.margin = '0'
+ inner.style.overflow = 'hidden'
+ if (!renderCodeInto(inner, el, doc)) {
// Fallback to unformatted text
inner.innerText = el.content
}
diff --git a/slides/src/styles.css b/slides/src/styles.css
index 17b5177c..b2f63566 100644
--- a/slides/src/styles.css
+++ b/slides/src/styles.css
@@ -486,8 +486,20 @@ a.ed-btn { text-decoration: none; } /* the update block's "What's new" link is
cursor: default;
}
-.bento-el-code span {
- display: inline-flex;
+/* Code tokens the morph may MOVE. A CSS transform does nothing to a
+ non-replaced inline element — accepted, readable back on style.transform,
+ and zero pixels of movement — so a token has to be an atomic inline-level
+ box before it can travel. LOAD-BEARING: delete this and code morphs stop
+ animating silently, with no error anywhere.
+
+ Scoped to [data-tok] rather than every span on purpose: the renderer sets
+ the attribute only on tokens with ink. Whitespace and newline tokens must
+ stay inline — a newline inside an atomic box no longer breaks the line
+ under `white-space: pre`, and the block collapses to one rendered line
+ (identically under inline-block and inline-flex; the display value was
+ never the variable that mattered). */
+.bento-el-code [data-tok] {
+ display: inline-block;
}
/* A hidden slide is still an ordinary, editable slide — it is just out of the