Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
slides: pasting keeps its formatting; a long bullet wraps under its text (#503, #502) (#506)
nyblnet593fe8ac26c1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0c8d6ce9..eacdef5c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1388,6 +1388,12 @@ jobs:# routes the argument. Bare {{date}} stays viewer-locale (#381).run: node scripts/test-slides-fields.ts+ - name: Typed bullets become lists rig+ # editor/bullets.ts bulletsToLists: glyph lines become real <ul><li>+ # at commit (hanging indent), nesting by indent, untouched otherwise,+ # idempotent; both paste handlers read the clipboard through+ # editor/paste.ts (the html flavour, sanitized) -- #502, #503.+ run: node scripts/test-slides-bullets.ts- name: Inline-edit listeners rig# Every keydown/input/paste/blur listener a text-box or cell edit# attaches carries that edit's AbortSignal, and both commits abort it —diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8c3a75f2..c24409af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,18 @@ pre-1.0.## [Unreleased]+- **Pasting keeps the formatting.** Copy bold, italic or a list from one text+ box and paste it into another, or into a table cell, and it arrives as it+ was — the paste used to read only the plain-text copy and rebuild from+ that. What arrives goes through the same checker as every other piece of+ text: no styles, no scripts, no handlers, a link only if it is a web+ address. Plain text pasted from elsewhere still converts its markdown.+ Reported by Hermholtz (#503).+- **A long bullet wraps under its text.** Typing `- ` makes a bullet as you+ type; when you finish editing, those lines become a real list, so a bullet+ that runs onto a second line indents that line under the first word, not+ under the dot — and an indented `- ` nests. Lists you made from the+ formatting bar are untouched. Reported by Hermholtz (#502).- **A typed bullet keeps its space.** Typing `- ` made the bullet, but thenext letter landed right against it — the space after the glyph was aplain space at the end of the line, which the browser treats as nothing anddiff --git a/scripts/test-sanitize.ts b/scripts/test-sanitize.tsindex 9f23d192..5bf2a180 100644--- a/scripts/test-sanitize.ts+++ b/scripts/test-sanitize.ts@@ -298,9 +298,10 @@ const CHROME = [* render.ts, so this is the shipping code path and not a re-implementation of* it. Written without backticks or `${` so it can live in a template literal.*/-const probeSource = (renderPath: string, modelPath: string) => `+const probeSource = (renderPath: string, modelPath: string, pastePath: string) => `import { renderSlide, sanitizeHtml } from ${JSON.stringify(renderPath)}import { newDoc } from ${JSON.stringify(modelPath)}+import { clipboardToHtml } from ${JSON.stringify(pastePath)}const O = location.originconst pwned: number[] = []@@ -410,6 +411,72 @@ if (location.pathname === '/meta.html') {}check('3c — and clicking or hovering the lifted elements runs nothing', ![41, 42, 44, 45].some((n) => pwned.includes(n)))+ // --- 3d. the clipboard's html flavour, pasted into a live text box --------+ // Discussion #503: a paste now prefers text/html. It goes through the SAME+ // sanitizer (editor/paste.ts clipboardToHtml), so the hostile corpus above,+ // arriving as a ClipboardEvent into a contentEditable box, comes out with+ // no handler, no script, no style, and nothing runs when the pasted nodes+ // are clicked or hovered. Chrome's copy quirks are handled first: meta and+ // style elements go, and a <b style="font-weight:normal"> (Chrome's way+ // of saying NOT bold inside a bold run) is unwrapped rather than becoming+ // a real <b> once its attribute is stripped.+ const box3d = document.createElement('div')+ box3d.contentEditable = 'true'+ document.body.appendChild(box3d)+ box3d.focus()+ const hostile = '<meta charset="utf-8"><style>b{color:red}</style>' ++ '<b onclick="window.__pwn(51)" style="font-weight:700">bold</b> ' ++ '<b style="font-weight:normal">notbold</b> ' ++ '<i onmouseover="window.__pwn(52)">it</i>' ++ '<script>window.__pwn(53)</scr' + 'ipt>' ++ '<a href="javascript:window.__pwn(54)">j</a><a href="https://bento.page/" target="_top" onclick="window.__pwn(55)">ok</a>' ++ '<section><u onclick="window.__pwn(56)">deep</u></section>' ++ '<img src=x onerror="window.__pwn(57)">' ++ '<span style="position:fixed;inset:0;background:url(' + O + '/beacon.png)">s</span>' ++ // every shape a browser starts LOADING the moment a node joins a live+ // document, each pointing at this rig's own server, with the handlers+ // such a load would fire — the paste helper must let none of them run+ // or fetch, because nothing it touches may ever join the live document+ '<img src="' + O + '/paste-img.gif" onload="window.__pwn(61)">' ++ '<img srcset="' + O + '/paste-srcset.gif 1x" src="' + O + '/paste-src2.gif">' ++ '<picture><source srcset="' + O + '/paste-source.gif"><img src="' + O + '/paste-pic.gif"></picture>' ++ '<video poster="' + O + '/paste-poster.gif" src="' + O + '/paste-video.mp4" onerror="window.__pwn(62)"></video>' ++ '<audio src="' + O + '/paste-audio.mp3" onerror="window.__pwn(63)"></audio>' ++ '<input type="image" src="' + O + '/paste-input.gif" onload="window.__pwn(64)">' ++ '<noscript><img src="' + O + '/paste-noscript.gif"></noscript>' ++ '<iframe src="' + O + '/paste-frame.html"></iframe>' ++ '<object data="' + O + '/paste-object.svg"></object>' ++ '<ul><li>one</li><li>two</li></ul>'+ const dt3d = new DataTransfer()+ dt3d.setData('text/html', hostile)+ dt3d.setData('text/plain', 'plain fallback')+ const inserted = clipboardToHtml(dt3d)+ document.execCommand('insertHTML', false, inserted)+ const kept = box3d.innerHTML+ check('3d — the html flavour is used (bold, italic, underline and the list survive the paste)',+ /<b>bold<\\/b>/.test(kept) && /<i>it<\\/i>/.test(kept) && /<u>deep<\\/u>/.test(kept) && /<ul><li>one<\\/li><li>two<\\/li><\\/ul>/.test(kept))+ check('3d — Chrome\\'s "not bold" <b> is unwrapped, not promoted to bold', !/<b>notbold<\\/b>/.test(kept) && /notbold/.test(kept))+ check('3d — no handler, script, style, img or meta survives the paste',+ !box3d.querySelector('[onclick],[onmouseover],[onerror],[style],script,img,meta,style,link') && !kept.includes('__pwn') && !kept.includes('javascript:'))+ const a3d = Array.from(box3d.querySelectorAll('a'))+ check('3d — only the web link keeps its href, with no other attribute',+ a3d.length === 1 && a3d[0].getAttribute('href') === 'https://bento.page/' && a3d[0].attributes.length === 1)+ for (const el of Array.from(box3d.querySelectorAll('b, i, u, span, li'))) {+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }))+ el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }))+ }+ check('3d — clicking or hovering the pasted nodes runs nothing', ![51, 52, 53, 54, 55, 56, 57].some((n) => pwned.includes(n)))+ check('3d — no media element of any kind survives the paste', !box3d.querySelector('img,picture,source,video,audio,input,noscript,iframe,object'))+ // the load handlers fire asynchronously: asserted again after the settle+ // at the end (see "3d — the paste started no load" below), and the+ // server's hit list is checked on the node side+ const dtPlain = new DataTransfer()+ dtPlain.setData('text/plain', 'just text')+ check('3d — a clipboard with no html flavour hands over to the plain path', clipboardToHtml(dtPlain) === '')+ const dtEmpty = new DataTransfer()+ dtEmpty.setData('text/html', '<meta charset="utf-8"><style>x{}</style><script>window.__pwn(58)</scr' + 'ipt>')+ check('3d — html that is nothing but junk hands over to the plain path too', clipboardToHtml(dtEmpty) === '' && !pwned.includes(58))+// --- 4. network out of a self-contained file -------------------------------draw('<div>x</div><link rel="stylesheet" href="' + O + '/tracker.css">' +'<svg><style>@import url("' + O + '/imported.css");.q{fill:red}</sty' + 'le>' +@@ -609,7 +676,11 @@ if (location.pathname === '/meta.html') {check('the probe ran to the end (it threw: ' + String(err) + ')', false)}- setTimeout(() => {+ setTimeout(async () => {+ // a fence: one request of our own, answered in order after any load the+ // paste might have started, so the node side's hit list is complete+ try { await fetch(O + '/paste-fence', { cache: 'no-store' }) } catch {}+ check('3d — after the settle, no load or error handler from the paste ran', ![61, 62, 63, 64].some((n) => pwned.includes(n)))check('nothing executed: ' + (pwned.length ? pwned.join(',') : 'clean'), pwned.length === 0)const pre = document.createElement('pre')pre.id = 'bento-results'@@ -625,7 +696,7 @@ if (location.pathname === '/meta.html') {async function runBrowserSection(chrome: string) {const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bento-sanitize-'))const entry = path.join(tmp, 'probe.ts')- fs.writeFileSync(entry, probeSource(repoFile('slides/src/render.ts'), repoFile('slides/src/model.ts')))+ fs.writeFileSync(entry, probeSource(repoFile('slides/src/render.ts'), repoFile('slides/src/model.ts'), repoFile('slides/src/editor/paste.ts')))execFileSync(repoFile('slides/node_modules/.bin/esbuild'), [entry, '--bundle', '--format=esm', '--outfile=' + path.join(tmp, 'probe.js'),], { stdio: 'pipe' })@@ -711,6 +782,9 @@ async function runBrowserSection(chrome: string) {ok(!hits.includes('/desc-img.png') && !hits.includes('/title-img.png'),'8 — nothing inside <desc> or <title> fetches either')ok(!hits.includes('/xlink.svg'), '7 — nor an xlink:href <use> pointing out of the document')+ ok(hits.includes('/paste-fence'), '3d — the fence request arrived (the hit list is complete)')+ const pasteLoads = hits.filter((h) => h.startsWith('/paste-') && h !== '/paste-fence')+ ok(pasteLoads.length === 0, '3d — the paste helper started no load: img, srcset, picture/source, video poster/src, audio, input type=image, noscript img, iframe, object' + (pasteLoads.length ? ' — FETCHED ' + pasteLoads.join(' ') : ''))ok(hits.includes('/remote.png'), 'an <image href="http(s)://…"> still loads — that one is allowed on purpose')ok(hits.includes('/xlink-remote.png'), 'and so does the xlink:href spelling of it — the policy is not a ban on pictures')ok(hits.includes('/embed-view.png'), '9 — an embed view is held to the svg policy, no stricter: its <image> loads too')diff --git a/scripts/test-slides-bullets.ts b/scripts/test-slides-bullets.tsnew file mode 100644index 00000000..adfd5ef3--- /dev/null+++ b/scripts/test-slides-bullets.ts@@ -0,0 +1,75 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Typed bullets become real lists when an edit ends (discussion #502).+//+// node scripts/test-slides-bullets.ts+//+// WHAT THIS PROVES. editor/bullets.ts bulletsToLists is a pure function of+// the box's html: a run of glyph lines ("•" + NBSP, indented "◦" + NBSP) is+// one <ul>, an indented line nests under the item before it, lines between+// runs are untouched, lists the formatting bar made are untouched, a glyph in+// the middle of a line is untouched, a box with no typed bullet is returned+// byte-identical (no <div> folding, nothing), and converting the result again+// changes nothing. Hanging indent itself is CSS the renderer already has+// (styles.css list-style-position outside) and is measured in the PR.++import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'+import { bulletsToLists, hasTypedBullets } from '../slides/src/editor/bullets.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}+const NB = '\u00a0'+const B = `\u2022${NB}`, S = `\u25e6${NB}`++console.log('runs of glyph lines\n')+ok(bulletsToLists(`${B}one<br>${B}two`) === '<ul><li>one</li><li>two</li></ul>', 'two top-level bullets → one list')+ok(bulletsToLists(`${B}one<br>${NB}${NB}${S}sub<br>${B}two`) === '<ul><li>one<ul><li>sub</li></ul></li><li>two</li></ul>', 'an indented \u25e6 nests under the item before it')+ok(bulletsToLists(`${B}one<br> ${S}sub`) === '<ul><li>one<ul><li>sub</li></ul></li></ul>', 'the indent may be entities (what innerHTML serialises)')+ok(bulletsToLists(`\u2022 one`) === '<ul><li>one</li></ul>', 'the glyph\'s NBSP may be an entity too')+ok(bulletsToLists('\u2022 one<br> \u25e6 sub') === '<ul><li>one<ul><li>sub</li></ul></li></ul>', 'or the plain space Chrome normalises it to once text follows (what commit sees)')+ok(bulletsToLists(`${NB}${NB}${S}orphan`) === '<ul><li><ul><li>orphan</li></ul></li></ul>', 'a run opening with a sub-bullet gets an empty parent item')++console.log('\nwhat stays as it was\n')+ok(bulletsToLists('Title<br>plain<br><div>x</div>') === 'Title<br>plain<br><div>x</div>', 'no typed bullet → byte-identical, divs untouched')+ok(bulletsToLists(`Title<br>${B}one<br>${B}two<br>after`) === 'Title<ul><li>one</li><li>two</li></ul>after', 'text before and after a run survives; a list is a block, no <br> around it')+ok(bulletsToLists(`a ${B} in the middle`) === `a ${B} in the middle`, 'a glyph mid-line is not a bullet')+const barMade = `<ul><li>from the bar</li></ul>`+ok(bulletsToLists(barMade) === barMade, 'a list the formatting bar made is untouched')+ok(bulletsToLists(`<ul><li>${B}glyph inside a li</li></ul>`) === `<ul><li>${B}glyph inside a li</li></ul>`, 'a glyph inside an existing li is left alone')+ok(bulletsToLists(`<ul><li>x<br>${B}typed inside a li</li></ul>`) === `<ul><li>x<br>${B}typed inside a li</li></ul>`, 'a glyph line that carries list markup (typed inside an existing item) is left alone')+ok(bulletsToLists(`<b>${B}bold bullet</b>`) === `<b>${B}bold bullet</b>`, 'a glyph after an opening tag is not a line start')++console.log('\ncontentEditable blocks\n')+ok(bulletsToLists(`<div>${B}one</div><div>${B}two</div>`) === '<ul><li>one</li><li>two</li></ul>', 'Enter-made <div> blocks are lines')+ok(bulletsToLists(`intro<div>${B}one</div>`) === 'intro<ul><li>one</li></ul>', 'a div after inline text is a line too')++console.log('\nidempotence\n')+for (const src of [`${B}one<br>${B}two`, `Title<br>${B}one<br>${NB}${NB}${S}sub<br>after`, 'plain<br>text', barMade]) {+ const once = bulletsToLists(src)+ ok(bulletsToLists(once) === once, `converting again changes nothing: ${JSON.stringify(src).slice(0, 40)}`)+ ok(!hasTypedBullets(once), 'and the result reports no typed bullets left')+}++console.log('\nthe commit calls it, cells do not\n')+const root = join(dirname(fileURLToPath(import.meta.url)), '..')+const canvas = readFileSync(join(root, 'slides/src/editor/canvas.ts'), 'utf8')+const textCommit = canvas.slice(canvas.indexOf(' commitTextEdit() {'), canvas.indexOf(' private editCellAt('))+const cellCommit = canvas.slice(canvas.indexOf(' private commitCellEdit('), canvas.indexOf(' private moveCell('))+ok(/bulletsToLists\(sanitizeHtml\(/.test(textCommit), 'commitTextEdit converts the sanitized html (sanitize first, then lists)')+ok(!/bulletsToLists/.test(cellCommit), 'commitCellEdit does not (no list styling in a cell)')+ok(/clipboardToHtml\(ev\.clipboardData\)/.test(canvas) && (canvas.match(/clipboardToHtml\(ev\.clipboardData\)/g) ?? []).length === 2, 'both paste handlers read the clipboard through editor/paste.ts')+ok(!/getData\('text\/html'\)/.test(canvas), 'nothing in canvas.ts reads text/html directly — only the sanitized helper does')+const paste = readFileSync(join(root, 'slides/src/editor/paste.ts'), 'utf8').replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '')+ok(/new DOMParser\(\)\.parseFromString\(/.test(paste), 'paste.ts parses the clipboard html in a document of its own (DOMParser)')+ok(!/document\.createElement|document\.body|appendChild|cloneNode|innerHTML\s*=/.test(paste), 'and never creates, appends or clones into the live document — a node adopted there starts loading what it names before any sanitizer runs')++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/slides/src/editor/bullets.ts b/slides/src/editor/bullets.tsnew file mode 100644index 00000000..1aea3150--- /dev/null+++ b/slides/src/editor/bullets.ts@@ -0,0 +1,97 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+/**+ * Typed bullets become real lists when the edit ends (discussion #502).+ *+ * Typing "- " puts a bullet GLYPH in the text ("•" + NBSP; "◦" for an+ * indented sub-bullet) — markdown.ts explains why it is a glyph and not a+ * list item while you type: converting the line under the caret moves the+ * caret and captures Enter. But a glyph is inline text, so a long bullet+ * wraps back to the box's left edge, under the bullet. A real `<li>` hangs+ * its wrapped lines under the text (styles.css: list-style-position outside,+ * padding-inline-start), which is what a reader expects.+ *+ * So the conversion happens at COMMIT, on the sanitized html of the whole+ * box, and it is a pure string function: a run of consecutive lines that+ * begin with the glyph becomes one `<ul>`, an indented "◦" line nests one+ * level under the item before it. Lines are what `<br>` separates (and what+ * contentEditable's `<div>` blocks separate — those are folded to `<br>`+ * first, ONLY when there is a glyph line to convert, so a box without typed+ * bullets is returned byte-identical). Everything else — text between runs,+ * lists the formatting bar already made, a glyph in the middle of a line —+ * is left exactly as it was. Converting the result again changes nothing.+ *+ * Table cells are NOT converted: a cell has no list styling and its bullets+ * are usually single lines.+ */++// The glyph's NBSP survives typing as an NBSP, an entity, or — once+// a character follows it — a plain space Chrome normalised it to; all three+// are the same bullet. The indent before a sub-bullet is the same mix.+const NB = '(?:\u00a0| | )'+const TOP = new RegExp(`^\u2022${NB}`)+const SUB = new RegExp(`^${NB}{2,}\u25e6${NB}`)++// A line that carries list markup of its own is already inside a list the+// formatting bar made (a glyph typed inside an <li>); it is not converted.+const LIST_TAG = /<\/?(?:li|ul|ol)\b/i+const isBullet = (l: string) => (TOP.test(l) || SUB.test(l)) && !LIST_TAG.test(l)++/** Does this html contain a line that starts with a typed bullet? */+export function hasTypedBullets(html: string): boolean {+ return splitLines(html).some(isBullet)+}++/** `<br>` and contentEditable's `<div>…</div>` blocks both end a line. */+function splitLines(html: string): string[] {+ // a closing div followed by another div, or by the end, breaks nothing by+ // itself (the next opener or the end does); one followed by inline content+ // starts a new line; an opener starts a new line unless it opens the box+ const folded = html+ .replace(/<\/div>(?=\s*(?:<div>|$))/gi, '')+ .replace(/<\/div>/gi, '<br>')+ .replace(/<div>/gi, (_m, off: number) => (off === 0 ? '' : '<br>'))+ return folded.split(/<br\s*\/?>/i)+}++/** Glyph lines → real lists; anything else untouched. Idempotent. */+export function bulletsToLists(html: string): string {+ if (!hasTypedBullets(html)) return html+ const lines = splitLines(html)+ const out: string[] = []+ let i = 0+ while (i < lines.length) {+ const line = lines[i]+ if (!isBullet(line)) { out.push(line); i++; continue }+ // a run of bullet lines → one list; a sub-bullet nests under the item+ // before it (a run that opens with a sub-bullet gets an empty parent item)+ let list = '<ul>'+ let openSub = false+ let openItem = false+ while (i < lines.length && isBullet(lines[i])) {+ const l = lines[i]+ if (SUB.test(l)) {+ if (!openItem) { list += '<li>'; openItem = true }+ if (!openSub) { list += '<ul>'; openSub = true }+ list += `<li>${l.replace(SUB, '')}</li>`+ } else {+ if (openSub) { list += '</ul>'; openSub = false }+ if (openItem) { list += '</li>'; openItem = false }+ list += `<li>${l.replace(TOP, '')}`+ openItem = true+ }+ i+++ }+ if (openSub) list += '</ul>'+ if (openItem) list += '</li>'+ list += '</ul>'+ out.push(list)+ }+ // a list is a block: no <br> needed around it+ return out.reduce((acc, piece, k) => {+ if (k === 0) return piece+ const prevBlock = /<\/ul>$/.test(acc)+ const thisBlock = /^<ul>/.test(piece)+ return acc + (prevBlock || thisBlock ? '' : '<br>') + piece+ }, '')+}diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.tsindex 8235ed8c..0562f52f 100644--- a/slides/src/editor/canvas.ts+++ b/slides/src/editor/canvas.ts@@ -11,6 +11,8 @@ import { t } from '../i18n'import { defaultShape, internAsset, readableInk, uid, type ShapeElement, type SlideElement, type TableElement } from '../model'import { renderSlide, sanitizeHtml } from '../render'import { autoformatAtCaret, clearAutoformat, markdownToHtml, undoAutoformat } from './markdown'+import { bulletsToLists } from './bullets'+import { clipboardToHtml } from './paste'import { execFormat, hideFormatBar, syncFormatBar } from './richtext'import { PathEditor } from './patheditor'import { LineEditor, isLineLike, setLineEndpoints, setPathAnchors } from './lineedit'@@ -1461,6 +1463,10 @@ export class SlideCanvas {if (!autoformatAtCaret()) clearAutoformat()}, { signal })inner.addEventListener('paste', (ev) => {+ // formatting travels: the clipboard's html flavour, through the one+ // sanitizer (editor/paste.ts); plain text keeps its markdown conversion+ const rich = clipboardToHtml(ev.clipboardData)+ if (rich) { ev.preventDefault(); document.execCommand('insertHTML', false, rich); return }const text = ev.clipboardData?.getData('text/plain')if (!text) returnev.preventDefault()@@ -1494,7 +1500,10 @@ export class SlideCanvas {// For code, we care about the raw innerTextconst text = inner.innerText// drop the zero-width caret spacers autoformat leaves behind- const html = sanitizeHtml(inner.innerHTML.replace(/\u200B/g, '').replace(/\\([*_~`-])/g, '$1'))+ // typed "- " bullets are glyphs while you type (markdown.ts says why);+ // once the edit ends they become real list items, so a long bullet wraps+ // under its text rather than under the glyph (#502, editor/bullets.ts)+ const html = bulletsToLists(sanitizeHtml(inner.innerHTML.replace(/\u200B/g, '').replace(/\\([*_~`-])/g, '$1')))const grownH = Math.max(parseFloat(node.style.height) || 0, inner.scrollHeight)const el = this.store.doc.slides.find((slide) => slide.id === slideId)@@ -1578,6 +1587,10 @@ export class SlideCanvas {}, { signal })inner.addEventListener('input', () => { if (!autoformatAtCaret()) clearAutoformat() }, { signal })inner.addEventListener('paste', (ev) => {+ // formatting travels: the clipboard's html flavour, through the one+ // sanitizer (editor/paste.ts); plain text keeps its markdown conversion+ const rich = clipboardToHtml(ev.clipboardData)+ if (rich) { ev.preventDefault(); document.execCommand('insertHTML', false, rich); return }const text = ev.clipboardData?.getData('text/plain')if (!text) returnev.preventDefault()diff --git a/slides/src/editor/paste.ts b/slides/src/editor/paste.tsnew file mode 100644index 00000000..f481e1a1--- /dev/null+++ b/slides/src/editor/paste.ts@@ -0,0 +1,59 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+/**+ * What a paste into a text box or table cell inserts (discussion #503).+ *+ * The clipboard carries the selection twice: as `text/html` — the browser's+ * own serialisation of what was copied, formatting and all — and as+ * `text/plain`. Until now only the plain flavour was read, so copying bold,+ * italic or bullets from one box and pasting into another lost everything.+ * The html flavour is preferred now, through the ONE sanitizer (render.ts+ * sanitizeHtml: an allowlist of tags, every attribute dropped, an anchor's+ * href kept only when it is a web URL, nested markup walked before it is+ * lifted). Plain text stays the fallback and keeps its markdown conversion.+ *+ * Browser clipboards are not tidy. Chrome writes `<meta charset>` first, wraps+ * the selection in `<span style="…">` soup with the computed font, and marks+ * a NOT-bold run inside a bold context as `<b style="font-weight:normal">` —+ * a `<b>` that means "not bold". The sanitizer drops attributes, which would+ * turn that into a real bold. So the quirks are handled before it runs: meta+ * and style elements removed, a `<b>`/`<strong>` whose inline style says+ * `font-weight: normal` (or ≤ 400) unwrapped. Spans survive the sanitizer as+ * bare `<span>`s, which render as nothing.+ *+ * Everything above happens in a document of its own, made by DOMParser and+ * never attached to the page: untrusted nodes are parsed, tidied and+ * serialised there, and only the resulting STRING reaches sanitizeHtml. A+ * node adopted into the live document starts loading what it names (img,+ * source, poster, input type=image) and fires its load and error handlers+ * before any sanitizer has run — measured — so nothing here is ever created+ * in or appended to `document`.+ */++import { sanitizeHtml } from '../render'++/** The html to insert for this clipboard, or '' when the plain-text path+ * should run instead (no html flavour, or nothing left after cleaning). */+export function clipboardToHtml(dt: DataTransfer | null | undefined): string {+ const html = dt?.getData('text/html')+ if (!html || typeof DOMParser === 'undefined') return ''+ // an inert document: no loads, no scripts, no handlers ever fire in it+ const inert = new DOMParser().parseFromString(html, 'text/html')+ const body = inert.body+ for (const junk of Array.from(body.querySelectorAll('meta, style, script, title, link, head'))) junk.remove()+ for (const b of Array.from(body.querySelectorAll('b, strong'))) {+ const w = (b as HTMLElement).style.fontWeight.trim().toLowerCase()+ const light = w === 'normal' || w === 'lighter' || (/^\d+$/.test(w) && Number(w) <= 400)+ if (light) {+ const parent = b.parentNode+ if (!parent) continue+ while (b.firstChild) parent.insertBefore(b.firstChild, b)+ b.remove()+ }+ }+ const clean = sanitizeHtml(body.innerHTML)+ // nothing but whitespace/empty tags → let the plain path decide. Checked+ // in an inert document too: the cleaned string is parsed back there.+ const check = new DOMParser().parseFromString(clean, 'text/html').body+ return check.textContent?.trim() || check.querySelector('br, li') ? clean : ''+}