Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: callouts, quotes, captions and dividers survive Markdown byte for byte (#560)
nyblnet1cb72b72493a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex fca50261..eddc986b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -228,14 +228,27 @@ jobs:# checked: the starter space is exported and read back, and no page may# come back with materially less text than it went in with, nor may a# single block vanish entirely. Block TYPES are deliberately not- # asserted — Markdown has no callout, toggle, media embed or board, so a- # callout leaving as a blockquote is the format being honest, not a bug.+ # asserted here — Markdown has no toggle, media embed or board, so a toggle+ # leaving as a bullet is the format being honest, not a bug (the strict+ # rig below holds each type to its own bar).# (Bundled: the app's imports are extensionless.)run: |slides/node_modules/.bin/esbuild scripts/test-spaces-roundtrip.ts --bundle --platform=node --format=esm \--outfile="$RUNNER_TEMP/test-spaces-roundtrip.mjs"node "$RUNNER_TEMP/test-spaces-roundtrip.mjs"+ - name: Spaces Markdown strict rig+ # The round-trip rig above checks WORDS; this checks TYPES. Every+ # registered block type is exported and read back, and must return as+ # the same JSON (ids aside) and re-export to the same text — or be+ # PINNED with the reason Markdown cannot carry it yet. A pinned type+ # that starts to round-trip fails too, so closing a gap is a deliberate+ # edit to the rig. (Bundled: the app's imports are extensionless.)+ run: |+ slides/node_modules/.bin/esbuild scripts/test-spaces-md-strict.ts --bundle --platform=node --format=esm \+ --outfile="$RUNNER_TEMP/test-spaces-md-strict.mjs"+ node "$RUNNER_TEMP/test-spaces-md-strict.mjs"+- name: Spaces model rig# Properties that fail SILENTLY, and that a shipped file cannot be# talked out of once it exists:diff --git a/scripts/test-spaces-md-strict.ts b/scripts/test-spaces-md-strict.tsnew file mode 100644index 00000000..2ee910fd--- /dev/null+++ b/scripts/test-spaces-md-strict.ts@@ -0,0 +1,285 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/spaces: which block types survive Markdown BYTE FOR BYTE.+//+// node scripts/test-spaces.mjs md-strict+//+// (Bundled, not run directly: the app's imports are extensionless. See the+// runner.)+//+// THE STRICT BAR, per block type. One fixture per type in the registry →+// about.ts toMarkdown → markdown.ts parseNote, and a type QUALIFIES only when+// both of these hold:+// · the blocks that come back are the blocks that went in, as JSON — ids+// aside, and `parent` compared by POSITION, since ids are fresh on import;+// · exporting what came back reproduces the first export's text exactly.+//+// test-spaces-roundtrip.ts is the LOOSE bar — words, on the whole starter —+// and says in its own header that type-for-type is not its business. This rig+// is that business. The two do not overlap: a callout that came back as a+// quote passes the loose rig (every word is there) and fails this one.+//+// A TYPE THAT DOES NOT QUALIFY IS PINNED, with the reason Markdown cannot yet+// carry it. The pin is two-sided on purpose: a pinned type that starts to+// qualify FAILS this rig too. So teaching the importer a new shape (toggles+// as <details>, props as front matter …) is a deliberate edit here — the pin+// comes out in the same PR that earns it — never a silent improvement that+// nobody records, and never a silent regression hidden among known losses.+//+// A block type with no fixture fails as well: a type added to blocks.ts has to+// be put on one side of this line or the other.+import { toMarkdown } from '../spaces/src/about.ts'+import { parseNote } from '../spaces/src/markdown.ts'+import { Store } from '../spaces/src/store.ts'+import { SPECS, CALLOUT_TONES } from '../spaces/src/blocks.ts'+import { DEFAULT_FIELDS, propBlock } from '../spaces/src/fields.ts'+import { type Block, type Page, type SpacesDoc, defaultTheme, writeTable } from '../spaces/src/model.ts'++let checks = 0+let failures = 0+function ok(cond: boolean, msg: string, detail?: string) {+ checks+++ if (cond) { console.log(` ok ${msg}`); return }+ failures+++ console.log(` FAIL ${msg}`)+ if (detail) console.log(detail.split('\n').map((l) => ` ${l}`).join('\n'))+}++let n = 0+const id = () => `f-${++n}`+/** A block in the EDITOR's shape: model.newBlock always writes `html: ''`. */+const b = (type: string, html = '', extra: Record<string, unknown> = {}): Block =>+ ({ id: id(), type, html, ...extra }) as Block++const PAGE = 'fixture-page'+const TITLE = 'Fixture'++function doc(pages: Page[]): SpacesDoc {+ return { format: 'bento/spaces', version: 1, docId: 'fixture', title: TITLE, theme: defaultTheme(), pages } as SpacesDoc+}++interface Fixture { blocks: Block[]; extraPages?: Page[] }++// ONE PER TYPE. Each is what the editor would produce, with every field the+// type actually carries set — a fixture that leaves a field out cannot notice+// it being dropped.+const FIX: Record<string, () => Fixture> = {+ p: () => ({ blocks: [b('p', 'Plain <strong>bold</strong> <em>em</em> <code>code</code> text with a <a href="https://x.y/z">link</a>.')] }),+ h1: () => ({ blocks: [b('p', 'lead'), b('h1', 'A heading')] }),+ h2: () => ({ blocks: [b('h2', 'A heading')] }),+ h3: () => ({ blocks: [b('h3', 'A heading')] }),+ bullet: () => { const a = b('bullet', 'one'); return { blocks: [a, b('bullet', 'nested', { parent: a.id }), b('bullet', 'two')] } },+ number: () => ({ blocks: [b('number', 'first'), b('number', 'second')] }),+ todo: () => ({ blocks: [b('todo', 'open', { done: false }), b('todo', 'done', { done: true })] }),+ toggle: () => { const t = b('toggle', 'Fold me', { open: false }); return { blocks: [t, b('p', 'inside the fold', { parent: t.id })] } },+ // a callout with its own two lines AND a child: the child is what proves the+ // alert body is parsed as blocks, not flattened into the callout's text+ callout: () => { const c = b('callout', 'Mind the gap<br>and the step', { tone: 'warning' }); return { blocks: [c, b('p', 'body line', { parent: c.id })] } },+ quote: () => ({ blocks: [b('quote', 'Said once.<br>Said twice.')] }),+ code: () => ({ blocks: [b('code', 'const a = 1\nif (a < 2) {}', { lang: 'ts' })] }),+ divider: () => ({ blocks: [b('p', 'above'), b('divider'), b('p', 'below')] }),+ // alt, src, caption — what `` can say. Size is pinned+ // separately below.+ image: () => ({ blocks: [b('image', '', { src: 'asset:abc', alt: 'A diagram', caption: 'Drawn, not "photographed"' })] }),+ media: () => ({ blocks: [b('media', '', { kind: 'audio', src: 'asset:tone', alt: 'A tone', controls: true })] }),+ link: () => ({ blocks: [b('link', '<a href="https://bento.page">Bento</a> — desc', { url: 'https://bento.page', title: 'Bento', desc: 'desc', site: 'bento.page' })] }),+ pagelink: () => ({ blocks: [b('pagelink', '', { page: 'other' })], extraPages: [{ id: 'other', title: 'Other page', blocks: [b('p', 'x')] }] }),+ prop: () => ({ blocks: [propBlock(DEFAULT_FIELDS[0], 'doing', id())] }),+ table: () => {+ const t = b('table', '')+ writeTable(t, { rows: [['A', 'B'], ['1', '<strong>2</strong>']], cols: [1, 1], colAlign: ['', 'right'], header: true })+ return { blocks: [t] }+ },+ view: () => ({+ blocks: [b('view', 'Issues', { layout: 'board', groupBy: 'status' })],+ extraPages: [{ id: 'iss1', title: 'Fix it', parent: PAGE, blocks: [propBlock(DEFAULT_FIELDS[0], 'todo', id()), b('p', 'body')] }],+ }),+ canvas: () => { const c = b('canvas', 'Roadmap'); return { blocks: [c, b('p', 'card one', { parent: c.id, x: 40, y: 60 }), b('p', 'card two', { parent: c.id, x: 300, y: 120 })] } },+}++// THE PINS — the types Markdown cannot yet carry, each with why. The reason is+// the design brief's own row, so a reader of a failure knows what closing it+// would take. Removing a pin is the deliberate edit this rig asks for.+const PINNED: Record<string, string> = {+ toggle: 'exports as `- text` and comes back a bullet; needs `<details open><summary>` (an html-block parser)',+ link: 'exports as `[title](url) — desc` and comes back a paragraph; needs a lone-link-line rule or a fence, and `site`/`image` are lost',+ media: 'exports as `[label](src)` and comes back a paragraph; needs `<video>`/`<audio>` html or a fence, and `controls`/`loop`/`muted` are lost',+ prop: 'exports as `**Status:** In progress` and comes back a paragraph; the natural form is front matter (`status: doing`), and value id vs label needs the schema',+ view: 'exports as a title and a grouped issue list and comes back as p+p+bullet; needs a `bento-view` fence (its rows are other pages)',+ pagelink: 'exports as `→ [[Title]]` and comes back a paragraph holding a wikilink',+ canvas: 'exports its name and cards as prose and comes back as paragraphs; card positions are lost (a `bento-canvas` fence or `{x= y=}` attributes)',+}++// ---- the measurement --------------------------------------------------------++/** ids out, `parent` as the parent's position — ids are minted fresh on import */+function strip(blocks: Block[]): unknown[] {+ const pos = new Map(blocks.map((x, i) => [x.id, i]))+ return blocks.map((x) => {+ const { id: _id, parent, ...rest } = x as Record<string, unknown> & { id: string; parent?: string }+ return parent === undefined ? rest : { ...rest, parent: `#${pos.get(parent) ?? parent}` }+ })+}+const canon = (v: unknown): string => JSON.stringify(v, (_k, x) =>+ x && typeof x === 'object' && !Array.isArray(x)+ ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, (x as Record<string, unknown>)[k]]))+ : x)++/** The fixture page's own section of an export: its body, without the `# Fixture` title. */+function section(md: string, others: Page[]): string {+ let s = md.slice(md.indexOf(`# ${TITLE}\n`))+ for (const p of others) {+ const at = s.search(new RegExp(`\\n#+ ${p.title}\\n`))+ if (at >= 0) s = s.slice(0, at + 1)+ }+ return s.replace(new RegExp(`^# ${TITLE}\\n\\n?`), '')+}++interface Trip { md: string; md2: string; inJson: string; outJson: string; back: Block[] }++function trip(fx: Fixture): Trip {+ const extra = fx.extraPages ?? []+ const exportOf = (blocks: Block[]) =>+ section(toMarkdown(new Store(doc([{ id: PAGE, title: TITLE, blocks }, ...extra]) as never) as never), extra)+ const md = exportOf(fx.blocks)+ const back = parseNote(md, TITLE).blocks+ return { md, md2: exportOf(back), inJson: canon(strip(fx.blocks)), outJson: canon(strip(back)), back }+}++const qualifies = (t: Trip): boolean => t.inJson === t.outJson && t.md === t.md2+const why = (t: Trip): string => [+ 'markdown:', ...t.md.trimEnd().split('\n').map((l) => ` | ${l}`),+ ...(t.inJson !== t.outJson ? [`json in : ${t.inJson}`, `json out: ${t.outJson}`] : []),+ ...(t.md !== t.md2 ? ['re-exported:', ...t.md2.trimEnd().split('\n').map((l) => ` | ${l}`)] : []),+].join('\n')++// ---- per type ---------------------------------------------------------------++console.log('\nevery registered block type, exported and read back')+const types = SPECS.map((s) => s.type)+let exact = 0+for (const type of types) {+ const fx = FIX[type]+ if (!fx) { ok(false, `${type}: has a fixture (a new block type must be put on one side of the pin line)`); continue }+ const t = trip(fx())+ const q = qualifies(t)+ if (q) exact+++ const pin = PINNED[type]+ if (pin) {+ ok(!q, `${type}: pinned as lossy — ${pin}`,+ q ? 'it now round-trips byte for byte. Remove its pin from PINNED: that is the deliberate edit this rig exists to force.' : undefined)+ } else {+ ok(q, `${type}: byte-identical (JSON minus ids, and the re-exported text)`, q ? undefined : why(t))+ }+}+for (const type of Object.keys(PINNED)) {+ ok(types.includes(type), `pin "${type}" names a registered block type`)+}+for (const type of Object.keys(FIX)) {+ ok(types.includes(type), `fixture "${type}" names a registered block type`)+}+const expected = types.length - Object.keys(PINNED).length+ok(exact === expected, `${exact} of ${types.length} block types are byte-identical (expected ${expected}; ${Object.keys(PINNED).length} pinned)`)++// ---- the shapes one fixture per type does not reach -------------------------++console.log('\ncallouts: every tone, and a body that is more than one paragraph')+for (const { tone } of CALLOUT_TONES) {+ const c = b('callout', `A ${tone}`, { tone })+ const t = trip({ blocks: [c, b('p', 'first child', { parent: c.id }), b('p', 'after the box')] })+ ok(qualifies(t), `tone "${tone}" ⇄ > [!${tone.toUpperCase()}]`, qualifies(t) ? undefined : why(t))+}+{+ const c = b('callout', '', { tone: 'note' })+ const li = b('bullet', 'a point', { parent: c.id })+ const t = trip({ blocks: [c, b('p', 'one', { parent: c.id }), li, b('bullet', 'under it', { parent: li.id }), b('p', 'outside')] })+ ok(qualifies(t), 'an EMPTY callout whose body is a paragraph and a nested list', qualifies(t) ? undefined : why(t))+}+{+ const outer = b('callout', 'Outer', { tone: 'important' })+ const inner = b('callout', 'Inner', { tone: 'caution', parent: outer.id })+ const t = trip({ blocks: [outer, inner, b('p', 'deep', { parent: inner.id })] })+ ok(qualifies(t), 'a callout nested in a callout (> > [!CAUTION])', qualifies(t) ? undefined : why(t))+}+{+ const t = trip({ blocks: [b('callout', 'first', { tone: 'tip' }), b('callout', 'second', { tone: 'tip' })] })+ ok(qualifies(t), 'two adjacent callouts stay two', qualifies(t) ? undefined : why(t))+}++console.log('\nquotes and images at their edges')+{+ const t = trip({ blocks: [b('quote', 'stanza one<br><br>stanza two'), b('quote', 'a second quote')] })+ ok(qualifies(t), 'a quote holding a blank line, then a separate quote', qualifies(t) ? undefined : why(t))+}+{+ const t = trip({ blocks: [b('image', '', { src: 'asset:x', caption: 'a back\\slash' })] })+ ok(qualifies(t), 'a caption with a backslash and no alt', qualifies(t) ? undefined : why(t))+}+{+ const t = trip({ blocks: [b('image', '', { src: 'asset:x', alt: 'no caption' })] })+ ok(qualifies(t) && !t.md.includes('"'), 'an image without a caption exports no title', qualifies(t) ? undefined : why(t))+}+// A PINNED FIELD LOSS inside a qualifying type. `` has no+// place for a size, so a sized image is NOT byte-identical — and when+// `{width=80%}` (or similar) is taught to both sides, this fails and asks for+// the pin to come out.+{+ const t = trip({ blocks: [b('image', '', { src: 'asset:abc', alt: 'A', caption: 'c', w: 640, h: 300, width: 80 })] })+ const kept = t.back[0] as Record<string, unknown>+ ok(kept.w === undefined && kept.h === undefined && kept.width === undefined,+ 'pinned: an image\'s w/h/width do not survive Markdown (needs an attribute syntax such as {width=80%})',+ 'the size now survives — remove this pin and fold the size into the image fixture')+}++// ---- Markdown this app did not write ----------------------------------------+// An importer that only reads its own exporter's spelling is a round trip, not+// an importer. These are alerts as GitHub documents them and as Obsidian writes+// callouts.++console.log('\nalerts written elsewhere')+function only(md: string) { return parseNote(md, 'Note').blocks }+{+ const got = only('> [!WARNING]\n> Critical content demanding immediate user attention due to potential risks.\n')+ ok(got.length === 1 && got[0].type === 'callout' && got[0].tone === 'warning' &&+ got[0].html === 'Critical content demanding immediate user attention due to potential risks.',+ 'GitHub: `> [!WARNING]` then `> text` is a warning callout holding that text', JSON.stringify(got))+}+{+ const got = only('> [!NOTE]\n> Useful information.\n>\n> - one\n> - two\n\nAfter.\n')+ ok(got.map((x) => `${x.type}${x.parent === got[0].id ? '^' : ''}`).join(' ') === 'callout bullet^ bullet^ p',+ 'GitHub: a multi-paragraph alert keeps its list inside the box, and the next line outside', JSON.stringify(got))+ ok(got[0].html === 'Useful information.', 'GitHub: the alert\'s first paragraph is the callout\'s own text', JSON.stringify(got[0]))+}+{+ const got = only('- item\n > [!IMPORTANT]\n > inside a list\n- next\n')+ ok(got.map((x) => x.type).join(' ') === 'bullet callout bullet' && got[1].parent === got[0].id &&+ got[1].html === 'inside a list' && got[2].parent === undefined,+ 'an alert indented under a list item belongs to that item, and the list resumes after it', JSON.stringify(got))+}+{+ // a lazy line after the tag is NOT the callout's text: the box has ended+ const got = only('> [!NOTE]\nnot in the box\n')+ ok(got.length === 2 && got[0].type === 'callout' && got[0].html === '' && got[1].type === 'p' && !got[1].parent,+ 'a line after the alert without `>` is not pulled into it', JSON.stringify(got))+}+{+ const got = only('> [!tip] Remember this\n> and this too\n')+ ok(got.length === 1 && got[0].type === 'callout' && got[0].tone === 'tip' && got[0].html === 'Remember this<br>and this too',+ 'Obsidian: lower-case `[!tip] Title` on the tag line keeps the title as text', JSON.stringify(got))+}+{+ const got = only('> [!caution]- Folded\n> body\n')+ ok(got[0]?.type === 'callout' && got[0].tone === 'caution', 'Obsidian: a fold marker `[!caution]-` is still a caution callout', JSON.stringify(got))+}+{+ const got = only('> [!info] Not one of the five\n')+ ok(got.length === 1 && got[0].type === 'quote', 'an alert type outside the five stays a quote, word for word', JSON.stringify(got))+}+{+ const got = only('> Just a quote\n> [!NOTE] mid-quote is text\n')+ ok(got.length === 1 && got[0].type === 'quote', 'an alert tag that does not OPEN the blockquote is quote text', JSON.stringify(got))+}++console.log(`\n${checks - failures}/${checks} checks passed · ${exact} of ${types.length} block types byte-identical`)+if (failures) process.exit(1)diff --git a/scripts/test-spaces-roundtrip.ts b/scripts/test-spaces-roundtrip.tsindex ee5497fe..be2281b9 100644--- a/scripts/test-spaces-roundtrip.ts+++ b/scripts/test-spaces-roundtrip.ts@@ -14,11 +14,10 @@// and this is the path OUT — the sentence people are asked to trust when they// decide whether to keep a year of notes in one HTML file.//-// WHAT IT DOES NOT CHECK, deliberately: block TYPES. Markdown has no callout,-// no toggle, no media embed, no board. A callout leaves as a blockquote, a-// toggle as a bullet, a link card as `[title](url)`, an image as ``.-// Asserting type-for-type round-tripping would be asserting that Markdown is-// something it is not, and would fail on every honest export.+// WHAT IT DOES NOT CHECK, deliberately: block TYPES. Markdown has no toggle,+// no media embed, no board: a toggle leaves as a bullet, a link card as+// `[title](url)`. Type-for-type is test-spaces-md-strict.ts's bar, per block,+// with the types Markdown cannot carry pinned there by name.//// WHAT IT DOES CHECK is the thing that would actually hurt: WORDS. If a// paragraph, a table cell or a list item goes into the exporter and does notdiff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjsindex 7267c86a..774820fb 100755--- a/scripts/test-spaces.mjs+++ b/scripts/test-spaces.mjs@@ -50,6 +50,7 @@ const RIGS = [{ name: 'undo', file: 'scripts/test-spaces-undo.ts', bundle: true },{ name: 'invite', file: 'scripts/test-spaces-invite.ts', bundle: true },{ name: 'roundtrip', file: 'scripts/test-spaces-roundtrip.ts', bundle: true },+ { name: 'md-strict', file: 'scripts/test-spaces-md-strict.ts', bundle: true },{ name: 'restore-gate', file: 'scripts/test-spaces-restore-gate.ts', bundle: true },{ name: 'size', file: 'scripts/test-spaces-size.mjs' },// Revision tracking has no timezone dependency; the browser rig needs thediff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex 82ff16b2..828ead8a 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -486,6 +486,30 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.2026, from the same file. `bento.journal()` opens today's for an agent, and`bento.journal('2026-08-06')` any day's.+- **Callouts, quotes and captions survive a trip through Markdown.** Four+ places where the exporter and the importer disagreed with each other, each+ measured by exporting one block and reading it back:+ - A **GitHub alert** — `> [!NOTE]`, `[!TIP]`, `[!IMPORTANT]`, `[!WARNING]`,+ `[!CAUTION]` — now imports as a callout of that tone, with everything in+ the box (lists, code, a nested alert) as its body. The export already+ wrote alerts; the importer read them back as a plain quote with `[!WARNING]`+ as its first words. Alerts written by GitHub or Obsidian read the same way,+ including Obsidian's lower-case tags, fold markers and text on the tag+ line. Other tags (`[!info]`) stay a quote, word for word.+ - A **quote with a line break** exported its second line without `> `, so a+ blank line inside it came back as a quote followed by a loose paragraph.+ Every line is marked now.+ - An **image caption** leaves as the Markdown title, ``.+ The importer already read that title as the caption; the exporter was+ dropping it. An image's size still does not survive — Markdown has no+ place for it.+ - A **divider** comes back as the same block the editor made.++ `scripts/test-spaces-md-strict.ts` holds every block type to this bar: 13 of+ the 20 now come back byte for byte (9 did before), and the other 7 — toggle,+ link card, media, field, board, page link, canvas — are pinned with the+ reason, so the rig fails if one starts to qualify without the pin being+ lifted on purpose.- **Footnotes.** A mark in the prose, the note at the foot of the page — write`[^1]` where the mark goes and the note appears as a numbered slot below thepage to write into. Notes print, export as `[^1]: the note.` and import backdiff --git a/spaces/src/blocks.ts b/spaces/src/blocks.tsindex 28ec22be..b35e1d28 100644--- a/spaces/src/blocks.ts+++ b/spaces/src/blocks.ts@@ -189,7 +189,12 @@ export const SPECS: BlockSpec[] = [{type: 'quote', label: 'Quote', hint: '>', icon: 'quote',tag: 'blockquote', text: true, md: [/^> $/],- toMd: (_b, text) => [`> ${text}`],+ // `> ` on EVERY line, like the callout above. htmlToMd turns <br> into a+ // newline, and a second line without its marker is a LAZY continuation:+ // GitHub still draws it inside the quote, but it is the one spelling that+ // stops at the next blank line — so `a<br><br>b` came back as a quote and a+ // loose paragraph. A bare `>` keeps a blank line inside the box.+ toMd: (_b, text) => text.split('\n').map((l) => (l ? `> ${l}` : '>')),},{type: 'code', label: 'Code', hint: '``` ', icon: 'code',@@ -355,7 +360,16 @@ export const SPECS: BlockSpec[] = [{type: 'image', label: 'Image', hint: 'Embedded in the file', icon: 'image',tag: 'div', custom: true,- toMd: (b) => [`})`],+ // The caption is the link TITLE — `` — which the+ // importer already read and this used to drop, so every captioned image+ // lost its caption on the way out. Written verbatim (it is the same inline+ // html both ways), with `"` and `\` escaped as CommonMark spells them in a+ // title, and on one line: a newline would end the image.+ toMd: (b) => {+ const cap = String(b.caption ?? '').replace(/\s*\n\s*/g, ' ')+ const title = cap ? ` "${cap.replace(/["\\]/g, '\\$&')}"` : ''+ return [`}${title})`]+ },},{type: 'media', label: 'Video or audio', hint: 'Plays in the page', icon: 'play',diff --git a/spaces/src/markdown.ts b/spaces/src/markdown.tsindex b72896f9..500766f5 100644--- a/spaces/src/markdown.ts+++ b/spaces/src/markdown.ts@@ -209,7 +209,9 @@ export interface ParsedNote {const mk = (type: string, extra: Partial<Block> = {}): Block => ({ id: uid('b'), type, ...extra })-const IMG_LINE = /^!\[([^\]]*)\]\(\s*<?([^\s)>]*)>?(?:\s+"([^"]*)")?\s*\)$/+// The title may hold `\"` and `\\` — CommonMark's escapes, and what the+// exporter writes for a caption containing either (blocks.ts image toMd).+const IMG_LINE = /^!\[([^\]]*)\]\(\s*<?([^\s)>]*)>?(?:\s+"((?:[^"\\]|\\.)*)")?\s*\)$/const IMG_EMBED = /^!\[\[([^\]|]+)(?:\|[^\]]*)?\]\]$/const IMAGE_EXT = /\.(png|jpe?g|gif|webp|avif|svg|bmp|ico)$/i@@ -217,7 +219,7 @@ const IMAGE_EXT = /\.(png|jpe?g|gif|webp|avif|svg|bmp|ico)$/i* image FILE — otherwise it is an embed of another note, which is a link. */function imageOf(line: string): { ref: string; alt: string; caption?: string } | null {const m = IMG_LINE.exec(line.trim())- if (m) return { ref: m[2], alt: m[1], ...(m[3] ? { caption: m[3] } : {}) }+ if (m) return { ref: m[2], alt: m[1], ...(m[3] ? { caption: m[3].replace(/\\(["\\])/g, '$1') } : {}) }const e = IMG_EMBED.exec(line.trim())if (e && IMAGE_EXT.test(e[1].trim())) return { ref: e[1].trim(), alt: '' }return null@@ -266,6 +268,16 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {/** open list levels, innermost last */const stack: Array<{ indent: number; id: string }> = []+ /**+ * Open GitHub alerts, innermost last: the line index where each one's+ * blockquote ENDS, and how deep `stack` was before it opened. An alert is a+ * container whose body is ordinary markdown — lists, fences, nested alerts —+ * so its lines are un-quoted IN PLACE and read by this same loop, with the+ * callout on `stack` as their owner until `end`.+ */+ const alerts: Array<{ end: number; depth: number }> = []+ /** a callout whose tag line held no text: its next line, if adjacent, is its text */+ let alertText: Block | null = null/** the paragraph a soft line break continues, and the quote a `>` continues */let para: Block | null = nulllet quote: Block | null = null@@ -284,7 +296,9 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {// "could a file the user picked satisfy this address" — and a relative path// is the one case where the answer is yes.const imageBlock = (ref: string, alt: string, caption: string | undefined, parent?: string) => {- const b = mk('image', { src: ref, ...(alt ? { alt } : {}), ...(caption ? { caption } : {}) })+ // `html: ''` is the shape model.newBlock gives every block, so an image+ // that goes out and comes back is the same JSON the editor made+ const b = mk('image', { html: '', src: ref, ...(alt ? { alt } : {}), ...(caption ? { caption } : {}) })add(b, parent)if (/^(https?:)?\/\//i.test(ref)) remoteImages++else if (!/^data:/i.test(ref)) images.push({ block: b, ref, dir: '' })@@ -292,6 +306,12 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {}for (; i < lines.length; i++) {+ while (alerts.length && i >= alerts[alerts.length - 1].end) {+ stack.length = alerts.pop()!.depth+ para = null; quote = null; alertText = null+ }+ const ownText = alertText+ alertText = nullconst line = lines[i].replace(/\t/g, TAB)const indent = /^ */.exec(line)![0].lengthconst body = line.slice(indent).trimEnd()@@ -360,7 +380,8 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {if (/^([-*_])\s*(?:\1\s*){2,}$/.test(body)) {para = null; quote = null- add(mk('divider'), ownerFor(indent))+ // `html: ''`, as model.newBlock writes it — see imageBlock+ add(mk('divider', { html: '' }), ownerFor(indent))continue}@@ -373,6 +394,30 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {continue}+ // A GITHUB ALERT — `> [!WARNING]` opening a blockquote — is a callout, and+ // the five tags ARE the five tones (blocks.ts CALLOUT_TONES), so this is+ // the exporter read backwards. Obsidian's spelling reads too: lower case,+ // a fold marker (`[!tip]-`, dropped: a callout does not fold) and text on+ // the tag line. Any other tag stays a quote, word for word — and so does+ // a tag that does not OPEN its blockquote.+ const alert = quote ? null : /^>\s?\[!(note|tip|important|warning|caution)\][+-]?(?:\s+(.*))?$/i.exec(body)+ if (alert) {+ para = null+ const callout = add(mk('callout', { html: inlineHtml(alert[2] ?? ''), tone: alert[1].toLowerCase() }), ownerFor(indent))+ let j = i + 1+ for (; j < lines.length; j++) {+ const m = /^( *)>\s?(.*)$/.exec(lines[j].replace(/\t/g, TAB))+ if (!m || m[1].length < indent) break+ lines[j] = ' '.repeat(indent) + m[2]+ }+ alerts.push({ end: j, depth: stack.length })+ // below `indent`, so no line of the body can pop it before `end` does+ stack.push({ indent: indent - 0.5, id: callout.id })+ if (callout.html) para = callout+ else alertText = callout+ continue+ }+const q = /^>\s?(.*)$/.exec(body)if (q) {para = null@@ -428,7 +473,8 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {// facts), and joining them into a paragraph is not reversible — while// keeping them is, by deleting the break.const text = inlineHtml(body)- if (para) para.html = `${para.html}<br>${text}`+ if (ownText) { ownText.html = text; para = ownText }+ else if (para) para.html = `${para.html}<br>${text}`else para = add(mk('p', { html: text }), ownerFor(indent))}