Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

Fade in tokens that have no partner

nyblnet51ccbdb5ce49
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1f6be985..5322683c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -251,6 +251,13 @@ jobs:
# a code block to one line with no error anywhere.
run: node scripts/test-tokenize.ts
+ - name: Code-morph identity engine
+ # HeckelDiff decides which token on slide N is the same token as on
+ # slide N-1; every wrong answer is a token that jumps, tears, or steals
+ # another token's journey on screen. Regressions for the three pairing
+ # bugs found in review ride along.
+ run: node scripts/test-codediff.ts
+
- name: First-page preview rig
# Every save writes a static render of page one for file-manager
# thumbnails. Two decisions in that path fail silently: an encrypted
diff --git a/scripts/test-codediff.ts b/scripts/test-codediff.ts
new file mode 100644
index 00000000..3f674a7b
--- /dev/null
+++ b/scripts/test-codediff.ts
@@ -0,0 +1,128 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The code-morph identity engine, held to its answers.
+//
+// node scripts/test-codediff.ts
+//
+// WHAT THIS PROVES. HeckelDiff decides WHICH token on slide N is the same
+// token as on slide N-1; every wrong answer is a token that jumps, tears, or
+// steals another token's journey on screen. Each case here is either a bug
+// found during the #259 review (kept as a regression) or an invariant the
+// renderer builds on.
+
+import { HeckelDiff, type State, type Match } from '../slides/src/diff.ts'
+
+const FAILS: string[] = []
+const check = (name: string, cond: boolean) => {
+ if (!cond) FAILS.push(name)
+ console.log(`${cond ? ' ok ' : ' FAIL '} ${name}`)
+}
+
+/** A minimal doc: one code element per slide, all in one morph group. */
+const codeDoc = (contents: Array<string | null>, lang = 'js') => ({
+ slides: contents.map((content, i) => ({
+ id: `s${i}`,
+ elements: content === null ? [] : [{
+ type: 'code', id: `c${i}`, morphId: 'g', content, grammarName: lang,
+ }],
+ })),
+}) as any
+
+const idsOf = (states: State[] | undefined) =>
+ (states ?? []).filter((s) => s.kind !== 'empty').map((s: any) =>
+ (s.kind === 'match' ? s.current : s.token).morphId())
+const toksOf = (states: State[] | undefined) =>
+ (states ?? []).filter((s) => s.kind !== 'empty').map((s: any) =>
+ (s.kind === 'match' ? s.current : s.token))
+
+// 1. LOSSLESS THROUGH THE ADAPTER — the rendered text is rebuilt from these
+// tokens, multiline splitting included.
+{
+ const src = `function f() {\n /* multi\n line\n comment */\n x = '''nope'''\n}`
+ const doc = codeDoc([src])
+ const states = new HeckelDiff(doc).computeDiffs('g')
+ const rebuilt = toksOf(states.get(0)).map((t: any) => t.content).join('')
+ check('adapter is lossless (multiline comment split included)', rebuilt === src)
+ check('no ink token carries a newline after splitting',
+ toksOf(states.get(0)).every((t: any) => !/\S/.test(t.content) || !t.content.includes('\n')))
+}
+
+// 2. SLIDE 0 GETS IDS — zipIndex results were checked by truthiness, and
+// index 0 is falsy: a group starting on the deck's first slide got nothing.
+{
+ const states = new HeckelDiff(codeDoc(['a()', 'a()\nb()'])).computeDiffs('g')
+ check('a group starting on slide 0 gets ids', idsOf(states.get(0)).every(Boolean))
+ const id0 = idsOf(states.get(0))
+ const id1 = idsOf(states.get(1))
+ check('slide 0 ids carry into slide 1', id0.length > 0 && id0.every((id) => id1.includes(id)))
+}
+
+// 3. NO DOUBLE CLAIM — duplicating a token beside an anchor (X B Y -> X B B Y)
+// let the backward pass claim one previous token twice: two current-side
+// tokens shared one morph id. Verified live against the pre-fix engine.
+{
+ const states = new HeckelDiff(codeDoc(['X\nB\nY', 'X\nB\nB\nY'])).computeDiffs('g')
+ const after = idsOf(states.get(1))
+ check('duplicating a line yields no duplicate ids', new Set(after).size === after.length)
+}
+
+// 4. ODD REPEATS ARE NOT ANCHORS — the old add/delete counting re-added a key
+// on its third occurrence, making it a false "unique" anchor. Three
+// close-parens are enough. Observable invariant: ids stay unique per slide
+// and every previous-side id claimed on the current side exists.
+{
+ const A = `a()\nb()\nc()` // ')' appears 3x, '(' 3x
+ const B = `c()\na()\nb()`
+ const states = new HeckelDiff(codeDoc([A, B])).computeDiffs('g')
+ const after = idsOf(states.get(1))
+ check('odd-repeat punctuation causes no duplicate ids', new Set(after).size === after.length)
+ // the three call names are unique anchors and must keep their ids
+ const names = ['a', 'b', 'c']
+ const t0 = toksOf(states.get(0)), t1 = toksOf(states.get(1))
+ check('moved lines keep their identities', names.every((n) => {
+ const before = t0.find((t: any) => t.content === n)
+ const moved = t1.find((t: any) => t.content === n)
+ return before && moved && before.morphId() === moved.morphId()
+ }))
+}
+
+// 5. RENAME — unchanged tokens keep ids; the renamed token is genuinely new.
+{
+ const states = new HeckelDiff(codeDoc(['const total = sum(xs)\nreturn total',
+ 'const acc = sum(xs)\nreturn acc'])).computeDiffs('g')
+ const t0 = toksOf(states.get(0)), t1 = toksOf(states.get(1))
+ const keep = ['const', 'sum', 'xs', 'return']
+ check('rename: unchanged tokens keep ids', keep.every((n) => {
+ const a = t0.find((t: any) => t.content === n)
+ const b = t1.find((t: any) => t.content === n)
+ return a && b && a.morphId() === b.morphId()
+ }))
+ const acc = t1.filter((t: any) => t.content === 'acc')
+ check('rename: the new name has fresh ids', acc.every((t: any) =>
+ !t0.some((p: any) => p.morphId() === t.morphId())))
+}
+
+// 6. PERSISTENCE ACROSS THE CHAIN — a token surviving three slides keeps one
+// id the whole way; a slide with no code in the group does not break it.
+{
+ const states = new HeckelDiff(codeDoc(['f(x)', 'f(x)\ng(y)', null, 'g(y)\nf(x)'])).computeDiffs('g')
+ const at = (i: number, name: string) =>
+ toksOf(states.get(i)).find((t: any) => t.content === name)?.morphId()
+ check('id survives slides 0 -> 1 -> 3 (2 has no code)',
+ at(0, 'f') !== undefined && at(0, 'f') === at(1, 'f') && at(1, 'f') === at(3, 'f'))
+}
+
+// 7. DETERMINISM — same input, same ids: canvas, thumbnails and present must
+// agree without sharing state.
+{
+ const doc = codeDoc(['a()\nb()', 'b()\na()'])
+ const one = new HeckelDiff(doc).computeDiffs('g')
+ const two = new HeckelDiff(doc).computeDiffs('g')
+ check('two independent runs agree exactly',
+ JSON.stringify([...one.entries()].map(([k, v]) => [k, idsOf(v)])) ===
+ JSON.stringify([...two.entries()].map(([k, v]) => [k, idsOf(v)])))
+}
+
+console.log(FAILS.length ? `\n${FAILS.length} FAILED` : '\nall passed')
+process.exit(FAILS.length ? 1 : 0)
diff --git a/slides/src/diff.ts b/slides/src/diff.ts
index b9eeea75..47e97d07 100644
--- a/slides/src/diff.ts
+++ b/slides/src/diff.ts
@@ -6,7 +6,10 @@
// 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"
+// import type, deliberately: only type names are used, and the erased import
+// is what lets scripts/test-codediff.ts run this file under plain node
+// (extensionless runtime imports do not resolve there).
+import type { BentoDoc, Slide } from "./model"
import { tokenize, type Tok } from "../../kernel/src/tokenize.ts"
// The stable token that we can diff between slides.
diff --git a/slides/src/present.ts b/slides/src/present.ts
index 136cfcd1..e0812e41 100644
--- a/slides/src/present.ts
+++ b/slides/src/present.ts
@@ -1510,6 +1510,23 @@ function morphMathSymbols(
const toAt = symbolOffsets(to, b.w, b.h)
if (!toAt.size) return false
+ // A symbol with no partner on the previous slide has nowhere to travel FROM,
+ // so it simply appeared. For a formula that is right — a new term rides the
+ // element's own transition. For code it is not: a step can introduce a whole
+ // line, and a line that snaps in while its neighbours glide reads as a redraw
+ // rather than an edit. Fading them in, staggered and starting once the travel
+ // is under way, makes the two motions one beat.
+ const fresh = Array.from(to.querySelectorAll<HTMLElement>('[data-sym]'))
+ .filter((s) => !fromAt.has(s.dataset.sym!))
+ fresh.forEach((s, i) => {
+ anim.fromTo(s, { opacity: 0 }, {
+ opacity: 1,
+ duration: 0.3,
+ delay: MORPH_DURATION * 0.4 + Math.min(i, 30) * 0.015,
+ ease: 'power2.out',
+ })
+ })
+
const pairs: Array<{ node: HTMLElement; dx: number; dy: number }> = []
for (const sym of Array.from(to.querySelectorAll<HTMLElement>('[data-sym]'))) {
const src = fromAt.get(sym.dataset.sym!)