Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides: add a new `typeWriter` effect for code blocks. (#837)

Rahul Ravikumar251cf9c11626
diff --git a/.github/workflows/ci-slides.yml b/.github/workflows/ci-slides.yml
index ff3014fa..bca3a171 100644
--- a/.github/workflows/ci-slides.yml
+++ b/.github/workflows/ci-slides.yml
@@ -211,6 +211,11 @@ jobs:
# typing at the end of that line is plain text, at the box's end or
# before a line break; opening and closing a box changes nothing.
run: node scripts/test-slides-code-run-exit-browser.mjs
+ - name: The code typewriter types in the show and nowhere else in Chromium
+ # Stable token ids (a plain→typewriter morph types only the new text),
+ # no cursor in the editor, a capped run, and M or leaving the slide
+ # settles it at once.
+ run: node scripts/test-slides-typewriter-browser.mjs
- name: Connectors route on every slide in Chromium
# #493: a deck saved or loaded with stale connector endpoints opens with
# every slide's connectors on their elements' borders (thumbnail too),
diff --git a/schema/slides.json b/schema/slides.json
index 64ea35ca..8bca17e7 100644
--- a/schema/slides.json
+++ b/schema/slides.json
@@ -118,6 +118,9 @@
"type": "number",
"minimum": 0,
"maximum": 10000
+ },
+ "typeWriter": {
+ "type": "boolean"
}
},
"additionalProperties": false
@@ -2310,6 +2313,12 @@
},
"slideNumber": {
"type": "boolean"
+ },
+ "typeWriterSeconds": {
+ "type": "number",
+ "minimum": 0.08,
+ "maximum": 1,
+ "description": "typewriter: seconds per character (absent = 0.08)"
}
},
"additionalProperties": false
diff --git a/scripts/test-slides-typewriter-browser.mjs b/scripts/test-slides-typewriter-browser.mjs
new file mode 100644
index 00000000..4a3ddfc7
--- /dev/null
+++ b/scripts/test-slides-typewriter-browser.mjs
@@ -0,0 +1,172 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The code typewriter (fx.typeWriter): types in the show, and nowhere else.
+//
+// npm run build:single --prefix slides && node scripts/test-slides-typewriter-browser.mjs
+//
+// WHAT THIS PROVES, in the packaged document, on the animation engine's manual
+// clock so every reading is at a known moment:
+// 1. a deck carrying fx.typeWriter and present.typeWriterSeconds opens with
+// both intact (the gate keeps what the schema declares);
+// 2. the editor never shows a cursor, and a typewriter code element renders
+// the SAME token ids as the plain one it morphs from — no extra splits,
+// no empty spans — so the morph pairs it token for token;
+// 3. on that morph arrival the carried tokens are on screen at once while
+// only the new text types in, character by character, behind one cursor,
+// and the run ends with everything shown and the cursor gone;
+// 4. a long snippet finishes within the cap instead of holding the slide;
+// 5. M (reduced motion) mid-run shows everything at once, with no cursor,
+// and nothing resumes; leaving the slide mid-run leaves it whole.
+import { readFileSync, writeFileSync, mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+
+let checks = 0
+let failures = 0
+function ok(cond, msg) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`)
+}
+const shell = readFileSync(new URL('../slides/dist-single/Bento_Slides.bento.html', import.meta.url), 'utf8')
+const dir = mkdtempSync(join(tmpdir(), 'bento-typewriter-'))
+
+const code = (id, content, fx) => ({
+ id, type: 'code', x: 100, y: 100, w: 1000, h: 500, fontSize: 20, fontFamily: 'ui-monospace, monospace',
+ align: 'left', valign: 'top', lineHeight: 1.4, color: '#1E2A3A', content, ...(fx ? { fx } : {}),
+})
+const slide = (id, elements, extra = {}) => ({ id, background: '#ffffff', transition: 'none', notes: '', elements, ...extra })
+const A = 'let total = price * count'
+const B = A + '\nconst label = format(total)'
+const LONG = Array.from({ length: 60 }, (_, i) => `const value${i} = compute(${i}, value${i ? i - 1 : 0})`).join('\n')
+const doc = {
+ format: 'bento/slides', version: 1, docId: 'typewriter-rig', title: 'typewriter',
+ size: { width: 1280, height: 720 },
+ theme: { background: '#ffffff', color: '#1E2A3A', accent: '#f7a600', fontFamily: 'system-ui' },
+ present: { typeWriterSeconds: 0.08 },
+ slides: [
+ slide('s1', [{ id: 'title', type: 'text', x: 100, y: 100, w: 800, h: 120, html: '<p>start</p>' }]),
+ slide('s2', [code('cd', A)]),
+ slide('s3', [code('cd', B, { typeWriter: true })], { transition: 'morph' }),
+ slide('s4', [code('mid', B, { typeWriter: true })]),
+ slide('s5', [code('long', LONG, { typeWriter: true })]),
+ slide('s6', [{ id: 'end', type: 'text', x: 100, y: 100, w: 800, h: 120, html: '<p>end</p>' }]),
+ ],
+}
+const open = '<script type="application/bento+json" id="bento-doc">', close = '</' + 'script>'
+const at = shell.indexOf(open) + open.length
+const file = join(dir, 'deck.bento.html')
+writeFileSync(file, shell.slice(0, at) + JSON.stringify(doc).replace(/</g, '\\u003c') + shell.slice(shell.indexOf(close, at)))
+
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+try {
+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } })
+ await ctx.route(/^https?:/, (r) => r.abort())
+ await ctx.addInitScript(() => {
+ try { localStorage.setItem('bento-slideshow-started', '1'); localStorage.setItem('bento-reduce-motion', 'off') } catch {}
+ })
+ const p = await ctx.newPage()
+ const errors = []
+ p.on('pageerror', (e) => errors.push(e.message))
+ await p.goto('file://' + file)
+ await p.waitForFunction(() => window.bento?.doc && document.querySelector('.ed-sidebar .ed-thumb'), null, { timeout: 20000 })
+ await p.waitForTimeout(800)
+
+ console.log('the format\n')
+ const kept = await p.evaluate(() => ({ fx: window.bento.doc.slides[2].elements[0].fx?.typeWriter, secs: window.bento.doc.present?.typeWriterSeconds }))
+ ok(kept.fx === true && kept.secs === 0.08, `fx.typeWriter and present.typeWriterSeconds survive opening the file (got ${kept.fx}, ${kept.secs})`)
+
+ console.log('\nthe editor\n')
+ const syms = (slideIdx) => p.evaluate(async (i) => {
+ document.querySelectorAll('.ed-sidebar .ed-thumb')[i].click()
+ await new Promise((r) => setTimeout(r, 300))
+ const host = document.querySelector('.ed-stage-scale .bento-el-code')
+ return { ids: [...host.querySelectorAll('[data-sym]')].map((s) => s.dataset.sym), empty: [...host.querySelectorAll('[data-sym]')].filter((s) => !s.textContent).length }
+ }, slideIdx)
+ const plain = await syms(1)
+ const typed = await syms(2)
+ const carried = plain.ids.filter((id) => typed.ids.includes(id)).length
+ ok(plain.ids.length > 0 && carried === plain.ids.length, `every token of the plain slide keeps its id on the typewriter slide (${carried}/${plain.ids.length})`)
+ ok(typed.empty === 0, `no empty token spans (${typed.empty})`)
+ const cursors = await p.evaluate(() => document.querySelectorAll('.bento-code-cursor, .ed-root .cursor').length)
+ ok(cursors === 0, `no cursor anywhere in the editor — canvas or thumbnails (${cursors})`)
+
+ console.log('\nthe show\n')
+ await p.evaluate(() => { document.querySelectorAll('.ed-sidebar .ed-thumb')[0].click(); window.bento.anim.setManual(true) })
+ await p.waitForTimeout(200)
+ await p.keyboard.press('F5')
+ await p.waitForFunction(() => document.querySelector('.bento-present-overlay .reveal .slides > section'), null, { timeout: 10000 })
+ await p.waitForTimeout(500)
+ const tick = (secs) => p.evaluate((s) => { for (let t = 0; t < s; t += 0.05) window.bento.anim.tick(0.05) }, secs)
+ const next = async () => { await p.keyboard.press('ArrowRight'); await p.waitForTimeout(150) }
+ const prev = async () => { await p.keyboard.press('ArrowLeft'); await p.waitForTimeout(150) }
+ // what the audience sees of one code element: per token, is it fully shown?
+ const read = (id, carriedIds = []) => p.evaluate(([id, carriedIds]) => {
+ const host = [...document.querySelectorAll(`.bento-present-overlay [data-el-id="${id}"]`)].find((n) => n.closest('section.present'))
+ ?? document.querySelector(`.bento-present-overlay [data-el-id="${id}"]`)
+ const shown = (s) => {
+ const cs = getComputedStyle(s)
+ if (Number(cs.opacity) < 0.99) return 0
+ const m = /inset\(\S+ ([\d.]+)%/.exec(cs.clipPath)
+ return m ? 1 - Number(m[1]) / 100 : 1
+ }
+ const ink = [...host.querySelectorAll('[data-sym]')].filter((s) => /\S/.test(s.textContent))
+ const frac = (list) => { const n = list.reduce((a, s) => a + s.textContent.length, 0); return n ? list.reduce((a, s) => a + shown(s) * s.textContent.length, 0) / n : 1 }
+ return {
+ all: frac(ink),
+ carried: frac(ink.filter((s) => carriedIds.includes(s.dataset.sym))),
+ fresh: frac(ink.filter((s) => !carriedIds.includes(s.dataset.sym))),
+ partial: ink.some((s) => { const v = shown(s); return v > 0 && v < 1 }),
+ cursors: host.querySelectorAll('.bento-code-cursor, .cursor').length,
+ }
+ }, [id, carriedIds])
+
+ await next(); await tick(1.5) // s2, plain
+ await next() // s3: morph arrival, the typewriter version of the same element
+ await tick(0.35)
+ const m1 = await read('cd', plain.ids)
+ await tick(0.6)
+ const m2 = await read('cd', plain.ids)
+ ok(m1.carried === 1 && m2.carried === 1, `on the morph arrival the carried tokens are shown at once (${m1.carried}, ${m2.carried})`)
+ ok(m1.fresh < m2.fresh && m2.fresh < 1, `only the new text types in, and it advances (${m1.fresh.toFixed(2)} → ${m2.fresh.toFixed(2)})`)
+ ok(m1.partial || m2.partial || (m2.fresh > m1.fresh && m2.fresh - m1.fresh < 0.6), 'it types a character at a time, not a token at a time')
+ ok(m2.cursors === 1, `one cursor while typing (${m2.cursors})`)
+ await tick(5)
+ const m3 = await read('cd', plain.ids)
+ ok(m3.all === 1 && m3.cursors === 0, `the run ends whole, cursor gone (shown ${m3.all.toFixed(2)}, cursors ${m3.cursors})`)
+
+ await next() // s4
+ await tick(0.8)
+ const r1 = await read('mid')
+ await p.keyboard.press('m')
+ await p.waitForTimeout(150)
+ const r2 = await read('mid')
+ await tick(2)
+ const r3 = await read('mid')
+ ok(r1.all < 1, `s4 is mid-run before M (${r1.all.toFixed(2)})`)
+ ok(r2.all === 1 && r2.cursors === 0 && r3.all === 1 && r3.cursors === 0, `M settles at once — all shown, no cursor — and nothing resumes (${r2.all.toFixed(2)}/${r2.cursors}, then ${r3.all.toFixed(2)}/${r3.cursors})`)
+ await p.keyboard.press('m') // motion back on: s4 replays its run
+ await p.waitForTimeout(150)
+ await tick(8)
+
+ await next() // s5: long snippet
+ const chars = LONG.length
+ await tick(0.5)
+ const l0 = await read('long')
+ await tick(7.5)
+ const l1 = await read('long')
+ ok(l0.all < 1 && l1.all === 1 && l1.cursors === 0, `${chars} characters finish inside the cap — done 8 s in (${l0.all.toFixed(2)} → ${l1.all.toFixed(2)}, cursors ${l1.cursors})`)
+
+ await prev() // s4 types again; leave it mid-run
+ await tick(0.6)
+ const e0 = await read('mid')
+ await next()
+ await tick(0.2)
+ const e1 = await read('mid')
+ ok(e0.all < 1 && e1.all === 1 && e1.cursors === 0, `leaving a slide mid-run leaves it whole (${e0.all.toFixed(2)} → ${e1.all.toFixed(2)}, cursors ${e1.cursors})`)
+ ok(errors.length === 0, `no page error${errors.length ? ' — ' + errors[0] : ''}`)
+} finally {
+ await browser.close()
+}
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.ts
index 0d6fca9b..9d4eb28e 100644
--- a/slides/src/editor/panels.ts
+++ b/slides/src/editor/panels.ts
@@ -58,6 +58,7 @@ const ROW_TIPS: Record<string, string> = {
'Enter secs': 'How long the entrance takes, in seconds',
'Reveal step': 'Animate on click: hidden until the n-th → on this slide (0 = shown with the slide)',
'Count up': 'Numbers in this text count up from zero when the slide enters',
+ 'Typewriter': 'Code types in a character at a time, behind a cursor, when it appears',
'Ambient': 'Continuous motion while the slide is on screen — Ken Burns drift or zoom',
'Zoom': 'Ken Burns direction — drift, settle out, or settle in',
'Zoom %': 'How far the Ken Burns zoom travels',
@@ -757,7 +758,7 @@ export class PropsPanel {
const setFx = (patch: Partial<NonNullable<SlideElement['fx']>>) =>
this.mutate(el.id, (e) => {
const fx = { ...(e.fx ?? {}), ...patch }
- if (!fx.enter && !fx.countUp && !fx.ambient && !fx.loop && !fx.step) delete e.fx
+ if (!fx.enter && !fx.countUp && !fx.ambient && !fx.loop && !fx.step && !fx.typeWriter) delete e.fx
else e.fx = fx
}, true)
@@ -789,6 +790,9 @@ export class PropsPanel {
this.row('Count up', this.select(
['off', 'on'], el.fx?.countUp ? 'on' : 'off',
(v) => setFx({ countUp: v === 'on' ? true : undefined })))
+ if (el.type === 'code') this.row('Typewriter', this.select(
+ ['off', 'on'], el.fx?.typeWriter ? 'on' : 'off',
+ (v) => setFx({ typeWriter: v === 'on' ? true : undefined })))
this.row('Ambient', this.select(
['none', 'kenburns'], el.fx?.ambient ?? 'none',
(v) => setFx(v === 'none' ? { ambient: undefined, ken: undefined } : { ambient: 'kenburns' })))
@@ -2302,7 +2306,7 @@ export class PropsPanel {
const el = this.store.element(id)
if (!el) continue
const fx = { ...(el.fx ?? {}), step: step > 0 ? step : undefined }
- if (!fx.enter && !fx.countUp && !fx.ambient && !fx.loop && !fx.step) delete el.fx
+ if (!fx.enter && !fx.countUp && !fx.ambient && !fx.loop && !fx.step && !fx.typeWriter) delete el.fx
else el.fx = fx
}
}, true)
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index 691caa19..c39a4670 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -118,6 +118,7 @@ export const de: Catalog = {
"Couldn't check: {m}": "Prüfung fehlgeschlagen: {m}",
"Couldn’t access the clipboard": "Zugriff auf die Zwischenablage nicht möglich",
"Count up": "Hochzählen",
+ "Typewriter": "Schreibmaschine",
"Custom ({n})": "Benutzerdefiniert ({n})",
"Data": "Daten",
"Default set": "Standardgruppe",
@@ -663,6 +664,7 @@ export const de: Catalog = {
'Entrance animation when the slide appears (plays on non-morph entries; equal order = together)': 'Eingangsanimation beim Erscheinen der Folie (nur bei Nicht-Morph-Einstiegen; gleiche Reihenfolge = gleichzeitig)',
'How long the entrance takes, in seconds': 'Dauer des Eingangs in Sekunden',
'Numbers in this text count up from zero when the slide enters': 'Zahlen in diesem Text zählen beim Folieneintritt von null hoch',
+ 'Code types in a character at a time, behind a cursor, when it appears': 'Code wird beim Erscheinen Zeichen für Zeichen hinter einem Cursor getippt',
'Continuous motion while the slide is on screen — Ken Burns drift or zoom': 'Dauerbewegung, solange die Folie zu sehen ist — Ken-Burns-Drift oder -Zoom',
'Ken Burns direction — drift, settle out, or settle in': 'Ken-Burns-Richtung — Drift, Heraus- oder Hineinzoomen',
'How far the Ken Burns zoom travels': 'Wie weit der Ken-Burns-Zoom fährt',
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index 29457819..6a715a3a 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -118,6 +118,7 @@ export const es: Catalog = {
"Couldn't check: {m}": "No se pudo comprobar: {m}",
"Couldn’t access the clipboard": "No se pudo acceder al portapapeles",
"Count up": "Contador",
+ "Typewriter": "Máquina de escribir",
"Custom ({n})": "Personalizado ({n})",
"Data": "Datos",
"Default set": "Grupo predeterminado",
@@ -663,6 +664,7 @@ export const es: Catalog = {
'Entrance animation when the slide appears (plays on non-morph entries; equal order = together)': 'Animación de entrada al aparecer la diapositiva (solo en entradas sin morph; mismo orden = a la vez)',
'How long the entrance takes, in seconds': 'Duración de la entrada, en segundos',
'Numbers in this text count up from zero when the slide enters': 'Los números de este texto cuentan desde cero al entrar la diapositiva',
+ 'Code types in a character at a time, behind a cursor, when it appears': 'El código se escribe carácter a carácter, tras un cursor, al aparecer',
'Continuous motion while the slide is on screen — Ken Burns drift or zoom': 'Movimiento continuo mientras la diapositiva está en pantalla — deriva o zoom Ken Burns',
'Ken Burns direction — drift, settle out, or settle in': 'Dirección Ken Burns — deriva, asentar alejando o asentar acercando',
'How far the Ken Burns zoom travels': 'Cuánto avanza el zoom Ken Burns',
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index bb9771b3..372f0dd7 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -118,6 +118,7 @@ export const fr: Catalog = {
"Couldn't check: {m}": "Vérification impossible : {m}",
"Couldn’t access the clipboard": "Impossible d'accéder au presse-papiers",
"Count up": "Compteur",
+ "Typewriter": "Machine à écrire",
"Custom ({n})": "Personnalisé ({n})",
"Data": "Données",
"Default set": "Groupe par défaut",
@@ -663,6 +664,7 @@ export const fr: Catalog = {
'Entrance animation when the slide appears (plays on non-morph entries; equal order = together)': 'Animation d’entrée à l’apparition de la diapositive (jouée hors morph ; même ordre = ensemble)',
'How long the entrance takes, in seconds': 'Durée de l’entrée, en secondes',
'Numbers in this text count up from zero when the slide enters': 'Les nombres de ce texte comptent depuis zéro à l’entrée de la diapositive',
+ 'Code types in a character at a time, behind a cursor, when it appears': 'Le code se tape caractère par caractère, derrière un curseur, à son apparition',
'Continuous motion while the slide is on screen — Ken Burns drift or zoom': 'Mouvement continu pendant l’affichage — dérive ou zoom Ken Burns',
'Ken Burns direction — drift, settle out, or settle in': 'Direction Ken Burns — dérive, zoom arrière ou zoom avant',
'How far the Ken Burns zoom travels': 'Amplitude du zoom Ken Burns',
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index ca135435..c36147d1 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -118,6 +118,7 @@ export const it: Catalog = {
"Couldn't check: {m}": "Verifica non riuscita: {m}",
"Couldn’t access the clipboard": "Impossibile accedere agli appunti",
"Count up": "Conteggio",
+ "Typewriter": "Macchina da scrivere",
"Custom ({n})": "Personalizzato ({n})",
"Data": "Dati",
"Default set": "Gruppo predefinito",
@@ -663,6 +664,7 @@ export const it: Catalog = {
'Entrance animation when the slide appears (plays on non-morph entries; equal order = together)': 'Animazione d’ingresso all’apparire della slide (solo su ingressi senza morph; stesso ordine = insieme)',
'How long the entrance takes, in seconds': 'Durata dell’ingresso, in secondi',
'Numbers in this text count up from zero when the slide enters': 'I numeri in questo testo contano da zero all’ingresso della slide',
+ 'Code types in a character at a time, behind a cursor, when it appears': 'Il codice si digita un carattere alla volta, dietro un cursore, quando appare',
'Continuous motion while the slide is on screen — Ken Burns drift or zoom': 'Movimento continuo mentre la slide è visibile — deriva o zoom Ken Burns',
'Ken Burns direction — drift, settle out, or settle in': 'Direzione Ken Burns — deriva, assestamento in uscita o in entrata',
'How far the Ken Burns zoom travels': 'Quanto avanza lo zoom Ken Burns',
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index a56c495e..c3dae3de 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -118,6 +118,7 @@ export const ja: Catalog = {
"Couldn't check: {m}": "確認できませんでした: {m}",
"Couldn’t access the clipboard": "クリップボードにアクセスできませんでした",
"Count up": "カウントアップ",
+ "Typewriter": "タイプライター",
"Custom ({n})": "カスタム ({n})",
"Data": "データ",
"Default set": "既定セット",
@@ -663,6 +664,7 @@ export const ja: Catalog = {
'Entrance animation when the slide appears (plays on non-morph entries; equal order = together)': 'スライド表示時の登場アニメーション(モーフ以外の入りで再生。同じ順番 = 同時)',
'How long the entrance takes, in seconds': '登場にかける秒数',
'Numbers in this text count up from zero when the slide enters': 'スライド表示時にテキスト中の数字が 0 からカウントアップ',
+ 'Code types in a character at a time, behind a cursor, when it appears': 'スライドが表示されると、コードがカーソルの後ろで1文字ずつ入力されます',
'Continuous motion while the slide is on screen — Ken Burns drift or zoom': 'スライド表示中の常時モーション — Ken Burns のドリフトまたはズーム',
'Ken Burns direction — drift, settle out, or settle in': 'Ken Burns の方向 — ドリフト、ズームアウト、ズームイン',
'How far the Ken Burns zoom travels': 'Ken Burns ズームの移動量',
diff --git a/slides/src/i18n/packed.ts b/slides/src/i18n/packed.ts
index dc6da6f1..d39eaf47 100644
--- a/slides/src/i18n/packed.ts
+++ b/slides/src/i18n/packed.ts
@@ -129,6 +129,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Couldn't check: {m}": ["確認できませんでした: {m}","无法检查:{m}","無法檢查:{m}","No se pudo comprobar: {m}","Vérification impossible : {m}","Prüfung fehlgeschlagen: {m}","Verifica non riuscita: {m}","Não foi possível verificar: {m}"],
"Couldn’t access the clipboard": ["クリップボードにアクセスできませんでした","无法访问剪贴板","無法存取剪貼簿","No se pudo acceder al portapapeles","Impossible d'accéder au presse-papiers","Zugriff auf die Zwischenablage nicht möglich","Impossibile accedere agli appunti","Não foi possível acessar a área de transferência"],
"Count up": ["カウントアップ","数字递增","數字遞增","Contador","Compteur","Hochzählen","Conteggio","Contagem crescente"],
+ "Typewriter": ["タイプライター","打字机","打字機","Máquina de escribir","Machine à écrire","Schreibmaschine","Macchina da scrivere","Máquina de escrever"],
"Custom ({n})": ["カスタム ({n})","自定义 ({n})","自訂 ({n})","Personalizado ({n})","Personnalisé ({n})","Benutzerdefiniert ({n})","Personalizzato ({n})","Personalizado ({n})"],
"Data": ["データ","数据","資料","Datos","Données","Daten","Dati","Dados"],
"Default set": ["既定セット","默认组","預設組","Grupo predeterminado","Groupe par défaut","Standardgruppe","Gruppo predefinito","Conjunto padrão"],
@@ -670,6 +671,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Entrance animation when the slide appears (plays on non-morph entries; equal order = together)": ["スライド表示時の登場アニメーション(モーフ以外の入りで再生。同じ順番 = 同時)","幻灯片出现时的入场动画(仅非变形进入时播放;顺序相同 = 同时)","投影片出現時的進場動畫(僅非變形進場時播放;順序相同 = 同時)","Animación de entrada al aparecer la diapositiva (solo en entradas sin morph; mismo orden = a la vez)","Animation d’entrée à l’apparition de la diapositive (jouée hors morph ; même ordre = ensemble)","Eingangsanimation beim Erscheinen der Folie (nur bei Nicht-Morph-Einstiegen; gleiche Reihenfolge = gleichzeitig)","Animazione d’ingresso all’apparire della slide (solo su ingressi senza morph; stesso ordine = insieme)","Animação de entrada quando o slide aparece (ocorre em entradas sem morph; mesma ordem = juntos)"],
"How long the entrance takes, in seconds": ["登場にかける秒数","入场动画时长(秒)","進場動畫秒數","Duración de la entrada, en segundos","Durée de l’entrée, en secondes","Dauer des Eingangs in Sekunden","Durata dell’ingresso, in secondi","Quanto tempo a entrada leva, em segundos"],
"Numbers in this text count up from zero when the slide enters": ["スライド表示時にテキスト中の数字が 0 からカウントアップ","幻灯片进入时文字中的数字从 0 开始递增","投影片進場時文字中的數字從 0 開始遞增","Los números de este texto cuentan desde cero al entrar la diapositiva","Les nombres de ce texte comptent depuis zéro à l’entrée de la diapositive","Zahlen in diesem Text zählen beim Folieneintritt von null hoch","I numeri in questo testo contano da zero all’ingresso della slide","Os números deste texto contam a partir do zero quando o slide entra"],
+ "Code types in a character at a time, behind a cursor, when it appears": ["スライドが表示されると、コードがカーソルの後ろで1文字ずつ入力されます","出现时,代码在光标后逐字键入","出現時,程式碼在游標後逐字鍵入","El código se escribe carácter a carácter, tras un cursor, al aparecer","Le code se tape caractère par caractère, derrière un curseur, à son apparition","Code wird beim Erscheinen Zeichen für Zeichen hinter einem Cursor getippt","Il codice si digita un carattere alla volta, dietro un cursore, quando appare","O código é digitado caractere a caractere, atrás de um cursor, ao aparecer"],
"Continuous motion while the slide is on screen — Ken Burns drift or zoom": ["スライド表示中の常時モーション — Ken Burns のドリフトまたはズーム","幻灯片显示期间的持续动效 — Ken Burns 漂移或缩放","投影片顯示期間的持續動態 — Ken Burns 漂移或縮放","Movimiento continuo mientras la diapositiva está en pantalla — deriva o zoom Ken Burns","Mouvement continu pendant l’affichage — dérive ou zoom Ken Burns","Dauerbewegung, solange die Folie zu sehen ist — Ken-Burns-Drift oder -Zoom","Movimento continuo mentre la slide è visibile — deriva o zoom Ken Burns","Movimento contínuo enquanto o slide está na tela — deriva ou zoom Ken Burns"],
"Ken Burns direction — drift, settle out, or settle in": ["Ken Burns の方向 — ドリフト、ズームアウト、ズームイン","Ken Burns 方向 — 漂移、缩小定格或放大定格","Ken Burns 方向 — 漂移、縮小定格或放大定格","Dirección Ken Burns — deriva, asentar alejando o asentar acercando","Direction Ken Burns — dérive, zoom arrière ou zoom avant","Ken-Burns-Richtung — Drift, Heraus- oder Hineinzoomen","Direzione Ken Burns — deriva, assestamento in uscita o in entrata","Direção do Ken Burns — deriva, acomodar afastando ou acomodar aproximando"],
"How far the Ken Burns zoom travels": ["Ken Burns ズームの移動量","Ken Burns 缩放幅度","Ken Burns 縮放幅度","Cuánto avanza el zoom Ken Burns","Amplitude du zoom Ken Burns","Wie weit der Ken-Burns-Zoom fährt","Quanto avanza lo zoom Ken Burns","O quanto o zoom Ken Burns percorre"],
diff --git a/slides/src/i18n/pt.ts b/slides/src/i18n/pt.ts
index fa89c939..7876026d 100644
--- a/slides/src/i18n/pt.ts
+++ b/slides/src/i18n/pt.ts
@@ -109,6 +109,7 @@ export const pt: Catalog = {
"Couldn't check: {m}": "Não foi possível verificar: {m}",
"Couldn’t access the clipboard": "Não foi possível acessar a área de transferência",
"Count up": "Contagem crescente",
+ "Typewriter": "Máquina de escrever",
"Custom ({n})": "Personalizado ({n})",
"Data": "Dados",
"Default set": "Conjunto padrão",
@@ -650,6 +651,7 @@ export const pt: Catalog = {
"Entrance animation when the slide appears (plays on non-morph entries; equal order = together)": "Animação de entrada quando o slide aparece (ocorre em entradas sem morph; mesma ordem = juntos)",
"How long the entrance takes, in seconds": "Quanto tempo a entrada leva, em segundos",
"Numbers in this text count up from zero when the slide enters": "Os números deste texto contam a partir do zero quando o slide entra",
+ "Code types in a character at a time, behind a cursor, when it appears": "O código é digitado caractere a caractere, atrás de um cursor, ao aparecer",
"Continuous motion while the slide is on screen — Ken Burns drift or zoom": "Movimento contínuo enquanto o slide está na tela — deriva ou zoom Ken Burns",
"Ken Burns direction — drift, settle out, or settle in": "Direção do Ken Burns — deriva, acomodar afastando ou acomodar aproximando",
"How far the Ken Burns zoom travels": "O quanto o zoom Ken Burns percorre",
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index 45d31739..d1e380b7 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -118,6 +118,7 @@ export const zhHans: Catalog = {
"Couldn't check: {m}": "无法检查:{m}",
"Couldn’t access the clipboard": "无法访问剪贴板",
"Count up": "数字递增",
+ "Typewriter": "打字机",
"Custom ({n})": "自定义 ({n})",
"Data": "数据",
"Default set": "默认组",
@@ -663,6 +664,7 @@ export const zhHans: Catalog = {
'Entrance animation when the slide appears (plays on non-morph entries; equal order = together)': '幻灯片出现时的入场动画(仅非变形进入时播放;顺序相同 = 同时)',
'How long the entrance takes, in seconds': '入场动画时长(秒)',
'Numbers in this text count up from zero when the slide enters': '幻灯片进入时文字中的数字从 0 开始递增',
+ 'Code types in a character at a time, behind a cursor, when it appears': '出现时,代码在光标后逐字键入',
'Continuous motion while the slide is on screen — Ken Burns drift or zoom': '幻灯片显示期间的持续动效 — Ken Burns 漂移或缩放',
'Ken Burns direction — drift, settle out, or settle in': 'Ken Burns 方向 — 漂移、缩小定格或放大定格',
'How far the Ken Burns zoom travels': 'Ken Burns 缩放幅度',
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index 068669e1..042d1b1e 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -118,6 +118,7 @@ export const zhHant: Catalog = {
"Couldn't check: {m}": "無法檢查:{m}",
"Couldn’t access the clipboard": "無法存取剪貼簿",
"Count up": "數字遞增",
+ "Typewriter": "打字機",
"Custom ({n})": "自訂 ({n})",
"Data": "資料",
"Default set": "預設組",
@@ -663,6 +664,7 @@ export const zhHant: Catalog = {
'Entrance animation when the slide appears (plays on non-morph entries; equal order = together)': '投影片出現時的進場動畫(僅非變形進場時播放;順序相同 = 同時)',
'How long the entrance takes, in seconds': '進場動畫秒數',
'Numbers in this text count up from zero when the slide enters': '投影片進場時文字中的數字從 0 開始遞增',
+ 'Code types in a character at a time, behind a cursor, when it appears': '出現時,程式碼在游標後逐字鍵入',
'Continuous motion while the slide is on screen — Ken Burns drift or zoom': '投影片顯示期間的持續動態 — Ken Burns 漂移或縮放',
'Ken Burns direction — drift, settle out, or settle in': 'Ken Burns 方向 — 漂移、縮小定格或放大定格',
'How far the Ken Burns zoom travels': 'Ken Burns 縮放幅度',
diff --git a/slides/src/model.ts b/slides/src/model.ts
index 788de1ff..b6807791 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -76,6 +76,8 @@ export interface ElementBase {
* `scale` is the far end of the zoom (e.g. 1.06), `duration` in seconds.
*/
ken?: { dir?: 'drift' | 'out' | 'in'; scale?: number; duration?: number }
+ /** code only: the text types in a character at a time when it appears (present) */
+ typeWriter?: boolean
/** continuous looping animation */
loop?:
| { type: 'dash-march'; distance?: number; duration?: number }
@@ -598,6 +600,11 @@ export interface BentoDoc {
* around them wants a slower beat. Clamped on read.
*/
morphSeconds?: number
+ /**
+ * Typewriter pace, in seconds per character. Absent = 0.08; clamped to
+ * 0.08–1 on read, and a whole run never takes longer than 6 seconds.
+ */
+ typeWriterSeconds?: number
}
/** shared assets (raw SVG markup or data URIs), referenced by key */
assets?: Record<string, string>
diff --git a/slides/src/modelkeys.generated.ts b/slides/src/modelkeys.generated.ts
index 1804aea2..15ed3a27 100644
--- a/slides/src/modelkeys.generated.ts
+++ b/slides/src/modelkeys.generated.ts
@@ -24,7 +24,7 @@ export const MODEL_KEYS = {
"embed": ["app", "backdropFilter", "blend", "blur", "doc", "fx", "group", "groupId", "h", "id", "link", "live", "morphId", "opacity", "role", "rotation", "shadow", "showOnHover", "themeRefs", "type", "url", "view", "w", "x", "y"],
"code": ["align", "backdropFilter", "blend", "blur", "color", "content", "fontFamily", "fontSize", "fx", "grammarAssetId", "grammarName", "group", "groupId", "h", "id", "lineHeight", "link", "morphId", "opacity", "role", "rotation", "shadow", "showOnHover", "themeAssetId", "themeName", "themeRefs", "type", "valign", "w", "x", "y"],
},
- "fx": ["ambient", "countUp", "enter", "enterDur", "ken", "loop", "order", "step"],
+ "fx": ["ambient", "countUp", "enter", "enterDur", "ken", "loop", "order", "step", "typeWriter"],
"fxKen": ["dir", "duration", "scale"],
"fxLoop": ["delay", "distance", "duration", "ease", "path", "speeds", "type"],
"shadow": ["blur", "color", "x", "y"],
@@ -39,7 +39,7 @@ export const MODEL_KEYS = {
"theme": ["accent", "background", "chartPalette", "codePalette", "color", "fontFamily", "headingFamily", "palette", "table"],
"themePalette": ["accent2", "accent3", "accent4", "accent5", "accent6", "bg2", "folHlink", "hlink", "tx2"],
"themeCodePalette": ["a", "c", "d", "f", "k", "n", "p", "s"],
- "present": ["controls", "morphSeconds", "numberHidden", "progress", "slideNumber"],
+ "present": ["controls", "morphSeconds", "numberHidden", "progress", "slideNumber", "typeWriterSeconds"],
"font": ["asset", "family", "style", "weight"],
} as const
diff --git a/slides/src/present.ts b/slides/src/present.ts
index e1f9474f..c31ea268 100644
--- a/slides/src/present.ts
+++ b/slides/src/present.ts
@@ -26,6 +26,11 @@ const MORPH_DURATION_DEFAULT = 0.65
/** Set per-deck by doc.present.morphSeconds; clamped to something sane. */
let MORPH_DURATION = MORPH_DURATION_DEFAULT
const MORPH_EASE = 'power2.inOut'
+const TYPE_WRITER_DURATION_DEFAULT = 0.08
+/** Seconds per typed character, per-deck by doc.present.typeWriterSeconds. */
+let TYPE_WRITER_DURATION = TYPE_WRITER_DURATION_DEFAULT
+/** No typewriter run lasts longer than this; a long snippet types faster. */
+const TYPE_WRITER_MAX_TOTAL = 6
export interface PresentSession {
exit(): void
@@ -80,6 +85,7 @@ export function startPresentation(
} = {},
): PresentSession {
MORPH_DURATION = Math.min(6, Math.max(0.1, doc.present?.morphSeconds ?? MORPH_DURATION_DEFAULT))
+ TYPE_WRITER_DURATION = Math.min(1, Math.max(0.08, doc.present?.typeWriterSeconds ?? TYPE_WRITER_DURATION_DEFAULT))
const overlay = document.createElement('div')
overlay.className = 'bento-present-overlay'
@@ -929,6 +935,7 @@ export function startPresentation(
const section = slidesEl.children[cur] as HTMLElement | undefined
const slide = doc.slides[cur]
if (section && slide) {
+ settleTypeWriter(section)
anim.killTweensOf(section.querySelectorAll('.bento-el'))
for (const el of slide.elements) {
const node = section.querySelector<HTMLElement>(`[data-el-id="${CSS.escape(el.id)}"]`)
@@ -1307,6 +1314,7 @@ export function startPresentation(
// stuck at its "from" state (invisible) for every future visit.
anim.killTweensOf(from.querySelectorAll('.bento-el'))
sweepSymbolSpans(from)
+ settleTypeWriter(from)
const fromSlide = doc.slides[fromIdx]
for (const el of fromSlide?.elements ?? []) {
const node = from.querySelector<HTMLElement>(`[data-el-id="${CSS.escape(el.id)}"]`)
@@ -1436,7 +1444,7 @@ export function startPresentation(
for (const el of slide.elements) {
if (stepOf(el) <= steps.step || stepOf(el) > was) continue
const node = section.querySelector<HTMLElement>(`[data-el-id="${CSS.escape(el.id)}"]`)
- if (node) { anim.killTweensOf(node); applyElementFrame(node, el); resetXform(node) }
+ if (node) { settleTypeWriter(node); anim.killTweensOf(node); applyElementFrame(node, el); resetXform(node) }
}
applyStep(section, slide, steps.step)
}
@@ -1645,7 +1653,7 @@ function enterSpec(kind: EnterKind, enterDur?: number) {
function runEnterFx(slide: Slide, section: HTMLElement, only?: Set<string>, revealing = false, atStep = 0) {
const entering = fxNodes(slide, section)
// reveal-set members are shown/hidden by hover, never by entrance tweens
- .filter(([el]) => (el.fx!.enter || el.fx!.countUp || (revealing && only?.has(el.id))) && !el.showOnHover)
+ .filter(([el]) => (el.fx!.enter || el.fx!.countUp || el.fx!.typeWriter || (revealing && only?.has(el.id))) && !el.showOnHover)
.filter(([el]) => (only ? only.has(el.id) : shownAt(el, atStep)))
.sort((a, b) => (a[0].fx!.order ?? 0) - (b[0].fx!.order ?? 0))
// Delay derives from fx.order when set (equal order ⇒ elements enter
@@ -1673,6 +1681,7 @@ function runEnterFx(slide: Slide, section: HTMLElement, only?: Set<string>, reve
)
}
if (fx.countUp) runCountUp(node)
+ if (fx.typeWriter) runTypeWriter(node, [...node.querySelectorAll<HTMLElement>('[data-sym]')], 0.12 + Math.min(step, 24) * 0.05)
})
settleGuarantee(entering.map(([el, node]) => [node, el]))
}
@@ -1740,6 +1749,89 @@ function runCountUp(node: HTMLElement) {
})
}
+/**
+ * Typewriter (fx.typeWriter, code elements): the tokens appear a character at
+ * a time behind a blinking cursor. Nothing is split — each token span stays
+ * exactly as code.ts rendered it, so its `data-sym` id is the one a plain
+ * code element on the neighbouring slide carries, and a morph between the two
+ * pairs token for token: matched tokens travel, only the NEW text types.
+ * Characters are revealed by clipping the token's box, never by changing its
+ * text, so typing reflows nothing — a token travelling on the same line lands
+ * where the morph measured it.
+ *
+ * Pacing is per character (doc.present.typeWriterSeconds), with the whole run
+ * capped at TYPE_WRITER_MAX_TOTAL: a short snippet types at the authored
+ * speed, a long one speeds up rather than holding the slide for a minute.
+ *
+ * Every run is recorded so it can be SETTLED — finished at once, text whole,
+ * cursor gone — on slide exit, a step back, and reduced motion.
+ */
+const typing = new Map<HTMLElement, () => void>()
+
+function runTypeWriter(node: HTMLElement, tokens: HTMLElement[], delay = 0) {
+ settleTypeWriter(node)
+ const runs: Array<{ span: HTMLElement; start: number; len: number; ink: boolean; shown: number }> = []
+ let total = 0
+ for (const span of tokens) {
+ const len = span.textContent?.length ?? 0
+ if (!len) continue
+ runs.push({ span, start: total, len, ink: span.dataset.tok !== undefined, shown: -1 })
+ total += len
+ }
+ if (!total) return
+ const per = Math.min(TYPE_WRITER_DURATION, TYPE_WRITER_MAX_TOTAL / total)
+ // The cursor exists only while a run does. It is never part of the model
+ // render, so the editor canvas, thumbnails, print and the file preview
+ // cannot show it.
+ const cursor = document.createElement('span')
+ cursor.className = 'bento-code-cursor'
+ cursor.textContent = '▎'
+ cursor.setAttribute('aria-hidden', 'true')
+ runs[0].span.parentElement!.appendChild(cursor)
+ const paint = (k: number) => {
+ let at = runs[0].span
+ let frac = 0
+ for (const r of runs) {
+ const shown = Math.max(0, Math.min(r.len, k - r.start))
+ if (shown !== r.shown) {
+ r.shown = shown
+ // whitespace is invisible either way; only ink needs hiding
+ if (r.ink) r.span.style.clipPath = shown >= r.len ? '' : `inset(0 ${(1 - shown / r.len) * 100}% 0 0)`
+ }
+ // a newline span has no useful box to stand the cursor on
+ if (shown > 0 && !r.span.textContent!.includes('\n')) { at = r.span; frac = shown / r.len }
+ }
+ cursor.style.transform = `translate(${at.offsetLeft + at.offsetWidth * frac}px, ${at.offsetTop}px)`
+ }
+ paint(0)
+ const state = { k: 0 }
+ const finish = () => {
+ if (typing.get(node) !== finish) return
+ typing.delete(node)
+ anim.killTweensOf(state)
+ anim.killTweensOf(cursor)
+ for (const r of runs) r.span.style.clipPath = ''
+ cursor.remove()
+ }
+ typing.set(node, finish)
+ anim.to(state, {
+ k: total,
+ duration: per * total,
+ delay,
+ ease: 'none',
+ onUpdate: () => paint(Math.floor(state.k)),
+ onComplete: () => {
+ paint(total)
+ anim.to(cursor, { opacity: 0, duration: 0.3, delay: 0.6, ease: 'power2.out', onComplete: finish })
+ },
+ })
+}
+
+/** Finish the typewriter runs inside `scope` at once: all text shown, no cursor. */
+function settleTypeWriter(scope: HTMLElement) {
+ for (const [node, finish] of [...typing]) if (scope === node || scope.contains(node)) finish()
+}
+
/** Re-parse inline svg elements so their CSS animations replay on entry. */
function restartSvgAnimations(section: HTMLElement) {
for (const host of section.querySelectorAll<HTMLElement>('.bento-el-svg')) {
@@ -2021,7 +2113,9 @@ function morphMathSymbols(
// 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) => {
+ // A typewriter element types its new text instead, once the travel is under way.
+ if (b.fx?.typeWriter) runTypeWriter(to, fresh, MORPH_DURATION * 0.4)
+ else fresh.forEach((s, i) => {
anim.fromTo(s, { opacity: 0 }, {
opacity: 1,
duration: 0.3,
@@ -2168,6 +2262,11 @@ function runMorph(
if (fromEls.has(id)) continue
const m = toModel.get(id)
if (m?.showOnHover && m.showOnHover !== activeSet) continue // hover-revealed, stays hidden
+ if (m?.fx?.typeWriter) {
+ // new to this slide: it types in, all of it — and rises only if it asked to
+ runTypeWriter(n, [...n.querySelectorAll<HTMLElement>('[data-sym]')], MORPH_DURATION * 0.4)
+ if (!m.fx.enter) continue
+ }
entering.push([n, m?.opacity ?? 1])
}
if (entering.length) {
diff --git a/slides/src/schema.ts b/slides/src/schema.ts
index 8ab3db1b..6fe30b60 100644
--- a/slides/src/schema.ts
+++ b/slides/src/schema.ts
@@ -102,6 +102,7 @@ export function buildSchema(version: string): JsonSchema {
present: obj(MODEL_KEYS.present, {
numberHidden: { type: 'boolean' }, slideNumber: { type: 'boolean' }, controls: { type: 'boolean' }, progress: { type: 'boolean' },
morphSeconds: { type: 'number', minimum: 0, maximum: 60 },
+ typeWriterSeconds: { type: 'number', minimum: 0.08, maximum: 1, description: 'typewriter: seconds per character (absent = 0.08)' },
}),
slides: { type: 'array', minItems: 1, maxItems: LIMITS.slides, items: { $ref: '#/$defs/slide' } },
layouts: { type: 'array', maxItems: LIMITS.slides, items: { $ref: '#/$defs/slide' }, description: 'slide templates' },
diff --git a/slides/src/styles.css b/slides/src/styles.css
index 1cd5ec38..e91f093b 100644
--- a/slides/src/styles.css
+++ b/slides/src/styles.css
@@ -590,6 +590,20 @@ a.ed-btn { text-decoration: none; } /* the update block's "What's new" link is
display: inline-block;
}
+/* The typewriter's cursor (present.ts runTypeWriter). It exists only while a
+ run does, so no other surface ever renders one. Absolute, so standing on a
+ token moves nothing the morph measured. */
+.bento-code-cursor {
+ position: absolute;
+ top: 0;
+ left: 0;
+ pointer-events: none;
+ animation: bento-code-cursor-blink 1s step-end infinite;
+}
+@keyframes bento-code-cursor-blink {
+ 50% { opacity: 0; }
+}
+
/* A hidden slide is still an ordinary, editable slide — it is just out of the
show. Dimmed rather than greyed out, and the number struck through, so the
sidebar reads as "this one will be skipped" without looking broken. */
diff --git a/slides/src/untrusted.ts b/slides/src/untrusted.ts
index a07ad68c..0d2ea82e 100644
--- a/slides/src/untrusted.ts
+++ b/slides/src/untrusted.ts
@@ -316,6 +316,7 @@ const fx = shape(MODEL_KEYS.fx, {
order: num(-1e4, 1e4),
step: num(0, 1e4),
countUp: bool,
+ typeWriter: bool,
ambient: oneOf('kenburns'),
ken: shape(MODEL_KEYS.fxKen, {
dir: oneOf('drift', 'out', 'in'), scale: num(0, 100), duration: num(0, 3600),