Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: footnotes, anchored as text and numbered at render time (#438)
nyblnetfda0d2b1a179
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 4509aa6b..52ffcc81 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -14,6 +14,50 @@ Decision. Why. Pointers.---+## 2026-09-10 — bento/spaces footnotes: the reference is a TEXT TOKEN, and the number is derived++**Decision.** A footnote in `bento/spaces` is `doc.footnotes` (a document-level+map, label → inline html — bento/type's shape) plus the literal text `[^label]`+inside a block's `html`. The number a reader sees is derived at render time from+order of appearance, per page, and is never stored.++**Why a text token rather than an anchor.** bento/type anchors a reference by+character offset into a block's `text` runs, and can: it owns the run list and+rewrites every offset in one place. A spaces block carries `html`, and an offset+into html is a position in one particular serialization of a position — three+things move it without changing a word of the prose: `canonicalize()` reorders+mark nesting at every typing-run close, `sanitizeInline()` unwraps and strips on+every read of untrusted html, and the CRDT merges `html` as one register, which+an offset in a second register cannot merge with.++The other candidate was an inline marker element (`<sup>`, or an `<a href="#fn/…">`+with a new scheme in `HREF_OK`). Rejected because a new allowlist entry is a+ONE-WAY DATA HAZARD, which sanitize.ts's own comment on `HREF_OK` already spells+out: a reference written by this build would be STRIPPED, silently, by every+build shipped before it, on the first edit that touched the block. A text token+is round-tripped byte-for-byte by builds that already exist — verified by+loading a footnoted document into a shell built from the previous release.++**Why the number is derived.** Footnotes renumber on insertion, so a stored+number is wrong the moment a sentence moves and nothing says so. Same rule as+calc.ts's magic notes and slides' dynamic fields: store the token, derive the+output. The label is therefore an identifier, not a number, exactly as in pandoc+and Obsidian — which is also why the markdown round trip is the identity+function on the reference half.++**Consequences a future session should not treat as bugs.** (1) While a block is+being EDITED the author sees `[^1]`, not a superscript — injecting marker markup+into a contenteditable host puts it one keystroke from being committed into+`html` (`host.innerHTML` is written to the model on every `input`), which loses+the reference and stores a literal "1". The derived form is drawn in reading+view, print and the file-manager still. (2) A dangling reference is still+numbered and gets an empty row, because that is the authoring gesture and+because what is missing is the note, not the reference. (3) An orphaned note is+reported, never deleted. (4) `[^…]` inside a `code` block is not scanned.++**Pointers.** `spaces/src/footnotes.ts` (the whole argument, at length),+`spaces/CHANGELOG.md`, `docs/spaces-agents.md` §Footnotes, rigs in+`scripts/test-spaces-model.ts` and `scripts/test-spaces-agent.ts`.## 2026-10-05 — Android meets the `launchQueue` rules, and a reload also forgets its Save-As copies**Decision.** Android implements the two host rules from the entry below: adiff --git a/docs/spaces-agents.md b/docs/spaces-agents.mdindex 6ebcdb0f..6dbbb953 100644--- a/docs/spaces-agents.md+++ b/docs/spaces-agents.md@@ -203,6 +203,42 @@ Links are same-document fragments:`href` must match `^(https?:|mailto:|#p/)`. Anything else is stripped.+## Footnotes++A footnote reference is the literal text `[^label]` inside a block's `html`,+and the notes live in one document-level table:++```json+{+ "pages": [{ "id": "p1", "title": "Coffee", "blocks": [+ { "id": "b8", "type": "p", "html": "Coffee grows in the tropics.[^1]" }+ ] }],+ "footnotes": { "1": "Between Cancer and Capricorn." }+}+```++The reference is **text, not markup** — no tag, no attribute, nothing for the+sanitizer to allow — so it survives every edit and every sanitize pass exactly+the way the word beside it does, and a build that predates footnotes shows the+sentence with `[^1]` in it and round-trips the `footnotes` key untouched.++A label is `[A-Za-z0-9_-]{1,32}`. It is an **identifier, not a number**: notes+are numbered by order of appearance and the number is derived when the page is+drawn, so inserting a reference earlier on the page renumbers everything after+it and nothing in the file changes. Never write a number into the model and+never expect `[^1]` to render as 1.++Numbering is **per page** — the page is what prints and what a reader reads.+The section at the foot of a page is derived too: it is that page's references,+in order, so there is no block to add and nothing to keep in step. A note's+value is inline `html`, under the same allowlist as a block's.++`[^label]` inside a `code` block is left alone. It is not scanned in one and+never becomes a reference.++Markdown import and export both speak `[^1]` and `[^1]: the note.`, so an+Obsidian or Pandoc vault keeps its footnotes in both directions.+## The issue tracker**An issue is a page.** There is no issue type and no flag: a page carrying a@@ -357,6 +393,13 @@ markup inside inline `html` (and markup that is dropped whole), hrefs outside thallowlist, images with no `alt`, no size, a missing `asset:` or a remote `src`,a `home` naming nothing, pages with no blocks, and assets nothing references.+On footnotes it adds `dangling-footnote` (**warning**: a `[^label]` with no+note behind it — the reference still renders, numbered, into an empty note),+`orphan-footnote` (**info**: a note in `doc.footnotes` that nothing references,+so it is never numbered and never printed — it is kept, never deleted) and+`unreachable-footnote` (**warning**: a label outside the grammar above, which+no `[^label]` can ever match).+On the tracker it adds: `prop-html-stale` (a value whose readable `html` sayssomething else — the check worth running after any hand edit),`unknown-field-value` and `unknown-field-key` (**info**, because that is how adiff --git a/scripts/test-spaces-agent.ts b/scripts/test-spaces-agent.tsindex 3f188ef2..14f27314 100644--- a/scripts/test-spaces-agent.ts+++ b/scripts/test-spaces-agent.ts@@ -924,5 +924,56 @@ const issue = (id: string, values: Record<string, unknown>, extra: Record<string'every field is coerced to the type the report promises')}+// ---- footnotes: both broken shapes are REPORTED and neither throws ---------+//+// An orphaned note (the sentence went, the note stayed) and a dangling+// reference (the note went, the marker stayed) are the two ways a footnote can+// come apart, and BOTH are invisible from the page: the prose still reads, the+// file still parses, and nothing is missing that an author would notice. That+// is precisely the shape of thing a validator exists for.+{+ const doc = load([+ p('p1', [+ { id: 'b1', type: 'p', html: 'A claim.[^1] Another.[^gone]' },+ ]),+ ], { footnotes: { '1': 'the note', spare: 'nobody points at me', 'a b': 'unreachable' } })++ const v = validateDoc(doc)+ const codes = new Set(v.findings.map((f) => f.code))+ ok(codes.has('dangling-footnote'), 'a reference with no note behind it is reported')+ ok(codes.has('orphan-footnote'), 'a note nothing references is reported')+ ok(codes.has('unreachable-footnote'),+ 'a label no [^token] could ever match is reported — the note is stranded, silently')++ const dang = v.findings.filter((f) => f.code === 'dangling-footnote')+ ok(dang.length === 1 && dang[0].block === 'b1' && dang[0].page === 'p1',+ 'the dangling one names the page and block it is in, so it can be found')+ ok(dang.every((f) => f.severity === 'warning'),+ 'and it is a WARNING, not an error — no word was lost, only the connection')+ ok(v.findings.filter((f) => f.code === 'orphan-footnote').every((f) => f.severity === 'info'),+ 'an orphaned note is INFO: it is still somebody’s writing, sitting in the file')+ ok(v.findings.filter((f) => f.code.endsWith('footnote')).every((f) => !!f.fix && !!f.message),+ 'every footnote finding says what is wrong AND how to fix it')++ // NEITHER MAY EVER THROW. `doc.footnotes` arrives in a file somebody mailed+ // you, so every shape a hand edit or a generator can produce has to be inert.+ for (const bad of ['yes', 7, null, [], { a: 5 }, { a: null }]) {+ let threw = false+ try {+ validateDoc(load([p('p1', [{ id: 'b1', type: 'p', html: 'x[^a]' }])], { footnotes: bad }))+ } catch { threw = true }+ ok(!threw, `validate() survives footnotes: ${JSON.stringify(bad)}`)+ }++ // a document with matched references and notes reports NEITHER — a validator+ // that cries wolf on good documents is one an agent learns to skip+ const clean = validateDoc(load([+ p('p1', [{ id: 'b1', type: 'p', html: 'A claim.[^1]' }]),+ ], { footnotes: { '1': 'the note' } }))+ const cleanCodes = new Set(clean.findings.map((f) => f.code))+ ok(!cleanCodes.has('dangling-footnote') && !cleanCodes.has('orphan-footnote'),+ 'a document whose footnotes all match reports nothing about them')+}+console.log(`\n${checks - failures}/${checks} checks passed`)if (failures) process.exit(1)diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.tsindex 229c78ef..8725147c 100644--- a/scripts/test-spaces-model.ts+++ b/scripts/test-spaces-model.ts@@ -44,6 +44,9 @@ import {VIEW_LAYOUTS, layoutOf, nextLayout,} from '../spaces/src/fields.ts'import { inlineHtml, parseNote, planImport } from '../spaces/src/markdown.ts'+import {+ notesOnPage, markRefs, noteOf, orphanNotes, danglingRefs, refsIn, definitionLines,+} from '../spaces/src/footnotes.ts'import {canonicalMarks, applyMark, clearMarks, markActive, linkAt, linkAttrs, htmlToMd,CLASS_OK, keepClasses,@@ -3620,6 +3623,222 @@ function fsTable(f: string): string {}+// ---- 9. FOOTNOTES ----------------------------------------------------------+//+// The anchor is a TEXT TOKEN (`[^1]`) in a block's html and the number is+// DERIVED at render time from order of appearance — spaces/src/footnotes.ts+// argues both at length. What follows pins the two properties that make that+// design worth anything, and they are asserted BEHAVIOURALLY (the functions are+// imported and run) rather than by grepping the source, because a source grep+// passes through a live regression: this rig has watched that happen twice.+{+ const mkdoc = (pages: SpacesDoc["pages"], footnotes?: Record<string, string>): SpacesDoc =>+ ({+ format: FORMAT, version: 1, docId: 'd1', title: 'T',+ pages, theme: {} as never, ...(footnotes ? { footnotes } : {}),+ }) as unknown as SpacesDoc++ // ---- numbering is derived, so an INSERT renumbers what follows -----------+ //+ // THE LOAD-BEARING ONE. If the number were stored, this is the case that+ // would be wrong and silent: the author inserts a note earlier in the page+ // and every note after it keeps the number it was born with.+ {+ const page = {+ id: 'p1', title: 'P',+ blocks: [+ { id: 'b1', type: 'p', html: 'The first claim.[^a]' },+ { id: 'b2', type: 'p', html: 'The second claim.[^b]' },+ ],+ }+ const doc = mkdoc([page], { a: 'note A', b: 'note B' })++ const before = notesOnPage(doc, page as never)+ ok(before.num.get('a') === 1 && before.num.get('b') === 2,+ 'footnotes number 1,2 in order of appearance')+ // RENDERED, not just the map: markRefs is what the reader actually sees.+ ok(markRefs('The second claim.[^b]', before, 'p1').includes('>2</a>'),+ 'the second reference RENDERS as 2')++ // now insert a THIRD note ahead of both of them+ page.blocks.unshift({ id: 'b0', type: 'p', html: 'An earlier aside.[^c]' })+ ;(doc as { footnotes: Record<string, string> }).footnotes.c = 'note C'++ const after = notesOnPage(doc, page as never)+ ok(after.num.get('c') === 1 && after.num.get('a') === 2 && after.num.get('b') === 3,+ 'inserting a footnote BEFORE the others renumbers them: c=1, a=2, b=3')+ ok(markRefs('The first claim.[^a]', after, 'p1').includes('>2</a>'),+ 'the first claim RENDERS as 2 now — the number moved with the page, not with the note')+ ok(markRefs('The second claim.[^b]', after, 'p1').includes('>3</a>'),+ 'the second claim RENDERS as 3')+ // and the DOCUMENT still says what the author wrote+ ok(page.blocks[1].html === 'The first claim.[^a]',+ 'the model still holds the label, never the number — nothing was rewritten')++ // a repeat of the same label reuses its number, as every footnote system does+ const rep = notesOnPage(mkdoc([{ id: 'p9', title: 'P', blocks: [+ { id: 'x', type: 'p', html: 'one[^a] two[^b] again[^a]' },+ ] }], { a: 'A', b: 'B' }), { id: 'p9', title: 'P', blocks: [+ { id: 'x', type: 'p', html: 'one[^a] two[^b] again[^a]' },+ ] } as never)+ ok(rep.order.length === 2 && rep.num.get('a') === 1 && rep.num.get('b') === 2,+ 'the same label twice on a page is one note, numbered once')+ }++ // ---- markdown round trip: [^1] in and [^1] out ---------------------------+ {+ const src = [+ '# Imported',+ '',+ 'Coffee is grown in the tropics.[^1] Tea is not.[^tea]',+ '',+ '[^1]: Between the Tropics of Cancer and Capricorn.',+ '[^tea]: Mostly, anyway.',+ '',+ ].join('\n')+ const note = parseNote(src, 'file')+ ok(note.footnotes?.['1'] === 'Between the Tropics of Cancer and Capricorn.',+ 'a [^1]: definition line is taken out of the file and becomes a note')+ ok(note.footnotes?.tea === 'Mostly, anyway.', 'a named label survives too')+ const prose = note.blocks.map((b) => b.html ?? '').join(' ')+ ok(prose.includes('[^1]') && prose.includes('[^tea]'),+ 'the REFERENCES pass through untouched — markdown and this model spell them the same')+ ok(!prose.includes('Tropics of Cancer'),+ 'the definition line did NOT arrive as a paragraph (the silent-downgrade failure)')++ // ...and back out again+ const doc = mkdoc([{ id: 'p1', title: 'Imported', blocks: note.blocks }], note.footnotes)+ const lines = definitionLines(doc, doc.pages[0], (h) => h)+ ok(lines[0] === '[^1]: Between the Tropics of Cancer and Capricorn.',+ 'exporting writes the definition back in the same syntax')+ ok(lines.length === 2 && lines[1] === '[^tea]: Mostly, anyway.',+ '…for every note the page references, in rendered order')++ // the whole loop, twice: parse → export → parse must be a fixed point+ const again = parseNote(['# Imported', '', prose, '', ...lines, ''].join('\n'), 'file')+ ok(JSON.stringify(again.footnotes) === JSON.stringify(note.footnotes),+ 'markdown round trip is lossless: the same notes come back under the same labels')+ }++ // ---- a note is not read through the prototype chain ----------------------+ //+ // `doc.footnotes` is DATA OUT OF A FILE. A bare lookup hands back+ // Object.prototype.toString for the label `toString` — a FUNCTION, which is+ // truthy, so a `?? ''` never fires and its source gets stringified into the+ // page. That exact bug has shipped twice in this app.+ {+ const doc = mkdoc([{ id: 'p1', title: 'P', blocks: [+ { id: 'b1', type: 'p', html: 'trap[^toString] and[^constructor]' },+ ] }])+ ok(noteOf(doc, 'toString') === undefined, 'noteOf("toString") is undefined, not a function')+ const notes = notesOnPage(doc, doc.pages[0])+ ok(notes.dangling.length === 2, 'both prototype labels are DANGLING, not satisfied')+ const out = markRefs('trap[^toString] and[^constructor]', notes, 'p1')+ ok(!out.includes('function') && !out.includes('native code'),+ 'and nothing from Object.prototype reaches the rendered html')+ }++ // ---- hostile / hand-edited shapes never throw ----------------------------+ {+ for (const bad of ['yes', 42, null, [], { a: 5 }, { 'a b': 'x' }]) {+ const doc = mkdoc([{ id: 'p1', title: 'P', blocks: [{ id: 'b', type: 'p', html: 'x[^a]' }] }])+ ;(doc as Record<string, unknown>).footnotes = bad+ let threw = false+ try {+ const n = notesOnPage(doc, doc.pages[0])+ markRefs('x[^a]', n, 'p1')+ orphanNotes(doc)+ danglingRefs(doc)+ } catch { threw = true }+ ok(!threw, `a footnotes field of ${JSON.stringify(bad)} is ignored, never iterated into a throw`)+ }+ }++ // ---- an unknown reference stays the author's own text --------------------+ {+ const doc = mkdoc([{ id: 'p1', title: 'P', blocks: [+ { id: 'b', type: 'p', html: 'see [^nope] and [^yes]' },+ ] }], { yes: 'here' })+ const n = notesOnPage(doc, doc.pages[0])+ const out = markRefs('see [^nope] and [^yes]', n, 'p1')+ // A DANGLING REFERENCE IS STILL NUMBERED, deliberately: it gets a marker+ // and an EMPTY row in the section, which is both the authoring gesture+ // (type [^1], get a slot to write into) and the honest reading — the note+ // is missing, not the reference. Leaving it as raw `[^nope]` in the reading+ // view was the other candidate and shows the reader syntax they never typed.+ ok((out.match(/sp-fnref/g) ?? []).length === 2,+ 'a reference with no note is still numbered — the note is what is missing, not the reference')+ ok(!out.includes('[^nope]'), '…so no raw token is left in the reading view')+ ok(danglingRefs(doc).length === 1 && danglingRefs(doc)[0].label === 'nope',+ 'and it is reported as dangling, with the block it is in')+ // a token this page's numbering does not know is untouched — that is the+ // path a table cell from another page, or a half-typed `[^`, takes+ ok(markRefs('other [^elsewhere]', n, 'p1') === 'other [^elsewhere]',+ 'a token outside this page’s numbering is left exactly as the author typed it')+ }++ // ---- an orphaned note is reported and never deleted ----------------------+ {+ const doc = mkdoc([{ id: 'p1', title: 'P', blocks: [{ id: 'b', type: 'p', html: 'nothing here' }] }],+ { a: 'a note nobody points at' })+ ok(JSON.stringify(orphanNotes(doc)) === '["a"]', 'a note nothing references is reported as an orphan')+ ok(noteOf(doc, 'a') === 'a note nobody points at', '…and is still in the document, untouched')+ }++ // ---- a code block is not scanned ----------------------------------------+ {+ const doc = mkdoc([{ id: 'p1', title: 'P', blocks: [+ { id: 'b', type: 'code', html: 'grep "[^a]" file', lang: 'sh' },+ ] }], { a: 'A' })+ ok(notesOnPage(doc, doc.pages[0]).order.length === 0,+ '`[^a]` in a shell snippet is a shell snippet, not a footnote')+ }++ // ---- format additivity: the key survives a build that ignores it ---------+ {+ const json = JSON.stringify({+ format: FORMAT, version: 1, docId: 'd', title: 'T',+ pages: [{ id: 'p', title: 'P', blocks: [{ id: 'b', type: 'p', html: 'x[^1]' }] }],+ theme: {}, footnotes: { '1': 'kept' },+ })+ const res = parseDoc(json)+ ok(res.ok && (res.doc as { footnotes?: Record<string, string> }).footnotes?.['1'] === 'kept',+ 'doc.footnotes round-trips parseDoc untouched')+ ok(res.ok && JSON.parse(JSON.stringify(res.doc)).footnotes['1'] === 'kept',+ '…and survives re-serialization, which is what an older build does with it')+ }++ // ---- importing two files that both number from 1 ------------------------+ //+ // Two vaults collide by construction. Without the rename, the second file's+ // [^1] would be answered by the FIRST file's note: a wrong footnote, which is+ // worse than a missing one because nothing looks broken.+ {+ const plan = planImport([+ { path: 'a.md', text: '# A\n\nAlpha.[^1]\n\n[^1]: from A\n' },+ { path: 'b.md', text: '# B\n\nBeta.[^1]\n\n[^1]: from B\n' },+ ], { rootTitle: 'Imported' })+ const bodies = Object.values(plan.footnotes).sort()+ ok(bodies.length === 2 && bodies[0] === 'from A' && bodies[1] === 'from B',+ 'both files’ notes survive the import — neither is swallowed by the other')+ const pageA = plan.pages.find((p) => p.title === 'A')!+ const pageB = plan.pages.find((p) => p.title === 'B')!+ const refA = refsIn(pageA.blocks.map((b) => b.html ?? '').join(' '))[0]+ const refB = refsIn(pageB.blocks.map((b) => b.html ?? '').join(' '))[0]+ ok(refA !== refB, 'the colliding label was renamed in exactly one of the two files')+ ok(plan.footnotes[refA] === 'from A' && plan.footnotes[refB] === 'from B',+ 'and each page’s reference resolves to ITS OWN note')++ // the same file twice is not a collision — re-importing must not fork a note+ const same = planImport([+ { path: 'a.md', text: '# A\n\nAlpha.[^1]\n\n[^1]: from A\n' },+ { path: 'c/a.md', text: '# A2\n\nAlpha.[^1]\n\n[^1]: from A\n' },+ ], { rootTitle: 'Imported' })+ ok(Object.keys(same.footnotes).length === 1,+ 'an identical note under the same label is the same note, not a fork')+ }+}+// ---- ONE BRANCH PER LAYOUT -------------------------------------------------// A rebase duplicated a whole `if (layout === 'table')` block into render.ts.// Both copies compiled, both were valid, and the FIRST one returned — so thediff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex f25d6b5f..82ff16b2 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -486,6 +486,32 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.2026, from the same file. `bento.journal()` opens today's for an agent, and`bento.journal('2026-08-06')` any day's.+- **Footnotes.** A mark in the prose, the note at the foot of the page — write+ `[^1]` where the mark goes and the note appears as a numbered slot below the+ page to write into. Notes print, export as `[^1]: the note.` and import back+ the same way, so an Obsidian or Pandoc vault keeps its footnotes in both+ directions rather than losing them silently on the way in.++ **The number is never stored.** Footnotes are numbered by order of appearance+ and the number is worked out when the page is drawn, the way a magic note's+ answer and a slide's page number are: put a new reference above two existing+ ones and they renumber to 2 and 3 with nothing in the file changing. Measured+ in the built shell — `[^1]` renders as "2" while `block.html` still says+ `[^1]`. A stored number would have been wrong from the first sentence anyone+ moved, and nothing would have said so.++ **The reference is text, not markup**, which is the whole reason it survives+ editing: `[^1]` moves with the prose through a keystroke, a sanitize pass, a+ canonicalisation and a merge exactly the way the word beside it does, because+ there is no offset to keep in step and no attribute for the allowlist to have+ an opinion about. It also means a build that predates this shows the sentence+ with `[^1]` in it and hands the `footnotes` key back untouched — verified by+ loading a footnoted document into a shell built from the previous release.++ A reference whose note has been deleted still renders, numbered, into an+ empty note; a note whose reference has gone is kept, never quietly dropped.+ `bento.validate()` reports both (`dangling-footnote`, `orphan-footnote`) and+ names the block. Costs 3,176 bytes on the shell.- **A saved copy of a shared space rejoins its live session with its offlineedits.** ⌘S, Save a copy and both self-update writes now stamp the livesession's sync state into the file (`collab.sync`), as bento/slides alwaysdiff --git a/spaces/src/about.ts b/spaces/src/about.tsindex 80ce0b64..8cd8bc25 100644--- a/spaces/src/about.ts+++ b/spaces/src/about.ts@@ -41,6 +41,7 @@ import { t, localeChoices, locale, setLocale } from './i18n'import { appearanceSection } from './appearance'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 {@@ -628,6 +629,16 @@ export function toMarkdown(store: Store): string {out.push(...lines.flatMap((l) => l.split('\n')).map((l) => (l ? quote + l : quote.trimEnd())))out.push(sep)})+ // FOOTNOTE DEFINITIONS, AFTER THE PAGE THEY BELONG TO.+ //+ // Per page, not once at the end, because markdown scopes a definition to+ // its file and the export is ONE file: a `[^1]` on page nine answered by+ // page one's note would be a wrong footnote rather than a missing one.+ // The references themselves need nothing here — `[^1]` is already the+ // text in `html`, so htmlToMd carries it out unchanged, which is the+ // whole point of the anchor being a text token (src/footnotes.ts).+ const defs = definitionLines(store.doc, page, htmlToMd)+ if (defs.length) { out.push(...defs, '') }}}walk()diff --git a/spaces/src/agent.ts b/spaces/src/agent.tsindex e2b412a7..a688784e 100644--- a/spaces/src/agent.ts+++ b/spaces/src/agent.ts@@ -34,6 +34,7 @@ import { type SpacesDoc, type Page, type Block, buildIndex, isRemote, newBlock,import { SPECS, SPEC } from './blocks.ts'import { sanitizeInline, textOf, inertBody, esc, UNWRAP } from './sanitize.ts'import { orphanAssets, humanBytes } from './assets.ts'+import { danglingRefs, orphanNotes, LABEL_OK } from './footnotes.ts'import {type FieldSpec, ISSUE_FIELDS, fieldsOf, fieldByKey, optionOf, propBlock, propHtml, valuesOf, isIssue, headerLength,} from './fields.ts'@@ -539,6 +540,40 @@ export function validateDoc(doc: SpacesDoc): ValidateResult {fix: `Delete these keys to shrink the file: ${orphans.slice(0, 8).join(', ')}${orphans.length > 8 ? ', …' : ''}` })}+ // ---- footnotes -----------------------------------------------------------+ // BOTH HALVES ARE REPORTED AND NEITHER IS AN ERROR, because neither loses a+ // word: a dangling reference still shows the `[^1]` the author typed and a+ // note nothing points at is still the note they wrote. What they lose is the+ // CONNECTION, and a connection is exactly the thing an author cannot see is+ // missing by reading the page. Neither can throw — every lookup here goes+ // through footnotes.ts, which uses Object.hasOwn and tolerates a+ // `"footnotes": "yes"` out of a hand-edited file.+ for (const d of danglingRefs(doc)) {+ add({ page: d.pageId, block: d.blockId, code: 'dangling-footnote', severity: 'warning', path: 'footnotes',+ message: `A footnote reference [^${d.label}] has no note behind it, so it renders as the literal text "[^${d.label}]" instead of a number.`,+ fix: `Add "${d.label}" to doc.footnotes, or delete the [^${d.label}] from the text.` })+ }+ const loose = orphanNotes(doc)+ if (loose.length) {+ // ONE finding, like the orphan assets above and for the same reason: the+ // actionable fact is the total plus the labels, not a row each.+ add({ code: 'orphan-footnote', severity: 'info', path: 'footnotes',+ message: `${loose.length} footnote(s) in doc.footnotes are referenced by nothing, so they are never numbered and never printed: ${loose.slice(0, 8).join(', ')}${loose.length > 8 ? ', …' : ''}`,+ fix: 'Put a [^label] back in the text, or delete the key from doc.footnotes.' })+ }+ const rawNotes = (doc as { footnotes?: unknown }).footnotes+ if (rawNotes && typeof rawNotes === 'object' && !Array.isArray(rawNotes)) {+ // A label outside the token grammar can never be REFERENCED — `[^a b]`+ // does not match — so the note is unreachable however many times it is+ // written into the prose. Silent, and only findable from here.+ const bad = Object.keys(rawNotes as object).filter((k) => !LABEL_OK.test(k))+ if (bad.length) {+ add({ code: 'unreachable-footnote', severity: 'warning', path: 'footnotes',+ message: `${bad.length} footnote label(s) are outside the reference grammar (letters, digits, "_" and "-", up to 32), so no [^label] can ever point at them: ${bad.slice(0, 5).map((b) => JSON.stringify(b)).join(', ')}`,+ fix: 'Rename the key to a plain label and update the [^label] in the text.' })+ }+ }+const counts: Record<Severity, number> = { error: 0, warning: 0, info: 0 }for (const f of findings) counts[f.severity]++return { ok: counts.error === 0, counts, findings }diff --git a/spaces/src/editor.ts b/spaces/src/editor.tsindex 8587319c..4e5dae96 100644--- a/spaces/src/editor.ts+++ b/spaces/src/editor.ts@@ -18,6 +18,7 @@ import * as collabUi from './collabui.ts'import { syncNoticeText } from './syncnotice.ts'import { Store } from './store'import { renderPage, toneLabel, paintCode } from './render'+import { notesOnPage } from './footnotes.ts'import { wireCanvas, placeNewCard } from './canvas.ts'import { CODE_LANGS, langLabel, normLang } from './highlight'import { canonicalize, escText, sanitizeInline, textOf } from './sanitize'@@ -1041,10 +1042,36 @@ export class Editor {})}+ /**+ * Repaint if — and only if — this page's footnote NUMBERING has changed.+ *+ * DERIVE, DO NOT COMMIT: the same shape slides uses for linked charts and+ * connectors. Nothing is written to the document here; the section at the+ * foot of the page is a function of the references in the blocks, so the+ * only thing that can be stale is the DOM. The signature is the ordered+ * label list, which is exactly what the section and every marker are drawn+ * from — so an unconditional repaint on blur would be a caret-losing+ * flicker on every click, and no repaint at all would leave a note the+ * author just referenced with nowhere to write it.+ */+ private syncFootnotes(): void {+ const page = this.store.page+ if (!page) return+ const sig = notesOnPage(this.store.doc, page).order.join('\u001F')+ if (sig === this.fnSig) return+ this.fnSig = sig+ this.paintPage()+ }++ private fnSig = ''+// ---- the page -----------------------------------------------------------private paintPage(): void {const s = this.storeconst page = s.page+ // the baseline `syncFootnotes` compares against — set here so switching+ // pages can never leave the previous page's signature behind+ this.fnSig = page ? notesOnPage(s.doc, page).order.join('\u001F') : ''// The bar holds a reference to the block host it is floating over, and this// is about to replace every one of them.this.format?.close()@@ -2237,9 +2264,50 @@ export class Editor {const clean = canonicalize(b.html)if (clean !== b.html) { b.html = clean; host.innerHTML = clean }}+ // A FOOTNOTE REFERENCE TYPED INTO THIS BLOCK CHANGES THE PAGE.+ //+ // The section at the foot is derived from every block's references, so+ // adding or deleting a `[^1]` renumbers the notes and adds or removes a+ // row. Repainting on `input` would do it a keystroke sooner and take+ // the caret with it — half of `[^1` is not a reference, so every one of+ // those keystrokes is a signature change. Blur is the first moment the+ // caret is not the thing being protected.+ this.syncFootnotes()})}+ // FOOTNOTE BODIES. `data-edit-note` and not `data-edit`: the generic+ // handler above writes its host's html to a BLOCK, and a note is not one.+ // The label is the key into doc.footnotes and it is derived from the text —+ // so a note is created by the first keystroke into an empty slot and the+ // slot itself came from a `[^label]` somebody typed.+ if (!s.readOnly && !this.reading) {+ for (const body of view.querySelectorAll<HTMLElement>('[data-edit-note]')) {+ const label = body.dataset.editNote!+ body.addEventListener('input', () => {+ if (this.painting) return+ s.runEdit(`fn:${label}`, () => {+ const table = (s.doc.footnotes ??= {})+ table[label] = body.innerHTML+ })+ })+ body.addEventListener('blur', () => {+ if (this.painting) return+ s.endRun()+ const table = s.doc.footnotes+ if (!table || !Object.hasOwn(table, label)) return+ const clean = canonicalize(table[label])+ // AN EMPTIED NOTE IS DELETED, not stored as ''. An empty string is a+ // note that exists and says nothing, which reads to validate() as a+ // satisfied reference and prints as a blank numbered line; deleting+ // the key puts the reference back to dangling, which is the truth and+ // is what the author just did.+ if (!clean.trim()) delete table[label]+ else if (clean !== table[label]) { table[label] = clean; body.innerHTML = clean }+ })+ }+ }+for (const box of view.querySelectorAll<HTMLInputElement>('.sp-check')) {box.addEventListener('change', () => {const id = (box.closest('[data-block-id]') as HTMLElement).dataset.blockId!@@ -4538,12 +4606,18 @@ export class Editor {for (const page of plan.pages) {for (const b of page.blocks) if (b.html) b.html = sanitizeInline(b.html)}+ for (const [label, body] of Object.entries(plan.footnotes)) {+ plan.footnotes[label] = sanitizeInline(body)+ }// ONE step: pages, images and fonts land together or not at all.s.commit(() => {s.doc.pages.push(...plan.pages)if (Object.keys(plan.assets).length) Object.assign((s.doc.assets ??= {}), plan.assets)if (plan.fonts.length) (s.doc.fonts ??= []).push(...plan.fonts)+ // ADDITIONS ONLY here (unlike the Markdown path, whose plan starts from+ // this table): planGraft returns what the host does not already hold.+ if (Object.keys(plan.footnotes).length) Object.assign((s.doc.footnotes ??= {}), plan.footnotes)})if (plan.pages[0]) s.goToPage(plan.pages[0].id)this.repaint()@@ -4687,6 +4761,9 @@ export class Editor {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 it+ existingNotes: s.doc.footnotes,})// ---- images ------------------------------------------------------------@@ -4748,6 +4825,11 @@ export class Editor {for (const page of plan.pages) {for (const b of page.blocks) if (b.html) b.html = sanitizeInline(b.html)}+ // A NOTE IS INLINE HTML OUT OF SOMEBODY ELSE'S FILE and goes through the+ // same gate as a block's, in the same pass, for the same reason.+ for (const [label, body] of Object.entries(plan.footnotes)) {+ plan.footnotes[label] = sanitizeInline(body)+ }// The import already lands under exactly one root (planImport wraps a mixed// selection); re-homing that root is the whole of "add these under this@@ -4758,7 +4840,15 @@ export class Editor {for (const page of plan.pages) if (!page.parent || !arrived.has(page.parent)) page.parent = under}- s.commit(() => { s.doc.pages.push(...plan.pages) })+ s.commit(() => {+ s.doc.pages.push(...plan.pages)+ // `plan.footnotes` STARTED from this document's own table and had the+ // imported notes merged into it, renaming collisions — so it is assigned+ // whole rather than spread over the existing one. Absent stays absent+ // when nothing has footnotes, so importing plain notes does not add an+ // empty key to the file.+ if (Object.keys(plan.footnotes).length) s.doc.footnotes = plan.footnotes+ })if (plan.pages[0]) s.goToPage(plan.pages[0].id)this.repaint()this.status(t('Imported'))diff --git a/spaces/src/footnotes.ts b/spaces/src/footnotes.tsnew file mode 100644index 00000000..a929072c--- /dev/null+++ b/spaces/src/footnotes.ts@@ -0,0 +1,431 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// FOOTNOTES: a mark in the prose, the note at the foot of the page.+//+// The whole of this file is PURE — no DOM, no import that touches one — so+// scripts/test-spaces-model.ts imports it directly and asserts the parts that+// actually break: the numbering under an insert, the markdown round trip, an+// orphaned note and a dangling reference.+//+// ---------------------------------------------------------------------------+// THE SHAPE+// ---------------------------------------------------------------------------+//+// doc.footnotes: { "<label>": "<inline html>" } the notes, doc-level+// block.html: "…as measured[^1] last week…" the references+//+// The doc-level, id-keyed map is bento/type's (type/src/model.ts): a note has+// to be able to outlive the paragraph that points at it, and keying it by id+// means moving a paragraph between pages carries nothing but the reference.+//+// ---------------------------------------------------------------------------+// THE ANCHOR, WHICH IS THE ONE THING THAT DOES NOT CARRY OVER FROM type+// ---------------------------------------------------------------------------+//+// type anchors a reference by CHARACTER OFFSET into a block's `text` runs+// (`NoteRef { id, at }`). It can: a run list has stable offsets, and type+// rewrites every offset when the text changes, in one place.+//+// A spaces block carries `html`, not runs, and an offset into html is not a+// position — it is a position in one particular SERIALIZATION of a position.+// Three things move it without changing a word of the prose:+//+// · `canonicalize()` runs at every typing-run close. It reorders nesting+// (`<i><b>x</b></i>` → `<b><i>x</i></b>`), coalesces adjacent runs and+// drops empty ones. Byte offsets after the first mark are different+// afterwards; the text is identical.+// · `sanitizeInline()` runs on EVERY read of untrusted html, including at+// render time. It unwraps `<p>`, strips an href that fell out of the+// allowlist, filters class tokens. Every one of those changes the length+// of the string before the offset.+// · The CRDT holds `html` as one register and merges concurrent edits at the+// token level; an offset stored in a SECOND register cannot merge with it.+//+// So the reference is not stored beside the html. It is stored IN it, as text:+//+// [^label]+//+// A LITERAL TEXT TOKEN, and the reasons it wins are the reasons calc.ts gives+// for storing `budget * 0.3 =` rather than the answer:+//+// · IT MOVES WITH THE PROSE FOR FREE. Typing before it, bolding around it,+// merging two blocks, splitting one, a sanitize pass, a canonicalize pass,+// a CRDT merge — the token is characters, so every one of those carries it+// exactly the way it carries the word next to it. There is no offset to+// keep in step because there is no offset.+// · IT NEEDS NOTHING FROM sanitize.ts. No new tag, no new attribute, no new+// href scheme. That is not tidiness: an inline construct that needs a new+// allowlist entry is a ONE-WAY DATA HAZARD, spelled out in sanitize.ts's own+// comment on HREF_OK — a reference written by this build would be STRIPPED,+// silently, by every build shipped before it, on the first edit that touched+// the block. A text token is round-tripped byte-for-byte by every build that+// has ever existed, including the ones already on people's disks.+// · AN OLDER BUILD READS IT. `[^1]` in prose is the markdown/pandoc source+// form; a shell that has never heard of footnotes shows the sentence with+// `[^1]` in it, which is exactly what the author would have typed in any+// other editor. Degraded, not lost.+// · MARKDOWN IS THE IDENTITY FUNCTION on the reference half. `[^1]` in,+// `[^1]` out, no conversion, nothing to get wrong.+// · IT IS GREPPABLE. ⌘F, the search index and `textOf()` all see it, because+// it is text.+//+// The cost, stated plainly: while you are EDITING a block you see `[^1]`, not+// a superscript 1. That is deliberate and it is the same trade render.ts makes+// for magic notes — the model holds what you wrote and the DERIVED form is+// drawn where it cannot be typed into. Injecting the marker markup into the+// contenteditable host would put it one keystroke away from being committed+// into `html` (`host.innerHTML` is written to the model on every `input`), at+// which point the note is a literal "1" and the reference is gone. That is a+// data-loss-shaped bug and no amount of care on the read-back path makes it+// not one.+//+// ---------------------------------------------------------------------------+// THE NUMBER IS DERIVED, NEVER STORED+// ---------------------------------------------------------------------------+//+// Footnotes are numbered by ORDER OF APPEARANCE, so inserting one renumbers+// everything after it. calc.ts and slides' dynamic fields settle this: store+// the token, derive the output. A stored number is wrong the moment a sentence+// moves, and nothing tells the author it went wrong.+//+// The LABEL is therefore an identifier and not a number, exactly as it is in+// pandoc and Obsidian. `[^1]` moved to the end of the page still says `[^1]`+// in the file and renders as "3". Which is also why the markdown round trip is+// lossless: the label is the thing markdown stores too.+//+// Numbering is PER PAGE. A page is the unit that prints, the unit that is read+// and the unit a note sits at the foot of; numbering the whole space would+// give the third page of a wiki footnote 47.++import type { Block, Page, SpacesDoc } from './model.ts'++/**+ * What a label may be: the character set every markdown implementation agrees+ * on for `[^…]`, and short enough that a runaway `[^` in prose cannot make the+ * scanner walk a paragraph.+ *+ * Deliberately NOT the full pandoc set (which allows almost anything but+ * whitespace): a narrow class keeps the token safe to interpolate into an+ * `id=` and an `href="#…"` without escaping games, and it is the set an author+ * actually types.+ */+export const LABEL_OK = /^[A-Za-z0-9_-]{1,32}$/++/**+ * A fresh scanner every time.+ *+ * A module-level `/g` regex carries `lastIndex` between calls, so the second+ * caller starts halfway through its own string and finds nothing. That has+ * shipped as a bug in this repo's neighbourhood before; a factory cannot.+ */+const refRe = (): RegExp => /\[\^([A-Za-z0-9_-]{1,32})\]/g++/** A definition line as markdown writes it: `[^1]: the note.` */+const DEF_RE = /^\[\^([A-Za-z0-9_-]{1,32})\]:[ \t]?(.*)$/++/**+ * The note behind a label, or undefined.+ *+ * `Object.hasOwn`, never `in` and never truthiness. `doc.footnotes` is DATA OUT+ * OF A FILE and a bare index reaches the prototype chain: `footnotes.toString`+ * is a FUNCTION, which is truthy, so a `?? ''` never fires and the stringified+ * source of `Object.prototype.toString` is what gets rendered into the page.+ * That exact bug has shipped twice in this app (the icon lookup, the asset+ * lookup) and both times it was a bare lookup on author-supplied data.+ */+export function noteOf(doc: SpacesDoc, label: string): string | undefined {+ const table = (doc as { footnotes?: unknown }).footnotes+ if (!table || typeof table !== 'object' || Array.isArray(table)) return undefined+ if (!Object.hasOwn(table as object, label)) return undefined+ const v = (table as Record<string, unknown>)[label]+ return typeof v === 'string' ? v : undefined+}++/** Every note in the document, by label — defensive about the shape, because+ * `"footnotes": "yes"` must be ignored rather than iterated. */+export function allNotes(doc: SpacesDoc): Array<[string, string]> {+ const table = (doc as { footnotes?: unknown }).footnotes+ if (!table || typeof table !== 'object' || Array.isArray(table)) return []+ return Object.entries(table as Record<string, unknown>)+ .filter(([k, v]) => LABEL_OK.test(k) && typeof v === 'string') as Array<[string, string]>+}++/**+ * The strings of a block that hold prose, in reading order.+ *+ * A table keeps its content in `rows` and MIRRORS it into `html` as the+ * additivity fallback (model.ts writeTable). Scanning both would count every+ * reference in a cell twice; scanning `html` alone would number a reference+ * that the table renderer — which draws from `rows` — never marks up. So a+ * table is its cells and everything else is its html, which is the same+ * either/or buildIndex makes about links, decided from the same fact.+ *+ * A `code` block is EXCLUDED. Its html is escaped literal text; `[^1]` in a+ * shell snippet is a shell snippet.+ */+export function proseOf(b: Block): string[] {+ if (b.type === 'code') return []+ if (b.type === 'table' && Array.isArray(b.rows)) {+ const out: string[] = []+ for (const row of b.rows as unknown[]) {+ if (!Array.isArray(row)) continue+ for (const cell of row) if (typeof cell === 'string') out.push(cell)+ }+ return out+ }+ return typeof b.html === 'string' && b.html ? [b.html] : []+}++/** The labels referenced in one string, in order, duplicates included. */+export function refsIn(html: string): string[] {+ const out: string[] = []+ for (const m of html.matchAll(refRe())) out.push(m[1])+ return out+}++/** What a page's footnotes come to, all derived. */+export interface PageNotes {+ /** labels in first-appearance order — INCLUDING ones with no note behind+ * them, because a reference the author has not written the note for yet is+ * the normal state one second after typing it */+ order: string[]+ /** label → the number it renders as, 1-based */+ num: Map<string, number>+ /** referenced here, no note in doc.footnotes — reported by validate() and+ * shown as an empty slot in the editor rather than silently swallowed */+ dangling: string[]+}++/**+ * Number a page's footnotes: first appearance wins, repeats reuse the number.+ *+ * PURE and READ-TIME, the same choice `effectiveParents` and `tableOf` make+ * for the same reason — two readers of one file agree without exchanging an+ * op, and merely opening a space rewrites nothing.+ */+export function notesOnPage(doc: SpacesDoc, page: Page): PageNotes {+ const order: string[] = []+ const num = new Map<string, number>()+ const dangling: string[] = []+ for (const b of Array.isArray(page.blocks) ? page.blocks : []) {+ for (const src of proseOf(b)) {+ for (const label of refsIn(src)) {+ if (num.has(label)) continue+ num.set(label, order.length + 1)+ order.push(label)+ if (noteOf(doc, label) === undefined) dangling.push(label)+ }+ }+ }+ return { order, num, dangling }+}++/** Every label referenced anywhere in the document. */+export function referencedLabels(doc: SpacesDoc): Set<string> {+ const out = new Set<string>()+ for (const p of Array.isArray(doc.pages) ? doc.pages : []) {+ for (const b of Array.isArray(p.blocks) ? p.blocks : []) {+ for (const src of proseOf(b)) for (const l of refsIn(src)) out.add(l)+ }+ }+ return out+}++/**+ * Notes nothing points at any more — the author deleted the sentence and kept+ * the note.+ *+ * NOT repaired and NOT deleted. The note is somebody's writing; dropping it+ * because the marker went would be the same silent loss the reference design+ * exists to avoid. validate() says so out loud instead.+ */+export function orphanNotes(doc: SpacesDoc): string[] {+ const used = referencedLabels(doc)+ return allNotes(doc).map(([k]) => k).filter((k) => !used.has(k)).sort()+}++/** Every dangling reference in the document, with where it is. */+export function danglingRefs(doc: SpacesDoc): Array<{ pageId: string; blockId: string; label: string }> {+ const out: Array<{ pageId: string; blockId: string; label: string }> = []+ const seen = new Set<string>()+ for (const p of Array.isArray(doc.pages) ? doc.pages : []) {+ for (const b of Array.isArray(p.blocks) ? p.blocks : []) {+ for (const src of proseOf(b)) {+ for (const label of refsIn(src)) {+ if (noteOf(doc, label) !== undefined) continue+ const key = `${b.id}${label}`+ if (seen.has(key)) continue+ seen.add(key)+ out.push({ pageId: p.id, blockId: b.id, label })+ }+ }+ }+ }+ return out+}++// ---------------------------------------------------------------------------+// rendering — the STRING half, so it is testable without a browser+// ---------------------------------------------------------------------------++/** DOM ids are document-global and PRINT draws every page at once, so a+ * label's ids are scoped by page or two pages using `[^1]` collide. */+export const refId = (scope: string, label: string): string => `spfnr-${scope}-${label}`+export const noteId = (scope: string, label: string): string => `spfn-${scope}-${label}`++const attr = (s: string): string =>+ s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')++/**+ * Replace every KNOWN reference token in a piece of already-sanitized inline+ * html with its superscript marker.+ *+ * RUNS AFTER sanitizeInline, never before — the markup this emits is OURS, and+ * feeding it back through the allowlist would strip the class and the+ * fragment href. That ordering is the reason no sanitizer change was needed+ * for this feature at all.+ *+ * SUBSTITUTION IS TEXT-CHUNK ONLY. The html is split into tags and text, and+ * only the text is touched: a `[^1]` that somehow ended up inside an+ * attribute value stays an attribute value. A token whose brackets an author+ * has split across a mark boundary (`[^<b>1</b>]`) is not contiguous text and+ * is left alone — it reads as literal, which is honest, rather than being+ * half-matched.+ *+ * A DANGLING REFERENCE IS STILL NUMBERED. `notesOnPage` puts a label with no+ * note behind it on the list anyway, so it gets a marker and an EMPTY row in+ * the section: that is the authoring gesture (type `[^1]`, get a slot to write+ * the note into) and it is the honest reading — what is missing is the note,+ * not the reference. Leaving it as raw `[^1]` in the reading view was the other+ * candidate and shows a reader syntax they never typed.+ *+ * A token this page's numbering does not know at all — a half-typed `[^`, a+ * cell carried in from somewhere else — is left as the literal text the author+ * typed. Nothing is ever removed from the prose here.+ */+export function markRefs(html: string, notes: PageNotes, scope: string): string {+ if (!html || !notes.num.size) return html+ return html.replace(/<[^>]*>|[^<]+/g, (chunk) => {+ if (chunk.startsWith('<')) return chunk+ return chunk.replace(refRe(), (whole, label: string) => {+ const n = notes.num.get(label)+ if (n === undefined) return whole+ return `<sup class="sp-fnref" id="${attr(refId(scope, label))}">`+ + `<a href="#${attr(noteId(scope, label))}">${n}</a></sup>`+ })+ })+}++// ---------------------------------------------------------------------------+// markdown+// ---------------------------------------------------------------------------++/**+ * Take the `[^1]: …` definitions out of a markdown file.+ *+ * Returns the remaining lines and the notes, so the caller's parser never sees+ * a definition line and cannot turn it into a paragraph. That downgrade — a+ * construct silently arriving as something duller — is exactly the import loss+ * the transclusion work found with `![[embed]]`, and it is the whole reason+ * this runs before the block parser rather than after it.+ *+ * A CONTINUATION LINE (indented under the definition, as pandoc allows) is+ * folded into the note with a space. A blank line ends the note.+ */+export function takeDefinitions(lines: string[]): { rest: string[]; notes: Record<string, string> } {+ const rest: string[] = []+ const notes: Record<string, string> = {}+ let open: string | null = null+ for (const line of lines) {+ const m = DEF_RE.exec(line)+ if (m) {+ open = m[1]+ // FIRST DEFINITION WINS, so a file that defines `[^1]` twice does not+ // depend on which half of it the reader remembers.+ if (!Object.hasOwn(notes, open)) notes[open] = m[2].trim()+ continue+ }+ if (open !== null) {+ if (/^[ \t]+\S/.test(line)) { notes[open] = `${notes[open]} ${line.trim()}`.trim(); continue }+ if (!line.trim()) { open = null; continue }+ open = null+ }+ rest.push(line)+ }+ return { rest, notes }+}++/**+ * The definition lines for one page's notes, in rendered order.+ *+ * Emitted per page because that is where they are numbered and where a reader+ * looks for them, and because markdown scopes a definition to its file — the+ * export writes one file, and a `[^1]` on page nine must not be answered by+ * page one's note. The label is written out unchanged, so re-importing the+ * export gives back the same labels and therefore the same notes.+ */+export function definitionLines(doc: SpacesDoc, page: Page, toMd: (html: string) => string): string[] {+ const notes = notesOnPage(doc, page)+ const out: string[] = []+ for (const label of notes.order) {+ const body = noteOf(doc, label)+ if (body === undefined) continue+ // ONE LINE each: a note is inline content, and a newline inside it would+ // need the four-space continuation to survive — the flattening is what the+ // `<br>` was worth, and it is the same flattening htmlToMd already does+ // everywhere else.+ out.push(`[^${label}]: ${toMd(body).replace(/\n+/g, ' ').trim()}`)+ }+ return out+}++// ---------------------------------------------------------------------------+// writing+// ---------------------------------------------------------------------------++/** A label nothing in this document is using yet. */+export function freshLabel(doc: SpacesDoc, used: Set<string> = referencedLabels(doc)): string {+ const taken = new Set([...used, ...allNotes(doc).map(([k]) => k)])+ for (let n = 1; ; n++) if (!taken.has(String(n))) return String(n)+}++/**+ * Merge an incoming set of notes into a document's, renaming any label that+ * would land on a DIFFERENT note.+ *+ * Two vaults both number their footnotes from 1, so an import of more than one+ * file collides by construction; without this, the second file's `[^1]` would+ * silently answer with the first file's note. Returns the renames so the+ * caller can rewrite the references in that file's blocks.+ *+ * An IDENTICAL note under the same label is not a collision — re-importing the+ * same file must not fork the note.+ */+export function mergeNotes(+ into: Record<string, string>,+ incoming: Record<string, string>,+ used: Set<string>,+): Map<string, string> {+ const renames = new Map<string, string>()+ for (const [label, body] of Object.entries(incoming)) {+ if (!LABEL_OK.test(label)) continue+ if (!Object.hasOwn(into, label)) { into[label] = body; used.add(label); continue }+ if (into[label] === body) { used.add(label); continue }+ let n = 2+ let next = `${label}-${n}`+ while (Object.hasOwn(into, next) || used.has(next)) next = `${label}-${++n}`+ into[next] = body+ used.add(next)+ renames.set(label, next)+ }+ return renames+}++/** Rewrite reference tokens after a merge renamed their labels. */+export function renameRefs(html: string, renames: Map<string, string>): string {+ if (!renames.size) return html+ return html.replace(refRe(), (whole, label: string) => {+ const next = renames.get(label)+ return next ? `[^${next}]` : whole+ })+}diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.tsindex 5de3ea8c..08de3ad6 100644--- a/spaces/src/i18n/de.ts+++ b/spaces/src/i18n/de.ts@@ -629,6 +629,9 @@ export const de: Catalog = {"Date": "Datum","Person": "Person","Labels": "Labels",+ "Footnotes": "Fußnoten",+ "Back to the text": "Zurück zum Text",+ "Write the note": "Notiz schreiben","People": "Personen","Share a copy": "Kopie teilen","Same pages, new identity — it never syncs with this one": "Dieselben Seiten, neue Identität — synchronisiert nie mit diesem Space",diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.tsindex 9250d77b..cf14ad8b 100644--- a/spaces/src/i18n/es.ts+++ b/spaces/src/i18n/es.ts@@ -629,6 +629,9 @@ export const es: Catalog = {"Date": "Fecha","Person": "Persona","Labels": "Etiquetas",+ "Footnotes": "Notas al pie",+ "Back to the text": "Volver al texto",+ "Write the note": "Escribe la nota","People": "Personas","Share a copy": "Compartir una copia","Same pages, new identity — it never syncs with this one": "Las mismas páginas, una identidad nueva — nunca se sincroniza con este",diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.tsindex c71a728c..c09eb69a 100644--- a/spaces/src/i18n/fr.ts+++ b/spaces/src/i18n/fr.ts@@ -629,6 +629,9 @@ export const fr: Catalog = {"Date": "Date","Person": "Personne","Labels": "Étiquettes",+ "Footnotes": "Notes de bas de page",+ "Back to the text": "Revenir au texte",+ "Write the note": "Rédigez la note","People": "Personnes","Share a copy": "Partager une copie","Same pages, new identity — it never syncs with this one": "Les mêmes pages, une nouvelle identité — il ne se synchronise jamais avec celui-ci",diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.tsindex fc519d2c..10c2e741 100644--- a/spaces/src/i18n/it.ts+++ b/spaces/src/i18n/it.ts@@ -629,6 +629,9 @@ export const it: Catalog = {"Date": "Data","Person": "Persona","Labels": "Etichette",+ "Footnotes": "Note a piè di pagina",+ "Back to the text": "Torna al testo",+ "Write the note": "Scrivi la nota","People": "Persone","Share a copy": "Condividi una copia","Same pages, new identity — it never syncs with this one": "Le stesse pagine, una nuova identità — non si sincronizza mai con questo",diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.tsindex 3cce2e1b..4030154f 100644--- a/spaces/src/i18n/ja.ts+++ b/spaces/src/i18n/ja.ts@@ -629,6 +629,9 @@ export const ja: Catalog = {"Date": "日付","Person": "担当者","Labels": "ラベル",+ "Footnotes": "脚注",+ "Back to the text": "本文に戻る",+ "Write the note": "脚注を入力","People": "メンバー","Share a copy": "コピーを共有","Same pages, new identity — it never syncs with this one": "同じページ、新しい ID — このスペースとは同期しません",diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.tsindex 9ababa1e..4c696851 100644--- a/spaces/src/i18n/packed.ts+++ b/spaces/src/i18n/packed.ts@@ -69,6 +69,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Audio": ["音声","音频","音訊","Audio","Audio","Audio","Audio","Áudio"],"Audio from {host}": ["{host} の音声","来自 {host} 的音频","來自 {host} 的音訊","Audio de {host}","Audio provenant de {host}","Audio von {host}","Audio da {host}","Áudio de {host}"],"Back": ["戻る","返回","返回","Atrás","Retour","Zurück","Indietro","Voltar"],+ "Back to the text": ["本文に戻る","返回正文","回到內文","Volver al texto","Revenir au texte","Zurück zum Text","Torna al testo","Voltar ao texto"],"Background": ["背景","背景","背景","Fondo","Arrière-plan","Hintergrund","Sfondo","Plano de fundo"],"Block": ["ブロック","块","區塊","Bloque","Bloc","Block","Blocco","Bloco"],"Block options": ["ブロックのオプション","块选项","區塊選項","Opciones del bloque","Options du bloc","Block-Optionen","Opzioni del blocco","Opções do bloco"],@@ -199,6 +200,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Find or create a page…": ["ページを検索または作成…","查找或新建页面…","尋找或建立頁面…","Buscar o crear una página…","Trouver ou créer une page…","Seite finden oder erstellen…","Trova o crea una pagina…","Encontrar ou criar uma página…"],"Fit": ["全体表示","适应窗口","適應視窗","Ajustar","Ajuster","Einpassen","Adatta","Ajustar"],"Following — view only": ["追従中 — 閲覧のみ","跟随中 — 仅供查看","跟隨中 — 僅供檢視","Siguiendo — solo lectura","Suivi en cours — lecture seule","Folgt mit — nur Ansicht","In ascolto — sola lettura","Acompanhando — somente visualização"],+ "Footnotes": ["脚注","脚注","註腳","Notas al pie","Notes de bas de page","Fußnoten","Note a piè di pagina","Notas de rodapé"],"Formatting": ["書式","格式","格式","Formato","Mise en forme","Formatierung","Formattazione","Formatação"],"Full width": ["全幅","全宽","全寬","Ancho completo","Pleine largeur","Volle Breite","Larghezza piena","Largura total"],"Gallery": ["ギャラリー","图库","圖庫","Galería","Galerie","Galerie","Galleria","Galeria"],@@ -576,6 +578,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Windows on this computer still sync; turn offline mode off in About to work with someone elsewhere.": ["このコンピュータ上のウィンドウ同士は引き続き同期します。ほかの場所にいる人と作業するには「About」でオフラインモードを解除してください。","本机的窗口仍会同步;要与其他地方的人协作,请在“关于”中关闭离线模式。","本機的視窗仍會同步;要與其他地方的人協作,請在「關於」中關閉離線模式。","Las ventanas de este equipo siguen sincronizándose; desactiva el modo sin conexión en «Acerca de» para trabajar con alguien en otro lugar.","Les fenêtres de cet ordinateur restent synchronisées ; désactivez le mode hors ligne dans « À propos » pour travailler avec quelqu’un ailleurs.","Fenster auf diesem Computer synchronisieren sich weiterhin; deaktiviere den Offline-Modus unter „Über“, um mit jemandem anderswo zu arbeiten.","Le finestre su questo computer restano sincronizzate; disattiva la modalità offline in «Informazioni» per lavorare con qualcuno altrove.","As janelas neste computador continuam sincronizando; desative o modo offline em Sobre para trabalhar com alguém em outro lugar."],"Words": ["語数","字数","字數","Palabras","Mots","Wörter","Parole","Palavras"],"Workload": ["作業量","工作量","工作量","Carga de trabajo","Charge de travail","Auslastung","Carico di lavoro","Carga de trabalho"],+ "Write the note": ["脚注を入力","撰写脚注","撰寫註腳","Escribe la nota","Rédigez la note","Notiz schreiben","Scrivi la nota","Escreva a nota"],"Writing": ["書く","写作","書寫","Escribir","Écrire","Schreiben","Scrivere","Escrever"],"Wrong password — try again": ["パスワードが違います — もう一度お試しください","密码错误 — 请重试","密碼錯誤 — 請重試","Contraseña incorrecta: inténtalo de nuevo","Mot de passe incorrect — réessayez","Falsches Passwort — bitte erneut versuchen","Password errata — riprova","Palavra-passe incorreta — tente novamente"],"Yellow": ["黄","黄色","黃色","Amarillo","Jaune","Gelb","Giallo","Amarelo"],diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.tsindex d14b8155..35cac181 100644--- a/spaces/src/i18n/pt.ts+++ b/spaces/src/i18n/pt.ts@@ -629,6 +629,9 @@ export const pt: Catalog = {"Date": "Data","Person": "Pessoa","Labels": "Etiquetas",+ "Footnotes": "Notas de rodapé",+ "Back to the text": "Voltar ao texto",+ "Write the note": "Escreva a nota","People": "Pessoas","Share a copy": "Compartilhar uma cópia","Same pages, new identity — it never syncs with this one": "As mesmas páginas, uma nova identidade — nunca sincroniza com este",diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.tsindex 5abead29..4680955e 100644--- a/spaces/src/i18n/zh-Hans.ts+++ b/spaces/src/i18n/zh-Hans.ts@@ -629,6 +629,9 @@ export const zh_Hans: Catalog = {"Date": "日期","Person": "人员","Labels": "标签",+ "Footnotes": "脚注",+ "Back to the text": "返回正文",+ "Write the note": "撰写脚注","People": "成员","Share a copy": "分享副本","Same pages, new identity — it never syncs with this one": "页面相同,身份全新 — 永不与此空间同步",diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.tsindex afab8dec..491f4bc8 100644--- a/spaces/src/i18n/zh-Hant.ts+++ b/spaces/src/i18n/zh-Hant.ts@@ -629,6 +629,9 @@ export const zh_Hant: Catalog = {"Date": "日期","Person": "人員","Labels": "標籤",+ "Footnotes": "註腳",+ "Back to the text": "回到內文",+ "Write the note": "撰寫註腳","People": "成員","Share a copy": "分享副本","Same pages, new identity — it never syncs with this one": "頁面相同,身分全新 — 永不與此空間同步",diff --git a/spaces/src/markdown.ts b/spaces/src/markdown.tsindex f9803ef9..b72896f9 100644--- a/spaces/src/markdown.ts+++ b/spaces/src/markdown.ts@@ -18,6 +18,7 @@// `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 { takeDefinitions, mergeNotes, renameRefs } from './footnotes.ts'import { keepClasses } from './marks.ts'/** A tab indents four columns. Nothing here depends on the exact number; it@@ -193,6 +194,17 @@ export interface ParsedNote {remoteImages: number/** markdown tables, which this model has no block for yet */tables: number+ /**+ * `[^1]: the note.` definitions, by label — absent when the file has none.+ *+ * TAKEN OUT BEFORE THE BLOCK PARSER RUNS. A definition line left in the+ * stream parses as an ordinary paragraph, which is the silent downgrade this+ * importer has produced once before (`![[embed]]` arriving as a plain link):+ * nothing errors, the words are all still there, and the construct is gone.+ * The REFERENCES need no handling at all — `[^1]` is the same text in+ * markdown and in this model (src/footnotes.ts).+ */+ footnotes?: Record<string, string>}const mk = (type: string, extra: Partial<Block> = {}): Block => ({ id: uid('b'), type, ...extra })@@ -222,7 +234,11 @@ function imageOf(line: string): { ref: string; alt: string; caption?: string } |* pointing at a page whose name is nowhere in the sidebar.*/export function parseNote(text: string, fileTitle: string): ParsedNote {- const lines = text.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n').split('\n')+ // FOOTNOTE DEFINITIONS COME OUT FIRST, before a single line is classified.+ // They are a document-level table, not blocks, and a line the block parser+ // has already turned into a paragraph cannot be un-turned.+ const { rest: lines, notes: footnotes } =+ takeDefinitions(text.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n').split('\n'))const blocks: Block[] = []const images: PendingImage[] = []let remoteImages = 0@@ -423,6 +439,8 @@ export function parseNote(text: string, fileTitle: string): ParsedNote {images,remoteImages,tables,+ // absent when the file had none — a default is never stored (PLATFORM §3)+ ...(Object.keys(footnotes).length ? { footnotes } : {}),}}@@ -495,6 +513,18 @@ export interface ImportPlan {/** local image references, still to be resolved against picked files */images: PendingImage[]stats: ImportStats+ /**+ * The document's footnotes AFTER the import — `opts.existingNotes` with+ * every imported note merged in, so the caller assigns it whole.+ *+ * A SUPERSET, never a patch, because merging renames: two vaults both number+ * their footnotes from 1, so importing more than one file collides by+ * construction, and the second file's `[^1]` must not be answered by the+ * first file's note. Whatever was renamed has already been rewritten in that+ * file's blocks, here, where it is still known which blocks came from which+ * file.+ */+ footnotes: Record<string, string>}const normalizePath = (p: string): string =>@@ -528,6 +558,9 @@ export function planImport(* arrive as dead text.*/resolveExisting?: (target: string) => string | undefined+ /** 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>},): ImportPlan {const src = files@@ -544,6 +577,8 @@ export function planImport(const pages: Page[] = []const images: PendingImage[] = []+ const footnotes: Record<string, string> = { ...(opts.existingNotes ?? {}) }+ const usedLabels = new Set(Object.keys(footnotes))const stats: ImportStats = {files: src.length, pages: 0, blocks: 0, linked: 0, dangling: 0,frontmatter: 0, tables: 0, remoteImages: 0, duplicateNames: 0,@@ -619,6 +654,14 @@ export function planImport(page.blocks.push(...frontmatterBlocks(note.frontmatter))}page.blocks.push(...note.blocks)+ if (note.footnotes) {+ // PER FILE, while it is still known which blocks are this file's — after+ // the loop every page is just a page and a rename could not be aimed.+ const renames = mergeNotes(footnotes, note.footnotes, usedLabels)+ if (renames.size) {+ for (const b of note.blocks) if (b.html) b.html = renameRefs(b.html, renames)+ }+ }for (const img of note.images) images.push({ ...img, dir })stats.tables += note.tablesstats.remoteImages += note.remoteImages@@ -655,7 +698,7 @@ export function planImport(for (const p of pages) stats.blocks += p.blocks.lengthstats.duplicateNames = collisionsstats.pages = pages.length- return { pages, images, stats }+ return { pages, images, stats, footnotes }}/**diff --git a/spaces/src/model.ts b/spaces/src/model.tsindex 82c6d1b8..4c30a32f 100644--- a/spaces/src/model.ts+++ b/spaces/src/model.ts@@ -350,6 +350,29 @@ export interface SpacesDoc {home?: stringtheme: Themeassets?: Record<string, string>+ /**+ * FOOTNOTES, by label → inline html. See src/footnotes.ts for the whole+ * design; the two things that belong in the FORMAT's own file are these.+ *+ * DOC-LEVEL AND KEYED, which is bento/type's shape (type/src/model.ts) and+ * is chosen for its reason: a note has to be able to outlive the paragraph+ * that points at it, and keying it by label means moving a paragraph between+ * pages carries the reference and nothing else.+ *+ * NO NUMBER IS STORED HERE OR ANYWHERE. Footnotes are numbered by order of+ * appearance, so the number is a fact about the page and not about the note;+ * it is derived at render time, the way calc.ts derives an answer and slides+ * derives a page number. The LABEL is an identifier — `[^1]` is what pandoc+ * and Obsidian store too, and it can perfectly well render as "3".+ *+ * The REFERENCE is the literal text `[^label]` inside a block's html: a text+ * token, so it moves with the prose through every edit, sanitize pass,+ * canonicalisation and CRDT merge, and so no allowlist in sanitize.ts had to+ * change for it. An older build shows the sentence with `[^1]` in it and+ * round-trips this key untouched — absent means no footnotes, which is the+ * behaviour every build shipped before this one already has.+ */+ footnotes?: Record<string, string>fonts?: Array<{ family: string; asset: string; weight?: string; style?: string }>readonly?: booleantemplate?: boolean@@ -548,7 +571,11 @@ export const newPage = (title = 'Untitled', extra: Partial<Page> = {}): Page =>/** Content that matters for "did this change" — excludes volatile fields. */export function docContentKey(doc: SpacesDoc): string {- return JSON.stringify([doc.title, doc.home, doc.pages])+ // `footnotes` is content: a note's text is somebody's writing and lives+ // nowhere else, so a recovery snapshot that ignored it would compare equal to+ // a document whose notes had all been rewritten. Appended at the END so the+ // key for a document with no footnotes changes shape once and never again.+ return JSON.stringify([doc.title, doc.home, doc.pages, doc.footnotes])}// ---- derived, NEVER stored -------------------------------------------------diff --git a/spaces/src/portable.ts b/spaces/src/portable.tsindex fe6a3f8f..7fa0753e 100644--- a/spaces/src/portable.ts+++ b/spaces/src/portable.ts@@ -19,6 +19,7 @@// `.ts` extensions ON PURPOSE: node resolves this module directly for the rig.import { type SpacesDoc, type Page, type Block, repairId, pageAssetKeys } from './model.ts'import { esc } from './sanitize.ts'+import { allNotes, mergeNotes, renameRefs } from './footnotes.ts'/** An `<a href="#p/…">` in a block, however many attributes it carries. */const PAGE_LINK = /<a\s([^>]*?)href="#p\/([^"]*)"([^>]*)>([\s\S]*?)<\/a>/g@@ -264,6 +265,9 @@ export interface GraftPlan {/** asset entries to add — already keyed so nothing in the host is overwritten */assets: Record<string, string>fonts: NonNullable<SpacesDoc['fonts']>+ /** notes to ADD to the host's table — already deconflicted, and the arriving+ * references already rewritten to match (src/footnotes.ts) */+ footnotes: Record<string, string>stats: GraftStats}@@ -416,8 +420,38 @@ export function planGraft(for (const b of p.blocks) rewriteAssetRefs(b, keyMap)}+ // FOOTNOTES FOLLOW THE PAGES THAT REFERENCE THEM, and they follow the same+ // rule the asset keys above follow: a label already held by this space, with+ // a DIFFERENT note behind it, is renamed and the arriving references are+ // rewritten. Without this, grafting a page whose prose says `[^1]` would+ // either answer with the host's own note or leave every reference dangling —+ // and both are silent, which is the class of import loss this app has been+ // bitten by before.+ const footnotes: Record<string, string> = {}+ const incomingNotes = Object.fromEntries(allNotes(incoming))+ if (Object.keys(incomingNotes).length) {+ const hostNotes = Object.fromEntries(allNotes(host))+ const merged = { ...hostNotes }+ const renames = mergeNotes(merged, incomingNotes, new Set(Object.keys(hostNotes)))+ for (const [k, v] of Object.entries(merged)) {+ if (!Object.hasOwn(hostNotes, k)) footnotes[k] = v+ }+ if (renames.size) {+ for (const p of pages) {+ for (const b of p.blocks) {+ if (typeof b.html === 'string') b.html = renameRefs(b.html, renames)+ if (Array.isArray(b.rows)) {+ b.rows = (b.rows as unknown[]).map((r) =>+ Array.isArray(r) ? r.map((c) => (typeof c === 'string' ? renameRefs(c, renames) : c)) : r) as string[][]+ }+ }+ }+ }+ }+return {pages,+ footnotes,assets,fonts,stats: {diff --git a/spaces/src/render.ts b/spaces/src/render.tsindex 644ad853..f030fe3a 100644--- a/spaces/src/render.ts+++ b/spaces/src/render.ts@@ -23,6 +23,7 @@ import {import { answer, feed, freshContext, type CalcCtx } from './calc.ts'import { ICONS, type IconName } from './icons'import { renderCanvasHead, placeCard } from './canvas.ts'+import { markRefs, notesOnPage, noteOf, noteId, refId, type PageNotes } from './footnotes.ts'export interface RenderOpts {/** editable per-block hosts (the editor); false for reader/print */@@ -50,6 +51,18 @@ export interface RenderOpts {* it would travel to the next person the file is mailed to.*/allowRemote?: (src: string) => boolean+ /**+ * DERIVED, and set by `renderBlocks` for its own descent — never by a caller.+ *+ * Footnote numbering is a fact about a whole PAGE (order of appearance), and+ * `renderBlock` draws one block, so the numbering has to arrive from above.+ * It rides in the options rather than as a fifth parameter for the same+ * reason `calc` does not: every intermediate would have to thread it.+ */+ footnotes?: PageNotes+ /** the page whose numbering `footnotes` is — DOM ids are document-global and+ * print draws every page at once, so a label's ids are scoped by page */+ footnoteScope?: string}// The tag and list maps come from the block registry (blocks.ts), so a new@@ -66,6 +79,12 @@ export interface RenderOpts {*/export function renderBlocks(page: Page, doc: SpacesDoc, opts: RenderOpts = {}): DocumentFragment {const frag = document.createDocumentFragment()+ // FOOTNOTE NUMBERING IS COMPUTED ONCE, HERE. It is order-of-appearance over+ // the whole page, so no block can work it out on its own — and it is derived+ // every paint rather than stored, so inserting a reference renumbers+ // everything after it with nothing to keep in step (src/footnotes.ts).+ const fnotes = notesOnPage(doc, page)+ if (fnotes.order.length) opts = { ...opts, footnotes: fnotes, footnoteScope: page.id }// MAGIC NOTES' CONTEXT, accumulated as the pass goes. A name is defined by a// line and usable by the lines BELOW it — the same direction a person reads// in, and the reason this needs no second pass and cannot cycle.@@ -644,7 +663,12 @@ function renderTable(b: Block, opts: RenderOpts): HTMLElement {// over the whole table. A cell says which block AND which cell it is.td.dataset.cell = b.id}- td.innerHTML = sanitizeInline(cell)+ // the same either/or as inlineHost, for the same reason — a cell is an+ // editable host too+ const cleanCell = sanitizeInline(cell)+ td.innerHTML = opts.editable || !opts.footnotes+ ? cleanCell+ : markRefs(cleanCell, opts.footnotes, opts.footnoteScope ?? '')tr.appendChild(td)})if (head) {@@ -738,7 +762,17 @@ function inlineHost(b: Block, opts: RenderOpts): HTMLElement {// document's theme.dir — PLATFORM §8's two-layer ruleinner.dir = 'auto'if (opts.editable) inner.contentEditable = 'true'- inner.innerHTML = sanitizeInline(b.html ?? '')+ // MARKERS ARE DRAWN ONLY WHERE THEY CANNOT BE TYPED INTO. `host.innerHTML`+ // is written straight to `Block.html` on every `input` event, so a `<sup>`+ // injected into an editable host is one keystroke from being committed to the+ // document — and the reference `[^1]` it replaced would be gone. While a+ // block is editable the author sees and edits the token, exactly as they see+ // and edit `budget * 0.3 =` (calc.ts). Reading view, print and the+ // file-manager still are all `editable: false` and get the superscript.+ const clean = sanitizeInline(b.html ?? '')+ inner.innerHTML = opts.editable || !opts.footnotes+ ? clean+ : markRefs(clean, opts.footnotes, opts.footnoteScope ?? '')if (!b.html) inner.dataset.empty = '1'return inner}@@ -1016,10 +1050,77 @@ export function renderPage(page: Page, doc: SpacesDoc, opts: RenderOpts = {}): Hinner.appendChild(h)inner.appendChild(renderBlocks(page, doc, opts))+ const feet = renderFootnotes(page, doc, opts)+ if (feet) inner.appendChild(feet)art.appendChild(inner)return art}+/**+ * The notes at the foot of the page, or null when the page has none.+ *+ * DERIVED, LIKE THE NUMBERS. Nothing in the document says "put a footnote+ * section here" — the section IS the page's references, in the order they+ * appear, so deleting the last reference removes the section and no cleanup+ * has to remember to.+ *+ * A REFERENCE WITH NO NOTE STILL GETS A ROW, and that is the whole authoring+ * gesture: type `[^1]` in a sentence and an empty numbered slot appears down+ * here to write the note into. It is also why a dangling reference cannot be+ * silently lost — what validate() reports is the same thing the author is+ * already looking at.+ *+ * In the editor the note body is an editable host; in reading view, print and+ * the file-manager still it is inert. `data-edit-note`, deliberately NOT+ * `data-edit`: that name means "this element's html IS a BLOCK's html", and the+ * editor's generic input handler would write a note over a block.+ */+function renderFootnotes(page: Page, doc: SpacesDoc, opts: RenderOpts): HTMLElement | null {+ const notes = notesOnPage(doc, page)+ if (!notes.order.length) return null+ const sec = document.createElement('section')+ sec.className = 'sp-fnotes'+ // A real landmark with a real name: on paper it is the block at the foot of+ // the page, and to a screen reader it is the region the superscripts point at.+ sec.setAttribute('aria-label', t('Footnotes'))++ const ol = document.createElement('ol')+ ol.className = 'sp-fnlist'+ for (const label of notes.order) {+ const li = document.createElement('li')+ li.className = 'sp-fnote'+ li.id = noteId(page.id, label)++ // BACK TO THE SENTENCE. A footnote you cannot get back from costs the+ // reader their place; in print the anchor is inert and harmless, so it is+ // hidden by the stylesheet rather than conditioned on the surface here.+ const back = document.createElement('a')+ back.className = 'sp-fnback'+ back.href = `#${refId(page.id, label)}`+ back.textContent = '\u21A9'+ back.setAttribute('aria-label', t('Back to the text'))+ li.appendChild(back)++ const body = document.createElement('span')+ body.className = 'sp-fnbody'+ body.dir = 'auto'+ // The note came out of a file somebody mailed you, exactly like a block's+ // html, and goes through the same allowlist.+ body.innerHTML = sanitizeInline(noteOf(doc, label) ?? '')+ if (opts.editable) {+ body.contentEditable = 'true'+ body.dataset.editNote = label+ // `:empty::before`, the same idiom the canvas title uses — no companion+ // `data-empty` flag to keep in step with what the author has typed+ body.dataset.ph = t('Write the note')+ }+ li.appendChild(body)+ ol.appendChild(li)+ }+ sec.appendChild(ol)+ return sec+}+/** What a value reads as. Mirrors fields.ts propHtml, which writes the same* text into the block so an older build shows it too. */function shownValue(f: FieldSpec | undefined, value: unknown): string {diff --git a/spaces/src/styles.css b/spaces/src/styles.cssindex 0c4849eb..d5d8cdf8 100644--- a/spaces/src/styles.css+++ b/spaces/src/styles.css@@ -2641,6 +2641,65 @@ body.sp-canvas-dragging { user-select: none; cursor: grabbing; }.sp-cv-grip, .sp-canvas-btn { display: none !important; }}+/* ---------------------------------------------------------------------------+ FOOTNOTES (src/footnotes.ts)++ The marker is a superscript number and the notes are a numbered list at the+ foot of the page. Both are DERIVED — nothing here has a document field+ behind it — so the styling only has to do two jobs: keep the marker from+ disturbing the line it sits in, and keep the notes quieter than the prose+ they belong to.+ --------------------------------------------------------------------------- */+/* THE MARKER MUST NOT CHANGE THE LINE HEIGHT. `vertical-align: super` on a+ normal-size box grows the line box, and a paragraph with one footnote in it+ then sits taller than the one above it — visible as a stutter down a page of+ prose. `line-height: 0` on the raised box is what stops that. */+.sp-fnref { font-size: 0.72em; line-height: 0; vertical-align: super; }+.sp-fnref a {+ color: var(--accent-ink); text-decoration: none; padding: 0 1px; border-radius: 3px;+}+.sp-fnref a:hover, .sp-fnref a:focus-visible { background: var(--chrome-2); }++.sp-fnotes {+ margin: 40px 0 0; padding-top: 14px; border-top: 1px solid var(--line);+ font-size: 14px; color: var(--muted);+}+.sp-fnlist { margin: 0; padding-inline-start: 22px; }+.sp-fnote { margin: 0 0 6px; }+.sp-fnote::marker { color: var(--accent-ink); }+.sp-fnbody { display: inline; }+.sp-fnbody[data-ph]:empty::before {+ content: attr(data-ph); color: var(--ph); pointer-events: none;+}+.sp-fnbody[contenteditable="true"]:focus {+ outline: none; box-shadow: 0 0 0 2px var(--chrome-2); border-radius: 3px;+}+/* THE WAY BACK. Quiet until you want it — a column of arrows down the notes+ reads as decoration, and the arrow is only ever wanted once you have+ finished reading the note it belongs to. */+.sp-fnback {+ color: var(--ph); text-decoration: none; margin-inline-end: 6px; font-size: 12px;+}+.sp-fnote:hover .sp-fnback, .sp-fnback:focus-visible { color: var(--accent-ink); }++@media print {+ /* WHERE FOOTNOTES LAND ON PAPER: at the foot of the PAGE OF THE DOCUMENT,+ not of the sheet. CSS `float: footnote` is the typographic answer and no+ browser implements it (it is Paged Media, and print-to-PDF from Chrome,+ Safari and Firefox all ignore it) — so a "real" footnote here would be one+ that silently did not print, which is the single outcome this feature+ cannot have. A page of a space is one flow under one heading and the+ section already sits at the end of it: endnotes per page, which is what a+ multi-page handout wants anyway. Kept whole across a sheet break, because+ a note split down the middle is worse than one that starts lower. */+ .sp-fnotes { break-inside: avoid; color: #000; border-top-color: #999; }+ .sp-fnote { break-inside: avoid; }+ /* the arrow is navigation, and paper has none */+ .sp-fnback { display: none !important; }+ /* an accent marker on a monochrome printer is a grey smudge at 7px */+ .sp-fnref a { color: #000; background: none !important; }+}+/* ————— SLIDES PARITY: the keyboard ring —————slides #573 (and the kernel's .bkm-item): 2px --accent-ink. Bar and dialogbuttons draw it OUTSIDE, on the surface they sit on (inside, it would vanish