Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: Markdown families — toggles, image size, link cards, media, marks, page links, views, canvases, block ids (replaces #562) (#661)
nyblnet53571469815f
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex d3e2fcfb..ac8e4a5a 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -9279,3 +9279,50 @@ shape-aware); diamond, hexagon, cylinder and the other closed outlines are`path` shapes, which `isLineLike` hands to the line/curve editor; and an edgeor node label is a free text element, because nothing binds a label to itselement.+## 2026-09-26 — bento/spaces: the Markdown form of every block, and the syntax reserved for the rest++**Decision.** Every spaces block type except `prop` now survives Markdown byte+for byte: the JSON comes back with only its ids changed, and the next export is+the same text. `scripts/test-spaces-md-strict.ts` holds that bar type by type,+with 19 of 20 types passing. The forms, with the full table in+`docs/spaces-agents.md` under "Markdown in and out":++- toggle `<details>`/`<summary>`; image size `{width=60% w=640 h=300}`+ (Pandoc attributes); media `<video>`/`<audio>` holding a link to the clip;+ page link `[[Title]]` alone on a line; view and canvas as `bento-view` and+ `bento-canvas` fences holding one JSON line; block ids as a trailing `{#id}`.+- **A link card is a link plus a hidden marker**,+ `[title](url) — desc <!-- bento:card site="…" image="…" -->`. This+ EXTENDS 2026-08-22 ("in Markdown a link card is a link") without reversing+ it. An unmarked lone link would turn every README line that is just a link+ into a card. A fence would stop it being a link. A Pandoc `{.card …}`+ would print on GitHub, and a `data:` thumbnail in it would be kilobytes of+ visible text. A `data:` thumbnail over 512 bytes is left out, as a pinned+ loss.+- **A clip leaves as html, superseding 2026-08-22's "a clip exports as a+ markdown LINK".** The link survives as the element's fallback content, so a+ renderer that strips `<video>` shows exactly the old export, and one that+ keeps it plays the clip. `autoplay` is written as `data-autoplay`, so an+ exported file never makes another renderer obey what this app records and+ refuses.+- **Colour keeps its raw-html export.** `<span class="sp-fg-red">` renders as+ clean text on GitHub and in Obsidian. Pandoc's `[x]{color=red}` would print+ its brackets there. The importer also accepts `[x]{color=…}` and `{bg=…}`,+ palette names only.+- **Ids are written only where something points**, at a comment anchor or a+ `#p/<page>/<block>` target, so a space with neither exports exactly as it+ did before. That is asserted against a pinned pre-change export. On import+ an id already used in the note, in the import or in the target space is+ replaced, and ids matching an `Object.prototype` name are refused.++**Import is an untrusted path, and none of this widened it.** No html+attribute is copied by name. Urls pass the same allowlists as the editor, and+fences go through `JSON.parse` and never `eval`. A fence cannot set `id`,+`type`, `parent`, `html` or `comments`, and a malformed fence stays a code+block. Block `html` still goes through `sanitizeInline` in the importer.++**Reserved for features not yet on main** (math `$…$`/`$$…$$`, a+`` ```mermaid `` fence, `` ```chart bar `` over a table or CSV,+`![[Page]]`/`![[Page#Section]]`, GFM footnotes, `:::columns`/`:::hero`/`:::card`):+the syntax is fixed in `docs/spaces-agents.md` so the branches that ship them+agree with each other and with this importer.diff --git a/docs/spaces-agents.md b/docs/spaces-agents.mdindex f9c5fe6d..c27db621 100644--- a/docs/spaces-agents.md+++ b/docs/spaces-agents.md@@ -238,6 +238,69 @@ never becomes a reference.Markdown import and export both speak `[^1]` and `[^1]: the note.`, so anObsidian or Pandoc vault keeps its footnotes in both directions.+## Markdown in and out++"Download as Markdown" writes every page as one `.md` file, and "Import+Markdown" reads `.md` files, a folder of them or an Obsidian vault. For every+block type except `prop`, a block that goes out comes back as the same block,+with the same JSON apart from its id and the same text on the next export+(`scripts/test-spaces-md-strict.ts` holds that bar type by type). You can+write these forms by hand or generate them, and they are what this app reads.++The rule behind every choice: **use a syntax other Markdown tools already+read**, so the file still makes sense on GitHub, in Obsidian and in a plain+editor. Invent syntax only where nothing exists, and then use a fenced block,+which everything else shows as code.++| block | Markdown |+|---|---|+| `p`, `h1`–`h3`, lists, `todo`, `quote`, `code`, `divider` | CommonMark / GFM, as you would write it |+| `table` | a GFM pipe table; an empty header row means `header: false` |+| `callout` | a GitHub alert, `> [!WARNING]`, with the body inside the blockquote |+| `toggle` | `<details open>` (or `<details>` when folded), `<summary>text</summary>`, the children, then `</details>` |+| `image` | `{width=60% w=640 h=300}`. The size is a Pandoc attribute list: `width` is the column percentage (10–100), and `w`/`h` are the intrinsic pixels, both or neither |+| `link` | `[title](url) — description <!-- bento:card site="…" icon="…" image="…" -->`. The comment makes the line a card, and every renderer hides it. A lone link without it stays a paragraph |+| `media` | `<video src="…" controls loop muted poster="…" title="alt" width="…" height="…" data-width="…" data-caption="…" data-autoplay><a href="…">alt</a></video>`, or `<audio …>` |+| `pagelink` | `[[Page title]]` alone on its line |+| `view` | a fence `` ```bento-view `` holding ONE JSON line, `{"name":"Issues","layout":"board","groupBy":"status"}`, which may be followed by `//` lines (ignored) |+| `canvas` | a fence `` ```bento-canvas `` holding `{"name":"Map","ratio":1.6,"cards":[[40,60],null]}`, then the cards as the next blocks at the same level, one per `cards` entry |+| `prop` | `**Status:** In progress`, which comes back as a paragraph. Fields will move to front matter |++Inline marks: `**bold**`, `*italic*`, `***both***`, `~~strike~~`,+`` `code` ``, `==highlight==`, and `<u>`, `<sub>` and `<sup>` as raw html.+A palette colour is raw `<span class="sp-fg-red">` or+`<mark class="sp-bg-yellow">`, and on import the Pandoc forms+`[words]{color=red}` and `[words]{bg=yellow}` also work. Only the nine+palette names count: gray, brown, orange, yellow, green, blue, purple, pink+and red.++**Block ids.** ` {#id}` at the end of a block's line (for a fence, on its+opening line; for a toggle, on the `<details>` line) gives the block that id.+The exporter writes one only on blocks that something points at: a comment+thread, or a `#p/<page>/<block>` link. On import an id that is already used,+in the note, in the import or in the space, is replaced with a fresh one.+Tables and dividers never carry an id.++**Everything imported is untrusted.** Links, clip sources, posters and card+thumbnails go through the same allowlists as the editor: `https:`, `http:` and+`mailto:` for links; `asset:`, an inline file of the right kind or `http(s)`+for media; and never `javascript:`, svg data or a relative path for a player.+No attribute is copied from html by name. Fences are read with `JSON.parse`,+and a fence cannot set `id`, `type`, `parent`, `html` or `comments`.++### Reserved syntax, for features not yet on main++These features exist only on unmerged branches. When they land, their+Markdown form is this one, so every branch reads the same file the same way:++| feature | Markdown | why |+|---|---|---|+| math | `$…$` inline, `$$…$$` on its own lines for a display block | what GitHub, Obsidian, Pandoc and KaTeX-based tools read |+| diagram | a `` ```mermaid `` fence holding the source | GitHub and Obsidian render it, and it is a `code` block with `lang: "mermaid"` today, so nothing changes in the format |+| chart | `` ```chart bar `` (or `line`, `pie` …), holding a GFM table or CSV of the data | everything else shows the data as a readable table. The chart type is the word after `chart` |+| transclusion | `![[Page]]`, or `![[Page#Section]]` for part of a page, alone on its line | Obsidian's embed. `![[picture.png]]` stays an image |+| footnotes | `[^1]` in the text and `[^1]: the note.` below | GFM footnotes, which GitHub renders |+| layout | `:::columns`, `:::hero` and `:::card` fenced divs, closed by `:::` | Pandoc and markdown-it-container read them, and anything else shows the markers as text around readable content |## The issue trackerdiff --git a/scripts/test-spaces-md-strict.ts b/scripts/test-spaces-md-strict.tsindex 2ee910fd..9b532f11 100644--- a/scripts/test-spaces-md-strict.ts+++ b/scripts/test-spaces-md-strict.ts@@ -30,11 +30,11 @@// 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 { parseNote, planImport, resolvePageLinks } 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'+import { type Block, type Page, type SpacesDoc, defaultTheme, writeTable, linkCard, linkCardHtml } from '../spaces/src/model.ts'let checks = 0let failures = 0@@ -79,11 +79,11 @@ const FIX: Record<string, () => Fixture> = {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"' })] }),+ // alt, src, caption — `` — and the size as a Pandoc+ // attribute list, `{width=80% w=640 h=300}`+ image: () => ({ blocks: [b('image', '', { src: 'asset:abc', alt: 'A diagram', caption: 'Drawn, not "photographed"', width: 80, w: 640, h: 300 })] }),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' })] }),+ link: () => ({ blocks: [b('link', '<a href="https://bento.page">Bento</a> — desc', { url: 'https://bento.page', title: 'Bento', desc: 'desc', site: 'bento.page', icon: '🍱', image: 'asset:thumb' })] }),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: () => {@@ -92,23 +92,22 @@ const FIX: Record<string, () => Fixture> = {return { blocks: [t] }},view: () => ({- blocks: [b('view', 'Issues', { layout: 'board', groupBy: 'status' })],+ blocks: [b('view', 'Open <em>issues</em>', { layout: 'board', groupBy: 'status', filter: { is: { status: ['todo', 'doing'] } }, sort: { key: 'status', dir: 'desc' } })],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 })] } },+ canvas: () => {+ const c = b('canvas', 'Roadmap', { ratio: 1 })+ const three = b('bullet', 'card three, a list', { parent: c.id, x: 12.5, y: 0 })+ 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 }),+ three, b('bullet', 'its own child', { parent: three.id }), b('p', 'card four, placed by slot', { parent: c.id }), b('p', 'after the canvas')] }+ },}// 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 --------------------------------------------------------@@ -121,6 +120,8 @@ function strip(blocks: Block[]): unknown[] {return parent === undefined ? rest : { ...rest, parent: `#${pos.get(parent) ?? parent}` }})}+/** a block carrying one review thread — what makes an id worth exporting */+const on2 = (x: Block): Block => Object.assign(x, { comments: [{ id: 'c', author: 'A', at: '2026-09-26T00:00:00Z', text: 't' }] })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]]))@@ -144,6 +145,10 @@ function trip(fx: Fixture): Trip {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+ // `[[Title]]` page links resolve once every page exists — planImport's job,+ // done here against the fixture's own pages by title+ const byTitle = new Map([{ id: PAGE, title: TITLE }, ...extra].map((p) => [p.title.toLowerCase(), p.id]))+ resolvePageLinks(back, (target) => byTitle.get(target.toLowerCase()))return { md, md2: exportOf(back), inJson: canon(strip(fx.blocks)), outJson: canon(strip(back)), back }}@@ -182,6 +187,38 @@ for (const type of Object.keys(FIX)) {const expected = types.length - Object.keys(PINNED).lengthok(exact === expected, `${exact} of ${types.length} block types are byte-identical (expected ${expected}; ${Object.keys(PINNED).length} pinned)`)+// ---- a space with none of the lossless-family shapes -------------------------+// Every family below (toggles, sized images, cards, media, page links, views,+// canvases, block ids) changes how ITS OWN block exports. A space that has none+// of them must export exactly as it did before any family existed — byte for+// byte, marks and all — so a README someone keeps in git does not churn+// because the exporter learned a shape the document never used. The expected+// text was captured from the exporter BEFORE the first family landed.++console.log('\na space without any family shape exports byte-identically to before')+{+ const t = b('table', '')+ writeTable(t, { rows: [['A', 'B'], ['1', '<strong>2</strong>']], cols: [1, 1], colAlign: ['', 'right'], header: true })+ const blocks = [+ { id: 'g1', type: 'p', html: 'Plain <strong>bold</strong> <em>em</em> <u>u</u> <s>s</s> <sub>2</sub> <sup>3</sup> <code>c</code> <mark>hi</mark> <a href="https://x.y/z">link</a> and a <a href="#p/pg2">page link</a>.' },+ { id: 'g2', type: 'h1', html: 'One' }, { id: 'g3', type: 'h2', html: 'Two' }, { id: 'g4', type: 'h3', html: 'Three' },+ { id: 'g5', type: 'bullet', html: 'a' }, { id: 'g6', type: 'bullet', html: 'b', parent: 'g5' },+ { id: 'g7', type: 'number', html: 'n' }, { id: 'g8', type: 'todo', html: 't', done: true },+ t,+ { id: 'g10', type: 'callout', html: 'Careful', tone: 'warning' }, { id: 'g11', type: 'p', html: 'inside', parent: 'g10' },+ { id: 'g12', type: 'quote', html: 'q<br>r' },+ { id: 'g13', type: 'code', html: 'x < 1', lang: 'js' },+ { id: 'g14', type: 'divider', html: '' },+ { id: 'g15', type: 'image', html: '', src: 'asset:k', alt: 'alt', caption: 'cap' },+ { id: 'g16', type: 'p', html: '<span class="sp-fg-red">red</span> <mark class="sp-bg-blue">band</mark> Last {not an attribute} [bracket] ==text== line' },+ ] as Block[]+ const d = { ...doc([{ id: 'pg', title: 'Plain', blocks }, { id: 'pg2', title: 'Second', parent: 'pg', blocks: [b('p', 'child page')] }]), docId: 'g', title: 'G' }+ const got = toMarkdown(new Store(d as never) as never)+ const want = "# Plain\n\nPlain **bold** *em* <u>u</u> ~~s~~ <sub>2</sub> <sup>3</sup> `c` ==hi== [link](https://x.y/z) and a [page link](#p/pg2).\n\n# One\n\n## Two\n\n### Three\n\n- a\n\n - b\n\n1. n\n\n- [x] t\n\n| A | B |\n| --- | ---: |\n| 1 | **2** |\n\n> [!WARNING]\n> Careful\n>\n> inside\n\n> q\n> r\n\n```js\nx < 1\n```\n\n---\n\n\n\n<span class=\"sp-fg-red\">red</span> <mark class=\"sp-bg-blue\">band</mark> Last {not an attribute} [bracket] ==text== line\n\n## Second\n\nchild page\n"+ ok(got === want, 'export of a plain space is byte-identical to the pre-family exporter',+ got === want ? undefined : `want:\n${want}\ngot:\n${got}`)+}+// ---- the shapes one fixture per type does not reach -------------------------console.log('\ncallouts: every tone, and a body that is more than one paragraph')@@ -220,16 +257,355 @@ console.log('\nquotes and images at their edges')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.+console.log('\nimage sizes: {width=N% w= h=}')+{+ const t = trip({ blocks: [b('image', '', { src: 'asset:abc', width: 62.5 }), b('image', '', { src: 'asset:d', alt: 'only px', w: 12, h: 34 })] })+ ok(qualifies(t) && t.md.includes('{width=62.5%}') && t.md.includes('{w=12 h=34}'),+ 'a fractional width alone, and pixels alone, each round-trip', qualifies(t) ? undefined : why(t))+}+{+ const t = trip({ blocks: [b('image', '', { src: 'asset:x', width: 'wide', w: 'x', h: 3 } as never)] })+ ok(!/\{/.test(t.md), 'a size field holding a non-number is not written', t.md)+}+{+ const got = only('- {width=40%}\n')+ ok(got[0]?.type === 'image' && got[0].width === 40, 'a sized image as a list item keeps its size', JSON.stringify(got))+}+{+ const got = only('{width=30% w=100}\n{width=5%}\n{width=300px height=200}\n')+ ok(got.length === 3 && got[0].width === 30 && got[0].w === undefined && got[1].width === undefined && got[2].width === undefined && got[2].w === undefined,+ 'Pandoc-flavoured sizes outside the model (one of w/h, under 10%, px widths) are ignored, the image kept', JSON.stringify(got))+}+{+ const hostile = [+ '{width="><script>alert(1)</script>"}',+ '{width=100% onerror=alert(1) style="background:url(//t.invalid)"}',+ '{width=javascript:alert(1)}',+ '{width=50% w=1e9 h=-1}',+ '{width=50%" onload="alert(1)}',+ ]+ for (const line of hostile) {+ const got = only(`${line}\n`)+ const all = JSON.stringify(got)+ const img = got.find((x) => x.type === 'image')+ const keys = img ? Object.keys(img).filter((k) => !['id', 'type', 'html', 'src', 'alt', 'width'].includes(k)) : []+ ok(!/onerror|onload|style|javascript/i.test(Object.keys(img ?? {}).join(' ')) && keys.length === 0 &&+ (img?.width === undefined || img.width === 100 || img.width === 50) && !/<script/i.test(img?.alt ?? ''),+ `HOSTILE size: ${line} — no key but a validated width reaches the block`, all)+ }+}++console.log('\nlink cards: [title](url) — desc <!-- bento:card … -->')+{+ const card = (f: Record<string, unknown>) => {+ const x = b('link', '', f)+ x.html = linkCardHtml(linkCard(x))+ return x+ }+ const t = trip({ blocks: [+ card({ url: 'https://x.y/a b(c)', title: 'Tricky [title] with \\ and -- dashes', desc: 'says "hi" --> <b>not a tag</b>', site: 'x--y "site" >' }),+ card({ title: 'No url here', desc: 'still a card' }),+ card({ url: 'https://only.url/' }),+ card({ url: 'mailto:[email protected]', title: 'Mail', image: 'data:image/png;base64,iVBORw0KGgo=' }),+ ] })+ ok(qualifies(t), 'brackets, backslashes, dashes, quotes and a --> in the fields; a card with no url; an untitled one; a small data: thumbnail',+ qualifies(t) ? undefined : why(t))+ ok(t.md.split('\n').filter((l) => l.includes('<!-- bento:card')).every((l) => {+ const c = l.slice(l.lastIndexOf('<!-- bento:card') + 4)+ return c.indexOf('--') === c.length - 3 && !/[<>]/.test(c.slice(0, -1))+ }), 'no field can close or nest the marker comment: its only `--` is the closing one', t.md)+}+{+ // THE PINNED LOSS: a large data: thumbnail is left out of the export+ const big = `data:image/png;base64,${'A'.repeat(4000)}`+ const x = b('link', '', { url: 'https://big.img/', title: 'Big', image: big })+ x.html = linkCardHtml(linkCard(x))+ const t = trip({ blocks: [x] })+ ok(!t.md.includes('AAAA') && t.back[0]?.type === 'link' && t.back[0].image === undefined,+ 'pinned: a data: thumbnail over CARD_IMAGE_MD_BUDGET does not leave (the card does, without it)', t.md)+}+{+ const got = only('[Docs](https://example.com) — the manual\n\n[Just a link](https://example.com)\n')+ ok(got.length === 2 && got.every((x) => x.type === 'p'), 'an UNMARKED lone link stays a paragraph', JSON.stringify(got))+}+{+ const hostile: Array<[string, (x: Block[]) => boolean]> = [+ ['[Click](javascript:alert(1)) <!-- bento:card -->', (x) => x[0]?.type === 'link' && x[0].url === undefined && !/javascript/i.test(x[0].html ?? '')],+ ['[Click]( JAVASCRIPT:alert(1)) <!-- bento:card -->', (x) => x[0]?.url === undefined && x[0]?.title === 'Click' && !/javascript/i.test(JSON.stringify(x))],+ ['[x](https://ok.example) <!-- bento:card image="https://tracker.invalid/p.png" -->', (x) => x[0]?.type === 'link' && x[0].image === undefined],+ ['[x](https://ok.example) <!-- bento:card image="data:image/svg+xml;base64,PHN2Zz4=" -->', (x) => x[0]?.image === undefined],+ ['[x](https://ok.example) <!-- bento:card image="javascript:alert(1)" onload="alert(1)" -->', (x) => x[0]?.image === undefined && !('onload' in (x[0] ?? {}))],+ ['[x](https://ok.example) <!-- bento:card site="a" --> <script>alert(1)</script> <!-- bento:card -->', (x) => !/<script/i.test(JSON.stringify(x))],+ ['[x](https://ok.example) <!-- bento:card site="<img src=x onerror=alert(1)>" -->', (x) => !/<img/i.test(JSON.stringify(x))],+ ['[x](https://ok.example) <!-- bento:card site="<img src=x onerror=alert(1)>" -->', (x) => x[0]?.type === 'link' && x[0].site === '<img src=x onerror=alert(1)>' && !/<img/i.test(x[0].html ?? '')],+ ['[x](https://ok.example) <!-- bento:other site="evil" -->', (x) => x[0]?.type === 'p'],+ ]+ for (const [line, fine] of hostile) {+ const got = only(`${line}\n`)+ ok(fine(got), `HOSTILE card: ${line}`, JSON.stringify(got))+ }+}++console.log('\nmedia: <video>/<audio> with a link inside')+{+ const t = trip({ blocks: [+ b('media', '', { kind: 'video', src: 'https://v.example/a%20b.mp4?x=1&y=2', alt: 'The <demo> & more', caption: 'A <strong>caption</strong>', poster: 'asset:still',+ controls: false, loop: true, muted: true, autoplay: true, width: 75, w: 1280, h: 720 }),+ b('media', '', { kind: 'audio', src: 'data:audio/mpeg;base64,SUQz', controls: true }),+ ] })+ ok(qualifies(t), 'a video carrying every field (controls off, loop, muted, autoplay, poster, sizes, caption) and an embedded audio clip',+ qualifies(t) ? undefined : why(t))+ ok(!/\sautoplay[\s>=]/.test(t.md) && t.md.includes('data-autoplay'),+ 'autoplay is recorded as data-autoplay, so no other renderer plays the clip on the author\'s behalf', t.md)+ ok(/<a href="[^"]+">The <demo> & more<\/a><\/video>/.test(t.md),+ 'the element holds a link to the clip: a renderer that strips <video> still shows the old export', t.md)+}+{+ const got = only('<video controls width="640" height="360">\n <source src="https://example.com/demo.mp4" type="video/mp4">\n Your browser does not play video.\n</video>\n\nAfter.\n')+ ok(got.length === 2 && got[0].type === 'media' && got[0].src === 'https://example.com/demo.mp4' && got[0].controls === true &&+ got[0].w === 640 && got[1].html === 'After.', 'README: a multi-line <video> with a <source> child', JSON.stringify(got))+}+{+ const got = only('<audio src="https://example.com/a.mp3" autoplay></audio>\n')+ ok(got[0]?.type === 'media' && got[0].kind === 'audio' && got[0].autoplay === true && got[0].controls === false,+ 'a real autoplay is recorded (and mediaPlayback never obeys it)', JSON.stringify(got))+}+{+ const hostile: Array<[string, (x: Block[]) => boolean]> = [+ ['<video src="javascript:alert(1)" controls><a href="javascript:alert(1)">x</a></video>', (x) => x[0]?.type === 'p' && x[0].src === undefined && /<code>javascript:alert\(1\)<\/code>/.test(x[0].html ?? '')],+ ['<video src=" JAVASCRIPT:alert(1)"></video>', (x) => x[0]?.type === 'p'],+ ['<audio src="file:///etc/passwd"></audio>', (x) => x[0]?.type === 'p'],+ ['<video src="clip.mp4"></video>', (x) => x[0]?.type === 'p' && (x[0].html ?? '').includes('<code>clip.mp4</code>')],+ ['<video src="https://ok.example/a.mp4" onerror="alert(1)" onloadstart=alert(2) style="x:url(//t.invalid)" poster="javascript:alert(3)"></video>',+ (x) => x[0]?.type === 'media' && x[0].poster === undefined && !/alert|onerror|style/i.test(JSON.stringify(x))],+ ['<video src="https://ok.example/a.mp4" poster="data:image/svg+xml;base64,PHN2Zz4="></video>', (x) => x[0]?.type === 'media' && x[0].poster === undefined],+ ['<video src="https://ok.example/a.mp4" data-caption="<img src=x onerror=alert(1)>"></video>',+ (x) => x[0]?.type === 'media' && x[0].caption === '<img src=x onerror=alert(1)>'],+ ['<video src="https://ok.example/a.mp4"><script>alert(1)</script></video>', (x) => x[0]?.type === 'media' && !/script/i.test(JSON.stringify(x))],+ ['<video src="https://ok.example/a.mp4">', (x) => x.every((y) => y.type === 'p') && !/<video/i.test(JSON.stringify(x))],+ ]+ for (const [line, fine] of hostile) {+ const got = only(`${line}\n`)+ ok(fine(got), `HOSTILE media: ${line}`, JSON.stringify(got))+ }+}++console.log('\ninline marks: every mark the model has, exported and read back')+{+ const MARKS: Array<[string, string]> = [+ ['strong', 'a <strong>bold</strong> word'],+ ['em', 'an <em>emphasised</em> word'],+ ['u', 'an <u>underlined</u> word'],+ ['s', 'a <s>struck</s> word'],+ ['sub', 'H<sub>2</sub>O'],+ ['sup', 'x<sup>2</sup>'],+ ['code', 'some <code>code</code> here'],+ ['a', 'a <a href="https://x.y/?a=1&b=2">link</a> here'],+ ['mark (plain highlight, ==x==)', 'a <mark>highlighted</mark> word'],+ ['span (ink colour)', 'a <span class="sp-fg-red">red</span> word'],+ ['mark (band colour)', 'a <mark class="sp-bg-yellow">banded</mark> word'],+ ['nested marks', '<a href="https://x.y"><mark><span class="sp-fg-blue"><strong><em>all</em></strong></span></mark></a> of them'],+ ]+ for (const [name, html] of MARKS) {+ const t = trip({ blocks: [b('p', html)] })+ ok(qualifies(t), `${name}: byte-identical`, qualifies(t) ? undefined : why(t))+ }+ const hi = trip({ blocks: [b('p', 'a <mark>highlighted</mark> word')] })+ ok(hi.md.trim() === 'a ==highlighted== word', 'a plain highlight is written ==x==, Obsidian\'s spelling', hi.md)+}+{+ const got = only('[ink]{color=red} [band]{bg=yellow} [both]{color=blue bg=green}\n')+ ok(got[0]?.html === '<span class="sp-fg-red">ink</span> <mark class="sp-bg-yellow">band</mark> <mark class="sp-bg-green"><span class="sp-fg-blue">both</span></mark>',+ 'Pandoc spans with palette colours read as the palette marks', JSON.stringify(got))+}+{+ const cases = [+ '[x]{color=coral}',+ '[x]{color="red;background:url(//t.invalid)"}',+ '[x]{bg=red onclick=alert(1)}',+ '[x]{color=red .evil}',+ '[x]{#id color=red}',+ '[x]{color=sp-fg-red}',+ '[x]{color=__proto__}',+ '[x]{color=toString}',+ ]+ for (const src of cases) {+ const got = only(`${src}\n`)+ ok(got.length === 1 && !/class=|<span|<mark/.test(got[0].html ?? ''),+ `HOSTILE colour: ${src} stays text, and no class is minted`, JSON.stringify(got))+ }+}++console.log('\npage links, views and canvases')+{+ const others: Page[] = [{ id: 'o1', title: 'Other page', blocks: [b('p', 'x')] }, { id: 'o2', title: 'Odd [title] | here', blocks: [b('p', 'y')] }]+ const t = trip({ blocks: [b('pagelink', '', { page: 'o1' }), b('pagelink', '', { page: 'o2' }), b('pagelink', '', { page: 'gone' })], extraPages: others })+ ok(t.back[0]?.type === 'pagelink' && t.back[0].page === 'o1' && t.md.startsWith('[[Other page]]\n'),+ 'a page link is `[[Title]]` alone on its line, and resolves to the page', why(t))+ ok(t.back[1]?.type === 'p' && t.back[2]?.type === 'p' && t.md.includes('→ [[?]]'),+ 'pinned: a title a wikilink cannot spell, and a missing page, keep the old `→ [[…]]` paragraph', why(t))+}+{+ const plan = planImport([{ path: 'v/A.md', text: '[[B]]\n\n[[Home]]\n\n[[Missing]]\n' }, { path: 'v/B.md', text: 'bee\n' }],+ { rootTitle: 'R', resolveExisting: (k) => (k === 'home' ? 'existing-home' : undefined) })+ const a = plan.pages.find((p) => p.title === 'A')!+ const bId = plan.pages.find((p) => p.title === 'B')!.id+ ok(a.blocks[0].type === 'pagelink' && a.blocks[0].page === bId && a.blocks[1].page === 'existing-home' &&+ a.blocks[2].type === 'p' && plan.stats.linked === 2 && plan.stats.dangling === 1,+ 'planImport resolves a lone [[link]] to a page in the import, then to one the space already has, and counts a miss', JSON.stringify(a.blocks))+}+{+ const got = only('[[Nowhere]]\n\n[[A|alias]]\n\nSee [[B]] inline.\n')+ resolvePageLinks(got, () => undefined)+ ok(got.map((x) => x.type).join(' ') === 'p p p' && got[0].html === '[[Nowhere]]',+ 'an unresolved lone link, an aliased one and an inline one are all paragraphs', JSON.stringify(got))+}+{+ const view = (body: string) => only('```bento-view\n' + body + '\n```\n')[0]+ const hostile: Array<[string, (x: Block) => boolean]> = [+ ['{"name":"x","id":"evil","type":"p","parent":"p1","html":"<img src=x onerror=alert(1)>","comments":[{"text":"x"}]}',+ (x) => x.type === 'view' && x.id !== 'evil' && x.parent === undefined && x.html === 'x' && x.comments === undefined],+ ['{"name":"<img src=x onerror=alert(1)>"}', (x) => x.type === 'view' && !/<img/i.test(x.html ?? '')],+ ['{"__proto__":{"polluted":1},"constructor":{"x":1},"layout":"list"}',+ (x) => x.type === 'view' && x.layout === 'list' && ({} as Record<string, unknown>).polluted === undefined && !Object.hasOwn(x, 'constructor')],+ ['not json at all', (x) => x.type === 'code' && x.lang === 'bento-view'],+ ['{"a":1}\n{"b":2}', (x) => x.type === 'code'],+ ['[1,2,3]', (x) => x.type === 'code'],+ ['{"name":"x","layout":"toString"}', (x) => x.type === 'view' && x.layout === 'toString'],+ ]+ for (const [body, fine] of hostile) {+ const got = view(body)+ ok(!!got && fine(got), `HOSTILE view fence: ${body.slice(0, 70)}`, JSON.stringify(got))+ }+ const cv = only('```bento-canvas\n{"name":"C","cards":[[1,2],"x",[1e999,3],[4,5,6]]}\n```\n\na\n\nb\n\nc\n\nd\n\ne\n')+ ok(cv[0].type === 'canvas' && cv.slice(1, 5).every((x) => x.parent === cv[0].id) && cv[5].parent === undefined &&+ cv[1].x === 1 && cv[2].x === undefined && cv[3].x === undefined && cv[4].x === undefined,+ 'HOSTILE canvas positions: only [finite, finite] pairs place a card; the count still claims its cards', JSON.stringify(cv))+}++console.log('\nblock ids: {#id} on the blocks something points at')+{+ // A thread on every type that can carry an id; the export writes `{#id}` for+ // exactly those, and the import gives each block back its own id.+ const thread = [{ id: 'c1', author: 'A', at: '2026-09-26T00:00:00Z', text: 'look' }]+ const on = (x: Block): Block => Object.assign(x, { comments: thread })+ const li = on(b('bullet', 'a point'))+ const tg = on(b('toggle', 'fold', { open: true }))+ const cv = on(b('canvas', 'Map'))+ const blocks: Block[] = [+ on(b('h2', 'A heading')), on(b('p', 'two<br>lines')), li, on(b('bullet', 'its child', { parent: li.id })),+ on(b('todo', 'do it', { done: false })), on(b('callout', 'boxed', { tone: 'note' })), on(b('callout', '', { tone: 'tip' })),+ on(b('quote', 'said<br>twice')), on(b('code', 'x = 1', { lang: 'py' })), tg, on(b('p', 'folded', { parent: tg.id })),+ on(b('image', '', { src: 'asset:i', width: 50 })), on(b('media', '', { kind: 'audio', src: 'asset:a' })),+ on(b('link', '<a href="https://x.y">X</a>', { url: 'https://x.y', title: 'X' })),+ on(b('pagelink', '', { page: 'o1' })), on(b('view', 'Issues', { layout: 'list' })),+ cv, on(b('p', 'a card', { parent: cv.id, x: 5, y: 5 })),+ b('p', 'no thread, no id'),+ ]+ const t = trip({ blocks, extraPages: [{ id: 'o1', title: 'Other', blocks: [b('p', 'x')] }] })+ const want = blocks.map((x) => x.id)+ const got = t.back.map((x) => x.id)+ ok(t.back.length === blocks.length && want.slice(0, -1).every((id, k) => got[k] === id) && got.at(-1) !== want.at(-1),+ 'every anchored block comes back with ITS id, and an unanchored one does not export one', `want ${want.join(' ')}\ngot ${got.join(' ')}\n${t.md}`)+ ok(t.back[3].parent === li.id && t.back[10].parent === tg.id && t.back[17].parent === cv.id,+ '…and children point at the renamed parents (list, fold, canvas)', JSON.stringify(t.back.map((x) => [x.id, x.parent])))+ // THE THREADS THEMSELVES DO NOT TRAVEL: Markdown has no comments, so the+ // second export has nothing anchored and writes no ids. What the trip keeps+ // is the id, which is what a thread (or a later re-import) re-attaches by.+ ok(t.md2 === t.md.replace(/ \{#[^}]+\}/g, ''), '…and the second export is the first without the ids (the threads stayed home)', why(t))+ ok(!/\{#/.test(t.md.split('\n').filter((l) => l.includes('no thread')).join('')), 'a block nothing points at carries no id')+}+{+ const target = b('p', 'linked to')+ const t = trip({ blocks: [b('p', `see <a href="#p/${PAGE}/${target.id}">there</a>`), target] })+ ok(t.md.includes(`linked to {#${target.id}}`) && t.back[1].id === target.id,+ 'a #p/<page>/<block> link makes its target carry {#id}', t.md)+}+{+ const t = trip({ blocks: [on2(b('table', '')), on2(b('divider'))] })+ ok(!/\{#/.test(t.md), 'pinned: a table and a divider never carry {#id} (a row or a rule would break)', t.md)+}+{+ const got = only('one {#dup-1}\n\ntwo {#dup-1}\n')+ ok(got[0].id === 'dup-1' && got[1].id !== 'dup-1' && got[1].html === 'two',+ 'a duplicated block (same {#id} twice in a note) keeps its words; only the first keeps the id', JSON.stringify(got))+}+{+ const plan = planImport([{ path: 'n/A.md', text: 'alpha {#b-shared}\n\n- item {#b-mine}\n - child\n' }, { path: 'n/B.md', text: 'beta {#b-shared}\n' }],+ { rootTitle: 'R', idTaken: (id) => id === 'b-mine' })+ const a = plan.pages.find((p) => p.title === 'A')!.blocks+ const bb = plan.pages.find((p) => p.title === 'B')!.blocks+ ok(a[0].id === 'b-shared' && bb[0].id !== 'b-shared', 'across notes: the first note keeps a shared id, the second is renamed', JSON.stringify([a, bb]))+ ok(a[1].id !== 'b-mine' && a[2].parent === a[1].id, 'an id the space already uses is renamed, and its children follow it', JSON.stringify(a))+}+{+ for (const src of ['x {#__proto__}', 'x {#constructor}', 'x {#"><script>alert(1)</script>}', 'x {#1abc}', 'x {#a b}', `x {#${'a'.repeat(80)}}`]) {+ const got = only(`${src}\n`)+ ok(got.length === 1 && got[0].id.startsWith('b-') && !/<script/i.test(got[0].html ?? ''),+ `HOSTILE id: ${src.slice(0, 50)} is not taken as an id`, JSON.stringify(got))+ }+}++console.log('\ntoggles: <details>, open or folded, holding anything')+{+ const t = trip({ blocks: [b('toggle', 'Open one', { open: true }), b('toggle', 'Shut one', { open: false })] })+ ok(qualifies(t) && t.md.includes('<details open>') && t.md.includes('<details>\n'),+ 'an open and a folded toggle keep their state, and an empty one closes at once', qualifies(t) ? undefined : why(t))+}+{+ const outer = b('toggle', 'Outer & more', { open: true })+ const inner = b('toggle', 'Inner <strong>bold</strong>', { open: false, parent: outer.id })+ const li = b('bullet', 'a point', { parent: inner.id })+ const t = trip({ blocks: [outer, inner, b('p', 'deep', { parent: inner.id }), li, b('bullet', 'under it', { parent: li.id }),+ b('p', 'back in outer', { parent: outer.id }), b('p', 'outside')] })+ ok(qualifies(t), 'a toggle in a toggle, holding a paragraph and a nested list, then prose after both', qualifies(t) ? undefined : why(t))+}+{+ const c = b('callout', 'Box', { tone: 'tip' })+ const tg = b('toggle', 'Fold in a box', { open: true, parent: c.id })+ const t = trip({ blocks: [c, tg, b('p', 'folded words', { parent: tg.id }), b('p', 'still in the box', { parent: c.id }), b('p', 'out')] })+ ok(qualifies(t), 'a toggle inside a callout closes inside the blockquote', qualifies(t) ? undefined : why(t))+}+{+ const tg = b('toggle', 'Holds a box', { open: false })+ const c = b('callout', 'Boxed', { tone: 'note', parent: tg.id })+ const t = trip({ blocks: [tg, c, b('p', 'box body', { parent: c.id }), b('p', 'after')] })+ ok(qualifies(t), 'a callout inside a toggle', qualifies(t) ? undefined : why(t))+}+{+ const tg = b('toggle', 'Code inside', { open: true })+ const t = trip({ blocks: [tg, b('code', 'x = 1\n\ny = 2', { lang: 'py', parent: tg.id })] })+ ok(qualifies(t), 'a code block with a blank line inside a toggle', qualifies(t) ? undefined : why(t))+}++console.log('\ntoggles written elsewhere, and hostile ones')+{+ // the shape GitHub's own docs show, summary indented on its own line+ const got = only('<details>\n <summary>Click to expand</summary>\n\n ### Heading\n 1. Foo\n 2. Bar\n\n</details>\n\nAfter.\n')+ ok(got.map((x) => `${x.type}${x.parent === got[0].id ? '^' : ''}`).join(' ') === 'toggle h3^ number^ number^ p' &&+ got[0].html === 'Click to expand' && got[0].open === false,+ 'GitHub: a folded <details> with an indented summary holds its heading and list', JSON.stringify(got))+}+{+ const got = only('<details><summary><b>Why?</b></summary>Because.</details>\n\nNext.\n')+ ok(got.map((x) => `${x.type}${x.parent === got[0]?.id ? '^' : ''}`).join(' ') === 'toggle p^ p' &&+ got[0].html === '<b>Why?</b>' && got[1].html === 'Because.',+ 'a one-line <details><summary>…</summary>body</details>', JSON.stringify(got))+}+{+ const got = only('<details open>\n<summary>Unclosed</summary>\n\nbody\n')+ ok(got.length === 2 && got[0].type === 'toggle' && got[0].open === true && got[1].parent === got[0].id,+ 'a <details> never closed holds the rest of the note', JSON.stringify(got))+}+{+ const got = only('</details>\n\ntext\n')+ ok(got.length === 1 && got[0].type === 'p' && got[0].html === 'text', 'a stray </details> is dropped', JSON.stringify(got))+}{- 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')+ const got = only('<details onclick="alert(1)" ontoggle=alert(2) title="open"><summary onmouseover="alert(3)">Hi <img src=x onerror=alert(4)></summary>\n\nbody\n\n</details>\n')+ const all = JSON.stringify(got)+ ok(got[0]?.type === 'toggle' && got[0].open === false && !/alert|onclick|ontoggle|onmouseover|onerror|<img/i.test(all),+ 'HOSTILE: <details onclick ontoggle> and <summary onmouseover> carry no attribute or tag into the block, and `title="open"` is not the open flag', all)}// ---- Markdown this app did not write ----------------------------------------diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.tsindex 2a283a1b..2f6c661e 100644--- a/scripts/test-spaces-model.ts+++ b/scripts/test-spaces-model.ts@@ -2507,12 +2507,18 @@ function fsTable(f: string): string {{ id: 'p3', title: 'Third', group: 'Done', fields: '' },],}).join('\n')- ok(md.includes('[First](#p/p1)') && md.includes('[Third](#p/p3)'),- 'a board exports its ISSUES, each one a link back to its page')- ok(md.includes('**Todo**') && md.includes('**Done**'), '…grouped as the board groups them')- ok(md.indexOf('**Todo**') < md.indexOf('**Done**'), '…in the board\'s column order')- ok(md.includes('[First](#p/p1) — High'), '…carrying the same chips the card shows')- ok(viewSpec.toMd!({ id: 'v', type: 'view' } as Block, 'Issues', '', ctx).join('\n').includes('_No issues._'),+ // A ```bento-view fence: the settings as one JSON line (what reads back as a+ // view), then the issues as `//` lines for a reader elsewhere — the fence's+ // round trip is held byte for byte in scripts/test-spaces-md-strict.ts+ ok(md.startsWith('```bento-view\n{"name":"Issues"}\n') && md.endsWith('\n```'),+ 'a board exports as a bento-view fence carrying its settings')+ ok(md.includes('// - First') && md.includes('// - Third'),+ 'a board exports its ISSUES, one readable line each')+ ok(md.includes('// Todo') && md.includes('// Done'), '…grouped as the board groups them')+ ok(md.indexOf('// Todo') < md.indexOf('// Done'), '…in the board\'s column order')+ ok(md.includes('// - First — High'), '…carrying the same chips the card shows')+ ok(!/^#/m.test(md), '…and no line of it starts with `#`, which a tool splitting at headings would cut on')+ ok(viewSpec.toMd!({ id: 'v', type: 'view' } as Block, 'Issues', '', { ...ctx, inline: (h: string) => h }).join('\n').includes('// No issues.'),'an empty board says so rather than exporting a bare heading')}@@ -2632,16 +2638,23 @@ function fsTable(f: string): string {ok(mediaPlayback({ id: 'x', type: 'media', kind: 'holo-tape' }).kind === 'video','a kind from a newer build degrades to video, which plays an audio file anyway')- // MARKDOWN HAS NO VIDEO. A link is the one form correct in every renderer;- // `` is image syntax and draws a broken-image glyph everywhere.+ // MARKDOWN HAS NO VIDEO. A clip leaves as the html element, holding a LINK:+ // a renderer that strips <video> keeps its content, which is the link this+ // block used to export as — and `` (image syntax, a broken+ // glyph everywhere) is still never written. The element's fields are held to+ // byte identity in scripts/test-spaces-md-strict.ts.const md = (b: Block): string =>- (SPEC.get('media')!.toMd!(b, '', '', { titleOf: () => undefined, rowsOf: () => [] })).join('\n')- ok(md({ id: 'x', type: 'media', src: 'asset:k1' }) === '[Video](asset:k1)',- 'a clip exports as a markdown LINK, not as an image')- ok(md({ id: 'x', type: 'media', kind: 'audio', src: 'https://h/x.mp3' }) === '[Audio](https://h/x.mp3)',+ (SPEC.get('media')!.toMd!(b, '', '', { titleOf: () => undefined, rowsOf: () => [], inline: (h: string) => h })).join('\n')+ const inner = (b: Block): string => /<a href="[^"]*">([^<]*)<\/a><\/(?:video|audio)>$/.exec(md(b))?.[1] ?? '(no link)'+ ok(/^<video src="asset:k1" controls><a href="asset:k1">Video<\/a><\/video>$/.test(md({ id: 'x', type: 'media', src: 'asset:k1' })),+ 'a clip exports as a <video> holding a markdown-safe LINK to it, never as an image')+ ok(/^<audio src="https:\/\/h\/x.mp3"/.test(md({ id: 'x', type: 'media', kind: 'audio', src: 'https://h/x.mp3' })) &&+ inner({ id: 'x', type: 'media', kind: 'audio', src: 'https://h/x.mp3' }) === 'Audio','…named for what it is')- ok(md({ id: 'x', type: 'media', src: 'asset:k1', alt: 'The demo' }) === '[The demo](asset:k1)',+ ok(inner({ id: 'x', type: 'media', src: 'asset:k1', alt: 'The demo' }) === 'The demo','…using alt as the label when there is one, exactly as the image exporter does')+ ok(!/ autoplay/.test(md({ id: 'x', type: 'media', src: 'asset:k1', autoplay: true })),+ '…and never with a live autoplay attribute, which another renderer would obey')ok(md({ id: 'x', type: 'media' }) === '_Video_','and a block with no source yet exports as a word, never as an empty link')@@ -2827,7 +2840,13 @@ function fsTable(f: string): string {// --- markdown: a link card is a link -------------------------------------const linkSpec = SPEC.get('link')!- const md = (b: Block) => linkSpec.toMd!(b, '', '', { titleOf: () => undefined, rowsOf: () => [] }).join('\n')+ const withMarker = (b: Block) => linkSpec.toMd!(b, '', '', { titleOf: () => undefined, rowsOf: () => [], inline: (h: string) => h }).join('\n')+ // the VISIBLE line; the trailing `<!-- bento:card … -->` that marks it as a+ // card (hidden by every renderer) is asserted on its own below and covered+ // field by field in scripts/test-spaces-md-strict.ts+ const md = (b: Block) => withMarker(b).replace(/ <!-- bento:card[^\n]*-->$/, '')+ ok(/ <!-- bento:card -->$/.test(withMarker(card({ url: 'https://a.b/x', title: 'Docs' }))),+ 'a card line ends in the bento:card marker comment, which is what makes it a card on the way back in')ok(md(card({ url: 'https://a.b/x', title: 'Docs' })) === '[Docs](https://a.b/x)','a link card exports as a markdown link')ok(md(card({ url: 'https://a.b/x', title: 'Docs', desc: 'The manual' })) === '[Docs](https://a.b/x) — The manual',@@ -3671,12 +3690,12 @@ function fsTable(f: string): string {ok(TAG_OF.canvas === 'div', 'a canvas is a div, like every other surface block')ok(!LIST_OF.canvas, 'a canvas is not a list item')- // ITS MARKDOWN IS ITS NAME. The cards follow as their own indented lines,- // because they are their own blocks — so `toMd` must NOT print them again.- const cvMd = cvSpec!.toMd!({ id: 'cv', type: 'canvas' } as Block, 'Launch plan', '', {} as never)- ok(cvMd.join('\n') === '**Launch plan**', 'a canvas exports as its name')- ok(cvSpec!.toMd!({ id: 'cv', type: 'canvas' } as Block, '', '', {} as never)[0] === '**Canvas**',- 'an unnamed canvas still says what it is rather than exporting a blank line')+ // ITS MARKDOWN IS A bento-canvas FENCE: its name, its settings and where each+ // card sits. The cards follow as their own lines, because they are their own+ // blocks — so `toMd` must NOT print them again.+ const cvMd = cvSpec!.toMd!({ id: 'cv', type: 'canvas' } as Block, 'Launch plan', '', { cardsOf: () => [[10, 20], null] } as never)+ ok(cvMd.join('\n') === '```bento-canvas\n{"name":"Launch plan","cards":[[10,20],null]}\n```',+ 'a canvas exports as a fence holding its name and its cards\' positions, and not the cards')// A CARD'S OWN WORDS TRAVEL, AS THEIR OWN LINE. mdLayout decides the two// decorations a block cannot decide for itself, and the one that matters here@@ -3687,7 +3706,7 @@ function fsTable(f: string): string {// which a plain text card's does not — so the assertion is on the quote.)const cvLay = mdLayout(cvPage.blocks)ok(cvLay[1].quote === '', 'a card is not swept into its canvas as a blockquote')- ok(cvLay[1].indent === ' ', "…and mdLayout reads it as its container's child")+ ok(cvLay[1].indent === '', "…and mdLayout writes it at the canvas's own level (the bento-canvas fence counts its cards)")}diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex a62fae2d..b14b04fb 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -995,6 +995,91 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.space, 6.5ms per page open, against 1.9ms for the backlink index the appalready built. A 100-page space is 1.3ms.+- **A toggle leaves as `<details>` and comes back a toggle.** It used to export+ as `- text` and return as a bullet, with its fold state gone and its contents+ loose. Now it is `<details open>` or `<details>`, then `<summary>`, then its+ contents as ordinary Markdown, then `</details>`. GitHub, Obsidian and any+ browser draw that as the same fold. The importer also reads `<details>` as+ GitHub READMEs write it: the summary on its own indented line, on one line+ with its body, or never closed. It takes one fact from the tag, whether it+ says `open`, and copies nothing else from it, so an `onclick` or `ontoggle`+ on it reaches nothing. A space with no toggles exports exactly as before, and+ the rig now checks that byte for byte.++- **An image keeps its size through Markdown.** The width you dragged, and the+ pixel size that holds its space while it loads, now follow the image as a+ Pandoc attribute list: `{width=60% w=640 h=300}`.+ Pandoc and markdown-it-attrs read that. GitHub and Obsidian show the braces+ as text after the picture, which only happens on a sized image. Only numbers+ are written and only validated numbers are read back: a width between 10% and+ 100%, and both pixel sizes or neither. Any other key or value is ignored and+ the image is kept.++- **A link card comes back a link card.** It still leaves as a link,+ `[title](url) — description`, followed by a comment,+ `<!-- bento:card site="…" image="…" -->`. GitHub, Obsidian and browsers+ hide the comment, so the page reads as the link and nothing else. The comment+ is what marks the line as a card, so a README line that happens to be a lone+ link stays a paragraph. It also carries the fields the visible line cannot:+ site, icon and thumbnail, plus title and description for a card with no+ address. Every field is checked on the way back in. The address must be+ http, https or mailto, and anything else is dropped. The thumbnail must be an+ embedded picture: no remote address and no svg. The other fields are stored+ as plain text. One loss is deliberate: a thumbnail embedded as more than 512+ bytes of data is not written into the Markdown, because in a plain editor it+ would be a screen of base64 after every card.++- **A video or audio clip comes back a clip.** It exported as a Markdown link+ and returned as a paragraph, losing controls, loop, muted, poster, size and+ caption. It now leaves as `<video>` or `<audio>` carrying those fields, with+ a link to the clip inside it. Obsidian and browsers play it. A renderer that+ strips the tag keeps the link, which is exactly what the old export was.+ Autoplay is written as `data-autoplay`, so the file never makes another+ renderer start the clip; this app records autoplay and never obeys it. The+ importer also reads clips as READMEs write them, including a `<source>` child+ and a tag spread over several lines. Nothing is copied from the tag by name.+ The source must be an embedded clip or an http(s) address, and the poster an+ embedded raster picture or an http(s) address. Anything else, such as a+ `javascript:` source or a relative path, arrives as its label and the address+ as plain code text, never as a player.++- **Every inline mark survives Markdown, and Pandoc's colour spans come in.**+ Bold with italic (`***both***`, the way the exporter writes the pair)+ came back wrongly nested and now comes back as written. Colour still leaves as+ `<span class="sp-fg-red">`, which GitHub and Obsidian show as clean text, and+ a highlight still leaves as `==x==`. The importer now also reads+ `[words]{color=red}` and `[words]{bg=yellow}`, but only for the nine palette+ colours. A name outside the palette, or any other key, leaves the span as the+ text it was.++- **Page links, boards and canvases come back as themselves.** A page link+ leaves as `[[Title]]` on its own line. Obsidian reads that as a link to the+ note, and the importer turns it back into a page card for the page with that+ title, whether it came in the same import or is already in the space. A link+ to no page stays the text it was. A board leaves as a+ ```` ```bento-view ```` fence: its settings on one JSON line, then its issues+ as readable `//` lines, which the importer ignores and the next export writes+ again. A canvas leaves as a ```` ```bento-canvas ```` fence holding its+ settings and each card's position, with the cards following as their own+ lines, so the positions survive. The fences are read with a JSON parser into+ the block's own fields. No id, type, parent, text or comments can be set that+ way, and a fence that does not parse stays the code block it looks like.++- **A block something points at keeps its id through Markdown.** A block+ with a review thread, or one a `#p/page/block` link targets, now exports+ with ` {#id}` after its line. That is Pandoc's heading-attribute spelling,+ which markdown-it-attrs also reads after any block. The importer gives the+ block that id back. Blocks nothing points at carry no id, so most exports+ do not change at all. Ids stay unique. A block copied in another editor+ with its id keeps its words and gets a fresh id. Two notes in one import+ cannot share an id, and neither can a note and the space it is imported+ into; the later holder is renamed and its children follow it. Only plain+ identifiers are taken, and never a name like `constructor`. Two limits:+ the threads themselves do not travel, because Markdown has nowhere to put+ them, so what survives is the anchor they re-attach by. And a table or a+ divider never carries an id, because the attribute would break the row or+ the rule.+## [0.1.0] — 2026-08-03First release.diff --git a/spaces/src/about.ts b/spaces/src/about.tsindex 4864acc1..7464b618 100644--- a/spaces/src/about.ts+++ b/spaces/src/about.ts@@ -43,7 +43,8 @@ import { esc, textOf } from './sanitize'import { htmlToMd } from './marks.ts'import { definitionLines } from './footnotes.ts'import { humanBytes } from './assets'-import { SPEC, mdLayout, type MdCtx } from './blocks'+import { SPEC, mdLayout, withBlockId, type MdCtx } from './blocks'+import { effectiveParents } from './model'import {issuesOf, passesFilter, sortRows, fieldByKey, optionOf, fieldsOf,} from './fields'@@ -556,6 +557,17 @@ export function toMarkdown(store: Store): string {// one type whose text is not a single string. A table with its own inline// rules would be the second place `**bold**` is decided.inline: htmlToMd,+ // a canvas's cards are the blocks it owns, in order — by the one parent+ // rule (model.ts effectiveParents), the same one the canvas renders by+ cardsOf: (b: Block) => {+ const page = store.doc.pages.find((p) => p.blocks.includes(b))+ if (!page) return []+ const eff = effectiveParents(page)+ return page.blocks.filter((c) => eff.get(c.id) === b.id).map((c) => {+ const x = (c as { x?: unknown }).x, y = (c as { y?: unknown }).y+ return typeof x === 'number' && typeof y === 'number' && Number.isFinite(x) && Number.isFinite(y) ? [x, y] : null+ })+ },// DERIVED THE SAME WAY THE SCREEN DERIVES IT — same filter, same sort, same// grouping — so the file you download is the board you were looking at. A// second traversal here is how an export starts quietly disagreeing with@@ -601,6 +613,15 @@ export function toMarkdown(store: Store): string {// neither was ever visited. Store.tree() carries the visited set and surfaces// what a cycle orphans, and this now inherits both. Measured before the fix:// 13 pages in the file, 11 in the export.+ // THE BLOCKS SOMETHING POINTS AT — a review thread's anchor, or the target+ // of a `#p/<page>/<block>` link anywhere in the space (a table cell and a+ // caption included, hence the whole serialised page list). Only these carry+ // `{#id}` in the export (blocks.ts withBlockId).+ const anchored = new Set<string>()+ for (const page of store.doc.pages) {+ for (const b of page.blocks) if (Array.isArray(b.comments) && b.comments.length) anchored.add(b.id)+ }+ for (const m of JSON.stringify(store.doc.pages).matchAll(/#p\/[^"\\/]+\/([A-Za-z][A-Za-z0-9_-]{0,63})/g)) anchored.add(m[1])const walk = () => {for (const { page, depth } of store.tree()) {out.push(`${'#'.repeat(Math.min(depth + 1, 6))} ${page.title}`, '')@@ -609,13 +630,14 @@ export function toMarkdown(store: Store): string {// registry in one pass (blocks.ts mdLayout).const layout = mdLayout(page.blocks)page.blocks.forEach((b, i) => {- const { quote, indent, sep } = layout[i]+ const { quote, indent, sep, close } = layout[i]const text = htmlToMd(b.html ?? '')// From the block registry, so a new type exports correctly the moment// it is declared. An UNKNOWN type — a file written by a newer build —// falls through to its text, which is the honest default.const spec = SPEC.get(b.type)- const lines = spec?.toMd ? spec.toMd(b, text, indent, ctx) : [text]+ const own = (spec?.toMd ? spec.toMd(b, text, indent, ctx) : [text]).flatMap((l) => l.split('\n'))+ const lines = anchored.has(b.id) ? withBlockId(b, own) : own// PER LINE, not per returned element. A spec returns ELEMENTS, and an// element can hold newlines: a code block's body is one multi-line// string, and htmlToMd turns <br> into a newline in ordinary text. Any@@ -627,6 +649,8 @@ export function toMarkdown(store: Store): string {// An empty line inside a quote must be a bare '>', never '> ' and never// blank: a blank line closes the blockquote.out.push(...lines.flatMap((l) => l.split('\n')).map((l) => (l ? quote + l : quote.trimEnd())))+ // the `</details>` of every fold that ends at this block (blocks.ts)+ for (const c of close) out.push(c.line ? c.quote + c.line : c.quote.trimEnd())out.push(sep)})// FOOTNOTE DEFINITIONS, AFTER THE PAGE THEY BELONG TO.diff --git a/spaces/src/blocks.ts b/spaces/src/blocks.tsindex b35e1d28..4f5db6fb 100644--- a/spaces/src/blocks.ts+++ b/spaces/src/blocks.ts@@ -76,6 +76,21 @@ export interface BlockSpec {* what mdLayout() below works out.*/mdQuoteChildren?: boolean+ /**+ * In markdown, this type is an html `<details>` element and its subtree+ * sits between its `<summary>` and the closing `</details>` that mdLayout()+ * places after the last descendant. The children are NOT indented further+ * than the block itself: indenting a paragraph inside `<details>` would make+ * GitHub read it as a nested list's continuation, or at four columns as code.+ */+ mdDetails?: boolean+ /**+ * In markdown, this type's children are written at ITS OWN indent, not one+ * level in: they are delimited some other way (a `</details>`, a counted+ * fence), and indenting them only invites a renderer to read them as a+ * nested list or code.+ */+ mdLevelChildren?: boolean/** Rendered by a dedicated case in render.ts, not by tag + inline host. */custom?: boolean/** Carries editable inline html. False for divider, image, pagelink. */@@ -113,6 +128,9 @@ export interface MdCtx {* context, exactly like the two questions above.*/inline: (html: string) => string+ /** a canvas's cards' positions, in order: `[x, y]`, or null for a card+ * with none (it takes a slot at read time) */+ cardsOf?: (b: Block) => Array<[number, number] | null>}export const SPECS: BlockSpec[] = [@@ -154,9 +172,20 @@ export const SPECS: BlockSpec[] = [},{type: 'toggle', label: 'Toggle', hint: 'Collapsible section', icon: 'toggle',- tag: 'div', text: true, custom: true, container: 'fold',+ tag: 'div', text: true, custom: true, container: 'fold', mdDetails: true, mdLevelChildren: true,init: (b) => { if (b.open === undefined) b.open = true },- toMd: (_b, text, indent) => [`${indent}- ${text}`],+ // A TOGGLE IS `<details>`, which GitHub, Obsidian and every browser render+ // as the same fold — the one piece of html a Markdown reader already knows+ // as "collapsible". `open` is written only when the block is open (the+ // renderer reads an absent `open` as folded, and so does html). The+ // summary is the block's text as inline MARKDOWN, so it reads back through+ // the same converter as every other line; GitHub shows `**` literally in a+ // summary, which is the price of one converter instead of two.+ //+ // The children follow as ordinary markdown and mdLayout() writes the+ // closing `</details>` after the last of them. Exported as `- text` before+ // this, and read back as a bullet: the fold and its state were lost.+ toMd: (b, text, indent) => [`${indent}<details${b.open === true ? ' open' : ''}>`, `${indent}<summary>${text}</summary>`],},{type: 'callout', label: 'Callout', hint: 'A note, tip or warning', icon: 'callout',@@ -246,7 +275,15 @@ export const SPECS: BlockSpec[] = [{type: 'pagelink', label: 'Link to page', hint: 'A card that opens a page', icon: 'link',tag: 'div', custom: true,- toMd: (b, _text, _indent, ctx) => [`→ [[${ctx.titleOf(String(b.page)) ?? '?'}]]`],+ // `[[Title]]` ALONE ON ITS LINE: a wikilink, which Obsidian and Foam read+ // as a link to that note, and which this app's importer reads back as a+ // page card (markdown.ts). A title a wikilink cannot spell — one holding+ // `[`, `]`, `|`, `#`, `^` or a newline — and a card to a missing page keep+ // the old `→ [[…]]` form, which reads back as the paragraph it is.+ toMd: (b, _text, _indent, ctx) => {+ const title = ctx.titleOf(String(b.page))+ return title && title.trim() === title && /^[^[\]|#^\n]+$/.test(title) ? [`[[${title}]]`] : [`→ [[${title ?? '?'}]]`]+ },},{// A LINK TO SOMEWHERE ON THE WEB — the outward-facing sibling of pagelink.@@ -267,18 +304,30 @@ export const SPECS: BlockSpec[] = [// link, so the default export would already be close — but `html` is a// fallback for old builds, and an export that reads it would silently// export nothing at all for a card an agent wrote fields-only.+ //+ // WHAT MAKES IT A CARD, and not a paragraph that happens to be one link, is+ // a trailing html comment: `<!-- bento:card site="…" image="…" -->`.+ // GitHub, Obsidian and every html renderer hide a comment, so the page+ // reads as the link and its description and nothing else — where a Pandoc+ // `{.card site=…}` would print as text after every card, and a data: image+ // in it as kilobytes of it. An UNMARKED lone link is not read as a card:+ // that would turn every README line that is just a link into one. The+ // fields the visible line cannot say (site, icon, image; title and desc+ // for a card with no url) ride in the comment. See cardComment().toMd: (b) => {const c = linkCard(b)+ const meta = ` ${cardComment(b, c.url)}`// no url, no link: a card that is not clickable must not export as// something a reader will click- if (!c.url) return [[c.title, c.desc].filter(Boolean).join(' — ')]- const tail = c.desc ? ` — ${c.desc}` : ''+ if (!c.url) return [[c.title, c.desc].filter(Boolean).join(' — ') + meta]+ const tail = c.desc ? ` — ${c.desc.replace(/\s*\n\s*/g, ' ')}` : ''// `[` and `]` in a title end the link text early and leave the url as- // loose parenthesised prose; a url holding a space or a bracket needs the- // angle form, which is what <> is FOR in CommonMark- const label = c.title.replace(/([[\]])/g, '\\$1')+ // loose parenthesised prose (and a backslash would escape the bracket+ // after it); a url holding a space or a bracket needs the angle form,+ // which is what <> is FOR in CommonMark+ const label = c.title.replace(/\s*\n\s*/g, ' ').replace(/([\\[\]])/g, '\\$1')const href = /[\s()<>]/.test(c.url) ? `<${c.url}>` : c.url- return [`[${label}](${href})${tail}`]+ return [`[${label}](${href})${tail}${meta}`]},},{@@ -318,21 +367,30 @@ export const SPECS: BlockSpec[] = [// from the pages that follow. The rows are derived (the export applies the// same filter and sort the screen does), which is why they arrive through// the context rather than off the block.- toMd: (b, text, indent, ctx) => {+ //+ // A ```` ```bento-view ```` FENCE: the view's settings as one JSON line+ // (fenceJson), which is what makes it a view again on the way back in —+ // then THE ISSUES, as `//` lines the importer ignores — never `#`, which a+ // tool splitting a file at its headings cuts on. The rows are derived+ // (the export applies the same filter and sort the screen does), which is+ // why they arrive through the context rather than off the block, and why+ // they are regenerated rather than read back. Outside this app the fence is+ // a code block: the settings and a readable list of the work.+ toMd: (b, text, _indent, ctx) => {const rows = ctx.rowsOf(b)- const out = [`**${text || 'Issues'}**`, '']- if (!rows.length) return [...out, `${indent}_No issues._`]+ const out = ['```bento-view', fenceJson(b, text)]+ if (!rows.length) out.push('// No issues.')let group: string | undefinedfor (const r of rows) {// grouped exactly as the board groups, and a flat list when it is oneif (r.group !== undefined && r.group !== group) {group = r.group- out.push('', `${indent}**${group}**`, '')+ out.push(`// ${oneLine(group)}`)}const meta = r.fields ? ` — ${r.fields}` : ''- out.push(`${indent}- [${r.title}](#p/${r.id})${meta}`)+ out.push(`// - ${oneLine(r.title + meta)}`)}- return out+ return [...out, '```']},},{@@ -349,13 +407,18 @@ export const SPECS: BlockSpec[] = [// unknown type), the name must NOT duplicate them. A table's fallback has// to hold its cells' text and pays for it in bytes; a canvas's does not.type: 'canvas', label: 'Canvas', hint: 'Cards you place by hand', icon: 'canvas',- tag: 'div', text: true, custom: true, container: 'always',+ tag: 'div', text: true, custom: true, container: 'always', mdLevelChildren: true,// THE NAME, then the cards — which arrive on their own, as the indented// lines of the blocks they are. A canvas is a picture and Markdown has no// pictures, so the honest export is the list of what is on it, in document// order. Positions are what does not survive, and saying so in the export// would be a comment in someone else's document.- toMd: (_b, text) => [`**${text || 'Canvas'}**`],+ //+ // A ```` ```bento-canvas ```` FENCE holding the canvas's settings and each+ // card's position, in order (fenceJson); the cards follow it as their own+ // lines, and the importer hands it the next `cards.length` blocks at its+ // level. Outside this app: a code block, then the cards as text.+ toMd: (b, text, _indent, ctx) => ['```bento-canvas', fenceJson(b, text, ctx.cardsOf?.(b)), '```'],},{type: 'image', label: 'Image', hint: 'Embedded in the file', icon: 'image',@@ -365,10 +428,16 @@ export const SPECS: BlockSpec[] = [// 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.+ //+ // Its SIZE follows as a Pandoc attribute list, `{width=60% w=640 h=300}`:+ // Pandoc and markdown-it-attrs read it, GitHub and Obsidian show it as+ // literal text after the picture — the one visible cost, paid only by a+ // sized image. Absent fields write nothing, so an unsized image exports+ // exactly as it did before.toMd: (b) => {const cap = String(b.caption ?? '').replace(/\s*\n\s*/g, ' ')const title = cap ? ` "${cap.replace(/["\\]/g, '\\$&')}"` : ''- return [`}${title})`]+ return [`}${title})${sizeAttrs(b)}`]},},{@@ -379,30 +448,153 @@ export const SPECS: BlockSpec[] = [// what the file actually IS, so the default here only has to be the shape// that degrades usefully.init: (b) => { if (b.kind === undefined) b.kind = 'video' },- // MARKDOWN HAS NO VIDEO, and pretending otherwise loses the block.+ // MARKDOWN HAS NO VIDEO, so a clip leaves as the html element every+ // Markdown renderer that allows html already plays — `<video>` or+ // `<audio>` — WITH A LINK INSIDE IT:+ //+ // <video src="clip.mp4" controls loop title="The demo"><a href="clip.mp4">The demo</a></video>+ //+ // A renderer that plays media hides the link (it is the element's fallback+ // content); a renderer that strips the tag keeps its content, which is+ // the link this block used to export as. So it degrades to exactly the+ // old export, and in Obsidian or a browser it plays.//- // Three candidates, and only one of them is right in more than one place.- // `` is IMAGE syntax: every renderer that has ever existed- // draws a broken-image glyph for it. A bare URL on its own line becomes a- // player on github.com and on nothing else, so it exports as a naked- // string everywhere a reader is likelier to open the file. A LINK is- // correct in all of them: it says what the thing is and where it is, and- // the one renderer that could do better still shows something you can- // click.+ // `autoplay` is written as `data-autoplay`: the block RECORDS it and this+ // app never obeys it (mediaPlayback), and an exported file must not make+ // some other renderer obey it on our behalf. The fields with no html+ // attribute (the column percentage, the caption) ride as data-*;+ // `width`/`height` are the intrinsic pixels, which is what those html+ // attributes mean.//// The target is `src` verbatim, `asset:` and data: included, exactly as- // the image exporter already writes it. That link does not resolve outside- // the space — which is the truth about an embedded clip, and a truthful- // dead link beats a silently dropped block.+ // the image exporter already writes it. That does not resolve outside the+ // space — which is the truth about an embedded clip.toMd: (b) => {- const kind = String(b.kind ?? 'video') === 'audio' ? 'Audio' : 'Video'- const label = String(b.alt ?? '') || kind+ const video = String(b.kind ?? 'video') !== 'audio'+ const kind = video ? 'Video' : 'Audio'const src = String(b.src ?? '')- return [src ? `[${label}](${src})` : `_${kind}_`]+ if (!src) return [`_${kind}_`]+ const alt = String(b.alt ?? '')+ const at = (k: string, v: unknown) => (typeof v === 'string' && v ? ` ${k}="${attrValue(v)}"` : '')+ const num = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : undefined)+ const tag = video ? 'video' : 'audio'+ let a = ` src="${attrValue(src)}"`+ if (b.controls !== false) a += ' controls'+ if (b.loop === true) a += ' loop'+ if (b.muted === true) a += ' muted'+ if (b.autoplay === true) a += ' data-autoplay'+ a += at('poster', b.poster) + at('title', alt)+ const w = num(b.w), h = num(b.h)+ if (w !== undefined && h !== undefined && Number.isInteger(w) && Number.isInteger(h)) a += ` width="${w}" height="${h}"`+ const width = num(b.width)+ if (width !== undefined) a += ` data-width="${width}"`+ a += at('data-caption', b.caption)+ const label = (alt || kind).replace(/\s*\n\s*/g, ' ')+ return [`<${tag}${a}><a href="${attrValue(src)}">${attrValue(label)}</a></${tag}>`]},},]+/**+ * A block's size as a Pandoc attribute list, or '' when it has none.+ *+ * ONLY NUMBERS LEAVE. `width` is a percentage and `w`/`h` pixel counts; a+ * field holding anything else — a string out of a hand-edited file — is not+ * written, so nothing a file says can end the list early or add a key.+ * `extra` is appended inside the braces (a block id, in a later family).+ */+export function sizeAttrs(b: Block, extra: string[] = []): string {+ const num = (v: unknown): number | undefined =>+ typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : undefined+ const parts = [...extra]+ const width = num(b.width)+ if (width !== undefined) parts.push(`width=${width}%`)+ const w = num(b.w), h = num(b.h)+ if (w !== undefined && h !== undefined && Number.isInteger(w) && Number.isInteger(h)) parts.push(`w=${w}`, `h=${h}`)+ return parts.length ? `{${parts.join(' ')}}` : ''+}++/**+ * A block id Markdown may carry: `{#id}` after the block's line. Ids are only+ * WRITTEN for blocks something points at — a review thread anchored to the+ * block, or a `#p/<page>/<block>` link — so a space with neither exports+ * exactly as it always has, and the ids that do appear are the ones whose+ * loss would orphan something.+ */+export const BLOCK_ID = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/+/** The id goes on the FIRST line of these (a fence's info line, the+ * `<details>` tag), the LAST non-empty line of anything else. */+const ID_ON_FIRST = new Set(['code', 'toggle', 'view', 'canvas'])+/** A trailing `{#id}` would break these: a table row becomes a ragged row,+ * a `---` stops being a rule. Their ids are not written (a known loss). */+export const NO_MD_ID = new Set(['table', 'divider'])++export function withBlockId(b: Block, lines: string[]): string[] {+ if (NO_MD_ID.has(b.type) || !BLOCK_ID.test(b.id) || b.id in Object.prototype) return lines+ let k = ID_ON_FIRST.has(b.type) ? 0 : -1+ if (k < 0) for (let j = lines.length - 1; j >= 0; j--) if (lines[j].replace(/^[>\s]*/, '')) { k = j; break }+ if (k < 0) return lines+ const out = [...lines]+ out[k] = `${out[k]} {#${b.id}}`+ return out+}++/** A readable `//` line inside a fence: one line, and never a fence of its own. */+const oneLine = (s: string): string => s.replace(/\s*\n\s*/g, ' ').replace(/`/g, "'")++/**+ * A view's or a canvas's fence body: ONE JSON line. `name` is the block's text+ * as inline markdown, `cards` a canvas's card positions, and every other key a+ * field of the block — all of them, so a field a newer build adds round-trips.+ * Fields named `name` or `cards` would collide and are not written.+ */+export function fenceJson(b: Block, text: string, cards?: Array<[number, number] | null>): string {+ const out: Record<string, unknown> = { name: text }+ for (const [k, v] of Object.entries(b)) {+ if (['id', 'type', 'parent', 'html', 'comments', 'name', 'cards'].includes(k) || v === undefined) continue+ out[k] = v+ }+ if (cards && cards.some((c) => c)) out.cards = cards+ return JSON.stringify(out)+}++/** An html attribute value (and element text): `&`, `"`, `<`, `>` as+ * entities, one line. markdown.ts decodes exactly these four. */+export const attrValue = (v: string): string =>+ v.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>').replace(/\s*\n\s*/g, ' ')++/**+ * A data: image larger than this is left out of a card's comment. It would be+ * invisible on GitHub, but not in a plain editor, where a thumbnail's worth of+ * base64 after every card is the whole screen. The loss is pinned in+ * scripts/test-spaces-md-strict.ts.+ */+export const CARD_IMAGE_MD_BUDGET = 512++/**+ * A comment-safe attribute value. `&` first, so the others are unambiguous;+ * `"` so the value cannot end early; `<` and `>` so no tag and no `-->` can+ * form; and `--` because it is what ends a comment. Undone in reverse by+ * markdown.ts cardFields().+ */+export const commentValue = (v: string): string =>+ v.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')+ .replace(/--/g, '--').replace(/\s*\n\s*/g, ' ')++/** The marker that makes a link line a link card, with the fields the line+ * itself cannot carry. Raw stored fields, never the derived fallbacks. */+export function cardComment(b: Block, url: string): string {+ const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : '')+ const parts: string[] = []+ const put = (k: string, v: string) => { if (v) parts.push(`${k}="${commentValue(v)}"`) }+ if (!url) { put('title', str(b.title)); put('desc', str(b.desc)) }+ put('site', str(b.site))+ put('icon', str(b.icon))+ const image = str(b.image)+ if (!(image.startsWith('data:') && image.length > CARD_IMAGE_MD_BUDGET)) put('image', image)+ return `<!-- bento:card${parts.map((p) => ` ${p}`).join('')} -->`+}+/** The `:---:` rule row's four forms, which are the whole of what GFM can say* about alignment — and the reason `colAlign` is per column, not per cell. */const RULE: Record<string, string> = { left: ':---', center: ':---:', right: '---:' }@@ -562,7 +754,9 @@ export const LIST_OF: Record<string, 'ul' | 'ol'> =* this. This is the part with the edge cases, so this is the part that has to* be reachable from a test.*/-export function mdLayout(blocks: Block[]): Array<{ quote: string; indent: string; sep: string }> {+export interface MdLine { quote: string; indent: string; sep: string; close: Array<{ quote: string; line: string }> }++export function mdLayout(blocks: Block[]): MdLine[] {const byId = new Map(blocks.map((b) => [b.id, b]))// HOP-CAPPED: `parent` is a plain id in a file anyone can hand-edit, so two// blocks can name each other. The renderer is a pre-order pass and cannot@@ -588,18 +782,37 @@ export function mdLayout(blocks: Block[]): Array<{ quote: string; indent: stringconst alert = (b: Block): string | undefined => owners(b).find(wraps)?.idconst depth = (b: Block): number => owners(b).filter(wraps).length- return blocks.map((b, i) => {+ const folds = (b: Block | undefined): boolean => !!b && SPEC.get(b.type)?.mdDetails === true+ const out: MdLine[] = []+ const at = new Map(blocks.map((b, i) => [b.id, i]))+ blocks.forEach((b, i) => {const parent = b.parent ? byId.get(b.parent) : undefined// Inside a callout a child is the alert's BODY, not a nested list item.// Indenting it makes GitHub read it as a nested list — or, at four spaces,- // as a code block.- const indent = parent && !wraps(parent) ? ' ' : ''+ // as a code block. Inside a `<details>` fold it sits at the fold's own+ // indent, for the same reason. (Effective parent for the fold case: the+ // fold's line is already laid out, because a parent is always earlier.)+ const effParent = eff.get(b.id)+ const level = (x: Block | undefined): boolean => !!x && SPEC.get(x.type)?.mdLevelChildren === true+ const fold = effParent !== undefined && level(byId.get(effParent)) ? at.get(effParent) : undefined+ const indent = fold !== undefined ? out[fold].indent : parent && !wraps(parent) ? ' ' : ''const next = blocks[i + 1]// "same alert" compares the alert the NEXT block is in against the alert// this one IS or is in, so a callout and its first child are joined, and so// are two children of one callout — but two adjacent callouts are not.const mine = wraps(b) ? b.id : alert(b)const sep = next && alert(next) && alert(next) === mine ? '> '.repeat(depth(next)).trimEnd() : ''- return { quote: '> '.repeat(depth(b)), indent, sep }+ // EVERY FOLD WHOSE SUBTREE ENDS HERE closes here, innermost first: this+ // block itself if it is a fold with no children, then each fold above it+ // that the next block is not inside.+ const nextOwners = next ? new Set(owners(next).map((o) => o.id)) : new Set<string>()+ const close: MdLine['close'] = []+ for (const f of [b, ...owners(b)]) {+ if (!folds(f) || nextOwners.has(f.id)) continue+ const q = '> '.repeat(depth(f))+ close.push({ quote: q, line: '' }, { quote: q, line: `${out[at.get(f.id)!]?.indent ?? indent}</details>` })+ }+ out.push({ quote: '> '.repeat(depth(b)), indent, sep, close })})+ return out}diff --git a/spaces/src/editor.ts b/spaces/src/editor.tsindex a6c9a7a2..590684cf 100644--- a/spaces/src/editor.ts+++ b/spaces/src/editor.ts@@ -5383,12 +5383,20 @@ export class Editor {// land on the page already titled "New York": aliases have to reach the// resolver or they are an alias in name only.const existing = nameIndex(s.doc).byName+ // every id the space already uses, so a `{#id}` in a note never lands on+ // a second block (or a page) with the same id+ const usedIds = new Set<string>()+ for (const page of s.doc.pages) {+ usedIds.add(page.id)+ for (const b of page.blocks) usedIds.add(b.id)+ }const plan = planImport(files, {rootTitle: t('Imported notes'),resolveExisting: (target) => existing.get(target),// so an imported `[^1]` that would land on a note this space already has// is renamed, in the plan, along with the references to itexistingNotes: s.doc.footnotes,+ idTaken: (id) => usedIds.has(id),})// ---- images ------------------------------------------------------------diff --git a/spaces/src/markdown.ts b/spaces/src/markdown.tsindex 500766f5..e671c60d 100644--- a/spaces/src/markdown.ts+++ b/spaces/src/markdown.ts@@ -16,10 +16,10 @@// `.ts` extensions ON PURPOSE: this module is imported directly by// `scripts/test-spaces-model.ts`, which node resolves without a bundler.-import { type Block, type Page, uid, writeTable } from './model.ts'-import { esc } from './sanitize.ts'+import { type Block, type Page, uid, writeTable, linkCard, linkCardHtml } from './model.ts'+import { esc, externalHref } from './sanitize.ts'import { takeDefinitions, mergeNotes, renameRefs } from './footnotes.ts'-import { keepClasses } from './marks.ts'+import { keepClasses, PALETTE } from './marks.ts'/** A tab indents four columns. Nothing here depends on the exact number; it* only has to be the same everywhere so nesting is consistent. */@@ -143,8 +143,36 @@ export function inlineHtml(src: string): string {? hold(`<a href="${esc(url)}">`) + text + hold('</a>'): m)+ // A PANDOC SPAN carrying a palette colour — `[words]{color=red}` for the+ // ink, `[words]{bg=yellow}` for the band behind them, or both. This app's+ // own exporter writes colour as raw `<span class="sp-fg-red">`, which GitHub+ // and Obsidian show as clean text (the brace form would show as literal+ // braces there); this is the other spelling, for Markdown written with+ // Pandoc in mind. THE PALETTE ONLY: a name outside it (`coral`,+ // `red;background:url(…)`) or any key but these two leaves the whole span+ // as the text it was, so nothing here can mint a class the sanitizer's+ // pattern would then accept.+ s = s.replace(/\[([^[\]\n]+)\]\{([^{}\n]*)\}/g, (m: string, x: string, list: string) => {+ const a = parseAttrs(`{${list}}`)+ if (!a || a.id !== undefined || a.classes.length || !a.kv.size) return m+ const named = (k: string): string | undefined => {+ const v = a.kv.get(k)+ return v !== undefined && (PALETTE as readonly string[]).includes(v) ? v : undefined+ }+ for (const k of a.kv.keys()) if ((k !== 'color' && k !== 'bg') || !named(k)) return m+ const fg = named('color'), bg = named('bg')+ const open = (bg ? `<mark class="sp-bg-${bg}">` : '') + (fg ? `<span class="sp-fg-${fg}">` : '')+ const close = (fg ? '</span>' : '') + (bg ? '</mark>' : '')+ return hold(open) + x + hold(close)+ })+s = s.replace(/~~([\s\S]+?)~~/g, (_m, x: string) => hold('<s>') + x + hold('</s>'))s = s.replace(/==([\s\S]+?)==/g, (_m, x: string) => hold('<mark>') + x + hold('</mark>'))+ // `***x***` — bold AND italic, which is how the exporter spells the pair+ // (marks.ts: strong outside em). Left to the two rules below it read as+ // `**` + `*x` + `**` and then an `*` with no partner, and came back as the+ // mis-nested `<strong><em>x</strong></em>`.+ s = s.replace(/\*\*\*(?=\S)([^*]+?)\*\*\*/g, (_m, x: string) => hold('<strong><em>') + x + hold('</em></strong>'))s = s.replace(/\*\*(?=\S)([\s\S]+?)\*\*/g, (_m, x: string) => hold('<strong>') + x + hold('</strong>'))s = s.replace(/(^|[^\w\\])__(?=\S)([\s\S]+?)__(?!\w)/g,(_m, pre: string, x: string) => pre + hold('<strong>') + x + hold('</strong>'))@@ -211,15 +239,277 @@ const mk = (type: string, extra: Partial<Block> = {}): Block => ({ id: uid('b'),// 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*\)$/+// A trailing `{…}` is a Pandoc attribute list: `{width=60% w=640 h=300}`.+const IMG_LINE = /^!\[([^\]]*)\]\(\s*<?([^\s)>]*)>?(?:\s+"((?:[^"\\]|\\.)*)")?\s*\)(\{[^{}\n]*\})?$/++/**+ * A PANDOC ATTRIBUTE LIST — `{#id .class key=value key="quoted value"}` — the+ * syntax Pandoc, markdown-it-attrs and kramdown-alikes already read after an+ * image, a link or a heading. Parsed into plain strings and NOTHING is+ * interpreted here: each caller takes only the keys it knows, validates each+ * value against its own pattern, and ignores the rest. An attribute list out+ * of a mailed file is data, and the only way it can matter is through a+ * validator that says yes.+ *+ * A malformed list (an unterminated quote, a token that is none of the three+ * forms) yields null, and the caller treats the line as ordinary text.+ */+export interface Attrs { id?: string; classes: string[]; kv: Map<string, string> }+export function parseAttrs(src: string): Attrs | null {+ const m = /^\{([^{}\n]*)\}$/.exec(src.trim())+ if (!m) return null+ const out: Attrs = { classes: [], kv: new Map() }+ const re = /\s*(?:#([A-Za-z][\w-]*)|\.([A-Za-z][\w-]*)|([A-Za-z][\w-]*)=(?:"([^"]*)"|([^\s"]+)))\s*/y+ let at = 0+ const body = m[1]+ while (at < body.length) {+ re.lastIndex = at+ const t = re.exec(body)+ if (!t || re.lastIndex === at) return null+ at = re.lastIndex+ if (t[1] !== undefined) out.id = t[1]+ else if (t[2] !== undefined) out.classes.push(t[2])+ else if (!out.kv.has(t[3])) out.kv.set(t[3], t[4] ?? t[5] ?? '')+ }+ return out+}++/**+ * An image's (or a clip's) SIZE out of its attribute list, validated.+ *+ * `width` is the block's percentage of the text column, 10..100, written with+ * its `%` exactly as Pandoc spells a relative width. `w`/`h` are the intrinsic+ * pixels the block keeps to hold its aspect box while it decodes — not a+ * display size, so they are NOT Pandoc's `width`/`height` (a foreign+ * `width=300px` means something else and is ignored rather than guessed at).+ * Both or neither: one of the pair is not an aspect ratio.+ */+export function sizeOf(a: Attrs | null): { width?: number; w?: number; h?: number } {+ if (!a) return {}+ const out: { width?: number; w?: number; h?: number } = {}+ const pct = /^(\d{1,3}(?:\.\d{1,3})?)%$/.exec(a.kv.get('width') ?? '')+ if (pct) { const n = Number(pct[1]); if (n >= 10 && n <= 100) out.width = n }+ const w = /^[1-9]\d{0,4}$/.test(a.kv.get('w') ?? '') ? Number(a.kv.get('w')) : 0+ const h = /^[1-9]\d{0,4}$/.test(a.kv.get('h') ?? '') ? Number(a.kv.get('h')) : 0+ if (w && h) { out.w = w; out.h = h }+ return out+}const IMG_EMBED = /^!\[\[([^\]|]+)(?:\|[^\]]*)?\]\]$/const IMAGE_EXT = /\.(png|jpe?g|gif|webp|avif|svg|bmp|ico)$/i+// ---- link cards -------------------------------------------------------------++/**+ * A LINK CARD's line: a link, an optional ` — description`, and the marker+ * comment blocks.ts cardComment() writes — or, for a card with no url, any+ * text before the marker (its title and desc are in the comment). The marker is+ * what makes it a card; the same line without it is an ordinary paragraph.+ */+const CARD_LINE = /^(?:\[((?:\\.|[^\]\\])*)\]\(\s*(?:<([^>\n]*)>|([^\s()<>]*))\s*\)(?: — (.*?))?|(.*?))\s*<!-- bento:card((?:\s+[a-z]+="[^"<>]*")*)\s*-->$/++const uncomment = (v: string): string =>+ v.replace(/-/g, '-').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&')++/** A thumbnail a card may point at: an asset key, or an inline raster image.+ * Never a remote address (linkCard() would drop one anyway) and never svg. */+const CARD_IMAGE = /^(?:asset:[A-Za-z0-9_-]{1,128}|data:image\/(?:png|jpeg|gif|webp|avif);base64,[A-Za-z0-9+/]+=*)$/++/**+ * A card line → the card's fields, every one validated, or null when the line+ * is not a card. Plain-text fields (title, desc, site, icon) are stored as+ * TEXT — the renderer writes them with textContent — and capped; the url must+ * pass externalHref(), the same allowlist the editor's card dialog uses, and+ * a url that fails it is dropped rather than stored (the card keeps its+ * title and is a dead card, which is what render.ts draws for one).+ */+function cardOf(line: string): Partial<Block> | null {+ const m = CARD_LINE.exec(line)+ if (!m) return null+ const kv = new Map<string, string>()+ for (const a of m[6].matchAll(/([a-z]+)="([^"]*)"/g)) if (!kv.has(a[1])) kv.set(a[1], uncomment(a[2]))+ const text = (v: string | undefined, cap: number): string => (v ?? '').replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, cap)+ const out: Partial<Block> = {}+ const linked = m[2] !== undefined || m[3] !== undefined+ if (linked) {+ const url = externalHref(m[2] ?? m[3])+ const shown = text(m[1].replace(/\\([\\[\]])/g, '$1'), 500)+ if (url) out.url = url+ // an untitled card exports its url as its text; that is not a title+ if (shown && shown !== url) out.title = shown+ const desc = text(m[4], 2000)+ if (desc) out.desc = desc+ } else {+ // no title in the marker: the visible words are the title, as plain text+ // — a line whose link could not be read (`[Evil](javascript:…)`, whose+ // parentheses the url pattern refuses) keeps its words, not its address+ const shown = m[5] ?? ''+ // a second marker (or any comment) in the words is not a card line: it is+ // someone trying to close ours early, and the line stays text+ if (shown.includes('<!--')) return null+ const words = /^\[((?:\\.|[^\]\\])*)\]\(.*\)$/.exec(shown)?.[1].replace(/\\([\\[\]])/g, '$1') ?? plainText(shown)+ const title = text(kv.get('title') ?? words, 500)+ const desc = text(kv.get('desc'), 2000)+ if (title) out.title = title+ if (desc) out.desc = desc+ }+ const site = text(kv.get('site'), 200)+ if (site) out.site = site+ const icon = text(kv.get('icon'), 16)+ if (icon) out.icon = icon+ const image = kv.get('image') ?? ''+ if (CARD_IMAGE.test(image)) out.image = image+ return out+}++// ---- media ------------------------------------------------------------------++const unattr = (v: string): string =>+ v.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&')++/** An html tag's attributes, lower-cased names, values decoded. Booleans map+ * to ''. Parsing only: what any name MEANS is decided by the caller. */+function htmlAttrs(src: string): Map<string, string> {+ const out = new Map<string, string>()+ for (const m of src.matchAll(/([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)) {+ const k = m[1].toLowerCase()+ if (!out.has(k)) out.set(k, unattr(m[2] ?? m[3] ?? m[4] ?? ''))+ }+ return out+}++/**+ * Where a clip or its poster may point: an asset key, an inline file of the+ * right kind, or an http(s) address — the three forms the model has, and the+ * same allowlist the editor's "Use a link…" box applies. An ALLOWLIST, like+ * HREF_OK: `javascript:`, `file:`, `blob:`, a relative path and anything+ * the URL parser would normalise into one of those all fail it.+ */+const MEDIA_SRC = /^(?:asset:[A-Za-z0-9_-]{1,128}|data:(?:video|audio)\/[\w.+-]{1,40};base64,[A-Za-z0-9+/]+=*|https?:\/\/[^\s"'<>]+)$/i+const POSTER_SRC = /^(?:asset:[A-Za-z0-9_-]{1,128}|data:image\/(?:png|jpeg|gif|webp|avif);base64,[A-Za-z0-9+/]+=*|https?:\/\/[^\s"'<>]+)$/i++/**+ * `<video …>…</video>` or `<audio …>…</audio>` (already joined onto one line)+ * → a media block's fields, or null when the source is not one the model may+ * hold. Reads the element blocks.ts media toMd writes, and the shapes READMEs+ * use: a `<source src>` child instead of a `src` attribute, and a real+ * `autoplay` (recorded, never obeyed — mediaPlayback). Every value is checked;+ * no attribute is copied by name, so `onerror`, `style` and the rest have+ * nowhere to go.+ */+function mediaOf(html: string): { fields: Partial<Block> } | { refused: string; label: string } | null {+ const m = /^<(video|audio)(\s[^>]*)?>([\s\S]*?)<\/\1\s*>$/i.exec(html.trim())+ if (!m) return null+ const kind = m[1].toLowerCase()+ const a = htmlAttrs(m[2] ?? '')+ const inner = m[3]+ const source = /<source(\s[^>]*)?>/i.exec(inner)+ const raw = (a.get('src') ?? (source ? htmlAttrs(source[1] ?? '').get('src') : undefined) ?? '').trim()+ const fallback = /<a(?:\s[^>]*)?>([\s\S]*?)<\/a>/i.exec(inner)?.[1] ?? inner+ const label = unattr(fallback.replace(/<[^>]*>/g, '')).replace(/\s+/g, ' ').trim()+ if (!MEDIA_SRC.test(raw)) return { refused: raw, label }+ const f: Partial<Block> = { kind, src: raw }+ const alt = (a.get('title') ?? a.get('aria-label') ?? '').replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 500)+ if (alt) f.alt = alt+ f.controls = a.has('controls')+ if (a.has('loop')) f.loop = true+ if (a.has('muted')) f.muted = true+ if (a.has('autoplay') || a.has('data-autoplay')) f.autoplay = true+ const poster = (a.get('poster') ?? '').trim()+ if (POSTER_SRC.test(poster)) f.poster = poster+ const px = (v: string | undefined) => (/^[1-9]\d{0,4}$/.test(v ?? '') ? Number(v) : 0)+ const w = px(a.get('width')), h = px(a.get('height'))+ if (w && h) { f.w = w; f.h = h }+ const pct = /^(\d{1,3}(?:\.\d{1,3})?)$/.exec(a.get('data-width') ?? '')+ if (pct && Number(pct[1]) >= 10 && Number(pct[1]) <= 100) f.width = Number(pct[1])+ const caption = (a.get('data-caption') ?? '').trim()+ if (caption) f.caption = caption.slice(0, 2000)+ return { fields: f }+}++// ---- views and canvases -------------------------------------------------------++/** What a structured fence may hold at most. A file can be hand-edited or+ * generated; a view's settings are a few hundred bytes. */+const FENCE_MAX = 65536+/** A field name a fence may set: a plain identifier. Excludes `__proto__`+ * by construction (it starts with `_`), and the reserved names below by+ * list. */+const FIELD_KEY = /^[A-Za-z][A-Za-z0-9]{0,31}$/+const RESERVED = new Set(['id', 'type', 'parent', 'html', 'comments', 'name', 'cards', 'constructor', 'prototype'])++/**+ * A ```` ```bento-view ```` or ```` ```bento-canvas ```` fence → the block.+ *+ * The body is ONE JSON object (blocks.ts fenceJson writes it): `name` is the+ * block's text as inline markdown, `cards` (canvas only) the card positions,+ * and every other key is a field of the block, copied as data — so a field a+ * newer build adds to a view round-trips through this one. Lines starting `//`+ * are the readable summary the exporter adds for people reading the file+ * elsewhere, and are ignored. JSON.parse, never eval; the object's OWN keys+ * only, each a plain identifier; nothing structural (`id`, `type`, `parent`,+ * `html`, `comments`) can be set from the fence. Anything malformed returns+ * null and the fence stays the code block it looks like.+ *+ * This is no more trust than the app already extends to a `.bento.html` file+ * someone mails you, whose blocks are JSON with every one of these fields.+ */+function fencedBlock(kind: 'view' | 'canvas' | string, body: string[]): { block: Block; cards?: Array<[number, number] | null> } | null {+ const json = body.filter((l) => l.trim() && !l.trim().startsWith('//'))+ if (json.length !== 1 || json[0].length > FENCE_MAX) return null+ let obj: unknown+ try { obj = JSON.parse(json[0]) } catch { return null }+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return null+ const o = obj as Record<string, unknown>+ const block = mk(kind, { html: typeof o.name === 'string' ? inlineHtml(o.name) : '' })+ for (const k of Object.keys(o)) {+ if (!Object.hasOwn(o, k) || !FIELD_KEY.test(k) || RESERVED.has(k)) continue+ block[k] = o[k]+ }+ if (kind !== 'canvas') return { block }+ const cards: Array<[number, number] | null> = []+ if (Array.isArray(o.cards)) {+ for (const c of o.cards.slice(0, 1000)) {+ cards.push(Array.isArray(c) && c.length === 2 && c.every((n) => typeof n === 'number' && Number.isFinite(n))+ ? [c[0] as number, c[1] as number] : null)+ }+ }+ return { block, cards }+}++/**+ * Turn the `[[Title]]` page links parseNote left pending into real page ids.+ *+ * One that names no page becomes the paragraph it would otherwise have been,+ * holding the literal `[[Title]]` — the same rule as an inline wikilink that+ * finds nothing (resolveWikilinks): honest text, never a card to nowhere.+ */+export function resolvePageLinks(blocks: Block[], lookup: (target: string) => string | undefined): { linked: number; dangling: number } {+ let linked = 0, dangling = 0+ for (const b of blocks) {+ if (b.type !== 'pagelink' || typeof b.page !== 'string' || !b.page.startsWith(WIKI_SCHEME)) continue+ let target = b.page.slice(WIKI_SCHEME.length)+ try { target = decodeURIComponent(target) } catch { /* keep the raw form */ }+ const id = lookup(target)+ if (id) { b.page = id; linked++; continue }+ dangling+++ b.type = 'p'+ delete b.page+ b.html = `[[${esc(target)}]]`+ }+ return { linked, dangling }+}+/** A line that is nothing but an image. `![[x]]` counts only when it names an* 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 {+function imageOf(line: string): { ref: string; alt: string; caption?: string; attrs?: Attrs | null } | null {const m = IMG_LINE.exec(line.trim())- if (m) return { ref: m[2], alt: m[1], ...(m[3] ? { caption: m[3].replace(/\\(["\\])/g, '$1') } : {}) }+ if (m) {+ return {+ ref: m[2], alt: m[1],+ ...(m[3] ? { caption: m[3].replace(/\\(["\\])/g, '$1') } : {}),+ ...(m[4] ? { attrs: parseAttrs(m[4]) } : {}),+ }+ }const e = IMG_EMBED.exec(line.trim())if (e && IMAGE_EXT.test(e[1].trim())) return { ref: e[1].trim(), alt: '' }return null@@ -276,6 +566,15 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {* callout on `stack` as their owner until `end`.*/const alerts: Array<{ end: number; depth: number }> = []+ /**+ * Open `<details>` folds, innermost last: how deep `stack` was before each+ * opened. A fold is a container like an alert, but it ends at an explicit+ * `</details>` rather than at the end of a blockquote.+ */+ const folds: Array<{ depth: number }> = []+ /** canvases read from a `bento-canvas` fence, and the card positions each+ * one carries — the cards themselves are the blocks that follow it */+ const canvases: Array<{ block: Block; cards: Array<[number, number] | null> }> = []/** 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 */@@ -286,19 +585,44 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop()return stack[stack.length - 1]?.id || undefined}+ /** the block the line being read created or continued — where a trailing+ * `{#id}` on that line belongs */+ let touched: Block | null = null+ /** the id a line carried, waiting for that line to finish */+ let pendingId: string | null = nullconst add = (b: Block, parent?: string): Block => {if (parent) b.parent = parentblocks.push(b)+ touched = breturn b}+ const taken = new Set<string>()+ /**+ * Give the block the line just read the id that line carried. The block was+ * minted with a fresh id when the line began, and anything opened since+ * (a list level, a callout's body) points at that one — so it is a RENAME,+ * of the stack entries and of any `parent` already written. An id this note+ * has already given out stays with its first holder: a paragraph another+ * editor duplicated keeps its words and gets a fresh id.+ */+ const settleId = () => {+ const id = pendingId+ pendingId = null+ if (!id || !touched || taken.has(id)) return+ taken.add(id)+ const old = touched.id+ touched.id = id+ for (const e of stack) if (e.id === old) e.id = id+ for (const b of blocks) if (b.parent === old) b.parent = id+ }// NOT model.isRemote(): that answers "would loading this touch the network",// where a relative path counts as remote. The question here is different —// "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 imageBlock = (ref: string, alt: string, caption: string | undefined, parent?: string, attrs?: Attrs | null) => {// `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 } : {}) })+ const b = mk('image', { html: '', src: ref, ...(alt ? { alt } : {}), ...(caption ? { caption } : {}), ...sizeOf(attrs ?? null) })add(b, parent)if (/^(https?:)?\/\//i.test(ref)) remoteImages++else if (!/^data:/i.test(ref)) images.push({ block: b, ref, dir: '' })@@ -306,17 +630,32 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {}for (; i < lines.length; i++) {+ settleId()while (alerts.length && i >= alerts[alerts.length - 1].end) {stack.length = alerts.pop()!.depth+ // a fold left open inside the box ends with it+ while (folds.length && folds[folds.length - 1].depth > stack.length) folds.pop()para = null; quote = null; alertText = null}const ownText = alertTextalertText = nullconst line = lines[i].replace(/\t/g, TAB)const indent = /^ */.exec(line)![0].length- const body = line.slice(indent).trimEnd()+ let body = line.slice(indent).trimEnd()++ // A BLOCK ID — ` {#id}` ending a line, Pandoc's heading-attribute+ // spelling and what markdown-it-attrs reads after any block. Taken off+ // the line before anything else reads it, and given to whichever block+ // this line creates or continues (settleId, at the next line). Only a+ // plain identifier, and never a name Object.prototype already has.+ const idm = / \{#([A-Za-z][A-Za-z0-9_-]{0,63})\}$/.exec(body)+ if (idm && !(idm[1] in Object.prototype)) {+ body = body.slice(0, idm.index).trimEnd()+ pendingId = idm[1]+ touched = null+ }- if (!body) { para = null; quote = null; continue }+ if (!body) { para = null; quote = null; pendingId = null; continue }// fenced code — taken whole, so nothing inside is interpretedconst fence = /^(`{3,}|~{3,})\s*(\S*)/.exec(body)@@ -332,7 +671,14 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {buf.push(lines[j].startsWith(' '.repeat(indent)) ? lines[j].slice(indent) : lines[j])}i = j- add(mk('code', { html: esc(buf.join('\n')), ...(fence[2] ? { lang: fence[2].toLowerCase() } : {}) }), owner)+ const lang = fence[2].toLowerCase()+ const structured = lang === 'bento-view' || lang === 'bento-canvas' ? fencedBlock(lang.slice(6), buf) : null+ if (structured) {+ add(structured.block, owner)+ if (structured.cards) canvases.push({ block: structured.block, cards: structured.cards })+ continue+ }+ add(mk('code', { html: esc(buf.join('\n')), ...(fence[2] ? { lang } : {}) }), owner)continue}@@ -394,6 +740,51 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {continue}+ // A `<details>` FOLD is a toggle. GitHub renders it, Obsidian renders it,+ // and it is what this app's exporter writes (blocks.ts toggle toMd).+ //+ // THE TAG IS READ, NEVER KEPT. Of everything the opening tag may carry,+ // the one fact taken from it is whether it says `open`; no attribute value+ // is copied anywhere, so `<details onclick=…>` or `<details ontoggle=…>`+ // costs the importer nothing to refuse — there is no html built from it to+ // refuse. The summary is inline markdown and goes through inlineHtml like+ // any other line (and sanitizeInline after it, in the importer).+ const det = /^<details(\s[^>]*)?>(.*)$/i.exec(body)+ if (det) {+ para = null; quote = null+ // quoted values out first, so `title="open"` does not read as the flag+ const attrs = (det[1] ?? '').replace(/"[^"]*"|'[^']*'/g, '""')+ const open = /(?:^|\s)open(?:\s|=|$)/i.test(attrs)+ let rest = det[2].trim()+ if (!rest) {+ // the summary on the next non-blank line, as GitHub READMEs indent it+ let j = i + 1+ while (j < lines.length && !lines[j].trim()) j+++ if (/^<summary(?:\s[^>]*)?>/i.test(lines[j]?.trim() ?? '')) { rest = lines[j].trim(); i = j }+ }+ const sum = /^<summary(?:\s[^>]*)?>(.*?)<\/summary>(.*)$/i.exec(rest)+ const toggle = add(mk('toggle', { html: inlineHtml(sum ? sum[1].trim() : ''), open }), ownerFor(indent))+ // anything after the summary on the same line is the fold's first line,+ // and a `</details>` there closes it at once+ let after = (sum ? sum[2] : rest).trim()+ const shut = /<\/details>\s*$/i.test(after)+ after = after.replace(/<\/details>\s*$/i, '').trim()+ if (after) add(mk('p', { html: inlineHtml(after) }), toggle.id)+ if (!shut) {+ folds.push({ depth: stack.length })+ // below `indent`, so no line of the body can pop it; `</details>` does+ stack.push({ indent: indent - 0.5, id: toggle.id })+ }+ continue+ }+ if (/^<\/details\s*>$/i.test(body)) {+ para = null; quote = null+ const f = folds.pop()+ // a stray closer (no fold open) is dropped, as the raw-tag sweep would+ if (f) stack.length = Math.min(stack.length, f.depth)+ 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,@@ -422,7 +813,7 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {if (q) {para = nullconst text = inlineHtml(q[1].replace(/^[>\s]+/, ''))- if (quote) quote.html = `${quote.html}<br>${text}`+ if (quote) { quote.html = `${quote.html}<br>${text}`; touched = quote }else quote = add(mk('quote', { html: text }), ownerFor(indent))continue}@@ -438,7 +829,7 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {const block = todo? add(mk('todo', { html: inlineHtml(todo[2]), done: todo[1] !== ' ' }), owner): pic- ? imageBlock(pic.ref, pic.alt, pic.caption, owner)+ ? imageBlock(pic.ref, pic.alt, pic.caption, owner, pic.attrs): add(mk(/^\d/.test(item[1]) ? 'number' : 'bullet', { html: inlineHtml(text) }), owner)// An IMAGE is not a container and holds no text, so it is neither a// continuation target nor a parent.@@ -462,7 +853,52 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {const pic = imageOf(body)if (pic) {para = null- imageBlock(pic.ref, pic.alt, pic.caption, ownerFor(indent))+ imageBlock(pic.ref, pic.alt, pic.caption, ownerFor(indent), pic.attrs)+ continue+ }++ // A CLIP — `<video>`/`<audio>`, on one line as the exporter writes it or+ // spread over a few as READMEs do (bounded: an unclosed tag is text).+ const clipOpen = /^<(video|audio)(?:\s|>)/i.exec(body)+ if (clipOpen) {+ let html = body+ let j = i+ const closer = new RegExp(`</${clipOpen[1]}\\s*>`, 'i')+ while (!closer.test(html) && j + 1 < lines.length && j - i < 20) html += `\n${lines[++j].trim()}`+ const clip = closer.test(html) ? mediaOf(html) : null+ if (clip) {+ para = null+ i = j+ if ('fields' in clip) add(mk('media', { html: '', ...clip.fields }), ownerFor(indent))+ // A SOURCE THE MODEL MAY NOT HOLD is shown, never loaded: the words+ // and the address as inert code, the same way an image that could+ // not be imported is reported. `javascript:` ends up as text.+ else add(mk('p', { html: `${esc(clip.label || clipOpen[1].toLowerCase())}${clip.refused ? ` <code>${esc(clip.refused)}</code>` : ''}` }), ownerFor(indent))+ continue+ }+ }++ // A PAGE LINK is a wikilink ALONE on its line — `[[Title]]`, which+ // Obsidian and Foam already read as a link to that note. Resolved to a+ // page id with the other wikilinks, once every page exists; one that+ // names no page falls back to the paragraph it would have been+ // (resolvePageLinks). An aliased `[[a|b]]` stays inline: the alias is+ // words a page card has no place for.+ const lone = /^\[\[([^[\]|#^\n]+)\]\]$/.exec(body)+ if (lone && lone[1].trim()) {+ para = null+ add(mk('pagelink', { html: '', page: `${WIKI_SCHEME}${encodeURIComponent(lone[1].trim())}` }), ownerFor(indent))+ continue+ }++ const card = body.includes('<!-- bento:card') ? cardOf(body) : null+ if (card) {+ para = null+ const b = mk('link', card)+ // the readable fallback an old build renders, written from the fields+ // by the one function the editor also uses (model.ts)+ b.html = linkCardHtml(linkCard(b))+ add(b, ownerFor(indent))continue}@@ -473,10 +909,26 @@ 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 (ownText) { ownText.html = text; para = ownText }- else if (para) para.html = `${para.html}<br>${text}`+ if (ownText) { ownText.html = text; para = ownText; touched = ownText }+ else if (para) { para.html = `${para.html}<br>${text}`; touched = para }else para = add(mk('p', { html: text }), ownerFor(indent))}+ settleId()++ // A CANVAS OWNS THE CARDS ITS FENCE COUNTS: the next `cards.length` blocks+ // at the canvas's own level, in order, each taking its position. Their own+ // children stay theirs. Counting rather than indenting, because a card is+ // any block type and several types export without indentation.+ for (const { block, cards } of canvases) {+ let k = blocks.indexOf(block) + 1+ for (const pos of cards) {+ while (k < blocks.length && blocks[k].parent !== block.parent) k+++ if (k >= blocks.length) break+ const card = blocks[k++]+ card.parent = block.id+ if (pos) { card.x = pos[0]; card.y = pos[1] }+ }+ }return {title: title || fileTitle,@@ -607,6 +1059,14 @@ export function planImport(/** the footnotes the space already has, so an imported label that would* land on a DIFFERENT note is renamed rather than silently reused */existingNotes?: Record<string, string>+ /**+ * Is this id already used in the space the import lands in — by a block+ * or a page? A `{#id}` a note carries is kept only when the answer is no+ * and no earlier note in this import took it; otherwise the block gets a+ * fresh id. Ids are unique document-wide, and a Markdown file is the one+ * place an id arrives that this app did not mint.+ */+ idTaken?: (id: string) => boolean},): ImportPlan {const src = files@@ -713,9 +1173,31 @@ export function planImport(stats.remoteImages += note.remoteImages}+ // ---- block ids: unique across the import and the space ------------------+ // Each note already refused a repeat of its own ids; this is the same rule+ // across notes (a vault where one note was copied to make another) and+ // against the space being imported into (a space's own export, imported+ // back into it). The later holder is renamed, children and all.+ {+ const seen = new Set<string>(pages.map((p) => p.id))+ for (const page of pages) {+ for (const b of page.blocks) {+ if (!seen.has(b.id) && !opts.idTaken?.(b.id)) { seen.add(b.id); continue }+ const old = b.id+ b.id = uid('b')+ seen.add(b.id)+ for (const c of page.blocks) if (c.parent === old) c.parent = b.id+ }+ }+ }+// ---- wikilinks, once every page exists ----------------------------------const { index, collisions } = linkIndex(src, parsed, filePage, tops.size === 1 ? [...tops][0] : '')for (const page of pages) {+ const pl = resolvePageLinks(page.blocks, (target) =>+ index.get(linkKey(target)) ?? opts.resolveExisting?.(linkKey(target)))+ stats.linked += pl.linked+ stats.dangling += pl.danglingfor (const b of page.blocks) {if (!b.html) continueconst r = resolveWikilinks(b.html, (target) =>