Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: magic notes — a line ending in `=` works itself out (#288)

nyblnet158ee808cff4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 86088598..45ab7d0f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -144,6 +144,18 @@ jobs:
# reported by the process it hangs.
run: node scripts/test-spaces-agent.ts
+ - name: Magic notes evaluator (several timezones)
+ # Two failure modes, and the second is what would make the feature worse
+ # than not having it: a WRONG answer (silent, confident, in somebody's
+ # notes), and an answer where there should be none — "Meet Ana at 3" is
+ # a sentence. The parser must consume the whole line or return nothing.
+ # Dates run in several timezones for the reasons journal.ts records.
+ run: |
+ for tz in UTC Europe/Berlin America/Los_Angeles Pacific/Kiritimati; do
+ echo "--- $tz"
+ TZ=$tz node scripts/test-spaces-calc.ts
+ done
+
- name: Spaces shell size ceiling
# A budget nobody measures is a wish. DECISIONS.md set a 100KB ceiling,
# the round finished at 108KB, and the same entry claimed the ceiling
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 7829cd9d..c37d0410 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -218,6 +218,53 @@ chosen. `STRICT=1` turns every one into an assertion — flip it in CI the day
the three decisions land, and the rig becomes their enforcement rather than
their evidence.
+## 2026-08-10 — Magic notes: the expression is stored, the answer is derived, and there is no eval
+
+**Decision.** A line whose text ends in `=` gets an answer rendered after it.
+The document stores what was written — `budget * 0.3 =` — and never the number.
+`spaces/src/calc.ts` is the evaluator; `render.ts` derives per page in one
+forward pass.
+
+**Why derived and not stored.** Change `budget = 5000` to 6000 and every line
+below re-answers, because nothing downstream was frozen — measured in the
+browser: 750 → 1,950 and 480 → 720 from one edit, with the file still holding
+only the expressions. It is the rule slides settled for dynamic fields, and it
+also means the file stays plain: search, grep, the Markdown export and a build
+that predates this all see `budget * 0.3 =`, which reads as prose. No new block
+type, no attribute for the sanitizer to strip.
+
+**The trailing `=` is an OPT-IN, and that is the feature.** A notes app where
+every line with numbers became a calculator would be unusable — "we shipped 3
+of 7" is a sentence. The parser must consume the WHOLE line or return nothing;
+a partial parse is a refusal. The rig spends as many assertions on what must
+NOT answer as on what must.
+
+**NO `eval`, NO `new Function`, and it is a security boundary.** Block html
+comes out of a file somebody mailed you, and sanitize.ts exists so nothing in a
+document can execute. Reaching for the JS parser to evaluate `2+2` would hand
+that back. A recursive-descent parser over a fixed grammar can only return a
+number.
+
+**`sum above` means the run of figures DIRECTLY above.** Summing every number
+on the page was the first behaviour and it was confidently wrong: on a page
+with a budget, three expenses and two other answers it reported 78,732 where
+the reader means 515. A heading, a sentence, a definition or another answer
+ends the run — a subtotal is where a group finishes.
+
+**Order matters, and it is fed AFTER each block is drawn.** Feeding before
+meant an answering line cleared the very run its own answer needed, and
+`sum above` read 0. After means a line sees what is above it and nothing of
+itself.
+
+**Precision is a note's, not a physics paper's** — 2 decimals above 100, 4
+above 1, 6 below. `584.088921 mi` is noise around `584.09`.
+
+**Dates and times use the local calendar**, for the reasons journal.ts records:
+UTC makes "today" the wrong day for hours at a time outside Greenwich, and a
+day is not 86,400 seconds on the two DST boundaries. `2026-08-10` is lexed as
+ONE token — as three, it parses as 2026 minus 08 minus 10 and answers 2008,
+which is the worst bug this file could have.
+
## 2026-08-03 — Sync parameterization is gated on BYTE equivalence, not convergence
Making `slides/src/sync/` serve spaces (`doc.pages[] → page.blocks[]`) by
diff --git a/scripts/size-budgets.json b/scripts/size-budgets.json
index 076ae0c4..70685fa4 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": 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."
+ "max": 143360,
+ "//": "140 KiB. Raised from 132: magic notes cost ~4.6 KB compressed — a recursive-descent evaluator (no eval, ever: block html comes from a file somebody mailed you), a small unit table, date and clock arithmetic, the derived answer in the renderer and the typing preview. Headroom is deliberate: the shell is mostly a zlib block and zlib differs across node versions — one 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-calc.ts b/scripts/test-spaces-calc.ts
new file mode 100644
index 00000000..c223f9c1
--- /dev/null
+++ b/scripts/test-spaces-calc.ts
@@ -0,0 +1,209 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Magic notes — the evaluator.
+//
+// node scripts/test-spaces-calc.ts
+// TZ=Pacific/Kiritimati node scripts/test-spaces-calc.ts
+//
+// TWO FAILURE MODES, and the second is the one that would make the feature
+// worse than not having it:
+//
+// 1. A WRONG ANSWER. Silent, confident, and in somebody's notes — the number
+// they then act on. Float dust (0.1+0.2), a bad conversion, a percentage
+// read the wrong way round.
+//
+// 2. AN ANSWER WHERE THERE SHOULD BE NONE. "Meet Ana at 3" is a sentence.
+// "We shipped 3 of 7" is a sentence. A calculator that answers those has
+// made the app noisier for everyone who is only writing. So the parser
+// must consume the WHOLE line or return nothing — a partial parse is a
+// refusal, not a result.
+//
+// Dates run under several TZ values in CI for the reasons journal.ts records:
+// a date test that only runs in one timezone has not been run.
+
+import { evaluate, answer, format, definition, asksForAnswer, feed, freshContext, type Val, type CalcCtx } from '../spaces/src/calc.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+}
+/** `expr` → formatted answer, with an en-GB locale so the digits are stable */
+const A = (src: string, ctx: CalcCtx = {}) => {
+ const v = evaluate(src, ctx)
+ return v ? format(v, 'en-GB') : null
+}
+const is = (src: string, want: string, ctx: CalcCtx = {}) =>
+ ok(A(src, ctx) === want, `${src} → ${want} (got ${A(src, ctx)})`)
+const none = (src: string, ctx: CalcCtx = {}) =>
+ ok(A(src, ctx) === null, `${src} → no answer (got ${A(src, ctx)})`)
+
+console.log(`magic notes — the evaluator (TZ=${process.env.TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone})\n`)
+
+// ---- arithmetic -------------------------------------------------------------
+is('2 + 2', '4')
+is('1200 * 1.2', '1,440')
+is('(3 + 4) / 2', '3.5')
+is('2 ^ 10', '1,024')
+is('-5 + 12', '7')
+is('10 / 4', '2.5')
+is('1,250 + 1,250', '2,500') // thousands separators, as pasted
+is('1_000 * 3', '3,000')
+// float dust is the classic wrong-looking-right answer
+is('0.1 + 0.2', '0.3')
+is('1.1 * 3', '3.3')
+none('5 / 0') // not Infinity in someone's notes
+
+// ---- percentages ------------------------------------------------------------
+is('20% of 340', '68')
+is('340 + 15%', '391')
+is('340 - 15%', '289')
+is('12.5% of 80', '10')
+// the reading everybody means: "+15%" is an increase, not "plus 0.15"
+ok(A('200 + 10%') === '220', 'a trailing percentage increases rather than adds')
+
+// ---- units ------------------------------------------------------------------
+// The decimals are the ones a NOTE wants: 2 places above 100, 4 above 1, 6
+// below. "584.088921 mi" is noise around 584.09, and a page of notes reads
+// worse for it.
+is('10 km in miles', '6.2137 mi')
+is('26.2 miles in km', '42.1648 km')
+is('5 ft in cm', '152.4 cm')
+is('2.5 GB in MB', '2,560 MB')
+is('1 hour in minutes', '60 min')
+is('90 min in hours', '1.5 h')
+is('72 f in c', '22.2222 °C')
+is('100 c in f', '212 °F')
+is('0 c in k', '273.15 K')
+is('1 kg in lb', '2.2046 lb')
+none('10 km in kg') // families do not mix
+none('10 km in wombats')
+
+// ---- unit arithmetic --------------------------------------------------------
+is('2 km + 300 m', '2.3 km')
+is('1 h + 30 min', '1.5 h')
+is('3 kg * 2', '6 kg')
+none('2 km + 3 kg')
+
+// ---- clock times ------------------------------------------------------------
+is('9:30 + 45 min', '10:15') // a time, not "10.25 h"
+is('17:00 - 9:30', '7.5 h') // …and the gap between two times is a duration
+is('23:30 + 45 min', '0:15') // wrapping midnight beats a 25th hour
+none('9:30 + 17:00') // two times of day do not add
+none('9:70') // nor does a 70th minute exist
+
+// ---- variables --------------------------------------------------------------
+{
+ const vars = new Map<string, Val>()
+ const def = definition('budget = 5000')
+ ok(def?.name === 'budget' && def.val.n === 5000, 'a bare `name = value` line defines a name')
+ if (def) vars.set(def.name, def.val)
+ is('budget * 0.3', '1,500', { vars })
+ is('budget - 1200', '3,800', { vars })
+ is('20% of budget', '1,000', { vars })
+
+ // a definition can use one already defined
+ const d2 = definition('spent = budget * 0.4', { vars })
+ ok(d2?.val.n === 2000, 'a definition can build on an earlier one')
+ if (d2) vars.set(d2.name, d2.val)
+ is('budget - spent', '3,000', { vars })
+
+ // …and a unit survives the round trip
+ const d3 = definition('trip = 120 km')
+ if (d3) vars.set(d3.name, d3.val)
+ is('trip in miles', '74.5645 mi', { vars })
+
+ // a name that is a unit, or a keyword, is NOT a definition — `in = 5` would
+ // quietly break every conversion on the page
+ ok(definition('in = 5') === null, 'a unit name cannot be redefined')
+ ok(definition('today = 5') === null, 'nor can a keyword')
+ // and a line that ASKS for an answer is not a definition
+ ok(definition('budget * 2 =') === null, 'a question is not a definition')
+}
+
+// ---- sum of the lines above -------------------------------------------------
+is('sum above', '60', { above: [10, 20, 30] })
+is('total', '6', { above: [1, 2, 3] })
+is('sum above / 3', '20', { above: [10, 20, 30] })
+is('sum above', '0', { above: [] })
+
+// …and what "above" MEANS, which is the run of figures directly above and not
+// every number on the page. Summing the page was the first behaviour, and on a
+// page with a budget, three expenses and two other answers it reported 78,732
+// where the reader means 515.
+{
+ const ctx = freshContext()
+ for (const line of [
+ 'budget = 2400', // a definition — not a figure, and it ends any run
+ 'Trip costs', // prose — ends the run
+ '120', '340', '55', // THE run
+ ]) feed(ctx, line)
+ ok(A('sum above =', ctx) === '515',
+ `sum above is the run directly above (got ${A('sum above =', ctx)})`)
+
+ // a sentence between the figures and the sum breaks the run, which is what
+ // somebody reading the page would expect
+ const broken = freshContext()
+ for (const line of ['120', '340', 'and then we stopped counting']) feed(broken, line)
+ ok(A('sum above =', broken) === '0', 'prose ends the run')
+
+ // an answered line is not itself a figure — otherwise a running total would
+ // count its own subtotals
+ const subtotals = freshContext()
+ for (const line of ['10', '20', 'sum above =', '30']) feed(subtotals, line)
+ ok(A('sum above =', subtotals) === '30', 'an answer does not join the run it summarises')
+}
+
+// ---- dates ------------------------------------------------------------------
+{
+ const ctx = { today: '2026-08-10' }
+ is('today', '2026-08-10', ctx)
+ is('tomorrow', '2026-08-11', ctx)
+ is('yesterday', '2026-08-09', ctx)
+ is('today + 3 weeks', '2026-08-31', ctx)
+ is('today + 90 days', '2026-11-08', ctx)
+ is('2026-12-25 - today', '137 days', ctx)
+ is('2026-08-31 - 2026-08-10', '21 days', ctx)
+ is('2026-08-10 + 1 day', '2026-08-11', ctx)
+ // across a year end, a leap day, and a DST boundary
+ is('2026-12-31 + 1 day', '2027-01-01', ctx)
+ is('2024-02-28 + 1 day', '2024-02-29', ctx)
+ is('2026-03-28 + 1 day', '2026-03-29', ctx)
+ is('2026-10-24 + 2 days', '2026-10-26', ctx)
+ none('2026-13-99 + 1 day') // not a date, so not an answer
+ none('today + today') // two dates do not add
+ none('today * 2') // nor scale
+}
+
+// ---- THE REFUSALS, which matter as much as the answers ----------------------
+// Every one of these is a sentence somebody would write in a note.
+none('Meet Ana at 3')
+none('We shipped 3 of 7')
+none('call Bob')
+none('')
+none(' ')
+none('3 apples and 4 pears')
+none('v2 launch')
+none('$5 for coffee') // a bare currency symbol is not a unit here
+none('12 of 60')
+none('the 5th')
+ok(A('2026') === '2,026', 'a bare number is a number when asked')
+none('a + b') // undefined names
+none('budget * 2') // …including when nothing is defined
+// a very long line is refused rather than parsed, so a pasted wall of text
+// cannot become a calculation
+none('1 + '.repeat(80) + '1')
+
+// ---- the marker -------------------------------------------------------------
+ok(asksForAnswer('2 + 2 ='), 'a trailing = asks for an answer')
+ok(asksForAnswer('2 + 2 = '), '…with trailing space')
+ok(!asksForAnswer('2 + 2'), 'and without it, nothing happens')
+ok(!asksForAnswer('a = b'), 'a definition does not ask')
+ok(answer('2 + 2 =') === '4', 'answer() drives off the marker')
+ok(answer('2 + 2') === null, '…and only the marker')
+ok(answer('hello =') === null, 'a line that asks but does not parse gets nothing')
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.md
index 9cd62ac0..f39d863a 100644
--- a/spaces/CHANGELOG.md
+++ b/spaces/CHANGELOG.md
@@ -103,6 +103,24 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.
now, and it cannot tangle: a block is nested under its parent only when that
parent is genuinely above it on the page.
+- **Lines that work things out.** End a line with `=` and it answers:
+ `budget - flights =`, `20% of 340 =`, `940 km in miles =`, `today + 3 weeks =`,
+ `9:30 + 45 min =`, `sum above =`. Give something a name — `budget = 2400` —
+ and the lines below can use it.
+
+ **The answer is never written into your file.** The line stores what you
+ typed, and the number is worked out each time the page is drawn. Change the
+ budget at the top and every line below follows. Search, export and older
+ versions of the app all see the expression, which reads perfectly well on its
+ own.
+
+ Type a sum *without* the `=` and it shows you the answer first, quietly, with
+ a `Tab` to keep it — so nothing appears in your notes that you did not ask
+ for. A line it cannot fully work out gets nothing at all: "Meet Ana at 3"
+ stays a sentence.
+
+ `bento.calc('20% of 340')` answers the same way for an agent.
+
## [0.1.0] — 2026-08-03
First release.
diff --git a/spaces/README.md b/spaces/README.md
index df6fac10..ea00dbd3 100644
--- a/spaces/README.md
+++ b/spaces/README.md
@@ -71,6 +71,7 @@ load contract and format additivity.
| `src/model.ts` | the format, `buildIndex()` (tree, backlinks), id repair |
| `src/sanitize.ts` | the inline allowlist — the only thing between a file someone mailed you and script execution |
| `src/store.ts` | undo, and the **typing run** |
+| `src/calc.ts` | magic notes — the evaluator behind a line ending in `=`. No eval, ever |
| `src/render.ts` | model → DOM, shared by the editor, reading view and print |
| `src/highlight.ts` | the code lexer — text → `{kind, a, b}` ranges, no DOM, no strings |
| `src/markdown.ts` | markdown → blocks, the folder tree → the page tree, `[[wikilinks]]` → `#p/` links. Pure and DOM-free, so the import is tested in node |
diff --git a/spaces/src/calc.ts b/spaces/src/calc.ts
new file mode 100644
index 00000000..d92a7c1c
--- /dev/null
+++ b/spaces/src/calc.ts
@@ -0,0 +1,519 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Magic notes: a line that ends in `=` gets its answer.
+//
+// THE SHAPE, and why it is this one. The document stores what you wrote —
+// `budget * 0.3 =` — and the ANSWER is derived when the page is drawn. Never
+// stored. That is the same rule slides settled for dynamic fields ("the model
+// stores the raw token; only output is resolved"), and here it buys three
+// things a stored answer cannot:
+//
+// · CHANGE A NUMBER AND EVERYTHING FOLLOWS. Edit `budget = 5000` to 6000 and
+// every line below it re-answers, because nothing downstream was frozen.
+// · The file stays PLAIN. Search, grep, the Markdown export and a build that
+// predates this all see `budget * 0.3 =`, which reads perfectly well as
+// prose. No new block type, no new attribute, nothing for the sanitizer to
+// strip, nothing for an older build to render as a mystery.
+// · The trailing `=` is an OPT-IN. A notes app where every line containing
+// numbers turned into a calculator would be unusable — "we shipped 3 of 7"
+// is a sentence, not a sum. You ask by typing the `=` you were going to
+// type anyway.
+//
+// NO `eval`, NO `new Function`, AND THAT IS A SECURITY BOUNDARY, not a style
+// preference. Block html comes out of a file somebody mailed you; the whole
+// point of sanitize.ts is that nothing in a document can execute. An
+// expression evaluator that reached for the JS parser would hand that back.
+// This is a recursive-descent parser over a fixed grammar and it can only ever
+// return a number.
+
+/** What a parsed value is: a number, optionally carrying a unit or a date. */
+export interface Val {
+ n: number
+ /** canonical unit key, e.g. 'm' | 'kg' | 'day' | '%'; absent = plain number */
+ u?: string
+ /** the value IS a date, `n` being days since the epoch in local terms */
+ date?: boolean
+ /** the value is a TIME OF DAY, `n` being seconds since midnight. `9:30 + 45
+ * min` should read 10:15, not "36,900 s" — the answer people want back is
+ * the one in the shape they asked in. */
+ clock?: boolean
+}
+
+export interface CalcCtx {
+ /** names defined earlier on the same page — `budget = 5000` */
+ vars?: Map<string, Val>
+ /** numbers from the lines above, for `sum above` */
+ above?: number[]
+ /** today, as an ISO date. Injected so the rig is not at the mercy of a clock. */
+ today?: string
+}
+
+// ---------------------------------------------------------------------------
+// units — deliberately few
+// ---------------------------------------------------------------------------
+//
+// Every unit here is one somebody actually writes in a note. The temptation is
+// a physics library; the cost of a wrong or surprising conversion in someone's
+// notes is worse than the cost of not having it, so the table stays short and
+// each family converts through one base.
+
+interface Unit { base: string; k: number; off?: number }
+const UNITS: Record<string, Unit> = {
+ // length → metres
+ mm: { base: 'm', k: 0.001 }, cm: { base: 'm', k: 0.01 }, m: { base: 'm', k: 1 },
+ km: { base: 'm', k: 1000 }, inch: { base: 'm', k: 0.0254 }, ft: { base: 'm', k: 0.3048 },
+ yd: { base: 'm', k: 0.9144 }, mi: { base: 'm', k: 1609.344 },
+ // mass → grams
+ mg: { base: 'g', k: 0.001 }, g: { base: 'g', k: 1 }, kg: { base: 'g', k: 1000 },
+ t: { base: 'g', k: 1e6 }, oz: { base: 'g', k: 28.349523125 }, lb: { base: 'g', k: 453.59237 },
+ // data → bytes. 1024, because a note about file sizes means the one the
+ // operating system shows.
+ byte: { base: 'byte', k: 1 }, kb: { base: 'byte', k: 1024 }, mb: { base: 'byte', k: 1024 ** 2 },
+ gb: { base: 'byte', k: 1024 ** 3 }, tb: { base: 'byte', k: 1024 ** 4 },
+ // duration → seconds
+ ms: { base: 's', k: 0.001 }, s: { base: 's', k: 1 }, min: { base: 's', k: 60 },
+ h: { base: 's', k: 3600 }, day: { base: 's', k: 86400 }, week: { base: 's', k: 604800 },
+ // temperature → celsius, and these need an OFFSET as well as a scale, which
+ // is why `off` exists at all
+ c: { base: 'c', k: 1 }, f: { base: 'c', k: 5 / 9, off: -32 }, k: { base: 'c', k: 1, off: -273.15 },
+}
+
+/** What people type → the canonical key. */
+const ALIAS: Record<string, string> = {
+ millimetre: 'mm', millimeter: 'mm', centimetre: 'cm', centimeter: 'cm',
+ metre: 'm', meter: 'm', metres: 'm', meters: 'm', kilometre: 'km', kilometer: 'km',
+ kilometres: 'km', kilometers: 'km', in: 'inch', inches: 'inch', foot: 'ft', feet: 'ft',
+ yard: 'yd', yards: 'yd', mile: 'mi', miles: 'mi',
+ gram: 'g', grams: 'g', kilogram: 'kg', kilograms: 'kg', kilo: 'kg', kilos: 'kg',
+ tonne: 't', tonnes: 't', ounce: 'oz', ounces: 'oz', pound: 'lb', pounds: 'lb', lbs: 'lb',
+ b: 'byte', bytes: 'byte', kib: 'kb', mib: 'mb', gib: 'gb', tib: 'tb',
+ sec: 's', secs: 's', second: 's', seconds: 's', minute: 'min', minutes: 'min', mins: 'min',
+ hour: 'h', hours: 'h', hr: 'h', hrs: 'h', d: 'day', days: 'day',
+ wk: 'week', weeks: 'week', w: 'week',
+ celsius: 'c', centigrade: 'c', fahrenheit: 'f', kelvin: 'k',
+}
+const unitOf = (w: string): string | undefined => {
+ const k = w.toLowerCase()
+ const canon = ALIAS[k] ?? k
+ return UNITS[canon] ? canon : undefined
+}
+
+const toBase = (v: Val): number => {
+ const u = UNITS[v.u!]
+ return (v.n + (u.off ?? 0)) * u.k
+}
+const fromBase = (n: number, to: string): number => {
+ const u = UNITS[to]
+ return n / u.k - (u.off ?? 0)
+}
+
+// ---------------------------------------------------------------------------
+// dates
+// ---------------------------------------------------------------------------
+//
+// Local-calendar arithmetic, for the same reasons journal.ts spells out: UTC
+// makes "today" the wrong day for hours at a time outside Greenwich, and a day
+// is not 86,400 seconds on the two daylight-saving boundaries each year. Dates
+// are carried as days-since-epoch in LOCAL terms so date maths is integer
+// maths, and converted back through the local calendar.
+
+const ISO = /^(\d{4})-(\d{2})-(\d{2})$/
+const dayMs = 86400000
+const toDay = (y: number, m: number, d: number): number =>
+ Math.round(new Date(y, m - 1, d).getTime() / dayMs - new Date(y, m - 1, d).getTimezoneOffset() / 1440)
+const fromDay = (n: number): string => {
+ const at = new Date(n * dayMs)
+ const y = at.getUTCFullYear(), m = at.getUTCMonth() + 1, d = at.getUTCDate()
+ return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`
+}
+function parseISO(s: string): number | null {
+ const m = ISO.exec(s)
+ if (!m) return null
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])]
+ const at = new Date(y, mo - 1, d)
+ if (at.getFullYear() !== y || at.getMonth() !== mo - 1 || at.getDate() !== d) return null
+ return toDay(y, mo, d)
+}
+
+/**
+ * Today, in the READER'S timezone.
+ *
+ * Not `toISOString().slice(0,10)`: that is UTC, so "today" is the wrong day for
+ * hours at a time for everyone who does not live in Greenwich, and a note that
+ * says `today + 1 week =` would answer with somebody else's calendar.
+ */
+export function localToday(now: Date = new Date()): string {
+ const p = (n: number) => String(n).padStart(2, '0')
+ return `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}`
+}
+
+// ---------------------------------------------------------------------------
+// the parser
+// ---------------------------------------------------------------------------
+
+type Tok = { t: 'n'; v: number } | { t: 'w'; v: string } | { t: 'o'; v: string } | { t: 'd'; v: number }
+
+function lex(src: string): Tok[] | null {
+ const out: Tok[] = []
+ let i = 0
+ while (i < src.length) {
+ const c = src[i]
+ if (c === ' ' || c === '\t' || c === ' ') { i++; continue }
+ // A DATE IS ONE TOKEN. Lexed before numbers, because `2026-08-10` would
+ // otherwise become 2026 minus 08 minus 10 — which parses, and answers 2008.
+ // That is the worst kind of bug this file can have: a confident wrong
+ // number in somebody's notes.
+ if (/[0-9]/.test(c)) {
+ const m = /^\d{4}-\d{2}-\d{2}/.exec(src.slice(i))
+ if (m) {
+ const day = parseISO(m[0])
+ if (day === null) return null // digit-shaped, not a date
+ out.push({ t: 'd', v: day })
+ i += m[0].length
+ continue
+ }
+ }
+ if (/[0-9.]/.test(c)) {
+ // digits, with , or _ as thousands separators — people paste both
+ let j = i, seen = ''
+ while (j < src.length && /[0-9.,_]/.test(src[j])) {
+ if (src[j] === ',' && !/[0-9]/.test(src[j + 1] ?? '')) break
+ seen += src[j] === ',' || src[j] === '_' ? '' : src[j]
+ j++
+ }
+ const n = Number(seen)
+ if (!Number.isFinite(n)) return null
+ out.push({ t: 'n', v: n })
+ i = j
+ continue
+ }
+ if (/[A-Za-z_$£€]/.test(c)) {
+ let j = i
+ while (j < src.length && /[A-Za-z0-9_$£€]/.test(src[j])) j++
+ out.push({ t: 'w', v: src.slice(i, j) })
+ i = j
+ continue
+ }
+ if ('+-*/^()%:'.includes(c)) { out.push({ t: 'o', v: c }); i++; continue }
+ return null // a character this grammar does not know: not an expression
+ }
+ return out
+}
+
+class P {
+ i = 0
+ t: Tok[]
+ ctx: CalcCtx
+ // plain fields, not constructor parameter properties: node's type stripping
+ // is strip-ONLY, and a parameter property is syntax that would have to be
+ // transformed. The rigs run this file directly.
+ constructor(t: Tok[], ctx: CalcCtx) { this.t = t; this.ctx = ctx }
+ peek(): Tok | undefined { return this.t[this.i] }
+ word(): string | undefined { const x = this.peek(); return x?.t === 'w' ? x.v.toLowerCase() : undefined }
+ op(v: string): boolean {
+ const x = this.peek()
+ if (x?.t === 'o' && x.v === v) { this.i++; return true }
+ return false
+ }
+ kw(...w: string[]): boolean {
+ const x = this.word()
+ if (x && w.includes(x)) { this.i++; return true }
+ return false
+ }
+
+ /** expr := term (('+'|'-') term)* , with `+ N%` meaning "increase by N%" */
+ expr(): Val | null {
+ let a = this.term()
+ if (!a) return null
+ for (;;) {
+ const plus = this.op('+')
+ const minus = !plus && this.op('-')
+ if (!plus && !minus) return a
+ const b = this.term()
+ if (!b) return null
+ if (b.u === '%') {
+ // 340 + 15% → 391. The reading everybody means.
+ a = { ...a, n: a.n * (1 + (plus ? 1 : -1) * b.n / 100) }
+ continue
+ }
+ const r = this.add(a, b, plus ? 1 : -1)
+ if (!r) return null
+ a = r
+ }
+ }
+
+ add(a: Val, b: Val, sign: number): Val | null {
+ // clock ± duration = clock; clock − clock = how long between them
+ if (a.clock && b.clock) {
+ if (sign > 0) return null // two times of day do not add
+ // in HOURS, not seconds: "how long between 9:30 and 17:00" is answered
+ // "7.5 h" by every person who has ever asked it, and "27,000 s" by
+ // nobody.
+ return { n: (a.n - b.n) / 3600, u: 'h' }
+ }
+ if (a.clock) {
+ if (!b.u || UNITS[b.u]?.base !== 's') return null
+ // wrap across midnight rather than reporting a 25th hour
+ const n = ((a.n + sign * toBase(b)) % 86400 + 86400) % 86400
+ return { n, u: 's', clock: true }
+ }
+ if (b.clock) return null
+ // date ± duration = date; date − date = days
+ if (a.date && b.date) {
+ if (sign > 0) return null
+ return { n: a.n - b.n, u: 'day' }
+ }
+ if (a.date) {
+ if (!b.u || UNITS[b.u]?.base !== 's') return null
+ const days = toBase(b) / 86400
+ if (!Number.isInteger(days)) return { n: a.n + sign * days, date: true }
+ return { n: a.n + sign * days, date: true }
+ }
+ if (b.date) return null
+ if (a.u && b.u) {
+ if (UNITS[a.u]?.base !== UNITS[b.u]?.base) return null
+ return { n: fromBase(toBase(a) + sign * toBase(b), a.u), u: a.u }
+ }
+ if (a.u || b.u) return { n: a.n + sign * b.n, u: a.u ?? b.u }
+ return { n: a.n + sign * b.n }
+ }
+
+ /** term := pow (('*'|'/') pow)* */
+ term(): Val | null {
+ let a = this.pow()
+ if (!a) return null
+ for (;;) {
+ const mul = this.op('*')
+ const div = !mul && this.op('/')
+ if (!mul && !div) return a
+ const b = this.pow()
+ if (!b) return null
+ if (a.date || b.date) return null
+ if (b.u === '%') { a = { ...a, n: mul ? a.n * b.n / 100 : a.n / (b.n / 100) }; continue }
+ if (div && b.n === 0) return null
+ a = { n: mul ? a.n * b.n : a.n / b.n, u: a.u ?? (mul ? b.u : undefined) }
+ }
+ }
+
+ pow(): Val | null {
+ const a = this.unary()
+ if (!a) return null
+ if (this.op('^')) {
+ const b = this.unary()
+ if (!b || a.date || b.date) return null
+ return { n: a.n ** b.n, u: a.u }
+ }
+ return a
+ }
+
+ unary(): Val | null {
+ if (this.op('-')) { const v = this.unary(); return v && !v.date ? { ...v, n: -v.n } : null }
+ if (this.op('+')) return this.unary()
+ return this.atom()
+ }
+
+ atom(): Val | null {
+ // N% of X
+ const start = this.i
+ const a = this.primary()
+ if (!a) return null
+ if (a.u === '%' && this.kw('of')) {
+ const b = this.expr()
+ return b && !b.date ? { n: b.n * a.n / 100, u: b.u } : null
+ }
+ // X in UNIT / X to UNIT / X as UNIT
+ if (this.kw('in', 'to', 'as')) {
+ const w = this.word()
+ const to = w && unitOf(w)
+ if (!to || !a.u || a.date) { this.i = start; return null }
+ if (UNITS[to].base !== UNITS[a.u].base) return null
+ this.i++
+ return { n: fromBase(toBase(a), to), u: to }
+ }
+ return a
+ }
+
+ primary(): Val | null {
+ if (this.op('(')) {
+ const v = this.expr()
+ if (!v || !this.op(')')) return null
+ return v
+ }
+ const x = this.peek()
+ if (!x) return null
+
+ if (x.t === 'd') { this.i++; return { n: x.v, date: true } }
+
+ if (x.t === 'n') {
+ this.i++
+ // a clock time: 9:30
+ if (this.op(':')) {
+ const m = this.peek()
+ if (m?.t !== 'n' || m.v > 59) return null
+ this.i++
+ return { n: x.v * 3600 + m.v * 60, u: 's', clock: true }
+ }
+ if (this.op('%')) return { n: x.v, u: '%' }
+ const w = this.word()
+ if (w) {
+ const u = unitOf(w)
+ if (u) { this.i++; return { n: x.v, u } }
+ }
+ return { n: x.v }
+ }
+
+ if (x.t === 'w') {
+ const w = x.v.toLowerCase()
+ const today = this.ctx.today ? parseISO(this.ctx.today) : null
+ if (w === 'today' && today !== null) { this.i++; return { n: today, date: true } }
+ if (w === 'tomorrow' && today !== null) { this.i++; return { n: today + 1, date: true } }
+ if (w === 'yesterday' && today !== null) { this.i++; return { n: today - 1, date: true } }
+ if (w === 'sum' || w === 'total') {
+ this.i++
+ this.kw('above', 'of')
+ const list = this.ctx.above ?? []
+ return { n: list.reduce((s, v) => s + v, 0) }
+ }
+ const v = this.ctx.vars?.get(w)
+ if (v) { this.i++; return { ...v } }
+ return null
+ }
+ return null
+ }
+}
+
+// ---------------------------------------------------------------------------
+// formatting
+// ---------------------------------------------------------------------------
+
+const LABEL: Record<string, string> = {
+ inch: 'in', byte: 'B', kb: 'KB', mb: 'MB', gb: 'GB', tb: 'TB',
+ day: 'days', week: 'weeks', c: '°C', f: '°F', k: 'K',
+}
+
+/** Round away the float dust — 0.1+0.2 must not read as 0.30000000000000004. */
+const tidy = (n: number): number => Math.abs(n) < 1e-10 ? 0 : Number(n.toPrecision(12))
+
+export function format(v: Val, locale?: string): string {
+ if (v.date) return fromDay(Math.round(v.n))
+ if (v.clock) {
+ const t = Math.round(v.n / 60)
+ return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, '0')}`
+ }
+ const n = tidy(v.n)
+ // PRECISION A NOTE WANTS. Six decimal places is right for a conversion table
+ // and wrong for "how far is it" — 584.088921 mi is noise around 584.09. The
+ // bigger the number, the fewer decimals carry meaning.
+ const abs = Math.abs(n)
+ const digits = abs >= 100 ? 2 : abs >= 1 ? 4 : 6
+ const num = new Intl.NumberFormat(locale, { maximumFractionDigits: digits }).format(n)
+ if (!v.u) return num
+ if (v.u === '%') return `${num}%`
+ // Every unit gets a space except the percent sign. SI puts a space before
+ // °C; only % is written tight against its number.
+ return `${num} ${LABEL[v.u] ?? v.u}`
+}
+
+// ---------------------------------------------------------------------------
+// the surface
+// ---------------------------------------------------------------------------
+
+/** The trailing `=` that asks for an answer, with optional trailing space. */
+const ASKS = /=\s*$/
+
+/** Does this line ask for an answer? */
+export const asksForAnswer = (text: string): boolean => ASKS.test(text)
+
+/**
+ * `name = value` on its own line DEFINES a name for the lines below it.
+ *
+ * Deliberately not `let` or `set`: people already write `budget = 5000` in
+ * notes, and the feature is worth nothing if it needs its own vocabulary.
+ */
+const DEF = /^\s*([A-Za-z_][A-Za-z0-9_ ]{0,30}?)\s*=\s*(.+)$/
+
+export function definition(text: string, ctx: CalcCtx = {}): { name: string; val: Val } | null {
+ const m = DEF.exec(text)
+ if (!m || asksForAnswer(text)) return null
+ const name = m[1].trim().toLowerCase()
+ if (!name || unitOf(name) || ['today', 'tomorrow', 'yesterday', 'sum', 'total'].includes(name)) return null
+ const val = evaluate(m[2], ctx)
+ return val ? { name, val } : null
+}
+
+/**
+ * Evaluate an expression. Returns null for anything this grammar does not
+ * fully understand — including a partial parse, which is the case that matters:
+ * "meet at 3" must not quietly become 3.
+ */
+export function evaluate(src: string, ctx: CalcCtx = {}): Val | null {
+ const body = src.replace(ASKS, '').trim()
+ if (!body || body.length > 200) return null
+ const toks = lex(body)
+ if (!toks || !toks.length) return null
+ const p = new P(toks, ctx)
+ const v = p.expr()
+ // the whole line must be consumed, or it was prose that happened to start
+ // with something numeric
+ if (!v || p.i !== toks.length || !Number.isFinite(v.n)) return null
+ return v
+}
+
+/** The answer for a line, already formatted — or null if there is not one. */
+export function answer(text: string, ctx: CalcCtx = {}, locale?: string): string | null {
+ if (!asksForAnswer(text)) return null
+ const v = evaluate(text, ctx)
+ return v ? format(v, locale) : null
+}
+
+/**
+ * The context a line on a page sees: every name defined ABOVE it, and the
+ * numbers above it for `sum above`.
+ *
+ * Shared by the renderer and the editor's preview so the ghost answer and the
+ * committed one can never disagree — two implementations of "what does this
+ * line know" is exactly the kind of drift that makes a preview a liar.
+ */
+export function pageContext(
+ lines: Array<{ id: string; text: string }>,
+ upTo: string,
+): CalcCtx {
+ const ctx = freshContext()
+ for (const l of lines) {
+ if (l.id === upTo) break
+ feed(ctx, l.text)
+ }
+ return ctx
+}
+
+/** A context for the top of a page. */
+export const freshContext = (): CalcCtx =>
+ ({ vars: new Map<string, Val>(), above: [], today: localToday() })
+
+/**
+ * Take one line into the context, in reading order.
+ *
+ * ONE implementation, used by the renderer and by the editor's preview. Two
+ * would drift, and a preview that disagrees with the committed answer is worse
+ * than no preview.
+ *
+ * `sum above` means THE RUN OF FIGURES DIRECTLY ABOVE, not every number on the
+ * page. Summing the whole page was the first behaviour and it was confidently
+ * wrong: with three figures in a list under a budget and two other answers, it
+ * reported 78,732 where a person reading the page means 515. So any line that
+ * is not itself a plain figure ends the run — a heading, a sentence, a
+ * definition, another answer.
+ */
+export function feed(ctx: CalcCtx, text: string): void {
+ const def = definition(text, ctx)
+ if (def) { ctx.vars!.set(def.name, def.val); ctx.above!.length = 0; return }
+ // An ANSWER ENDS THE RUN as well as staying out of it. A subtotal is where a
+ // group of figures finishes, so the next `sum above` means the figures after
+ // it — otherwise every subtotal silently includes the ones before it.
+ if (asksForAnswer(text)) { ctx.above!.length = 0; return }
+ const v = evaluate(text, ctx)
+ // a figure is a line that IS a number — `120`, `45 kg`, `12 * 3`. A date is
+ // not a figure, and neither is a sentence.
+ if (v && !v.date && !v.clock) ctx.above!.push(v.n)
+ else if (text.trim()) ctx.above!.length = 0
+}
diff --git a/spaces/src/editor.ts b/spaces/src/editor.ts
index d6b0867e..35bbb00e 100644
--- a/spaces/src/editor.ts
+++ b/spaces/src/editor.ts
@@ -20,7 +20,8 @@ import {
} from './fields'
import { planImport, type SourceFile } from './markdown'
import { countOutsideTags, replaceOutsideTags } from './findreplace'
-import { t } from './i18n'
+import { asksForAnswer, evaluate, format, pageContext } from './calc'
+import { t, locale } from './i18n'
import { openAbout } from './about'
import { canWriteInPlace } from '../../kernel/src/save.ts'
import { ICONS, type IconName } from './icons'
@@ -1275,6 +1276,91 @@ export class Editor {
this.paintPage()
}
+ /** the block whose ghost answer is currently showing, if any */
+ private ghostFor: string | null = null
+
+ private clearGhost(): void {
+ this.main.querySelectorAll('.sp-preview').forEach((n) => n.remove())
+ this.ghostFor = null
+ }
+
+ /**
+ * While you type, show what the answer WOULD be.
+ *
+ * The answer is not in the document yet and must not look as though it is:
+ * it renders muted, beside the line, and says how to keep it. Pressing Tab
+ * appends the `=` — so committing is one keystroke, and ignoring it is none,
+ * which is the right balance for something that appears while you are
+ * writing prose.
+ *
+ * Nothing is shown for a line that already asks (the real answer is there),
+ * for a line that does not fully parse, or for a bare number — `42` on its
+ * own is not a calculation anybody needs confirming.
+ */
+ private ghost(id: string, host: HTMLElement): void {
+ const s = this.store
+ if (this.ghostFor && this.ghostFor !== id) this.clearGhost()
+ const block = s.block(id)
+ const page = s.page
+ if (!block || !page) return
+ const line = textOf(host.innerHTML)
+ const holder = host.parentElement
+ if (!holder) return
+ holder.querySelectorAll('.sp-preview').forEach((n) => n.remove())
+ this.ghostFor = null
+ if (asksForAnswer(line) || !/[-+*/^%=]|\bin\b|\bof\b/.test(line)) return
+
+ const ctx = pageContext(page.blocks.map((x) => ({ id: x.id, text: textOf(x.html ?? '') })), id)
+ const v = evaluate(line, ctx)
+ // a bare number is not a calculation; neither is a line that only names a
+ // value already defined
+ if (!v || /^\s*[\d.,_]+\s*$/.test(line)) return
+
+ const g = document.createElement('span')
+ g.className = 'sp-preview'
+ g.contentEditable = 'false'
+ g.setAttribute('aria-hidden', 'true')
+ g.textContent = `= ${format(v, locale())}`
+ const kbd = document.createElement('kbd')
+ kbd.textContent = 'Tab'
+ g.appendChild(kbd)
+ holder.appendChild(g)
+ this.ghostFor = id
+ }
+
+ /**
+ * Keep the ghost answer: append the `=` that asks for it.
+ *
+ * The ANSWER is not written — only the question. That is the whole design:
+ * the document holds `budget * 0.3 =` and the number is derived every time
+ * the page is drawn, so changing `budget` above updates this line too.
+ * Writing the number here would freeze it, and a frozen number that no
+ * longer matches its own expression is worse than no number at all.
+ */
+ private commitAnswer(id: string): boolean {
+ const s = this.store
+ const b = s.block(id)
+ if (!b || s.readOnly) return false
+ const html = `${(b.html ?? '').replace(/\s+$/, '')} =`
+ s.commit(() => { b.html = html })
+ this.clearGhost()
+ this.paintPage()
+ afterPaint(() => {
+ const h = this.main.querySelector<HTMLElement>(`[data-edit="${CSS.escape(id)}"]`)
+ // caret at the END, not selecting the line: you asked for the answer,
+ // you did not ask to replace what you wrote
+ if (!h) return
+ h.focus()
+ const r = document.createRange()
+ r.selectNodeContents(h)
+ r.collapse(false)
+ const sel = getSelection()
+ sel?.removeAllRanges()
+ sel?.addRange(r)
+ })
+ return true
+ }
+
/** Attach behaviour to a freshly painted page. */
private wire(view: HTMLElement): void {
const s = this.store
@@ -1313,9 +1399,11 @@ export class Editor {
if (b) b.html = host.innerHTML
})
this.autoformat(id, host)
+ this.ghost(id, host)
})
host.addEventListener('blur', () => {
if (this.painting) return
+ this.clearGhost()
s.endRun()
const b = s.block(id)
if (b && b.html !== undefined) {
@@ -1725,6 +1813,11 @@ export class Editor {
}
if (e.key === 'Tab') {
e.preventDefault()
+ // A GHOST ANSWER CLAIMS TAB, and only while it is showing. Committing is
+ // then the keystroke your hand is already on, and ignoring it costs
+ // nothing — you carry on typing and it goes away. Shift+Tab still
+ // outdents, so the one gesture people use constantly is never stolen.
+ if (!e.shiftKey && this.ghostFor === cur.id && this.commitAnswer(cur.id)) return
this.indent(cur.id, !e.shiftKey)
return
}
diff --git a/spaces/src/main.ts b/spaces/src/main.ts
index 057d6b77..1deb9dd0 100644
--- a/spaces/src/main.ts
+++ b/spaces/src/main.ts
@@ -14,7 +14,7 @@ import {
} from '../../kernel/src/save.ts'
import { putRecovery, getRecovery, clearRecovery, pruneOld } from '../../kernel/src/autosave.ts'
import { APP_VERSION } from '../../kernel/src/update.ts'
-import { t, applyDirection } from './i18n'
+import { t, locale, applyDirection } from './i18n'
import { parseDoc, docContentKey, uid, newPage, type SpacesDoc, type ParseResult } from './model'
import {
validateDoc, outlineDoc, statsDoc,
@@ -25,6 +25,7 @@ import {
} from './agent'
import { starterDoc } from './starter'
import { textOf } from './sanitize'
+import { evaluate, format, pageContext } from './calc'
import { buildSpacePreview } from './preview'
import { Store } from './store'
import { Editor } from './editor'
@@ -354,6 +355,22 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')
* / menu, no way to type — so an agent creating one would hand a human a
* page they cannot write in.
*/
+ /**
+ * Work out an expression the way a line ending in `=` would.
+ *
+ * `bento.calc('20% of 340')` → 68. With a page id, the names defined on
+ * that page are in scope, so an agent sees exactly what a reader sees.
+ * Returns null for anything the grammar does not fully understand — the
+ * same refusal the page makes, rather than a guess.
+ */
+ calc: (expr: string, pageId?: string) => {
+ const page = pageId ? store.index.page.get(pageId) : undefined
+ const ctx = page
+ ? pageContext(page.blocks.map((b) => ({ id: b.id, text: textOf(b.html ?? '') })), '')
+ : {}
+ const v = evaluate(String(expr ?? ''), ctx)
+ return v ? { value: v.n, text: format(v, locale()) } : null
+ },
newPage: (title: string, parent?: string) => {
if (store.readOnly) return null
// A TITLE, not something that stringifies into one. This takes a string
diff --git a/spaces/src/render.ts b/spaces/src/render.ts
index 25a3301b..4b9fec98 100644
--- a/spaces/src/render.ts
+++ b/spaces/src/render.ts
@@ -12,12 +12,13 @@
import { type SpacesDoc, type Page, type Block, isRemote } from './model'
import { sanitizeInline, inertBody, esc } from './sanitize'
import { tokenize } from './highlight'
-import { t } from './i18n'
+import { t, locale } 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 { answer, feed, freshContext, type CalcCtx } from './calc.ts'
import { ICONS, type IconName } from './icons'
export interface RenderOpts {
@@ -54,6 +55,10 @@ export interface RenderOpts {
*/
export function renderBlocks(page: Page, doc: SpacesDoc, opts: RenderOpts = {}): DocumentFragment {
const frag = document.createDocumentFragment()
+ // MAGIC NOTES' CONTEXT, accumulated as the pass goes. A name is defined by a
+ // line and usable by the lines BELOW it — the same direction a person reads
+ // in, and the reason this needs no second pass and cannot cycle.
+ const calc: CalcCtx = freshContext()
// stack of open containers, innermost last: [blockId, element]
const stack: Array<[string, HTMLElement]> = []
let list: { el: HTMLElement; kind: 'ul' | 'ol'; under: string } | null = null
@@ -80,8 +85,16 @@ export function renderBlocks(page: Page, doc: SpacesDoc, opts: RenderOpts = {}):
}
page.blocks.forEach((b, i) => {
+ // MAGIC NOTES' CONTEXT IS FED AFTER THE BLOCK IS DRAWN, not before, and the
+ // order is the whole difference between `sum above` working and reading 0:
+ // an answering line ENDS the run of figures it summarises, so feeding it
+ // first cleared the very run its own answer needed. After means a line sees
+ // exactly what is above it and nothing of itself — which is also what makes
+ // a name usable by the lines below and by none above.
+ const takeIn = () => feed(calc, textFromHtml(b.html))
if (strip && i < head) {
- strip.appendChild(renderBlock(b, doc, opts))
+ strip.appendChild(renderBlock(b, doc, opts, calc))
+ takeIn()
return
}
const host = hostFor(b.parent)
@@ -99,7 +112,8 @@ export function renderBlocks(page: Page, doc: SpacesDoc, opts: RenderOpts = {}):
list = null
}
- const node = renderBlock(b, doc, opts)
+ const node = renderBlock(b, doc, opts, calc)
+ takeIn()
;(kind && list ? list.el : host).appendChild(node)
// A CONTAINER owns the blocks whose parent is its id. Which types those are
@@ -133,7 +147,7 @@ export function renderBlocks(page: Page, doc: SpacesDoc, opts: RenderOpts = {}):
return frag
}
-export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}): HTMLElement {
+export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}, calc: CalcCtx = {}): HTMLElement {
const type = b.type
const el = document.createElement(TAG_OF[type] ?? 'div')
el.dataset.blockId = b.id
@@ -225,7 +239,7 @@ export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}): HT
// the checkbox is a control, not text: it must not be inside the
// editable host or typing would land in it
el.appendChild(box)
- el.appendChild(inlineHost(b, opts))
+ hostAndAnswer(el, b, opts, calc)
if (b.done) el.classList.add('sp-done')
return el
}
@@ -301,7 +315,7 @@ export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}): HT
label.textContent = toneLabel(raw)
chip.append(mark, label)
el.appendChild(chip)
- el.appendChild(inlineHost(b, opts))
+ hostAndAnswer(el, b, opts, calc)
return el
}
@@ -313,12 +327,12 @@ export function renderBlock(b: Block, doc: SpacesDoc, opts: RenderOpts = {}): HT
twist.setAttribute('aria-label', 'Toggle section')
twist.textContent = '▸'
el.appendChild(twist)
- el.appendChild(inlineHost(b, opts))
+ hostAndAnswer(el, b, opts, calc)
return el
}
default:
- el.appendChild(inlineHost(b, opts))
+ hostAndAnswer(el, b, opts, calc)
return el
}
}
@@ -371,6 +385,28 @@ function calloutMark(host: HTMLElement, b: Block, known: string): void {
host.innerHTML = ICONS[(TONE.get(known) ?? TONE.get('note')!).icon]
}
+/**
+ * The editable host, plus the ANSWER when the line asks for one.
+ *
+ * The answer is a SIBLING of the editable span, never inside it. Inside, it
+ * would be part of what contentEditable hands back on the next keystroke, and
+ * the derived answer would be committed into `html` — which is exactly the
+ * frozen-result design this feature exists to avoid. It is also
+ * contenteditable=false and aria-hidden: it is output, not text, and a screen
+ * reader should hear the line once.
+ */
+function hostAndAnswer(el: HTMLElement, b: Block, opts: RenderOpts, ctx: CalcCtx): void {
+ el.appendChild(inlineHost(b, opts))
+ const ans = answer(textFromHtml(b.html), ctx, locale())
+ if (ans === null) return
+ const out = document.createElement('span')
+ out.className = 'sp-ans'
+ out.contentEditable = 'false'
+ out.setAttribute('aria-hidden', 'true')
+ out.textContent = ans
+ el.appendChild(out)
+}
+
/** The editable text host. Per-block, never one big editable container — that
* is what keeps Selection block-scoped and stops a merge re-minting ids. */
function inlineHost(b: Block, opts: RenderOpts): HTMLElement {
diff --git a/spaces/src/starter.ts b/spaces/src/starter.ts
index d6c7e04b..691de08e 100644
--- a/spaces/src/starter.ts
+++ b/spaces/src/starter.ts
@@ -134,6 +134,15 @@ export function starterDoc(): SpacesDoc {
b('p', 'Anything indented under a toggle folds away with it.', { parent: toggle.id }),
b('divider'),
b('p', 'Inline: <b>⌘B</b>, <i>⌘I</i>, <u>⌘U</u>.'),
+ b('h2', 'Lines that work things out'),
+ b('p', 'End a line with <code>=</code> and it answers. The answer is never stored — change a number above and every line below follows.'),
+ b('p', 'budget = 2400'),
+ b('p', 'flights = 780'),
+ b('p', 'budget - flights ='),
+ b('p', '20% of budget ='),
+ b('p', '940 km in miles ='),
+ b('p', 'today + 3 weeks ='),
+ b('p', 'It understands arithmetic, percentages, units, dates, times, names you define, and <code>sum above</code>. Type a sum without the <code>=</code> and it shows you the answer first — press <code>Tab</code> to keep it.'),
],
},
{
diff --git a/spaces/src/styles.css b/spaces/src/styles.css
index b34a7270..d2c7bd91 100644
--- a/spaces/src/styles.css
+++ b/spaces/src/styles.css
@@ -911,3 +911,42 @@ button.sp-issue-set:hover { background: var(--chrome-2); border-color: #b9c3d2;
.sp-issue { box-shadow: none; }
.sp-prop-val { background: none; }
}
+
+/* Magic notes. The answer is OUTPUT, not text: it sits beside the line in the
+ accent, lighter than the writing, so a page of prose with one sum in it
+ still reads as prose. The ghost preview is the same thing at half strength —
+ it has not been committed to the document yet, and it should not look as
+ though it has. */
+/* `.sp-text` is display:block, so a sibling drops to its own line however it
+ is floated — a float after a full-width block has nothing to sit beside. The
+ host goes INLINE instead, and only on a block that actually has an answer,
+ so nothing else in the editor changes. The answer stays a SIBLING rather
+ than moving inside the host: inside, contentEditable would hand it back on
+ the next keystroke and the derived number would be committed to the file. */
+.sp-b:has(> .sp-ans) > .sp-text { display: inline }
+
+.sp-ans {
+ margin-inline-start: .45em;
+ color: var(--accent-ink);
+ font-variant-numeric: tabular-nums;
+ font-weight: 600;
+ user-select: none;
+}
+.sp-b:has(> .sp-preview) > .sp-text { display: inline }
+
+.sp-preview {
+ margin-inline-start: .45em;
+ color: var(--muted);
+ font-variant-numeric: tabular-nums;
+ user-select: none;
+ opacity: .8;
+}
+.sp-preview kbd {
+ font: inherit; font-size: .82em; opacity: .8;
+ border: 1px solid currentColor; border-radius: 4px; padding: 0 .3em;
+ margin-inline-start: .4em;
+}
+@media (prefers-reduced-motion: no-preference) {
+ .sp-preview { animation: sp-ghost-in .12s ease-out }
+ @keyframes sp-ghost-in { from { opacity: 0 } to { opacity: .75 } }
+}