Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: inline #tag — derived index, tag views, ⌘K and graph (#437)
nyblnetd77e0c6ba3dc
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 1f635b00..a39e5e87 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -6695,6 +6695,62 @@ chance to run and it is cheap. Reconciliation for this cycle: 41 commits, 40mapped, 1 correctly absent, run by bento-team-slides.+---++## 2026-09-10 — bento/spaces: a tag is the `#` in the prose, and nothing else++**Decided by** bento-team-spaces, on `spaces-tags`.++**A tag has exactly one storage location: the text of the block.** There is no+`Page.tags` array, and adding one later would be a regression rather than an+optimisation. The index (`spaces/src/tags.ts buildTagIndex`) is derived at read+time, invalidated by `store.reindex()` like `SpaceIndex`, and built lazily+because `touch()` reindexes on every keystroke of a typing run.++The argument is the one `buildIndex` already made for backlinks, and it is+about who else writes `html`: an agent calling `updateBlock`, a Markdown+import, a remote collaborator's CRDT op, a hand-edited `#bento-doc`. None of+them knows tags exist. A derived index is simply wrong for a moment and then+right; a stored array is wrong permanently, and nothing in a format with no+server can reconcile it.++It also makes **format additivity free rather than argued**, which was measured+rather than assumed: a build of the previous release renders a tagged paragraph+as ordinary prose, byte-identical html, no text lost — because a tag adds no+field, no attribute and no block type. The chip is drawn at render into the+DOM and taken back out of anything the editor commits (`readInline`), so the+model never learns it happened; the same move `wireCode` makes for syntax+colour.++**`#project/bento` is ONE nested tag.** Decided now because the timing is the+whole argument: if this build read it as the flat tag `project` followed by the+text `/bento`, adding nesting afterwards would silently change the meaning of+text already sitting in files on other people's disks — the one-way hazard+sanitize.ts records for the href allowlist. A parent nobody wrote gets no index+entry of its own; what nesting buys is that a query for `#project` reaches it.++**What is NOT a tag** is the expensive half, and every clause has a case in+`scripts/test-spaces-model.ts` that runs the parser: a `#` must open a word (so+`C#`, `a#b` and every URL fragment are out), must be followed immediately by a+tag character (so `# Title`, the Markdown heading, is out — and markdown.ts's+own reader requires that same space), must not be all digits (`#42`, `#404`),+and must not be a bare CSS hex colour (`#fff`, `#f7a600`). Inline `<code>` and+`<a>` are skipped structurally by both readers, which is what makes this app's+own `#p/` page links impossible to misread: an href is an attribute, never+text.++**The chip carries no `href`.** Two reasons, and the second is the safety net:+inventing a `#t/` fragment form would be the one-way hazard above, and an `<a>`+with no href is exactly what `sanitizeInline` UNWRAPS — so a chip that ever did+leak into `Block.html` is removed by the canonicalizer that already runs on+blur, leaving the text. The feature fails back to plain prose rather than into+the format.++**Related, found while doing this:** `unknownSourceKeys` existed in `fields.ts`+and nothing called it, so a view whose `source` a build cannot read fell back to+the backlog silently while its header still named the source. `render.ts` says+so now. Builds already shipped cannot be told, so a view sourced on a tag reads+as Issues on them — stated in the changelog rather than glossed.## 2026-09-12 — bento/dash keys its theme off `data-theme`, like the other three apps**The divergence the maintainer asked dash to fix was a MECHANISM, not adiff --git a/docs/spaces-agents.md b/docs/spaces-agents.mdindex d825c52b..97c4acf9 100644--- a/docs/spaces-agents.md+++ b/docs/spaces-agents.md@@ -434,6 +434,35 @@ list**: `{ "type": "view", "layout": "board", "groupBy": "status","html": "Issues by status" }`. Put it on a page of its own — a page carrying aview is laid out wide.+A view's `source` says which pages it holds: `{ "has": "<fieldKey>" }`,+`{ "under": "<pageId>" }`, or `{ "tag": "<tagKey>" }`. Absent means the+backlog. The tag key is **lower-case** and reaches nested tags, so+`{"tag":"project"}` also holds the pages carrying `#project/bento`.++### Tags++Write `#tag` in a block's `html` — that is the whole storage. **There is no+`tags` field on a page and you must not invent one**: the index is derived from+the prose every time it is asked for, exactly as backlinks are, so a stored+list would be a second copy that goes wrong the first time anything edits+`html` without knowing tags exist. Nothing to maintain, nothing to keep in+step.++What is and is not a tag, since a `#` means several things:++| written | read as |+|---|---|+| `#recipe`, `#work-in-progress`, `#レシピ` | a tag |+| `#project/bento` | ONE nested tag, also counted under `project` |+| `# Title` | a Markdown heading — a tag never has a space after the hash |+| `#42`, `#404` | an issue number, not a tag |+| `#fff`, `#f7a600` | a CSS colour, not a tag |+| `C#`, `a#b` | a `#` inside a word |+| `<code>#include</code>` | code |+| `https://x.example/p#top` | a URL fragment |+| `<a href="#p/abc">…</a>` | a page link — the href is an attribute, never text |++Tags are case-folded for matching and keep the casing you typed for display.### Narrowing a view`filter` is optional and every key inside it is too. **Absent means everything**,@@ -494,6 +523,8 @@ notifications, automation. The file is the team boundary and the capability.| a warning the reader must not miss | `callout` with the `tone` that fits | it is boxed, named and legible in print and without colour vision — but three per page and none of them registers || anything you would print | remember toggles print open and archived pages are excluded | |+| a topic that recurs across pages | an inline `#tag` in the sentence | the index, ⌘K's `#` mode, a view sourced on it and the graph all derive from it |+**The most-missed feature is backlinks.** They are derived — link to a page andit lists the linker, with no maintenance. A space where pages only link *down*the tree wastes the one thing this format does that a folder of files cannot.diff --git a/scripts/test-spaces-chrome.ts b/scripts/test-spaces-chrome.tsindex 290937ac..17476c5c 100644--- a/scripts/test-spaces-chrome.ts+++ b/scripts/test-spaces-chrome.ts@@ -929,6 +929,85 @@ async function browser(chrome: string, html: string): Promise<void> {for (const c of ['Audio', 'Gallery', 'List', 'Table view', 'Comment']) if (!(c in now)) lost.push(`${c} (new member unreachable)`)ok(lost.length === 0, `at ${w}px every command reachable before is reachable now (${BEFORE[w].length} checked${lost.length ? '; LOST: ' + lost.join(', ') : ''})`)}++ // ——— TAG CHIPS × FOOTNOTE MARKERS: the ORDER in render.ts ———+ // inlineHost and table cells set their content with the footnote+ // either/or (raw html while editable, `markRefs` <sup><a> markers+ // otherwise) and only THEN call `decorateTags`. The reverse order shipped+ // in September: the footnote `innerHTML =` replaced the host's children and+ // wiped every chip drawn before it. A source check cannot tell those two+ // orders apart from a refactor that keeps both calls, so this is measured+ // in the rendered DOM: the reading view must carry BOTH a chip and a+ // marker; the editor must draw the chip but keep `[^1]` as typed; and what+ // a trusted keystroke commits must carry NO chip markup.+ console.log('\n tag chips × footnote markers\n')+ await open(false)+ const TF_PAGE = 'tfpage', TF_P = 'tfpara', TF_T = 'tftable'+ const loaded = await js<boolean>(`(() => {+ const d = JSON.parse(JSON.stringify(window.bento.doc))+ d.pages = [{ id: ${JSON.stringify(TF_PAGE)}, title: 'Tags and footnotes', blocks: [+ { id: ${JSON.stringify(TF_P)}, type: 'p', html: 'See the plan #launch and the note[^1].' },+ { id: ${JSON.stringify(TF_T)}, type: 'table', rows: [['Item', 'Note'], ['Launch', '#launch and[^1]']] },+ ] }]+ d.footnotes = { '1': 'The note.' }+ return window.bento.loadDoc(JSON.stringify(d))+ })()`)+ await sleep(400)+ ok(loaded, 'the tags × footnotes fixture loads through window.bento.loadDoc')+ const PHOST = `document.querySelector('[data-block-id="${TF_P}"] [data-edit="${TF_P}"]')`+ const CHOST = `document.querySelector('[data-block-id="${TF_T}"] td[data-r="1"][data-c="1"]')`+ // what a host draws, read from the DOM: chips, footnote markers, whether+ // the raw token is still there, and whether the host is editable+ const shape = (host: string) => js<any>(`(() => { const h = ${host}; if (!h) return null; return {+ chips: [...h.querySelectorAll('a.sp-tag')].map(a => a.dataset.tag + '=' + a.textContent),+ markers: [...h.querySelectorAll('sup > a')].map(a => ({ n: a.textContent, chip: a.classList.contains('sp-tag') || !!a.dataset.tag })),+ raw: h.textContent.includes('[^1]'), editable: h.isContentEditable } })()`)++ // 1 — reading view (editable: false): a chip AND a marker, in both hosts+ await tap(TRIG('Reading view'))+ await sleep(300)+ ok(await js<boolean>(`!!document.querySelector('.sp-reading')`), 'the reading view is on (the eye on the bar)')+ for (const [what, host] of [['paragraph', PHOST], ['table cell', CHOST]] as const) {+ const s = await shape(host)+ ok(!!s && !s.editable && s.chips.includes('launch=#launch'),+ `reading view, ${what}: the #launch tag chip is drawn (${JSON.stringify(s?.chips)})`)+ ok(!!s && s.markers.length === 1 && s.markers[0].n === '1' && !s.markers[0].chip && !s.raw,+ `reading view, ${what}: the footnote is a sup > a marker "1", not a chip, and no raw [^1] is left (${JSON.stringify(s?.markers)})`)+ }+ await tap(TRIG('Reading view'))+ await sleep(300)+ ok(await js<boolean>(`!document.querySelector('.sp-reading')`), 'the reading view is off again')++ // 2, 3 — the editor: chip drawn, token raw, and the commit chip-free+ const docBlock = (id: string) => js<any>(`(() => window.bento.doc.pages.find(p => p.id === ${JSON.stringify(TF_PAGE)})?.blocks.find(b => b.id === ${JSON.stringify(id)}))()`)+ const chipFree = (h: unknown): h is string => typeof h === 'string' && !/sp-tag|data-tag/.test(h)+ for (const [what, host] of [['paragraph', PHOST], ['table cell', CHOST]] as const) {+ const s = await shape(host)+ ok(!!s && s.editable && s.chips.includes('launch=#launch'),+ `editing, ${what}: the #launch chip is drawn in the editable host (${JSON.stringify(s?.chips)})`)+ ok(!!s && s.markers.length === 0 && s.raw,+ `editing, ${what}: the footnote stays its raw [^1] token, no marker (${JSON.stringify(s?.markers)})`)+ // focus with a trusted click, park the caret at the host's very end+ // (outside every chip), type one trusted character, blur+ await tap(host)+ await js(`(() => { const h = ${host}; h.focus(); const r = document.createRange(); r.selectNodeContents(h); r.collapse(false); const sel = getSelection(); sel.removeAllRanges(); sel.addRange(r); return 1 })()`)+ await key('Z')+ await js(`document.activeElement?.blur?.(); 1`)+ await sleep(300)+ }+ const pb = await docBlock(TF_P)+ ok(chipFree(pb?.html) && /Z$/.test(pb.html) && pb.html.includes('[^1]') && pb.html.includes('#launch'),+ `the paragraph's COMMITTED html took the keystroke, carries no chip markup, and keeps [^1] and #launch as text (${JSON.stringify(pb?.html)})`)+ const tb = await docBlock(TF_T)+ const cell = tb?.rows?.[1]?.[1]+ ok(chipFree(cell) && /Z$/.test(cell) && cell.includes('[^1]') && cell.includes('#launch'),+ `the table cell's COMMITTED html took the keystroke, carries no chip markup, and keeps [^1] and #launch as text (${JSON.stringify(cell)})`)+ ok(chipFree(tb?.html), `the table's fallback html carries no chip markup either (${JSON.stringify(tb?.html)})`)+ // after the blur settle, the editor still draws the chip in both hosts+ for (const [what, host] of [['paragraph', PHOST], ['table cell', CHOST]] as const) {+ const s = await shape(host)+ ok(!!s && s.chips.includes('launch=#launch') && s.raw, `after blur, ${what}: the chip is redrawn and the [^1] token is still raw`)+ }ws.close()} finally {try { child.kill('SIGKILL') } catch { /* gone */ }diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.tsindex fb71dd13..0294e1bb 100644--- a/scripts/test-spaces-model.ts+++ b/scripts/test-spaces-model.ts@@ -42,6 +42,7 @@ import {passesFilter, filterCount, unknownFilterKeys, phaseField, isOpenPhase, reorderPages,sortRows, unknownSortKeys, sortDirOf, cycleSort, type IssueRow,VIEW_LAYOUTS, layoutOf, nextLayout,+ viewRows, unknownSourceKeys,} from '../spaces/src/fields.ts'import {unknownFilterOps, clauseCount, clauseSummary, windowRange, opsFor,@@ -76,8 +77,12 @@ import {} from '../spaces/src/canvas.ts'import type { Block, Page } from '../spaces/src/model.ts'import {- buildGraph, layoutGraph, stepLayout, nodeRadius, graphBounds,+ buildGraph, layoutGraph, stepLayout, nodeRadius, graphBounds, TAG_EDGE_MAX,} from '../spaces/src/graph.ts'+import {+ parseTags, ancestorsOf, buildTagIndex, keysUnder, pagesWithTag, pageHasTag,+ tagList, matchTags,+} from '../spaces/src/tags.ts'import {type PageTemplate, applyTemplate, expandTokens, instantiateBlocks, journalTemplate,makeTemplate, putTemplate, removeTemplate, setJournalTemplate, templateById, templatesOf,@@ -589,8 +594,25 @@ for (const [label, input, err] of [const ed = fs.readFileSync(new URL('../spaces/src/editor.ts', import.meta.url), 'utf8')ok(/export function viewRows\(/.test(fields), 'a view selects its rows through one function')- ok(/if \(!has && !under\) return issuesOf\(doc\)/.test(fields),- '…and with no source it is still the backlog, so old view blocks are unchanged')+ // BEHAVIOURAL, not a source grep. This assertion used to read+ // /if \(!has && !under\) return issuesOf\(doc\)/ against fields.ts, which is+ // a test of how the line is SPELLED: adding a third selector (`tag`) kept+ // every behaviour it was defending and turned it red anyway. Ask viewRows.+ {+ const sdoc = JSON.parse(doc({+ pages: [+ { id: 'v', title: 'Board', blocks: [{ id: 'vb', type: 'view' }] },+ { id: 'i1', title: 'One', blocks: [{ id: 's1', type: 'prop', key: 'status', value: 'todo' }] },+ { id: 'i2', title: 'Two', blocks: [{ id: 's2', type: 'prop', key: 'status', value: 'done' }] },+ { id: 'n1', title: 'Prose', blocks: [{ id: 'x1', type: 'p', html: 'no fields' }] },+ ],+ }))+ const back = JSON.stringify(issuesOf(sdoc).map((r) => r.page.id))+ ok(back === '["i1","i2"]', 'the fixture has a backlog to compare against')+ ok(JSON.stringify(viewRows(sdoc, undefined).map((r) => r.page.id)) === back+ && JSON.stringify(viewRows(sdoc, {}).map((r) => r.page.id)) === back,+ '…and with no source it is still the backlog, so old view blocks are unchanged')+ }ok(/viewRows\(doc, \(b as \{ source\?: unknown \}\)\.source\)/.test(render),'the renderer asks for the block\'s own source rather than the issues')@@ -3910,6 +3932,272 @@ function fsTable(f: string): string {}+// ---- 22. inline #tags ------------------------------------------------------+// WHAT THIS PROVES, and the order matters: the expensive failure here is not+// "a tag was missed", it is "a `#` that is NOT a tag became one". A parser+// that reads every code sample, every URL fragment and every internal page+// link as a tag turns the index into noise on the first real document, and+// there is no server to re-run afterwards.+//+// Every case below is exercised by CALLING the parser, never by grepping the+// source for a guard — the layout-cycle bug two sections up is what that costs.+{+ // --- the positives: a hash-word is a tag ---+ const tags = (html: string) => parseTags(html).map((h) => h.key)++ ok(tags('planning a <b>meal</b> #recipe today').join() === 'recipe',+ 'a tag mid-sentence is found')+ ok(tags('#recipe at the start').join() === 'recipe', 'a tag at the start of a block is found')+ ok(tags('two #apples and #pears').join() === 'apples,pears', 'two tags in one line')+ ok(tags('trailing dot #recipe.').join() === 'recipe', 'the sentence-ending full stop is not part of the tag')+ ok(tags('(#recipe) and "#soup"').join() === 'recipe,soup', 'brackets and quotes open a tag')+ ok(tags('#рецепт and #レシピ').join() === 'рецепт,レシピ',+ 'a tag is not ASCII — this app ships eight catalogs')+ ok(tags('#work-in-progress').join() === 'work-in-progress', 'hyphens are tag characters')+ ok(tags('#work- done').join() === 'work', 'a TRAILING hyphen belongs to the sentence')+ ok(tags('#Recipe and #recipe').join() === 'recipe,recipe',+ 'the KEY is case-folded, so one tag written two ways is one tag')+ ok(parseTags('#Recipe').map((h) => h.label).join() === 'Recipe',+ '…while the LABEL keeps the casing that was actually typed')++ // --- the negatives: every `#` that means something else ---+ // Each of these is a real thing that appears in a note, and each one is a+ // separate rule in TAG_SCAN. They are asserted one at a time so a regression+ // names the case it broke rather than "tags are wrong".+ const none = (html: string, why: string) =>+ ok(parseTags(html).length === 0, `NOT a tag: ${why} — ${JSON.stringify(html)}`)++ // These three would ALL be tags in plain prose — `#include`, `#recipe` and+ // `#production` are perfectly good hash-words. That is the point: they prove+ // the `<code>` exclusion, where `#!/bin/sh` and `--grep #42` would have+ // passed anyway on the punctuation and numeric rules and proved nothing.+ none('<code>#include <stdio.h></code>', 'a `#` in inline code')+ none('<code>#recipe</code> is the literal text', 'a would-be tag inside inline code')+ none('run <code>gi\u0074 log --grep #production</code> here', 'inline code mid-sentence')+ none('<a href="#p/abc123">Recipes</a>', 'the app\'s own #p/ page link (href is an attribute, not text)')+ none('<a href="#p/abc/b7">a block link</a>', 'the two-segment #p/page/block form')+ none('<a href="https://x.example/#top">a fragment link</a>', 'a URL fragment inside a link')+ // The three above are carried by tag-STRIPPING (the href never becomes+ // text). This one is carried by the `<a>` exclusion itself: a link whose own+ // TEXT is a hash-word — which is what an autolinked url looks like — and the+ // one case where keeping link text would put a tag in the index that the+ // renderer refuses to chip.+ none('<a href="https://x.example/t">#p/abc123</a>', 'a link whose visible TEXT is a hash-word')+ none('<a href="#p/abc">#recipe</a>', 'a page link labelled with a hash-word')+ none('see https://x.example/page#section for more', 'a bare URL fragment in prose')+ none('see https://x.example/#top now', 'a bare URL fragment whose hash follows a slash')+ none('# Title', 'a Markdown ATX heading — `#` plus a space')+ none('## Deeper', 'a Markdown h2')+ none('###### six', 'a Markdown h6')+ none('the language C# is fine', 'a `#` INSIDE a word')+ none('a#b', 'a `#` between two word characters')+ none('closes #42 today', 'an issue number')+ none('a #404 page', 'another issue number')+ none('#1', 'a bare digit')+ none('the accent is #fff', 'a three-digit CSS hex colour')+ none('the accent is #f7a600', 'a six-digit CSS hex colour')+ none('the accent is #f7a600cc', 'an eight-digit CSS hex colour with alpha')+ none('nothing here: # ', 'a lone hash')+ none('#!', 'a hash before punctuation')++ // MARKDOWN ROUND TRIP. The heading rule here and markdown.ts's own reader+ // must AGREE about what a heading is, or `#recipe` pasted as Markdown+ // becomes an h1 while the tag index still counts it as a tag.+ {+ const note = parseNote('#recipe stew\n\n# Real heading\n\nsee #project/bento\n', 'n')+ const kinds = note.blocks.map((b) => b.type).join()+ ok(kinds.startsWith('p,h1,p') || kinds.startsWith('p,h1'),+ `a line beginning #tag imports as a PARAGRAPH, and # + space as a heading (${kinds})`)+ const first = note.blocks[0]+ ok((first.html ?? '').includes('#recipe'),+ 'and the tag survives the import as the text it was')+ ok(parseTags(first.html).map((h) => h.key).join() === 'recipe',+ '…so the imported block indexes the same tag it was written with')+ // OUT again: html → markdown must give the hash back, unescaped.+ ok(htmlToMd('a #recipe and #project/bento') === 'a #recipe and #project/bento',+ 'markdown EXPORT emits `#tag` verbatim — in, out, byte for byte')+ }++ // A tag that LOOKS like a colour but is nested is still a tag: the hex test+ // is deliberately scoped to flat keys, so `#fff/ideas` is not swallowed.+ ok(tags('#fff/ideas').join() === 'fff/ideas', 'the hex-colour rule does not eat a NESTED tag')++ // --- nesting ---+ ok(tags('#project/bento is going well').join() === 'project/bento', 'a nested tag is ONE tag')+ ok(tags('#a/b/c').join() === 'a/b/c', 'nesting goes as deep as it is written')+ ok(ancestorsOf('project/bento/ui').join() === 'project,project/bento',+ 'every ancestor of a nested tag, shallowest first')+ ok(ancestorsOf('recipe').length === 0, 'a flat tag has no ancestors')++ // --- word breaks: the two readers must agree ---+ // `#re<b>cipe</b>` is TWO text nodes in the DOM, so the string reader has to+ // break the word in the same place. If it closed the gap instead it would+ // read `recipe` where the chip renderer draws `re`, and the index would+ // claim a tag nobody can see.+ ok(tags('#re<b>cipe</b>').join() === 're',+ 'an inline mark inside a tag BREAKS it, exactly as the DOM walker sees it')+ ok(tags('<b>#recipe</b>').join() === 'recipe', 'a tag wholly inside a mark is intact')++ // --- entities ---+ ok(tags('a & #recipe').join() === 'recipe', 'an entity before a tag decodes to a valid opener')+ ok(tags('<p> #recipe').join() === 'recipe',+ 'entities decode AFTER tags are stripped, so <p> cannot become markup')+ ok(tags(' #recipe').join() === 'recipe', 'a non-breaking space opens a tag')++ // --- the index ---+ const tdoc = {+ format: FORMAT, version: 1, docId: 'd1', title: 'T', theme: {},+ pages: [+ { id: 'p1', title: 'Stew', blocks: [+ { id: 'b1', type: 'p', html: 'a #Recipe for winter' },+ { id: 'b2', type: 'p', html: 'also #recipe and #project/bento' },+ ] },+ { id: 'p2', title: 'Soup', blocks: [+ { id: 'b3', type: 'p', html: 'another #recipe' },+ ] },+ { id: 'p3', title: 'Notes', blocks: [+ { id: 'b4', type: 'p', html: 'no tags here' },+ // a table that arrived WITHOUT html — the same silent hole buildIndex+ // documents for backlinks, and it must not reopen for tags+ { id: 'b5', type: 'table', rows: [['x', 'see #recipe'], ['y', 'z']] },+ ] },+ { id: 'p4', title: 'Archived', archived: true, blocks: [+ { id: 'b6', type: 'p', html: '#recipe in the archive' },+ ] },+ ],+ } as unknown as SpacesDoc+ // Captured BEFORE anything indexes it. A sabotage that made buildTagIndex+ // write a `tags` array onto each page went GREEN against a `before` taken+ // after the first index build — the mutation was already in both sides.+ const pristine = JSON.stringify(tdoc)+ const tix = buildTagIndex(tdoc)++ ok(tix.tags.get('recipe')?.label === 'Recipe',+ 'the label is the FIRST occurrence in document order — deterministic across readers')+ ok(tix.tags.get('recipe')?.refs.length === 5,+ 'every occurrence is a ref, including a repeat in the same page and a table cell')+ ok(tix.tags.get('recipe')?.pages.join() === 'p1,p2,p3,p4',+ 'pages are deduped and in document order')+ ok(tix.tags.get('recipe')?.pages.length === 4 && tix.tags.get('project/bento')?.pages.length === 1,+ 'a nested tag is its own entry')+ ok(!tix.tags.has('project'),+ 'a PARENT nobody wrote has no entry of its own — the index records what is written')+ ok(keysUnder(tix, 'project').join() === 'project/bento',+ '…but it is reachable: keysUnder finds what is nested below it')+ ok(pagesWithTag(tdoc, tix, 'project').map((p) => p.id).join() === 'p1',+ 'a view on #project therefore includes the page that only carries #project/bento')+ ok(pageHasTag(tix, 'p1', 'project') && !pageHasTag(tix, 'p2', 'project'),+ 'pageHasTag answers the same question per page')+ ok(pageHasTag(tix, 'p1', 'PROJECT'), 'and it folds case, like every other tag lookup')+ ok(tix.byPage.get('p1')?.join() === 'recipe,project/bento',+ 'byPage lists a page\'s tags once each, in first-seen order')+ ok((tix.byPage.get('p3') ?? []).join() === 'recipe',+ 'a table with rows and no html still contributes its cell tags')+ ok(tix.tags.get('recipe')?.pages.includes('p4') === true,+ 'an ARCHIVED page is indexed — the archive is out of the way, not deleted')++ ok(tagList(tix)[0].key === 'recipe', 'tagList is most-used first')+ ok(matchTags(tix, 'ecip').map((e) => e.key).join() === 'recipe',+ 'matchTags is a substring search over keys — what ⌘K\'s # mode runs')+ ok(matchTags(tix, 'zzz').length === 0, 'and it finds nothing when there is nothing')++ // --- a view sourced on a tag ---+ ok(unknownSourceKeys({ tag: 'recipe' }).length === 0,+ '`tag` is a source key this build understands')+ ok(unknownSourceKeys({ galaxy: 1 }).join() === 'galaxy',+ '…and a key from a NEWER build is still reported')+ {+ const rows = viewRows(tdoc, { tag: 'recipe' })+ ok(rows.map((r) => r.page.id).join() === 'p1,p2,p3',+ 'a view sourced on #recipe holds the pages that carry it — archived excluded, as every view is')+ ok(viewRows(tdoc, { tag: 'project' }).map((r) => r.page.id).join() === 'p1',+ 'and a view on a parent tag reaches its children')+ ok(viewRows(tdoc, { tag: 'nosuchtag' }).length === 0, 'an unwritten tag selects nothing')+ }++ // --- the graph ---+ // Two pages that share a tag are related even though neither links to the+ // other and neither is the other's parent. That relationship exists ONLY in+ // the prose, which is why it had to be drawn from the same index.+ {+ const gdoc = {+ format: FORMAT, version: 1, docId: 'g1', title: 'G', theme: {},+ pages: [+ { id: 'g1', title: 'Stew', blocks: [{ id: 'x1', type: 'p', html: 'winter #recipe' }] },+ { id: 'g2', title: 'Soup', blocks: [{ id: 'x2', type: 'p', html: 'quick #recipe' }] },+ { id: 'g3', title: 'Alone', blocks: [{ id: 'x3', type: 'p', html: 'nothing' }] },+ ],+ } as unknown as SpacesDoc+ const g = buildGraph(gdoc, buildIndex(gdoc))+ const tagEdges = g.edges.filter((e) => e.tag)+ ok(tagEdges.length === 1 && tagEdges[0].links === 0 && tagEdges[0].tree === false,+ 'a shared tag draws ONE undirected edge, with no link and no tree behind it')+ ok(g.nodes[tagEdges[0].a].deg === 1 && g.nodes[tagEdges[0].b].deg === 1,+ '…and it counts toward both pages\' connectedness, so the dots grow')+ ok(g.nodes.find((n) => n.title === 'Alone')?.deg === 0,+ 'a page with no tag stays an orphan')++ // THE CAP. Past TAG_EDGE_MAX pages a tag is a category, not a+ // relationship, and n(n-1)/2 lines is not a picture of anything.+ const many = {+ format: FORMAT, version: 1, docId: 'g2', title: 'G', theme: {},+ pages: Array.from({ length: TAG_EDGE_MAX + 1 }, (_, i) => ({+ id: 'm' + i, title: 'M' + i, blocks: [{ id: 'y' + i, type: 'p', html: 'a #note here' }],+ })),+ } as unknown as SpacesDoc+ ok(buildGraph(many, buildIndex(many)).edges.length === 0,+ `a tag on ${TAG_EDGE_MAX + 1} pages draws NOTHING — one over the cap`)+ const atCap = JSON.parse(JSON.stringify(many)) as SpacesDoc+ atCap.pages.pop()+ ok(buildGraph(atCap, buildIndex(atCap)).edges.length === (TAG_EDGE_MAX * (TAG_EDGE_MAX - 1)) / 2,+ `…and exactly at ${TAG_EDGE_MAX} it still draws every pair`)+ }++ // --- FORMAT ADDITIVITY, measured rather than assumed ---+ // The claim is that a tag costs the file NOTHING, so a build that predates+ // this one renders a tagged paragraph as ordinary prose. The way to measure+ // it is that the document is byte-identical before and after the index runs,+ // and that the block's html is still just the words.+ {+ tagList(buildTagIndex(tdoc))+ pagesWithTag(tdoc, buildTagIndex(tdoc), 'recipe')+ pageHasTag(buildTagIndex(tdoc), 'p1', 'recipe')+ ok(JSON.stringify(tdoc) === pristine,+ 'building the index MUTATES NOTHING — the tag is only ever in the prose')+ ok(!Object.hasOwn(tdoc.pages[0] as object, 'tags'),+ '…and specifically: no page gains a `tags` array that could disagree with the prose')+ ok(tdoc.pages[0].blocks[0].html === 'a #Recipe for winter',+ 'and the stored html is the sentence, with no tag markup in it at all')+ }+ {+ // The one that would actually break an older build: nothing this feature+ // touches introduces a field. A round trip through parseDoc keeps the+ // document identical, which is the same test additivity uses above.+ const r = parseDoc(JSON.stringify(tdoc))+ ok(r.ok && JSON.stringify(r.doc.pages) === JSON.stringify(tdoc.pages),+ 'a tagged document round-trips through parseDoc unchanged')+ }++ // --- pathological input ---+ ok(parseTags('#' + 'a'.repeat(500)).length === 0, 'an absurdly long key is not indexed')+ ok(parseTags(undefined).length === 0 && parseTags('').length === 0,+ 'absent and empty html are not an error')+ ok(buildTagIndex({ pages: [] } as unknown as SpacesDoc).tags.size === 0,+ 'a document with no pages yields an empty index')+ ok(buildTagIndex({} as unknown as SpacesDoc).tags.size === 0,+ 'and a document with no `pages` at all does not throw')+ {+ // prototype keys, the same class of bug as layoutOf above: a Map is used+ // rather than an object precisely so `#__proto__` cannot reach one+ const evil = buildTagIndex({+ pages: [{ id: 'p1', title: 'x', blocks: [{ id: 'b1', type: 'p', html: '#__proto__ #constructor' }] }],+ } as unknown as SpacesDoc)+ ok(evil.tags.get('__proto__')?.pages.join() === 'p1',+ '#__proto__ is an ordinary tag in a Map, not a way to reach Object.prototype')+ ok(({} as Record<string, unknown>).polluted === undefined, 'and nothing was polluted')+ }+}+// ---- page designs (DECISIONS 2026-09-26) ----------------------------------// The author picks the design; the reader's theme picks between its two// palettes. A design is DATA — palettes, font names, switch words, numbers —diff --git a/scripts/test-spaces-roundtrip.ts b/scripts/test-spaces-roundtrip.tsindex a6a3fcea..0ff09a6e 100644--- a/scripts/test-spaces-roundtrip.ts+++ b/scripts/test-spaces-roundtrip.ts@@ -139,6 +139,34 @@ if (lostBy.length) {ok(/\[[^\]]+\]\(https?:\/\/[^)]+\)/.test(md), 'a link card exports with its address intact')ok(/!\[[^\]]+\]\([^)]+\)/.test(md), 'an image exports with its alt text and reference')+// #TAG, IN AND OUT. A tag lives in the prose and nowhere else, so it costs the+// exporter nothing — which is precisely the claim that has to be measured+// rather than assumed. Two things could break it and both are silent: an+// exporter that escaped the hash for Markdown's sake (`\#recipe`), and a+// parser that read a line beginning `#recipe` as an ATX heading and ate the+// word. Either one loses the classification of every note in the space.+{+ const st = new Store(starterDoc())+ const page = st.doc.pages[0]+ page.blocks.push(+ { id: 'tg1', type: 'p', html: 'a note about #recipe and #project/bento' } as never,+ { id: 'tg2', type: 'p', html: '#leading tag at the start of a line' } as never,+ )+ st.reindex()+ ok(st.tags.tags.get('recipe')?.pages.includes(page.id) === true,+ 'the tag index finds a tag written into a page')++ const out = toMarkdown(st as never)+ ok(out.includes('#recipe') && out.includes('#project/bento'),+ 'Markdown export emits the hash unescaped — `#recipe`, not `\\#recipe`')++ const back = parseNote(out.slice(out.indexOf('#leading')), 'x')+ ok(back.blocks[0]?.type === 'p',+ 'a line that BEGINS with a tag reads back as a paragraph, never a heading')+ ok(String(back.blocks[0]?.html ?? '').includes('#leading'),+ '…with the tag still in it')+}+// ---- the design rides in the front matter ---------------------------------// "Selectable in the page Markdown": `design:` names it, and a design the// space carries itself travels as one `designs:` line. A space with no designdiff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex 405ba4aa..e8ea28d6 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -14,6 +14,40 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.## [Unreleased]+- **`#tag` in the prose, and everything that follows from it.** Type `#recipe`+ in a sentence and it renders as a clickable chip; the chip opens a tag sheet+ listing every page carrying it. Tags reach ⌘K (a query starting with `#`+ lists tags and how much of the space each covers), a view's **source** (a+ base can be "everything tagged #recipe", chosen from the Pages · button),+ and the graph (two pages sharing a tag draw an edge, capped at eight pages+ per tag — past that a tag is a category, not a relationship).++ **A tag is stored exactly once, in the words.** There is no `page.tags`+ array and there must not be one: the index is derived from `html` every time+ something asks, the same way backlinks already are, so it can never disagree+ with what is written. The consequence worth having is that this costs the+ FILE nothing — measured against a build of the previous release, a tagged+ paragraph renders there as ordinary prose, byte-identical, with no chip and+ no lost text.++ `#project/bento` is one **nested** tag, and it counts under `#project` too —+ settled now rather than later, because reading it as the flat tag `project`+ first would silently change the meaning of text already in files when+ nesting arrived. The tag sheet walks up and down that hierarchy.++ What is deliberately NOT a tag, each one tested by running the parser:+ `# Title` (a Markdown heading — a tag has no space after the hash), `#42`+ and `#404` (issue numbers), `#fff` and `#f7a600` (CSS colours), `C#` and+ `a#b` (a hash inside a word), a `#` in `<code>`, a URL fragment such as+ `https://x.example/p#top`, and this app's own `#p/` page links.++- **A view whose source this build cannot read now says so.** `unknownSourceKeys`+ existed and nothing called it, so a view selecting its pages in a way the+ build does not understand silently fell back to the backlog and showed a+ different set of pages while its header still named the source. It shows a+ line now, the way an unreadable filter already did. Known limitation, stated+ because it cannot be fixed retroactively: builds shipped before this one+ still degrade silently, so a view sourced on a tag reads as Issues there.- **The table sorts and edits again.** A rebase duplicated the whole`layout === 'table'` branch in the renderer. Both copies compiled, and thefirst one returned — so the second, the one carrying click-to-sort headersdiff --git a/spaces/src/editor.ts b/spaces/src/editor.tsindex a99757e0..6e495742 100644--- a/spaces/src/editor.ts+++ b/spaces/src/editor.ts@@ -49,6 +49,10 @@ import { openDesignPanel } from './designpanel'import { saveRows, type DocHost } from './doccmds.ts'import { openGraphView } from './graph.ts'import { pageToDeck, type DeckNote, type DeckNoteCode } from './todeck.ts'+import {+ redecorateTags, readInline, matchTags, pagesWithTag, tagList, keysUnder, ancestorsOf,+ type TagEntry,+} from './tags.ts'import {todayISO, stepDay, journalLabel, journalShort, isJournal, planJournal,} from './journal'@@ -1941,7 +1945,7 @@ export class Editor {const s = this.storeconst b = s.block(blockId)if (!b) return- const set = (src: { has?: string; under?: string } | undefined) => this.editView(blockId, 'source', src)+ const set = (src: { has?: string; under?: string; tag?: string } | undefined) => this.editView(blockId, 'source', src)this.menuAt(anchor, t('Which pages'), (m) => {caption(m, t('Which pages'))row(m, { icon: ICONS.board, label: t('Issues'), hint: t('Every page with a status'), run: () => set(undefined) })@@ -1960,6 +1964,19 @@ export class Editor {row(m, { icon: ICONS.page, label: here.title || t('Untitled'), hint: t('Pages nested under this one'),run: () => set({ under: here.id }) })}++ // The tags the space ACTUALLY HAS, most-used first — never a free-text+ // box. A tag that has not been written selects nothing, and a picker+ // that let you ask for one would be a view that is empty for a reason+ // you cannot see. Capped, because this is a menu, not the tag index.+ const tags = tagList(s.tags).slice(0, 12)+ if (tags.length) {+ caption(m, t('Tagged'))+ for (const e of tags) {+ row(m, { icon: ICONS.tag, label: '#' + e.label, hint: t('Pages carrying this tag'),+ run: () => set({ tag: e.key }) })+ }+ }})}@@ -2586,7 +2603,9 @@ export class Editor {delete host.dataset.emptys.runEdit(id, () => {const b = s.block(id)- if (b) b.html = host.innerHTML+ // readInline, NOT innerHTML: a render drew `#tag` chips into this+ // host and the model must never learn they happened (tags.ts).+ if (b) b.html = readInline(host)})this.autoformat(id, host)this.ghost(id, host)@@ -2600,6 +2619,11 @@ export class Editor {const clean = canonicalize(b.html)if (clean !== b.html) { b.html = clean; host.innerHTML = clean }}+ // Chips settle on BLUR, never during a run: redrawing them per+ // keystroke would replace the nodes the caret is standing in. Blur is+ // also when a chip that grew (a caret at its end is INSIDE the <a>, so+ // typing there appends to it) is taken apart and re-read.+ redecorateTags(host)// A FOOTNOTE REFERENCE TYPED INTO THIS BLOCK CHANGES THE PAGE.//// The section at the foot is derived from every block's references, so@@ -2881,6 +2905,13 @@ export class Editor {view.addEventListener('click', (e) => {const a = (e.target as HTMLElement).closest('a')if (!a) return+ // A tag chip is an <a> with no href (tags.ts explains why it has none),+ // so it is caught HERE, before the href test — and caught by the same+ // listener, because the whole point of a chip is that it behaves like+ // the link it visually is, inside a contenteditable where the browser+ // would follow nothing anyway.+ const tag = a.dataset.tag+ if (tag) { e.preventDefault(); this.openTag(tag); return }const href = a.getAttribute('href') ?? ''if (!href.startsWith('#p/')) return// through the same resolver as the address bar, so a block anchor@@ -3058,7 +3089,7 @@ export class Editor {if (!b) returnconst t = tableOf(b)if (!t.rows[r]) return- t.rows[r][c] = td.innerHTML+ t.rows[r][c] = readInline(td)writeTable(b, t)})})@@ -3073,6 +3104,7 @@ export class Editor {t.rows[r][c] = cleanwriteTable(b, t)td.innerHTML = clean+ redecorateTags(td)})}@@ -4188,6 +4220,12 @@ export class Editor {const q = input.value.trim().toLowerCase()results.innerHTML = ''if (!q) return+ // `#` SWITCHES THE QUESTION. Full text already finds `#recipe` — it is+ // literally in the prose — but it finds it the way it finds any other+ // word: a list of pages that happen to contain the string. A leading+ // hash asks the other question, "which tags exist", and answers with+ // the tag and how much of the space carries it.+ if (q.startsWith('#')) { runTags(q.slice(1)); return }let n = 0for (const p of s.doc.pages) {const hits: string[] = []@@ -4222,6 +4260,26 @@ export class Editor {at = 0mark()}+ const runTags = (want: string) => {+ const hits = matchTags(s.tags, want)+ if (!hits.length) {+ results.append(el('li', 'sp-noresult', t('No tags match')))+ return+ }+ for (const e of hits.slice(0, 30)) {+ const li = document.createElement('li')+ const a = document.createElement('button')+ a.className = 'sp-result'+ const n = pagesWithTag(s.doc, s.tags, e.key).length+ a.innerHTML =+ `<span class="sp-result-ico">${ICONS.tag}</span>` ++ `<span class="sp-result-txt"><strong>#${escapeHtml(e.label)}</strong>` ++ `<span>${escapeHtml(t('{n} pages', { n: String(n) }))}</span></span>`+ a.addEventListener('click', () => { close(); this.openTag(e.key) })+ li.append(a)+ results.append(li)+ }+ }// THE ARROWS MOVE THE HIGHLIGHT, the query keeps the focus — the / menu's// pattern. They did nothing here: a result was reachable only by Tab,// which walks past it into the rest of the card.@@ -4246,6 +4304,76 @@ export class Editor {}, { top: true })}+ /**+ * THE TAG INDEX, reachable from the tag itself.+ *+ * A chip you cannot click is decoration; the whole reason to write `#recipe`+ * rather than the word "recipe" is that the tag is a way BACK to everything+ * else carrying it. So the chip, ⌘K's `#` mode and the graph all land here.+ *+ * Everything on this sheet is derived on open, from `store.tags`, which is+ * itself derived from the prose. Nothing here is stored, so a tag that stops+ * being written stops existing, with no orphaned entry to garbage-collect —+ * which is the whole argument for not keeping a `page.tags` array.+ *+ * NESTED TAGS get a row of their own at the top. `#project` shows the pages+ * that carry `#project/bento` too (that is what nesting means), and naming+ * the children is what stops that from looking like a bug.+ */+ openTag(key: string): void {+ const s = this.store+ this.openOverlay(t('Tag'), (card, close) => {+ const entry = s.tags.tags.get(key)+ const label = entry?.label ?? key+ card.append(el('h2', 'sp-card-h', '#' + label))++ // UP and DOWN, both as chips, because a hierarchy nobody can walk is a+ // naming convention rather than a hierarchy. `#project` is the case that+ // makes the up half necessary: if only `#project/bento` was ever+ // written, `#project` has no entry of its own, appears in no ⌘K listing+ // and would be reachable from nothing at all — while still being a+ // perfectly good thing to ask a view for.+ const rel = [...ancestorsOf(key), ...keysUnder(s.tags, key).filter((k) => k !== key)]+ if (rel.length) {+ const row = el('div', 'sp-tag-kids')+ for (const k of rel) {+ const b = el('button', 'sp-tag-chip', '#' + (s.tags.tags.get(k)?.label ?? k))+ b.addEventListener('click', () => { close(); this.openTag(k) })+ row.append(b)+ }+ card.append(row)+ }++ const pages = pagesWithTag(s.doc, s.tags, key)+ card.append(el('p', 'sp-tag-count', t('{n} pages', { n: String(pages.length) })))+ const ul = el('ul', 'sp-results')+ for (const page of pages) {+ const li = document.createElement('li')+ const a = document.createElement('button')+ a.className = 'sp-result'+ // The snippet is the FIRST block on that page that actually carries the+ // tag — not the first block of the page. "Why is this page here" is the+ // question a tag index has to answer, and the page's opening line+ // usually does not.+ const ref = (entry?.refs ?? []).find((r) => r.pageId === page.id)+ const snip = textOf(s.index.block.get(ref?.blockId ?? '')?.block.html).slice(0, 120)+ a.innerHTML =+ `<span class="sp-result-ico">${ICONS.page}</span>` ++ `<span class="sp-result-txt"><strong>${escapeHtml(page.title || t('Untitled'))}` ++ (page.archived ? ` <em class="sp-arch">${t('archived')}</em>` : '') + `</strong>` ++ `<span>${escapeHtml(snip)}</span></span>`+ a.addEventListener('click', () => { close(); s.goToPage(page.id) })+ li.append(a)+ ul.append(li)+ }+ if (!pages.length) ul.append(el('li', 'sp-noresult', t('Nothing found')))+ card.append(ul)+ })+ }++ /** Every tag in the space, for the ⌘K empty state and anything else asking. */+ allTags(): TagEntry[] { return tagList(this.store.tags) }+/*** The block menu, anchored where you are.*diff --git a/spaces/src/fields.ts b/spaces/src/fields.tsindex 67cc079e..2217b057 100644--- a/spaces/src/fields.ts+++ b/spaces/src/fields.ts@@ -30,6 +30,7 @@ import type { SpacesDoc, Page, Block } from './model'// not follow an extensionless import. Vite is unaffected — the same fix main// already carries for i18n/packed.import { t } from './i18n.ts'+import { buildTagIndex, pageHasTag } from './tags.ts'import { passesClauses, clauseCount, type Clause } from './query.ts'/** What a field holds. Deliberately few: every one costs an editor and a@@ -467,11 +468,26 @@ export interface ViewSource {has?: string/** pages nested anywhere under this page */under?: string+ /**+ * pages whose PROSE carries this `#tag` (or anything nested under it)+ *+ * The third selector, and it earns its place on the same test the other two+ * pass: it says something about a page that nothing else in this format can+ * say. `has` asks about a declared field, `under` about the tree — both are+ * structure somebody set up in advance. A tag is written mid-sentence, in+ * the middle of writing something else, which is the only kind of+ * classification most notes ever get.+ *+ * The KEY is stored, lower-cased — a filter that matched casing would break+ * the moment somebody wrote `#Recipe` once. Nested tags include their+ * children: `tag: 'project'` selects `#project/bento` too.+ */+ tag?: string}export const unknownSourceKeys = (src: unknown): string[] =>!src || typeof src !== 'object' ? []- : Object.keys(src as Record<string, unknown>).filter((k) => k !== 'has' && k !== 'under')+ : Object.keys(src as Record<string, unknown>).filter((k) => k !== 'has' && k !== 'under' && k !== 'tag')/** Is this page anywhere below `root`? Cycle-safe, like the tree walk. */function isUnder(doc: SpacesDoc, page: Page, root: string): boolean {@@ -496,12 +512,19 @@ export function viewRows(doc: SpacesDoc, source?: unknown): IssueRow[] {const src = (source && typeof source === 'object' ? source : {}) as ViewSourceconst has = typeof src.has === 'string' ? src.has : ''const under = typeof src.under === 'string' ? src.under : ''- if (!has && !under) return issuesOf(doc)+ const tag = typeof src.tag === 'string' ? src.tag : ''+ if (!has && !under && !tag) return issuesOf(doc)++ // Derived here rather than passed in, so `viewRows` keeps the one-argument+ // shape every caller already has — including the node rigs, which have no+ // store to take an index from. Built ONLY when a tag is actually asked for.+ const tix = tag ? buildTagIndex(doc) : nullconst out: IssueRow[] = []for (const page of doc.pages) {if (page.archived) continueif (under && !isUnder(doc, page, under)) continue+ if (tix && !pageHasTag(tix, page.id, tag)) continueconst values = valuesOf(page)if (has && !values.has(has)) continueout.push({ page, values })diff --git a/spaces/src/graph.ts b/spaces/src/graph.tsindex bff92e89..f110c1c1 100644--- a/spaces/src/graph.ts+++ b/spaces/src/graph.ts@@ -41,6 +41,7 @@// on the first frame, which is the same picture, immediately.import type { SpacesDoc, SpaceIndex } from './model.ts'+import { buildTagIndex } from './tags.ts'import { ICONS } from './icons.ts'import { t } from './i18n.ts'import { enablePinchZoom } from './touch.ts'@@ -78,6 +79,8 @@ export interface GraphEdge {links: number/** true when one is the other's parent in the page tree */tree: boolean+ /** true when the two pages carry a tag in common */+ tag: boolean}export interface Graph {@@ -94,6 +97,10 @@ export interface Graph {* than one with one, and a linear map makes the hub a disc that swallows its* own neighbourhood. Floor 4 so an orphan is still a thing you can click.*/+/** Past this many pages a tag stops being a relationship and starts being a+ * category. See buildGraph. */+export const TAG_EDGE_MAX = 8+export const nodeRadius = (deg: number): number => Math.min(4 + 3.1 * Math.sqrt(deg), 20)/** Golden-angle spiral: even, deterministic, and not a grid. */@@ -143,7 +150,7 @@ export function buildGraph(doc: SpacesDoc, index: SpaceIndex): Graph {const k = key(a, b)const hit = seen.get(k)if (hit !== undefined) return edges[hit]- const e: GraphEdge = { a: Math.min(a, b), b: Math.max(a, b), links: 0, tree: false }+ const e: GraphEdge = { a: Math.min(a, b), b: Math.max(a, b), links: 0, tree: false, tag: false }seen.set(k, edges.length)edges.push(e)return e@@ -171,10 +178,33 @@ export function buildGraph(doc: SpacesDoc, index: SpaceIndex): Graph {edgeFor(a, b).tree = true}+ // …and shared TAGS, which are the only relationship in this format that+ // somebody states without meaning to state it. Two pages both tagged+ // `#recipe` are related; neither links to the other and neither is the+ // other's parent, so before this the graph drew them as strangers.+ //+ // CAPPED, and the cap is the whole design. A tag on n pages is n(n-1)/2+ // edges — `#note` on twenty pages is 190 lines, which is not a picture of+ // anything. Past the cap the tag is saying "these are notes", not "these two+ // specifically", and the tag sheet is the right way to read it. Below it,+ // co-tagging is exactly the weak association a graph is for.+ const tix = buildTagIndex(doc)+ for (const entry of tix.tags.values()) {+ if (entry.pages.length < 2 || entry.pages.length > TAG_EDGE_MAX) continue+ for (let i = 0; i < entry.pages.length; i++) {+ for (let j = i + 1; j < entry.pages.length; j++) {+ const a = at.get(entry.pages[i])+ const b = at.get(entry.pages[j])+ if (a === undefined || b === undefined || a === b) continue+ edgeFor(a, b).tag = true+ }+ }+ }+for (const e of edges) {nodes[e.a].deg++nodes[e.b].deg++- const w = e.links + (e.tree ? 1 : 0)+ const w = e.links + (e.tree ? 1 : 0) + (e.tag ? 1 : 0)nodes[e.a].weight += wnodes[e.b].weight += w}diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.tsindex 9359d07a..0d61f5dc 100644--- a/spaces/src/i18n/de.ts+++ b/spaces/src/i18n/de.ts@@ -321,6 +321,7 @@ export const de: Catalog = {"No issues yet. Add a status field to any page and it appears here.": "Noch keine Issues. Gib einer Seite ein Status-Feld, dann erscheint sie hier.","No page matches": "Keine Seite passt","No pages yet": "Noch keine Seiten",+ "No tags match": "Keine passenden Schlagwörter","No section named {name} on this page.": "Kein Abschnitt namens {name} auf dieser Seite.","No versions yet — they build up as you write and save.": "Noch keine Versionen — sie sammeln sich beim Schreiben und Speichern an.","No templates yet. Open a page you would like to reuse and choose “Save as template”.": "Noch keine Vorlagen. Öffne eine Seite, die du wiederverwenden möchtest, und wähle „Als Vorlage sichern“.",@@ -356,6 +357,7 @@ export const de: Catalog = {"Page": "Seite","Page options": "Seiten-Optionen","Pages": "Seiten",+ "Pages carrying this tag": "Seiten mit diesem Schlagwort","Pages nested under this one": "Seiten unterhalb dieser Seite","Pages open at their normal width again": "Seiten öffnen wieder in normaler Breite","Pages that have this property": "Seiten mit dieser Eigenschaft",@@ -480,6 +482,8 @@ export const de: Catalog = {"Strikethrough": "Durchgestrichen","Strikethrough — ⇧⌘S": "Durchgestrichen — ⇧⌘S","Table": "Tabelle",+ "Tag": "Schlagwort",+ "Tagged": "Mit Schlagwort","Take it elsewhere": "Woanders weitermachen","Taken from the address if blank": "Bleibt das Feld leer, wird er aus der Adresse übernommen","Tall": "Hoch",@@ -548,6 +552,7 @@ export const de: Catalog = {"This space is encrypted, so no versions are kept.": "Dieser Space ist verschlüsselt, deshalb werden keine Versionen aufbewahrt.","This space is encrypted. Saves stay encrypted.": "Dieser Space ist verschlüsselt. Speichern bleibt verschlüsselt.","This space is locked": "Dieser Space ist gesperrt",+ "This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.": "Diese Ansicht wählt ihre Seiten auf eine Weise, die diese Version nicht versteht, und zeigt stattdessen den Backlog.","This window is still running v{v} — reload to finish. A v{v} backup was downloaded.": "Dieses Fenster läuft noch mit v{v} — zum Abschließen neu laden. Ein v{v}-Backup wurde heruntergeladen.","This window is still running v{v} — reload to finish. A v{v} backup was saved beside this file.": "Dieses Fenster läuft noch mit v{v} — zum Abschließen neu laden. Ein v{v}-Backup wurde neben dieser Datei gespeichert.","This window is still running v{v}. If you overwrote the file that's open here, reload; otherwise open the file you saved.": "Dieses Fenster läuft noch mit v{v}. Wenn Sie die geöffnete Datei überschrieben haben, neu laden; andernfalls die gespeicherte Datei öffnen.",@@ -654,6 +659,7 @@ export const de: Catalog = {"{n} of {total} wikilink(s) resolved.": "{n} von {total} Wikilink(s) aufgelöst.","{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} Seite(n) hatten Frontmatter — wortgetreu in einem zugeklappten Block erhalten.","{n} page(s) inside it move up a level.": "{n} Unterseiten rücken eine Ebene nach oben.",+ "{n} pages": "{n} Seiten","{n} pages, in sidebar order, with a contents page": "{n} Seiten, in der Reihenfolge der Seitenleiste, mit Inhaltsverzeichnis","{n} table(s) imported, with their column alignment.": "{n} Tabelle(n) importiert, samt Spaltenausrichtung.","{n} table(s) kept as text: there is no table block in this format yet.": "{n} Tabelle(n) als Text übernommen: Dieses Format hat noch keinen Tabellenblock.",diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.tsindex 5c62062c..2cf84316 100644--- a/spaces/src/i18n/es.ts+++ b/spaces/src/i18n/es.ts@@ -321,6 +321,7 @@ export const es: Catalog = {"No issues yet. Add a status field to any page and it appears here.": "Aún no hay incidencias. Añade un campo de estado a cualquier página y aparecerá aquí.","No page matches": "Ninguna página coincide","No pages yet": "Aún no hay páginas",+ "No tags match": "Ninguna etiqueta coincide","No section named {name} on this page.": "No hay ninguna sección llamada {name} en esta página.","No versions yet — they build up as you write and save.": "Aún no hay versiones: se acumulan a medida que escribes y guardas.","No templates yet. Open a page you would like to reuse and choose “Save as template”.": "Todavía no hay plantillas. Abre una página que quieras reutilizar y elige «Guardar como plantilla».",@@ -356,6 +357,7 @@ export const es: Catalog = {"Page": "Página","Page options": "Opciones de la página","Pages": "Páginas",+ "Pages carrying this tag": "Páginas que llevan esta etiqueta","Pages nested under this one": "Páginas anidadas bajo esta","Pages open at their normal width again": "Las páginas vuelven a su anchura normal","Pages that have this property": "Páginas que tienen esta propiedad",@@ -480,6 +482,8 @@ export const es: Catalog = {"Strikethrough": "Tachado","Strikethrough — ⇧⌘S": "Tachado — ⇧⌘S","Table": "Tabla",+ "Tag": "Etiqueta",+ "Tagged": "Etiquetadas","Take it elsewhere": "Llévatelo a otra parte","Taken from the address if blank": "Si se deja vacío, se toma de la dirección","Tall": "Alto",@@ -548,6 +552,7 @@ export const es: Catalog = {"This space is encrypted, so no versions are kept.": "Este espacio está cifrado, así que no se guarda ninguna versión.","This space is encrypted. Saves stay encrypted.": "Este espacio está cifrado. Los guardados siguen cifrados.","This space is locked": "Este espacio está bloqueado",+ "This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.": "Esta vista elige sus páginas de una forma que esta versión no entiende, así que muestra la lista de tareas.","This window is still running v{v} — reload to finish. A v{v} backup was downloaded.": "Esta ventana sigue en v{v} — recarga para terminar. Se descargó una copia de seguridad v{v}.","This window is still running v{v} — reload to finish. A v{v} backup was saved beside this file.": "Esta ventana sigue en v{v} — recarga para terminar. Se guardó una copia de seguridad v{v} junto a este archivo.","This window is still running v{v}. If you overwrote the file that's open here, reload; otherwise open the file you saved.": "Esta ventana sigue en v{v}. Si sobrescribiste el archivo abierto aquí, recarga; si no, abre el archivo que guardaste.",@@ -654,6 +659,7 @@ export const es: Catalog = {"{n} of {total} wikilink(s) resolved.": "{n} de {total} wikilink(s) resueltos.","{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} página(s) tenían frontmatter, conservado tal cual en un bloque plegado.","{n} page(s) inside it move up a level.": "{n} página(s) que contiene suben un nivel.",+ "{n} pages": "{n} páginas","{n} pages, in sidebar order, with a contents page": "{n} páginas, en el orden de la barra lateral, con una página de índice","{n} table(s) imported, with their column alignment.": "{n} tabla(s) importada(s), con la alineación de sus columnas.","{n} table(s) kept as text: there is no table block in this format yet.": "{n} tabla(s) conservadas como texto: este formato aún no tiene bloque de tabla.",diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.tsindex 62ea6e4b..5637db69 100644--- a/spaces/src/i18n/fr.ts+++ b/spaces/src/i18n/fr.ts@@ -321,6 +321,7 @@ export const fr: Catalog = {"No issues yet. Add a status field to any page and it appears here.": "Aucun ticket pour l’instant. Ajoutez un champ statut à une page et elle apparaîtra ici.","No page matches": "Aucune page ne correspond","No pages yet": "Aucune page pour l’instant",+ "No tags match": "Aucune étiquette ne correspond","No section named {name} on this page.": "Aucune section nommée {name} sur cette page.","No versions yet — they build up as you write and save.": "Pas encore de versions — elles s’accumulent à mesure que vous écrivez et enregistrez.","No templates yet. Open a page you would like to reuse and choose “Save as template”.": "Aucun modèle pour l’instant. Ouvrez une page que vous voulez réutiliser et choisissez « Enregistrer comme modèle ».",@@ -356,6 +357,7 @@ export const fr: Catalog = {"Page": "Page","Page options": "Options de la page","Pages": "Pages",+ "Pages carrying this tag": "Pages portant cette étiquette","Pages nested under this one": "Pages imbriquées sous celle-ci","Pages open at their normal width again": "Les pages retrouvent leur largeur normale","Pages that have this property": "Pages qui ont cette propriété",@@ -480,6 +482,8 @@ export const fr: Catalog = {"Strikethrough": "Barré","Strikethrough — ⇧⌘S": "Barré — ⇧⌘S","Table": "Tableau",+ "Tag": "Étiquette",+ "Tagged": "Étiquetées","Take it elsewhere": "Emportez-le ailleurs","Taken from the address if blank": "Si vide, repris de l’adresse","Tall": "Haut",@@ -548,6 +552,7 @@ export const fr: Catalog = {"This space is encrypted, so no versions are kept.": "Cet espace est chiffré : aucune version n’est conservée.","This space is encrypted. Saves stay encrypted.": "Cet espace est chiffré. Les enregistrements restent chiffrés.","This space is locked": "Cet espace est verrouillé",+ "This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.": "Cette vue choisit ses pages d’une façon que cette version ne comprend pas ; elle affiche donc le backlog.","This window is still running v{v} — reload to finish. A v{v} backup was downloaded.": "Cette fenêtre tourne encore en v{v} — rechargez pour terminer. Une sauvegarde v{v} a été téléchargée.","This window is still running v{v} — reload to finish. A v{v} backup was saved beside this file.": "Cette fenêtre tourne encore en v{v} — rechargez pour terminer. Une sauvegarde v{v} a été enregistrée à côté de ce fichier.","This window is still running v{v}. If you overwrote the file that's open here, reload; otherwise open the file you saved.": "Cette fenêtre tourne encore en v{v}. Si vous avez écrasé le fichier ouvert ici, rechargez ; sinon ouvrez le fichier enregistré.",@@ -654,6 +659,7 @@ export const fr: Catalog = {"{n} of {total} wikilink(s) resolved.": "{n} wikilien(s) sur {total} résolus.","{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} page(s) avaient un frontmatter, conservé tel quel dans un bloc replié.","{n} page(s) inside it move up a level.": "{n} page(s) qu’elle contient remonteront d’un niveau.",+ "{n} pages": "{n} pages","{n} pages, in sidebar order, with a contents page": "{n} pages, dans l’ordre de la barre latérale, avec une page de sommaire","{n} table(s) imported, with their column alignment.": "{n} tableau(x) importé(s), avec l’alignement de leurs colonnes.","{n} table(s) kept as text: there is no table block in this format yet.": "{n} tableau(x) conservés en texte : ce format n’a pas encore de bloc tableau.",diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.tsindex 2ddb5127..3715a750 100644--- a/spaces/src/i18n/it.ts+++ b/spaces/src/i18n/it.ts@@ -321,6 +321,7 @@ export const it: Catalog = {"No issues yet. Add a status field to any page and it appears here.": "Ancora nessuna issue. Aggiungi un campo stato a una pagina e comparirà qui.","No page matches": "Nessuna pagina corrisponde","No pages yet": "Ancora nessuna pagina",+ "No tags match": "Nessuna etichetta corrisponde","No section named {name} on this page.": "Nessuna sezione chiamata {name} in questa pagina.","No versions yet — they build up as you write and save.": "Ancora nessuna versione: si accumulano mentre scrivi e salvi.","No templates yet. Open a page you would like to reuse and choose “Save as template”.": "Ancora nessun modello. Apri una pagina che vuoi riutilizzare e scegli «Salva come modello».",@@ -356,6 +357,7 @@ export const it: Catalog = {"Page": "Pagina","Page options": "Opzioni della pagina","Pages": "Pagine",+ "Pages carrying this tag": "Pagine con questa etichetta","Pages nested under this one": "Pagine annidate sotto questa","Pages open at their normal width again": "Le pagine tornano alla larghezza normale","Pages that have this property": "Pagine che hanno questa proprietà",@@ -480,6 +482,8 @@ export const it: Catalog = {"Strikethrough": "Barrato","Strikethrough — ⇧⌘S": "Barrato — ⇧⌘S","Table": "Tabella",+ "Tag": "Etichetta",+ "Tagged": "Etichettate","Take it elsewhere": "Portalo altrove","Taken from the address if blank": "Se vuoto, viene preso dall'indirizzo","Tall": "Alto",@@ -548,6 +552,7 @@ export const it: Catalog = {"This space is encrypted, so no versions are kept.": "Questo spazio è cifrato, quindi non viene conservata alcuna versione.","This space is encrypted. Saves stay encrypted.": "Questo spazio è cifrato. I salvataggi restano cifrati.","This space is locked": "Questo spazio è bloccato",+ "This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.": "Questa vista sceglie le sue pagine in un modo che questa versione non comprende, quindi mostra il backlog.","This window is still running v{v} — reload to finish. A v{v} backup was downloaded.": "Questa finestra esegue ancora la v{v} — ricarica per completare. È stato scaricato un backup v{v}.","This window is still running v{v} — reload to finish. A v{v} backup was saved beside this file.": "Questa finestra esegue ancora la v{v} — ricarica per completare. Un backup v{v} è stato salvato accanto a questo file.","This window is still running v{v}. If you overwrote the file that's open here, reload; otherwise open the file you saved.": "Questa finestra esegue ancora la v{v}. Se hai sovrascritto il file aperto qui, ricarica; altrimenti apri il file salvato.",@@ -654,6 +659,7 @@ export const it: Catalog = {"{n} of {total} wikilink(s) resolved.": "{n} wikilink su {total} risolti.","{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} pagine avevano un frontmatter, conservato alla lettera in un blocco richiuso.","{n} page(s) inside it move up a level.": "{n} pagine contenute salgono di un livello.",+ "{n} pages": "{n} pagine","{n} pages, in sidebar order, with a contents page": "{n} pagine, nell’ordine della barra laterale, con una pagina indice","{n} table(s) imported, with their column alignment.": "{n} tabella/e importata/e, con l’allineamento delle colonne.","{n} table(s) kept as text: there is no table block in this format yet.": "{n} tabelle conservate come testo: questo formato non ha ancora un blocco tabella.",diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.tsindex 38900c53..9ac8c89a 100644--- a/spaces/src/i18n/ja.ts+++ b/spaces/src/i18n/ja.ts@@ -321,6 +321,7 @@ export const ja: Catalog = {"No issues yet. Add a status field to any page and it appears here.": "まだイシューはありません。どれかのページにステータス項目を追加すると、ここに表示されます。","No page matches": "一致するページがありません","No pages yet": "ページがまだありません",+ "No tags match": "一致するタグはありません","No section named {name} on this page.": "このページに「{name}」という見出しはありません。","No versions yet — they build up as you write and save.": "まだバージョンはありません。書いて保存するたびに増えていきます。","No templates yet. Open a page you would like to reuse and choose “Save as template”.": "まだテンプレートはありません。再利用したいページを開いて「テンプレートとして保存」を選んでください。",@@ -356,6 +357,7 @@ export const ja: Catalog = {"Page": "ページ","Page options": "ページのオプション","Pages": "ページ",+ "Pages carrying this tag": "このタグが付いたページ","Pages nested under this one": "このページの下にあるページ","Pages open at their normal width again": "ページは通常の幅に戻りました","Pages that have this property": "このプロパティを持つページ",@@ -480,6 +482,8 @@ export const ja: Catalog = {"Strikethrough": "取り消し線","Strikethrough — ⇧⌘S": "取り消し線 — ⇧⌘S","Table": "表",+ "Tag": "タグ",+ "Tagged": "タグ付き","Take it elsewhere": "外に持ち出す","Taken from the address if blank": "空欄ならアドレスから取り込みます","Tall": "縦長",@@ -548,6 +552,7 @@ export const ja: Catalog = {"This space is encrypted, so no versions are kept.": "このスペースは暗号化されているため、バージョンは保存されません。","This space is encrypted. Saves stay encrypted.": "このスペースは暗号化されています。保存しても暗号化されたままです。","This space is locked": "このスペースはロックされています",+ "This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.": "このビューは、このバージョンが理解できない方法でページを選んでいるため、代わりにバックログを表示しています。","This window is still running v{v} — reload to finish. A v{v} backup was downloaded.": "このウィンドウはまだ v{v} で動作中 — 再読込で完了します。v{v} のバックアップをダウンロード済み。","This window is still running v{v} — reload to finish. A v{v} backup was saved beside this file.": "このウィンドウはまだ v{v} で動作中 — 再読込で完了します。v{v} のバックアップをこのファイルの隣に保存しました。","This window is still running v{v}. If you overwrote the file that's open here, reload; otherwise open the file you saved.": "このウィンドウはまだ v{v} で動作中。開いているファイルを上書きした場合は再読込を。別に保存した場合はそのファイルを開いてください。",@@ -654,6 +659,7 @@ export const ja: Catalog = {"{n} of {total} wikilink(s) resolved.": "{total} 個のウィキリンクのうち {n} 個を解決しました。","{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} ページにフロントマターがありました。折りたたみブロックにそのまま保存しています。","{n} page(s) inside it move up a level.": "中にある {n} ページが 1 つ上の階層に移動します。",+ "{n} pages": "{n} 件のページ","{n} pages, in sidebar order, with a contents page": "{n} ページをサイドバー順に、目次ページ付きで","{n} table(s) imported, with their column alignment.": "{n} 個の表を取り込みました(列の配置も含みます)。","{n} table(s) kept as text: there is no table block in this format yet.": "{n} 個の表はテキストとして保存しました。この形式にはまだ表ブロックがありません。",diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.tsindex ab389e4e..2b75cd5b 100644--- a/spaces/src/i18n/packed.ts+++ b/spaces/src/i18n/packed.ts@@ -416,6 +416,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"No pages yet": ["ページがまだありません","还没有页面","尚無頁面","Aún no hay páginas","Aucune page pour l’instant","Noch keine Seiten","Ancora nessuna pagina","Ainda sem páginas"],"No recovery — lose the password and the space is gone": ["復元できません — パスワードを失うとスペースも失われます","无法找回 — 丢失密码,空间也就没了","無法找回 — 遺失密碼,空間也就沒了","Sin recuperación: si pierdes la contraseña, pierdes el espacio","Aucune récupération : perdez le mot de passe et l’espace est perdu","Keine Wiederherstellung — Passwort verloren, Space verloren","Nessun recupero: se perdi la password, perdi lo spazio","Sem recuperação — perca a senha e o espaço se perde"],"No section named {name} on this page.": ["このページに「{name}」という見出しはありません。","本页没有名为“{name}”的标题。","本頁沒有名為「{name}」的標題。","No hay ninguna sección llamada {name} en esta página.","Aucune section nommée {name} sur cette page.","Kein Abschnitt namens {name} auf dieser Seite.","Nessuna sezione chiamata {name} in questa pagina.","Não há nenhuma secção chamada {name} nesta página."],+ "No tags match": ["一致するタグはありません","没有匹配的标签","沒有相符的標籤","Ninguna etiqueta coincide","Aucune étiquette ne correspond","Keine passenden Schlagwörter","Nessuna etichetta corrisponde","Nenhuma etiqueta corresponde"],"No templates yet. Open a page you would like to reuse and choose “Save as template”.": ["まだテンプレートはありません。再利用したいページを開いて「テンプレートとして保存」を選んでください。","还没有模板。打开一个想重复使用的页面,选择“保存为模板”。","還沒有範本。開啟一個想重複使用的頁面,選擇「儲存為範本」。","Todavía no hay plantillas. Abre una página que quieras reutilizar y elige «Guardar como plantilla».","Aucun modèle pour l’instant. Ouvrez une page que vous voulez réutiliser et choisissez « Enregistrer comme modèle ».","Noch keine Vorlagen. Öffne eine Seite, die du wiederverwenden möchtest, und wähle „Als Vorlage sichern“.","Ancora nessun modello. Apri una pagina che vuoi riutilizzare e scegli «Salva come modello».","Ainda não há modelos. Abre uma página que queiras reutilizar e escolhe «Guardar como modelo»."],"No versions yet — they build up as you write and save.": ["まだバージョンはありません。書いて保存するたびに増えていきます。","暂无版本。随着你的书写和保存,版本会逐渐累积。","尚無版本。隨著你的書寫與儲存,版本會逐漸累積。","Aún no hay versiones: se acumulan a medida que escribes y guardas.","Pas encore de versions — elles s’accumulent à mesure que vous écrivez et enregistrez.","Noch keine Versionen — sie sammeln sich beim Schreiben und Speichern an.","Ancora nessuna versione: si accumulano mentre scrivi e salvi.","Ainda sem versões — vão-se acumulando à medida que escreves e guardas."],"None": ["なし","无","無","Ninguno","Aucun","Keine","Nessuno","Nenhum"],@@ -457,6 +458,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Page": ["ページ","页面","頁面","Página","Page","Seite","Pagina","Página"],"Page options": ["ページのオプション","页面选项","頁面選項","Opciones de la página","Options de la page","Seiten-Optionen","Opzioni della pagina","Opções da página"],"Pages": ["ページ","页面","頁面","Páginas","Pages","Seiten","Pagine","Páginas"],+ "Pages carrying this tag": ["このタグが付いたページ","带有此标签的页面","帶有此標籤的頁面","Páginas que llevan esta etiqueta","Pages portant cette étiquette","Seiten mit diesem Schlagwort","Pagine con questa etichetta","Páginas com esta etiqueta"],"Pages nested under this one": ["このページの下にあるページ","嵌套在此页面下的页面","巢狀在此頁面下的頁面","Páginas anidadas bajo esta","Pages imbriquées sous celle-ci","Seiten unterhalb dieser Seite","Pagine annidate sotto questa","Páginas aninhadas sob esta"],"Pages open at their normal width again": ["ページは通常の幅に戻りました","页面已恢复为正常宽度","頁面已恢復為正常寬度","Las páginas vuelven a su anchura normal","Les pages retrouvent leur largeur normale","Seiten öffnen wieder in normaler Breite","Le pagine tornano alla larghezza normale","As páginas voltam à largura normal"],"Pages that have this property": ["このプロパティを持つページ","具有此属性的页面","具有此屬性的頁面","Páginas que tienen esta propiedad","Pages qui ont cette propriété","Seiten mit dieser Eigenschaft","Pagine che hanno questa proprietà","Páginas que têm esta propriedade"],@@ -604,6 +606,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Table": ["表","表格","表格","Tabla","Tableau","Tabelle","Tabella","Tabela"],"Table view": ["表ビュー","表格视图","表格檢視","Vista de tabla","Vue tableau","Tabellenansicht","Vista tabella","Vista de tabela"],"Tables": ["表","表格","表格","Tablas","Tableaux","Tabellen","Tabelle","Tabelas"],+ "Tag": ["タグ","标签","標籤","Etiqueta","Étiquette","Schlagwort","Etichetta","Etiqueta"],+ "Tagged": ["タグ付き","带标签","有標籤","Etiquetadas","Étiquetées","Mit Schlagwort","Etichettate","Etiquetadas"],"Taken from the address if blank": ["空欄ならアドレスから取り込みます","留空则取自网址","留空則取自網址","Si se deja vacío, se toma de la dirección","Si vide, repris de l’adresse","Bleibt das Feld leer, wird er aus der Adresse übernommen","Se vuoto, viene preso dall'indirizzo","Se ficar vazio, é retirado do endereço"],"Takes effect on the next save": ["次の保存から有効になります","下次保存时生效","下次儲存時生效","Se aplica en el próximo guardado","Prend effet au prochain enregistrement","Gilt ab der nächsten Speicherung","Ha effetto dal prossimo salvataggio","Vale a partir do próximo salvamento"],"Tall": ["縦長","竖向","直式","Alto","Haut","Hoch","Alto","Alto"],@@ -686,6 +690,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"This space is locked": ["このスペースはロックされています","此空间已锁定","此空間已鎖定","Este espacio está bloqueado","Cet espace est verrouillé","Dieser Space ist gesperrt","Questo spazio è bloccato","Este espaço está bloqueado"],"This space no longer uses a design of its own.": ["このスペースは独自のデザインを使わなくなりました。","此空间不再使用自己的设计。","此空間不再使用自己的設計。","Este espacio ya no usa un diseño propio.","Cet espace n’utilise plus de design qui lui soit propre.","Dieser Space verwendet keine eigene Gestaltung mehr.","Questo spazio non usa più un design proprio.","Este espaço já não usa um design próprio."],"This space reads right-to-left; a deck has no such setting.": ["このスペースは右から左へ読みます。デッキにはその設定がありません。","这个空间从右向左阅读;演示文稿没有这项设置。","這個空間由右至左閱讀;簡報沒有這項設定。","Este espacio se lee de derecha a izquierda; una presentación no tiene ese ajuste.","Cet espace se lit de droite à gauche ; une présentation n’a pas ce réglage.","Dieser Raum wird von rechts nach links gelesen; eine Präsentation hat diese Einstellung nicht.","Questo spazio si legge da destra a sinistra; una presentazione non ha questa impostazione.","Este espaço lê-se da direita para a esquerda; uma apresentação não tem essa definição."],+ "This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.": ["このビューは、このバージョンが理解できない方法でページを選んでいるため、代わりにバックログを表示しています。","此视图以本版本无法理解的方式选择页面,因此改为显示待办列表。","此檢視以本版本無法理解的方式選擇頁面,因此改為顯示待辦清單。","Esta vista elige sus páginas de una forma que esta versión no entiende, así que muestra la lista de tareas.","Cette vue choisit ses pages d’une façon que cette version ne comprend pas ; elle affiche donc le backlog.","Diese Ansicht wählt ihre Seiten auf eine Weise, die diese Version nicht versteht, und zeigt stattdessen den Backlog.","Questa vista sceglie le sue pagine in un modo che questa versione non comprende, quindi mostra il backlog.","Esta vista escolhe as suas páginas de uma forma que esta versão não entende, por isso mostra o backlog."],"This week": ["今週","本周","本週","Esta semana","Cette semaine","Diese Woche","Questa settimana","Esta semana"],"This window is still running v{v} — reload to finish. A v{v} backup was downloaded.": ["このウィンドウはまだ v{v} で動作中 — 再読込で完了します。v{v} のバックアップをダウンロード済み。","此窗口仍在运行 v{v} — 重新加载以完成。已下载 v{v} 备份。","此視窗仍在執行 v{v} — 重新載入以完成。已下載 v{v} 備份。","Esta ventana sigue en v{v} — recarga para terminar. Se descargó una copia de seguridad v{v}.","Cette fenêtre tourne encore en v{v} — rechargez pour terminer. Une sauvegarde v{v} a été téléchargée.","Dieses Fenster läuft noch mit v{v} — zum Abschließen neu laden. Ein v{v}-Backup wurde heruntergeladen.","Questa finestra esegue ancora la v{v} — ricarica per completare. È stato scaricato un backup v{v}.","Esta janela ainda está executando a v{v} — recarregue para concluir. Um backup da v{v} foi baixado."],"This window is still running v{v} — reload to finish. A v{v} backup was saved beside this file.": ["このウィンドウはまだ v{v} で動作中 — 再読込で完了します。v{v} のバックアップをこのファイルの隣に保存しました。","此窗口仍在运行 v{v} — 重新加载以完成。已在此文件旁保存 v{v} 备份。","此視窗仍在執行 v{v} — 重新載入以完成。已在此檔案旁儲存 v{v} 備份。","Esta ventana sigue en v{v} — recarga para terminar. Se guardó una copia de seguridad v{v} junto a este archivo.","Cette fenêtre tourne encore en v{v} — rechargez pour terminer. Une sauvegarde v{v} a été enregistrée à côté de ce fichier.","Dieses Fenster läuft noch mit v{v} — zum Abschließen neu laden. Ein v{v}-Backup wurde neben dieser Datei gespeichert.","Questa finestra esegue ancora la v{v} — ricarica per completare. Un backup v{v} è stato salvato accanto a questo file.","Esta janela ainda está executando a v{v} — recarregue para concluir. Um backup da v{v} foi salvo ao lado deste arquivo."],@@ -835,6 +840,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"{n} of {total} wikilink(s) resolved.": ["{total} 個のウィキリンクのうち {n} 個を解決しました。","{total} 个 wiki 链接中解析了 {n} 个。","{total} 個 wiki 連結中解析了 {n} 個。","{n} de {total} wikilink(s) resueltos.","{n} wikilien(s) sur {total} résolus.","{n} von {total} Wikilink(s) aufgelöst.","{n} wikilink su {total} risolti.","{n} de {total} wikilink(s) resolvidos."],"{n} page(s) had frontmatter, kept verbatim in a folded block.": ["{n} ページにフロントマターがありました。折りたたみブロックにそのまま保存しています。","{n} 个页面带有 frontmatter,已原样保存在折叠块里。","{n} 個頁面帶有 frontmatter,已原樣保存在摺疊區塊裡。","{n} página(s) tenían frontmatter, conservado tal cual en un bloque plegado.","{n} page(s) avaient un frontmatter, conservé tel quel dans un bloc replié.","{n} Seite(n) hatten Frontmatter — wortgetreu in einem zugeklappten Block erhalten.","{n} pagine avevano un frontmatter, conservato alla lettera in un blocco richiuso.","{n} página(s) tinham frontmatter, guardado tal e qual num bloco fechado."],"{n} page(s) inside it move up a level.": ["中にある {n} ページが 1 つ上の階層に移動します。","其中的 {n} 个页面会上移一级。","其中的 {n} 個頁面會往上移一層。","{n} página(s) que contiene suben un nivel.","{n} page(s) qu’elle contient remonteront d’un niveau.","{n} Unterseiten rücken eine Ebene nach oben.","{n} pagine contenute salgono di un livello.","{n} página(s) dentro dela sobem um nível."],+ "{n} pages": ["{n} 件のページ","{n} 个页面","{n} 個頁面","{n} páginas","{n} pages","{n} Seiten","{n} pagine","{n} páginas"],"{n} pages, in sidebar order, with a contents page": ["{n} ページをサイドバー順に、目次ページ付きで","{n} 个页面,按侧边栏顺序,并附一个目录页","{n} 個頁面,依側邊欄順序排列,並附目錄頁","{n} páginas, en el orden de la barra lateral, con una página de índice","{n} pages, dans l’ordre de la barre latérale, avec une page de sommaire","{n} Seiten, in der Reihenfolge der Seitenleiste, mit Inhaltsverzeichnis","{n} pagine, nell’ordine della barra laterale, con una pagina indice","{n} páginas, pela ordem da barra lateral, com uma página de índice"],"{n} slide(s).": ["スライド {n} 枚。","{n} 张幻灯片。","{n} 張投影片。","{n} diapositiva(s).","{n} diapositive(s).","{n} Folie(n).","{n} diapositiva/e.","{n} slide(s)."],"{n} table(s) imported, with their column alignment.": ["{n} 個の表を取り込みました(列の配置も含みます)。","已导入 {n} 个表格,并保留列对齐方式。","已匯入 {n} 個表格,並保留欄位對齊方式。","{n} tabla(s) importada(s), con la alineación de sus columnas.","{n} tableau(x) importé(s), avec l’alignement de leurs colonnes.","{n} Tabelle(n) importiert, samt Spaltenausrichtung.","{n} tabella/e importata/e, con l’allineamento delle colonne.","{n} tabela(s) importada(s), com o alinhamento das colunas."],diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.tsindex 99ed05b0..879d535a 100644--- a/spaces/src/i18n/pt.ts+++ b/spaces/src/i18n/pt.ts@@ -321,6 +321,7 @@ export const pt: Catalog = {"No issues yet. Add a status field to any page and it appears here.": "Ainda não há tarefas. Adiciona um campo de estado a qualquer página e ela aparece aqui.","No page matches": "Nenhuma página corresponde","No pages yet": "Ainda sem páginas",+ "No tags match": "Nenhuma etiqueta corresponde","No section named {name} on this page.": "Não há nenhuma secção chamada {name} nesta página.","No versions yet — they build up as you write and save.": "Ainda sem versões — vão-se acumulando à medida que escreves e guardas.","No templates yet. Open a page you would like to reuse and choose “Save as template”.": "Ainda não há modelos. Abre uma página que queiras reutilizar e escolhe «Guardar como modelo».",@@ -356,6 +357,7 @@ export const pt: Catalog = {"Page": "Página","Page options": "Opções da página","Pages": "Páginas",+ "Pages carrying this tag": "Páginas com esta etiqueta","Pages nested under this one": "Páginas aninhadas sob esta","Pages open at their normal width again": "As páginas voltam à largura normal","Pages that have this property": "Páginas que têm esta propriedade",@@ -480,6 +482,8 @@ export const pt: Catalog = {"Strikethrough": "Tachado","Strikethrough — ⇧⌘S": "Tachado — ⇧⌘S","Table": "Tabela",+ "Tag": "Etiqueta",+ "Tagged": "Etiquetadas","Take it elsewhere": "Levar para outro lado","Taken from the address if blank": "Se ficar vazio, é retirado do endereço","Tall": "Alto",@@ -548,6 +552,7 @@ export const pt: Catalog = {"This space is encrypted, so no versions are kept.": "Este espaço está cifrado, por isso não são guardadas versões.","This space is encrypted. Saves stay encrypted.": "Este espaço está encriptado. Continua encriptado sempre que guardar.","This space is locked": "Este espaço está bloqueado",+ "This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.": "Esta vista escolhe as suas páginas de uma forma que esta versão não entende, por isso mostra o backlog.","This window is still running v{v} — reload to finish. A v{v} backup was downloaded.": "Esta janela ainda está executando a v{v} — recarregue para concluir. Um backup da v{v} foi baixado.","This window is still running v{v} — reload to finish. A v{v} backup was saved beside this file.": "Esta janela ainda está executando a v{v} — recarregue para concluir. Um backup da v{v} foi salvo ao lado deste arquivo.","This window is still running v{v}. If you overwrote the file that's open here, reload; otherwise open the file you saved.": "Esta janela ainda está executando a v{v}. Se você sobrescreveu o arquivo aberto aqui, recarregue; caso contrário, abra o arquivo que salvou.",@@ -654,6 +659,7 @@ export const pt: Catalog = {"{n} of {total} wikilink(s) resolved.": "{n} de {total} wikilink(s) resolvidos.","{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} página(s) tinham frontmatter, guardado tal e qual num bloco fechado.","{n} page(s) inside it move up a level.": "{n} página(s) dentro dela sobem um nível.",+ "{n} pages": "{n} páginas","{n} pages, in sidebar order, with a contents page": "{n} páginas, pela ordem da barra lateral, com uma página de índice","{n} table(s) imported, with their column alignment.": "{n} tabela(s) importada(s), com o alinhamento das colunas.","{n} table(s) kept as text: there is no table block in this format yet.": "{n} tabela(s) ficaram como texto: este formato ainda não tem bloco de tabela.",diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.tsindex feae1ddb..694f0ab7 100644--- a/spaces/src/i18n/zh-Hans.ts+++ b/spaces/src/i18n/zh-Hans.ts@@ -321,6 +321,7 @@ export const zh_Hans: Catalog = {"No issues yet. Add a status field to any page and it appears here.": "还没有事项。给任意页面添加状态字段,它就会出现在这里。","No page matches": "没有匹配的页面","No pages yet": "还没有页面",+ "No tags match": "没有匹配的标签","No section named {name} on this page.": "本页没有名为“{name}”的标题。","No versions yet — they build up as you write and save.": "暂无版本。随着你的书写和保存,版本会逐渐累积。","No templates yet. Open a page you would like to reuse and choose “Save as template”.": "还没有模板。打开一个想重复使用的页面,选择“保存为模板”。",@@ -356,6 +357,7 @@ export const zh_Hans: Catalog = {"Page": "页面","Page options": "页面选项","Pages": "页面",+ "Pages carrying this tag": "带有此标签的页面","Pages nested under this one": "嵌套在此页面下的页面","Pages open at their normal width again": "页面已恢复为正常宽度","Pages that have this property": "具有此属性的页面",@@ -480,6 +482,8 @@ export const zh_Hans: Catalog = {"Strikethrough": "删除线","Strikethrough — ⇧⌘S": "删除线 — ⇧⌘S","Table": "表格",+ "Tag": "标签",+ "Tagged": "带标签","Take it elsewhere": "把内容带走","Taken from the address if blank": "留空则取自网址","Tall": "竖向",@@ -548,6 +552,7 @@ export const zh_Hans: Catalog = {"This space is encrypted, so no versions are kept.": "此空间已加密,因此不保存任何版本。","This space is encrypted. Saves stay encrypted.": "此空间已加密。保存时仍保持加密。","This space is locked": "此空间已锁定",+ "This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.": "此视图以本版本无法理解的方式选择页面,因此改为显示待办列表。","This window is still running v{v} — reload to finish. A v{v} backup was downloaded.": "此窗口仍在运行 v{v} — 重新加载以完成。已下载 v{v} 备份。","This window is still running v{v} — reload to finish. A v{v} backup was saved beside this file.": "此窗口仍在运行 v{v} — 重新加载以完成。已在此文件旁保存 v{v} 备份。","This window is still running v{v}. If you overwrote the file that's open here, reload; otherwise open the file you saved.": "此窗口仍在运行 v{v}。若覆盖了当前打开的文件请重新加载;否则请打开您保存的文件。",@@ -654,6 +659,7 @@ export const zh_Hans: Catalog = {"{n} of {total} wikilink(s) resolved.": "{total} 个 wiki 链接中解析了 {n} 个。","{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} 个页面带有 frontmatter,已原样保存在折叠块里。","{n} page(s) inside it move up a level.": "其中的 {n} 个页面会上移一级。",+ "{n} pages": "{n} 个页面","{n} pages, in sidebar order, with a contents page": "{n} 个页面,按侧边栏顺序,并附一个目录页","{n} table(s) imported, with their column alignment.": "已导入 {n} 个表格,并保留列对齐方式。","{n} table(s) kept as text: there is no table block in this format yet.": "{n} 个表格按原文保留为文字:这个格式还没有表格块。",diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.tsindex 2f331ab9..5a1fdc73 100644--- a/spaces/src/i18n/zh-Hant.ts+++ b/spaces/src/i18n/zh-Hant.ts@@ -321,6 +321,7 @@ export const zh_Hant: Catalog = {"No issues yet. Add a status field to any page and it appears here.": "還沒有項目。為任一頁面新增狀態欄位,它就會出現在這裡。","No page matches": "沒有相符的頁面","No pages yet": "尚無頁面",+ "No tags match": "沒有相符的標籤","No section named {name} on this page.": "本頁沒有名為「{name}」的標題。","No versions yet — they build up as you write and save.": "尚無版本。隨著你的書寫與儲存,版本會逐漸累積。","No templates yet. Open a page you would like to reuse and choose “Save as template”.": "還沒有範本。開啟一個想重複使用的頁面,選擇「儲存為範本」。",@@ -356,6 +357,7 @@ export const zh_Hant: Catalog = {"Page": "頁面","Page options": "頁面選項","Pages": "頁面",+ "Pages carrying this tag": "帶有此標籤的頁面","Pages nested under this one": "巢狀在此頁面下的頁面","Pages open at their normal width again": "頁面已恢復為正常寬度","Pages that have this property": "具有此屬性的頁面",@@ -480,6 +482,8 @@ export const zh_Hant: Catalog = {"Strikethrough": "刪除線","Strikethrough — ⇧⌘S": "刪除線 — ⇧⌘S","Table": "表格",+ "Tag": "標籤",+ "Tagged": "有標籤","Take it elsewhere": "把內容帶走","Taken from the address if blank": "留空則取自網址","Tall": "直式",@@ -548,6 +552,7 @@ export const zh_Hant: Catalog = {"This space is encrypted, so no versions are kept.": "此空間已加密,因此不保存任何版本。","This space is encrypted. Saves stay encrypted.": "此空間已加密。往後的儲存也會維持加密。","This space is locked": "此空間已鎖定",+ "This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.": "此檢視以本版本無法理解的方式選擇頁面,因此改為顯示待辦清單。","This window is still running v{v} — reload to finish. A v{v} backup was downloaded.": "此視窗仍在執行 v{v} — 重新載入以完成。已下載 v{v} 備份。","This window is still running v{v} — reload to finish. A v{v} backup was saved beside this file.": "此視窗仍在執行 v{v} — 重新載入以完成。已在此檔案旁儲存 v{v} 備份。","This window is still running v{v}. If you overwrote the file that's open here, reload; otherwise open the file you saved.": "此視窗仍在執行 v{v}。若已覆寫目前開啟的檔案請重新載入;否則請開啟您儲存的檔案。",@@ -654,6 +659,7 @@ export const zh_Hant: Catalog = {"{n} of {total} wikilink(s) resolved.": "{total} 個 wiki 連結中解析了 {n} 個。","{n} page(s) had frontmatter, kept verbatim in a folded block.": "{n} 個頁面帶有 frontmatter,已原樣保存在摺疊區塊裡。","{n} page(s) inside it move up a level.": "其中的 {n} 個頁面會往上移一層。",+ "{n} pages": "{n} 個頁面","{n} pages, in sidebar order, with a contents page": "{n} 個頁面,依側邊欄順序排列,並附目錄頁","{n} table(s) imported, with their column alignment.": "已匯入 {n} 個表格,並保留欄位對齊方式。","{n} table(s) kept as text: there is no table block in this format yet.": "{n} 個表格按原文保留為文字:這個格式還沒有表格區塊。",diff --git a/spaces/src/render.ts b/spaces/src/render.tsindex d5f5781f..037f7b1b 100644--- a/spaces/src/render.ts+++ b/spaces/src/render.ts@@ -12,12 +12,13 @@import { type SpacesDoc, type Page, type Block, loadsRemotely, assetValue, tableOf, linkCard, coverSrc } from './model'import { proceduralCoverSvg, proceduralCoverFor } from './procedural'import { sanitizeInline, inertBody, esc } from './sanitize'+import { decorateTags } from './tags.ts'import { tokenize } from './highlight'import { t, locale } from './i18n'import { TAG_OF, LIST_OF, SPEC, TONE, mediaPlayback } from './blocks'import {fieldByKey, fieldsOf, optionOf, viewRows, headerLength, propBlockOf,- passesFilter, filterCount, unknownFilterKeys,+ passesFilter, filterCount, unknownFilterKeys, unknownSourceKeys,sortRows, unknownSortKeys, sortDirOf, layoutOf, nextLayout,type ViewSort, type FieldSpec, type ViewLayout,} from './fields'@@ -692,6 +693,7 @@ function renderTable(b: Block, opts: RenderOpts): HTMLElement {td.innerHTML = opts.editable || !opts.footnotes? cleanCell: markRefs(cleanCell, opts.footnotes, opts.footnoteScope ?? '')+ decorateTags(td)tr.appendChild(td)})if (head) {@@ -863,6 +865,12 @@ function inlineHost(b: Block, opts: RenderOpts): HTMLElement {inner.innerHTML = opts.editable || !opts.footnotes? clean: markRefs(clean, opts.footnotes, opts.footnoteScope ?? '')+ // TAG CHIPS GO ON AFTER the footnote either/or above, never before: that+ // `innerHTML =` replaces the host's children, so chips drawn first were+ // wiped (the September integration bug). Chips skip <a>, so a footnote+ // marker is never decorated, and tags.ts readInline strips chips back out+ // of whatever an editable host commits.+ decorateTags(inner)if (!b.html) inner.dataset.empty = '1'return inner}@@ -1369,19 +1377,41 @@ function renderView(host: HTMLElement, b: Block, doc: SpacesDoc, opts: RenderOpt// WHICH PAGES. Named after what it answers rather than "Source", because// the question in the reader's head is "what is in this?" — and it says the// answer, not the word, when there is one.- const src = (b as { source?: { has?: unknown; under?: unknown } }).source+ const src = (b as { source?: { has?: unknown; under?: unknown; tag?: unknown } }).sourceconst hasKey = typeof src?.has === 'string' ? src.has : ''const underId = typeof src?.under === 'string' ? src.under : ''+ const tagKey = typeof src?.tag === 'string' ? src.tag : ''const srcLabel = hasKey ? (fieldByKey(doc, hasKey)?.label ?? hasKey): underId ? (doc.pages.find((p) => p.id === underId)?.title || t('Untitled'))- : t('Issues')+ // the tag SAYS ITSELF — no lookup, and the hash is what makes it read+ // as a tag rather than as a page somebody happened to call "recipe"+ : tagKey ? '#' + tagKey+ : t('Issues')const sourceB = btn('viewSource', `${t('Pages')} · ${srcLabel}`,- t('Choose which pages this view holds'), !!(hasKey || underId))+ t('Choose which pages this view holds'), !!(hasKey || underId || tagKey))head.append(layoutB, sourceB, ...(asList ? [] : [groupB]), sortB, openB, filterB)}host.appendChild(head)+ // A SOURCE this build cannot evaluate is the WORST of the three, and it had+ // no warning at all until now — `unknownSourceKeys` existed in fields.ts and+ // nothing called it. An unreadable filter over-shows; an unreadable SOURCE+ // means the view silently falls back to the backlog and shows a completely+ // different set of pages, with the header still naming the source it cannot+ // apply. Measured against a build of `main`: a view sourced on a tag renders+ // as Issues there, and says nothing.+ //+ // That build is already shipped and cannot be told. What this fixes is+ // forward: the FOURTH selector, whenever somebody adds one, degrades loudly.+ const unknownSrc = unknownSourceKeys((b as { source?: unknown }).source)+ if (unknownSrc.length) {+ const note = document.createElement('p')+ note.className = 'sp-view-empty'+ note.textContent = t('This view chooses its pages in a way this build does not understand, so it is showing the backlog instead.')+ host.appendChild(note)+ }+// A rule this build cannot evaluate means the view shows MORE than its author// asked for. Additivity keeps the rule; honesty says so.// ...and the same rule one level down: an OPERATOR from a newer build is adiff --git a/spaces/src/store.ts b/spaces/src/store.tsindex 3375a022..cff78cdb 100644--- a/spaces/src/store.ts+++ b/spaces/src/store.ts@@ -14,6 +14,7 @@type Scope = 'doc' | 'page'import { type SpacesDoc, type Page, type Block, buildIndex, type SpaceIndex, homePage } from './model'+import { buildTagIndex, type TagIndex } from './tags.ts'import { FROM_LIVE } from '../../kernel/src/docfields.ts'type Listener = () => void@@ -88,6 +89,19 @@ type Entry =export class Store {doc: SpacesDocindex: SpaceIndex+ /**+ * Every `#tag` in the prose, derived and LAZY.+ *+ * Lazy because `touch()` reindexes on every keystroke of a typing run, and a+ * tag index is a second full scan of every block in the document. Nothing+ * reads it per-keystroke — the chips a render draws come from the text in+ * front of them, not from here — so it is built when something asks (a view+ * sourced on a tag, ⌘K, the graph, the tag sheet) and dropped whenever the+ * document changes. Same derived-never-stored rule as `index`, one less full+ * pass per keystroke.+ */+ get tags(): TagIndex { return (this.tagIx ??= buildTagIndex(this.doc)) }+ private tagIx: TagIndex | null = null/** the page being viewed */pageId: string/** blocks currently selected at block level (Esc from text editing) */@@ -265,6 +279,7 @@ export class Store {*/reindex(): void {this.index = buildIndex(this.doc)+ this.tagIx = nullif (!this.index.page.has(this.pageId)) this.pageId = homePage(this.doc)?.id ?? ''}diff --git a/spaces/src/styles.css b/spaces/src/styles.cssindex e4682338..00f338ed 100644--- a/spaces/src/styles.css+++ b/spaces/src/styles.css@@ -494,6 +494,29 @@ option { background: var(--field); color: var(--ink); }/* the accent at a tint a paragraph can be read through, and an explicit ink:`mark`'s UA default is black on yellow, which is not this document's ink */.sp-body mark { background: color-mix(in srgb, var(--accent) 30%, transparent); color: inherit; border-radius: 3px; padding: 0 .08em; }++/* THE #TAG CHIP.+ Drawn at render into content that is often contenteditable, and taken back+ out of whatever the editor commits (tags.ts). So it must stay INLINE and+ selectable-through: no `display: inline-block`, no `contenteditable=false`,+ no `user-select: none`. A caret has to be able to walk into it and a+ backspace has to delete one character, because inside the editor this is a+ word somebody is still typing. Everything here is paint. */+.sp-tag {+ color: var(--accent-ink);+ background: color-mix(in srgb, var(--accent) 16%, transparent);+ border-radius: 4px; padding: 0 .22em; cursor: pointer;+ text-decoration: none; white-space: nowrap;+}+.sp-tag:hover { background: color-mix(in srgb, var(--accent) 30%, transparent); }+.sp-tag-kids { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 10px; }+.sp-tag-chip {+ font: inherit; font-size: 13px; cursor: pointer;+ color: var(--accent-ink); background: color-mix(in srgb, var(--accent) 16%, transparent);+ border: 0; border-radius: 999px; padding: 3px 10px;+}+.sp-tag-chip:hover { background: color-mix(in srgb, var(--accent) 30%, transparent); }+.sp-tag-count { color: var(--muted); font-size: 13px; margin: 0 0 8px; }/* No blanket link colour here. There was one — `.sp-body a { color: var(--blue) }`— and it never painted a single prose link: `.sp-page a` sets the ink at thesame specificity and later in the sheet, so it won every time. What the rulediff --git a/spaces/src/tags.ts b/spaces/src/tags.tsnew file mode 100644index 00000000..66baa393--- /dev/null+++ b/spaces/src/tags.ts@@ -0,0 +1,449 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Inline `#tag` — the parser, the derived index, and the chip.+//+// THE TAG IS THE `#tag` IN THE PROSE. There is no `Page.tags` array and there+// must never be one. A stored list is a second copy of a fact the text already+// states, and the two disagree the first time anything writes `html` without+// knowing tags exist — an agent calling `updateBlock`, a Markdown import, a+// remote collaborator's op, a hand-edited `#bento-doc`. The backlink index in+// model.ts settled this for links (`buildIndex` reads `html` and stores+// nothing); tags follow it exactly, for the same reason and with the same+// consequence: the index is STALE the moment the document changes, so it is+// rebuilt from the document rather than maintained alongside it.+//+// That also makes format additivity FREE rather than argued: a tagged+// paragraph is a paragraph whose text contains a `#`. A build from before this+// file existed renders it as ordinary prose, because that is all it is. Nothing+// new is written to the file, so there is nothing for an older reader to drop.+//+// TWO READERS OF THE SAME TEXT, and they must agree:+//+// · `parseTags(html)` — a pure string function, no DOM. This one is the+// TRUTH: the index, the filters, the search and the graph all come from it,+// and it is the one a node rig can run.+// · `decorateTags(host)` — a DOM pass that turns the same spans of text into+// chips at render time. Cosmetic. Where the two could ever disagree the+// index wins and the chip is simply not drawn.+//+// They are kept aligned by construction: both refuse to look inside `<a>` and+// `<code>`, and both treat any other inline tag as a word BREAK — the DOM+// walker because `#re<b>cipe</b>` is two text nodes, the string reader because+// it replaces a stripped tag with a space rather than closing the gap.++import type { SpacesDoc, Page } from './model.ts'++/**+ * WHAT COUNTS AS A TAG. Every clause here exists because of a `#` that is not+ * one, and each is covered by its own case in scripts/test-spaces-tags.ts.+ *+ * `(^|[^\p{L}\p{N}_#/\\])` — THE CHARACTER BEFORE.+ * A tag's `#` opens a word. Requiring a non-word character before it is what+ * keeps `C#`, `a#b` and — the one that matters — a URL fragment out:+ * `https://example.com/page#section` is preceded by `e`, and+ * `https://example.com/#top` by `/`. `#` itself is excluded so `##` (a+ * Markdown h2 that somehow reached inline html) opens nothing, and `\` so an+ * escape can be added later without changing what already parses.+ *+ * `#([\p{L}\p{N}_][\p{L}\p{N}_-]*…)` — NO SPACE AFTER THE HASH.+ * This is the whole answer to `# Title`. A Markdown ATX heading is `#` + a+ * space, and markdown.ts's own reader requires that space (`/^(#{1,6})\s+/`),+ * so the two agree about what a heading is. A bare `#` before punctuation+ * (`#!`, `#.`) is likewise nothing.+ *+ * Unicode classes, not `[a-z]`: `#рецепт` and `#レシピ` are tags in the+ * languages this app already ships eight catalogs for.+ *+ * `(?:\/…)*` — NESTED TAGS. See NESTING below.+ *+ * `#p/<id>` — the app's own page-link href — is handled STRUCTURALLY rather+ * than by a special case here: a real page link is an `<a href="#p/…">` whose+ * href is an ATTRIBUTE, not text, and whose link text is a title. Neither+ * reader looks at attributes and neither descends into `<a>`, so no page link+ * can become a tag. A `#p/abc` somebody typed as literal prose IS read as the+ * nested tag `p/abc`, which is correct — it is a hash-word in a sentence, and+ * pretending otherwise would mean reserving a namespace inside the user's own+ * vocabulary.+ */+const TAG_SCAN = /(^|[^\p{L}\p{N}_#/\\])#([\p{L}\p{N}_][\p{L}\p{N}_-]*(?:\/[\p{L}\p{N}_][\p{L}\p{N}_-]*)*)/gu++/**+ * NESTING: `#project/bento` is ONE tag whose key is `project/bento`, and it+ * counts as being under `project` for anything that asks.+ *+ * Decided now rather than later, and that timing is the argument. `/` is+ * either part of the tag character set or it is not; if this build read+ * `#project/bento` as the flat tag `project` followed by the text `/bento`,+ * then adding nesting afterwards would silently CHANGE THE MEANING of text+ * already sitting in files on other people's disks — the same one-way hazard+ * sanitize.ts records for the href allowlist. There is no migration available+ * to a format with no server, so the permissive reading has to be the first+ * one.+ *+ * A parent is not itself an occurrence. `#project` has an entry only if+ * somebody wrote `#project`; what nesting buys is that `pagesWithTag('project')`+ * includes the pages that only carry `#project/bento`.+ */+export const SEP = '/'++/** Longest key we will index. A pathological line cannot grow the index. */+const KEY_MAX = 100++/**+ * The key a tag is COUNTED under: lower-cased, in the document's own casing+ * rules rather than the reader's locale.+ *+ * `toLowerCase()` and NOT `toLocaleLowerCase()`. The index is part of the+ * document's meaning — two people with different `navigator.language` opening+ * the same file must see the same tags — and Turkish locale folding maps `I`+ * to `ı`, so `#Idea` and `#idea` would be one tag in Istanbul and two+ * everywhere else.+ */+export const tagKey = (label: string): string => label.toLowerCase()++/** `project/bento` → `['project']`. Empty for a flat tag. */+export function ancestorsOf(key: string): string[] {+ const parts = key.split(SEP)+ const out: string[] = []+ for (let i = 1; i < parts.length; i++) out.push(parts.slice(0, i).join(SEP))+ return out+}++/**+ * Is this token a `#` that means something else?+ *+ * ALL DIGITS — `#42`, `#404`, `#1`. Prose is full of these ("closes #42",+ * "a #404 page") and essentially none of them are tags. The cost is that a+ * numeric tag has to be written with a letter in it; the alternative is that+ * every issue number in every note becomes an index entry.+ *+ * A CSS HEX COLOUR — `#fff`, `#1e2a3a`, `#ff8800cc`. Three, four, six or eight+ * hex digits and no separator. `#fff` survives the all-digits test (it has+ * letters) and would otherwise be the most common false tag in a document that+ * talks about design at all.+ */+function isNotATag(label: string): boolean {+ if (!/[^\p{Nd}]/u.test(label)) return true+ return !label.includes(SEP) && /^(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(label)+}++/** A tag as it was written, and where in the string it sits. */+export interface TagHit {+ /** the index key — lower-cased */+ key: string+ /** the casing this occurrence used */+ label: string+ /** offset of the `#` in the string that was scanned */+ at: number+}++/**+ * Every tag in one run of plain text.+ *+ * The shared core: `parseTags` feeds it text recovered from html, and+ * `decorateTags` feeds it one DOM text node. One regex, one rejection list, so+ * the index and the chip cannot drift apart on what a tag is.+ */+export function scanText(text: string): TagHit[] {+ const out: TagHit[] = []+ TAG_SCAN.lastIndex = 0+ for (const m of text.matchAll(TAG_SCAN)) {+ // a trailing `-` belongs to the sentence, not the tag: "#work-" and+ // "#a—b" both end the word there+ const label = m[2].replace(/-+$/, '')+ if (!label || label.length > KEY_MAX) continue+ if (isNotATag(label)) continue+ out.push({ key: tagKey(label), label, at: m.index + m[1].length })+ }+ return out+}++/**+ * The plain text a tag may be found in, from a block's inline html.+ *+ * NOT `sanitize.ts textOf`. That one wants every word, and it needs a DOM. This+ * one has to run in a node rig with no DOM at all, and it has to make the two+ * exclusions structural:+ *+ * · `<a>…</a>` goes entirely — link TEXT is a page title or a url someone+ * pasted, not prose, and dropping it is what makes `#p/` page links+ * impossible to misread;+ * · `<code>…</code>` goes entirely — a `#` in inline code is code. (A `code`+ * BLOCK never reaches here: its model value is escaped text, and render.ts+ * paints it through `paintCode`, which this file never touches.)+ *+ * Each removal leaves a SPACE. That is not tidiness: the DOM walker sees+ * `#re<b>cipe</b>` as two separate text nodes and reads `re`, so this reader+ * has to break the word in the same place or the two would disagree.+ *+ * Entities are decoded AFTER tags are stripped — decoding first would let+ * `<b>` become markup that then gets stripped, which is the standard way+ * a two-pass text extractor becomes a parser differential.+ */+export function tagText(html: string): string {+ return html+ .replace(/<a\b[^>]*>[\s\S]*?<\/a\s*>/gi, ' ')+ .replace(/<code\b[^>]*>[\s\S]*?<\/code\s*>/gi, ' ')+ .replace(/<[^>]*>/g, ' ')+ .replace(/ /gi, ' ')+ .replace(/</gi, '<')+ .replace(/>/gi, '>')+ .replace(/"/gi, '"')+ .replace(/�*39;|'/gi, "'")+ .replace(/&/gi, '&')+}++/** Every tag in a block's inline html. */+export const parseTags = (html: string | undefined): TagHit[] =>+ html ? scanText(tagText(html)) : []++// ---- the derived index -----------------------------------------------------++export interface TagRef {+ pageId: string+ blockId: string+}++export interface TagEntry {+ key: string+ /** the casing of the FIRST occurrence in document order — deterministic, so+ * two readers of one file label the tag identically */+ label: string+ /** every occurrence, in document order; a block tagged twice appears twice */+ refs: TagRef[]+ /** the pages carrying it directly, in document order, no duplicates */+ pages: string[]+}++export interface TagIndex {+ /** key → entry, DIRECT occurrences only (see NESTING) */+ tags: Map<string, TagEntry>+ /** page id → the tag keys written on it, first-seen order */+ byPage: Map<string, string[]>+}++/**+ * A table's cells as one string, for scanning only — the same shape and the+ * same reason as model.ts's private `tableCellsText`.+ *+ * Duplicated deliberately rather than exported from model.ts: nine branches+ * are open against this app at once and a one-word export is still a line in+ * a file four of them are editing. Six lines that can only ever be read are+ * the cheaper collision.+ */+function cellsText(rows: unknown[]): string {+ let out = ''+ for (const row of rows) {+ if (!Array.isArray(row)) continue+ for (const cell of row) if (typeof cell === 'string') out += cell + '\n'+ }+ return out+}++/**+ * Build the tag index.+ *+ * WHERE A TAG MAY LIVE mirrors `buildIndex` exactly, including its `rows`+ * fallback and including why: a table the editor wrote mirrors its cells into+ * `html`, so scanning both would count every cell tag twice; a table that+ * arrived any other way has `rows` and no `html`, and a tag in one of its+ * cells must not vanish.+ *+ * Archived pages ARE indexed. An archive is "out of the way", not "deleted" —+ * the sidebar still lists them and ⌘K still finds them — so a tag index that+ * dropped them would answer "nothing carries #recipe" about a document that+ * does. What excludes them is `viewRows`, at the point where a view asks.+ */+export function buildTagIndex(doc: SpacesDoc): TagIndex {+ const tags = new Map<string, TagEntry>()+ const byPage = new Map<string, string[]>()+ const pages = Array.isArray(doc.pages) ? doc.pages : []++ for (const p of pages) {+ if (!p || !Array.isArray(p.blocks)) continue+ const mine: string[] = []+ const seenHere = new Set<string>()+ for (const b of p.blocks) {+ if (!b) continue+ const src = b.html || (Array.isArray(b.rows) ? cellsText(b.rows) : '')+ if (!src) continue+ for (const hit of parseTags(src)) {+ let entry = tags.get(hit.key)+ if (!entry) {+ entry = { key: hit.key, label: hit.label, refs: [], pages: [] }+ tags.set(hit.key, entry)+ }+ entry.refs.push({ pageId: p.id, blockId: b.id })+ if (entry.pages[entry.pages.length - 1] !== p.id && !entry.pages.includes(p.id)) {+ entry.pages.push(p.id)+ }+ if (!seenHere.has(hit.key)) { seenHere.add(hit.key); mine.push(hit.key) }+ }+ }+ if (mine.length) byPage.set(p.id, mine)+ }+ return { tags, byPage }+}++/** An empty index, for the load path before a document exists. */+export const emptyTagIndex = (): TagIndex => ({ tags: new Map(), byPage: new Map() })++/** `key` itself plus every tag nested under it. Keys only — some may be absent. */+export function keysUnder(index: TagIndex, key: string): string[] {+ const want = tagKey(key)+ const out: string[] = []+ for (const k of index.tags.keys()) {+ if (k === want || k.startsWith(want + SEP)) out.push(k)+ }+ return out.sort()+}++/**+ * Every page carrying this tag OR anything nested under it, in document order.+ *+ * Document order, not index order: two calls with the same document must list+ * the same pages the same way, and `Map` iteration order is insertion order —+ * which is scan order, which is nearly but not exactly page order once a tag+ * appears on a later page first.+ */+export function pagesWithTag(doc: SpacesDoc, index: TagIndex, key: string): Page[] {+ const keys = new Set(keysUnder(index, key))+ if (!keys.size) return []+ const want = new Set<string>()+ for (const k of keys) for (const id of index.tags.get(k)?.pages ?? []) want.add(id)+ return (Array.isArray(doc.pages) ? doc.pages : []).filter((p) => p && want.has(p.id))+}++/** Does this page carry the tag, or anything under it? */+export function pageHasTag(index: TagIndex, pageId: string, key: string): boolean {+ const want = tagKey(key)+ for (const k of index.byPage.get(pageId) ?? []) {+ if (k === want || k.startsWith(want + SEP)) return true+ }+ return false+}++/**+ * Every tag, most-used first, then alphabetical.+ *+ * Count is PAGES, not occurrences: a tag written nine times on one page is one+ * page's worth of "what carries this", and sorting by occurrences would put a+ * repetitive note above a tag that actually spans the space.+ */+export function tagList(index: TagIndex): TagEntry[] {+ return [...index.tags.values()].sort((a, b) =>+ b.pages.length - a.pages.length || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))+}++/** Tags whose key contains `q` (already lower-cased by the caller). */+export const matchTags = (index: TagIndex, q: string): TagEntry[] =>+ tagList(index).filter((e) => e.key.includes(q))++// ---- the chip --------------------------------------------------------------++/** Class on a rendered chip. Also the marker `readInline` strips. */+export const TAG_CLASS = 'sp-tag'++/**+ * Elements a chip is never drawn inside — the DOM half of the two exclusions+ * `tagText` makes structurally.+ */+const NO_DESCEND = new Set(['A', 'CODE', 'SCRIPT', 'STYLE', 'TEXTAREA'])++/**+ * Turn every `#tag` in already-sanitized content into a chip, in place.+ *+ * NO MARKUP IS EVER BUILT AS A STRING. The chip's text comes from+ * `createTextNode` and its key from `dataset`, so the most a hostile `#tag`+ * out of a mailed file can do is name itself something long — the same+ * discipline `paintCode` uses, and for the same reason: this runs on content+ * somebody sent you.+ *+ * THE CHIP CARRIES NO `href`, and that is deliberate twice over. sanitize.ts+ * records why a NEW fragment form is a one-way data hazard (a `#t/` href+ * written under this build would be STRIPPED by a stricter one on the next+ * edit that touched the block), so no such href is invented. And an `<a>` with+ * no href is exactly what `sanitizeInline` UNWRAPS — so if a chip ever does+ * leak into `Block.html`, the canonicalizer that already runs on blur removes+ * it and leaves the text. The feature fails back to plain prose rather than+ * into the format.+ *+ * Idempotent: a chip is inside an `A`, which the walk refuses to descend into.+ */+export function decorateTags(host: HTMLElement): void {+ if (typeof document === 'undefined') return+ const walk = (node: Node): void => {+ for (const child of [...node.childNodes]) {+ if (child.nodeType === Node.ELEMENT_NODE) {+ if (!NO_DESCEND.has((child as HTMLElement).tagName)) walk(child)+ continue+ }+ if (child.nodeType !== Node.TEXT_NODE) continue+ const text = child.nodeValue ?? ''+ const hits = scanText(text)+ if (!hits.length) continue+ const frag = document.createDocumentFragment()+ let cut = 0+ for (const hit of hits) {+ const end = hit.at + 1 + hit.label.length+ if (hit.at > cut) frag.appendChild(document.createTextNode(text.slice(cut, hit.at)))+ const chip = document.createElement('a')+ chip.className = TAG_CLASS+ chip.dataset.tag = hit.key+ chip.textContent = text.slice(hit.at, end)+ frag.appendChild(chip)+ cut = end+ }+ if (cut < text.length) frag.appendChild(document.createTextNode(text.slice(cut)))+ child.parentNode?.replaceChild(frag, child)+ }+ }+ walk(host)+}++/**+ * Strip the chips and draw them again.+ *+ * WHY THIS EXISTS, measured in a browser rather than reasoned: a caret at the+ * end of a chip is a caret INSIDE the `<a>`, so typing there appends to the+ * chip. The model stays right — `readInline` unwraps before committing — but+ * the chip on screen grows to read `#project/bento X`, and `decorateTags`+ * alone cannot repair it because it refuses to descend into an `<a>` (which is+ * exactly what makes it idempotent).+ *+ * So the settle is: take every chip apart, then re-read the text. Called on+ * BLUR only. Doing it per keystroke would be correct and unusable — it+ * replaces the nodes the caret is standing in.+ */+export function redecorateTags(host: HTMLElement): void {+ if (typeof document === 'undefined') return+ for (const chip of [...host.querySelectorAll('.' + TAG_CLASS)]) {+ while (chip.firstChild) chip.parentNode!.insertBefore(chip.firstChild, chip)+ chip.remove()+ }+ host.normalize()+ decorateTags(host)+}++/**+ * An editable host's html WITH THE CHIPS TAKEN BACK OUT — what the model gets.+ *+ * The editor commits `host.innerHTML` on every keystroke, so without this the+ * chips a render just drew would be written straight into `Block.html` and the+ * tag would be stored twice: once as the text, once as the markup around it.+ * This is the same move `wireCode` makes for syntax colour (it commits+ * `textContent`, never `innerHTML`) and for the same reason — the decoration+ * is a rendering, and the model never learns it happened.+ *+ * The fast path matters: this runs per keystroke, and a block with no tag in it+ * must cost one `querySelector`.+ */+export function readInline(host: HTMLElement): string {+ if (!host.querySelector('.' + TAG_CLASS)) return host.innerHTML+ const copy = host.cloneNode(true) as HTMLElement+ for (const chip of [...copy.querySelectorAll('.' + TAG_CLASS)]) {+ while (chip.firstChild) chip.parentNode!.insertBefore(chip.firstChild, chip)+ chip.remove()+ }+ return copy.innerHTML+}