Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

Markdown support in text editing: autoformat as you type + paste conversion

nyblnete8b337a70212
diff --git a/CLAUDE.md b/CLAUDE.md
index 06930d07..72808802 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -52,7 +52,10 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.
url(#…) refs are document-global across canvas/thumbs/present). Arrange kit in
the panel: align/distribute/z-step + Group (⌘G/⇧⌘G — `groupId`, distinct from
presentation `group`; click selects the group, Alt-click reaches a member;
- duplicate remaps groupIds). Text editing supports ⌘B/I/U inline markup.
+ duplicate remaps groupIds). Text editing supports ⌘B/I/U plus markdown
+ autoformat (editor/markdown.ts: **bold** *italic* `code` ~~strike~~ and "- "
+ bullets collapse as typed — mind contentEditable NBSPs and stale
+ Selection offsets after DOM surgery; pasted plain text converts too).
Sidebar has hover insert-gaps between thumbnails (never between a parent and
its states). Selecto's continue-select list is synced in syncTargets — stale
cross-slide shift-click selections were a real bug.
diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.ts
index a7dad441..44ec123c 100644
--- a/slides/src/editor/canvas.ts
+++ b/slides/src/editor/canvas.ts
@@ -7,6 +7,7 @@ import Selecto from 'selecto'
import type { Store } from '../store'
import type { SlideElement } from '../model'
import { renderSlide, sanitizeHtml } from '../render'
+import { autoformatAtCaret, markdownToHtml } from './markdown'
import { PathEditor } from './patheditor'
export class SlideCanvas {
@@ -440,6 +441,15 @@ export class SlideCanvas {
}
}
})
+ // markdown affordances: **bold** / *italic* / `code` / ~~strike~~ / "- "
+ // collapse as you type; pasted plain text converts the same patterns
+ inner.addEventListener('input', () => autoformatAtCaret())
+ inner.addEventListener('paste', (ev) => {
+ const text = ev.clipboardData?.getData('text/plain')
+ if (!text) return
+ ev.preventDefault()
+ document.execCommand('insertHTML', false, sanitizeHtml(markdownToHtml(text)))
+ })
inner.addEventListener('blur', () => this.commitTextEdit(), { once: true })
}
@@ -452,7 +462,8 @@ export class SlideCanvas {
node.classList.remove('bento-editing')
if (!inner || !id) return
inner.contentEditable = 'false'
- const html = sanitizeHtml(inner.innerHTML)
+ // drop the zero-width caret spacers autoformat leaves behind
+ const html = sanitizeHtml(inner.innerHTML.replace(/​/g, ''))
const grownH = Math.max(parseFloat(node.style.height) || 0, inner.scrollHeight)
const el = this.store.element(id)
if (el && el.type === 'text' && (el.html !== html || grownH > el.h)) {
diff --git a/slides/src/editor/markdown.ts b/slides/src/editor/markdown.ts
new file mode 100644
index 00000000..fb493dcb
--- /dev/null
+++ b/slides/src/editor/markdown.ts
@@ -0,0 +1,96 @@
+// Lightweight markdown affordances for text editing. Two entry points:
+// - autoformatAtCaret: called on every input; when the text just before the
+// caret completes an inline pattern (**bold**, *italic*, `code`, ~~strike~~)
+// the markers collapse into the real element, Notion-style. "- " at the
+// start of a line becomes a bullet glyph.
+// - 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.
+
+const INLINE: Array<{ re: RegExp; tag: string }> = [
+ { re: /\*\*([^*\n]+)\*\*$/, tag: 'b' },
+ { re: /__([^_\n]+)__$/, tag: 'b' },
+ { re: /(?<![*\w])\*([^*\n]+)\*$/, tag: 'i' },
+ { re: /(?<![_\w])_([^_\n]+)_$/, tag: 'i' },
+ { re: /~~([^~\n]+)~~$/, tag: 's' },
+ { re: /`([^`\n]+)`$/, tag: 'code' },
+]
+
+/** Collapse a just-completed markdown marker before the caret. Returns true if it fired. */
+export function autoformatAtCaret(): boolean {
+ const sel = document.getSelection()
+ 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
+ const upto = node.data.slice(0, off)
+
+ // "- " at line start → bullet glyph (contentEditable renders the trailing
+ // space as NBSP, so match both; keep NBSP so the glyph's gap can't collapse)
+ if (/(?:^|\n)-[  ]$/.test(upto) && off >= 2 && isLineStart(node, off - 2)) {
+ node.replaceData(off - 2, 2, '• ')
+ placeCaret(node, off)
+ return true
+ }
+
+ for (const { re, tag } of INLINE) {
+ const m = upto.match(re)
+ if (!m || !m[1]) continue
+ const start = off - m[0].length
+ const range = document.createRange()
+ range.setStart(node, start)
+ range.setEnd(node, off)
+ range.deleteContents()
+ const el = document.createElement(tag)
+ el.textContent = m[1]
+ range.insertNode(el)
+ // caret into a fresh text node AFTER the element so typing continues plain
+ const tail = document.createTextNode('​')
+ el.after(tail)
+ placeCaret(tail, 1)
+ return true
+ }
+ return false
+}
+
+/** True when offset sits at the start of a rendered line (node start or after
+ * a <br>). Zero-width caret spacers left by autoformat are see-through. */
+function isLineStart(node: Text, offset: number): boolean {
+ const before = node.data.slice(0, offset).replace(/​/g, '')
+ if (before) return before.endsWith('\n')
+ let prev = node.previousSibling
+ while (prev && prev.nodeType === Node.TEXT_NODE && /^[​\s]*$/.test((prev as Text).data)) {
+ prev = prev.previousSibling
+ }
+ return !prev || (prev instanceof Element && prev.tagName === 'BR')
+}
+
+function placeCaret(node: Node, offset: number) {
+ const r = document.createRange()
+ r.setStart(node, offset)
+ r.collapse(true)
+ const sel = document.getSelection()
+ sel?.removeAllRanges()
+ sel?.addRange(r)
+}
+
+const escapeHtml = (s: string) =>
+ s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
+
+/** Pasted plain text → the inline-HTML subset (bold/italic/strike/code/bullets/<br>). */
+export function markdownToHtml(text: string): string {
+ return text
+ .split('\n')
+ .map((line) => {
+ let s = escapeHtml(line).replace(/^(\s*)- /, '$1• ')
+ s = s.replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>')
+ s = s.replace(/__([^_]+)__/g, '<b>$1</b>')
+ s = s.replace(/(?<![*\w])\*([^*]+)\*/g, '<i>$1</i>')
+ s = s.replace(/(?<![_\w])_([^_]+)_(?![\w])/g, '<i>$1</i>')
+ s = s.replace(/~~([^~]+)~~/g, '<s>$1</s>')
+ s = s.replace(/`([^`]+)`/g, '<code>$1</code>')
+ return s
+ })
+ .join('<br>')
+}
diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.ts
index 79c7aef3..9740cc83 100644
--- a/slides/src/editor/panels.ts
+++ b/slides/src/editor/panels.ts
@@ -412,6 +412,10 @@ export class PropsPanel {
private buildTextProps(el: TextElement) {
this.section('Typography')
+ const hint = document.createElement('p')
+ hint.className = 'ed-hint'
+ hint.innerHTML = 'While editing: <b>⌘B</b>/<b>⌘I</b>/<b>⌘U</b> · markdown auto-converts — **bold*&#8203;* *italic*&#8203; `code` ~~strike~~ and "- " bullets; pasting markdown converts too.'
+ this.host.appendChild(hint)
this.row('Font', this.fontSelect(el))
this.row('Size', this.number(el.fontSize, 1, (v, fin) =>
this.mutate(el.id, (e) => { (e as TextElement).fontSize = Math.max(v, 4) }, fin)))
diff --git a/slides/src/render.ts b/slides/src/render.ts
index 629b3717..c0f06ab7 100644
--- a/slides/src/render.ts
+++ b/slides/src/render.ts
@@ -180,7 +180,7 @@ export function shapeSvg(el: ShapeElement): SVGSVGElement {
return svg
}
-const ALLOWED_TAGS = new Set(['B', 'I', 'U', 'BR', 'SPAN', 'DIV', 'P', 'STRONG', 'EM'])
+const ALLOWED_TAGS = new Set(['B', 'I', 'U', 'BR', 'SPAN', 'DIV', 'P', 'STRONG', 'EM', 'S', 'CODE'])
/** Keep pasted/edited rich text down to a safe inline subset. */
export function sanitizeHtml(html: string): string {
diff --git a/slides/src/styles.css b/slides/src/styles.css
index 9055e3ea..67452a07 100644
--- a/slides/src/styles.css
+++ b/slides/src/styles.css
@@ -464,6 +464,15 @@ html, body {
border-radius: 999px;
}
+/* inline code spans inside text elements — editor, present and print alike */
+.bento-el-text code {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 0.9em;
+ background: rgb(127 127 127 / 0.16);
+ padding: 0 0.28em;
+ border-radius: 3px;
+}
+
/* arrange kit: align/distribute/z-step buttons */
.ed-arrange { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }
.ed-arrange-btn {