Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides: a ``` fence in a text box becomes a Code element; select lines and press ` to set them as code (#641)

nyblnetedc1eef18a9e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 9f5e3489..909f22fc 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1603,6 +1603,11 @@ jobs:
# line breaks and nothing else; the editor-only "Not rendered" hint;
# paste and commit keep a formula's backslashes. Real engine, DOM-free.
run: node scripts/test-slides-math-delims.ts
+ - name: Code fence rig
+ # ``` fences in a text box: which text is a fence (closed only), the
+ # language aliases, autoformat's open-fence guard, and the elements a
+ # fenced box becomes (identity on the first part, no duplicate morph key).
+ run: node scripts/test-slides-code-fence.ts
- name: Maths coverage rig
# #551: maths-lite against Temml's WHOLE vocabulary (1,237 commands and
# environments, frozen offline): no covered command may fall back to
@@ -2105,6 +2110,11 @@ jobs:
# short window), D4 dialog titles, D8 help shortcuts, the compact Save
# caret, phone menu rows, the designed focus ring, dark menu shadow.
run: node scripts/test-slides-chrome-rulings-browser.mjs
+ - name: Code in a text box in Chromium
+ # Real typing: a ``` fence becomes a Code element (in place, or split
+ # out of the text around it), select + ` wraps lines in <code>, pasted
+ # fences convert, and an unclosed fence stays text.
+ run: node scripts/test-slides-code-fence-browser.mjs
spaces-save-browser:
runs-on: ubuntu-latest
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6b1f00d6..091791e8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,17 @@ pre-1.0.
## [Unreleased]
+- **Turn text into code without leaving the text box.** Type a fenced block
+ — a line of three backticks (optionally with a language, like ```` ```js ````
+ or ```` ```python ````), your code, and a closing line of three backticks —
+ and when you finish editing it becomes a real Code element: highlighted,
+ with its language set, and able to morph between slides. If the box held
+ only the fence it turns into the Code element in place; text above or below
+ stays as text boxes stacked around it. Pasting fenced text works the same,
+ into a text box or straight onto the slide. Backticks inside the code are
+ kept as typed, and an unclosed fence stays plain text. You can also select
+ one or more lines and press `` ` `` to set them in code style; press it
+ again to undo that.
- **Screen readers announce what each Save-as and Share command does.** The
menus keep one-line rows with the description on hover, and the same text
is now read out as the command's description; the Save-as list scrolls when
diff --git a/scripts/test-slides-code-fence-browser.mjs b/scripts/test-slides-code-fence-browser.mjs
new file mode 100644
index 00000000..b575e644
--- /dev/null
+++ b/scripts/test-slides-code-fence-browser.mjs
@@ -0,0 +1,172 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Code in a text box, driven through the packaged document (Chromium):
+//
+// npm run build:single --prefix slides && node scripts/test-slides-code-fence-browser.mjs
+//
+// WHAT THIS PROVES (slides/src/editor/codefence.ts). Multi-line text could not
+// become code: the backtick shortcut only converted `x` on one line, and
+// nothing turned text into a Code element. Now, typed with a real keyboard
+// into a real text box:
+// 1. a box that is only a ``` fence becomes a Code element IN PLACE — same id
+// (morph pairing survives), the language from the info string, the code
+// exactly as typed (a `template` literal keeps its backticks: autoformat
+// stays out of an open fence);
+// 2. a box with text around the fence splits into text / code / text,
+// stacked top to bottom inside where the box was;
+// 3. an unclosed fence stays text;
+// 4. typing ``` right after entering a box REPLACES its text (the automatic
+// select-all is not a request to wrap);
+// 5. selecting lines and pressing ` wraps each line in <code>; pressing it
+// again unwraps;
+// 6. a fence pasted into a box being edited, and one pasted onto the canvas,
+// both become Code elements.
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+
+let checks = 0, failures = 0
+const ok = (cond, msg) => { checks++; if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`) }
+const SHELL = new URL('../slides/dist-single/Bento_Slides.bento.html', import.meta.url).href
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+
+/** A fresh page on a one-slide deck holding one text box 'tx'. */
+async function fresh(html = 'Old text') {
+ const p = await browser.newPage({ viewport: { width: 1600, height: 1000 } })
+ const errors = []
+ p.on('pageerror', (e) => errors.push(e.message))
+ await p.route(/^https?:/, (r) => r.abort())
+ await p.goto(SHELL)
+ await p.waitForFunction(() => window.bento?.doc && document.querySelector('.ed-stage-scale'))
+ await p.evaluate((html) => {
+ const d = JSON.parse(JSON.stringify(window.bento.doc))
+ const s = d.slides[0]
+ d.slides = [{ ...s, id: 'fence-slide', stateOf: undefined, elements: [{
+ id: 'tx', type: 'text', x: 200, y: 150, w: 880, h: 300, rotation: 0, opacity: 1,
+ html, fontSize: 32, fontFamily: 'Inter, sans-serif', fontWeight: 400, color: '#1E2A3A',
+ align: 'left', valign: 'top', lineHeight: 1.2, morphId: 'keep-me' }] }]
+ window.bento.loadDoc(JSON.stringify(d))
+ }, html)
+ await p.waitForTimeout(300)
+ return { p, errors }
+}
+const edit = async (p) => {
+ await p.locator('.ed-stage-scale [data-el-id="tx"]').dblclick()
+ await p.waitForFunction(() => document.querySelector('.ed-stage-scale .bento-editing'))
+}
+const typeLines = async (p, lines) => {
+ for (let i = 0; i < lines.length; i++) {
+ if (i) await p.keyboard.press('Enter')
+ await p.keyboard.type(lines[i], { delay: 5 })
+ }
+}
+const commit = async (p) => { await p.keyboard.press('Escape'); await p.waitForTimeout(300) }
+const els = (p) => p.evaluate(() => window.bento.doc.slides[0].elements.map((e) => ({
+ id: e.id, type: e.type, y: e.y, h: e.h, x: e.x, w: e.w, morphId: e.morphId,
+ content: e.content, grammarName: e.grammarName, html: e.html })))
+
+try {
+ console.log('\n1 · a box that is only a fence → a Code element in place\n')
+ {
+ const { p, errors } = await fresh()
+ await edit(p)
+ await typeLines(p, ['```js', 'const a = `hi`', 'const b = 2', '```'])
+ await commit(p)
+ const e = await els(p)
+ ok(e.length === 1 && e[0].type === 'code', `one element, now code (${e.map((x) => x.type).join(', ')})`)
+ ok(e[0]?.id === 'tx' && e[0]?.morphId === 'keep-me', 'same id and morph key — it still pairs across slides')
+ ok(e[0]?.grammarName === 'js', `language from the info string (${e[0]?.grammarName})`)
+ ok(e[0]?.content === 'const a = `hi`\nconst b = 2', `the code exactly as typed, backticks kept (${JSON.stringify(e[0]?.content)})`)
+ ok(errors.length === 0, `no page errors${errors.length ? ': ' + errors.join('; ') : ''}`)
+ await p.close()
+ }
+
+ console.log('\n2 · text around the fence → text / code / text, stacked\n')
+ {
+ const { p } = await fresh()
+ await edit(p)
+ await typeLines(p, ['Intro line', '```python', 'print(1)', '```', 'After line'])
+ await commit(p)
+ const e = await els(p)
+ ok(e.map((x) => x.type).join(',') === 'text,code,text', `three parts in order (${e.map((x) => x.type).join(',')})`)
+ ok(e[0]?.id === 'tx' && /Intro line/.test(e[0]?.html ?? '') && !/```/.test(e[0]?.html ?? ''), 'the first part keeps the box (id) and holds the text before')
+ ok(e[1]?.content === 'print(1)' && e[1]?.grammarName === 'py' && e[1]?.id !== 'tx', `the code part: content, language python→py (${e[1]?.grammarName})`)
+ ok(/After line/.test(e[2]?.html ?? ''), 'the last part holds the text after')
+ ok(e[1]?.morphId === undefined && e[2]?.morphId === undefined, 'new parts do not copy the morph key (unique per slide)')
+ ok(e.length === 3 && e[0].y < e[1].y && e[1].y < e[2].y && e.every((x) => x.x === 200 && x.w === 880), `stacked top to bottom in the box's column (y ${e.map((x) => x.y).join(' < ')})`)
+ ok(e.length === 3 && e[0].y === 150 && e[1].y >= e[0].y + e[0].h - 2 && e[2].y >= e[1].y + e[1].h - 2, 'starting at the box top, without overlapping')
+ await p.close()
+ }
+
+ console.log('\n3 · an unclosed fence stays text\n')
+ {
+ const { p } = await fresh()
+ await edit(p)
+ await typeLines(p, ['```', 'not closed'])
+ await commit(p)
+ const e = await els(p)
+ ok(e.length === 1 && e[0].type === 'text' && /not closed/.test(e[0].html), 'still one text box')
+ await p.close()
+ }
+
+ console.log('\n4 · typing ``` on entering a box replaces, it does not wrap\n')
+ {
+ const { p } = await fresh('Old text')
+ await edit(p) // the whole box is selected on entry
+ await p.keyboard.type('`x`', { delay: 5 })
+ await commit(p)
+ const e = await els(p)
+ ok(!/Old text/.test(e[0]?.html ?? '') && !/<code>Old text/.test(e[0]?.html ?? ''), `the old text was replaced, not wrapped (${e[0]?.html})`)
+ await p.close()
+ }
+
+ console.log('\n5 · select lines, press ` → each line wrapped in <code>; again → unwrapped\n')
+ {
+ const { p } = await fresh()
+ await edit(p)
+ await typeLines(p, ['alpha one', 'beta two'])
+ await p.keyboard.press('ControlOrMeta+a') // select-all on every platform: Meta+A is not select-all on Linux CI
+ await p.keyboard.press('`')
+ await commit(p)
+ let e = await els(p)
+ const codes = (e[0]?.html.match(/<code>/g) ?? []).length
+ ok(e[0]?.type === 'text' && codes === 2, `two lines, two <code> runs (${e[0]?.html})`)
+ ok(/<code>alpha one<\/code>/.test(e[0]?.html) && /<code>beta two<\/code>/.test(e[0]?.html), 'each line wrapped whole, text unchanged')
+ await edit(p)
+ await p.keyboard.press('ControlOrMeta+a') // select-all on every platform: Meta+A is not select-all on Linux CI
+ await p.keyboard.press('`')
+ await commit(p)
+ e = await els(p)
+ ok(!/<code>/.test(e[0]?.html) && /alpha one/.test(e[0]?.html) && /beta two/.test(e[0]?.html), `pressed again on code: unwrapped (${e[0]?.html})`)
+ await p.close()
+ }
+
+ console.log('\n6 · pasted fences\n')
+ {
+ const { p } = await fresh()
+ await edit(p)
+ await p.evaluate(() => {
+ const dt = new DataTransfer()
+ dt.setData('text/plain', '```ts\nlet n: number = `x`.length\n```')
+ document.querySelector('.ed-stage-scale .bento-editing .bento-text-inner').dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }))
+ })
+ await commit(p)
+ let e = await els(p)
+ ok(e.length === 1 && e[0].type === 'code' && e[0].grammarName === 'ts' && e[0].content === 'let n: number = `x`.length',
+ `pasted into a box being edited → code on commit (${JSON.stringify(e[0]?.content)})`)
+ await p.locator('.ed-scroll').click({ position: { x: 8, y: 8 } })
+ await p.evaluate(() => {
+ const dt = new DataTransfer()
+ dt.setData('text/plain', 'Steps\n```bash\nnpm ci\nnpm test\n```')
+ document.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }))
+ })
+ await p.waitForTimeout(300)
+ e = await els(p)
+ const added = e.slice(1)
+ ok(added.map((x) => x.type).join(',') === 'text,code' && added[1]?.grammarName === 'sh' && added[1]?.content === 'npm ci\nnpm test',
+ `pasted onto the canvas → a text box and a Code element (${added.map((x) => x.type).join(',')}, ${added[1]?.grammarName})`)
+ await p.close()
+ }
+} finally { await browser.close() }
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-slides-code-fence.ts b/scripts/test-slides-code-fence.ts
new file mode 100644
index 00000000..ad1b8cd2
--- /dev/null
+++ b/scripts/test-slides-code-fence.ts
@@ -0,0 +1,68 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The DOM-free rules behind code in a text box (slides/src/editor/codefence.ts):
+//
+// node scripts/test-slides-code-fence.ts
+//
+// WHAT THIS PROVES. Which text counts as a fence (only a CLOSED one — a
+// half-typed ``` is never swallowed), what language its info string means
+// (common spellings mapped to the built-in tokenizer's ids, unknown ones left
+// unset), when the caret is inside an open fence (autoformat's guard), and
+// what elements a fenced box becomes (the first part keeps the box's identity;
+// later parts never copy its morph key, which must stay unique on a slide).
+// test-slides-code-fence-browser.mjs drives the same rules through the editor.
+
+import { codeLanguage, estimatedFrames, fencedElements, hasFence, insideOpenFence, splitFences } from '../slides/src/editor/codefence.ts'
+import { defaultText } from '../slides/src/model.ts'
+
+let failures = 0, checks = 0
+const ok = (cond: boolean, msg: string) => { checks++; if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`) }
+
+console.log('\nsplitFences\n')
+const one = splitFences('```js\nconst a = 1\n```')
+ok(one.length === 1 && one[0].kind === 'code' && one[0].lines.join('\n') === 'const a = 1' && (one[0] as { lang?: string }).lang === 'js', 'a box that is only a fence → one code part')
+const mixed = splitFences('Intro\n\n```py\nprint(1)\n\nprint(2)\n```\n\nAfter')
+ok(mixed.map((p) => p.kind).join(',') === 'text,code,text', `text, code, text (${mixed.map((p) => p.kind).join(',')})`)
+ok(mixed[1].lines.join('\n') === 'print(1)\n\nprint(2)', 'blank lines INSIDE the code are kept')
+ok(mixed[0].lines.join('|') === 'Intro' && mixed[2].lines.join('|') === 'After', 'blank lines at the edges of text parts are dropped')
+ok(splitFences('```\nnot closed').every((p) => p.kind === 'text') && !hasFence('```\nnot closed'), 'an unclosed fence stays text')
+ok(splitFences('a\n```\nx\n```\n```ts\ny\n```').filter((p) => p.kind === 'code').length === 2, 'two fences → two code parts')
+ok(splitFences(' ``` \nx\n```').some((p) => p.kind === 'code'), 'contentEditable NBSPs around ``` still count')
+ok(splitFences('use ``` inline ``` here').every((p) => p.kind === 'text'), '``` mid-line is not a fence')
+ok(splitFences('```js\nx\n```js').every((p) => p.kind === 'text'), 'only a bare ``` closes (```js twice is not open+close)')
+
+console.log('\ncodeLanguage\n')
+const lang: Record<string, string | undefined> = {
+ js: 'js', javascript: 'js', JSX: 'js', typescript: 'ts', tsx: 'ts', python: 'py', bash: 'sh', shell: 'sh',
+ 'c++': 'cpp', 'c#': 'csharp', rb: 'ruby', rs: 'rust', golang: 'go', yml: 'yaml', markdown: 'md', diff: 'diff',
+ kotlin: 'kotlin', sql: 'sql', '': undefined, nosuchlang: undefined,
+}
+for (const [info, want] of Object.entries(lang)) ok(codeLanguage(info) === want, `"${info}" → ${want ?? 'unset'} (${codeLanguage(info)})`)
+
+console.log('\ninsideOpenFence (autoformat\'s guard)\n')
+ok(insideOpenFence('```js\nconst a = `hi'), 'caret after an opener → inside')
+ok(!insideOpenFence('```js\nx\n```\nnow `prose'), 'after the closer → outside again')
+ok(!insideOpenFence('plain `text'), 'no fence → outside')
+ok(insideOpenFence('```\na\n```\n```\nb'), 'a second opener → inside')
+
+console.log('\nfencedElements\n')
+const src = { ...defaultText({ html: 'x', color: '#123456' }), id: 'tx', morphId: 'keep', role: 'body', x: 100, y: 50, w: 700 }
+const parts = splitFences('Intro\n```ts\nlet a = 1\n```\nAfter')
+const els = fencedElements(src as never, parts, estimatedFrames(src, parts))
+ok(els.map((e) => e.type).join(',') === 'text,code,text', 'element types follow the parts')
+ok(els[0].id === 'tx' && els[0].morphId === 'keep' && (els[0] as { role?: string }).role === 'body', 'the first part keeps id, morph key and role')
+ok(els.slice(1).every((e) => e.id !== 'tx' && e.morphId === undefined && (e as { role?: string }).role === undefined), 'later parts: fresh ids, no morph key, no role')
+const code = els[1] as { content: string; grammarName?: string; color: string; fontFamily: string }
+ok(code.content === 'let a = 1' && code.grammarName === 'ts' && code.color === '#123456', 'the code part: content, language, the box\'s colour')
+ok(els.every((e) => e.x === 100 && e.w === 700) && els[0].y === 50 && els[0].y < els[1].y && els[1].y < els[2].y, 'one column, stacked from the box top')
+const whole = fencedElements(src as never, splitFences('```\nplain\n```'), [{ y: 50, h: 100 }])
+ok(whole.length === 1 && whole[0].type === 'code' && whole[0].id === 'tx' && whole[0].morphId === 'keep' && (whole[0] as { grammarName?: string }).grammarName === undefined,
+ 'a whole-box fence: the box itself becomes code, identity kept, no language guessed')
+ok(fencedElements(src as never, parts, [{ y: 1, h: 1, html: '<b>Intro</b>' }, { y: 2, h: 2 }, { y: 3, h: 3 }])[0].type === 'text' &&
+ (fencedElements(src as never, parts, [{ y: 1, h: 1, html: '<b>Intro</b>' }, { y: 2, h: 2 }, { y: 3, h: 3 }])[0] as { html: string }).html === '<b>Intro</b>',
+ 'a measured text part keeps its formatting (html from the editor)')
+ok((src as { html: string }).html === 'x' && src.id === 'tx', 'the source element is not modified')
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.ts
index a9a675d6..c0c5db42 100644
--- a/slides/src/editor/canvas.ts
+++ b/slides/src/editor/canvas.ts
@@ -8,7 +8,8 @@ import Moveable from 'moveable'
import Selecto from 'selecto'
import type { Store } from '../store'
import { t } from '../i18n'
-import { defaultShape, internAsset, readableInk, uid, type ShapeElement, type SlideElement, type TableElement } from '../model'
+import { defaultShape, internAsset, readableInk, uid, type ShapeElement, type SlideElement, type TableElement, type TextElement } from '../model'
+import { estimatedFrames, fencedElements, splitFences, toggleCodeOnSelection, type FencePart, type PartFrame } from './codefence'
import { renderSlide, sanitizeHtml } from '../render'
import { autoformatAtCaret, clearAutoformat, markdownToHtml, stripMarkerEscapes, undoAutoformat } from './markdown'
import { bulletsToLists } from './bullets'
@@ -67,6 +68,8 @@ export class SlideCanvas {
/** startTextEdit swapped the rendered form for raw source (a field or a
* formula), so commit must re-render even if the text is unchanged. */
private editingShowedRaw = false
+ /** The selection is still the select-all that entering the box made. */
+ private editAutoSelected = false
/** when editing a table cell, which cell (else null → text element edit) */
private editingCell: { r: number; c: number } | null = null
/** tears down the selection watcher that drives the formatting bar */
@@ -1437,9 +1440,11 @@ export class SlideCanvas {
inner.contentEditable = 'true'
inner.focus()
document.getSelection()?.selectAllChildren(inner)
+ this.editAutoSelected = true // cleared by the first key or click (see the ` toggle)
this.syncTargets()
this.watchSelection(inner)
this.onTextEditChange?.(node.dataset.elId)
+ inner.addEventListener('mousedown', () => { this.editAutoSelected = false }, { signal })
inner.addEventListener('keydown', (ev) => {
ev.stopPropagation() // keep global shortcuts (Delete, arrows…) away
@@ -1448,6 +1453,17 @@ export class SlideCanvas {
this.commitTextEdit()
return
}
+ // ` on a selection wraps each selected line as code (on code: unwraps);
+ // with nothing selected it types a backtick as usual (codefence.ts).
+ // Not on the select-all that entering the box makes: typing ``` there
+ // replaces the text, it does not wrap it — only a selection the author
+ // made (drag, shift-arrows, ⌘A) is a request to wrap.
+ const autoSelected = this.editAutoSelected
+ this.editAutoSelected = false
+ if (ev.key === '`' && !autoSelected && !ev.metaKey && !ev.ctrlKey && !ev.altKey && toggleCodeOnSelection(inner)) {
+ ev.preventDefault()
+ return
+ }
// inline markup: ⌘/Ctrl+B/I/U toggle bold/italic/underline on the
// selection (sanitize keeps b/i/u/strong/em, so it round-trips)
if (ev.metaKey || ev.ctrlKey) {
@@ -1516,6 +1532,15 @@ export class SlideCanvas {
const el = this.store.doc.slides
.find((slide) => slide.id === slideId)
?.elements.find((element) => element.id === id)
+ // a closed ``` fence: the text box becomes (or splits around) a Code element
+ if (el && el.type === 'text') {
+ const parts = splitFences(text)
+ if (parts.some((p) => p.kind === 'code')) {
+ this.commitFences(el, slideId, node, inner, parts)
+ this.flushPendingRender()
+ return
+ }
+ }
if (el && el.type === 'text' && (el.html !== html || grownH > el.h)) {
this.store.commit(() => {
el.html = html
@@ -1541,6 +1566,99 @@ export class SlideCanvas {
this.flushPendingRender()
}
+ /** Replace a text box holding a closed ``` fence with its parts — text, code,
+ * text — in one undoable commit, and select the code. */
+ private commitFences(el: TextElement, slideId: string | null, node: HTMLElement, inner: HTMLElement, parts: FencePart[]) {
+ const slide = this.store.doc.slides.find((s) => s.id === slideId)
+ if (!slide) return
+ const frames = this.measureFenceParts(el, node, inner, parts) ?? estimatedFrames(el, parts)
+ let made: SlideElement[] = []
+ this.store.commit(() => {
+ const at = slide.elements.findIndex((e) => e.id === el.id)
+ if (at < 0) return
+ made = fencedElements(el, parts, frames)
+ slide.elements.splice(at, 1, ...made)
+ })
+ const code = made.find((e) => e.type === 'code')
+ if (code && slide.id === this.store.slide?.id) this.store.select([code.id])
+ }
+
+ /**
+ * Where each fence part sat in the box just edited, in slide units, read off
+ * the rendered lines — so the split parts land where the author saw them —
+ * with each text part's html (its formatting kept). null when the rendered
+ * lines do not line up with the parsed parts, or the box is rotated; the
+ * caller then estimates from line counts.
+ */
+ private measureFenceParts(el: TextElement, node: HTMLElement, inner: HTMLElement, parts: FencePart[]): PartFrame[] | null {
+ if (el.rotation) return null
+ const nodeRect = node.getBoundingClientRect()
+ const scale = nodeRect.width / el.w
+ if (!scale || !Number.isFinite(scale)) return null
+ const isBlock = (n: Node) => n instanceof Element && /^(DIV|P|LI|H1|H2)$/.test(n.tagName)
+ // the line box holding a text node: its block under `inner`, else itself
+ const lineBox = (n: Node): Node => {
+ let b = n
+ while (b.parentNode && b.parentNode !== inner) b = b.parentNode
+ return isBlock(b) ? b : n
+ }
+ const fences: Node[] = []
+ const walker = document.createTreeWalker(inner, NodeFilter.SHOW_TEXT)
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
+ if (/^[ \t ]*```[\w+#.-]*[ \t ]*$/.test((n as Text).data.replace(/​/g, ''))) fences.push(lineBox(n))
+ }
+ const codeCount = parts.filter((p) => p.kind === 'code').length
+ if (fences.length !== codeCount * 2) return null
+ const rectOf = (n: Node) => {
+ if (n instanceof Element) return n.getBoundingClientRect()
+ const r = document.createRange()
+ r.selectNodeContents(n)
+ return r.getBoundingClientRect()
+ }
+ const all = document.createRange()
+ all.selectNodeContents(inner)
+ const contentBottom = all.getBoundingClientRect().bottom
+ // the html between two boundaries (null = the start/end of the box)
+ const htmlBetween = (after: Node | null, before: Node | null): string => {
+ const r = document.createRange()
+ if (after) r.setStartAfter(after); else r.setStart(inner, 0)
+ if (before) r.setEndBefore(before); else r.setEnd(inner, inner.childNodes.length)
+ const box = document.createElement('div')
+ box.append(r.cloneContents())
+ const edge = /^(?:\s|<br\s*\/?>|<div>(?:\s|<br\s*\/?>)*<\/div>)+|(?:\s|<br\s*\/?>|<div>(?:\s|<br\s*\/?>)*<\/div>)+$/g
+ return bulletsToLists(sanitizeHtml(stripMarkerEscapes(box.innerHTML.replace(/​/g, '')))).replace(edge, '')
+ }
+ const minH = Math.ceil(el.fontSize * (el.lineHeight || 1.2))
+ // Heights are measured; positions are re-stacked from the box top, each part
+ // right under the last: the ``` lines are gone, and leaving their two lines
+ // of space around every code part reads as a hole in the slide.
+ const gap = Math.round(el.fontSize * 0.4)
+ const frames: PartFrame[] = []
+ let prevClose: Node | null = null
+ let segTop = nodeRect.top // screen y where the current text segment starts
+ let y = el.y
+ const place = (h: number, html?: string) => {
+ frames.push({ y: Math.round(y), h: Math.max(minH, Math.round(h)), ...(html !== undefined ? { html } : {}) })
+ y += Math.max(minH, Math.round(h)) + gap
+ }
+ for (let i = 0; i <= codeCount; i++) {
+ const open = fences[i * 2] ?? null
+ const html = htmlBetween(prevClose, open)
+ // a text segment exists as a part only when it holds visible text
+ if (html.replace(/<[^>]*>/g, '').replace(/&nbsp;| /g, ' ').trim()) {
+ const bottom = open ? rectOf(open).top : contentBottom
+ place((bottom - segTop) / scale, html)
+ }
+ if (!open) break
+ const close = fences[i * 2 + 1]
+ // the code's own lines: below the opening ``` line, above the closing one
+ place((rectOf(close).top - rectOf(open).bottom) / scale)
+ prevClose = close
+ segTop = rectOf(close).bottom
+ }
+ return frames.length === parts.length ? frames : null
+ }
+
/** Run a repaint that was deferred while an inline edit was in progress (a
* remote op that arrived mid-edit). No-op when nothing is pending. Runs
* after the commit above, so the repaint reflects the merged model. */
diff --git a/slides/src/editor/codefence.ts b/slides/src/editor/codefence.ts
new file mode 100644
index 00000000..249d3fa0
--- /dev/null
+++ b/slides/src/editor/codefence.ts
@@ -0,0 +1,250 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Code in a TEXT box, two ways (maintainer request, 2026-10-07):
+//
+// 1. A fence. Lines between ``` and ``` (optionally ```js, ```python…) become
+// a real Code element when the edit is committed, or when such text is
+// pasted onto the canvas: highlighted, language-aware, and able to morph.
+// A box that is ONLY a fence turns into the Code element in place (same id,
+// so its morph pairing survives); a box with text around the fence splits
+// into text / code / text, stacked where the parts were.
+// 2. A selection. Selecting text and pressing ` wraps each selected line in
+// <code> (pressed again on code, it unwraps), like ⌘B for bold.
+//
+// The fence rules are DOM-free (the rig drives them in node); only
+// toggleCodeOnSelection touches the document.
+
+import { LANGS } from '../../../kernel/src/tokenize.ts'
+import { defaultCode, uid, type CodeElement, type SlideElement, type TextElement } from '../model.ts'
+
+/** A fence line: ``` with an optional info string (the language). Spaces and
+ * NBSPs around it are allowed — contentEditable turns spaces into NBSPs. */
+const FENCE = /^[ \t ]*```[ \t ]*([\w+#.-]*)[ \t ]*$/
+
+const isOpen = (line: string) => FENCE.test(line)
+const isClose = (line: string) => { const m = line.match(FENCE); return !!m && m[1] === '' }
+
+/** Common info-string spellings → the built-in tokenizer's language ids. */
+const ALIASES: Record<string, string> = {
+ javascript: 'js', jsx: 'js', mjs: 'js', cjs: 'js', node: 'js',
+ typescript: 'ts', tsx: 'ts', mts: 'ts',
+ python: 'py', py3: 'py', python3: 'py',
+ bash: 'sh', shell: 'sh', console: 'sh', shellscript: 'sh', shellsession: 'sh',
+ 'c++': 'cpp', cc: 'cpp', cxx: 'cpp', hpp: 'cpp', h: 'c',
+ 'c#': 'csharp', cs: 'csharp', 'f#': 'fsharp', fs: 'fsharp',
+ rb: 'ruby', rs: 'rust', golang: 'go', kt: 'kotlin', kts: 'kotlin',
+ yml: 'yaml', markdown: 'md', htm: 'html', xhtml: 'html', svg: 'xml',
+ docker: 'dockerfile', tf: 'hcl', terraform: 'hcl',
+ 'objective-c': 'objc', objectivec: 'objc', ps1: 'powershell', pwsh: 'powershell',
+ ex: 'elixir', exs: 'elixir', erl: 'erlang', hs: 'haskell', ml: 'ocaml', pl: 'perl',
+ psql: 'sql', postgres: 'sql', postgresql: 'sql', mysql: 'sql', sqlite: 'sql',
+ patch: 'diff', make: 'makefile', mk: 'makefile', jl: 'julia', clj: 'clojure',
+ scm: 'scheme', tex: 'latex', bat: 'batch', cmd: 'batch', vbnet: 'vb',
+ sol: 'solidity', protobuf: 'proto', gql: 'graphql', j2: 'jinja', jinja2: 'jinja',
+}
+
+/** The Code element language for a fence's info string, or undefined when it
+ * names nothing built in (the element then keeps its default). */
+export function codeLanguage(info: string): string | undefined {
+ const k = info.trim().toLowerCase()
+ if (!k) return undefined
+ const id = ALIASES[k] ?? k
+ return id in LANGS || id === 'diff' || id === 'md' ? id : undefined
+}
+
+export type FencePart =
+ | { kind: 'text'; lines: string[] }
+ | { kind: 'code'; lines: string[]; lang?: string }
+
+/**
+ * Split plain text (lines) into text and fenced-code parts. Only a CLOSED fence
+ * counts: an opener with no closer stays text, so a half-typed fence is never
+ * swallowed. Blank lines at the edges of a text part are dropped, and a part
+ * that is all blank disappears (the line between a heading and its fence).
+ */
+export function splitFences(text: string): FencePart[] {
+ const lines = text.replace(/​/g, '').replace(/\r\n?/g, '\n').split('\n')
+ const parts: FencePart[] = []
+ let buf: string[] = []
+ const flush = () => {
+ while (buf.length && !buf[0].trim()) buf.shift()
+ while (buf.length && !buf[buf.length - 1].trim()) buf.pop()
+ if (buf.length) parts.push({ kind: 'text', lines: buf })
+ buf = []
+ }
+ for (let i = 0; i < lines.length; i++) {
+ const m = lines[i].match(FENCE)
+ if (m) {
+ let j = i + 1
+ while (j < lines.length && !isClose(lines[j])) j++
+ if (j < lines.length) {
+ flush()
+ const lang = codeLanguage(m[1])
+ parts.push({ kind: 'code', lines: lines.slice(i + 1, j), ...(lang ? { lang } : {}) })
+ i = j
+ continue
+ }
+ }
+ buf.push(lines[i])
+ }
+ flush()
+ return parts
+}
+
+/** True when the text holds at least one closed fence. */
+export const hasFence = (text: string): boolean => splitFences(text).some((p) => p.kind === 'code')
+
+/** True when the END of `before` (the text up to the caret) is inside an open
+ * fence: markdown autoformat must leave code alone, or a template literal's
+ * backticks — `hello` — would vanish into a <code> tag. */
+export function insideOpenFence(before: string): boolean {
+ let open = false
+ for (const line of before.replace(/​/g, '').split('\n')) {
+ if (!open && isOpen(line)) open = true
+ else if (open && isClose(line)) open = false
+ }
+ return open
+}
+
+/** The fields an element keeps whatever its type. The first part keeps the
+ * box's identity; later parts get fresh ids and drop what must stay unique on
+ * a slide (the morph key) or names one specific box (its role). */
+const BASE_KEYS = ['morphId', 'rotation', 'opacity', 'shadow', 'blur', 'blend', 'backdropFilter',
+ 'fx', 'link', 'group', 'groupId', 'showOnHover', 'role'] as const
+const UNIQUE_KEYS = ['morphId', 'role'] as const
+
+export type PartFrame = { y: number; h: number; html?: string }
+
+/**
+ * The elements a fenced text box becomes, in order. `frames[i]` places part i
+ * (slide units) and, for a text part, may carry its html (formatting kept);
+ * without it the part's lines are used as plain text.
+ */
+export function fencedElements(src: TextElement, parts: FencePart[], frames: PartFrame[]): SlideElement[] {
+ const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
+ return parts.map((part, i) => {
+ const { y, h } = frames[i]
+ const id = i === 0 ? src.id : uid(part.kind === 'code' ? 'code' : 'text')
+ const base: Record<string, unknown> = {}
+ for (const k of BASE_KEYS) if ((src as unknown as Record<string, unknown>)[k] !== undefined) base[k] = structuredClone((src as unknown as Record<string, unknown>)[k])
+ if (i > 0) for (const k of UNIQUE_KEYS) delete base[k]
+ if (part.kind === 'code') {
+ const themeColor = src.themeRefs?.color
+ return defaultCode({
+ ...(base as Partial<CodeElement>),
+ id, x: src.x, y, w: src.w, h,
+ fontSize: src.fontSize, color: src.color, align: 'left', valign: 'top',
+ content: part.lines.join('\n'),
+ ...(part.lang ? { grammarName: part.lang } : {}),
+ ...(themeColor ? { themeRefs: { color: themeColor } } : {}),
+ })
+ }
+ const text: TextElement = structuredClone(src)
+ if (i > 0) for (const k of UNIQUE_KEYS) delete (text as unknown as Record<string, unknown>)[k]
+ text.id = id
+ text.y = y
+ text.h = h
+ text.html = frames[i].html ?? part.lines.map(esc).join('<br>')
+ return text
+ })
+}
+
+/** Heights when there is no rendered DOM to measure (a paste): one line box per
+ * line at the text's size, code at the Code element's own line height. */
+export function estimatedFrames(src: Pick<TextElement, 'y' | 'fontSize' | 'lineHeight'>, parts: FencePart[], gap = 16): PartFrame[] {
+ let y = src.y
+ return parts.map((p) => {
+ const lh = p.kind === 'code' ? 1.25 : (src.lineHeight || 1.2)
+ const h = Math.ceil(Math.max(1, p.lines.length) * src.fontSize * lh + (p.kind === 'code' ? src.fontSize : 0))
+ const frame = { y, h }
+ y += h + gap
+ return frame
+ })
+}
+
+/** The plain text of `root` up to (node, offset), with a newline at every <br>
+ * and block boundary — what insideOpenFence needs, which Range.toString()
+ * (no line breaks) cannot give. */
+export function textUpTo(root: HTMLElement, node: Node, offset: number): string {
+ const r = document.createRange()
+ r.setStart(root, 0)
+ r.setEnd(node, offset)
+ const box = document.createElement('div')
+ box.append(r.cloneContents())
+ return lineHtml(box).map((l) => l.replace(/<[^>]*>/g, '').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')).join('\n')
+}
+
+// --- 2. selection → <code> (DOM) --------------------------------------------
+
+const escapeHtml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
+const BLOCK = new Set(['DIV', 'P', 'LI', 'H1', 'H2'])
+
+/** A fragment's content as html, one string per rendered line (<br> and block
+ * boundaries split lines). Inline formatting inside a line is kept. */
+function lineHtml(root: Node): string[] {
+ const lines = ['']
+ const walk = (n: Node) => {
+ for (const c of Array.from(n.childNodes)) {
+ if (c.nodeName === 'BR') { lines.push(''); continue }
+ if (c instanceof Element && BLOCK.has(c.tagName)) {
+ if (lines[lines.length - 1] !== '') lines.push('')
+ walk(c)
+ lines.push('')
+ continue
+ }
+ if (c instanceof Element) {
+ if (c.querySelector('br,div,p,li,h1,h2')) walk(c) // a wrapper spanning lines: keep its lines, not the wrapper
+ else lines[lines.length - 1] += c.outerHTML
+ continue
+ }
+ if (c.nodeType === Node.TEXT_NODE) lines[lines.length - 1] += escapeHtml((c as Text).data)
+ }
+ }
+ walk(root)
+ while (lines.length > 1 && lines[lines.length - 1] === '') lines.pop()
+ return lines
+}
+
+/**
+ * Toggle inline code on the selection inside `root` (the editing text box).
+ * Every selected line is wrapped in its own <code>; when everything selected
+ * is already code, the touched code is unwrapped instead. Goes through
+ * insertHTML so the browser's own ⌘Z undoes it. Returns false — and does
+ * nothing — when there is no selection inside `root` (a plain ` keystroke).
+ */
+export function toggleCodeOnSelection(root: HTMLElement): boolean {
+ const sel = document.getSelection()
+ if (!sel || sel.isCollapsed || !sel.rangeCount) return false
+ const range = sel.getRangeAt(0)
+ if (!root.contains(range.commonAncestorContainer)) return false
+ const codeOf = (n: Node | null): HTMLElement | null => {
+ const c = (n instanceof Element ? n : n?.parentElement)?.closest('code') ?? null
+ return c && root.contains(c) ? c as HTMLElement : null
+ }
+ // the text the selection actually covers, ignoring caret spacers
+ const texts: Text[] = []
+ const walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_TEXT)
+ for (let n = walker.currentNode; n; n = walker.nextNode() as Node) {
+ if (n.nodeType === Node.TEXT_NODE && range.intersectsNode(n) && (n as Text).data.replace(/​/g, '').trim()) texts.push(n as Text)
+ }
+ if (!texts.length) return false
+ const allCode = texts.every((t) => codeOf(t))
+ // never insert INSIDE a code element: widen the range over any code element
+ // it starts or ends in, so the result replaces it rather than nesting
+ const startCode = codeOf(range.startContainer)
+ const endCode = codeOf(range.endContainer)
+ if (startCode) range.setStartBefore(startCode)
+ if (endCode) range.setEndAfter(endCode)
+ const box = document.createElement('div')
+ box.append(range.cloneContents())
+ box.querySelectorAll('code').forEach((c) => c.replaceWith(...Array.from(c.childNodes)))
+ const lines = lineHtml(box)
+ const html = allCode
+ ? lines.join('<br>')
+ : lines.map((l) => (l.replace(/​/g, '').trim() ? `<code>${l}</code>` : l)).join('<br>')
+ sel.removeAllRanges()
+ sel.addRange(range)
+ document.execCommand('insertHTML', false, html)
+ return true
+}
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index e97d4b54..d25c9b2b 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -29,6 +29,7 @@ import { adoptFileHandle, canWriteInPlace, currentFileName, fileBase, hasFileHan
import { noteSavedFromWeb } from './returngate'
import { addVersion, clearRecovery, clearVersions, docContentKey, getRecovery, listVersions, pruneOld, putRecovery, type Snapshot } from '../autosave'
import { insertElements, insertSlides, parseClip, serializeElements, serializeSlides } from './clipboard'
+import { estimatedFrames, fencedElements, splitFences } from './codefence'
import { openSpeakerWindow, speakerIdleBody } from '../screens'
import { boxCenter, connectorEndpoint, lineEndpoints, pathEndpoints, setLineEndpoints, setPathEndpoints } from './lineedit'
import { ICONS } from '../icons'
@@ -2475,10 +2476,20 @@ export class Editor {
this.toast(made.length === 1 ? t('Pasted 1 slide') : t('Pasted {n} slides', { n: made.length }))
return true
}
- // 3) plain text → a text element
+ // 3) plain text → a text element; a ``` fenced block in it → a Code
+ // element (with any text around it as text boxes above and below)
if (text && text.trim()) {
- const esc = text.trim().slice(0, 4000).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')
const { width } = this.store.doc.size
+ const parts = splitFences(text.slice(0, 20000))
+ if (parts.some((p) => p.kind === 'code')) {
+ const src = defaultText({ html: '', color: readableInk(this.store.slide.background), x: Math.round(width / 2 - 400), y: 120, w: 800 })
+ const made = fencedElements(src, parts, estimatedFrames(src, parts))
+ this.store.commit(() => this.store.slide.elements.push(...made))
+ this.store.select(made.map((e) => e.id))
+ this.toast(made.length === 1 ? t('Pasted 1 item') : t('Pasted {n} items', { n: made.length }))
+ return true
+ }
+ const esc = text.trim().slice(0, 4000).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>')
const el = defaultText({ html: esc, color: readableInk(this.store.slide.background), x: Math.round(width / 2 - 300), y: 260, w: 600 })
this.store.commit(() => this.store.slide.elements.push(el))
this.store.select([el.id])
diff --git a/slides/src/editor/markdown.ts b/slides/src/editor/markdown.ts
index 8d5c4133..bfa8a54a 100644
--- a/slides/src/editor/markdown.ts
+++ b/slides/src/editor/markdown.ts
@@ -17,6 +17,7 @@
// a list is asked for explicitly; this is where a bullet is typed.
import { isWebUrl } from '../model.ts'
+import { insideOpenFence, textUpTo } from './codefence.ts'
const INLINE: Array<{ re: RegExp; tag: string }> = [
{ re: /\*\*([^*\n]+)\*\*$/, tag: 'b' },
@@ -64,6 +65,11 @@ export function autoformatAtCaret(): boolean {
if (!sel?.isCollapsed || !(sel.anchorNode instanceof Text)) return false
const node = sel.anchorNode
const off = sel.anchorOffset // capture — DOM mutation below resets the live selection
+ // inside an open ``` fence the text is code: no marker, bullet or link
+ // conversion, or `template` literals would lose their backticks before the
+ // commit turns the fence into a Code element (codefence.ts)
+ const root = node.parentElement?.closest<HTMLElement>('.bento-text-inner')
+ if (root && insideOpenFence(textUpTo(root, node, off))) return false
const upto = node.data.slice(0, off)
// "- " or "* " at line start → bullet glyph (contentEditable renders the
@@ -165,8 +171,13 @@ export function markdownToHtml(text: string): string {
const PARK = ''
const parked: string[] = []
const park = (c: string) => PARK + (parked.push(c) - 1) + PARK
- // formulas first, whole and escaped, so no marker rule reaches inside one
- const withParked = text.split(FORMULA)
+ // fenced code before anything: kept literally, its ``` lines included, so no
+ // marker rule reaches inside it and the commit can turn it into a Code
+ // element (codefence.ts) instead of inline <code> fragments
+ const unfenced = text.replace(/^[ \t]*```[^\n]*\n[\s\S]*?\n[ \t]*```[ \t]*$/gm,
+ (block) => park(escapeHtml(block).replace(/\n/g, '<br>')))
+ // formulas next, whole and escaped, so no marker rule reaches inside one
+ const withParked = unfenced.split(FORMULA)
.map((part, i) => (i % 2 ? park(escapeHtml(part)) : part.replace(/\\([*_~`-])/g, (_, c: string) => park(c))))
.join('')
const out = withParked