Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: an issue is a page — a Linear-shaped tracker in one file (#242)
nyblnet0c02b08645b2
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 5a89776c..59081ac7 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -1275,6 +1275,160 @@ CI-testable, but the registry drifting from the tree is. It pins `appId`against each app's own `configureApp()` call and the manifest URL against thepath the release publishes to.+## 2026-08-05 — The board's order IS the page order, and a view's filter is two keys++**Decision.** Dragging a card between columns sets that issue's field value.+Dragging it *within* a column reorders `doc.pages`. There is **no per-view+order field**, and nobody may add one in a drag handler. A view's filter is+`filter: { is?: {key: string[]}, open?: boolean }` on the `view` block, and+absent means everything.++**Why order is the page array.** An issue IS a page, and pages are already an+ordered list — the sidebar renders it, the markdown export walks it, and a+saved file preserves it. A stored per-view order is a permanent format field+that has to answer what happens to an issue no view has ever seen, what happens+when two views disagree, and what a build that predates it does with the+orphaned key. Reordering the pages answers none of those questions because it+does not ask them. The consequence is deliberate and worth saying out loud: the+board's order and the sidebar's order are the same order. `fields.ts+reorderPages` is the whole mechanism, and it returns null when a drop changes+nothing, which is what keeps a drag that went nowhere out of the undo stack.++**Why `sort` is NOT implemented.** `sort: [...]` appears in the shape sketched+in the ruling below. It is still unimplemented, and now it is not free: a+stored sort and a hand-dragged order contradict each other, and which one wins+is a format decision, not a rendering detail. Whoever needs sort settles that+first. Until then a `sort` key round-trips untouched and is ignored.++**Why the filter is two keys.** `is` (a field's values) and `open` (a phase).+A filter language grows without limit and can never shrink — every operator is+in files on other people's disks the moment it ships. These two answer the two+questions a tracker is actually asked. Rules: an absent filter, an absent key+and an empty value list all mean "no constraint", so every view block written+before filters keeps working and an empty stored filter is deleted rather than+kept; a value this build does not know is compared LITERALLY, so a filter a+newer build wrote still selects what it meant; `open` is derived from+`FieldOption.group` on the first field whose options declare one (never+hardcoded to `status`), and an unknown value counts as OPEN, because hiding+work this build cannot read is a loss and showing one issue too many is not; a+filter key this build cannot evaluate is kept, is not applied, and the view+SAYS SO — a count that is silently too high is the failure additivity would+otherwise trade for.++**Touch.** A phone cannot drag an HTML5 draggable, and the board is the+tracker's main screen, so every card carries a status BUTTON that opens the+same picker the issue's own header strip opens, through the same writer+(`editor.applyField` → `fields.propHtml`). There is exactly one place where+`value` and `html` are written, and there must stay exactly one.++## 2026-08-05 — An issue is a page: the tracker format for bento/spaces++**Decision.** bento/spaces gains an opinionated, Linear-shaped issue tracker.+An ISSUE IS A PAGE. Its fields are `prop` BLOCKS. The schema those fields draw+on is `doc.fields`. A saved view is a `view` BLOCK. Nothing about this is a new+document type and nothing is a page-level key.++**Why spaces rather than a new app.** A tracker is a pile of short documents+with typed fields and a few saved queries over them. Spaces already has pages,+rich bodies, links, backlinks, search, archive, print, i18n, nine languages and+an agent surface — which is most of a tracker — and Linear's own model is+"an issue is a document with fields". A separate app would rebuild all of it,+and would land where Jira is: a tracker whose issues cannot hold a real+document. The suite's other half, bento/dash, owns typed COLUMNS over rows;+this owns typed FIELDS on documents. That is the seam.++**The format.**++ doc.fields: [ // the schema, document-level+ { key: 'status', label: 'Status', vt: 'select', options: [+ { id: 'todo', label: 'Todo', color: '#…', group: 'unstarted' }, … ] },+ { key: 'assignee', label: 'Assignee', vt: 'person' },+ …+ ]++ // …and on an issue page, its values, as ordinary blocks:+ { id:'b1', type:'prop', key:'status', value:'todo', html:'Status: Todo' }++ // …and a board, which is also just a block:+ { id:'v1', type:'view', layout:'board', groupBy:'status',+ filter:{…}, sort:[…], html:'Board — all issues by status' }++**Why values are blocks and the schema is not.** The ruling above already+settled values: a `prop` block degrades losslessly on a build that predates it+(render.ts's `default:` branch shows its `html`), and it is found by ⌘F, ⌘K,+undo and the block registry for free, because every one of those iterates+`page.blocks`. A page-level key renders as nothing and is invisible to all of+them. But the SCHEMA is not a value: putting the status list on every issue+would copy it into every page and let two pages disagree about what "Todo"+means. Document-level is the only place it can live, and `doc.fields` is+additive — a build that predates it ignores the key and still renders every+`prop` block's `html`.++**Every `prop` block carries a human-readable `html`.** That is what makes the+format degrade rather than vanish, and it is not redundancy: it is the same+discipline as the static preview and the markdown export. An older build, a+thumbnailer, a grep, and a markdown export all see "Status: In progress"+without knowing what a field is.++**Fields render as a header strip, by CONVENTION not by a new container.**+`prop` blocks that precede the first non-prop block on a page are drawn as a+compact strip under the title; the same blocks later in the body render inline.+No format flag says "this is a header" — the position does — so an older build+shows the same information in the same order, just stacked.++**What this buys the day collaboration lands.** Nothing needs doing. The CRDT+syncs pages and blocks; properties ARE blocks, so per-field last-writer-wins+falls out of the existing per-(node,key) registers, and two people changing+status and assignee at the same time both win. Had properties been one object+on the page, that would have been one register and one of the two edits would+have been lost silently — which is the measured reason the ruling exists.++**Deliberately NOT in this format.** No teams (a file IS the team boundary), no+per-user permissions (the file is the capability, per PLATFORM §5), no+notifications, no server-side automation. Those are Buzz's problem shape — a+relay, signed events, agents as members — and Buzz is a Rust service with+Postgres behind it. The thing Bento can do that neither Linear nor Buzz can is+hand you the whole tracker as one file that opens offline, forever, with no+account. That is the feature, and it is the reason the format has to stay+small enough to keep that promise.++## 2026-08-05 — The tracker's agent surface: written, warned about, never refused++**Decision.** `window.bento` gains `fields()`, `issues(query?)`,+`setField(pageId, key, value)` and `newIssue({title, ...fields})`, and+`validate()` learns about fields. Three shapes are settled here because they are+an API other work will be built on.++**1. A value this build does not know is WRITTEN, and warned about — never+refused.** The format is permanent and additive: a status a newer build declared+has to round-trip through an older one, and a verb that refused it would make+the older build unable to edit a document the newer one wrote. But an agent+typing `'In progress'` where the option id is `'doing'` has made a mistake and+silence would leave it confident, so the result carries+`warning: {code:'unknown-option', options:[…]}` and `validate()` reports+`unknown-field-value` at **info**. Refuse the shapes JSON cannot carry, warn+about the vocabulary. The same reasoning makes `unknown-field-key` info, and+`prop-html-stale` a warning — but that check STANDS DOWN when the value names no+known option, because then the writer knew a label this build does not and its+`html` is right where ours would be a guess.++**2. An unknown key in an ARGUMENT is a typo, not additivity.** `newIssue` and+`setField` refuse a key that is in no schema (`err: 'no-such-field'`). Unknown+keys in a *document* are how a future build's data survives; unknown keys in a+*call* are how an agent believes it set a priority it did not set.++**3. "Open" means NOT FINISHED.** `issues({group:'open'})` is one predicate —+not `done`, not `cancelled` — so a status with no phase and a status this build+has never heard of both count as work, and a status naming no option reports+`group:'unknown'` rather than being folded in with the rest. An issue wrongly+shown in a backlog costs a glance; an issue wrongly hidden from one costs the+issue.++`setField` is the ONLY supported way to write a value, because it writes `value`+and `html` together through fields.ts `propHtml()` — the same call the editor's+own field picker makes, so the two cannot drift. Guarded by+`scripts/test-spaces-agent.ts`; guide in `docs/spaces-agents.md`.+## 2026-08-03 — bento/spaces: the format decisions that must precede parallel workFive independent design reviews of bento/spaces proposed overlapping featurediff --git a/docs/spaces-agents.md b/docs/spaces-agents.mdindex db830898..0f22ff45 100644--- a/docs/spaces-agents.md+++ b/docs/spaces-agents.md@@ -77,6 +77,8 @@ unique ids the first time.| `divider` | — | `<hr>` || `image` | `src` (see below), `alt`, `caption`, `width` (10–100 **%**), `w`/`h` (intrinsic px) | `<figure>` || `pagelink` | `page` | a card linking to another page |+| `prop` | `key`, `value`, `html` | one field value — see **The issue tracker** |+| `view` | `layout`, `groupBy`, `html` | a board or list of this space's issues |`type` is a **string**, not a closed set: an unknown type survives a round tripand renders its `html` as a fallback. Properties are **flat on the block** —@@ -177,6 +179,72 @@ Links are same-document fragments:`href` must match `^(https?:|mailto:|#p/)`. Anything else is stripped.+## The issue tracker++**An issue is a page.** There is no issue type and no flag: a page carrying a+`status` field is an issue, and a page that loses its status is a document again+with everything else about it intact.++**A field VALUE is a `prop` block** on that page. **The SCHEMA is+document-level** — `doc.fields`, absent means the built-in seven.++```jsonc+{+ "fields": [ // document-level, optional+ { "key": "status", "label": "Status", "vt": "select", "def": "todo",+ "options": [+ { "id": "backlog", "label": "Backlog", "color": "#8B95A5", "group": "unstarted" },+ { "id": "todo", "label": "Todo", "color": "#5B8DEF", "group": "unstarted" },+ { "id": "doing", "label": "In progress", "color": "#F7A600", "group": "started" },+ { "id": "review", "label": "In review", "color": "#A97BE0", "group": "started" },+ { "id": "done", "label": "Done", "color": "#2FA37C", "group": "done" },+ { "id": "cancelled", "label": "Cancelled", "color": "#98A2B3", "group": "cancelled" }+ ] },+ { "key": "priority", "label": "Priority", "vt": "select", "def": "none",+ "options": [ { "id": "urgent", "label": "Urgent" }, { "id": "high", "label": "High" },+ { "id": "medium", "label": "Medium" }, { "id": "low", "label": "Low" },+ { "id": "none", "label": "No priority" } ] }, // every option needs a label+ { "key": "assignee", "label": "Assignee", "vt": "person" },+ { "key": "estimate", "label": "Estimate", "vt": "number" },+ { "key": "labels", "label": "Labels", "vt": "labels" },+ { "key": "due", "label": "Due", "vt": "date" },+ { "key": "project", "label": "Project", "vt": "text" }+ ],+ "pages": [{ "id": "i-42", "title": "Search drops a keystroke", "blocks": [+ { "id": "b1", "type": "prop", "key": "status", "value": "doing", "html": "Status: In progress" },+ { "id": "b2", "type": "prop", "key": "assignee", "value": "ana", "html": "Assignee: ana" },+ { "id": "b3", "type": "p", "html": "Only on iOS, and only when typing fast." }+ ] }]+}+```++**`value` is the option `id`; `html` is the readable form, and you write BOTH.**+`html` is what an older build, a file-manager thumbnail, a `grep` and the+markdown export see, and it is *all* they see — a value written without it is+invisible to every one of them. The form is exactly `<Label>: <shown>`, where+`shown` is the option's **label** for a select, the values joined by `, ` for+`labels`, the value as text otherwise, and `—` when it is unset. Use+`bento.setField()` and this is not something you can get wrong; hand-editing the+file, it is the thing to get right. `bento.validate()` reports a mismatch as+`prop-html-stale`.++**Fields render as a header strip by POSITION**: the `prop` blocks *before* the+first non-prop block are drawn as one row under the title. There is no flag —+put them first.++**Unknown values and unknown keys are kept, never corrected.** A status this+build cannot name is shown verbatim and grouped as `unknown`; a field key that+is in no schema keeps rendering its own `html`. That is how a document written+by a newer build survives an older one, so never "fix" one by blanking it.++A board or list is a `view` block, and it stores a **query, never a membership+list**: `{ "type": "view", "layout": "board", "groupBy": "status",+"html": "Issues by status" }`. Put it on a page of its own — a page carrying a+view is laid out wide.++**Not in this format, deliberately**: teams, per-user permissions,+notifications, automation. The file is the team boundary and the capability.+## What makes a space good rather than merely correct| When the material is… | Reach for | Why |@@ -207,6 +275,12 @@ bento.validate() // what is wrong or suspectbento.stats() // pages, blocks, words, bytes, biggest assets// write — each one is ONE undoable step+bento.fields() // the field schema in force+bento.issues(query?) // the backlog, as data++// write — each one is ONE undoable step+bento.setField(pageId, key, value) // → {ok:true, …, warning?} | {ok:false, err}+bento.newIssue({title, ...fields}) // → {ok:true, id, blocks, warnings?}bento.newPage(title, parent?) // → new page id, or nullbento.insertBlocks(pageId, afterId, [...]) // → new block ids, or nullbento.updateBlock(id, patch) // → {ok:true, id, page} | {ok:false, err}@@ -233,7 +307,8 @@ empty step for someone to undo.The verbs added after 0.1.0 return `{ok: true, …}` or `{ok: false, err, detail}`rather than `null`. `err` is one of `readonly`, `no-such-block`, `no-such-page`,-`bad-patch`, `immutable`, `not-serializable`, `cycle`, `last-page`.+`no-such-field`, `bad-patch`, `immutable`, `not-serializable`, `cycle`,+`last-page`.`insertBlocks` and `newPage` keep their original shapes (ids, or `null`),because files and scripts already depend on them.@@ -257,6 +332,14 @@ markup inside inline `html` (and markup that is dropped whole), hrefs outside thallowlist, images with no `alt`, no size, a missing `asset:` or a remote `src`,a `home` naming nothing, pages with no blocks, and assets nothing references.+On the tracker it adds: `prop-html-stale` (a value whose readable `html` says+something else — the check worth running after any hand edit),+`unknown-field-value` and `unknown-field-key` (**info**, because that is how a+newer build's data arrives — the value is kept), `duplicate-prop` (two values+for one field on one page; a reader takes the last), `prop-no-key`, and+`bad-field-schema` for a `doc.fields` entry with no string `key` and `label`,+which is an **error**: writing a value for that field throws.+`ok` means no **errors**; warnings and info do not make a document invalid.Severity is meant literally, so that a clean document is silent: **`validate()`reports nothing at all on the space a fresh file opens with**, and the rig@@ -347,6 +430,92 @@ By default the pages inside it move up a level rather than disappearing with it;`{descendants: true}` takes the subtree. `links` in the result counts theinbound links that just went dead. Removing every page is refused.+### The tracker verbs, exactly++```js+bento.fields()+// [{ key: 'status', label: 'Status', vt: 'select', def: 'todo',+// options: [{ id: 'todo', label: 'Todo', color: '#5B8DEF', group: 'unstarted' }, …] },+// { key: 'assignee', label: 'Assignee', vt: 'person' }, …]+```+Call this **first**. A value is set by option **id**, and the ids are not the+labels: `doing`, not `In progress`. The schema is the document's own+(`doc.fields`), so a space may declare fields these defaults never had.++```js+bento.setField(pageId, key, value)+// {ok:true, pageId, key, value, html, blocks:[id], created, removed, warning?}+```+Writes `value` **and** its readable `html` together, which is the only reason+this verb exists: write a `prop` block yourself through `insertBlocks` and you+will eventually get that pairing wrong, and then the file says one thing to this+build and another to every older build, every thumbnailer, every grep and the+markdown export — silently, forever.++The page need not be an issue: **setting `status` is what makes it one.** A+value for a field the page does not carry yet is created in the header strip+(`created: true`). `null` **clears** the field, block and all — clear the status+and the page is an ordinary document again, body intact.++It refuses `no-such-page`, `no-such-field` (the key is in no schema) and+`not-serializable`, and returns `err: 'readonly'` on a locked file. A value that+is not one of a select's options is **written, not refused** — the format is+permanent and additive, so a status a newer build declared has to survive this+one — but it comes back with `warning: {code:'unknown-option', options:[…]}`.+If you see that warning and you did not mean it, you typed a label where an id+belongs.++```js+bento.issues({ where, group, archived })+// [{ id, title, url:'#p/<id>', archived?, group, fields:{status, priority, …} }]+```+`where` is field equality: a value, an array for any-of, or `null` for **not+set** (which covers both an absent field and an empty one). `group` is the+status **phase** — `unstarted` `started` `done` `cancelled`, plus `unknown` for a+status no option declares, and **`open`, which means "not finished"** and is the+one you want. Archived issues are excluded unless you ask for them.++```js+bento.newIssue({ title, ...fieldValues }) // → {ok:true, id, blocks, warnings?}+```+One page, one undoable step, every value written through the same path. `title`+and `parent` are the page's; every other key is a **field key**, and one that is+not in the schema is refused rather than parked on the page (an unknown key in+an argument is a typo, not additivity). It does not navigate — make twenty and+the person's cursor stays where it was.++### Triage, worked++```js+const ids = new Set(bento.fields().find(f => f.key === 'status').options.map(o => o.id))+// → {'backlog','todo','doing','review','done','cancelled'}++// everything open and unassigned, oldest first in page order+const inbox = bento.issues({ group: 'open', where: { assignee: null } })++for (const it of inbox) {+ const body = bento.getPage(it.id).blocks.map(b => b.html).join(' ')+ if (/crash|data loss/i.test(body)) {+ bento.setField(it.id, 'priority', 'urgent') // an id, never 'Urgent'+ bento.setField(it.id, 'assignee', 'ana')+ }+}++// a new one, complete, in one call+const { id } = bento.newIssue({+ title: 'Search drops the last keystroke on iOS',+ status: 'todo', priority: 'high', estimate: 2,+})+bento.insertBlocks(id, null, [{ type: 'p', html: 'Steps: type fast in ⌘K…' }])++bento.validate().findings.filter(f => f.code.startsWith('prop-') || f.code.includes('field'))+```++Every `setField` and `newIssue` is its own undo step, so a person watching can+take back exactly the one they disagree with. Check the `warning`/`warnings` on+what comes back before you move on: they are how you find out you set something+nothing will ever group.+### What you may writeEverything an agent writes goes through the same sanitizer the editor uses, ondiff --git a/scripts/size-budgets.json b/scripts/size-budgets.jsonindex f5747b06..076ae0c4 100644--- a/scripts/size-budgets.json+++ b/scripts/size-budgets.json@@ -3,8 +3,8 @@"shells": {"spaces": {"path": "spaces/dist-single/Bento_Spaces.bento.html",- "max": 120832,- "//": "118 KiB. Raised from 114 KiB at 117218 B on 2026-08-05 for the static first-page preview (spaces/src/preview.ts): without it a saved space showed the boot splash to every reader that runs no script — QuickLook, iOS Files, Bento Tray. Reported from the field. The preview itself is per-SAVE and separately budgeted at 64KB."+ "max": 135168,+ "//": "132 KiB. The tracker took spaces from 73 KB. Headroom is deliberate: the shell is mostly a zlib block and zlib differs across node versions \u2014 the same commit measured 130,095 B on node 26 locally and 131,246 B on CI node 24, so a tight ceiling fails in CI for no reason. CI is the number that counts."}}}diff --git a/scripts/test-spaces-agent.ts b/scripts/test-spaces-agent.tsindex c5021cd0..5504048d 100644--- a/scripts/test-spaces-agent.ts+++ b/scripts/test-spaces-agent.ts@@ -39,7 +39,9 @@ import {validateDoc, outlineDoc, statsDoc,planInsertBlocks, planUpdateBlock, planRemoveBlocks, planMoveBlock,planUpdatePage, planRemovePage,+ fieldsReport, issuesReport, planSetField, planNewIssue,} from '../spaces/src/agent.ts'+import { DEFAULT_FIELDS, ISSUE_FIELDS, propHtml, isIssue, valuesOf, columnMoves } from '../spaces/src/fields.ts'let checks = 0let failures = 0@@ -250,5 +252,437 @@ console.log('bento/spaces agent surface\n')ok(typeof s.todos.total === 'number', 'stats reports to-do progress')}+// ===========================================================================+// THE TRACKER: an issue is a page, its values are prop blocks+// ===========================================================================+//+// The permanent risk in this half is not a crash — it is a value that says one+// thing to this build and another to everything else that will ever read the+// file. `html` is what an older build, a thumbnailer, a grep and the markdown+// export see, and it is ALL they see, so every assertion below that looks+// cosmetic is really about that.++/** An issue page, written the way the editor writes one. */+const issue = (id: string, values: Record<string, unknown>, extra: Record<string, unknown> = {}) => ({+ id, title: id,+ blocks: [+ ...Object.entries(values).map(([k, v], i) => {+ const f = DEFAULT_FIELDS.find((x) => x.key === k)!+ return { id: `${id}-${i}`, type: 'prop', key: k, value: v, html: propHtml(f, v) }+ }),+ { id: `${id}-body`, type: 'p', html: 'the body' },+ ],+ ...extra,+})++// ---- validate() stays SILENT on tracker documents that are correct ---------+{+ const clean = load([+ issue('i1', { status: 'todo', priority: 'high', assignee: 'ana', estimate: 3 }),+ issue('i2', { status: 'done', priority: 'none', assignee: '', estimate: '' }),+ p('board', [{ id: 'v1', type: 'view', layout: 'board', groupBy: 'status', html: 'Issues by status' }]),+ ])+ const v = validateDoc(clean)+ ok(v.findings.length === 0,+ `a correct tracker raises nothing (${v.findings.map((f) => `${f.code}@${f.block}`).join(', ') || 'silent'})`)++ // A SELECT WITH NO DEFAULT. `makeIssue` writes `f.def ?? ''`, so an empty+ // select is a document THIS BUILD produced — flagging it would be a false+ // positive on the editor's own output.+ const nodef = load([{+ id: 'i1', title: 'i1',+ blocks: [{ id: 'b1', type: 'prop', key: 'phase', value: '', html: 'Phase: —' },+ { id: 'b2', type: 'prop', key: 'status', value: 'todo', html: 'Status: Todo' }],+ }], { fields: [...DEFAULT_FIELDS, { key: 'phase', label: 'Phase', vt: 'select', options: [{ id: 'a', label: 'A' }] }] })+ ok(!validateDoc(nodef).findings.some((f) => f.code === 'unknown-field-value'),+ 'an empty select is "not set", not an unknown option')++ // A VALUE FROM A NEWER BUILD, with the label that build knew. Its html is+ // RIGHT and ours would be the guess, so the staleness check must stand down.+ const newer = load([{+ id: 'i1', title: 'i1',+ blocks: [{ id: 'b1', type: 'prop', key: 'status', value: 'blocked', html: 'Status: Blocked' }],+ }])+ const nf = validateDoc(newer).findings+ ok(!nf.some((f) => f.code === 'prop-html-stale'),+ 'an unknown option\'s readable form is not reported stale — the newer build knew the label')+ ok(nf.some((f) => f.code === 'unknown-field-value' && f.severity === 'info'),+ 'an unknown option is INFO — the format keeps what a newer build wrote')+ ok(!nf.some((f) => f.severity === 'error'), 'and a newer build\'s value is never an error')++ // A field key this schema does not declare: the same story, one level up.+ const extraKey = load([{+ id: 'i1', title: 'i1',+ blocks: [{ id: 'b1', type: 'prop', key: 'status', value: 'todo', html: 'Status: Todo' },+ { id: 'b2', type: 'prop', key: 'sprint', value: '24', html: 'Sprint: 24' }],+ }])+ const ef = validateDoc(extraKey).findings+ ok(ef.length === 1 && ef[0].code === 'unknown-field-key' && ef[0].severity === 'info',+ `a field key from a newer build is one INFO and nothing else (${ef.map((f) => f.code).join(', ')})`)+}++// ---- …and names the ways a field value goes silently wrong -----------------+{+ const broken = load([+ // html that disagrees with the value: the degradation guarantee, broken+ { id: 'i1', title: 'i1', blocks: [+ { id: 'b1', type: 'prop', key: 'status', value: 'done', html: 'Status: In progress' },+ { id: 'b2', type: 'p', html: 'body' },+ ] },+ // two values for one field, and a prop naming no field at all+ { id: 'i2', title: 'i2', blocks: [+ { id: 'b3', type: 'prop', key: 'status', value: 'todo', html: 'Status: Todo' },+ { id: 'b4', type: 'prop', key: 'status', value: 'done', html: 'Status: Done' },+ { id: 'b5', type: 'prop', value: 'orphan', html: 'x' },+ ] },+ ])+ const codes = new Map(validateDoc(broken).findings.map((f) => [f.code, f]))+ for (const want of ['prop-html-stale', 'duplicate-prop', 'prop-no-key']) {+ ok(codes.has(want), `reports ${want} (got: ${[...codes.keys()].join(', ')})`)+ }+ ok(codes.get('prop-html-stale')?.block === 'b1' && codes.get('prop-html-stale')?.path === 'html',+ 'a stale readable form names the block and the field it is in')+ ok([...codes.values()].every((f) => !!f.message && !!f.fix), 'every tracker finding says what to do')++ // a schema entry that cannot be used: propHtml THROWS on it, so the editor's+ // field picker dies on click — an error, not a note+ const badSchema = load([p('p1', [b('b1')])], { fields: [{ key: 'status' }, { label: 'no key', vt: 'text' }] })+ const bs = validateDoc(badSchema).findings.filter((f) => f.code === 'bad-field-schema')+ ok(bs.length === 2 && bs.every((f) => f.severity === 'error'),+ `a malformed doc.fields entry is an error (${bs.length} found)`)+}++// ---- fields(): the schema, as data an agent can act on ---------------------+{+ const doc = load([p('p1', [b('b1')])])+ const fields = fieldsReport(doc)+ const status = fields.find((f) => f.key === 'status')!+ ok(status.options?.some((o) => o.id === 'doing' && o.label === 'In progress'),+ 'fields() carries the option IDS, which are not the labels')+ ok(status.options?.some((o) => o.group === 'started'),+ 'fields() carries the phase group, so "open" needs no filter to be configured')++ // The default schema is MODULE STATE shared by every document in the+ // session: handing it out live means one agent's push() edits the schema of+ // documents that have not been loaded yet.+ fields[0].options!.length = 0+ ok(fieldsReport(doc).find((f) => f.key === 'status')!.options!.length === 6,+ 'fields() hands back a copy — mutating it cannot corrupt the default schema')+}++// ---- setField(): value and html, together, always -------------------------+{+ const doc = load([issue('i1', { status: 'todo', assignee: '' }), p('plain', [b('b1')])])+ const r = apply(planSetField(doc, 'i1', 'status', 'doing'))+ const blk = doc.pages[0].blocks[0] as Record<string, unknown>+ ok(r.ok && blk.value === 'doing' && blk.html === 'Status: In progress',+ `setField writes the readable form with the value (${String(blk.html)})`)+ ok(r.html === blk.html && r.blocks[0] === blk.id, 'and reports exactly what it wrote')++ // a value for a field the page does not carry yet joins the HEADER STRIP —+ // prop blocks before the first non-prop block — not the end of the prose+ const r2 = apply(planSetField(doc, 'i1', 'due', '2026-09-01'))+ const types = doc.pages[0].blocks.map((x) => x.type)+ ok(r2.created === true && types.join(',') === 'prop,prop,prop,p',+ `a new value joins the header strip (${types.join(',')})`)+ ok((doc.pages[0].blocks[2] as Record<string, unknown>).html === 'Due: 2026-09-01',+ 'and it is created with its readable form, not without one')++ // a page becomes an issue by carrying a status; nothing else changes+ ok(!isIssue(doc.pages[1] as never), 'a plain page is not an issue')+ apply(planSetField(doc, 'plain', 'status', 'backlog'))+ ok(isIssue(doc.pages[1] as never) && doc.pages[1].blocks.length === 2,+ 'setField(status) is what makes a page an issue — no flag, no type')++ // …and clearing it makes it a document again, body intact+ const cleared = apply(planSetField(doc, 'plain', 'status', null))+ ok(cleared.removed === true && !isIssue(doc.pages[1] as never) && doc.pages[1].blocks.length === 1,+ 'clearing the status makes it a page again, with its body')+ ok(apply(planSetField(doc, 'plain', 'status', null)).ok === true,+ 'clearing a field that is not set is not an error — the call is idempotent')++ // while a duplicate exists, BOTH are written: a reader takes the last, so+ // writing one of them would be a set that changes nothing anyone can see+ const dup = load([{ id: 'i1', title: 'i1', blocks: [+ { id: 'b1', type: 'prop', key: 'status', value: 'todo', html: 'Status: Todo' },+ { id: 'b2', type: 'prop', key: 'status', value: 'todo', html: 'Status: Todo' },+ ] }])+ apply(planSetField(dup, 'i1', 'status', 'done'))+ ok(dup.pages[0].blocks.every((x) => (x as Record<string, unknown>).value === 'done'),+ 'a duplicated field is written in every copy, so the page cannot disagree with itself')+}++// ---- setField(): what it refuses, and what it deliberately allows ----------+{+ const doc = load([issue('i1', { status: 'todo' })])+ const refusals: Array<[string, string, { ok: boolean; err?: string }]> = [+ ['a page that does not exist', 'no-such-page', planSetField(doc, 'nope', 'status', 'todo') as never],+ ['a key that is in no schema', 'no-such-field', planSetField(doc, 'i1', 'staus', 'todo') as never],+ ['a value JSON cannot carry', 'not-serializable', planSetField(doc, 'i1', 'assignee', () => 1) as never],+ ]+ for (const [label, err, plan] of refusals) {+ ok(plan.ok === false && plan.err === err, `setField refuses ${label} with err:${err} (got ${plan.err})`)+ }+ const why = planSetField(doc, 'i1', 'staus', 'todo') as { detail?: string }+ ok(!!why.detail && why.detail.includes('status'),+ 'and the refusal names the keys that DO exist, so the caller can correct itself')++ // A VALUE THIS BUILD DOES NOT KNOW IS WRITTEN, NOT REFUSED. The format is+ // permanent: an option a newer build declared has to survive this one. But+ // an agent typing the LABEL where the id belongs must be told, or it is+ // wrong and confident.+ const w = apply(planSetField(doc, 'i1', 'status', 'In progress')) as {+ ok: boolean; warning?: { code: string; options: string[]; detail: string }+ }+ ok(w.ok === true && (doc.pages[0].blocks[0] as Record<string, unknown>).value === 'In progress',+ 'an unknown option is written verbatim — the format keeps what it is given')+ ok(w.warning?.code === 'unknown-option' && w.warning.options.includes('doing'),+ 'and comes back with a warning naming the ids that exist')+ ok(!apply(planSetField(doc, 'i1', 'status', 'doing')).warning,+ 'a known option warns about nothing')+ ok(!apply(planSetField(doc, 'i1', 'assignee', 'In progress')).warning,+ 'and a free-text field has no options to be wrong about')+ // "not set" is not a wrong option. `makeIssue` writes '' for a select with+ // no default, so warning here would fire on the editor's own output.+ ok(!apply(planSetField(doc, 'i1', 'status', '')).warning,+ 'clearing a select to "not set" warns about nothing')+}++// ---- a value from a NEWER build survives a round trip untouched ------------+// The whole degradation contract in one assertion: this build must be able to+// open, read, filter and edit a document written by a build that knew more+// than it does, and give back every byte it did not itself change.+{+ const original = {+ format: FORMAT, version: 1, docId: 'rt', title: 'Round trip', home: 'i1',+ theme: { background: '#fff', color: '#1E2A3A', accent: '#F7A600', measure: 720 },+ fields: [+ { key: 'status', label: 'Status', vt: 'select', def: 'todo', options: [+ ...DEFAULT_FIELDS[0].options!,+ { id: 'blocked', label: 'Blocked', color: '#E5484D', group: 'started', escalation: 'page-the-owner' },+ ] },+ { key: 'assignee', label: 'Assignee', vt: 'person' },+ { key: 'squad', label: 'Squad', vt: 'text' },+ ],+ pages: [{ id: 'i1', title: 'A newer issue', blocks: [+ { id: 'b1', type: 'prop', key: 'status', value: 'blocked', html: 'Status: Blocked', pinned: true },+ { id: 'b2', type: 'prop', key: 'squad', value: 'platform', html: 'Squad: platform' },+ { id: 'b3', type: 'p', html: 'body' },+ ] }],+ }+ const r = parseDoc(JSON.stringify(original))+ if (!r.ok) throw new Error('the newer-build fixture did not parse')+ const doc = r.doc++ ok(JSON.stringify(doc.pages) === JSON.stringify(original.pages),+ 'a page written by a newer build loads byte-identical')+ ok(validateDoc(doc).ok, 'and raises no errors')++ const rows = issuesReport(doc, { group: 'open' })+ ok(rows.length === 1 && rows[0].group === 'started',+ 'a status this build could not have written is still grouped by the schema the FILE declares')++ // editing a DIFFERENT field must not rewrite the one it does not understand+ apply(planSetField(doc, 'i1', 'assignee', 'ana'))+ ok(JSON.stringify(doc.pages[0].blocks[0]) === JSON.stringify(original.pages[0].blocks[0]),+ 'setField on another field leaves the newer build\'s block untouched, extra keys and all')+ ok((doc.pages[0].blocks[1] as Record<string, unknown>).value === 'platform',+ '…and the field this build has no editor for keeps its value')++ // and writing the SAME field keeps the file's own vocabulary+ apply(planSetField(doc, 'i1', 'status', 'blocked'))+ ok((doc.pages[0].blocks[0] as Record<string, unknown>).html === 'Status: Blocked',+ 'writing a value declared only by the FILE uses the file\'s label')+}++// ---- issues(): the backlog, in one call -----------------------------------+{+ const doc = load([+ issue('i1', { status: 'todo', priority: 'high', assignee: '', estimate: 2 }),+ issue('i2', { status: 'doing', priority: 'low', assignee: 'ana', estimate: 3 }),+ issue('i3', { status: 'done', priority: 'none', assignee: 'sam', estimate: 1 }),+ issue('i4', { status: 'cancelled', priority: 'none', assignee: '' }),+ issue('i5', { status: 'off-world', priority: 'urgent', assignee: '' }),+ issue('old', { status: 'todo' }, { archived: true }),+ p('doc1', [b('b1')]),+ ])+ const all = issuesReport(doc)+ ok(all.length === 5, `issues() returns the issues and not the documents (${all.length})`)+ ok(all[0].id === 'i1' && all[0].url === '#p/i1' && all[0].title === 'i1',+ 'each row carries the page id, its title and the href a link would use')+ ok(all[0].fields.priority === 'high' && all[0].fields.estimate === 2,+ 'every field value comes back, by key')+ ok(!all.some((x) => x.archived), 'archived issues are out by default')+ ok(issuesReport(doc, { archived: true }).length === 6 &&+ issuesReport(doc, { archived: true }).some((x) => x.archived === true),+ 'and are asked for explicitly, and say so')++ ok(all.find((x) => x.id === 'i2')!.group === 'started', 'a row reports the PHASE of its status')+ ok(all.find((x) => x.id === 'i5')!.group === 'unknown',+ 'a status this build does not know reports "unknown", never a phase it guessed')++ const open = issuesReport(doc, { group: 'open' }).map((x) => x.id)+ ok(open.join(',') === 'i1,i2,i5',+ `"open" means NOT FINISHED, so an unknown status counts as work (${open.join(',')})`)+ ok(issuesReport(doc, { group: 'done' }).map((x) => x.id).join(',') === 'i3',+ 'and a finished phase is asked for by name')+ ok(issuesReport(doc, { group: ['unstarted', 'unknown'] }).map((x) => x.id).join(',') === 'i1,i5',+ 'phases can be asked for together')++ // the call the whole thing exists for+ const triage = issuesReport(doc, { group: 'open', where: { assignee: null } }).map((x) => x.id)+ ok(triage.join(',') === 'i1,i5', `"open and unassigned" is one call (${triage.join(',')})`)+ ok(issuesReport(doc, { where: { status: ['todo', 'doing'] } }).map((x) => x.id).join(',') === 'i1,i2',+ 'a filter takes a list for any-of')+ ok(issuesReport(doc, { where: { estimate: '3' } }).map((x) => x.id).join(',') === 'i2',+ 'and compares as text, so 3 and "3" are the same estimate')+ ok(issuesReport(doc, { where: { assignee: 'nobody' } }).length === 0, 'a filter that matches nothing is empty')+}++// ---- newIssue(): one step, fields through the same path -------------------+{+ const doc = load([p('home', [b('b1')])])+ const r = apply(planNewIssue(doc, { title: 'Login is slow', priority: 'urgent', assignee: 'ana' })) as+ { ok: boolean; id: string; blocks: string[] }+ ok(r.ok && doc.pages.length === 2, 'newIssue adds one page')+ const page = doc.pages[1]+ const values = valuesOf(page as never)+ ok(page.title === 'Login is slow', 'with the title it was given')+ ok(isIssue(page as never) && values.get('status') === 'todo',+ 'an issue, from the schema\'s own default status')+ ok(values.get('priority') === 'urgent' && values.get('assignee') === 'ana',+ 'carrying the values it was given')+ // SPELLED OUT, not `ISSUE_FIELDS.every(...)`: asserting the list against+ // itself passes however the list is edited, which is not a test of anything.+ // These four are what ⌘⇧I seeds, and a `prop` cannot be added from the /+ // menu — a field missing here is a field a human cannot then set at all.+ ok(['status', 'priority', 'assignee', 'estimate'].every((k) => values.has(k)),+ `and every field a ⌘⇧I issue starts with (${[...values.keys()].join(', ')})`)+ ok(ISSUE_FIELDS.join(',') === 'status,priority,assignee,estimate',+ 'the shared seed list is those four')+ ok(page.blocks.every((x) => x.type !== 'prop' || x.html === propHtml(+ DEFAULT_FIELDS.find((f) => f.key === (x as Record<string, unknown>).key)!,+ (x as Record<string, unknown>).value)),+ 'every value written with its readable form — the same path as setField')+ ok(page.blocks[page.blocks.length - 1].type === 'p',+ 'and it ends in a paragraph: a page of nothing but props has nowhere to put the caret')+ ok(validateDoc(doc).findings.length === 0, 'the issue it produces is one validate() is silent about')++ // a typo in an ARGUMENT is a mistake, not additivity: refusing it is the+ // difference between an agent that knows it failed and one that does not+ const typo = planNewIssue(doc, { title: 'x', prioritty: 'urgent' }) as { ok: boolean; err?: string }+ ok(typo.ok === false && typo.err === 'no-such-field', 'newIssue refuses a field key that is in no schema')+ ok(doc.pages.length === 2, '…and a refused call adds no page at all')+ ok((planNewIssue(doc, { title: 'x', parent: 'ghost' }) as { err?: string }).err === 'no-such-page',+ 'and refuses a parent that does not exist')++ const w = apply(planNewIssue(doc, { title: 'y', status: 'In progress' })) as+ { warnings?: Array<{ code: string; key: string }> }+ ok(w.warnings?.[0]?.code === 'unknown-option' && w.warnings[0].key === 'status',+ 'a label typed where an option id belongs is written, and reported')++ const bare = apply(planNewIssue(doc, undefined)) as { ok: boolean; id: string }+ ok(bare.ok && doc.pages.find((x) => x.id === bare.id)?.title === 'New issue',+ 'newIssue with no argument is still a complete issue')+}++// ---- the tracker verbs go through the same undo/read-only gate -------------+// planSetField and planNewIssue are refused for a read-only document by+// main.ts's run(), which is also what takes the undo checkpoint. Calling a+// plan's apply() directly would bypass both — and nothing else in this rig+// would notice, because the plans themselves are correct.+{+ const fs = await import('node:fs')+ const main = fs.readFileSync(new URL('../spaces/src/main.ts', import.meta.url), 'utf8')+ for (const verb of ['planSetField', 'planNewIssue']) {+ ok(new RegExp(`run\\(${verb}\\(`).test(main),+ `${verb} is wired through run(), so read-only refuses it and undo records it`)+ }+ ok(/fields: \(\) => fieldsReport|issues: \(query/.test(main), 'fields() and issues() are on window.bento')++ // …and the editor seeds a new issue from the SAME list this does, or ⌘⇧I and+ // bento.newIssue() make two different kinds of issue.+ const editor = fs.readFileSync(new URL('../spaces/src/editor.ts', import.meta.url), 'utf8')+ ok(/ISSUE_FIELDS\.includes\(f\.key\)/.test(editor) &&+ !/'status', 'priority', 'assignee', 'estimate'/.test(editor),+ 'the editor seeds a new issue from the shared list, not a second copy of it')+}++// ---- five defects a review reproduced in the tracker ----------------------+{+ // 1. THE DEGRADATION GUARANTEE, enforced rather than claimed. setField kept+ // value and html in step; updateBlock and insertBlocks did not — measured,+ // updateBlock({value:'doing'}) left html:'Status: Todo', so the file SAID+ // Todo to every older build, thumbnailer, grep and markdown export while+ // its value said doing. A guarantee one writer keeps and three break is+ // not a guarantee, so it moved to where blocks are WRITTEN.+ const d = load([p('p1', [{ id: 'ps', type: 'prop', key: 'status', value: 'todo', html: 'Status: Todo' }])])+ apply(planUpdateBlock(d, 'ps', { value: 'doing' }))+ ok((d.pages[0].blocks[0] as { html?: string }).html === 'Status: In progress',+ 'updateBlock re-derives the readable form from the new value')++ apply(planInsertBlocks(d, 'p1', 'ps', [{ type: 'prop', key: 'priority', value: 'urgent' }]))+ ok((d.pages[0].blocks[1] as { html?: string }).html === 'Priority: Urgent',+ 'insertBlocks writes a readable form for a field it was given without one')++ apply(planInsertBlocks(d, 'p1', null, [{ type: 'prop', key: 'from-the-future', value: 'x', html: 'From the future: x' }]))+ const last = d.pages[0].blocks[d.pages[0].blocks.length - 1] as { html?: string }+ ok(last.html === 'From the future: x',+ '…and leaves a key it does not know exactly as a newer build wrote it')++ // 2. A malformed schema entry must not CRASH a write verb. It comes out of a+ // file, validate() reports it, and every other bad input is a tagged+ // refusal — this one threw a TypeError out of the public API.+ for (const [name, spec] of [+ ['no label', { key: 'owner', vt: 'text' }],+ ['a numeric label', { key: 'o', label: 42, vt: 'text' }],+ ['neither', { vt: 'text' }],+ ] as Array<[string, unknown]>) {+ let threw: string | null = null+ let out = ''+ try { out = propHtml(spec as never, 'ana') } catch (e) { threw = (e as Error).message }+ ok(threw === null, `a schema entry with ${name} does not throw (${threw ?? out})`)+ }++ // 3. A new issue must BE an issue, or the verb reports a success nothing can+ // see: invisible to issues(), to every board, and to a follow-up setField.+ const noStatus = load([p('p1', [b('b1')])], { fields: [{ key: 'state', label: 'State', vt: 'text' }] })+ const made = planNewIssue(noStatus, { title: 'filed by an agent' }) as { ok: boolean; err?: string }+ ok(made.ok === false && made.err === 'no-status-field',+ `a space with no status field refuses to make an issue (${made.err ?? 'ok'})`)++ // 4. An UNSET status is not an UNKNOWN one — they want opposite handling:+ // "leave it alone" versus "this needs triaging".+ const mixed = load([+ p('a', [{ id: 'a1', type: 'prop', key: 'status', value: '', html: 'Status: —' }]),+ p('c', [{ id: 'c1', type: 'prop', key: 'status', value: 'from-a-newer-build', html: 'Status: from-a-newer-build' }]),+ ])+ const rows = issuesReport(mixed, {})+ ok(rows.find((r) => r.id === 'a')?.group === undefined, 'an unset status reports no group')+ ok(rows.find((r) => r.id === 'c')?.group === 'unknown', 'a status from a newer build reports "unknown"')+}++// ---- a drop that changes nothing must WRITE nothing ------------------------+// reorderPages judged adjacency in doc.pages, and page order is not column+// order: a board with two columns interleaves them. Measured on+// [board,i1,i2,i3,i4,i5] with i1,i3,i5 in one column — dropping i1 back into+// its own slot rewrote doc.pages, took an undo entry, set the dirty flag, and+// visibly reshuffled the SIDEBAR, because board order is sidebar order. The rig+// missed it because its fixture had ONE column, the only shape where the two+// orders agree.+{+ const col = ['i1', 'i3', 'i5']+ for (const [label, aim] of [+ ['before its own next card', { before: 'i3' }],+ ['after its own previous card', { after: 'i3' }],+ ['onto itself', { after: 'i1' }],+ ] as Array<[string, never]>) {+ const moved = label.includes('previous') ? 'i5' : 'i1'+ ok(!columnMoves(col, moved, aim), `dropping ${label} moves nothing`)+ }+ ok(columnMoves(col, 'i5', { before: 'i1' } as never), 'a real move is a move')+ ok(columnMoves(col, 'newcomer', { before: 'i3' } as never), 'a card from another column always moves')+}+console.log(`\n${checks - failures}/${checks} checks passed`)if (failures) process.exit(1)diff --git a/scripts/test-spaces-model.ts b/scripts/test-spaces-model.tsindex 222d9764..1c31c4ff 100644--- a/scripts/test-spaces-model.ts+++ b/scripts/test-spaces-model.ts@@ -31,6 +31,11 @@ import {type SpacesDoc,} from '../spaces/src/model.ts'import { countOutsideTags, replaceOutsideTags } from '../spaces/src/findreplace.ts'+import {+ DEFAULT_FIELDS, fieldsOf, fieldByKey, optionOf, propHtml, propBlock,+ valuesOf, isIssue, issuesOf, headerLength, propBlockOf,+ passesFilter, filterCount, unknownFilterKeys, phaseField, isOpenPhase, reorderPages,+} from '../spaces/src/fields.ts'import { inlineHtml, parseNote, planImport } from '../spaces/src/markdown.ts'import { planUpdatePage } from '../spaces/src/agent.ts'import { tokenize, normLang, langLabel, CODE_LANGS } from '../spaces/src/highlight.ts'@@ -38,7 +43,7 @@ import { escText } from '../spaces/src/sanitize.ts'import {SPECS, SPEC, MENU_SPECS, MD_SPECS, TAG_OF, LIST_OF, CALLOUT_TONES, mdLayout,} from '../spaces/src/blocks.ts'-import type { Block } from '../spaces/src/model.ts'+import type { Block, Page } from '../spaces/src/model.ts'let failures = 0let checks = 0@@ -446,7 +451,22 @@ for (const [label, input, err] of [todoInit?.(probe as never)ok(probe.done === false, 'the to-do trigger initialises done:false')- ok(MENU_SPECS.length === SPECS.length, 'every type is offered in the / menu')+ // Every type is in the / menu UNLESS it is deliberately unlisted — and an+ // unlisted type must have another way in, or it is a block nobody can make.+ // `prop` is unlisted because a field is created from the issue header, where+ // its value can be chosen; "Field" in a block list would insert a value you+ // then have to go elsewhere to set.+ const hidden = SPECS.filter((sp) => sp.unlisted).map((sp) => sp.type)+ ok(MENU_SPECS.length === SPECS.length - hidden.length,+ `the / menu offers every type except the deliberately unlisted (${hidden.join(', ') || 'none'})`)+ {+ const fsm = await import('node:fs')+ const ed2 = fsm.readFileSync(new URL('../spaces/src/editor.ts', import.meta.url), 'utf8')+ for (const h of hidden) {+ ok(new RegExp(`propBlock|newBlock\\('${h}'\\)`).test(ed2),+ `…and ${h} has another way in`)+ }+ }ok(SPEC.get('futuretype') === undefined, 'an unknown type has no spec — and must still render as text')ok(SPECS.filter((s) => s.type !== 'p').every((s) => !!s.toMd),'every type but plain text says how it exports to markdown')@@ -1103,5 +1123,218 @@ for (const [label, input, err] of ['deleting the last block leaves something to type into')}+// ---- an issue is a page, and its fields are blocks ------------------------+// The tracker format is PERMANENT. What has to hold forever:+// · a value is a BLOCK, so search, undo, export and the preview see it+// · the block carries a readable `html`, so a build that predates all of this+// shows "Status: In progress" instead of nothing+// · the SCHEMA is document-level and additive, so an old build ignores it+// · nothing a newer build writes is DROPPED — not an unknown option, not an+// unknown field key+{+ const status = fieldByKey({ } as never, 'status') ?? DEFAULT_FIELDS[0]++ // the schema is additive: absent means the defaults, not "no fields"+ ok(fieldsOf({} as never).length === DEFAULT_FIELDS.length,+ 'a document with no fields key gets the default schema')+ ok(fieldsOf({ fields: [{ key: 'k', label: 'K', vt: 'text' }] } as never).length === 1,+ '…and a document that declares its own schema keeps it')++ // the readable form is the degradation guarantee+ ok(propHtml(status, 'doing') === 'Status: In progress',+ `a value's readable form names the field and the label (${propHtml(status, 'doing')})`)+ ok(propHtml(status, '') === 'Status: —', 'an empty value still says which field it is')+ const unknownOpt = propHtml(status, 'shipped-to-space')+ ok(unknownOpt.includes('shipped-to-space'),+ `an option this build does not know is shown VERBATIM, never blanked (${unknownOpt})`)+ ok(!/[<>]/.test(propHtml({ key: 'x', label: '<b>L', vt: 'text' }, '<img>')),+ 'the readable form is escaped — it is html, and the value is author data')++ // the block itself+ const blk = propBlock(status, 'todo', 'b1') as Record<string, unknown>+ ok(blk.type === 'prop' && blk.key === 'status' && blk.value === 'todo',+ 'a field value is a prop BLOCK carrying key and value')+ ok(typeof blk.html === 'string' && (blk.html as string).length > 0,+ '…and always its readable form, in step with the value')++ // an issue is DERIVED, never flagged+ const doc = parseDoc(JSON.stringify({+ format: FORMAT, version: 1, docId: 'tk', title: 'T', home: 'p1',+ pages: [+ { id: 'p1', title: 'Board', blocks: [{ id: 'v', type: 'view', layout: 'board', groupBy: 'status', html: 'All' }] },+ { id: 'p2', title: 'An issue', blocks: [+ { id: 'ps', type: 'prop', key: 'status', value: 'doing', html: 'Status: In progress' },+ { id: 'pa', type: 'prop', key: 'assignee', value: 'sam', html: 'Assignee: sam' },+ { id: 'pb', type: 'p', html: 'the body' },+ ] },+ { id: 'p3', title: 'Just a page', blocks: [{ id: 'x', type: 'p', html: 'prose' }] },+ { id: 'p4', title: 'Archived issue', archived: true, blocks: [+ { id: 'qs', type: 'prop', key: 'status', value: 'todo', html: 'Status: Todo' },+ ] },+ ],+ }))+ ok(doc.ok, 'a tracker document loads')+ if (doc.ok) {+ const [board, issue, plain] = doc.doc.pages+ ok(isIssue(issue) && !isIssue(plain) && !isIssue(board),+ 'an issue is a page WITH A STATUS — not a page type, not a flag')+ ok(valuesOf(issue).get('assignee') === 'sam', 'a page reports its field values by key')+ ok(headerLength(issue) === 2, 'leading prop blocks are the header strip, by POSITION')+ ok(headerLength(plain) === 0, '…and a page with no fields has no header')++ const rows = issuesOf(doc.doc)+ ok(rows.length === 1, `issuesOf lists issues only (${rows.length})`)+ ok(!rows.some((r) => r.page.archived), 'and never an archived one')++ // format additivity, both directions+ const round = JSON.parse(JSON.stringify(doc.doc))+ const kept = round.pages[1].blocks[0]+ ok(kept.key === 'status' && kept.value === 'doing' && kept.html === 'Status: In progress',+ 'a prop block round-trips whole')+ ok(round.pages[0].blocks[0].layout === 'board',+ 'a view block keeps the query a newer build wrote')+ }++ // an unknown FIELD KEY must not throw or vanish — it renders its own html+ ok(fieldByKey({} as never, 'no-such-field') === undefined,+ 'an unknown field key resolves to no spec')+ ok(optionOf(undefined, 'x') === undefined, '…and asking for its options is not an error')+}++// ---- a view can be NARROWED, and a card can be MOVED ----------------------+// A filter is stored on the view block, so it is as permanent as the board is,+// and everything here is a thing that fails SILENTLY: a filter shows too few+// issues and looks like an empty tracker; a filter this build cannot read shows+// too many and looks like it worked; a drag that lands where it started writes+// an undo step you have to press ⌘Z past for nothing.+{+ const doc = {+ format: FORMAT, version: 1, docId: 'tk', title: 'T',+ pages: [], theme: {},+ } as unknown as SpacesDoc+ const vals = (o: Record<string, unknown>) => new Map(Object.entries(o))++ // ABSENT MEANS EVERYTHING — the rule that keeps every view block written+ // before filters existed working unchanged+ ok(passesFilter(doc, vals({ status: 'done' }), undefined), 'no filter shows everything')+ ok(passesFilter(doc, vals({ status: 'done' }), {}), '…and neither does an empty one')+ ok(passesFilter(doc, vals({ status: 'done' }), { is: { status: [] } }),+ '…nor a field whose value list is empty, which is no constraint rather than "nothing passes"')++ // filter by a value+ ok(passesFilter(doc, vals({ status: 'todo' }), { is: { status: ['todo', 'doing'] } }),+ 'a value in the list passes')+ ok(!passesFilter(doc, vals({ status: 'done' }), { is: { status: ['todo', 'doing'] } }),+ '…and one that is not does not')+ ok(passesFilter(doc, vals({ labels: ['bug', 'ui'] }), { is: { labels: ['ui'] } }),+ 'a list-valued field passes on any member')+ ok(!passesFilter(doc, vals({}), { is: { status: ['todo'] } }),+ 'an issue with no value for a filtered field does not pass')++ // A VALUE THIS BUILD DOES NOT KNOW is compared literally — a filter written+ // by a newer build still selects the issues it meant+ ok(passesFilter(doc, vals({ status: 'shipped-to-space' }), { is: { status: ['shipped-to-space'] } }),+ 'an unknown value is filtered ON, not dropped')++ // OPEN ONLY, from FieldOption.group+ ok(phaseField(doc)?.key === 'status',+ 'the phase field is derived from the schema — the first whose options declare a group')+ ok(phaseField({ fields: [{ key: 'k', label: 'K', vt: 'text' }] } as never) === undefined,+ '…and a schema that declares no phases has none')+ ok(passesFilter(doc, vals({ status: 'doing' }), { open: true }), 'a started issue is open')+ ok(passesFilter(doc, vals({ status: 'backlog' }), { open: true }), 'an unstarted one is open')+ ok(!passesFilter(doc, vals({ status: 'done' }), { open: true }), 'a done one is not')+ ok(!passesFilter(doc, vals({ status: 'cancelled' }), { open: true }), 'nor is a cancelled one')+ ok(isOpenPhase(phaseField(doc), 'shipped-to-space'),+ 'a status this build cannot read counts as OPEN — hiding work is the loss, showing one issue too many is not')+ ok(passesFilter({ fields: [{ key: 'k', label: 'K', vt: 'text' }] } as never, vals({}), { open: true }),+ 'and "open" over a schema with no phases passes everything rather than emptying the board')++ // a rule from a NEWER BUILD: kept, not applied, and SAID OUT LOUD+ const future = { open: true, since: '2026-01-01' }+ ok(unknownFilterKeys(future).join() === 'since',+ 'a filter key this build cannot evaluate is reported')+ ok(unknownFilterKeys({ is: {}, open: true }).length === 0, '…and a known one is not')+ ok(passesFilter(doc, vals({ status: 'doing' }), future),+ 'the rules this build DOES know are still applied alongside it')+ ok(JSON.parse(JSON.stringify({ type: 'view', filter: future })).filter.since === '2026-01-01',+ 'and the rule itself round-trips verbatim')++ ok(filterCount(undefined) === 0 && filterCount({ open: true, is: { status: ['a'], p: [] } }) === 2,+ 'the Filter button counts what actually narrows — an empty value list narrows nothing')++ // ---- dropping a card ----------------------------------------------------+ // THE BOARD'S ORDER IS THE PAGE ORDER. No per-view order field exists, so the+ // arithmetic here is the whole mechanism, and its null return is what keeps a+ // drag that went nowhere out of the undo stack.+ const ps = (...ids: string[]): Page[] => ids.map((id) => ({ id, title: id, blocks: [] }))+ const ids = (list: Page[] | null): string => (list ?? []).map((p) => p.id).join('')++ ok(ids(reorderPages(ps('a', 'b', 'c'), 'c', { before: 'a' })) === 'cab', 'a card moves before another')+ ok(ids(reorderPages(ps('a', 'b', 'c'), 'a', { after: 'c' })) === 'bca', '…or after the last one')+ ok(reorderPages(ps('a', 'b', 'c'), 'a', { before: 'b' }) === null,+ 'dropping a card exactly where it already is records NOTHING')+ ok(reorderPages(ps('a', 'b', 'c'), 'b', { after: 'a' }) === null, '…from either side of the gap')+ ok(reorderPages(ps('a', 'b', 'c'), 'b', { before: 'b' }) === null, '…and dropping it on itself is not a move')+ ok(reorderPages(ps('a', 'b', 'c'), 'b', {}) === null,+ 'a drop into an EMPTY column is a status change only, never a reorder')+ ok(reorderPages(ps('a', 'b'), 'zz', { before: 'a' }) === null, 'a page that is not there does not move')+ ok(reorderPages(ps('a', 'b'), 'a', { before: 'zz' }) === null, '…and neither does one aimed at a card that is not')+ // the anchor is an ID because the index moves under the splice+ ok(ids(reorderPages(ps('a', 'b', 'c', 'd'), 'a', { before: 'd' })) === 'bcad',+ 'moving forwards lands before the anchor, not one short of it')+ ok(ids(reorderPages(ps('a', 'b', 'c', 'd'), 'd', { after: 'a' })) === 'adbc',+ 'and moving backwards lands after it')++ // the value block a card's status button and a drop both write through+ const page: Page = { id: 'p', title: 'x', blocks: [+ { id: 'b1', type: 'prop', key: 'status', value: 'todo', html: 'Status: Todo' },+ { id: 'b2', type: 'p', html: '' },+ ] }+ ok(propBlockOf(page, 'status')?.id === 'b1', 'a page reports the BLOCK holding a field, not just its value')+ ok(propBlockOf(page, 'priority') === undefined,+ 'and a field it does not carry has none — the drop creates one through propBlock')+}++// ---- the board's writes go through the ONE writer -------------------------+// `value` and `html` must move together on EVERY path, or a status set from the+// board is invisible to an older build, a thumbnailer, a grep and the markdown+// export. There are three ways to set one now (the header chip, the card+// button, a drag) and they must not become three writers.+{+ const fs = await import('node:fs')+ const ed = fs.readFileSync(new URL('../spaces/src/editor.ts', import.meta.url), 'utf8')+ const ren = fs.readFileSync(new URL('../spaces/src/render.ts', import.meta.url), 'utf8')++ ok((ed.match(/propHtml\(/g) ?? []).length === 1,+ 'editor.ts calls propHtml in exactly ONE place — applyField, the single writer')+ ok(/private applyField\([^)]*\)[^{]*\{\s*;?\(b as Record<string, unknown>\)\.value = value\s*b\.html = propHtml\(f, value\)/.test(ed),+ '…and that writer sets value and html together, in adjacent statements')+ ok(!/\.value = optId/.test(ed),+ 'the drop handler does not assign a value of its own')++ // undo scope: a page entry snapshots the page IN VIEW (store.ts), so a value+ // changed from a board — which is on another page — must take a doc entry+ ok(/at\.pageId === s\.pageId \? 'page' : 'doc'/.test(ed),+ 'a field set on another page takes a DOCUMENT undo entry, not a page one')++ // one drag = one undo step, and a drag that changed nothing = none+ ok(/if \(!setting && !order\) return/.test(ed),+ 'a drop that changes neither value nor order commits nothing')+ ok((ed.match(/s\.commit\(\(\) => \{[\s\S]*?if \(order\) s\.doc\.pages = order/g) ?? []).length === 1,+ 'the value change and the move are ONE commit — one drag, one undo step')++ // read-only and reading view: no board machinery at all. The guard is on the+ // wiring ITSELF, not only on its call site — the callout chip loop shipped+ // wired in reading view for exactly one round because the guard lived+ // somewhere a later edit could step outside of.+ ok(/private wireBoard\([^)]*\)[^{]*\{\s*const s = this\.store\s*if \(s\.readOnly \|\| this\.reading\) return/.test(ed),+ 'the board refuses to wire itself in a locked space or in reading view')+ ok(/const own = opts\.editable && field && propBlockOf/.test(ren),+ 'the renderer emits a card status BUTTON only for an editable document')+ ok(/if \(opts\.editable\) \{\s*const on = /.test(ren),+ '…and the view controls likewise, so a reader and a printout get neither')+}+console.log(`\n${checks - failures}/${checks} checks passed`)if (failures) process.exit(1)diff --git a/scripts/test-spaces-size.mjs b/scripts/test-spaces-size.mjsindex 37fd4253..aa439866 100644--- a/scripts/test-spaces-size.mjs+++ b/scripts/test-spaces-size.mjs@@ -19,6 +19,14 @@// reviewer can see and argue with. What it stops is the drift nobody chose —// forty commits each costing 300 bytes.//+// THE NUMBER IS ENVIRONMENT-SENSITIVE, and CI's is the one that counts.+// Most of the shell is a zlib-deflated block, and zlib's output differs+// slightly between node versions: measured on one commit, node 26 locally+// produced 130,095 B where CI's node 24 produced 131,246 B — 1.1 KB apart for+// identical input. So a ceiling set tight against a local build fails in CI for+// reasons that have nothing to do with the change. Leave a few KB of headroom,+// and when the two disagree, believe CI.+//// Spaces ships in ONE file that people mail to each other, and every byte is// paid on every open, on every phone, forever. Slides is 560KB because it grew// for a year without one of these.diff --git a/spaces/src/agent.ts b/spaces/src/agent.tsindex e7ebbcfd..53a0b498 100644--- a/spaces/src/agent.ts+++ b/spaces/src/agent.ts@@ -30,10 +30,13 @@// an undo entry that undoes nothing. Planning first also makes the whole write// path testable in node, where there is no store and no DOM.-import { type SpacesDoc, type Page, type Block, buildIndex, isRemote, newBlock, uid } from './model.ts'+import { type SpacesDoc, type Page, type Block, buildIndex, isRemote, newBlock, newPage, uid } from './model.ts'import { SPECS, SPEC } from './blocks.ts'import { sanitizeInline, textOf, inertBody, esc, UNWRAP } from './sanitize.ts'import { orphanAssets, humanBytes } from './assets.ts'+import {+ type FieldSpec, ISSUE_FIELDS, fieldsOf, fieldByKey, optionOf, propBlock, propHtml, valuesOf, isIssue, headerLength,+} from './fields.ts'// ---------------------------------------------------------------------------// shared helpers@@ -238,11 +241,24 @@ export function validateDoc(doc: SpacesDoc): ValidateResult {fix: 'Set home to a real page id. Readers land on the first page instead, which may not be the one you wrote to be landed on.' })}+ // ---- the field schema ----------------------------------------------------+ // Only a DECLARED `doc.fields` can be wrong; a document without one gets+ // DEFAULT_FIELDS, which is code.+ const fieldOf = new Map<string, FieldSpec>()+ for (const f of fieldsOf(doc)) {+ if (f && typeof f.key === 'string' && f.key && typeof f.label === 'string') { fieldOf.set(f.key, f); continue }+ add({ code: 'bad-field-schema', severity: 'error', path: 'fields',+ message: `A field in doc.fields has no string key and label (${JSON.stringify(f ?? null).slice(0, 60)}). Writing a value for it THROWS while building its readable form, so the editor's field picker fails on click and the page does not repaint.`,+ fix: 'Give every entry a string `key`, a string `label`, and a `vt` of select | person | number | date | text | labels.' })+ }+// ---- pages and blocks ---------------------------------------------------const usedAssets = new Set<string>()for (const p of pages) {const blocks = Array.isArray(p.blocks) ? p.blocks : []const own = new Set(blocks.map((b) => b.id))+ /** field keys already seen on THIS page — one value per field, per page */+ const propKeys = new Set<string>()if (!blocks.length) {// Not cosmetic: the editor's caret, gutter and / menu all hang off a@@ -334,6 +350,61 @@ export function validateDoc(doc: SpacesDoc): ValidateResult {}}+ // ---- field values ----------------------------------------------------+ // An ISSUE IS A PAGE and its values are `prop` blocks. Everything that+ // can be wrong here is wrong SILENTLY: the page still renders, the board+ // still draws, and the file still says something — just not what the+ // author meant.+ if (b.type === 'prop') {+ const key = String((b as { key?: unknown }).key ?? '')+ const f = fieldOf.get(key)+ const value = (b as { value?: unknown }).value+ const unset = value === undefined || value === null || value === ''+ if (!key) {+ add({ ...at, code: 'prop-no-key', severity: 'warning', path: 'key',+ message: 'A prop block has no `key`, so it names no field: nothing reads it, the header strip cannot label it, and a board cannot group by it.',+ fix: `Set key to one of: ${[...fieldOf.keys()].join(', ')}.` })+ } else if (!f) {+ // INFO, not a warning: `doc.fields` is additive, so a key this+ // schema does not declare is how a NEWER build's field arrives. The+ // value keeps rendering — the block carries its own html — but this+ // build cannot label it or edit it.+ add({ ...at, code: 'unknown-field-key', severity: 'info', path: 'key',+ message: `"${key}" is not a field in doc.fields, so its value shows only as the text in its html and cannot be edited or grouped by here.`,+ fix: `Add { "key": "${key}", "label": "…", "vt": "text" } to doc.fields, or use one of: ${[...fieldOf.keys()].join(', ')}.` })+ } else if (f.vt === 'select' && !unset && !optionOf(f, value)) {+ // INFO for the same reason: an option a newer build declared must+ // survive this one untouched. It is still worth saying, because the+ // OTHER way to get here is typing a label ('In progress') where an+ // id ('doing') belongs, and then wondering why the board files it+ // under "Other".+ add({ ...at, code: 'unknown-field-value', severity: 'info', path: 'value',+ message: `"${String(value)}" is not one of ${key}'s options, so it is shown verbatim and grouped apart from the rest.`,+ fix: `Use an option id — ${(f.options ?? []).map((o) => o.id).join(', ')} — or declare this one in doc.fields. The value is kept either way.` })+ } else if (b.html !== propHtml(f, value)) {+ // THE ONE THAT MATTERS. `html` is what an older build, a+ // thumbnailer, a grep and the markdown export see, and it is ALL+ // they see. A value edited without it says one thing to this build+ // and another to every one of them, forever, with nothing to notice+ // it — which is the whole degradation guarantee, broken silently.+ //+ // Deliberately NOT checked when the value names no known option+ // (above): the writer knew a label this build does not, so its html+ // is RIGHT and ours would be the guess.+ add({ ...at, code: 'prop-html-stale', severity: 'warning', path: 'html',+ message: `This value's readable form disagrees with its value: html is ${JSON.stringify(b.html ?? '')} where the value reads "${propHtml(f, value)}". An older build, a thumbnailer, a grep and the markdown export show the html — so they all show the wrong value.`,+ fix: 'Write both together: bento.setField(page, key, value) does, and so does the editor. Never assign `value` on its own.' })+ }+ if (key) {+ if (propKeys.has(key)) {+ add({ ...at, code: 'duplicate-prop', severity: 'warning', path: 'key',+ message: `This page carries more than one value for "${key}". A reader takes the LAST one, so the earlier block is a value that is shown in the header, found by search, and ignored by every query.`,+ fix: 'Remove the duplicate block. bento.setField writes all of them at once while they exist, so the page at least cannot disagree with itself.' })+ }+ propKeys.add(key)+ }+ }+const src = typeof b.src === 'string' ? b.src : ''if (src.startsWith('asset:')) usedAssets.add(src.slice(6))if (b.type === 'image') {@@ -622,6 +693,29 @@ function splitPatch(patch: Record<string, unknown>): { sets: Record<string, unkn* It used to append silently, which put the content somewhere the agent did not* ask for and reported success.*/+/**+ * A `prop` block's readable form, re-derived from its value. ALWAYS.+ *+ * The degradation guarantee — "an older build, a thumbnailer, a grep and the+ * markdown export all see 'Status: In progress'" — was claimed by setField and+ * enforced nowhere else. Measured on this build: `updateBlock(id,{value:'doing'})`+ * left `html:'Status: Todo'`, so the file SAID Todo while its value said doing;+ * and `insertBlocks` with a prop block wrote no `html` at all. A guarantee that+ * one writer keeps and three writers break is not a guarantee.+ *+ * So it is applied where blocks are WRITTEN, not where fields are set: every+ * verb goes through here, and a verb added later gets it without knowing.+ * An unknown key has no spec and keeps whatever it was given — that is a value+ * from a newer build, not an error.+ */+function syncProp(doc: SpacesDoc, b: Block): void {+ if (b.type !== 'prop') return+ const key = String((b as Record<string, unknown>).key ?? '')+ const f = key ? fieldByKey(doc, key) : undefined+ if (!f || typeof f.label !== 'string') return+ ;(b as Record<string, unknown>).html = propHtml(f, (b as Record<string, unknown>).value)+}+export function planInsertBlocks(doc: SpacesDoc, pageId: string, afterId: string | null, blocks: unknown,): Plan<{ ids: string[]; page: string }> {@@ -641,6 +735,7 @@ export function planInsertBlocks(const b = { ...src, id: uid('b'), type } as Blockif (typeof src.id === 'string' && src.id) remap.set(src.id, b.id)if (typeof b.html === 'string') b.html = normalizeHtml(b.html, type)+ syncProp(doc, b) // a field value is nothing without its readable formmade.push(b)}for (const b of made) {@@ -701,6 +796,7 @@ export function planUpdateBlock(doc: SpacesDoc, id: string, patch: unknown): Plafor (const k of dels) delete (block as Record<string, unknown>)[k]const retyped = typeof sets.type === 'string' && sets.type !== block.typeObject.assign(block, sets)+ syncProp(doc, block) // value and readable form move together, always// A TYPE CHANGE RUNS THE REGISTRY'S init, exactly as the editor's setType// does. Without it an agent-written callout has no `tone` and an// agent-written to-do has no `done` — documents the app itself could not@@ -924,3 +1020,302 @@ export function planRemovePage(doc: SpacesDoc, id: string, opts: RemovePageOpts},}}++// ---------------------------------------------------------------------------+// the tracker: the schema, the values, the backlog+// ---------------------------------------------------------------------------+//+// AN ISSUE IS A PAGE (docs/DECISIONS.md, 2026-08-05). Its field values are+// `prop` BLOCKS; the schema they draw on is `doc.fields`. Nothing here is a+// page-level key and nothing is a new page type.+//+// WHY THESE VERBS EXIST AT ALL. An agent could already write a prop block by+// hand through insertBlocks — and get the `html` wrong, which is the one thing+// that must never happen: that string is what an older build, a thumbnailer, a+// grep and the markdown export see, and it is ALL they see. A value written+// without it is a value those readers cannot read. So the only supported way to+// set a value goes through fields.ts propHtml(), exactly as the editor's own+// field picker does, and the two cannot drift because they are the same call.++/** The schema in force, as data. */+export function fieldsReport(doc: SpacesDoc): FieldSpec[] {+ // A COPY. `fieldsOf` hands back DEFAULT_FIELDS itself when the document+ // declares no schema of its own, and that array is module state shared by+ // every document opened in this session — one `bento.fields()[0].options.pop()`+ // would edit the schema of documents that have not been loaded yet.+ return JSON.parse(JSON.stringify(fieldsOf(doc))) as FieldSpec[]+}++export interface FieldWarning {+ code: 'unknown-option'+ key: string+ detail: string+ /** the ids that ARE options, so the caller can correct itself */+ options: string[]+}++/**+ * Is this a value the field's own options know?+ *+ * DELIBERATELY A WARNING, NOT A REFUSAL. The format is permanent and additive:+ * a status a NEWER build declared must round-trip through this one verbatim,+ * and a verb that refused it would make an older build unable to edit a+ * document a newer one wrote — the exact failure the additivity rule exists to+ * prevent. But an agent typing 'In progress' where the option id is 'doing' has+ * made a mistake, and silence would leave it believing otherwise: the value+ * would be stored, the board would file it under "Other", and nothing would+ * have said so. So it is written AND reported, with the ids listed.+ *+ * An empty value is "not set", never an unknown option — the editor itself+ * writes `''` for a select with no default (fields.ts `def`), so flagging it+ * would fire on documents this build produced.+ */+function optionWarning(f: FieldSpec, value: unknown): FieldWarning | undefined {+ if (f.vt !== 'select' || value === '' || value === null || value === undefined) return undefined+ if (optionOf(f, value)) return undefined+ const options = (f.options ?? []).map((o) => o.id)+ return {+ code: 'unknown-option', key: f.key, options,+ detail: `"${String(value)}" is not one of ${f.key}'s options (${options.join(', ')}). It was written unchanged — the format keeps a value a newer build may have declared — but if you meant an existing option, use its id, not its label.`,+ }+}++/** ONE refusal, worded once: both write verbs reject the same mistake. */+const noSuchField = (k: string, schema: FieldSpec[]): PlanError =>+ fail('no-such-field', `"${k}" is not a field in this space. The schema is doc.fields, which declares: ${schema.map((x) => x.key).join(', ')}. Add the field there first — a value whose field nothing declares cannot be labelled, edited or grouped by.`)++export interface SetFieldResult {+ pageId: string+ key: string+ value: unknown+ /** the readable form written with it — what an older build shows */+ html?: string+ /** the prop blocks that now hold the value (or that were just removed) */+ blocks: string[]+ /** the page had no value for this field and one was added to the header */+ created: boolean+ /** the value was cleared: those prop blocks are gone */+ removed: boolean+ warning?: FieldWarning+}++/**+ * Set one field on one page — the ONE undoable step that writes a field value.+ *+ * `null` (or `undefined`) CLEARS the field: the prop block goes, which is the+ * convention the patch verbs already use, and is how a page stops being an+ * issue (clear its status and it is a document again, body intact). Clearing a+ * field that is not set is not an error; the call is idempotent.+ *+ * The page need not already be an issue. Setting `status` on any page is+ * precisely what makes it one — there is no flag to set and no type to change.+ */+export function planSetField(doc: SpacesDoc, pageId: string, key: unknown, value: unknown): Plan<SetFieldResult> {+ const page = doc.pages.find((p) => p.id === pageId)+ if (!page) return fail('no-such-page', String(pageId))+ const k = String(key ?? '')+ const schema = fieldsOf(doc)+ const f = schema.find((x) => x.key === k)+ if (!f) return noSuchField(k, schema)+ if (value !== null && value !== undefined && !jsonSafe(value)) {+ return fail('not-serializable', `the value for "${k}" holds something JSON cannot carry (a function, a DOM node, a Date, a cycle). It would vanish or throw at save time.`)+ }++ // Normally exactly one. A page carrying TWO prop blocks for one key is a+ // defect validate() reports as `duplicate-prop` — and while it exists a+ // reader takes the LAST (fields.ts valuesOf), so writing only the first would+ // be a set that changes nothing anyone can see, and reports success.+ const mine = page.blocks.filter((b) => b.type === 'prop' && (b as { key?: unknown }).key === k)++ if (value === null || value === undefined) {+ return {+ ok: true, pageId: page.id, key: k, value: null,+ blocks: mine.map((b) => b.id), created: false, removed: true,+ apply() { page.blocks = page.blocks.filter((b) => !mine.includes(b)) },+ }+ }++ const html = propHtml(f, value)+ const fresh = mine.length ? null : propBlock(f, value, uid('b'))+ const warning = optionWarning(f, value)+ return {+ ok: true,+ pageId: page.id, key: k, value, html,+ blocks: fresh ? [fresh.id] : mine.map((b) => b.id),+ created: !!fresh, removed: false,+ ...(warning ? { warning } : {}),+ apply() {+ // VALUE AND html TOGETHER, always, through propHtml — the whole reason+ // this verb exists instead of an insertBlocks the caller writes itself.+ for (const b of mine) {+ ;(b as Record<string, unknown>).value = value+ b.html = html+ }+ // A new value joins the HEADER STRIP: prop blocks before the first+ // non-prop block are the header, by position (render.ts), so appending+ // one to the end of the page would leave a field stranded under the prose.+ if (fresh) page.blocks.splice(headerLength(page), 0, fresh)+ },+ }+}++export interface IssueReport {+ id: string+ title: string+ /** the href an inline link would use: `#p/<id>` */+ url: string+ archived?: true+ /**+ * The PHASE of its status (FieldOption.group) — what makes "open" mean+ * something without anyone configuring a filter. `'unknown'` when the status+ * names no option this schema declares: never silently folded in with the+ * rest, because that is exactly the value a newer build wrote.+ */+ group?: string+ /** every field value on the page, by key */+ fields: Record<string, unknown>+}++export interface IssueQuery {+ /**+ * Field equality. `{ status: 'todo' }`, an array for any-of+ * (`{ status: ['backlog', 'todo'] }`), `null` for "not set" — which covers+ * both an absent prop block and an empty one, because the editor writes `''`+ * for a field it has seeded and nobody has filled in.+ */+ where?: Record<string, unknown>+ /**+ * Status phase: 'unstarted' | 'started' | 'done' | 'cancelled' | 'unknown',+ * an array of those, or 'open'.+ */+ group?: string | string[]+ /** include archived issues too; they are excluded by default */+ archived?: boolean+}++const FINISHED = new Set(['done', 'cancelled'])++/** Compared as TEXT, so `3` and `"3"` are the same estimate. This document is+ * hand-written JSON as often as not, and a filter that missed on the type of a+ * number would look exactly like an empty backlog. */+function matches(actual: unknown, want: unknown): boolean {+ if (Array.isArray(want)) return want.some((w) => matches(actual, w))+ if (want === null || want === undefined) return actual === undefined || actual === null || actual === ''+ return String(actual ?? '') === String(want)+}++/**+ * The backlog, as data.+ *+ * One call rather than a page-by-page scan: "everything unstarted and+ * unassigned" is `issues({ group: 'open', where: { assignee: null } })`.+ */+export function issuesReport(doc: SpacesDoc, query: IssueQuery = {}): IssueReport[] {+ const status = fieldsOf(doc).find((f) => f.key === 'status')+ const want = query.group == null ? null+ : (Array.isArray(query.group) ? query.group : [query.group]).map(String)+ const out: IssueReport[] = []++ for (const page of doc.pages) {+ if (!isIssue(page)) continue+ if (page.archived && !query.archived) continue+ const values = valuesOf(page)+ const raw = values.get('status')+ const opt = status && optionOf(status, raw)+ // An UNSET status is not an UNKNOWN one. Reporting 'unknown' for a field+ // nobody has filled in tells an agent the value came from a build we do not+ // understand, when in fact there is no value — and those want opposite+ // handling: one is "leave it alone", the other is "this needs triaging".+ const group = raw === undefined || raw === null || raw === ''+ ? undefined+ : opt ? opt.group : 'unknown'++ // OPEN MEANS NOT FINISHED — one predicate, so a status with no group and a+ // status this build has never heard of both count as work. That is the safe+ // direction: an issue wrongly shown in a backlog costs a glance, an issue+ // wrongly hidden from one costs the issue.+ if (want && !want.some((g) => (g === 'open' ? !(group && FINISHED.has(group)) : g === group))) continue++ let keep = true+ for (const [k, w] of Object.entries(query.where ?? {})) {+ if (!matches(values.get(k), w)) { keep = false; break }+ }+ if (!keep) continue++ out.push({+ id: page.id, title: page.title, url: `#p/${page.id}`,+ ...(page.archived ? { archived: true as const } : {}),+ ...(group ? { group } : {}),+ fields: Object.fromEntries(values),+ })+ }+ return out+}++export interface NewIssueResult {+ id: string+ blocks: string[]+ warnings?: FieldWarning[]+}++/**+ * A new issue: one page, its fields already on it, in ONE undoable step.+ *+ * `title` and `parent` are the page's; every OTHER key is a field key, and one+ * that is not in the schema is REFUSED rather than parked on the page. Unknown+ * keys in a DOCUMENT are a feature — they are how a future build's data+ * survives this one — but an unknown key in an ARGUMENT is a typo, and an agent+ * that wrote `{ prioritty: 'high' }` would otherwise be told it had set a+ * priority it had not set.+ *+ * The page ends with an empty paragraph, exactly as ⌘⇧I does: a page whose+ * every block is a prop has nowhere to put a caret and nowhere to write the+ * issue down.+ */+export function planNewIssue(doc: SpacesDoc, spec: unknown): Plan<NewIssueResult> {+ if (spec !== undefined && !isPatch(spec)) return fail('bad-patch', 'pass { title?, parent?, ...fieldValues }')+ const src = (spec ?? {}) as Record<string, unknown>+ const parent = src.parent == null ? '' : String(src.parent)+ if (parent && !doc.pages.some((p) => p.id === parent)) return fail('no-such-page', `parent "${parent}"`)++ const schema = fieldsOf(doc)+ const values: Record<string, unknown> = {}+ const warnings: FieldWarning[] = []+ for (const [k, v] of Object.entries(src)) {+ if (k === 'title' || k === 'parent') continue+ const f = schema.find((x) => x.key === k)+ if (!f) return noSuchField(k, schema)+ if (v !== null && v !== undefined && !jsonSafe(v)) return fail('not-serializable', `the value for "${k}" holds something JSON cannot carry`)+ values[k] = v ?? ''+ const w = optionWarning(f, values[k])+ if (w) warnings.push(w)+ }++ const page = newPage(plainTitle(src.title) || 'New issue', parent ? { parent } : {})+ // The SEED LIST is fields.ts's, never a second copy here: a fresh issue from+ // an agent and a fresh issue from ⌘⇧I must carry the same fields, or one of+ // them makes an issue a human cannot assign — there is no "add a field"+ // gesture, because `prop` is unlisted in the / menu on purpose.+ const seed = schema.filter((f) => ISSUE_FIELDS.includes(f.key) || f.key in values)++ // A NEW ISSUE MUST BE AN ISSUE. A space that declares its own schema without+ // a `status` seeded nothing recognisable: the verb returned ok, and the page+ // it made was invisible to issues(), to every board, and to a follow-up+ // setField('status') that then failed `no-such-field`. Reporting success for+ // a page that is not an issue is worse than refusing to make one.+ if (!seed.some((f) => f.key === 'status')) {+ return fail('no-status-field',+ 'this space declares no `status` field, and a page is an issue because it has one — '+ + 'add a status field to doc.fields (see bento.fields()) before creating issues')+ }++ const props = seed+ .map((f) => propBlock(f, f.key in values ? values[f.key] : (f.def ?? ''), uid('b')))+ page.blocks = [...props, newBlock('p')]++ return {+ ok: true, id: page.id, blocks: page.blocks.map((b) => b.id),+ ...(warnings.length ? { warnings } : {}),+ apply() { doc.pages.push(page) },+ }+}diff --git a/spaces/src/blocks.ts b/spaces/src/blocks.tsindex 9975048d..1be52bc1 100644--- a/spaces/src/blocks.ts+++ b/spaces/src/blocks.ts@@ -194,6 +194,25 @@ export const SPECS: BlockSpec[] = [tag: 'div', custom: true,toMd: (b, _text, _indent, titleOf) => [`→ [[${titleOf(String(b.page)) ?? '?'}]]`],},+ {+ // A FIELD VALUE on a page. Unlisted: fields are added from the issue header,+ // not the / menu — "Field" in a block list would be a block whose value you+ // then have to go and find somewhere else.+ //+ // It renders its own `html` on any build that does not know the type, which+ // is the whole reason values are blocks rather than page keys.+ type: 'prop', label: 'Field', hint: 'A typed value on this page', icon: 'tag',+ tag: 'div', custom: true, unlisted: true,+ toMd: (b) => [`**${String((b as { key?: unknown }).key ?? 'field')}:** ${String((b as { value?: unknown }).value ?? '')}`],+ },+ {+ // A SAVED VIEW — a board or a list of the issues in this space. Also just a+ // block, so it lives on a page, moves, duplicates, deletes and prints like+ // anything else, and an older build shows its description instead.+ type: 'view', label: 'Board or list', hint: 'Issues, grouped or listed', icon: 'board',+ tag: 'div', custom: true,+ toMd: (b) => [`_${String(b.html ?? 'View')}_`],+ },{type: 'image', label: 'Image', hint: 'Embedded in the file', icon: 'image',tag: 'div', custom: true,diff --git a/spaces/src/editor.ts b/spaces/src/editor.tsindex d0c8f2b5..9e6e8a65 100644--- a/spaces/src/editor.ts+++ b/spaces/src/editor.ts@@ -14,6 +14,10 @@ import { renderPage, toneLabel, paintCode } from './render'import { CODE_LANGS, langLabel, normLang } from './highlight'import { canonicalize, escText, sanitizeInline, textOf } from './sanitize'import { MENU_SPECS, MD_SPECS, SPEC, CALLOUT_TONES } from './blocks'+import {+ fieldByKey, fieldsOf, propHtml, propBlock, propBlockOf, isIssue, headerLength,+ reorderPages, columnMoves, ISSUE_FIELDS, type DropAim, type FieldSpec, type ViewFilter,+} from './fields'import { planImport, type SourceFile } from './markdown'import { countOutsideTags, replaceOutsideTags } from './findreplace'import { t } from './i18n'@@ -175,6 +179,9 @@ export class Editor {keep?: (b: HTMLButtonElement) => void}> = [{ icon: 'page', label: t('New page'), hint: '⌘⌥N', run: () => this.newPage() },+ { icon: 'board', label: t('New issue'), hint: '⌘⇧I', run: () => this.newIssue() },+ { icon: 'tag', label: t('Make this page an issue'), hint: t('Adds status, priority, assignee, estimate'),+ run: () => this.makeIssue() },{ icon: 'eye', label: t('Reading view'), hint: t('The pages without the editing tools'),run: () => this.toggleReading(),keep: (b) => { this.readB = b } },@@ -481,7 +488,12 @@ export class Editor {a.draggable = truea.addEventListener('click', (e) => { e.preventDefault(); s.goToPage(page.id); this.toggleSidebar(false) })a.addEventListener('dragstart', (e) => e.dataTransfer?.setData('text/bento-page', page.id))- a.addEventListener('dragover', (e) => { e.preventDefault(); a.classList.add('sp-drop') })+ a.addEventListener('dragover', (e) => {+ // a sidebar row accepts PAGES; a card dragged over it lit up and+ // promised a nesting it would never perform+ if (!e.dataTransfer?.types.includes('text/bento-page')) return+ e.preventDefault(); a.classList.add('sp-drop')+ })a.addEventListener('dragleave', () => a.classList.remove('sp-drop'))a.addEventListener('drop', (e) => {e.preventDefault(); a.classList.remove('sp-drop')@@ -663,7 +675,16 @@ export class Editor {})grip.addEventListener('dragend', () => node.classList.remove('sp-dragging'))- node.addEventListener('dragover', (e) => { e.preventDefault(); node.classList.add('sp-dropline') })+ node.addEventListener('dragover', (e) => {+ // ONLY a block drag. A view block is a block node, so an issue card+ // dragged across the board lit the blue "block moves here" bar under the+ // whole view at the same time as the column's outline — two things+ // claiming one drop, from different owners. The payload says which+ // gesture this is; ask it.+ if (!e.dataTransfer?.types.includes('text/bento-block')) return+ e.preventDefault()+ node.classList.add('sp-dropline')+ })node.addEventListener('dragleave', () => node.classList.remove('sp-dropline'))node.addEventListener('drop', (e) => {e.preventDefault()@@ -726,6 +747,376 @@ export class Editor {]}+ /**+ * Change one field's value.+ *+ * Writes `value` AND `html` together, always. The readable form is what an+ * older build, a thumbnailer, a grep and the markdown export see, so a value+ * written without it is a value those readers cannot see at all — which is+ * the entire reason field values are blocks rather than page keys.+ */+ private setField(blockId: string, value: unknown): void {+ const s = this.store+ const at = s.index.block.get(blockId)+ if (!at) return+ const f = fieldByKey(s.doc, String((at.block as { key?: unknown }).key ?? ''))+ if (!f) return+ // PAGE SCOPE ONLY WHEN THE VALUE IS ON THE PAGE IN VIEW. The store's page+ // entry snapshots `store.pageId` by definition (store.ts entry()), and a+ // status changed from a BOARD lives on another page — so a page-scoped+ // checkpoint would record the board, and undo would restore the board while+ // leaving the changed status exactly where it was. Cheap when it is right,+ // silently wrong when it is not.+ const scope = at.pageId === s.pageId ? 'page' : 'doc'+ s.commit(() => this.applyField(at.block, f, value), { scope })+ this.paintPage()+ }++ /**+ * THE ONE WRITER for a field value. `value` and `html` move together, always,+ * because the readable form is the only thing an older build, a thumbnailer,+ * a grep and the markdown export can see. Every path that sets a value —+ * the header chip, the board's card button, a drag between columns — goes+ * through here, so there is one place for the two to fall out of step and it+ * is three lines long.+ */+ private applyField(b: Block, f: FieldSpec, value: unknown): void {+ ;(b as Record<string, unknown>).value = value+ b.html = propHtml(f, value)+ }++ private openFieldPicker(blockId: string, anchor: HTMLElement): void {+ const s = this.store+ if (s.readOnly || this.reading) return+ const b = s.block(blockId)+ const f = b && fieldByKey(s.doc, String((b as { key?: unknown }).key ?? ''))+ if (!b || !f) return+ this.closeOverlay()++ const pop = el('div', this.isDrawer() ? 'sp-pop sp-sheet' : 'sp-pop')+ pop.setAttribute('role', 'menu')+ this.trapAndClose(pop)++ if (f.vt === 'select' && f.options?.length) {+ const cur = String((b as { value?: unknown }).value ?? '')+ for (const o of f.options) {+ const item = document.createElement('button')+ item.className = 'sp-dditem' + (o.id === cur ? ' sp-sel' : '')+ item.type = 'button'+ const dot = el('span', 'sp-prop-dot')+ if (o.color) dot.style.background = o.color+ const name = document.createElement('span')+ name.textContent = o.label+ item.append(dot, name)+ item.addEventListener('click', () => { this.closeOverlay(); this.setField(blockId, o.id) })+ pop.append(item)+ }+ } else {+ // free text, a number or a date: one field, committed on Enter+ const input = document.createElement('input')+ input.className = 'sp-find'+ input.type = f.vt === 'number' ? 'number' : f.vt === 'date' ? 'date' : 'text'+ input.value = String((b as { value?: unknown }).value ?? '')+ input.placeholder = f.label+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault()+ const raw = input.value.trim()+ this.closeOverlay()+ this.setField(blockId, f.vt === 'number' ? (raw === '' ? '' : Number(raw)) : raw)+ }+ })+ pop.append(input)+ afterPaint(() => input.focus())+ }++ this.overlay = pop+ document.body.append(pop)+ if (this.isDrawer()) pop.classList.add('sp-sheet-in')+ else place(pop, anchor)+ const away = (ev: MouseEvent) => {+ if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }+ }+ setTimeout(() => document.addEventListener('mousedown', away), 0)+ }++ /**+ * THE BOARD, made to work — with a mouse and with a finger.+ *+ * Three affordances over one writer:+ * · DRAG a card to another column — that column's option becomes the value.+ * · DRAG within a column — the pages move, because the order of the board+ * IS the order of `doc.pages`. No stored per-view order: that would be a+ * new permanent format field, and a drag handler is not the place to+ * settle one (docs/DECISIONS.md, 2026-08-05).+ * · TAP the status on a card — a phone cannot drag an HTML5 draggable at+ * all, and the board is the tracker's main screen. It opens the SAME+ * picker the issue's own header strip opens.+ *+ * Everything here is wired only when the document is editable: the renderer+ * emits no card button in reading view, in a locked space or on paper, and+ * this is not called there, so there is no half-live board anywhere.+ */+ private wireBoard(root: HTMLElement): void {+ const s = this.store+ if (s.readOnly || this.reading) return+ for (const v of root.querySelectorAll<HTMLElement>('.sp-view')) {+ const vb = s.block(v.dataset.blockId ?? '')+ const groupKey = String((vb as { groupBy?: unknown } | undefined)?.groupBy ?? 'status')++ v.querySelector<HTMLElement>('[data-view-open]')?.addEventListener('click', () => {+ this.editViewFilter(v.dataset.blockId!, (f) => { if (f.open) delete f.open; else f.open = true })+ })+ const fb = v.querySelector<HTMLElement>('[data-view-filter]')+ fb?.addEventListener('click', () => this.openViewFilter(v.dataset.blockId!, fb))++ for (const btn of v.querySelectorAll<HTMLElement>('[data-set-field]')) {+ btn.addEventListener('click', (e) => {+ e.preventDefault()+ this.openFieldPicker(btn.dataset.setField!, btn)+ })+ }++ // NO BOARD, NO DRAG. A list has cards but no columns, so a draggable card+ // there is an affordance that promises something nothing can accept.+ const board = v.querySelector('.sp-board')+ if (!board) continue++ const marks = () => {+ for (const n of v.querySelectorAll('.sp-drop, .sp-dropend, .sp-dropbefore')) {+ n.classList.remove('sp-drop', 'sp-dropend', 'sp-dropbefore')+ }+ }+ for (const card of v.querySelectorAll<HTMLElement>('.sp-issue[data-issue]')) {+ card.draggable = true+ // A LINK DRAGS ITSELF, carrying its href, and that gesture would beat+ // the card's. Told not to, the drag belongs to the nearest draggable+ // ancestor, which is the card.+ card.querySelector('a')?.setAttribute('draggable', 'false')+ card.addEventListener('dragstart', (e) => {+ e.dataTransfer?.setData('text/bento-issue', card.dataset.issue!)+ card.classList.add('sp-dragging')+ })+ card.addEventListener('dragend', () => { card.classList.remove('sp-dragging'); marks() })+ }++ // THE COLUMN UNDER THE POINTER, never a guess — cleared on the way DOWN+ // (capture, on the board) and re-marked on the way up (the column the+ // pointer is actually inside). So the mark is where the pointer is and+ // nowhere else, including over the "Other" column, which accepts no drop+ // and must therefore not leave the last real column looking like a target.+ //+ // `dragleave` cannot do this: it bubbles from every child, so moving+ // across a card inside a column reports leaving the column.+ board.addEventListener('dragover', (e) => {+ if ((e as DragEvent).dataTransfer?.types.includes('text/bento-issue')) marks()+ }, true)+ for (const col of v.querySelectorAll<HTMLElement>('.sp-col[data-group]')) {+ col.addEventListener('dragover', (e) => {+ if (!e.dataTransfer?.types.includes('text/bento-issue')) return+ e.preventDefault()+ const aim = this.aimAt(col, e.clientY)+ col.classList.add('sp-drop')+ if (aim.before) col.querySelector(`[data-issue="${CSS.escape(aim.before)}"]`)?.classList.add('sp-dropbefore')+ else col.classList.add('sp-dropend')+ })+ col.addEventListener('drop', (e) => {+ const moved = e.dataTransfer?.getData('text/bento-issue')+ if (!moved) return+ e.preventDefault()+ const aim = this.aimAt(col, e.clientY)+ marks()+ this.dropIssue(moved, groupKey, col.dataset.group!, aim)+ })+ }+ }+ }++ /** Where in this column a drop at `y` lands: before a card, or after the last. */+ private aimAt(col: HTMLElement, y: number): DropAim {+ const cards = [...col.querySelectorAll<HTMLElement>('.sp-issue[data-issue]')]+ for (const c of cards) {+ const r = c.getBoundingClientRect()+ if (y < r.top + r.height / 2) return { before: c.dataset.issue }+ }+ return { after: cards[cards.length - 1]?.dataset.issue }+ }++ /**+ * A card landed. Set its value, move its page, or — if it landed where it+ * already was — do NOTHING: no commit, no undo entry, no dirty flag. A drag+ * that changes nothing must not be a step you have to press ⌘Z past.+ *+ * Both halves are ONE commit, because one drag is one user action.+ */+ private dropIssue(pageId: string, key: string, optId: string, aim: DropAim): void {+ const s = this.store+ const page = s.index.page.get(pageId)+ const f = fieldByKey(s.doc, key)+ if (!page || !f || s.readOnly) return+ const own = propBlockOf(page, key)+ const setting = !own || String((own as { value?: unknown }).value ?? '') !== optId+ // The no-op test is about the COLUMN, not the page array — those are+ // different orders the moment a board has two columns, and judging by page+ // adjacency let a drop that visibly did nothing rewrite doc.pages.+ const cards = [...document.querySelectorAll<HTMLElement>(`.sp-col[data-group="${CSS.escape(optId)}"] .sp-issue[data-issue]`)]+ .map((c) => c.dataset.issue!)+ const moves = columnMoves(cards, pageId, aim)+ const order = moves ? reorderPages(s.doc.pages, pageId, aim) : null+ if (!setting && !order) return++ s.commit(() => {+ if (setting) {+ if (own) this.applyField(own, f, optId)+ // A page can reach a column without carrying that field at all (a board+ // grouped by something an issue never had). It gains the value, in the+ // header strip where the others are — through propBlock, so the+ // readable form is written with it.+ else page.blocks.splice(headerLength(page), 0, propBlock(f, optId, newBlock('prop').id))+ }+ if (order) s.doc.pages = order+ })+ this.repaint()+ }++ /**+ * Narrow a view. The filter lives on the `view` block, so it is saved, shared+ * and permanent.+ *+ * Rules an edit here must not break: unknown keys are a NEWER build's and are+ * never touched, and a filter that narrows nothing is DELETED rather than+ * stored empty — so a view someone filtered and unfiltered is byte-identical+ * to one that never was.+ */+ private editViewFilter(blockId: string, edit: (f: ViewFilter) => void): void {+ const s = this.store+ const b = s.block(blockId)+ if (!b || s.readOnly || this.reading) return+ s.commit(() => {+ const next = { ...((b as { filter?: ViewFilter }).filter ?? {}) }+ edit(next)+ if (Object.keys(next).length) (b as { filter?: ViewFilter }).filter = next+ else delete (b as { filter?: ViewFilter }).filter+ }, { scope: 'page' })+ this.paintPage()+ }++ /** Toggle one value of one field in a view's filter. */+ private toggleViewValue(blockId: string, key: string, id: string): void {+ this.editViewFilter(blockId, (f) => {+ const is: Record<string, string[]> = { ...(f.is ?? {}) }+ const had = is[key] ?? []+ const next = had.filter((v) => v !== id)+ if (next.length === had.length) next.push(id)+ if (next.length) is[key] = next+ else delete is[key]+ if (Object.keys(is).length) f.is = is+ else delete f.is+ })+ }++ /**+ * The filter picker: every option of every select field, as toggles.+ *+ * Deliberately NOT a query builder — no operators, no and/or, no nesting.+ * A list of values you can switch on is the whole of what a board needs, it+ * fits a phone sheet, and it cannot grow a language that then has to be+ * supported forever.+ */+ private openViewFilter(blockId: string, anchor: HTMLElement): void {+ const s = this.store+ const b = s.block(blockId)+ if (!b || s.readOnly || this.reading) return+ this.closeOverlay()+ const pop = el('div', this.isDrawer() ? 'sp-pop sp-sheet' : 'sp-pop')+ pop.setAttribute('role', 'menu')+ this.trapAndClose(pop)+ const cur = ((b as { filter?: ViewFilter }).filter ?? {}) as ViewFilter++ for (const f of fieldsOf(s.doc)) {+ if (!f.options?.length) continue+ pop.append(el('div', 'sp-fgroup', f.label))+ for (const o of f.options) {+ const on = (cur.is?.[f.key] ?? []).includes(o.id)+ const item = document.createElement('button')+ item.className = 'sp-dditem' + (on ? ' sp-sel' : '')+ item.type = 'button'+ item.setAttribute('aria-pressed', String(on))+ const dot = el('span', 'sp-prop-dot')+ if (o.color) dot.style.background = o.color+ const name = document.createElement('span')+ name.textContent = o.label+ item.append(dot, name)+ // the popover STAYS OPEN: picking three labels is one thought, and+ // reopening a menu between each is the thing that makes filters+ // unusable. Each toggle is still its own undo step.+ item.addEventListener('click', () => {+ const next = !item.classList.contains('sp-sel')+ item.classList.toggle('sp-sel', next)+ item.setAttribute('aria-pressed', String(next))+ this.toggleViewValue(blockId, f.key, o.id)+ })+ pop.append(item)+ }+ }+ const clear = this.menuItem('trash', t('Clear filter'), '', () => {+ this.closeOverlay()+ // unknown keys survive: this clears what this build put there+ this.editViewFilter(blockId, (f) => { delete f.is; delete f.open })+ })+ pop.append(clear)++ this.overlay = pop+ document.body.append(pop)+ if (this.isDrawer()) pop.classList.add('sp-sheet-in')+ else place(pop, anchor)+ const away = (ev: MouseEvent) => {+ if (!pop.contains(ev.target as Node)) { this.closeOverlay(); document.removeEventListener('mousedown', away) }+ }+ setTimeout(() => document.addEventListener('mousedown', away), 0)+ }++ /**+ * Turn the current page into an issue, or make a new one.+ *+ * There is no "issue type" — a page WITH A STATUS is an issue, so this adds+ * the fields and nothing else. Remove the status later and it is a document+ * again, with its body, links and history intact.+ */+ makeIssue(pageId?: string): void {+ const s = this.store+ const page = pageId ? s.index.page.get(pageId) : s.page+ if (!page || s.readOnly) return+ if (isIssue(page)) { this.status(t('Already an issue')); return }+ const fields = fieldsOf(s.doc).filter((f) => ISSUE_FIELDS.includes(f.key))+ s.commit(() => {+ page.blocks.unshift(...fields.map((f) => propBlock(f, f.def ?? '', newBlock('prop').id)))+ })+ this.paintPage()+ this.status(t('Now an issue'))+ }++ /** A new issue: a page that starts with its fields, ready to be titled. */+ newIssue(): void {+ const s = this.store+ if (s.readOnly) return+ const page = newPage(t('New issue'))+ const fields = fieldsOf(s.doc).filter((f) => ISSUE_FIELDS.includes(f.key))+ page.blocks = [+ ...fields.map((f) => propBlock(f, f.def ?? '', newBlock('prop').id)),+ newBlock('p'),+ ]+ s.commit(() => { s.doc.pages.push(page) })+ s.goToPage(page.id)+ this.repaint()+ // the title is what you actually want to type first+ afterPaint(() => {+ const h = this.main.querySelector<HTMLElement>('[data-page-title]')+ h?.focus()+ if (h) { const r = document.createRange(); r.selectNodeContents(h); getSelection()?.removeAllRanges(); getSelection()?.addRange(r) }+ })+ }+/** The block actions, as a menu. Anchored on a wide screen, a sheet on a phone. */private openBlockMenu(id: string, anchor: HTMLElement): void {if (this.store.readOnly || this.reading) return@@ -950,6 +1341,19 @@ export class Editor {})}+ // FIELD CHIPS. Changing a status is the loop a tracker exists for, so it is+ // one click from the issue and one from the board — never a form.+ if (!this.store.readOnly && !this.reading) {+ for (const chip of view.querySelectorAll<HTMLElement>('[data-edit-field]')) {+ chip.addEventListener('click', (e) => {+ e.preventDefault()+ const id = (chip.closest('[data-block-id]') as HTMLElement).dataset.blockId!+ this.openFieldPicker(id, chip)+ })+ }+ this.wireBoard(view)+ }+// "Load this image" — the reader's consent to contact one remote host.// NOT a commit: nothing about the document changed, so this must not touch// undo, the dirty flag or autosave. It is view state, and it dies with the@@ -1244,6 +1648,7 @@ export class Editor {// reaches here when nothing is being edited (the text path returns above,// where `[` is the page-link trigger).if (!mod && e.key === '[') { e.preventDefault(); this.togglePane(); return }+ if (mod && e.shiftKey && e.key.toLowerCase() === 'i') { e.preventDefault(); this.newIssue(); return }if (mod && e.key.toLowerCase() === 'z') {e.preventDefault()if (e.shiftKey) s.redo(); else s.undo()diff --git a/spaces/src/fields.ts b/spaces/src/fields.tsnew file mode 100644index 00000000..7f69f063--- /dev/null+++ b/spaces/src/fields.ts@@ -0,0 +1,358 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Typed fields: the schema, the defaults, and reading a page's values.+//+// AN ISSUE IS A PAGE. Its fields are `prop` BLOCKS on that page; the schema+// they draw on is `doc.fields`. docs/DECISIONS.md (2026-08-05) carries the+// reasoning; the parts that matter when reading this file:+//+// · VALUES ARE BLOCKS because everything in spaces that matters iterates+// `page.blocks` — search, find-and-replace, undo, the block registry, the+// static preview, markdown export. A page-level key is invisible to all of+// them and renders as nothing on a build that predates it. And under+// collaboration each block property is its own last-writer-wins register, so+// two people setting status and assignee at the same moment both win; one+// object on the page would have been ONE register and would have lost an+// edit silently.+//+// · THE SCHEMA IS NOT A VALUE. Putting the status list on every issue would+// copy it into every page and let two pages disagree about what "Todo"+// means. It is document-level, and additive: a build that predates it+// ignores `doc.fields` and still renders each prop block's `html`.+//+// · EVERY PROP BLOCK CARRIES A READABLE `html`. That is what makes the format+// degrade instead of vanish — an older build, a thumbnailer, a grep and a+// markdown export all see "Status: In progress" without knowing what a field+// is. Keeping it in step with `value` is this file's job.++import type { SpacesDoc, Page, Block } from './model'++/** What a field holds. Deliberately few: every one costs an editor and a+ * permanent commitment, and a tracker needs exactly these. */+export type FieldType = 'select' | 'person' | 'number' | 'date' | 'text' | 'labels'++export interface FieldOption {+ id: string+ label: string+ color?: string+ /**+ * Which end of the board this sits at.+ *+ * Linear's insight, and the reason a board is useful rather than pretty: a+ * status is not just a name, it belongs to a PHASE. "Done" and "Cancelled"+ * are both finished; "In review" and "In progress" are both started. Grouping+ * by phase is what lets "show me what is open" mean something without anyone+ * configuring a filter.+ */+ group?: 'unstarted' | 'started' | 'done' | 'cancelled'+}++export interface FieldSpec {+ key: string+ label: string+ vt: FieldType+ options?: FieldOption[]+ /** shown on a new issue when nothing is chosen */+ def?: string+}++/**+ * The fields a fresh tracker starts with.+ *+ * Linear-shaped on purpose: Status, Assignee, Priority, Estimate, Labels,+ * Cycle, Project. Opinionated beats configurable here — a tracker you have to+ * design before you can use it is the thing everybody hates about the+ * alternatives, and every one of these is permanent, so the list is short.+ */+export const DEFAULT_FIELDS: FieldSpec[] = [+ {+ key: 'status', label: 'Status', vt: 'select', def: 'todo',+ options: [+ { id: 'backlog', label: 'Backlog', color: '#8B95A5', group: 'unstarted' },+ { id: 'todo', label: 'Todo', color: '#5B8DEF', group: 'unstarted' },+ { id: 'doing', label: 'In progress', color: '#F7A600', group: 'started' },+ { id: 'review', label: 'In review', color: '#A97BE0', group: 'started' },+ { id: 'done', label: 'Done', color: '#2FA37C', group: 'done' },+ { id: 'cancelled', label: 'Cancelled', color: '#98A2B3', group: 'cancelled' },+ ],+ },+ {+ key: 'priority', label: 'Priority', vt: 'select', def: 'none',+ options: [+ { id: 'urgent', label: 'Urgent', color: '#E5484D' },+ { id: 'high', label: 'High', color: '#F7A600' },+ { id: 'medium', label: 'Medium', color: '#5B8DEF' },+ { id: 'low', label: 'Low', color: '#8B95A5' },+ { id: 'none', label: 'No priority', color: '#C4CBD6' },+ ],+ },+ { key: 'assignee', label: 'Assignee', vt: 'person' },+ { key: 'estimate', label: 'Estimate', vt: 'number' },+ { key: 'labels', label: 'Labels', vt: 'labels' },+ { key: 'due', label: 'Due', vt: 'date' },+ { key: 'project', label: 'Project', vt: 'text' },+]++/**+ * The fields a NEW issue starts with.+ *+ * ONE list, because there are now two ways to make an issue — ⌘⇧I in the+ * editor and `bento.newIssue()` from an agent — and a field seeded by one but+ * not the other is a field a human then cannot set: `prop` is unlisted in the+ * / menu (blocks.ts), so the only way a value gets onto a page is that the page+ * was seeded with it. An agent-made issue missing `assignee` would be an issue+ * nobody can assign without hand-editing the JSON.+ *+ * The rest of the schema (labels, due, project) is set on demand and appears+ * when it is set — absent means unset, which is what the format already says.+ */+export const ISSUE_FIELDS = ['status', 'priority', 'assignee', 'estimate']++/** The schema in force: what the document declares, else the defaults. */+export function fieldsOf(doc: SpacesDoc): FieldSpec[] {+ const declared = (doc as { fields?: unknown }).fields+ return Array.isArray(declared) && declared.length ? (declared as FieldSpec[]) : DEFAULT_FIELDS+}++export const fieldByKey = (doc: SpacesDoc, key: string): FieldSpec | undefined =>+ fieldsOf(doc).find((f) => f.key === key)++export const optionOf = (f: FieldSpec | undefined, id: unknown): FieldOption | undefined =>+ f?.options?.find((o) => o.id === String(id))++/**+ * The readable form of a value — what goes in the block's `html`.+ *+ * Not decoration. This is the only thing an older build, a thumbnailer, a grep+ * or a markdown export can see, so it has to say what the field is as well as+ * what it holds.+ */+export function propHtml(f: FieldSpec, value: unknown): string {+ // COERCE, never assume. The schema comes out of a file someone sent you, so+ // `label` can be absent or a number — and this used to throw a TypeError+ // straight out of the public API (setField and newIssue), on exactly the+ // untrusted-file class the rest of the code is hardened against. A malformed+ // schema entry is something validate() reports; it is not something a write+ // verb should crash on. Falling back to the KEY keeps the readable form+ // readable, which is the whole job.+ const esc = (v: unknown) =>+ String(v ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ const label = typeof f?.label === 'string' && f.label ? f.label : String(f?.key ?? 'field')+ const shown =+ f.vt === 'select' ? (optionOf(f, value)?.label ?? String(value ?? ''))+ : f.vt === 'labels' ? (Array.isArray(value) ? value.join(', ') : String(value ?? ''))+ : String(value ?? '')+ return `${esc(label)}: ${esc(shown) || '—'}`+}++/** A page's field values, by key. Only `prop` blocks carry them. */+export function valuesOf(page: Page): Map<string, unknown> {+ const out = new Map<string, unknown>()+ for (const b of page.blocks) {+ if (b.type !== 'prop') continue+ const key = (b as { key?: unknown }).key+ if (typeof key === 'string' && key) out.set(key, (b as { value?: unknown }).value)+ }+ return out+}++/**+ * Is this page an ISSUE?+ *+ * It carries a status. Not a flag on the page and not a separate page type:+ * making "issue" a mode would mean a page could be the wrong kind, and would+ * put a second concept in a format whose whole shape is "a page with blocks".+ * A page with a status is an issue; remove the status and it is a document+ * again, with everything else about it intact.+ */+export const isIssue = (page: Page): boolean =>+ page.blocks.some((b) => b.type === 'prop' && (b as { key?: unknown }).key === 'status')++/** Where a page's prop blocks stop and its body begins. */+export function headerLength(page: Page): number {+ let n = 0+ while (n < page.blocks.length && page.blocks[n].type === 'prop') n+++ return n+}++/**+ * What NARROWS a view. Stored on the `view` block, so it is permanent.+ *+ * ABSENT MEANS EVERYTHING, and so does an absent key inside it. That is not a+ * default, it is the compatibility rule: every view block written before+ * filters existed carries no `filter`, and must keep showing every issue+ * forever. The same rule makes the editor DELETE the key rather than store an+ * empty object, so a view someone filtered and then unfiltered is byte-identical+ * to one that was never filtered.+ *+ * Deliberately two keys. A filter language is a thing that grows without limit+ * and can never shrink — every operator here is in files on other people's+ * disks the moment it ships — so this is the smallest pair that answers the two+ * questions a tracker is actually asked: "show me this label" and "show me what+ * is still open".+ */+export interface ViewFilter {+ /**+ * field key → the values that pass. A value THIS BUILD DOES NOT KNOW is+ * compared literally, so a filter written by a newer build still selects the+ * issues it meant instead of matching nothing.+ */+ is?: Record<string, string[]>+ /** only issues whose phase is neither done nor cancelled */+ open?: boolean+}++/** Filter keys this build can evaluate. */+const FILTER_KEYS = new Set(['is', 'open'])++/**+ * Filter keys from a NEWER build.+ *+ * They round-trip untouched, but this build cannot apply them, so the view+ * shows MORE than it should — and a count that is silently too high is exactly+ * the failure the format's additivity rule trades for. The view says so out+ * loud instead.+ */+export const unknownFilterKeys = (f: unknown): string[] =>+ f && typeof f === 'object' ? Object.keys(f).filter((k) => !FILTER_KEYS.has(k)) : []++/**+ * The field whose options declare PHASES — the one "open" is a question about.+ *+ * DERIVED FROM THE SCHEMA, never hardcoded to `status`: a document that+ * declares its own fields names its own phase field, and one that declares none+ * has no notion of open at all, in which case `open` passes everything rather+ * than emptying the board.+ */+export const phaseField = (doc: SpacesDoc): FieldSpec | undefined =>+ fieldsOf(doc).find((f) => f.options?.some((o) => o.group))++/**+ * Is this value a phase that is still going?+ *+ * An UNKNOWN value counts as open. A newer build's status must never be hidden+ * by "open only" — hiding work because this build cannot read its status is a+ * silent loss, and showing one issue too many is not.+ */+export const isOpenPhase = (f: FieldSpec | undefined, value: unknown): boolean => {+ const g = optionOf(f, value)?.group+ return g !== 'done' && g !== 'cancelled'+}++/** Does one issue pass a view's filter? */+export function passesFilter(doc: SpacesDoc, values: Map<string, unknown>, filter: unknown): boolean {+ if (!filter || typeof filter !== 'object') return true+ const f = filter as ViewFilter+ if (f.open) {+ const pf = phaseField(doc)+ if (!isOpenPhase(pf, values.get(pf?.key ?? ''))) return false+ }+ const is = f.is+ if (is && typeof is === 'object') {+ for (const key of Object.keys(is)) {+ const want = is[key]+ // an empty list is NO CONSTRAINT, not "nothing passes" — a stored empty+ // would empty the board for a reason nobody could see+ if (!Array.isArray(want) || !want.length) continue+ const v = values.get(key)+ const mine = Array.isArray(v) ? v.map(String) : [String(v ?? '')]+ if (!want.some((w) => mine.includes(String(w)))) return false+ }+ }+ return true+}++/** How many things a filter narrows by — what the Filter button counts. */+export const filterCount = (filter: unknown): number => {+ const f = (filter ?? {}) as ViewFilter+ const is = f.is && typeof f.is === 'object' ? f.is : {}+ return (f.open ? 1 : 0) + Object.keys(is).filter((k) => (is[k] ?? []).length).length+}++export interface IssueRow {+ page: Page+ values: Map<string, unknown>+}++/** Every issue in the space, in page order, archived pages excluded. */+export function issuesOf(doc: SpacesDoc): IssueRow[] {+ const out: IssueRow[] = []+ for (const page of doc.pages) {+ if (page.archived || !isIssue(page)) continue+ out.push({ page, values: valuesOf(page) })+ }+ return out+}++/** Where a dropped card lands: before a card, or after the last one. */+export interface DropAim { before?: string; after?: string }++/**+ * The page order after a card is dropped — or NULL when the drop changes+ * nothing.+ *+ * THE BOARD'S ORDER IS `doc.pages`. There is no per-view order field, and there+ * must not be one invented by a drag handler: a stored order is permanent, it+ * has to answer what happens to an issue no view has ever seen, and it can+ * disagree with the pages themselves. Reordering the pages cannot.+ *+ * Pure, and separate from the editor, because this is the arithmetic that is+ * easy to get wrong: the anchor is a page ID rather than an index precisely+ * because the index moves under the splice that removes the dragged page. The+ * null return is what keeps a drag that went nowhere out of the undo stack.+ */+export function reorderPages(pages: Page[], pageId: string, aim: DropAim): Page[] | null {+ const from = pages.findIndex((p) => p.id === pageId)+ const anchor = aim.before ?? aim.after+ if (from < 0 || !anchor) return null+ // already exactly there+ if (aim.before ? pages[from + 1]?.id === aim.before : pages[from - 1]?.id === aim.after) return null+ const next = pages.slice()+ const [moved] = next.splice(from, 1)+ // The anchor is looked up AFTER the removal, so the index is the one the+ // insert needs. It also covers dropping a card on itself: the anchor is the+ // page just removed, so it is not found and nothing moves.+ const at = next.findIndex((p) => p.id === anchor)+ if (at < 0) return null+ next.splice(aim.before ? at : at + 1, 0, moved)+ return next+}++/** One page's value block for a field, if it has one. */+export const propBlockOf = (page: Page, key: string): Block | undefined =>+ page.blocks.find((b) => b.type === 'prop' && (b as { key?: unknown }).key === key)++/** Build a prop block, with its readable form already in step. */+export function propBlock(f: FieldSpec, value: unknown, id: string): Block {+ return { id, type: 'prop', key: f.key, value, html: propHtml(f, value) } as Block+}++/**+ * Would this drop change the order the user can actually SEE?+ *+ * `reorderPages` compares adjacency in `doc.pages`, and page order is not+ * column order: a board with two columns interleaves them, so a card dropped+ * back into its own slot is NOT adjacent to itself in the page array. Measured:+ * pages [board,i1,i2,i3,i4,i5] with i1,i3,i5 in one column — dropping i1 where+ * it already sat returned a reordered array, so a gesture that visibly did+ * nothing wrote to the document, took an undo entry, set the dirty flag, and+ * visibly reshuffled the SIDEBAR, because board order is sidebar order.+ *+ * The rig missed it because its fixture had one column, which is the only+ * shape where the two orders coincide.+ *+ * `cards` is the column's card ids in the order they are drawn, INCLUDING the+ * dragged one. The answer is about the column, because the column is the only+ * order the gesture was about.+ */+export function columnMoves(cards: string[], moved: string, aim: DropAim): boolean {+ const at = cards.indexOf(moved)+ if (at < 0) return true // it is arriving from elsewhere+ const rest = cards.filter((id) => id !== moved)+ const target = aim.before+ ? rest.indexOf(aim.before)+ : aim.after ? rest.indexOf(aim.after) + 1 : rest.length+ if (target < 0) return true+ const next = [...rest.slice(0, target), moved, ...rest.slice(target)]+ return next.join('\u001f') !== cards.join('\u001f')+}diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.tsindex 38b6d8cc..dbb97ed6 100644--- a/spaces/src/i18n/de.ts+++ b/spaces/src/i18n/de.ts@@ -11,6 +11,7 @@import type { Catalog } from '../i18n'export const de: Catalog = {+ "A filter here is newer than this build and was not applied.": "Ein Filter dieser Ansicht ist neuer als diese Version und wurde nicht angewendet.","A list of every page, in order": "Eine Liste aller Seiten, der Reihe nach","A page cannot contain itself": "Eine Seite kann sich nicht selbst enthalten","A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "Ein Passwort verschlüsselt das Dokument in der Datei. Es gibt keine Wiederherstellung — verlierst du es, ist der Space weg.",@@ -27,10 +28,12 @@ export const de: Catalog = {"Caution": "Achtung","Change the kind of callout": "Art des Hinweisfelds ändern","Change this page's icon": "Symbol dieser Seite ändern",+ "Change {field}": "{field} ändern","Check for updates": "Nach Updates suchen","Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "Die Prüfung ist manuell und verifiziert: Der Download ist signiert, und seine Signatur wird gegen einen Schlüssel in dieser Datei geprüft, bevor irgendetwas überschrieben wird.","Checking…": "Prüfe…","Choose a password. There is no way to recover it.": "Wähle ein Passwort. Es lässt sich nicht wiederherstellen.",+ "Clear filter": "Filter zurücksetzen","Close": "Schließen","Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "Zugeklappte Toggle-Blöcke werden immer offen gedruckt. Im Druckdialog deines Browsers gibt es die Option „Als PDF speichern“.","Contents": "Inhalt",@@ -54,6 +57,7 @@ export const de: Catalog = {"Export as Markdown": "Als Markdown exportieren","Export as Markdown…": "Als Markdown exportieren…","File": "Datei",+ "Filter": "Filtern","Filter blocks…": "Blöcke filtern…","Find": "Suchen","Find in this space…": "In diesem Space suchen…",@@ -77,10 +81,12 @@ export const de: Catalog = {"New page inside": "Neue Unterseite","Next (⏎)": "Weiter (⏎)","No block matches": "Kein Block passt",+ "No issues match this filter.": "Keine Issues entsprechen diesem Filter.","No pages yet": "Noch keine Seiten","Note": "Hinweis","Nothing found": "Nichts gefunden","Off by default — they were archived for a reason": "Standardmäßig aus — sie wurden aus einem Grund archiviert",+ "Open only": "Nur offene","Other ways to save": "Weitere Speicheroptionen","Out of the sidebar, still searchable and linkable": "Weg aus der Seitenleiste, weiterhin auffindbar und verlinkbar","Page options": "Seiten-Optionen",@@ -223,4 +229,12 @@ export const de: Catalog = {"Move down": "Nach unten","Duplicate": "Duplizieren","Delete": "Löschen",+ "New issue": "Neues Issue",+ "Make this page an issue": "Diese Seite zu einem Issue machen",+ "Adds status, priority, assignee, estimate": "Fügt Status, Priorität, Bearbeiter:in und Schätzung hinzu",+ "Already an issue": "Ist bereits ein Issue",+ "Now an issue": "Jetzt ein Issue",+ "Issues": "Issues",+ "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.",+ "Other": "Sonstige",}diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.tsindex d005ec19..f0fe115a 100644--- a/spaces/src/i18n/es.ts+++ b/spaces/src/i18n/es.ts@@ -11,6 +11,7 @@import type { Catalog } from '../i18n'export const es: Catalog = {+ "A filter here is newer than this build and was not applied.": "Un filtro de esta vista es más reciente que esta versión y no se ha aplicado.","A list of every page, in order": "Una lista de todas las páginas, en orden","A page cannot contain itself": "Una página no puede contenerse a sí misma","A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "Una contraseña cifra el documento dentro del archivo. No hay forma de recuperarla — si la pierdes, el espacio desaparece.",@@ -27,10 +28,12 @@ export const es: Catalog = {"Caution": "Precaución","Change the kind of callout": "Cambiar el tipo de aviso","Change this page's icon": "Cambiar el icono de esta página",+ "Change {field}": "Cambiar {field}","Check for updates": "Buscar actualizaciones","Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "La comprobación es manual y verificada: la descarga va firmada y su firma se contrasta con una clave que está dentro de este archivo antes de reescribir nada.","Checking…": "Comprobando…","Choose a password. There is no way to recover it.": "Elige una contraseña. No hay forma de recuperarla.",+ "Clear filter": "Borrar el filtro","Close": "Cerrar","Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "Los desplegables plegados siempre se imprimen abiertos. El diálogo de impresión de tu navegador tiene la opción «Guardar como PDF».","Contents": "Índice",@@ -54,6 +57,7 @@ export const es: Catalog = {"Export as Markdown": "Exportar como Markdown","Export as Markdown…": "Exportar como Markdown…","File": "Archivo",+ "Filter": "Filtrar","Filter blocks…": "Filtrar bloques…","Find": "Buscar","Find in this space…": "Buscar en este espacio…",@@ -77,10 +81,12 @@ export const es: Catalog = {"New page inside": "Nueva página dentro","Next (⏎)": "Siguiente (⏎)","No block matches": "Ningún bloque coincide",+ "No issues match this filter.": "Ninguna incidencia coincide con este filtro.","No pages yet": "Aún no hay páginas","Note": "Nota","Nothing found": "Sin resultados","Off by default — they were archived for a reason": "Desactivado por defecto — por algo se archivaron",+ "Open only": "Solo abiertas","Other ways to save": "Otras formas de guardar","Out of the sidebar, still searchable and linkable": "Fuera de la barra lateral, pero aún se puede buscar y enlazar","Page options": "Opciones de la página",@@ -223,4 +229,12 @@ export const es: Catalog = {"Move down": "Bajar","Duplicate": "Duplicar","Delete": "Eliminar",+ "New issue": "Nueva incidencia",+ "Make this page an issue": "Convertir esta página en incidencia",+ "Adds status, priority, assignee, estimate": "Añade estado, prioridad, responsable y estimación",+ "Already an issue": "Ya es una incidencia",+ "Now an issue": "Ahora es una incidencia",+ "Issues": "Incidencias",+ "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í.",+ "Other": "Otras",}diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.tsindex 81cde408..11159c05 100644--- a/spaces/src/i18n/fr.ts+++ b/spaces/src/i18n/fr.ts@@ -11,6 +11,7 @@import type { Catalog } from '../i18n'export const fr: Catalog = {+ "A filter here is newer than this build and was not applied.": "Un filtre de cette vue est plus récent que cette version et n’a pas été appliqué.","A list of every page, in order": "La liste de toutes les pages, dans l’ordre","A page cannot contain itself": "Une page ne peut pas se contenir elle-même","A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "Un mot de passe chiffre le document à l’intérieur du fichier. Il n’y a aucune récupération — perdez-le et l’espace est perdu.",@@ -27,10 +28,12 @@ export const fr: Catalog = {"Caution": "Attention","Change the kind of callout": "Changer le type d'encadré","Change this page's icon": "Changer l’icône de cette page",+ "Change {field}": "Modifier {field}","Check for updates": "Rechercher des mises à jour","Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "La vérification est manuelle et contrôlée : le téléchargement est signé, et sa signature est vérifiée avec une clé contenue dans ce fichier avant toute réécriture.","Checking…": "Vérification…","Choose a password. There is no way to recover it.": "Choisissez un mot de passe. Il est impossible de le récupérer.",+ "Clear filter": "Effacer le filtre","Close": "Fermer","Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "Les bascules repliées s’impriment toujours dépliées. La boîte d’impression de votre navigateur propose « Enregistrer au format PDF ».","Contents": "Sommaire",@@ -54,6 +57,7 @@ export const fr: Catalog = {"Export as Markdown": "Exporter en Markdown","Export as Markdown…": "Exporter en Markdown…","File": "Fichier",+ "Filter": "Filtrer","Filter blocks…": "Filtrer les blocs…","Find": "Rechercher","Find in this space…": "Rechercher dans cet espace…",@@ -77,10 +81,12 @@ export const fr: Catalog = {"New page inside": "Nouvelle page à l’intérieur","Next (⏎)": "Suivant (⏎)","No block matches": "Aucun bloc correspondant",+ "No issues match this filter.": "Aucun ticket ne correspond à ce filtre.","No pages yet": "Aucune page pour l’instant","Note": "Note","Nothing found": "Aucun résultat","Off by default — they were archived for a reason": "Désactivé par défaut — elles ont été archivées pour une raison",+ "Open only": "Ouverts seulement","Other ways to save": "Autres façons d’enregistrer","Out of the sidebar, still searchable and linkable": "Hors de la barre latérale, toujours dans la recherche et les liens","Page options": "Options de la page",@@ -223,4 +229,12 @@ export const fr: Catalog = {"Move down": "Descendre","Duplicate": "Dupliquer","Delete": "Supprimer",+ "New issue": "Nouveau ticket",+ "Make this page an issue": "Transformer cette page en ticket",+ "Adds status, priority, assignee, estimate": "Ajoute statut, priorité, responsable et estimation",+ "Already an issue": "Déjà un ticket",+ "Now an issue": "C’est désormais un ticket",+ "Issues": "Tickets",+ "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.",+ "Other": "Autres",}diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.tsindex 4eb7de14..d151f854 100644--- a/spaces/src/i18n/it.ts+++ b/spaces/src/i18n/it.ts@@ -11,6 +11,7 @@import type { Catalog } from '../i18n'export const it: Catalog = {+ "A filter here is newer than this build and was not applied.": "Un filtro di questa vista è più recente di questa versione e non è stato applicato.","A list of every page, in order": "Un elenco di tutte le pagine, in ordine","A page cannot contain itself": "Una pagina non può contenere sé stessa","A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "Una password cifra il documento dentro il file. Non c’è modo di recuperarla — se la perdi, lo spazio è perso.",@@ -27,10 +28,12 @@ export const it: Catalog = {"Caution": "Attenzione","Change the kind of callout": "Cambia il tipo di riquadro","Change this page's icon": "Cambia l’icona di questa pagina",+ "Change {field}": "Cambia {field}","Check for updates": "Cerca aggiornamenti","Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "La verifica è manuale e controllata: il download è firmato e la sua firma viene confrontata con una chiave contenuta in questo file prima che qualcosa venga riscritto.","Checking…": "Verifica in corso…","Choose a password. There is no way to recover it.": "Scegli una password. Non c’è modo di recuperarla.",+ "Clear filter": "Azzera il filtro","Close": "Chiudi","Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "I blocchi comprimibili chiusi vengono sempre stampati aperti. La finestra di stampa del browser offre l’opzione «Salva come PDF».","Contents": "Indice",@@ -54,6 +57,7 @@ export const it: Catalog = {"Export as Markdown": "Esporta come Markdown","Export as Markdown…": "Esporta come Markdown…","File": "File",+ "Filter": "Filtra","Filter blocks…": "Filtra i blocchi…","Find": "Trova","Find in this space…": "Trova in questo spazio…",@@ -77,10 +81,12 @@ export const it: Catalog = {"New page inside": "Nuova pagina interna","Next (⏎)": "Successivo (⏎)","No block matches": "Nessun blocco corrisponde",+ "No issues match this filter.": "Nessuna issue corrisponde a questo filtro.","No pages yet": "Ancora nessuna pagina","Note": "Nota","Nothing found": "Nessun risultato","Off by default — they were archived for a reason": "Disattivo per impostazione predefinita — sono state archiviate per un motivo",+ "Open only": "Solo aperte","Other ways to save": "Altri modi per salvare","Out of the sidebar, still searchable and linkable": "Fuori dalla barra laterale, ma sempre ricercabile e collegabile","Page options": "Opzioni della pagina",@@ -223,4 +229,12 @@ export const it: Catalog = {"Move down": "Sposta giù","Duplicate": "Duplica","Delete": "Elimina",+ "New issue": "Nuova issue",+ "Make this page an issue": "Trasforma questa pagina in una issue",+ "Adds status, priority, assignee, estimate": "Aggiunge stato, priorità, assegnatario e stima",+ "Already an issue": "È già una issue",+ "Now an issue": "Ora è una issue",+ "Issues": "Issue",+ "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.",+ "Other": "Altre",}diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.tsindex 8a8e7820..e5473bdf 100644--- a/spaces/src/i18n/ja.ts+++ b/spaces/src/i18n/ja.ts@@ -11,6 +11,7 @@import type { Catalog } from '../i18n'export const ja: Catalog = {+ "A filter here is newer than this build and was not applied.": "このビューには、このバージョンより新しいフィルターがあり、適用されていません。","A list of every page, in order": "すべてのページを順番に並べた一覧","A page cannot contain itself": "ページを自分自身に入れることはできません","A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "パスワードはファイル内のドキュメントを暗号化します。復元手段はありません — 忘れたらこのスペースは失われます。",@@ -27,10 +28,12 @@ export const ja: Catalog = {"Caution": "注意","Change the kind of callout": "囲みの種類を変更","Change this page's icon": "このページのアイコンを変更",+ "Change {field}": "{field}を変更","Check for updates": "更新を確認","Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "確認は手動で、検証も行われます。ダウンロードには署名があり、何かを書き換える前にこのファイル内の鍵で署名を照合します。","Checking…": "確認中…","Choose a password. There is no way to recover it.": "パスワードを決めてください。復元する方法はありません。",+ "Clear filter": "フィルターを解除","Close": "閉じる","Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "折りたたんだトグルも印刷では必ず開いた状態になります。「PDF として保存」はブラウザの印刷ダイアログにあります。","Contents": "目次",@@ -54,6 +57,7 @@ export const ja: Catalog = {"Export as Markdown": "Markdown で書き出す","Export as Markdown…": "Markdown で書き出す…","File": "ファイル",+ "Filter": "フィルター","Filter blocks…": "ブロックを絞り込む…","Find": "検索","Find in this space…": "このスペース内を検索…",@@ -77,10 +81,12 @@ export const ja: Catalog = {"New page inside": "この中に新規ページ","Next (⏎)": "次へ (⏎)","No block matches": "一致するブロックがありません",+ "No issues match this filter.": "この条件に一致するイシューはありません。","No pages yet": "ページがまだありません","Note": "メモ","Nothing found": "見つかりませんでした","Off by default — they were archived for a reason": "既定ではオフ — アーカイブしたのには理由があります",+ "Open only": "未完了のみ","Other ways to save": "その他の保存方法","Out of the sidebar, still searchable and linkable": "サイドバーから外れますが、検索もリンクもできます","Page options": "ページのオプション",@@ -223,4 +229,12 @@ export const ja: Catalog = {"Move down": "下へ移動","Duplicate": "複製","Delete": "削除",+ "New issue": "新しいイシュー",+ "Make this page an issue": "このページをイシューにする",+ "Adds status, priority, assignee, estimate": "ステータス・優先度・担当者・見積もりを追加します",+ "Already an issue": "すでにイシューです",+ "Now an issue": "イシューになりました",+ "Issues": "イシュー",+ "No issues yet. Add a status field to any page and it appears here.": "まだイシューはありません。どれかのページにステータス項目を追加すると、ここに表示されます。",+ "Other": "その他",}diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.tsindex 8d1d08e6..7a00732c 100644--- a/spaces/src/i18n/packed.ts+++ b/spaces/src/i18n/packed.ts@@ -12,6 +12,7 @@export const PACKED_LOCALES = ["ja","zh-Hans","zh-Hant","es","fr","de","it","pt"] as constexport const PACKED: Record<string, ReadonlyArray<string | 0>> = {+ "A filter here is newer than this build and was not applied.": ["このビューには、このバージョンより新しいフィルターがあり、適用されていません。","此视图中有比当前版本更新的筛选条件,未被应用。","此檢視中有比目前版本更新的篩選條件,未被套用。","Un filtro de esta vista es más reciente que esta versión y no se ha aplicado.","Un filtre de cette vue est plus récent que cette version et n’a pas été appliqué.","Ein Filter dieser Ansicht ist neuer als diese Version und wurde nicht angewendet.","Un filtro di questa vista è più recente di questa versione e non è stato applicato.","Um filtro desta vista é mais recente do que esta versão e não foi aplicado."],"A folder of .md files becomes pages, with the folder tree and the [[wikilinks]] intact.": ["「.md」ファイルのフォルダーがページになります。フォルダー階層も [[ウィキリンク]] もそのままです。","一个装满 .md 文件的文件夹会变成页面,文件夹层级和 [[wiki 链接]] 都保留下来。","一個裝滿 .md 檔案的資料夾會變成頁面,資料夾層級和 [[wiki 連結]] 都會保留。","Una carpeta de archivos .md se convierte en páginas, con el árbol de carpetas y los [[wikilinks]] intactos.","Un dossier de fichiers .md devient des pages, avec l’arborescence et les [[wikilinks]] intacts.","Ein Ordner voller .md-Dateien wird zu Seiten — samt Ordnerbaum und den [[Wikilinks]] dazwischen.","Una cartella di file .md diventa pagine, con l’albero delle cartelle e i [[wikilink]] intatti.","Uma pasta de ficheiros .md transforma-se em páginas, com a árvore de pastas e os [[wikilinks]] intactos."],"A list of every page, in order": ["すべてのページを順番に並べた一覧","按顺序列出的所有页面","依順序列出每一個頁面","Una lista de todas las páginas, en orden","La liste de toutes les pages, dans l’ordre","Eine Liste aller Seiten, der Reihe nach","Un elenco di tutte le pagine, in ordine","Uma lista de todas as páginas, por ordem"],"A page cannot contain itself": ["ページを自分自身に入れることはできません","页面不能包含自身","頁面不能包含自己","Una página no puede contenerse a sí misma","Une page ne peut pas se contenir elle-même","Eine Seite kann sich nicht selbst enthalten","Una pagina non può contenere sé stessa","Uma página não pode conter-se a si própria"],@@ -23,6 +24,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"About this space": ["このスペースについて","关于此空间","關於此空間","Acerca de este espacio","À propos de cet espace","Über diesen Space","Informazioni su questo spazio","Sobre este espaço"],"Add a block below": ["下にブロックを追加","在下方添加块","在下方新增區塊","Añadir un bloque debajo","Ajouter un bloc en dessous","Block darunter hinzufügen","Aggiungi un blocco sotto","Adicionar um bloco abaixo"],"Add below": ["下に追加","在下方添加","在下方新增","Añadir debajo","Ajouter en dessous","Darunter einfügen","Aggiungi sotto","Adicionar abaixo"],+ "Adds status, priority, assignee, estimate": ["ステータス・優先度・担当者・見積もりを追加します","添加状态、优先级、负责人和估算","新增狀態、優先順序、負責人與估算","Añade estado, prioridad, responsable y estimación","Ajoute statut, priorité, responsable et estimation","Fügt Status, Priorität, Bearbeiter:in und Schätzung hinzu","Aggiunge stato, priorità, assegnatario e stima","Adiciona estado, prioridade, responsável e estimativa"],+ "Already an issue": ["すでにイシューです","已经是事项","已經是項目","Ya es una incidencia","Déjà un ticket","Ist bereits ein Issue","È già una issue","Já é uma tarefa"],"Archive": ["アーカイブ","归档","封存","Archivar","Archiver","Archivieren","Archivia","Arquivar"],"Archived ({n})": ["アーカイブ済み({n})","已归档 ({n})","已封存 ({n})","Archivadas ({n})","Archivées ({n})","Archiviert ({n})","Archiviate ({n})","Arquivadas ({n})"],"Block options": ["ブロックのオプション","块选项","區塊選項","Opciones del bloque","Options du bloc","Block-Optionen","Opzioni del blocco","Opções do bloco"],@@ -33,12 +36,14 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Change the kind of callout": ["囲みの種類を変更","更改标注类型","變更標註類型","Cambiar el tipo de aviso","Changer le type d'encadré","Art des Hinweisfelds ändern","Cambia il tipo di riquadro","Alterar o tipo de destaque"],"Change this block’s type": ["このブロックの種類を変更します","更改此块的类型","變更此區塊的類型","Cambiar el tipo de este bloque","Changer le type de ce bloc","Den Typ dieses Blocks ändern","Cambia il tipo di questo blocco","Alterar o tipo deste bloco"],"Change this page's icon": ["このページのアイコンを変更","更改此页面的图标","變更此頁面的圖示","Cambiar el icono de esta página","Changer l’icône de cette page","Symbol dieser Seite ändern","Cambia l’icona di questa pagina","Mudar o ícone desta página"],+ "Change {field}": ["{field}を変更","更改{field}","變更{field}","Cambiar {field}","Modifier {field}","{field} ändern","Cambia {field}","Alterar {field}"],"Check for updates": ["更新を確認","检查更新","檢查更新","Buscar actualizaciones","Rechercher des mises à jour","Nach Updates suchen","Cerca aggiornamenti","Verificar atualizações"],"Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": ["確認は手動で、検証も行われます。ダウンロードには署名があり、何かを書き換える前にこのファイル内の鍵で署名を照合します。","检查更新完全由你手动发起,并且经过验证:下载内容带有签名,改写任何内容之前,都会先用此文件内的密钥校验签名。","檢查是手動且經過驗證的:下載的檔案帶有簽章,在改寫任何內容之前,都會用此檔案內的金鑰驗證該簽章。","La comprobación es manual y verificada: la descarga va firmada y su firma se contrasta con una clave que está dentro de este archivo antes de reescribir nada.","La vérification est manuelle et contrôlée : le téléchargement est signé, et sa signature est vérifiée avec une clé contenue dans ce fichier avant toute réécriture.","Die Prüfung ist manuell und verifiziert: Der Download ist signiert, und seine Signatur wird gegen einen Schlüssel in dieser Datei geprüft, bevor irgendetwas überschrieben wird.","La verifica è manuale e controllata: il download è firmato e la sua firma viene confrontata con una chiave contenuta in questo file prima che qualcosa venga riscritto.","A verificação é manual e comprovada: a transferência é assinada e a sua assinatura é validada com uma chave dentro deste ficheiro antes de qualquer coisa ser reescrita."],"Checking…": ["確認中…","检查中…","檢查中…","Comprobando…","Vérification…","Prüfe…","Verifica in corso…","A verificar…"],"Choose .md files…": [".md ファイルを選ぶ…","选择 .md 文件…","選擇 .md 檔案…","Elegir archivos .md…","Choisir des fichiers .md…",".md-Dateien wählen…","Scegli file .md…","Escolher ficheiros .md…"],"Choose a folder…": ["フォルダーを選ぶ…","选择文件夹…","選擇資料夾…","Elegir una carpeta…","Choisir un dossier…","Ordner wählen…","Scegli una cartella…","Escolher uma pasta…"],"Choose a password. There is no way to recover it.": ["パスワードを決めてください。復元する方法はありません。","设置一个密码。它无法找回。","請設定密碼。沒有任何方法可以找回它。","Elige una contraseña. No hay forma de recuperarla.","Choisissez un mot de passe. Il est impossible de le récupérer.","Wähle ein Passwort. Es lässt sich nicht wiederherstellen.","Scegli una password. Non c’è modo di recuperarla.","Escolha uma palavra-passe. Não há forma de a recuperar."],+ "Clear filter": ["フィルターを解除","清除筛选","清除篩選","Borrar el filtro","Effacer le filtre","Filter zurücksetzen","Azzera il filtro","Limpar o filtro"],"Close": ["閉じる","关闭","關閉","Cerrar","Fermer","Schließen","Chiudi","Fechar"],"Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": ["折りたたんだトグルも印刷では必ず開いた状態になります。「PDF として保存」はブラウザの印刷ダイアログにあります。","折叠起来的折叠块打印时一律展开。浏览器的打印对话框里有“存为 PDF”选项。","收合的摺疊區塊列印時一律展開。「另存為 PDF」的選項在瀏覽器的列印對話方塊中。","Los desplegables plegados siempre se imprimen abiertos. El diálogo de impresión de tu navegador tiene la opción «Guardar como PDF».","Les bascules repliées s’impriment toujours dépliées. La boîte d’impression de votre navigateur propose « Enregistrer au format PDF ».","Zugeklappte Toggle-Blöcke werden immer offen gedruckt. Im Druckdialog deines Browsers gibt es die Option „Als PDF speichern“.","I blocchi comprimibili chiusi vengono sempre stampati aperti. La finestra di stampa del browser offre l’opzione «Salva come PDF».","Os blocos recolhidos são sempre impressos abertos. A janela de impressão do navegador tem a opção \"Guardar como PDF\"."],"Contents": ["目次","目录","目錄","Índice","Sommaire","Inhalt","Indice","Índice"],@@ -67,6 +72,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Export as Markdown": ["Markdown で書き出す","导出为 Markdown","匯出為 Markdown","Exportar como Markdown","Exporter en Markdown","Als Markdown exportieren","Esporta come Markdown","Exportar como Markdown"],"Export as Markdown…": ["Markdown で書き出す…","导出为 Markdown…","匯出為 Markdown…","Exportar como Markdown…","Exporter en Markdown…","Als Markdown exportieren…","Esporta come Markdown…","Exportar como Markdown…"],"File": ["ファイル","文件","檔案","Archivo","Fichier","Datei","File","Ficheiro"],+ "Filter": ["フィルター","筛选","篩選","Filtrar","Filtrer","Filtern","Filtra","Filtrar"],"Filter blocks…": ["ブロックを絞り込む…","筛选块…","篩選區塊…","Filtrar bloques…","Filtrer les blocs…","Blöcke filtern…","Filtra i blocchi…","Filtrar blocos…"],"Find": ["検索","查找","尋找","Buscar","Rechercher","Suchen","Trova","Localizar"],"Find in this space…": ["このスペース内を検索…","在此空间中查找…","在此空間尋找…","Buscar en este espacio…","Rechercher dans cet espace…","In diesem Space suchen…","Trova in questo spazio…","Localizar neste espaço…"],@@ -88,6 +94,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Insert": ["挿入","插入","插入","Insertar","Insérer","Einfügen","Inserisci","Inserir"],"Insert a block — text, headings, lists, code, images": ["ブロックを挿入 — テキスト、見出し、リスト、コード、画像","插入块 — 文本、标题、列表、代码、图片","插入區塊 — 文字、標題、清單、程式碼、圖片","Insertar un bloque — texto, encabezados, listas, código, imágenes","Insérer un bloc — texte, titres, listes, code, images","Block einfügen — Text, Überschriften, Listen, Code, Bilder","Inserisci un blocco — testo, titoli, elenchi, codice, immagini","Inserir um bloco — texto, títulos, listas, código, imagens"],"Interface language": ["表示言語","界面语言","介面語言","Idioma de la interfaz","Langue de l’interface","Sprache der Oberfläche","Lingua dell’interfaccia","Idioma da interface"],+ "Issues": ["イシュー","事项","項目","Incidencias","Tickets","Issues","Issue","Tarefas"],"Language": ["言語","语言","語言","Idioma","Langue","Sprache","Lingua","Idioma"],"Language follows whoever opens the file. It is never written into the document.": ["言語はファイルを開いた人に従います。ドキュメントには書き込まれません。","语言跟随打开文件的人,绝不会写入文档。","語言取決於開啟檔案的人,永遠不會寫入文件中。","El idioma sigue a quien abre el archivo. Nunca se escribe en el documento.","La langue suit la personne qui ouvre le fichier. Elle n’est jamais écrite dans le document.","Die Sprache richtet sich danach, wer die Datei öffnet. Sie wird nie ins Dokument geschrieben.","La lingua segue chi apre il file. Non viene mai scritta nel documento.","O idioma segue quem abre o ficheiro. Nunca é escrito no documento."],"Language — what this block is highlighted as": ["言語 — このブロックを何として色分けするか","语言 — 这个块按什么语言着色","語言 — 這個區塊以什麼語言上色","Lenguaje — cómo se colorea este bloque","Langage — la coloration de ce bloc","Sprache — wie dieser Block hervorgehoben wird","Linguaggio — come viene evidenziato questo blocco","Linguagem — como este bloco é realçado"],@@ -96,20 +103,27 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Linked from": ["リンク元","链接来源","連結來源","Enlazado desde","Liens entrants","Verlinkt von","Collegata da","Ligado a partir de"],"Links to it become dead": ["このページへのリンクが切れます","指向它的链接会失效","指向它的連結會失效","Los enlaces a ella dejan de funcionar","Les liens vers elle seront rompus","Links darauf laufen ins Leere","I collegamenti a questa pagina si interrompono","As ligações para ela ficam quebradas"],"Load this image": ["この画像を読み込む","加载此图片","載入此圖片","Cargar esta imagen","Charger cette image","Dieses Bild laden","Carica questa immagine","Carregar esta imagem"],+ "Make this page an issue": ["このページをイシューにする","将此页面变为事项","將此頁面變為項目","Convertir esta página en incidencia","Transformer cette page en ticket","Diese Seite zu einem Issue machen","Trasforma questa pagina in una issue","Transformar esta página numa tarefa"],"More": ["その他","更多","更多","Más","Plus","Mehr","Altro","Mais"],"Move down": ["下へ移動","下移","下移","Bajar","Descendre","Nach unten","Sposta giù","Mover para baixo"],"Move up": ["上へ移動","上移","上移","Subir","Monter","Nach oben","Sposta su","Mover para cima"],+ "New issue": ["新しいイシュー","新建事项","新增項目","Nueva incidencia","Nouveau ticket","Neues Issue","Nuova issue","Nova tarefa"],"New page": ["新規ページ","新建页面","新增頁面","Nueva página","Nouvelle page","Neue Seite","Nuova pagina","Nova página"],"New page (⌘⌥N)": ["新規ページ (⌘⌥N)","新建页面 (⌘⌥N)","新增頁面 (⌘⌥N)","Nueva página (⌘⌥N)","Nouvelle page (⌘⌥N)","Neue Seite (⌘⌥N)","Nuova pagina (⌘⌥N)","Nova página (⌘⌥N)"],"New page inside": ["この中に新規ページ","在其中新建页面","在其中新增頁面","Nueva página dentro","Nouvelle page à l’intérieur","Neue Unterseite","Nuova pagina interna","Nova página dentro desta"],"Next (⏎)": ["次へ (⏎)","下一个 (⏎)","下一個 (⏎)","Siguiente (⏎)","Suivant (⏎)","Weiter (⏎)","Successivo (⏎)","Seguinte (⏎)"],"No Markdown files in that selection": ["選択に Markdown ファイルがありません","所选内容里没有 Markdown 文件","所選項目中沒有 Markdown 檔案","No hay archivos Markdown en esa selección","Aucun fichier Markdown dans cette sélection","Keine Markdown-Dateien in dieser Auswahl","Nessun file Markdown in questa selezione","Não há ficheiros Markdown nessa seleção"],"No block matches": ["一致するブロックがありません","没有匹配的块","沒有符合的區塊","Ningún bloque coincide","Aucun bloc correspondant","Kein Block passt","Nessun blocco corrisponde","Nenhum bloco corresponde"],+ "No issues match this filter.": ["この条件に一致するイシューはありません。","没有符合此筛选条件的事项。","沒有符合此篩選條件的項目。","Ninguna incidencia coincide con este filtro.","Aucun ticket ne correspond à ce filtre.","Keine Issues entsprechen diesem Filter.","Nessuna issue corrisponde a questo filtro.","Nenhuma tarefa corresponde a este filtro."],+ "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í.","Aucun ticket pour l’instant. Ajoutez un champ statut à une page et elle apparaîtra ici.","Noch keine Issues. Gib einer Seite ein Status-Feld, dann erscheint sie hier.","Ancora nessuna issue. Aggiungi un campo stato a una pagina e comparirà qui.","Ainda não há tarefas. Adiciona um campo de estado a qualquer página e ela aparece aqui."],"No pages yet": ["ページがまだありません","还没有页面","尚無頁面","Aún no hay páginas","Aucune page pour l’instant","Noch keine Seiten","Ancora nessuna pagina","Ainda sem páginas"],"Not loaded — opening it would tell that site you opened this space.": ["未読み込み — 読み込むと、このスペースを開いたことがそのサイトに伝わります。","未加载 — 加载会让该网站知道你打开了这个空间。","未載入 — 載入會讓該網站知道你開啟了這個空間。","No cargada: al cargarla, ese sitio sabría que has abierto este espacio.","Non chargée : la charger indiquerait à ce site que vous avez ouvert cet espace.","Nicht geladen — beim Laden erfährt diese Website, dass du diesen Space geöffnet hast.","Non caricata: caricarla direbbe a quel sito che hai aperto questo spazio.","Não carregada — carregá-la diria a esse site que você abriu este espaço."],"Note": ["メモ","备注","備註","Nota","Note","Hinweis","Nota","Nota"],"Nothing found": ["見つかりませんでした","没有结果","找不到結果","Sin resultados","Aucun résultat","Nichts gefunden","Nessun risultato","Nada encontrado"],+ "Now an issue": ["イシューになりました","现在是事项了","現在是項目了","Ahora es una incidencia","C’est désormais un ticket","Jetzt ein Issue","Ora è una issue","Agora é uma tarefa"],"Off by default — they were archived for a reason": ["既定ではオフ — アーカイブしたのには理由があります","默认关闭 — 当初归档总是有原因的","預設關閉 — 它們被封存是有原因的","Desactivado por defecto — por algo se archivaron","Désactivé par défaut — elles ont été archivées pour une raison","Standardmäßig aus — sie wurden aus einem Grund archiviert","Disattivo per impostazione predefinita — sono state archiviate per un motivo","Desativado por predefinição — foram arquivadas por alguma razão"],+ "Open only": ["未完了のみ","仅未完成","僅未完成","Solo abiertas","Ouverts seulement","Nur offene","Solo aperte","Apenas em aberto"],+ "Other": ["その他","其他","其他","Otras","Autres","Sonstige","Altre","Outras"],"Other ways to save": ["その他の保存方法","其他保存方式","其他儲存方式","Otras formas de guardar","Autres façons d’enregistrer","Weitere Speicheroptionen","Altri modi per salvare","Outras formas de guardar"],"Out of the sidebar, still searchable and linkable": ["サイドバーから外れますが、検索もリンクもできます","移出侧边栏,仍可搜索和链接","移出側邊欄,仍可搜尋與連結","Fuera de la barra lateral, pero aún se puede buscar y enlazar","Hors de la barre latérale, toujours dans la recherche et les liens","Weg aus der Seitenleiste, weiterhin auffindbar und verlinkbar","Fuori dalla barra laterale, ma sempre ricercabile e collegabile","Fora da barra lateral, mas continua pesquisável e ligável"],"Page options": ["ページのオプション","页面选项","頁面選項","Opciones de la página","Options de la page","Seiten-Optionen","Opzioni della pagina","Opções da página"],diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.tsindex f4d29398..4ad58dd4 100644--- a/spaces/src/i18n/pt.ts+++ b/spaces/src/i18n/pt.ts@@ -11,6 +11,7 @@import type { Catalog } from '../i18n'export const pt: Catalog = {+ "A filter here is newer than this build and was not applied.": "Um filtro desta vista é mais recente do que esta versão e não foi aplicado.","A list of every page, in order": "Uma lista de todas as páginas, por ordem","A page cannot contain itself": "Uma página não pode conter-se a si própria","A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "Uma palavra-passe encripta o documento dentro do ficheiro. Não há recuperação — se a perder, o espaço desaparece.",@@ -27,10 +28,12 @@ export const pt: Catalog = {"Caution": "Cuidado","Change the kind of callout": "Alterar o tipo de destaque","Change this page's icon": "Mudar o ícone desta página",+ "Change {field}": "Alterar {field}","Check for updates": "Verificar atualizações","Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "A verificação é manual e comprovada: a transferência é assinada e a sua assinatura é validada com uma chave dentro deste ficheiro antes de qualquer coisa ser reescrita.","Checking…": "A verificar…","Choose a password. There is no way to recover it.": "Escolha uma palavra-passe. Não há forma de a recuperar.",+ "Clear filter": "Limpar o filtro","Close": "Fechar","Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "Os blocos recolhidos são sempre impressos abertos. A janela de impressão do navegador tem a opção \"Guardar como PDF\".","Contents": "Índice",@@ -54,6 +57,7 @@ export const pt: Catalog = {"Export as Markdown": "Exportar como Markdown","Export as Markdown…": "Exportar como Markdown…","File": "Ficheiro",+ "Filter": "Filtrar","Filter blocks…": "Filtrar blocos…","Find": "Localizar","Find in this space…": "Localizar neste espaço…",@@ -77,10 +81,12 @@ export const pt: Catalog = {"New page inside": "Nova página dentro desta","Next (⏎)": "Seguinte (⏎)","No block matches": "Nenhum bloco corresponde",+ "No issues match this filter.": "Nenhuma tarefa corresponde a este filtro.","No pages yet": "Ainda sem páginas","Note": "Nota","Nothing found": "Nada encontrado","Off by default — they were archived for a reason": "Desativado por predefinição — foram arquivadas por alguma razão",+ "Open only": "Apenas em aberto","Other ways to save": "Outras formas de guardar","Out of the sidebar, still searchable and linkable": "Fora da barra lateral, mas continua pesquisável e ligável","Page options": "Opções da página",@@ -223,4 +229,12 @@ export const pt: Catalog = {"Move down": "Mover para baixo","Duplicate": "Duplicar","Delete": "Eliminar",+ "New issue": "Nova tarefa",+ "Make this page an issue": "Transformar esta página numa tarefa",+ "Adds status, priority, assignee, estimate": "Adiciona estado, prioridade, responsável e estimativa",+ "Already an issue": "Já é uma tarefa",+ "Now an issue": "Agora é uma tarefa",+ "Issues": "Tarefas",+ "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.",+ "Other": "Outras",}diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.tsindex a8eb9bdc..9c74aba0 100644--- a/spaces/src/i18n/zh-Hans.ts+++ b/spaces/src/i18n/zh-Hans.ts@@ -11,6 +11,7 @@import type { Catalog } from '../i18n'export const zh_Hans: Catalog = {+ "A filter here is newer than this build and was not applied.": "此视图中有比当前版本更新的筛选条件,未被应用。","A list of every page, in order": "按顺序列出的所有页面","A page cannot contain itself": "页面不能包含自身","A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "密码会加密文件内的文档。没有任何找回方式 — 密码丢了,空间就没了。",@@ -27,10 +28,12 @@ export const zh_Hans: Catalog = {"Caution": "当心","Change the kind of callout": "更改标注类型","Change this page's icon": "更改此页面的图标",+ "Change {field}": "更改{field}","Check for updates": "检查更新","Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "检查更新完全由你手动发起,并且经过验证:下载内容带有签名,改写任何内容之前,都会先用此文件内的密钥校验签名。","Checking…": "检查中…","Choose a password. There is no way to recover it.": "设置一个密码。它无法找回。",+ "Clear filter": "清除筛选","Close": "关闭","Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "折叠起来的折叠块打印时一律展开。浏览器的打印对话框里有“存为 PDF”选项。","Contents": "目录",@@ -54,6 +57,7 @@ export const zh_Hans: Catalog = {"Export as Markdown": "导出为 Markdown","Export as Markdown…": "导出为 Markdown…","File": "文件",+ "Filter": "筛选","Filter blocks…": "筛选块…","Find": "查找","Find in this space…": "在此空间中查找…",@@ -77,10 +81,12 @@ export const zh_Hans: Catalog = {"New page inside": "在其中新建页面","Next (⏎)": "下一个 (⏎)","No block matches": "没有匹配的块",+ "No issues match this filter.": "没有符合此筛选条件的事项。","No pages yet": "还没有页面","Note": "备注","Nothing found": "没有结果","Off by default — they were archived for a reason": "默认关闭 — 当初归档总是有原因的",+ "Open only": "仅未完成","Other ways to save": "其他保存方式","Out of the sidebar, still searchable and linkable": "移出侧边栏,仍可搜索和链接","Page options": "页面选项",@@ -223,4 +229,12 @@ export const zh_Hans: Catalog = {"Move down": "下移","Duplicate": "创建副本","Delete": "删除",+ "New issue": "新建事项",+ "Make this page an issue": "将此页面变为事项",+ "Adds status, priority, assignee, estimate": "添加状态、优先级、负责人和估算",+ "Already an issue": "已经是事项",+ "Now an issue": "现在是事项了",+ "Issues": "事项",+ "No issues yet. Add a status field to any page and it appears here.": "还没有事项。给任意页面添加状态字段,它就会出现在这里。",+ "Other": "其他",}diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.tsindex 283ff1fe..05617ff4 100644--- a/spaces/src/i18n/zh-Hant.ts+++ b/spaces/src/i18n/zh-Hant.ts@@ -11,6 +11,7 @@import type { Catalog } from '../i18n'export const zh_Hant: Catalog = {+ "A filter here is newer than this build and was not applied.": "此檢視中有比目前版本更新的篩選條件,未被套用。","A list of every page, in order": "依順序列出每一個頁面","A page cannot contain itself": "頁面不能包含自己","A password encrypts the document inside the file. There is no recovery — lose it and the space is gone.": "密碼會加密檔案內的文件。沒有任何復原方式 — 密碼一旦遺失,這個空間就沒了。",@@ -27,10 +28,12 @@ export const zh_Hant: Catalog = {"Caution": "當心","Change the kind of callout": "變更標註類型","Change this page's icon": "變更此頁面的圖示",+ "Change {field}": "變更{field}","Check for updates": "檢查更新","Checking is manual and verified: the download is signed, and its signature is checked against a key inside this file before anything is rewritten.": "檢查是手動且經過驗證的:下載的檔案帶有簽章,在改寫任何內容之前,都會用此檔案內的金鑰驗證該簽章。","Checking…": "檢查中…","Choose a password. There is no way to recover it.": "請設定密碼。沒有任何方法可以找回它。",+ "Clear filter": "清除篩選","Close": "關閉","Collapsed toggles always print open. Your browser's print dialog has the \"Save as PDF\" option.": "收合的摺疊區塊列印時一律展開。「另存為 PDF」的選項在瀏覽器的列印對話方塊中。","Contents": "目錄",@@ -54,6 +57,7 @@ export const zh_Hant: Catalog = {"Export as Markdown": "匯出為 Markdown","Export as Markdown…": "匯出為 Markdown…","File": "檔案",+ "Filter": "篩選","Filter blocks…": "篩選區塊…","Find": "尋找","Find in this space…": "在此空間尋找…",@@ -77,10 +81,12 @@ export const zh_Hant: Catalog = {"New page inside": "在其中新增頁面","Next (⏎)": "下一個 (⏎)","No block matches": "沒有符合的區塊",+ "No issues match this filter.": "沒有符合此篩選條件的項目。","No pages yet": "尚無頁面","Note": "備註","Nothing found": "找不到結果","Off by default — they were archived for a reason": "預設關閉 — 它們被封存是有原因的",+ "Open only": "僅未完成","Other ways to save": "其他儲存方式","Out of the sidebar, still searchable and linkable": "移出側邊欄,仍可搜尋與連結","Page options": "頁面選項",@@ -223,4 +229,12 @@ export const zh_Hant: Catalog = {"Move down": "下移","Duplicate": "建立副本","Delete": "刪除",+ "New issue": "新增項目",+ "Make this page an issue": "將此頁面變為項目",+ "Adds status, priority, assignee, estimate": "新增狀態、優先順序、負責人與估算",+ "Already an issue": "已經是項目",+ "Now an issue": "現在是項目了",+ "Issues": "項目",+ "No issues yet. Add a status field to any page and it appears here.": "還沒有項目。為任一頁面新增狀態欄位,它就會出現在這裡。",+ "Other": "其他",}diff --git a/spaces/src/icons.ts b/spaces/src/icons.tsindex bd1930aa..ddcee4a0 100644--- a/spaces/src/icons.ts+++ b/spaces/src/icons.ts@@ -37,6 +37,7 @@ export const ICONS = {chevronDown: svg('<polyline points="6 9 12 15 18 9"/>'),eye: svg('<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/>'),edit: svg('<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"/>'),+ board: svg('<rect x="3" y="4" width="5" height="16" rx="1.5"/><rect x="10" y="4" width="5" height="11" rx="1.5"/><rect x="17" y="4" width="4" height="7" rx="1.5"/>'),up: svg('<path d="m18 15-6-6-6 6"/>'),down: svg('<path d="m6 9 6 6 6-6"/>'),chevronLeft: svg('<path d="m15 18-6-6 6-6"/>'),diff --git a/spaces/src/main.ts b/spaces/src/main.tsindex 5cd9b23a..36d04a87 100644--- a/spaces/src/main.ts+++ b/spaces/src/main.ts@@ -19,8 +19,9 @@ import { parseDoc, docContentKey, uid, newPage, type SpacesDoc, type ParseResultimport {validateDoc, outlineDoc, statsDoc,planInsertBlocks, planUpdateBlock, planRemoveBlocks, planMoveBlock, planUpdatePage, planRemovePage,+ fieldsReport, issuesReport, planSetField, planNewIssue,plainTitle,- type Plan, type PlanError,+ type Plan, type PlanError, type IssueQuery,} from './agent'import { starterDoc } from './starter'import { textOf } from './sanitize'@@ -332,6 +333,21 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')removePage: (id: string, opts?: { descendants?: boolean }) =>run(planRemovePage(store.doc, id, opts ?? {})),+ // ---- the tracker: an issue is a page ---------------------------------+ /** the schema in force — the option IDS a value must use */+ fields: () => fieldsReport(store.doc),+ /** the backlog as data, filtered by field value or by status phase */+ issues: (query?: IssueQuery) => issuesReport(store.doc, query ?? {}),+ /**+ * One field, one undoable step, `value` and its readable `html` written+ * TOGETHER — the only supported way to set a value, because a prop block+ * written by hand through insertBlocks gets that pairing wrong, and it is+ * the one thing that must never happen.+ */+ setField: (pageId: string, key: string, value: unknown) =>+ run(planSetField(store.doc, pageId, key, value)),+ newIssue: (spec?: unknown) => run(planNewIssue(store.doc, spec)),+/*** A page carries one empty paragraph, exactly as the editor's own New page* does. A page with no blocks has nothing to put a caret in — no gutter, nodiff --git a/spaces/src/render.ts b/spaces/src/render.tsindex 9d2a0ac1..25a3301b 100644--- a/spaces/src/render.ts+++ b/spaces/src/render.ts@@ -14,6 +14,10 @@ import { sanitizeInline, inertBody, esc } from './sanitize'import { tokenize } from './highlight'import { t } from './i18n'import { TAG_OF, LIST_OF, SPEC, TONE } from './blocks'+import {+ fieldByKey, optionOf, issuesOf, headerLength, propBlockOf,+ passesFilter, filterCount, unknownFilterKeys, type FieldSpec,+} from './fields'import { ICONS, type IconName } from './icons'export interface RenderOpts {@@ -59,7 +63,27 @@ export function renderBlocks(page: Page, doc: SpacesDoc, opts: RenderOpts = {}):return stack.length ? stack[stack.length - 1][1] : frag}- for (const b of page.blocks) {+ // FIELDS AT THE TOP ARE A HEADER STRIP — by position, not by a flag.+ //+ // `prop` blocks that precede the first non-prop block are drawn as one+ // compact row under the title; the same blocks further down render inline.+ // Nothing in the format says "this is a header", so a build that predates all+ // of this shows exactly the same values in exactly the same order, just+ // stacked — which is the whole reason the header is a convention rather than+ // a container.+ const head = headerLength(page)+ let strip: HTMLElement | null = null+ if (head > 0) {+ strip = document.createElement('div')+ strip.className = 'sp-props'+ frag.appendChild(strip)+ }++ page.blocks.forEach((b, i) => {+ if (strip && i < head) {+ strip.appendChild(renderBlock(b, doc, opts))+ return+ }const host = hostFor(b.parent)const kind = LIST_OF[b.type]@@ -105,7 +129,7 @@ export function renderBlocks(page: Page, doc: SpacesDoc, opts: RenderOpts = {}):// `container` implies are wrong for it.stack.push([b.id, node])}- }+ })return frag}@@ -206,6 +230,49 @@ export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}): HTreturn el}+ case 'prop': {+ // A FIELD VALUE. The chip is built from the schema, but the block's own+ // `html` is what a build that does not know this type shows — so the two+ // must always say the same thing, and fields.ts keeps them in step.+ const key = String((b as { key?: unknown }).key ?? '')+ const f = fieldByKey(doc, key)+ const value = (b as { value?: unknown }).value+ el.classList.add('sp-prop')+ el.dataset.field = key++ const label = document.createElement('span')+ label.className = 'sp-prop-key'+ label.textContent = f?.label ?? key+ el.appendChild(label)++ const val = document.createElement(opts.editable ? 'button' : 'span')+ val.className = 'sp-prop-val'+ if (opts.editable) {+ ;(val as HTMLButtonElement).type = 'button'+ val.dataset.editField = key+ }+ const opt = f && optionOf(f, value)+ if (opt) {+ const dot = document.createElement('span')+ dot.className = 'sp-prop-dot'+ // colour is a HINT, never the meaning — the label is always present, so+ // this reads correctly in monochrome and without colour vision+ if (opt.color) dot.style.background = opt.color+ val.appendChild(dot)+ }+ const text = document.createElement('span')+ text.textContent = shownValue(f, value)+ val.appendChild(text)+ el.appendChild(val)+ return el+ }++ case 'view': {+ el.classList.add('sp-view')+ renderView(el, b, doc, opts)+ return el+ }+case 'callout': {const raw = String(b.tone ?? 'note')const known = TONE.has(raw) ? raw : 'note'@@ -459,7 +526,14 @@ export function renderPage(page: Page, doc: SpacesDoc, opts: RenderOpts = {}): Hconst inner = document.createElement('div')inner.className = 'sp-page-inner'inner.dir = doc.theme.dir ?? 'ltr'- if (doc.theme.measure) inner.style.maxWidth = `${doc.theme.measure}px`+ // THE MEASURE IS FOR PROSE. A line of text has a comfortable width and that+ // is what `theme.measure` is for — but a board is not a line of text, and+ // squeezing one into 720px shows two and a half columns of a six-column+ // board. A page carrying a view gets the room instead; a page of writing+ // keeps its measure.+ const wide = page.blocks.some((b) => b.type === 'view')+ if (doc.theme.measure) inner.style.maxWidth = wide ? '1500px' : `${doc.theme.measure}px`+ if (wide) inner.classList.add('sp-wide')const h = document.createElement('h1')h.className = 'sp-title'@@ -473,3 +547,200 @@ export function renderPage(page: Page, doc: SpacesDoc, opts: RenderOpts = {}): Hart.appendChild(inner)return art}++/** What a value reads as. Mirrors fields.ts propHtml, which writes the same+ * text into the block so an older build shows it too. */+function shownValue(f: FieldSpec | undefined, value: unknown): string {+ if (value === undefined || value === null || value === '') return '—'+ if (f?.vt === 'select') return optionOf(f, value)?.label ?? String(value)+ if (f?.vt === 'labels') return Array.isArray(value) ? value.join(', ') : String(value)+ return String(value)+}++/**+ * A BOARD or a LIST of the issues in this space.+ *+ * Derived, never stored: the view holds a query, and the issues are wherever+ * they are. Storing membership would mean a card could disagree with the page+ * it stands for — the mistake every "database" makes when it keeps its own copy+ * of the rows.+ */+function renderView(host: HTMLElement, b: Block, doc: SpacesDoc, opts: RenderOpts): void {+ const layout = String((b as { layout?: unknown }).layout ?? 'board')+ const groupKey = String((b as { groupBy?: unknown }).groupBy ?? 'status')+ const field = fieldByKey(doc, groupKey)+ const filter = (b as { filter?: unknown }).filter+ const all = issuesOf(doc)+ const rows = all.filter((r) => passesFilter(doc, r.values, filter))++ const head = document.createElement('div')+ head.className = 'sp-view-head'+ const title = document.createElement('span')+ title.className = 'sp-view-title'+ title.textContent = String(b.html || t('Issues'))+ const count = document.createElement('span')+ count.className = 'sp-view-count'+ count.textContent = String(rows.length)+ head.append(title, count)++ // The controls belong to the EDITOR, like the callout chip and the language+ // chip: a reader, a printout and a locked space get the view, not the buttons+ // that change what it holds.+ if (opts.editable) {+ const on = !!(filter as { open?: unknown } | undefined)?.open+ const openB = document.createElement('button')+ openB.type = 'button'+ openB.className = 'sp-btn sp-view-btn' + (on ? ' sp-on' : '')+ openB.dataset.viewOpen = '1'+ openB.textContent = t('Open only')+ openB.setAttribute('aria-pressed', String(on))+ const filterB = document.createElement('button')+ filterB.type = 'button'+ filterB.className = 'sp-btn sp-view-btn'+ filterB.dataset.viewFilter = '1'+ const n = filterCount(filter)+ // the count rather than a list of chips: what matters is that the view is+ // narrowed at all, and the popover says by what+ filterB.textContent = n ? `${t('Filter')} · ${n}` : t('Filter')+ head.append(openB, filterB)+ }+ host.appendChild(head)++ // A rule this build cannot evaluate means the view shows MORE than its author+ // asked for. Additivity keeps the rule; honesty says so.+ const unknown = unknownFilterKeys(filter)+ if (unknown.length) {+ const note = document.createElement('p')+ note.className = 'sp-view-empty'+ note.textContent = t('A filter here is newer than this build and was not applied.')+ host.appendChild(note)+ }++ if (!rows.length) {+ const empty = document.createElement('p')+ empty.className = 'sp-view-empty'+ // says how to fix it, because an empty board with no explanation reads as+ // broken rather than as empty — and an empty board with issues behind a+ // filter is a DIFFERENT thing to fix+ empty.textContent = all.length+ ? t('No issues match this filter.')+ : t('No issues yet. Add a status field to any page and it appears here.')+ host.appendChild(empty)+ return+ }++ const card = (page: Page, values: Map<string, unknown>): HTMLElement => {+ // A DIV holding a link, not a link holding controls: the card carries a+ // BUTTON now (the status picker, which is the only way to change a status+ // with a finger), and interactive content inside an <a> is invalid and+ // unreachable from the keyboard. The whole card is still one click target —+ // the title's ::after stretches over it (styles.css).+ const a = document.createElement('div')+ a.className = 'sp-issue'+ a.dataset.issue = page.id+ const t1 = document.createElement(opts.editable === false ? 'span' : 'a')+ t1.className = 'sp-issue-title'+ if (t1 instanceof HTMLAnchorElement) t1.href = `#p/${page.id}`+ t1.textContent = page.title+ a.appendChild(t1)+ const meta = document.createElement('span')+ meta.className = 'sp-issue-meta'++ // THE STATUS IS A CONTROL, because a phone cannot drag. It is the same+ // picker and the same writer the issue's own header strip uses — one path,+ // so `value` and `html` can never fall out of step.+ const own = opts.editable && field && propBlockOf(page, groupKey)+ if (own) {+ const set = document.createElement('button')+ set.type = 'button'+ set.className = 'sp-issue-chip sp-issue-set'+ set.dataset.setField = own.id+ set.title = t('Change {field}', { field: field!.label })+ set.setAttribute('aria-label', t('Change {field}', { field: field!.label }))+ const cur = optionOf(field, values.get(groupKey))+ const d = document.createElement('span')+ d.className = 'sp-prop-dot'+ if (cur?.color) d.style.background = cur.color+ set.append(d, document.createTextNode(shownValue(field, values.get(groupKey))))+ meta.appendChild(set)+ }++ for (const k of ['priority', 'assignee', 'estimate']) {+ const v = values.get(k)+ if (v === undefined || v === '' || v === null) continue+ const f2 = fieldByKey(doc, k)+ const chip = document.createElement('span')+ chip.className = 'sp-issue-chip'+ const o = f2 && optionOf(f2, v)+ if (o?.color) {+ const d = document.createElement('span')+ d.className = 'sp-prop-dot'+ d.style.background = o.color+ chip.appendChild(d)+ }+ chip.append(document.createTextNode(shownValue(f2, v)))+ meta.appendChild(chip)+ }+ if (meta.childElementCount) a.appendChild(meta)+ return a+ }++ if (layout === 'list') {+ const ul = document.createElement('ul')+ ul.className = 'sp-view-list'+ for (const r of rows) {+ const li = document.createElement('li')+ li.appendChild(card(r.page, r.values))+ ul.appendChild(li)+ }+ host.appendChild(ul)+ return+ }++ // BOARD, in the schema's declared order — not alphabetical, and not the order+ // issues happen to be in. A status list has a direction, and a board that+ // does not follow it is a board you have to read rather than glance at.+ const board = document.createElement('div')+ board.className = 'sp-board'+ const cols = field?.options ?? []+ const seen = new Set<string>()+ for (const opt of cols) {+ const mine = rows.filter((r) => String(r.values.get(groupKey) ?? '') === opt.id)+ mine.forEach((r) => seen.add(r.page.id))+ const col = document.createElement('div')+ col.className = 'sp-col'+ col.dataset.group = opt.id+ const ch = document.createElement('div')+ ch.className = 'sp-col-head'+ const dot = document.createElement('span')+ dot.className = 'sp-prop-dot'+ if (opt.color) dot.style.background = opt.color+ ch.append(dot, document.createTextNode(opt.label))+ const n = document.createElement('span')+ n.className = 'sp-col-count'+ n.textContent = String(mine.length)+ ch.appendChild(n)+ col.appendChild(ch)+ for (const r of mine) col.appendChild(card(r.page, r.values))+ board.appendChild(col)+ }+ // An issue whose status this build does not know still has to appear, or the+ // board silently loses work written by a newer build. It carries NO+ // `data-group`, which is also what makes it a place you can drag OUT of and+ // not INTO: "Other" is not a value, so there is nothing a drop here could+ // write, and inventing one would overwrite a newer build's status with a+ // guess. Dragging a card from here to a real column is how you correct it,+ // deliberately.+ const orphans = rows.filter((r) => !seen.has(r.page.id))+ if (orphans.length) {+ const col = document.createElement('div')+ col.className = 'sp-col'+ const ch = document.createElement('div')+ ch.className = 'sp-col-head'+ ch.textContent = t('Other')+ col.appendChild(ch)+ for (const r of orphans) col.appendChild(card(r.page, r.values))+ board.appendChild(col)+ }+ host.appendChild(board)+}diff --git a/spaces/src/styles.css b/spaces/src/styles.cssindex 2ef7c083..b34a7270 100644--- a/spaces/src/styles.css+++ b/spaces/src/styles.css@@ -211,7 +211,7 @@ button.sp-callout-chip:hover { text-decoration: underline; text-underline-offset.sp-result-ico.sp-tone-warning, .sp-result-ico.sp-tone-caution { color: var(--tone-ink); }.sp-tonepop { width: 244px; }-.sp-toneopt.sp-sel { background: var(--chrome-2); }+.sp-dditem.sp-sel { background: var(--chrome-2); }.sp-tonerow { display: block; padding: 8px 9px 4px; border-top: 1px solid var(--line); margin-top: 4px; }.sp-tonelabel { display: block; font-size: 12px; color: var(--muted); margin-bottom: 4px; }.sp-toneicon { width: 100%; }@@ -283,7 +283,6 @@ button.sp-callout-chip:hover { text-decoration: underline; text-underline-offset}.sp-b-code:hover .sp-langchip, .sp-langchip:focus { opacity: 1; }.sp-langpop { width: 190px; }-.sp-langpop .sp-dditem.sp-sel { background: var(--chrome-2); }.sp-twist {flex: 0 0 auto; border: 0; background: transparent; color: var(--muted);@@ -795,3 +794,120 @@ body.sp-col-resizing { cursor: col-resize; user-select: none; }}.sp-pop.sp-sheet.sp-sheet-in { transform: none; opacity: 1; }.sp-pop.sp-sheet .sp-dditem { padding-block: 13px; }++/* ————— typed fields, and the boards that read them —————+ An issue is a page; its fields are blocks. The chip always carries its LABEL+ as well as its colour, so it reads correctly in monochrome, in print, and+ without colour vision — colour is a hint, never the meaning. */+.sp-props {+ display: flex; flex-wrap: wrap; gap: 6px 8px;+ margin: -4px 0 20px; padding-bottom: 14px;+ border-bottom: 1px solid var(--line);+}+.sp-props .sp-b { margin: 0; }+.sp-prop { display: inline-flex; align-items: center; gap: 7px; font-size: 13px; }+.sp-prop-key { color: var(--muted); }+.sp-prop-val {+ display: inline-flex; align-items: center; gap: 6px;+ font: inherit; color: var(--ink); background: var(--chrome);+ border: 1px solid var(--line); border-radius: 7px;+ padding: 3px 9px; cursor: pointer;+}+button.sp-prop-val:hover { background: #fff; border-color: #b9c3d2; }+.sp-prop-dot {+ width: 8px; height: 8px; border-radius: 50%;+ background: var(--line); flex: 0 0 auto;+}++.sp-view { margin: 0 0 18px; }+.sp-view-head { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }+.sp-view-btn { font-size: 12.5px; padding: 4px 9px; }+.sp-view-btn:first-of-type { margin-inline-start: auto; }+.sp-view-btn.sp-on { background: var(--chrome-2); border-color: #b9c3d2; color: var(--ink); }+/* a field's name above its values, in the filter picker */+.sp-fgroup { display: block; padding: 9px 9px 3px; font-size: 12px; color: var(--muted); }+.sp-view-title { font-weight: 650; font-size: 15px; }+.sp-view-count {+ font-size: 12px; color: var(--muted);+ background: var(--chrome-2); border-radius: 20px; padding: 1px 8px;+}+.sp-view-empty { color: var(--muted); font-size: 14px; }++/* The board scrolls SIDEWAYS inside itself — never the page. A horizontally+ scrolling document is the thing that makes a phone unusable. */+.sp-board {+ display: flex; gap: 12px; overflow-x: auto; padding-bottom: 6px;+ scroll-snap-type: x proximity;+}+.sp-col {+ flex: 0 0 232px; min-width: 232px; scroll-snap-align: start;+ background: var(--chrome); border-radius: 10px; padding: 9px;+}+.sp-col-head {+ display: flex; align-items: center; gap: 7px;+ font-size: 12.5px; font-weight: 600; color: var(--ink-2);+ padding: 2px 4px 9px;+}+.sp-col-count { margin-inline-start: auto; color: var(--muted); font-weight: 500; }++/* AN ISSUE CARD IS NOT A DIALOG CARD. Both were `.sp-card`, and the dialog's+ rule (line ~333) sets `width: min(560px, 92vw)` — so every card on the board+ was 560px wide inside a 232px column and spilled across its neighbours, on+ every screen, since the board shipped. Measured, not theorised. Its own name+ is the fix that cannot come back. */+.sp-issue {+ display: block; position: relative; color: inherit;+ background: #fff; border: 1px solid var(--line); border-radius: 8px;+ padding: 9px 10px; margin-bottom: 7px;+}+.sp-issue:hover { border-color: #b9c3d2; box-shadow: 0 2px 8px rgb(20 30 45 / .07); }+/* `.sp-page a` underlines every link in the reading column and out-specifies a+ bare class — a card title is a card, not a link in a sentence. */+.sp-page a.sp-issue-title, .sp-issue-title { display: block; font-size: 13.5px; line-height: 1.4; color: inherit; text-decoration: none; }+/* THE WHOLE CARD IS THE LINK, and the status button is still a real button.+ The card cannot BE an <a> any more (interactive content inside a link is+ invalid and unreachable from the keyboard), so the title's ::after stretches+ over the card and the button lifts above it. */+a.sp-issue-title::after { content: ''; position: absolute; inset: 0; }+.sp-issue-meta { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 7px; }+.sp-issue-chip {+ display: inline-flex; align-items: center; gap: 5px;+ font-size: 11.5px; color: var(--muted);+ background: var(--chrome); border-radius: 5px; padding: 1px 6px;+}+button.sp-issue-set {+ position: relative; z-index: 1; font: inherit; font-size: 11.5px;+ border: 1px solid var(--line); cursor: pointer;+ /* a finger's target, not a mouse's */+ padding: 4px 8px; min-height: 26px;+}+button.sp-issue-set:hover { background: var(--chrome-2); border-color: #b9c3d2; }+/* A FINGER: the status button is the only way to move an issue where HTML5+ drag does not exist, so on a touch device it gets a target worth aiming at.+ BOTH predicates — `coarse` is the honest one, and the width is the one a+ desktop browser at 375px can be measured against (58×29 → 58×34 there). */+@media (pointer: coarse), (max-width: 700px) {+ button.sp-issue-set { min-height: 34px; padding: 7px 10px; }+}++/* dragging a card: what is moving, and exactly where it would land */+.sp-issue[draggable='true'] { cursor: grab; }+.sp-issue.sp-dragging { opacity: .4; }+.sp-col.sp-drop { background: var(--chrome-2); outline: 2px solid var(--accent); outline-offset: -2px; }+.sp-issue.sp-dropbefore { box-shadow: 0 -7px 0 -5px var(--accent); }+.sp-col.sp-dropend::after {+ content: ''; display: block; height: 2px; border-radius: 2px;+ background: var(--accent); margin: 0 1px;+}+.sp-view-list { list-style: none; margin: 0; padding: 0; }+.sp-view-list li { margin: 0 0 6px; }++/* Print: a board is columns of cards on screen and a LIST on paper — a+ horizontal scroller cannot be printed, and cutting it off would silently+ drop issues. */+@media print {+ .sp-board { display: block; overflow: visible; }+ .sp-col { break-inside: avoid; margin-bottom: 10px; }+ .sp-issue { box-shadow: none; }+ .sp-prop-val { background: none; }+}