Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides: format text by selecting it, with real lists and headings (#292)

iamgeo923f2c73473662
diff --git a/docs/format.md b/docs/format.md
index df28acd8..85255999 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -134,7 +134,9 @@ The element `type` discriminant is one of: `text`, `shape`, `image`, `svg`,
### `text`
-`type: "text"` — `html` (sanitized inline subset: `b/i/u/s/code/br/span`),
+`type: "text"` — `html` (sanitized subset: inline `b/i/u/s/code/br/span` plus
+blocks `p/div/h1/h2/ul/ol/li`; every tag is attribute-free, and a shell that
+predates a tag unwraps it and keeps the words),
`fontSize`, `fontFamily`, `fontWeight`, `color`, `align` (`left|center|right`),
`valign` (`top|middle|bottom`), `lineHeight`. Optional `letterSpacing` (px) and
`placeholder` (a dimmed prompt shown while `html` is empty; hidden in
diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.ts
index fb700cf1..b6fd4e65 100644
--- a/slides/src/editor/canvas.ts
+++ b/slides/src/editor/canvas.ts
@@ -11,6 +11,7 @@ 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 { execFormat, hideFormatBar, syncFormatBar } from './richtext'
import { PathEditor } from './patheditor'
import { LineEditor, isLineLike, setLineEndpoints, setPathAnchors } from './lineedit'
import { BezierEditor, isCurve } from './beziereditor'
@@ -53,6 +54,8 @@ export class SlideCanvas {
private editingShowedRaw = 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 */
+ private stopSelectionWatch: (() => void) | null = null
/** a repaint arrived (e.g. a remote collab op) while an inline edit was in
* progress and was deferred so it wouldn't tear the edited node out from
* under the caret; flushed when the edit commits. */
@@ -1277,6 +1280,44 @@ export class SlideCanvas {
// --- text editing -----------------------------------------------------------
+ /**
+ * Follow the selection inside an open editable and raise the formatting bar
+ * over it. `selectionchange` fires on the DOCUMENT only — there is no
+ * per-element event — so the listener lives for the length of the edit and
+ * comes off when it commits.
+ *
+ * Deferred a frame because the selection reported DURING a command is the
+ * one from before the DOM moved; reading it afterwards is what makes the
+ * pressed states and the bar's position agree with what is on screen.
+ */
+ private watchSelection(inner: HTMLElement) {
+ this.stopSelectionWatch?.()
+ let queued = false
+ const onChange = () => {
+ if (queued) return
+ queued = true
+ requestAnimationFrame(() => {
+ queued = false
+ // the edit may have committed between the event and this frame
+ if (!this.editing || !inner.isConnected || inner.contentEditable !== 'true') {
+ hideFormatBar()
+ return
+ }
+ syncFormatBar(inner)
+ })
+ }
+ document.addEventListener('selectionchange', onChange)
+ // the canvas can move under a live selection (a zoom, a pan, a remote edit)
+ this.scroller.addEventListener('scroll', onChange, { passive: true })
+ this.stopSelectionWatch = () => {
+ document.removeEventListener('selectionchange', onChange)
+ this.scroller.removeEventListener('scroll', onChange)
+ this.stopSelectionWatch = null
+ hideFormatBar()
+ }
+ onChange()
+ }
+
/** Open the inline editor for an element by id — the entry point for callers
* that have an id rather than a node (the context menu). A table opens its
* first cell, since a menu has no point to aim at. */
@@ -1323,6 +1364,7 @@ export class SlideCanvas {
inner.focus()
document.getSelection()?.selectAllChildren(inner)
this.syncTargets()
+ this.watchSelection(inner)
this.onTextEditChange?.(node.dataset.elId)
inner.addEventListener('keydown', (ev) => {
@@ -1344,7 +1386,7 @@ export class SlideCanvas {
const cmd = { b: 'bold', i: 'italic', u: 'underline' }[ev.key.toLowerCase()]
if (cmd) {
ev.preventDefault()
- document.execCommand(cmd)
+ execFormat(cmd)
}
}
})
@@ -1367,6 +1409,10 @@ export class SlideCanvas {
onTextEditChange: ((elId: string | undefined) => void) | null = null
commitTextEdit() {
+ // Ahead of every early return below, and ahead of the delegation to
+ // commitCellEdit: a watcher left running would keep the formatting bar up
+ // over a box that is no longer being edited.
+ this.stopSelectionWatch?.()
const node = this.editing
if (!node) return
if (this.editingCell) { this.commitCellEdit(node); return }
@@ -1447,6 +1493,7 @@ export class SlideCanvas {
inner.focus()
document.getSelection()?.selectAllChildren(inner)
this.syncTargets()
+ this.watchSelection(inner)
this.onTextEditChange?.(id)
inner.addEventListener('keydown', (ev) => {
@@ -1457,7 +1504,7 @@ export class SlideCanvas {
if (ev.metaKey || ev.ctrlKey) {
if (ev.key.toLowerCase() === 'z' && !ev.shiftKey) { if (undoAutoformat()) ev.preventDefault(); return }
const cmd = { b: 'bold', i: 'italic', u: 'underline' }[ev.key.toLowerCase()]
- if (cmd) { ev.preventDefault(); document.execCommand(cmd) }
+ if (cmd) { ev.preventDefault(); execFormat(cmd) }
}
})
inner.addEventListener('input', () => { if (!autoformatAtCaret()) clearAutoformat() })
diff --git a/slides/src/editor/markdown.ts b/slides/src/editor/markdown.ts
index b39ce849..ad05d2ca 100644
--- a/slides/src/editor/markdown.ts
+++ b/slides/src/editor/markdown.ts
@@ -8,8 +8,12 @@
// - markdownToHtml: converts pasted plain text (inline patterns + bullets +
// line breaks) into the sanitized inline-HTML subset text elements store.
//
-// Deliberately inline-only: slides have no headings/lists DOM — bullets are a
-// "• " glyph, matching how decks lay out list lines as separate text rows.
+// This module stays INLINE-ONLY, and now by choice rather than by necessity.
+// A text box can hold real ul/ol/li and h1/h2 since the formatting bar landed
+// (editor/richtext.ts), but typing "- " still yields a "• " glyph: autoformat
+// fires mid-keystroke, and silently converting the line you are typing into a
+// list item moves the caret and captures Enter from then on. The bar is where
+// a list is asked for explicitly; this is where a bullet is typed.
const INLINE: Array<{ re: RegExp; tag: string }> = [
{ re: /\*\*([^*\n]+)\*\*$/, tag: 'b' },
diff --git a/slides/src/editor/richtext.ts b/slides/src/editor/richtext.ts
new file mode 100644
index 00000000..852820e4
--- /dev/null
+++ b/slides/src/editor/richtext.ts
@@ -0,0 +1,299 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The formatting bar that follows a text selection.
+//
+// It exists because the formatting a box already SUPPORTS had no handle on it:
+// bold/italic/underline were reachable only by ⌘B/⌘I/⌘U or by typing markdown,
+// which is knowledge the interface never offers, and lists and headings could
+// not be made at all. Selecting words and being shown what can be done to them
+// is how every editor answers that.
+//
+// Commands go through `document.execCommand`. It is deprecated and it is also
+// the only API that edits a contenteditable's DOM *and* the browser's own undo
+// stack together — the editor already relies on that for ⌘B/⌘I/⌘U, and a
+// hand-rolled Range implementation that did not feed native undo would be a
+// worse answer, not a more modern one.
+
+import { t } from '../i18n'
+
+/**
+ * Make execCommand emit TAGS (`<b>`, `<i>`, `<u>`) instead of styled spans.
+ *
+ * This is not a preference, it is a correctness requirement: the sanitizer
+ * strips every attribute, so a `<span style="font-weight:bold">` reaches the
+ * document as a bare `<span>` and the formatting is silently gone. Browsers
+ * pick the CSS form on their own — Chrome did it here the moment the box's own
+ * font-weight made "bold" a toggle-OFF — so the mode has to be set explicitly
+ * before every command rather than assumed.
+ *
+ * Both the bar and the ⌘B/⌘I/⌘U handler go through here, so neither can drift.
+ */
+export function execFormat(name: string, value?: string) {
+ try {
+ document.execCommand('styleWithCSS', false, 'false')
+ } catch {
+ /* older engines: the default is already the tag form */
+ }
+ document.execCommand(name, false, value)
+}
+
+/** Which commands the bar exposes, in the order they are shown. */
+type Cmd =
+ | { kind: 'exec'; name: string; label: string; title: string; glyph: string }
+ | { kind: 'block'; tag: 'H1' | 'H2' | 'P'; label: string; title: string; glyph: string }
+ | { kind: 'code'; label: string; title: string; glyph: string }
+ | { kind: 'clear'; label: string; title: string; glyph: string }
+ | 'sep'
+
+let bar: HTMLElement | null = null
+let host: HTMLElement | null = null
+let detach: (() => void) | null = null
+
+/** Is the bar currently up? */
+export function formatBarOpen() {
+ return !!bar
+}
+
+export function hideFormatBar() {
+ detach?.()
+ detach = null
+ bar?.remove()
+ bar = null
+ host = null
+}
+
+/**
+ * Show (or re-place) the bar for a selection inside `editable`. Called on every
+ * selection change while a text box is open; hides itself when the selection
+ * collapses to a caret, because a bar over a caret has nothing to act on and
+ * would just cover the words being typed.
+ */
+export function syncFormatBar(editable: HTMLElement) {
+ const sel = document.getSelection()
+ if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return hideFormatBar()
+ const range = sel.getRangeAt(0)
+ if (!editable.contains(range.commonAncestorContainer)) return hideFormatBar()
+ const rect = range.getBoundingClientRect()
+ if (!rect.width && !rect.height) return hideFormatBar()
+
+ if (!bar || host !== editable) {
+ hideFormatBar()
+ bar = build(editable)
+ host = editable
+ document.body.appendChild(bar)
+ // A press inside the bar must not move the caret out of the text, or the
+ // command would run against a collapsed selection somewhere else.
+ const keep = (ev: Event) => ev.preventDefault()
+ bar.addEventListener('pointerdown', keep)
+ bar.addEventListener('mousedown', keep)
+ detach = () => {
+ bar?.removeEventListener('pointerdown', keep)
+ bar?.removeEventListener('mousedown', keep)
+ }
+ }
+ place(bar, rect)
+ refresh(bar)
+}
+
+// A keyboard symbol is not prose, so the shortcut is appended rather than
+// baked into a second catalog key for every button that has one.
+const withKey = (label: string, key?: string) => (key ? `${label} (${key})` : label)
+
+const COMMANDS = (): Cmd[] => {
+ // `Title` on its own is already the DECK's title in the About dialog, and one
+ // English word with two meanings is one key too few (docs/DECISIONS.md — "One
+ // English word, two meanings = two keys"), so the text style is qualified.
+ const item = (
+ kind: 'exec' | 'block' | 'code' | 'clear',
+ glyph: string, label: string, extra: Record<string, string> = {}, key?: string,
+ ) => ({ kind, glyph, label, title: withKey(label, key), ...extra }) as Cmd
+ return [
+ item('exec', 'B', t('Bold'), { name: 'bold' }, '⌘B'),
+ item('exec', 'I', t('Italic'), { name: 'italic' }, '⌘I'),
+ item('exec', 'U', t('Underline'), { name: 'underline' }, '⌘U'),
+ item('exec', 'S', t('Strikethrough'), { name: 'strikeThrough' }),
+ item('code', '&lt;/&gt;', t('Code')),
+ 'sep',
+ item('block', 'H1', t('Title text'), { tag: 'H1' }),
+ item('block', 'H2', t('Heading'), { tag: 'H2' }),
+ item('block', '¶', t('Body text'), { tag: 'P' }),
+ 'sep',
+ item('exec', '•—', t('Bulleted list'), { name: 'insertUnorderedList' }),
+ item('exec', '1.', t('Numbered list'), { name: 'insertOrderedList' }),
+ 'sep',
+ item('clear', '⌫', t('Clear formatting')),
+ ]
+}
+
+function build(editable: HTMLElement): HTMLElement {
+ const el = document.createElement('div')
+ el.className = 'ed-fmtbar'
+ el.setAttribute('role', 'toolbar')
+ for (const cmd of COMMANDS()) {
+ if (cmd === 'sep') {
+ const s = document.createElement('span')
+ s.className = 'ed-fmtbar-sep'
+ el.appendChild(s)
+ continue
+ }
+ const b = document.createElement('button')
+ b.className = 'ed-fmtbar-btn'
+ b.innerHTML = cmd.glyph
+ b.title = cmd.title
+ b.setAttribute('aria-label', cmd.label)
+ if (cmd.kind === 'exec') b.dataset.cmd = cmd.name
+ if (cmd.kind === 'block') b.dataset.block = cmd.tag
+ if (cmd.kind === 'code') b.dataset.code = '1'
+ b.addEventListener('click', (ev) => {
+ ev.preventDefault()
+ editable.focus()
+ run(cmd, editable)
+ // The DOM moved under the selection, so both the bar's position and its
+ // pressed states are stale until the next frame.
+ requestAnimationFrame(() => syncFormatBar(editable))
+ })
+ el.appendChild(b)
+ }
+ return el
+}
+
+function run(cmd: Exclude<Cmd, 'sep'>, editable: HTMLElement) {
+ if (cmd.kind === 'exec') {
+ execFormat(cmd.name)
+ return
+ }
+ if (cmd.kind === 'clear') {
+ execFormat('removeFormat')
+ // removeFormat is inline-only by definition; a list or heading is a block
+ // and survives it, which reads as "the button did nothing".
+ execFormat('formatBlock', 'div')
+ return
+ }
+ if (cmd.kind === 'block') {
+ // Toggle: pressing Title on something already a Title returns it to body,
+ // so the same button both applies and removes.
+ const current = blockTag(editable)
+ execFormat('formatBlock', current === cmd.tag ? 'div' : cmd.tag.toLowerCase())
+ return
+ }
+ // `code` has no execCommand. Wrapping the range is enough for the common
+ // case (a run inside one text node); anything more tangled falls back to
+ // re-inserting the selection's own markup wrapped, which execCommand records
+ // on the undo stack for us.
+ if (inCode()) {
+ unwrapCode(editable)
+ return
+ }
+ const sel = document.getSelection()
+ if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return
+ const range = sel.getRangeAt(0)
+ const code = document.createElement('code')
+ try {
+ range.surroundContents(code)
+ sel.removeAllRanges()
+ const r = document.createRange()
+ r.selectNodeContents(code)
+ sel.addRange(r)
+ } catch {
+ const frag = range.cloneContents()
+ const box = document.createElement('div')
+ box.appendChild(frag)
+ execFormat('insertHTML', `<code>${box.innerHTML}</code>`)
+ }
+}
+
+/** The nearest block tag the selection sits in, uppercased. */
+function blockTag(editable: HTMLElement): string {
+ const node = document.getSelection()?.anchorNode
+ const el = node instanceof Element ? node : node?.parentElement
+ const block = el?.closest('h1,h2,p,div,li')
+ if (!block || !editable.contains(block) || block === editable) return 'DIV'
+ return block.tagName
+}
+
+function inCode(): boolean {
+ const node = document.getSelection()?.anchorNode
+ const el = node instanceof Element ? node : node?.parentElement
+ return !!el?.closest('code')
+}
+
+function unwrapCode(editable: HTMLElement) {
+ const node = document.getSelection()?.anchorNode
+ const el = node instanceof Element ? node : node?.parentElement
+ const code = el?.closest('code')
+ if (!code || !editable.contains(code)) return
+ const parent = code.parentNode
+ if (!parent) return
+ const first = code.firstChild
+ while (code.firstChild) parent.insertBefore(code.firstChild, code)
+ code.remove()
+ if (first) {
+ const sel = document.getSelection()
+ const r = document.createRange()
+ r.selectNodeContents(parent)
+ sel?.removeAllRanges()
+ sel?.addRange(r)
+ }
+}
+
+/**
+ * Bold cannot be turned OFF inside a box whose own `fontWeight` is already
+ * bold. Every tag in the allowlist is attribute-free, so there is no markup for
+ * "lighter than the box" — the browser can only express it as
+ * `<span style="font-weight:normal">`, and the sanitizer strips the attribute
+ * and leaves an empty span. Removing a `<b>` the selection sits inside IS
+ * representable, so that case stays enabled.
+ *
+ * Disabling it says so, instead of offering a button that quietly does nothing.
+ */
+function boldWouldVanish(editable: HTMLElement): boolean {
+ const base = parseInt(getComputedStyle(editable).fontWeight, 10) || 400
+ if (base < 600) return false
+ const node = document.getSelection()?.anchorNode
+ const el = node instanceof Element ? node : node?.parentElement
+ return !el?.closest('b,strong')
+}
+
+/** Light up whatever the caret is currently inside. */
+function refresh(el: HTMLElement) {
+ const editable = host ?? el
+ for (const b of Array.from(el.querySelectorAll<HTMLElement>('.ed-fmtbar-btn'))) {
+ let on = false
+ if (b.dataset.cmd) {
+ try {
+ on = document.queryCommandState(b.dataset.cmd)
+ } catch {
+ on = false
+ }
+ } else if (b.dataset.block) {
+ on = blockTag(editable) === b.dataset.block
+ } else if (b.dataset.code) {
+ on = inCode()
+ }
+ b.classList.toggle('is-on', on)
+ if (b.dataset.cmd === 'bold') {
+ const dead = boldWouldVanish(editable)
+ b.toggleAttribute('disabled', dead)
+ b.title = dead ? t('This text box is already bold') : withKey(t('Bold'), '⌘B')
+ }
+ }
+}
+
+/**
+ * Sit above the selection, or below it when there is no room — and never off
+ * the side. Measured from the live rect each time, because the selection moves
+ * as the user drags through the text.
+ */
+function place(el: HTMLElement, rect: DOMRect) {
+ const pad = 8
+ const gap = 10
+ // width is only known once it is in the DOM and laid out
+ const w = el.offsetWidth || 300
+ const h = el.offsetHeight || 38
+ let left = rect.left + rect.width / 2 - w / 2
+ left = Math.max(pad, Math.min(left, window.innerWidth - w - pad))
+ let top = rect.top - h - gap
+ if (top < pad) top = Math.min(window.innerHeight - h - pad, rect.bottom + gap)
+ el.style.left = `${Math.round(left)}px`
+ el.style.top = `${Math.round(Math.max(pad, top))}px`
+}
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index aef66757..b7050938 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -4,6 +4,17 @@
import type { Catalog } from '../i18n'
export const de: Catalog = {
+ "This text box is already bold": "Dieses Textfeld ist bereits fett",
+ "Italic": "Kursiv",
+ "Underline": "Unterstrichen",
+ "Strikethrough": "Durchgestrichen",
+ "Code": "Code",
+ "Title text": "Titeltext",
+ "Heading": "Überschrift",
+ "Body text": "Fließtext",
+ "Bulleted list": "Aufzählung",
+ "Numbered list": "Nummerierte Liste",
+ "Clear formatting": "Formatierung entfernen",
"Cut": "Ausschneiden",
"Copy": "Kopieren",
"Paste": "Einfügen",
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index 487eff52..d0510886 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -4,6 +4,17 @@
import type { Catalog } from '../i18n'
export const es: Catalog = {
+ "This text box is already bold": "Este cuadro de texto ya está en negrita",
+ "Italic": "Cursiva",
+ "Underline": "Subrayado",
+ "Strikethrough": "Tachado",
+ "Code": "Código",
+ "Title text": "Texto de título",
+ "Heading": "Encabezado",
+ "Body text": "Texto normal",
+ "Bulleted list": "Lista con viñetas",
+ "Numbered list": "Lista numerada",
+ "Clear formatting": "Borrar formato",
"Cut": "Cortar",
"Copy": "Copiar",
"Paste": "Pegar",
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index dbbb586d..cca67693 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -4,6 +4,17 @@
import type { Catalog } from '../i18n'
export const fr: Catalog = {
+ "This text box is already bold": "Cette zone de texte est déjà en gras",
+ "Italic": "Italique",
+ "Underline": "Souligné",
+ "Strikethrough": "Barré",
+ "Code": "Code",
+ "Title text": "Texte de titre",
+ "Heading": "Titre",
+ "Body text": "Corps de texte",
+ "Bulleted list": "Liste à puces",
+ "Numbered list": "Liste numérotée",
+ "Clear formatting": "Effacer la mise en forme",
"Cut": "Couper",
"Copy": "Copier",
"Paste": "Coller",
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index e471f7af..da11ec85 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -4,6 +4,17 @@
import type { Catalog } from '../i18n'
export const it: Catalog = {
+ "This text box is already bold": "Questa casella di testo è già in grassetto",
+ "Italic": "Corsivo",
+ "Underline": "Sottolineato",
+ "Strikethrough": "Barrato",
+ "Code": "Codice",
+ "Title text": "Testo del titolo",
+ "Heading": "Intestazione",
+ "Body text": "Testo normale",
+ "Bulleted list": "Elenco puntato",
+ "Numbered list": "Elenco numerato",
+ "Clear formatting": "Cancella formattazione",
"Cut": "Taglia",
"Copy": "Copia",
"Paste": "Incolla",
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index 7fbdd730..e2793ced 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -4,6 +4,17 @@
import type { Catalog } from '../i18n'
export const ja: Catalog = {
+ "This text box is already bold": "このテキストボックスはすでにボールドです",
+ "Italic": "斜体",
+ "Underline": "下線",
+ "Strikethrough": "取り消し線",
+ "Code": "コード",
+ "Title text": "タイトル文字",
+ "Heading": "見出し",
+ "Body text": "本文",
+ "Bulleted list": "箇条書き",
+ "Numbered list": "番号付きリスト",
+ "Clear formatting": "書式をクリア",
"Cut": "切り取り",
"Copy": "コピー",
"Paste": "貼り付け",
diff --git a/slides/src/i18n/packed.ts b/slides/src/i18n/packed.ts
index 444cd08f..21539d0a 100644
--- a/slides/src/i18n/packed.ts
+++ b/slides/src/i18n/packed.ts
@@ -15,6 +15,17 @@ export const PACKED_LOCALES = ["ja","zh-Hans","zh-Hant","es","fr","de","it","pt"
/** English source string -> translations, positional by PACKED_LOCALES. */
export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
+ "This text box is already bold": ["このテキストボックスはすでにボールドです","此文本框已是粗体","此文字方塊已是粗體","Este cuadro de texto ya está en negrita","Cette zone de texte est déjà en gras","Dieses Textfeld ist bereits fett","Questa casella di testo è già in grassetto","Esta caixa de texto já está em negrito"],
+ "Italic": ["斜体","斜体","斜體","Cursiva","Italique","Kursiv","Corsivo","Itálico"],
+ "Underline": ["下線","下划线","底線","Subrayado","Souligné","Unterstrichen","Sottolineato","Sublinhado"],
+ "Strikethrough": ["取り消し線","删除线","刪除線","Tachado","Barré","Durchgestrichen","Barrato","Tachado"],
+ "Code": ["コード","代码","程式碼","Código","Code","Code","Codice","Código"],
+ "Title text": ["タイトル文字","标题文字","標題文字","Texto de título","Texte de titre","Titeltext","Testo del titolo","Texto de título"],
+ "Heading": ["見出し","小标题","小標題","Encabezado","Titre","Überschrift","Intestazione","Cabeçalho"],
+ "Body text": ["本文","正文","內文","Texto normal","Corps de texte","Fließtext","Testo normale","Texto normal"],
+ "Bulleted list": ["箇条書き","项目符号列表","項目符號清單","Lista con viñetas","Liste à puces","Aufzählung","Elenco puntato","Lista com marcadores"],
+ "Numbered list": ["番号付きリスト","编号列表","編號清單","Lista numerada","Liste numérotée","Nummerierte Liste","Elenco numerato","Lista numerada"],
+ "Clear formatting": ["書式をクリア","清除格式","清除格式","Borrar formato","Effacer la mise en forme","Formatierung entfernen","Cancella formattazione","Limpar formatação"],
"Cut": ["切り取り","剪切","剪下","Cortar","Couper","Ausschneiden","Taglia","Recortar"],
"Copy": ["コピー","复制","複製","Copiar","Copier","Kopieren","Copia","Copiar"],
"Paste": ["貼り付け","粘贴","貼上","Pegar","Coller","Einfügen","Incolla","Colar"],
diff --git a/slides/src/i18n/pt.ts b/slides/src/i18n/pt.ts
index 6a7561a3..faac4759 100644
--- a/slides/src/i18n/pt.ts
+++ b/slides/src/i18n/pt.ts
@@ -7,6 +7,17 @@
import type { Catalog } from '../i18n'
export const pt: Catalog = {
+ "This text box is already bold": "Esta caixa de texto já está em negrito",
+ "Italic": "Itálico",
+ "Underline": "Sublinhado",
+ "Strikethrough": "Tachado",
+ "Code": "Código",
+ "Title text": "Texto de título",
+ "Heading": "Cabeçalho",
+ "Body text": "Texto normal",
+ "Bulleted list": "Lista com marcadores",
+ "Numbered list": "Lista numerada",
+ "Clear formatting": "Limpar formatação",
"Cut": "Recortar",
"Copy": "Copiar",
"Paste": "Colar",
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index fd7aa642..8c93423a 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -4,6 +4,17 @@
import type { Catalog } from '../i18n'
export const zhHans: Catalog = {
+ "This text box is already bold": "此文本框已是粗体",
+ "Italic": "斜体",
+ "Underline": "下划线",
+ "Strikethrough": "删除线",
+ "Code": "代码",
+ "Title text": "标题文字",
+ "Heading": "小标题",
+ "Body text": "正文",
+ "Bulleted list": "项目符号列表",
+ "Numbered list": "编号列表",
+ "Clear formatting": "清除格式",
"Cut": "剪切",
"Copy": "复制",
"Paste": "粘贴",
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index c21d2397..cfe0c062 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -4,6 +4,17 @@
import type { Catalog } from '../i18n'
export const zhHant: Catalog = {
+ "This text box is already bold": "此文字方塊已是粗體",
+ "Italic": "斜體",
+ "Underline": "底線",
+ "Strikethrough": "刪除線",
+ "Code": "程式碼",
+ "Title text": "標題文字",
+ "Heading": "小標題",
+ "Body text": "內文",
+ "Bulleted list": "項目符號清單",
+ "Numbered list": "編號清單",
+ "Clear formatting": "清除格式",
"Cut": "剪下",
"Copy": "複製",
"Paste": "貼上",
diff --git a/slides/src/preview.ts b/slides/src/preview.ts
index a31e603f..70082e3c 100644
--- a/slides/src/preview.ts
+++ b/slides/src/preview.ts
@@ -86,6 +86,24 @@ function inlineRuntimeCss(root: HTMLElement) {
prepend(el, 'font-family:ui-monospace,Menlo,Consolas,monospace;font-size:0.9em;' +
'background:rgb(127 127 127 / 0.16);padding:0 0.28em;border-radius:3px')
}
+ // Rich text inside a box. Without these the thumbnailer — which runs no
+ // script and never inflates the compressed stylesheet — would render a
+ // bulleted list as unindented, unmarked lines and a heading at body size,
+ // i.e. a thumbnail that misrepresents the slide it is standing in for.
+ for (const el of Array.from(root.querySelectorAll<HTMLElement>('ul, ol'))) {
+ // same alignment rule as styles.css: an outside marker only belongs at the
+ // box's start edge when the line starts there too
+ const align = el.closest<HTMLElement>('.bento-text-inner')?.dataset.align
+ const inside = align === 'center' || align === 'right'
+ prepend(el, `margin:0;list-style:${el.tagName === 'OL' ? 'decimal' : 'disc'};` +
+ (inside ? 'padding-inline-start:0;list-style-position:inside' : 'padding-inline-start:1.35em'))
+ }
+ for (const el of Array.from(root.querySelectorAll<HTMLElement>('li'))) {
+ prepend(el, 'margin:0.12em 0')
+ }
+ for (const el of Array.from(root.querySelectorAll<HTMLElement>('h1, h2'))) {
+ prepend(el, `margin:0 0 0.2em;line-height:1.15;font-weight:700;font-size:${el.tagName === 'H1' ? '1.55em' : '1.25em'}`)
+ }
}
/** Put `css` in front of the element's existing inline style (which wins). */
diff --git a/slides/src/render.ts b/slides/src/render.ts
index 5ca5a7e1..f8b05e94 100644
--- a/slides/src/render.ts
+++ b/slides/src/render.ts
@@ -483,7 +483,25 @@ export function resolveMath(html: string): string {
return out.replace(/\\\$/g, '$') // the escape has done its job
}
-const ALLOWED_TAGS = new Set(['B', 'I', 'U', 'BR', 'SPAN', 'DIV', 'P', 'STRONG', 'EM', 'S', 'CODE'])
+/**
+ * The rich-text vocabulary a text element (and a table cell) may use.
+ *
+ * Every tag here is ATTRIBUTE-FREE by construction — the sanitizer strips all
+ * attributes unconditionally, so a tag can only ever mean what its name means.
+ * That is why formatting is expressed as semantic tags rather than styled
+ * spans: a `<span style>` route would need the sanitizer to start reasoning
+ * about declarations, and this format's whole defence is that it does not.
+ *
+ * The block tags (UL/OL/LI, H1/H2) are newer than the inline ones. An older
+ * shell that has not heard of them UNWRAPS them and keeps the words, so a deck
+ * with lists opens everywhere — it simply loses the bullets until the reader
+ * updates. Sanitizing happens at RENDER time, so that degradation is visual
+ * only; the model keeps the markup unless that box is edited in the old shell.
+ */
+const ALLOWED_TAGS = new Set([
+ 'B', 'I', 'U', 'BR', 'SPAN', 'DIV', 'P', 'STRONG', 'EM', 'S', 'CODE',
+ 'UL', 'OL', 'LI', 'H1', 'H2',
+])
/** Keep pasted/edited rich text down to a safe inline subset. */
export function sanitizeHtml(html: string): string {
@@ -1033,6 +1051,11 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOpts
if (ts.fill === 'none') inner.style.color = 'transparent'
}
inner.style.textAlign = el.align
+ // List markers need to know. `outside` hangs a marker at the box's start
+ // edge, which is only where it belongs when the line starts there too —
+ // centre or right the text and the markers stay pinned to the left,
+ // detached from the words they belong to (styles.css keys off this).
+ inner.dataset.align = el.align
inner.style.lineHeight = String(el.lineHeight)
if (el.letterSpacing) inner.style.letterSpacing = `${el.letterSpacing}px`
inner.style.width = '100%'
diff --git a/slides/src/styles.css b/slides/src/styles.css
index 90dc834c..c7d85005 100644
--- a/slides/src/styles.css
+++ b/slides/src/styles.css
@@ -2420,6 +2420,104 @@ dialog.ed-pwdialog .ed-pwerr { color: #C33; }
.ed-stepper .ed-btn-icon { width: 24px; height: 24px; line-height: 1; font-size: 15px; padding: 0; }
.ed-stepper-val { min-width: 20px; text-align: center; font-variant-numeric: tabular-nums; font-size: 13px; }
input.ed-toggle { width: 16px; height: 16px; accent-color: #5E7699; cursor: pointer; }
+/* --- rich text inside a box ------------------------------------------------
+ Every size here is in `em`, never px: the element's own `fontSize` is the
+ type scale, so a heading is "larger than this box" rather than a fixed size
+ that would fight the box it lives in — and resizing the box keeps the whole
+ hierarchy in proportion. Shared by the canvas, thumbnails, present and
+ print, because they all go through render.ts. */
+.bento-text-inner ul,
+.bento-text-inner ol {
+ margin: 0;
+ padding-inline-start: 1.35em;
+ list-style-position: outside;
+}
+/* Centred or right-aligned text: an `outside` marker stays pinned to the box's
+ start edge while its line moves away from it, so the bullet ends up floating
+ on its own. Keeping the marker inside the line keeps the two together — at
+ the cost of the hanging indent, which only reads as an indent when the text
+ is start-aligned anyway. */
+.bento-text-inner[data-align='center'] ul,
+.bento-text-inner[data-align='center'] ol,
+.bento-text-inner[data-align='right'] ul,
+.bento-text-inner[data-align='right'] ol {
+ padding-inline-start: 0;
+ list-style-position: inside;
+}
+.bento-text-inner li { margin: 0.12em 0; }
+.bento-text-inner ul { list-style: disc; }
+.bento-text-inner ol { list-style: decimal; }
+.bento-text-inner ul ul { list-style: circle; }
+.bento-text-inner h1,
+.bento-text-inner h2 {
+ margin: 0 0 0.2em;
+ line-height: 1.15;
+ font-weight: 700;
+}
+.bento-text-inner h1 { font-size: 1.55em; }
+.bento-text-inner h2 { font-size: 1.25em; }
+/* A heading that opens the box has nothing to separate itself from. */
+.bento-text-inner > :first-child { margin-top: 0; }
+
+/* --- selection formatting bar (editor/richtext.ts) -------------------------
+ Positioned from JS against the VIEWPORT, so the canvas scroller, a side
+ panel or the topbar can never clip it. */
+.ed-fmtbar {
+ position: fixed;
+ z-index: 130; /* above the context menu (120), which it can outlive */
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding: 4px;
+ /* the token, not white: --surface is #ffffff in light and #21262e in dark,
+ and a chrome surface pinned to a literal puts light text on a light
+ background the moment the reader is in dark mode */
+ background: var(--surface);
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ box-shadow: 0 10px 28px rgb(20 30 45 / 0.20);
+ user-select: none;
+}
+.ed-fmtbar-btn {
+ min-width: 30px;
+ height: 30px;
+ padding: 0 6px;
+ border: 0;
+ border-radius: 7px;
+ background: transparent;
+ color: var(--ink);
+ font: inherit;
+ font-size: 12.5px;
+ line-height: 1;
+ cursor: pointer;
+}
+.ed-fmtbar-btn:hover { background: var(--hover, #f2f5f9); }
+/* --blue INVERTS with the theme (#5b8def light, #7aa5f5 dark), so its text has
+ to invert with it — main's own `.ed-insertgap-btn` pairs the same token with
+ var(--surface) for exactly this reason. A literal white here reads fine in
+ light mode and is the pale-on-pale case the gate exists to catch. */
+.ed-fmtbar-btn.is-on { background: var(--blue, #5b8def); color: var(--surface); }
+.ed-fmtbar-sep { width: 1px; height: 18px; margin: 0 3px; background: var(--line); }
+/* the letter buttons should read as what they do */
+.ed-fmtbar-btn[data-cmd='bold'] { font-weight: 700; }
+.ed-fmtbar-btn[data-cmd='italic'] { font-style: italic; }
+.ed-fmtbar-btn[data-cmd='underline'] { text-decoration: underline; }
+.ed-fmtbar-btn[data-cmd='strikeThrough'] { text-decoration: line-through; }
+.ed-fmtbar-btn[data-code] { font-family: ui-monospace, Menlo, Consolas, monospace; }
+
+/* On a phone the bar is the only route to formatting, so it must not be
+ narrower than a thumb — and it may need to wrap rather than run off. */
+@media (max-width: 700px) {
+ .ed-fmtbar {
+ max-width: calc(100vw - 16px);
+ flex-wrap: wrap;
+ justify-content: center;
+ }
+ .ed-fmtbar-btn { min-width: 36px; height: 36px; }
+}
+.ed-fmtbar-btn:disabled { opacity: 0.35; cursor: default; }
+.ed-fmtbar-btn:disabled:hover { background: transparent; }
+
/* Languages dialog: built-in vs installed packs vs available to add. */
.ed-lang-manage { margin: 10px 0 4px; display: flex; flex-direction: column; gap: 2px; }