Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

dash: properties panel shows only what applies; one number-format control (#806)

nyblnet1687dd4230fb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ccf9800b..ee455ad1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2734,6 +2734,15 @@ jobs:
# surface must show fields in its own container, and a planted
# browser-dressed field must be flagged.
run: node scripts/test-dash-fields-browser.mjs
+ - name: The dash properties panel shows only what applies
+ # Per column type on a dataset, Number format / Total / Formula appear
+ # only where they apply, with no money or formula placeholders; one
+ # Number format control on both sheet kinds (Custom… reveals the
+ # pattern, Apply to writes a cell override); unset colour wells paint
+ # the field's own fill, measured from pixels with a set-colour
+ # positive control, light and dark; bare checkboxes; a formula over
+ # Money is Money and one column never mixes grouping.
+ run: node scripts/test-dash-panel-context-browser.mjs
dash-gate-browser:
runs-on: ubuntu-latest
diff --git a/dash/CHANGELOG.md b/dash/CHANGELOG.md
index c6b33481..81fe52c0 100644
--- a/dash/CHANGELOG.md
+++ b/dash/CHANGELOG.md
@@ -233,6 +233,26 @@ The release that came out of watching somebody use 0.2.0.
two independent measures, it opens as 3D bars over two categories instead,
which is both true to the data and the view a spreadsheet cannot draw.
+- **The properties panel shows only what applies to what you selected.** A Text,
+ Date, Yes/No or Category column no longer shows a number format, a Total, or
+ an empty Formula field with another column's expression as its placeholder;
+ Formula appears on a formula column, Total on the number types.
+- **One Number format control.** A cell used to show a format dropdown, a
+ Pattern field and a "Shows as" box, and a dataset showed a cell Pattern and a
+ column Format as well. Now there is one dropdown (General, Number, Currency,
+ Percent, Date, Time, Text, Custom…) with a live sample under it. The pattern
+ field appears only for Custom…. On a dataset, "Apply to" chooses this column
+ or just these cells. Time is new: `2:30 pm` becomes `14:30`.
+- **An unset colour shows as an empty well.** Text colour and Background used
+ to show a grey or cream swatch when nothing was set, so an unformatted cell
+ looked formatted. They are struck-through empty wells now.
+- **Checkboxes in the panel are plain checkboxes**, not full-width boxes that
+ looked like empty text fields.
+- **A formula over money is money.** `Value * 2` on a £ column makes a Money
+ column with the same £ format. A plain number column no longer prints `8600`
+ beside `24,800`: without a pattern it does not group thousands (as Excel's
+ General does not), and a `#,##0` pattern groups every value.
+
## [0.2.0] — 2026-08-03
First release. A workbook is one self-contained HTML file: the data, the grid,
diff --git a/dash/src/cellfmt.ts b/dash/src/cellfmt.ts
index 0763f221..8ed04306 100644
--- a/dash/src/cellfmt.ts
+++ b/dash/src/cellfmt.ts
@@ -515,7 +515,13 @@ export function colourControl(
input.type = 'color'
input.value = /^#[0-9a-f]{6}$/i.test(value) ? value : fallback
input.disabled = readOnly
- if (!value) wrap.classList.add('dc-colour-off')
+ // UNSET is an empty well (cellprops.css), never the fallback colour: the
+ // fallback is only where the OS picker opens. Said in words too, for anyone
+ // not reading the swatch.
+ if (!value) {
+ wrap.classList.add('dc-colour-off')
+ input.title = t('Not set')
+ }
// `change`, never `input`: a drag through the OS colour wheel fires input on
// every pixel, and every one of those would be an undo step.
input.addEventListener('change', () => onChange(input.value))
diff --git a/dash/src/cellprops.css b/dash/src/cellprops.css
index b4012df4..f58bb66c 100644
--- a/dash/src/cellprops.css
+++ b/dash/src/cellprops.css
@@ -1,52 +1,44 @@
/* SPDX-License-Identifier: MIT
Copyright (c) 2026 The Bento authors
- The Cell section of the properties panel — three controls panels.css has no
+ The Cell section of the properties panel — the controls panels.css has no
shape for, and nothing else. Everything that CAN be a `.dp-row` is one: two
stylesheets describing the same row is how a panel starts to look like two
panels.
- THE CORNERS COME FROM panels.css, not from the app's --radius. These three
- controls sit in a column of `.dp-row` fields, and the panel's control radius
- is 6px (slides') where dash's app-wide --radius is 7px — so a preview at 7
- beside a pattern field at 6 was a one-pixel disagreement repeated down the
- Cell section. --dp-radius is declared on `.dp-panel`, so it is the same
- number the field above is using, by construction rather than by copying. */
+ THE CORNERS COME FROM panels.css, not from the app's --radius: --dp-radius
+ is declared on `.dp-panel`, so a control here uses the same number the field
+ above it does, by construction rather than by copying. */
-/* ————— the format preview —————
- A value, printed the way the chosen pattern prints it. It FILLS the control
- column that panels.css lays out (`--dp-ctl`) rather than restating 110px, so
- the section keeps its column when the panel narrows and stacks — a hard 110px
- here was a second definition of the same measurement, and the two would drift
- the first time either moved. Monospace-tabular, so switching decimals moves
- the digits you are looking at rather than the whole string. */
-.dc-preview {
- width: 100%;
+/* ————— the number-format sample —————
+ A value, printed the way the chosen format prints it. It is an ANSWER, not a
+ control, so it draws no box: the bordered "Shows as" field it replaces read
+ as a third format control beside the preset and the pattern. Monospace-
+ tabular, so changing the decimals moves the digits you are looking at rather
+ than the whole string. */
+.dc-sample {
min-width: 0;
- min-height: var(--dp-row, 26px);
- padding: 3px 7px;
- border: 1px solid var(--line);
- border-radius: var(--dp-radius);
- background: var(--wash);
- color: var(--ink);
+ color: var(--ink-2);
font-variant-numeric: tabular-nums;
- font-size: 12.5px;
+ font-size: 12px;
line-height: 18px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
-/* the cell is empty, so this is a SAMPLE — it must not read as the cell's value */
-.dc-preview-sample { color: var(--muted); font-style: italic; }
+/* the cell is empty, so this is an EXAMPLE — it must not read as the cell's value */
+.dc-sample-eg { color: var(--muted); font-style: italic; }
/* ————— colour, with an off state —————
- `<input type="color">` always holds a colour, so "no background" cannot be
- said by the swatch. The × is the off switch; the diagonal slash is what says
- the swatch is not in effect, since the input still paints its fallback. */
+ `<input type="color">` always holds a colour, so "no colour" cannot be said
+ by the swatch — it used to paint its FALLBACK (a grey ink, a cream fill) at
+ 40% under a faint slash, and an unformatted cell read as formatted in review.
+ So an unset well is EMPTY: the swatch is painted transparent and the well
+ shows only the field's own fill, struck through. The × is the off switch. */
.dc-colour {
display: flex;
align-items: center;
gap: 4px;
- width: 100%; /* the control column — see .dc-preview */
+ width: 100%; /* the control column */
min-width: 0;
}
/* The box is THE FIELD's colour well (styles.css); this only sizes. */
@@ -57,15 +49,23 @@
}
.dc-colour input[type='color']:disabled { cursor: default; opacity: 0.5; }
-/* Not set: the swatch is showing a DEFAULT, not the cell's colour, and it has
- to say so — otherwise every unstyled cell looks like it was painted. */
+/* Not set: an EMPTY well. `!important` because the engine paints the swatch
+ from the input's value with a style of its own, and only an important author
+ declaration outranks it. */
.dc-colour-off input[type='color'] {
- opacity: 0.4;
- /* an IMAGE over the field's own fill: the `background` shorthand used to
+ /* an IMAGE over the field's own fill: the `background` shorthand would
reset the fill to transparent along with drawing the strike */
background-image:
linear-gradient(to top right,
- transparent calc(50% - 1px), var(--line-strong) 50%, transparent calc(50% + 1px));
+ transparent calc(50% - 0.75px), var(--muted) 50%, transparent calc(50% + 0.75px));
+}
+.dc-colour-off input[type='color']::-webkit-color-swatch {
+ background: transparent !important;
+ border-color: transparent;
+}
+.dc-colour-off input[type='color']::-moz-color-swatch {
+ background: transparent !important;
+ border-color: transparent;
}
.dc-clear {
diff --git a/dash/src/cellprops.ts b/dash/src/cellprops.ts
index 6a6d715d..649feee2 100644
--- a/dash/src/cellprops.ts
+++ b/dash/src/cellprops.ts
@@ -86,7 +86,7 @@
import './cellprops.css'
import { t } from './i18n.ts'
-import { alignFor, formatValue } from './format.ts'
+import { formatValue } from './format.ts'
import { formatRef } from './a1.ts'
import { isFormula } from './cellformula.ts'
import {
@@ -110,8 +110,12 @@ export type { CellRange, Pos }
export const TEXT_PATTERN = '@'
/** The one date pattern dash writes. ISO, because rule 8 stores ISO. */
export const DATE_PATTERN = 'yyyy-mm-dd'
+/** The one time pattern dash writes: 24-hour, the same canonical-text idea as
+ * Date — a time is stored as `HH:MM` (or `HH:MM:SS`) TEXT, never a fraction
+ * of a day nobody can read in the file. */
+export const TIME_PATTERN = 'hh:mm'
-export type FormatKind = 'general' | 'number' | 'currency' | 'percent' | 'date' | 'text'
+export type FormatKind = 'general' | 'number' | 'currency' | 'percent' | 'date' | 'time' | 'text'
export interface FormatChoice {
kind: FormatKind
@@ -167,6 +171,7 @@ export function buildPattern(c: FormatChoice): string | undefined {
case 'general': return undefined
case 'text': return TEXT_PATTERN
case 'date': return DATE_PATTERN
+ case 'time': return TIME_PATTERN
case 'percent': return `${digitsFor(dp, c.group)}%`
case 'currency': return `${c.symbol}${digitsFor(dp, c.group)}`
case 'number': return digitsFor(dp, c.group)
@@ -177,6 +182,10 @@ export function buildPattern(c: FormatChoice): string | undefined {
export const isTextFormat = (fmt: unknown): boolean =>
typeof fmt === 'string' && fmt.trim() === TEXT_PATTERN
+/** An hour token and no digit placeholder. Asked BEFORE `looksLikeDate`, whose
+ * `m{1,4}` would otherwise claim `hh:mm` for a date by its minutes. */
+const looksLikeTime = (f: string): boolean => /h/i.test(f) && !/[#0]/.test(f) && !/[yd]/i.test(f)
+
const looksLikeDate = (f: string): boolean =>
/[ymd]/i.test(f) && !/[#0]/.test(f) && /y{2,4}|d{1,2}|m{1,4}/i.test(f)
@@ -191,6 +200,7 @@ export function classifyFormat(fmt: string | undefined): FormatChoice {
const f = (fmt ?? '').trim()
if (!f) return { ...DEFAULT_CHOICE }
if (f === TEXT_PATTERN) return { ...DEFAULT_CHOICE, kind: 'text' }
+ if (looksLikeTime(f)) return { ...DEFAULT_CHOICE, kind: 'time' }
if (looksLikeDate(f)) return { ...DEFAULT_CHOICE, kind: 'date' }
const pct = f.includes('%')
@@ -334,6 +344,28 @@ export function readTypedDate(text: string): string | null {
return null
}
+/**
+ * A time of day, canonical `HH:MM` (or `HH:MM:SS`), or null.
+ *
+ * Accepts `14:30`, `9:05`, `2:30 pm`, `2:30PM`, `14:30:15`. Unlike a date there
+ * is no day/month ambiguity to refuse — only an out-of-range hour or minute.
+ */
+export function readTypedTime(text: string): string | null {
+ const m = text.trim().match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?\s*([ap]\.?m\.?)?$/i)
+ if (!m) return null
+ let h = +m[1]
+ const min = +m[2]
+ const sec = m[3] === undefined ? null : +m[3]
+ if (m[4]) {
+ if (h < 1 || h > 12) return null
+ const pm = /^p/i.test(m[4])
+ h = (h % 12) + (pm ? 12 : 0)
+ }
+ if (h > 23 || min > 59 || (sec !== null && sec > 59)) return null
+ const two = (n: number): string => String(n).padStart(2, '0')
+ return `${two(h)}:${two(min)}${sec === null ? '' : `:${two(sec)}`}`
+}
+
// --- the two rules, as functions --------------------------------------------
/** A cell with nothing in it at all is not a cell — sparseness, kept here too. */
@@ -427,6 +459,11 @@ export function recastForFormat(prev: CanvasCell | undefined, fmt: string | unde
const d = readTypedDate(v)
return d ? { cell: { ...base, v: d }, refused: false } : { cell: base, refused: true }
}
+ if (kind === 'time') {
+ if (typeof v !== 'string') return { cell: base, refused: typeof v === 'number' }
+ const tm = readTypedTime(v)
+ return tm ? { cell: { ...base, v: tm }, refused: false } : { cell: base, refused: true }
+ }
if (kind === 'number' || kind === 'currency' || kind === 'percent') {
if (typeof v === 'number') return { cell: base, refused: false } // rule 6: never rescaled
if (typeof v !== 'string') return { cell: base, refused: true }
@@ -588,9 +625,16 @@ export interface CellPropsHost {
/** something the last edit needs to say — a refusal count, usually */
message?: string
say(msg: string): void
+ /** rebuild the panel without a commit — Custom… opening, mostly */
+ rerender(): void
+ /** the value the cursor cell SHOWS — a formula's result, not its absent `v` */
+ value?: unknown
}
-const FORMAT_KINDS: FormatKind[] = ['general', 'number', 'currency', 'percent', 'date', 'text']
+/** The presets a SPREADSHEET cell offers — every kind there is, since the cell
+ * is where this kind of sheet decides what a value IS. */
+export const CELL_KINDS: readonly FormatKind[] =
+ ['general', 'number', 'currency', 'percent', 'date', 'time', 'text']
/**
* A LITERAL translation call per preset, rather than one over a lookup table.
@@ -607,114 +651,227 @@ const kindLabel = (k: FormatKind): string =>
: k === 'currency' ? t('Currency')
: k === 'percent' ? t('Percent')
: k === 'date' ? t('Date')
- : t('Text')
+ : k === 'time' ? t('Time')
+ : t('Text')
/** A quantity for the preview when the cell is empty — something with a shape. */
const SAMPLE = 1234.5
+/** …and a moment, for the two presets that print one. */
+const SAMPLE_DATE = '2026-03-05'
+const SAMPLE_TIME = '14:30'
const valueType = (v: unknown): ColumnType =>
typeof v === 'number' ? 'number' : typeof v === 'boolean' ? 'bool' : 'text'
-/**
- * The Cell section: what this cell IS, and what it looks like.
- *
- * Reads the sheet, writes patches, and owns no state — the panel rebuilds on
- * every `doc` and every selection change, so anything remembered here would be
- * a second copy of the document going stale.
- */
-export function buildCellProps(ctx: CellPropsHost): void {
- const { host, kit, sheet, ranges, cursor, readOnly } = ctx
- const keys = rangeKeys(ranges)
- const cursorKey = a1(cursor.row, cursor.col)
- const cell: CanvasCell | undefined = sheet.cells[cursorKey]
+// ═══ ONE NUMBER-FORMAT CONTROL ═════════════════════════════════════════════
+//
+// Both kinds of sheet used to show three controls for one idea: a preset
+// dropdown, a raw Pattern field and a "Shows as" box on a spreadsheet; a cell
+// Pattern AND a column Format on a dataset, each with its own placeholder.
+// They are one control now, drawn by this one builder on both kinds:
+//
+// Number format [preset ▾] General, Number, Currency, Percent, … Custom…
+// (Decimals / Thousands separator / Symbol — only for the numeric presets)
+// Pattern [#,##0.00 "kg"] — ONLY while the preset is Custom…
+// £1,234.50 — a live sample, printed, not a field
+//
+// and, on a dataset, an "Apply to" choice above it — this column or these
+// cells — because there the column owns the format and a cell may override it.
+// No model field changed: the column still writes `format`, a cell override
+// still writes its own `format`, a spreadsheet cell still writes its own.
- kit.section(host, t('Cell'))
- kit.readonlyRow(host, t('Selection'), describeSelection(ranges) || cursorKey)
+/** What the preset select can stand on besides a FormatKind. */
+export type FormatOption = FormatKind | 'inherit'
- if (keys.length >= KEY_CAP) {
- kit.note(host, t('Only the first {n} cells of this selection will be changed.')
- .replace('{n}', String(KEY_CAP)))
- }
+export interface NumberFormatCtx {
+ host: HTMLElement
+ kit: PanelKit
+ /** the pattern stored in the CURRENT scope; absent = General (or inherit) */
+ fmt: string | undefined
+ /** the presets this scope offers, in order. Custom… is always appended. */
+ kinds: readonly FormatOption[]
+ /** the pattern a cell inherits when it has none (dataset, cells scope) */
+ inherited?: string
+ /** dataset only: the scope switch */
+ scope?: { value: 'column' | 'cells'; set(v: 'column' | 'cells'): void }
+ /** the sample, printed with a candidate pattern */
+ preview(fmt: string | undefined): { text: string; sample: boolean }
+ /** identifies the selection, so "Custom…" stays open across a rebuild */
+ key: string
+ locale?: string
+ readOnly: boolean
+ /** `undefined` clears the field in this scope */
+ write(next: string | undefined): void
+ rerender(): void
+}
- // --- number format --------------------------------------------------------
+/** Which selection has Custom… open with no custom pattern stored yet. */
+let customOpen: string | null = null
+/** …and whether the Pattern field it reveals should take the focus. */
+let focusPattern = false
+
+/** What the preset select shows for a stored pattern, in a given scope. */
+export function formatOptionFor(
+ fmt: string | undefined, kinds: readonly FormatOption[],
+): FormatOption | 'custom' {
+ if (!fmt) return kinds.includes('inherit') ? 'inherit' : 'general'
+ if (isCustomPattern(fmt)) return 'custom'
+ const k = classifyFormat(fmt).kind
+ return kinds.includes(k) ? k : 'custom'
+}
- const fmt = typeof cell?.format === 'string' ? cell.format : undefined
- const custom = isCustomPattern(fmt)
- const choice: FormatChoice = {
- ...classifyFormat(fmt),
- ...(fmt ? {} : { symbol: localeSymbol(ctx.locale) }),
+export function buildNumberFormat(ctx: NumberFormatCtx): void {
+ const { host, kit, fmt, kinds, readOnly } = ctx
+ const w = (next: string | undefined): void => { if (!readOnly) ctx.write(next) }
+
+ if (ctx.scope) {
+ const sc = ctx.scope
+ const scopeSel = kit.select(
+ [['column', t('This column')] as const, ['cells', t('These cells')] as const],
+ sc.value, (v) => sc.set(v as 'column' | 'cells'))
+ scopeSel.disabled = readOnly
+ scopeSel.dataset.dpField = 'format-scope'
+ kit.row(host, t('Apply to'), scopeSel)
}
- if (!fmt) choice.kind = 'general'
- const write = (next: string | undefined): void => {
- if (readOnly) return
- const r = formatPatch(sheet, keys, next)
- if (r.patch) ctx.commit(r.patch)
- ctx.say(r.refused
- ? t('{n} value(s) could not be read as this format, and were left as they are.')
- .replace('{n}', String(r.refused))
- : '')
+ const stored = formatOptionFor(fmt, kinds)
+ if (stored === 'custom' && customOpen === ctx.key) customOpen = null
+ const shown = customOpen === ctx.key ? 'custom' : stored
+ // A cell inheriting its column's pattern starts every preset from THAT
+ // pattern's decimals and symbol — "Number" on a £#,##0 column means 0dp.
+ const basis = fmt ?? ctx.inherited
+ const was = classifyFormat(basis)
+ const choice: FormatChoice = {
+ ...was,
+ ...(basis && was.kind === 'currency' ? {} : { symbol: localeSymbol(ctx.locale) }),
}
- const kinds: Array<readonly [string, string]> = [
- ...FORMAT_KINDS.map((k) => [k, kindLabel(k)] as const),
- ...(custom ? [['custom', t('Custom')] as const] : []),
+ const options: Array<readonly [string, string]> = [
+ ...kinds.map((k) => [k, k === 'inherit' ? t('Same as column') : kindLabel(k)] as const),
+ ['custom', t('Custom…')] as const,
]
- const kindSel = kit.select(kinds, custom ? 'custom' : choice.kind, (v) => {
- if (v === 'custom') return // a hand-written pattern is not ours to respell
+ const sel = kit.select(options, shown, (v) => {
+ if (v === 'custom') { customOpen = ctx.key; focusPattern = true; ctx.rerender(); return }
+ customOpen = null
+ if (v === 'inherit' || v === 'general') { w(undefined); ctx.rerender(); return }
const kind = v as FormatKind
- // A cell that had no format takes the preset's own defaults; one that had
- // a format keeps the decimals its author chose.
- write(buildPattern({ ...choice, ...(fmt ? {} : defaultsFor(kind)), kind }))
+ // No pattern yet: the preset's own defaults. A pattern already: keep the
+ // decimals its author chose — switching Currency to Number must not
+ // silently re-round a column somebody set to 3dp.
+ w(buildPattern({ ...choice, ...(basis ? {} : defaultsFor(kind)), kind }))
+ ctx.rerender()
})
- kindSel.disabled = readOnly
- kit.row(host, t('Format'), kindSel)
-
- const numeric = !custom &&
- (choice.kind === 'number' || choice.kind === 'currency' || choice.kind === 'percent')
+ sel.disabled = readOnly
+ sel.dataset.dpField = 'number-format'
+ kit.row(host, t('Number format'), sel)
- if (numeric) {
+ const preset = shown === 'number' || shown === 'currency' || shown === 'percent' ? shown : null
+ if (preset) {
const dp = kit.number(choice.dp, 1, (v) =>
- write(buildPattern({ ...choice, dp: Math.max(0, Math.min(9, Math.round(v))) })))
+ w(buildPattern({ ...choice, kind: preset, dp: Math.max(0, Math.min(9, Math.round(v))) })))
dp.min = '0'
dp.max = '9'
dp.disabled = readOnly
kit.row(host, t('Decimals'), dp)
- const grp = kit.check(choice.group, (v) => write(buildPattern({ ...choice, group: v })))
+ const grp = kit.check(choice.group, (v) => w(buildPattern({ ...choice, kind: preset, group: v })))
grp.disabled = readOnly
kit.row(host, t('Thousands separator'), grp)
- if (choice.kind === 'currency') {
+ if (preset === 'currency') {
const sym = kit.text(choice.symbol, (v) =>
- write(buildPattern({ ...choice, symbol: v.trim() || choice.symbol })))
+ w(buildPattern({ ...choice, kind: preset, symbol: v.trim() || choice.symbol })))
sym.disabled = readOnly
sym.classList.add('dp-narrow')
kit.row(host, t('Symbol'), sym)
}
}
- // THE ESCAPE HATCH, and it is not a lesser control: format.ts accepts any
- // Excel-ish pattern and the presets are only the six people ask for by name.
- const pat = kit.text(fmt ?? '', (v) => {
- const next = v.trim()
- if (next === (fmt ?? '')) return
- write(next || undefined)
+ // THE ESCAPE HATCH — revealed only for Custom…, where it is the whole control.
+ if (shown === 'custom') {
+ const pat = kit.text(fmt ?? '', (v) => {
+ const next = v.trim()
+ if (next === (fmt ?? '')) return
+ w(next || undefined)
+ })
+ pat.placeholder = basis ?? '#,##0.00'
+ pat.classList.add('dp-mono')
+ pat.disabled = readOnly
+ pat.dataset.dpField = 'pattern'
+ kit.row(host, t('Pattern'), pat)
+ if (focusPattern) {
+ focusPattern = false
+ // Selected, so typing REPLACES the preset's pattern it opened on and
+ // an arrow key edits it instead.
+ queueMicrotask(() => { if (pat.isConnected) { pat.focus(); pat.select() } })
+ }
+ }
+
+ // The live sample: what the pattern DOES, against this cell's own value. A
+ // printed line under the control, not a field — it is an answer, not a
+ // question, and a bordered box here read as a third control.
+ const p = ctx.preview(basis)
+ const line = document.createElement('div')
+ line.className = 'dp-row dp-row-sample'
+ const out = document.createElement('span')
+ out.className = p.sample ? 'dc-sample dc-sample-eg' : 'dc-sample'
+ out.title = t('Sample')
+ out.textContent = p.text
+ line.append(document.createElement('span'), out)
+ host.appendChild(line)
+}
+
+/** The sample for a spreadsheet cell: its own value, or a shape for the preset. */
+export function cellPreview(
+ value: unknown, fmt: string | undefined,
+): { text: string; sample: boolean } {
+ const empty = value === undefined || value === null || value === ''
+ const kind = classifyFormat(fmt).kind
+ const v = !empty ? value
+ : kind === 'date' ? SAMPLE_DATE : kind === 'time' ? SAMPLE_TIME : SAMPLE
+ return { text: formatValue(v, { type: valueType(v), format: fmt }), sample: empty }
+}
+
+/**
+ * The Cell section: what this cell IS, and what it looks like.
+ *
+ * Reads the sheet, writes patches, and owns no state — the panel rebuilds on
+ * every `doc` and every selection change, so anything remembered here would be
+ * a second copy of the document going stale.
+ */
+export function buildCellProps(ctx: CellPropsHost): void {
+ const { host, kit, sheet, ranges, cursor, readOnly } = ctx
+ const keys = rangeKeys(ranges)
+ const cursorKey = a1(cursor.row, cursor.col)
+ const cell: CanvasCell | undefined = sheet.cells[cursorKey]
+
+ kit.section(host, t('Cell'))
+ kit.readonlyRow(host, t('Selection'), describeSelection(ranges) || cursorKey)
+
+ if (keys.length >= KEY_CAP) {
+ kit.note(host, t('Only the first {n} cells of this selection will be changed.')
+ .replace('{n}', String(KEY_CAP)))
+ }
+
+ // --- number format --------------------------------------------------------
+
+ const fmt = typeof cell?.format === 'string' ? cell.format : undefined
+ buildNumberFormat({
+ host, kit, fmt, kinds: CELL_KINDS,
+ preview: (f) => cellPreview(ctx.value !== undefined ? ctx.value : cell?.v, f),
+ key: `${sheet.id}!${cursorKey}`,
+ locale: ctx.locale,
+ readOnly,
+ rerender: ctx.rerender,
+ write: (next) => {
+ const r = formatPatch(sheet, keys, next)
+ if (r.patch) ctx.commit(r.patch)
+ ctx.say(r.refused
+ ? t('{n} value(s) could not be read as this format, and were left as they are.')
+ .replace('{n}', String(r.refused))
+ : '')
+ },
})
- pat.placeholder = '#,##0.00'
- pat.classList.add('dp-mono')
- pat.disabled = readOnly
- kit.row(host, t('Pattern'), pat)
-
- // What the pattern DOES, against this cell's own value. The one control that
- // answers "why does my number look like that" without a save and a reload.
- const shownVal = cell?.v === undefined || cell.v === '' ? SAMPLE : cell.v
- const prev = document.createElement('div')
- prev.className = 'dc-preview'
- prev.textContent = formatValue(shownVal, { type: valueType(shownVal), format: fmt })
- if (cell?.v === undefined || cell.v === '') prev.classList.add('dc-preview-sample')
- prev.style.textAlign = (cell?.align as string | undefined) ?? alignFor(valueType(shownVal))
- kit.row(host, t('Shows as'), prev)
if (isTextFormat(fmt)) {
kit.note(host, t('Text cells keep exactly what is typed — leading zeros, slashes, and an = that is not a formula.'))
@@ -731,7 +888,7 @@ export function buildCellProps(ctx: CellPropsHost): void {
// ONE section builder, drawn identically on the dataset kind — see
// cellfmt.ts. This kind's own contribution above it is the FORMAT block,
- // which is where its cell types are decided and is meaningless on a dataset.
+ // which is where its cell types are decided.
buildAppearanceSection({ host, kit, cell: cell as Appearance | undefined, readOnly, write: style })
if (ctx.message) kit.note(host, ctx.message)
diff --git a/dash/src/computedtype.ts b/dash/src/computedtype.ts
index b8c2e3f3..76267af4 100644
--- a/dash/src/computedtype.ts
+++ b/dash/src/computedtype.ts
@@ -46,18 +46,20 @@
// trips it, and `scripts/test-dash-computedtype.ts` asserts that rather than
// assuming it.
-import { isErr, recalc } from './formula.ts'
+import { dependencies, isErr, recalc } from './formula.ts'
import { inferColumn } from './import.ts'
import type { Column, ColumnType, TableSheet } from './model.ts'
/** Why a type was chosen — for the rig, and for anything that wants to say so. */
-export type ComputedWhy = 'number' | 'bool' | 'text' | 'mixed' | 'nothing'
+export type ComputedWhy = 'number' | 'money' | 'bool' | 'text' | 'mixed' | 'nothing'
export interface ComputedType {
type: ColumnType
why: ComputedWhy
/** values that were real evidence: not blank, not an error */
judged: number
+ /** what a Money result carries over from the money column it came from */
+ carry?: Pick<Column, 'format' | 'unit'>
}
const blankish = (v: unknown): boolean =>
@@ -125,5 +127,46 @@ export function inferComputedType(
// throw over one, or the Add-column button dies mid-click.
return { type: 'text', why: 'nothing', judged: 0 }
}
- return judgeComputed(values)
+ return carryMoney(sheet, expr, judgeComputed(values))
+}
+
+/**
+ * NUMBERS COMPUTED FROM MONEY ARE MONEY.
+ *
+ * `Value * 2` over a £ column used to arrive as a plain Number column: no £,
+ * and — because a plain number groups only from 10,000 up — `8600` printed
+ * beside `24,800` in the same column. Excel carries the currency format of the
+ * cell a formula references; this is that rule at column grain: a numeric
+ * result whose expression reads ANY Money column is Money, with that column's
+ * format and unit. A ratio of two money columns is the case this gets wrong
+ * (it is a plain number), and the type stays one click away in the panel.
+ */
+export function carryMoney(sheet: TableSheet, expr: string, judged: ComputedType): ComputedType {
+ if (judged.type !== 'number') return judged
+ let refs: string[]
+ try { refs = dependencies(expr) } catch { return judged }
+ const byKey = new Map<string, Column>()
+ for (const c of sheet.columns) { byKey.set(c.id.toLowerCase(), c); byKey.set(c.name.toLowerCase(), c) }
+ const money = refs.map((r) => byKey.get(r.toLowerCase())).find((c) => c?.type === 'money')
+ if (!money) return judged
+ const carry: Pick<Column, 'format' | 'unit'> = {}
+ if (typeof money.format === 'string' && money.format) carry.format = money.format
+ if (typeof money.unit === 'string' && money.unit) carry.unit = money.unit
+ return { ...judged, type: 'money', why: 'money', carry }
+}
+
+/**
+ * The patch for a formula EDIT on an existing column: re-type it, but never
+ * overrule a person. The type moves only while it still matches what the OLD
+ * expression produced (nobody has chosen one by hand), and a re-type to Money
+ * brings the money column's format and unit only where this column has none.
+ */
+export function retypePatch(
+ col: Column, before: ComputedType, after: ComputedType, formula: string,
+): Partial<Column> {
+ if (!(col.type === before.type && after.type !== col.type)) return { formula }
+ const patch: Partial<Column> = { formula, type: after.type }
+ if (after.carry?.format && !col.format) patch.format = after.carry.format
+ if (after.carry?.unit && !col.unit) patch.unit = after.carry.unit
+ return patch
}
diff --git a/dash/src/format.ts b/dash/src/format.ts
index 591fb71e..25d8c172 100644
--- a/dash/src/format.ts
+++ b/dash/src/format.ts
@@ -137,7 +137,12 @@ export function formatValue(v: unknown, col: Pick<Column, 'type' | 'format'>): s
const rawDp = p.dp ?? (t === 'money' ? 2 : isPct ? 0 : shown % 1 === 0 ? 0 : 2)
const dp = Math.max(0, Math.min(100, rawDp))
- const group = p.group || (!col.format && (t === 'money' || Math.abs(shown) >= 10_000))
+ // GROUPING IS A PROPERTY OF THE COLUMN, never of one value. A plain number
+ // used to group from 10,000 up, so one column printed `8600` beside `24,800`.
+ // With no pattern, Money groups (as currency always does) and a plain number
+ // does not — Excel's, Sheets' and Numbers' General, and the only rule that
+ // cannot print a year as 2,026. A pattern with `#,##0` groups everything.
+ const group = p.group || (!col.format && t === 'money')
// A percent COLUMN prints a `%` even with no pattern saying so, which
// `assemble` cannot know from the pattern alone — so the sign is appended
// here when the type, rather than the pattern, is what asked for it.
diff --git a/dash/src/grid.ts b/dash/src/grid.ts
index 5b9c2e88..c85dc31b 100644
--- a/dash/src/grid.ts
+++ b/dash/src/grid.ts
@@ -1819,6 +1819,11 @@ export class Grid {
el.hidden = false
}
+ /** The value under the cursor — the properties panel's format sample. */
+ cursorValue(): unknown {
+ return this.valueAt(this.sel.cursor.row, this.sel.cursor.col)
+ }
+
/** Value at a VISIBLE position — what the clipboard and the status bar read. */
private valueAt(row: number, ci: number): unknown {
if (this.canvas) return this.cvValueAt(row, ci)
diff --git a/dash/src/i18n/de.ts b/dash/src/i18n/de.ts
index 73750f98..ab25acfa 100644
--- a/dash/src/i18n/de.ts
+++ b/dash/src/i18n/de.ts
@@ -465,7 +465,6 @@ export const de: Catalog = {
"Show sheet tabs ([)": "Blattregister einblenden ([)",
"Showing the first {n} of {total}.": "Es werden die ersten {n} von {total} angezeigt.",
"Shown as bars — a scatter has no category to select.": "Als Balken dargestellt — ein Punktdiagramm hat keine Kategorie zum Auswählen.",
- "Shows as": "Wird angezeigt als",
"Shrink a little, then continue on later pages": "Etwas verkleinern, dann auf Folgeseiten weiterlaufen",
"Shrink until the sheet fits the page width": "So weit verkleinern, dass das Blatt in die Seitenbreite passt",
"Size": "Größe",
@@ -505,7 +504,6 @@ export const de: Catalog = {
"That version could not be read.": "Diese Version konnte nicht gelesen werden.",
"That version has no table sheet to show.": "Diese Version enthält kein Tabellenblatt zum Anzeigen.",
"That workbook has no table sheet to show.": "Diese Arbeitsmappe enthält kein Tabellenblatt zum Anzeigen.",
- "The column decides what these cells ARE. A pattern here only changes how they print.": "Die Spalte entscheidet, WAS diese Zellen sind. Ein Muster hier ändert nur die Darstellung.",
"The document block is present but could not be read.": "Der Dokumentblock ist vorhanden, konnte aber nicht gelesen werden.",
"The first row holds the column names": "Die erste Zeile enthält die Spaltennamen",
"The formula in {cols} was carried down to the new row. A column formula would fill every new row, without being asked.": "Die Formel in {cols} wurde in die neue Zeile übernommen. Eine Spaltenformel würde jede neue Zeile füllen, ungefragt.",
@@ -756,4 +754,13 @@ export const de: Catalog = {
"Copy saved — you are still editing the original": "Kopie gespeichert — Sie bearbeiten weiterhin das Original",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "Die Absturzwiederherstellung ist für diese Arbeitsmappe deaktiviert – sie ist zu groß für eine Sicherungskopie. Speichern Sie häufig.",
"A backup of this workbook for yourself — same workbook, same live session.": "Eine Sicherungskopie für Sie — gleiche Arbeitsmappe, gleiche Live-Sitzung.",
+ "Apply to": "Anwenden auf",
+ "Custom…": "Benutzerdefiniert…",
+ "Not set": "Nicht festgelegt",
+ "Number format": "Zahlenformat",
+ "Same as column": "Wie Spalte",
+ "Sample": "Beispiel",
+ "These cells": "Diese Zellen",
+ "This column": "Diese Spalte",
+ "Time": "Uhrzeit",
}
diff --git a/dash/src/i18n/es.ts b/dash/src/i18n/es.ts
index 7215f795..df6e6adc 100644
--- a/dash/src/i18n/es.ts
+++ b/dash/src/i18n/es.ts
@@ -465,7 +465,6 @@ export const es: Catalog = {
"Show sheet tabs ([)": "Mostrar las pestañas de hojas ([)",
"Showing the first {n} of {total}.": "Se muestran las primeras {n} de {total}.",
"Shown as bars — a scatter has no category to select.": "Se muestra como barras: un gráfico de dispersión no tiene categoría que seleccionar.",
- "Shows as": "Se muestra como",
"Shrink a little, then continue on later pages": "Reducir un poco y continuar en las páginas siguientes",
"Shrink until the sheet fits the page width": "Reducir hasta que la hoja quepa en el ancho de la página",
"Size": "Tamaño",
@@ -505,7 +504,6 @@ export const es: Catalog = {
"That version could not be read.": "No se ha podido leer esa versión.",
"That version has no table sheet to show.": "Esa versión no tiene ninguna hoja de tabla que mostrar.",
"That workbook has no table sheet to show.": "Ese libro no tiene ninguna hoja de tabla que mostrar.",
- "The column decides what these cells ARE. A pattern here only changes how they print.": "La columna decide QUÉ SON estas celdas. Un patrón aquí solo cambia cómo se muestran.",
"The document block is present but could not be read.": "El bloque del documento está presente, pero no se ha podido leer.",
"The first row holds the column names": "La primera fila contiene los nombres de las columnas",
"The formula in {cols} was carried down to the new row. A column formula would fill every new row, without being asked.": "La fórmula de {cols} se ha extendido a la nueva fila. Una fórmula de columna rellenaría cada fila nueva, sin que se lo pidan.",
@@ -756,4 +754,13 @@ export const es: Catalog = {
"Copy saved — you are still editing the original": "Copia guardada: sigues editando el original",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "La recuperación tras fallos está desactivada para este libro: es demasiado grande para guardar una copia de seguridad. Guarda a menudo.",
"A backup of this workbook for yourself — same workbook, same live session.": "Una copia de seguridad para ti — mismo libro, misma sesión en vivo.",
+ "Apply to": "Aplicar a",
+ "Custom…": "Personalizado…",
+ "Not set": "Sin definir",
+ "Number format": "Formato de número",
+ "Same as column": "Igual que la columna",
+ "Sample": "Ejemplo",
+ "These cells": "Estas celdas",
+ "This column": "Esta columna",
+ "Time": "Hora",
}
diff --git a/dash/src/i18n/fr.ts b/dash/src/i18n/fr.ts
index 9cea8e7e..5d9cecc2 100644
--- a/dash/src/i18n/fr.ts
+++ b/dash/src/i18n/fr.ts
@@ -465,7 +465,6 @@ export const fr: Catalog = {
"Show sheet tabs ([)": "Afficher les onglets de feuilles ([)",
"Showing the first {n} of {total}.": "Affichage des {n} premières sur {total}.",
"Shown as bars — a scatter has no category to select.": "Affiché en barres — un nuage de points n’a pas de catégorie à sélectionner.",
- "Shows as": "Affiché comme",
"Shrink a little, then continue on later pages": "Réduire un peu, puis continuer sur les pages suivantes",
"Shrink until the sheet fits the page width": "Réduire jusqu’à ce que la feuille tienne dans la largeur de la page",
"Size": "Taille",
@@ -505,7 +504,6 @@ export const fr: Catalog = {
"That version could not be read.": "Cette version n’a pas pu être lue.",
"That version has no table sheet to show.": "Cette version n’a aucune feuille de tableau à afficher.",
"That workbook has no table sheet to show.": "Ce classeur n’a aucune feuille de tableau à afficher.",
- "The column decides what these cells ARE. A pattern here only changes how they print.": "C’est la colonne qui décide de CE QUE SONT ces cellules. Un format ici ne change que leur affichage.",
"The document block is present but could not be read.": "Le bloc document est présent mais n’a pas pu être lu.",
"The first row holds the column names": "La première ligne contient les noms de colonnes",
"The formula in {cols} was carried down to the new row. A column formula would fill every new row, without being asked.": "La formule de {cols} a été reportée sur la nouvelle ligne. Une formule de colonne remplirait chaque nouvelle ligne, sans qu’on le lui demande.",
@@ -756,4 +754,13 @@ export const fr: Catalog = {
"Copy saved — you are still editing the original": "Copie enregistrée — vous modifiez toujours l'original",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "La récupération après plantage est désactivée pour ce classeur : il est trop volumineux pour en garder une copie de secours. Enregistrez souvent.",
"A backup of this workbook for yourself — same workbook, same live session.": "Une sauvegarde pour vous — même classeur, même session live.",
+ "Apply to": "Appliquer à",
+ "Custom…": "Personnalisé…",
+ "Not set": "Non défini",
+ "Number format": "Format de nombre",
+ "Same as column": "Comme la colonne",
+ "Sample": "Aperçu",
+ "These cells": "Ces cellules",
+ "This column": "Cette colonne",
+ "Time": "Heure",
}
diff --git a/dash/src/i18n/it.ts b/dash/src/i18n/it.ts
index 5c87bd1a..6368184c 100644
--- a/dash/src/i18n/it.ts
+++ b/dash/src/i18n/it.ts
@@ -465,7 +465,6 @@ export const it: Catalog = {
"Show sheet tabs ([)": "Mostra le schede dei fogli ([)",
"Showing the first {n} of {total}.": "Mostrate le prime {n} di {total}.",
"Shown as bars — a scatter has no category to select.": "Mostrato a barre — un grafico a dispersione non ha una categoria da selezionare.",
- "Shows as": "Mostrato come",
"Shrink a little, then continue on later pages": "Riduci un poco, poi continua nelle pagine successive",
"Shrink until the sheet fits the page width": "Riduci finché il foglio non rientra nella larghezza della pagina",
"Size": "Dimensione",
@@ -505,7 +504,6 @@ export const it: Catalog = {
"That version could not be read.": "Non è stato possibile leggere quella versione.",
"That version has no table sheet to show.": "Quella versione non ha alcun foglio tabella da mostrare.",
"That workbook has no table sheet to show.": "Quella cartella di lavoro non ha alcun foglio tabella da mostrare.",
- "The column decides what these cells ARE. A pattern here only changes how they print.": "È la colonna a decidere COSA SONO queste celle. Un formato qui cambia solo come vengono mostrate.",
"The document block is present but could not be read.": "Il blocco del documento è presente ma non è stato possibile leggerlo.",
"The first row holds the column names": "La prima riga contiene i nomi delle colonne",
"The formula in {cols} was carried down to the new row. A column formula would fill every new row, without being asked.": "La formula in {cols} è stata riportata nella nuova riga. Una formula di colonna riempirebbe ogni nuova riga, senza che glielo si chieda.",
@@ -756,4 +754,13 @@ export const it: Catalog = {
"Copy saved — you are still editing the original": "Copia salvata: stai ancora modificando l'originale",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "Il ripristino dopo un arresto anomalo è disattivato per questa cartella di lavoro: è troppo grande per conservarne una copia di backup. Salva spesso.",
"A backup of this workbook for yourself — same workbook, same live session.": "Una copia di riserva per te — stessa cartella di lavoro, stessa sessione live.",
+ "Apply to": "Applica a",
+ "Custom…": "Personalizzato…",
+ "Not set": "Non impostato",
+ "Number format": "Formato numero",
+ "Same as column": "Come la colonna",
+ "Sample": "Esempio",
+ "These cells": "Queste celle",
+ "This column": "Questa colonna",
+ "Time": "Ora",
}
diff --git a/dash/src/i18n/ja.ts b/dash/src/i18n/ja.ts
index d1c5e5d7..55e69a13 100644
--- a/dash/src/i18n/ja.ts
+++ b/dash/src/i18n/ja.ts
@@ -465,7 +465,6 @@ export const ja: Catalog = {
"Show sheet tabs ([)": "シートタブを表示 ([)",
"Showing the first {n} of {total}.": "{total} 件のうち先頭 {n} 件を表示しています。",
"Shown as bars — a scatter has no category to select.": "棒グラフで表示しています — 散布図には選択できるカテゴリがありません。",
- "Shows as": "表示例",
"Shrink a little, then continue on later pages": "少し縮小し、収まらない列は次のページへ",
"Shrink until the sheet fits the page width": "ページ幅に収まるまで縮小する",
"Size": "サイズ",
@@ -505,7 +504,6 @@ export const ja: Catalog = {
"That version could not be read.": "そのバージョンを読み取れませんでした。",
"That version has no table sheet to show.": "そのバージョンには表示できるテーブルシートがありません。",
"That workbook has no table sheet to show.": "そのブックには表示できるテーブルシートがありません。",
- "The column decides what these cells ARE. A pattern here only changes how they print.": "これらのセルが何であるかは列が決めます。ここでの書式は表示のしかたを変えるだけです。",
"The document block is present but could not be read.": "ドキュメントブロックはありますが、読み取れませんでした。",
"The first row holds the column names": "先頭行を列名として使う",
"The formula in {cols} was carried down to the new row. A column formula would fill every new row, without being asked.": "{cols} の数式を新しい行に引き継ぎました。列の数式なら、頼まなくてもすべての新しい行が埋まります。",
@@ -756,4 +754,13 @@ export const ja: Catalog = {
"Copy saved — you are still editing the original": "コピーを保存しました — 編集中なのは引き続き元のファイルです",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "このブックのクラッシュ復旧はオフです — 大きすぎてバックアップを保存できません。こまめに保存してください。",
"A backup of this workbook for yourself — same workbook, same live session.": "自分用のバックアップ — 同じブック・同じライブセッションです。",
+ "Apply to": "適用先",
+ "Custom…": "カスタム…",
+ "Not set": "未設定",
+ "Number format": "表示形式",
+ "Same as column": "列と同じ",
+ "Sample": "サンプル",
+ "These cells": "これらのセル",
+ "This column": "この列",
+ "Time": "時刻",
}
diff --git a/dash/src/i18n/packed.ts b/dash/src/i18n/packed.ts
index 5a434412..71ba0f66 100644
--- a/dash/src/i18n/packed.ts
+++ b/dash/src/i18n/packed.ts
@@ -70,6 +70,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Appearance": ["外観","外观","外觀","Apariencia","Apparence","Darstellung","Aspetto","Aparência"],
"Applies to": ["適用範囲","适用于","套用於","Se aplica a","S’applique à","Gilt für","Si applica a","Aplica-se a"],
"Apply filter": ["フィルターを適用","应用筛选","套用篩選","Aplicar filtro","Appliquer le filtre","Filter anwenden","Applica filtro","Aplicar filtro"],
+ "Apply to": ["適用先","应用于","套用至","Aplicar a","Appliquer à","Anwenden auf","Applica a","Aplicar a"],
"At least {n} existing value(s) break this rule. They are marked, never changed.": ["既存の値のうち少なくとも {n} 件がこの規則に反しています。印が付くだけで、変更はされません。","已有的值中至少有 {n} 个不符合此规则。它们只会被标记,不会被更改。","既有的值中至少有 {n} 個不符合此規則。它們只會被標記,不會被更改。","Al menos {n} valor(es) existente(s) incumplen esta regla. Se marcan, nunca se cambian.","Au moins {n} valeur(s) existante(s) enfreignent cette règle. Elles sont signalées, jamais modifiées.","Mindestens {n} vorhandene Wert(e) verstoßen gegen diese Regel. Sie werden markiert, nie geändert.","Almeno {n} valore/i esistente/i violano questa regola. Vengono segnalati, mai modificati.","Pelo menos {n} valor(es) existente(s) infringem esta regra. Eles são marcados, nunca alterados."],
"Author": ["作成者","作者","作者","Autor","Auteur","Autor","Autore","Autor"],
"Auto": ["自動","自动","自動","Automático","Auto","Automatisch","Automatico","Automático"],
@@ -150,6 +151,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Custom": ["ユーザー定義","自定义","自訂","Personalizado","Personnalisé","Benutzerdefiniert","Personalizzato","Personalizado"],
"Custom formula": ["カスタム数式","自定义公式","自訂公式","Fórmula personalizada","Formule personnalisée","Eigene Formel","Formula personalizzata","Fórmula personalizada"],
"Custom formula (not checked by this build)": ["カスタム数式 (このビルドでは検証されません)","自定义公式(此版本不做检查)","自訂公式(此版本不做檢查)","Fórmula personalizada (esta versión no la comprueba)","Formule personnalisée (non vérifiée par cette version)","Eigene Formel (von dieser Version nicht geprüft)","Formula personalizzata (non verificata da questa versione)","Fórmula personalizada (não verificada por esta versão)"],
+ "Custom…": ["カスタム…","自定义…","自訂…","Personalizado…","Personnalisé…","Benutzerdefiniert…","Personalizzato…","Personalizado…"],
"Cut": ["切り取り","剪切","剪下","Cortar","Couper","Ausschneiden","Taglia","Recortar"],
"Cut the selection": ["選択範囲を切り取る","剪切所选内容","剪下選取範圍","Cortar la selección","Couper la sélection","Die Auswahl ausschneiden","Taglia la selezione","Recortar a seleção"],
"Dark": ["ダーク","深色","深色","Oscuro","Sombre","Dunkel","Scuro","Escuro"],
@@ -347,6 +349,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"None": ["なし","无","無","Ninguno","Aucune","Keine","Nessuno","Nenhum"],
"Normal — 12mm": ["標準 — 12mm","常规 — 12mm","標準 — 12mm","Normal — 12 mm","Normales — 12 mm","Normal — 12 mm","Normali — 12 mm","Normais — 12 mm"],
"Not a number — left out of totals, and a formula that reads it gives #VALUE!": ["数値ではありません — 合計から除外され、これを参照する数式は #VALUE! になります","不是数字 — 未计入合计,读取它的公式会得到 #VALUE!","不是數字 — 未計入合計,讀取它的公式會得到 #VALUE!","No es un número: queda fuera de los totales, y una fórmula que lo lea da #VALUE!","Pas un nombre — exclu des totaux, et une formule qui le lit donne #VALUE!","Keine Zahl — aus den Summen ausgenommen, und eine Formel, die sie liest, ergibt #VALUE!","Non è un numero — escluso dai totali, e una formula che lo legge dà #VALUE!","Não é um número — fica fora dos totais, e uma fórmula que o lê dá #VALUE!"],
+ "Not set": ["未設定","未设置","未設定","Sin definir","Non défini","Nicht festgelegt","Non impostato","Não definido"],
"Nothing has been flagged on this sheet yet.": ["このシートにはまだ何も指摘されていません。","此工作表上还没有任何标记。","此工作表上還沒有標記任何內容。","Aún no se ha marcado nada en esta hoja.","Rien n’a encore été signalé sur cette feuille.","Auf diesem Blatt wurde noch nichts markiert.","In questo foglio non è ancora stato segnalato nulla.","Nada foi sinalizado nesta planilha ainda."],
"Nothing in this column matches that search.": ["この列にはその検索に一致するものがありません。","此列中没有与该搜索匹配的内容。","此欄中沒有符合該搜尋的內容。","Nada en esta columna coincide con esa búsqueda.","Rien dans cette colonne ne correspond à cette recherche.","Nichts in dieser Spalte passt zu dieser Suche.","Nulla in questa colonna corrisponde a quella ricerca.","Nada nesta coluna corresponde a essa busca."],
"Nothing numeric to plot for this selection.": ["この選択範囲にはグラフにできる数値がありません。","当前选择没有可绘制的数值。","此選取範圍沒有可繪製的數值。","No hay nada numérico que representar en esta selección.","Rien de numérique à représenter pour cette sélection.","Für diese Auswahl gibt es nichts Numerisches zum Darstellen.","Niente di numerico da rappresentare per questa selezione.","Nada numérico para plotar nesta seleção."],
@@ -355,6 +358,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Nothing was pasted.": ["何も貼り付けられませんでした。","未粘贴任何内容。","未貼上任何內容。","No se pegó nada.","Rien n’a été collé.","Es wurde nichts eingefügt.","Non è stato incollato nulla.","Nada foi colado."],
"Nothing was split.": ["何も分割されませんでした。","未拆分任何内容。","未拆分任何內容。","No se dividió nada.","Rien n’a été divisé.","Es wurde nichts geteilt.","Non è stato diviso nulla.","Nada foi dividido."],
"Number": ["数値","数字","數值","Número","Numérique","Zahl","Numero","Número"],
+ "Number format": ["表示形式","数字格式","數字格式","Formato de número","Format de nombre","Zahlenformat","Formato numero","Formato de número"],
"OK": ["OK","确定","確定","Aceptar","Valider","OK","OK","OK"],
"Offline mode is on, so nothing was contacted.": ["オフラインモードが有効なため、どこにも接続していません。","离线模式已开启,因此未连接任何服务。","離線模式已開啟,因此沒有連線到任何地方。","El modo sin conexión está activado, así que no se ha contactado con nada.","Le mode hors ligne est activé : rien n’a été contacté.","Der Offlinemodus ist aktiv, es wurde nichts kontaktiert.","La modalità offline è attiva, quindi non è stato contattato nulla.","O modo offline está ligado, então nada foi contatado."],
"Offline mode is on: no update checks, no relay. Nothing leaves this computer. Sheets sync between tabs on this machine as before — that is not networking.": ["オフラインモードが有効です。更新の確認もリレーもありません。このコンピューターから何も送信されません。同じ端末のタブ間でのシート同期は従来どおり動作します — これはネットワーク通信ではありません。","离线模式已开启:不检查更新,不连接中继。没有任何内容离开这台电脑。本机各标签页之间的工作表同步照常进行 — 那不算联网。","離線模式已開啟:不檢查更新,不連線轉送伺服器。沒有任何內容離開這台電腦。本機各分頁之間的工作表同步照常進行 — 那不算連網。","El modo sin conexión está activado: sin comprobaciones de actualización ni relé. Nada sale de este ordenador. Las hojas siguen sincronizándose entre pestañas de esta máquina, como antes: eso no es red.","Le mode hors ligne est activé : aucune vérification de mise à jour, aucun relais. Rien ne quitte cet ordinateur. Les feuilles se synchronisent toujours entre les onglets de cette machine — ce n’est pas du réseau.","Der Offline-Modus ist an: keine Update-Prüfungen, kein Relay. Nichts verlässt diesen Computer. Blätter werden zwischen Tabs auf diesem Gerät weiterhin synchronisiert — das ist kein Netzwerkverkehr.","La modalità offline è attiva: nessun controllo aggiornamenti, nessun relay. Nulla lascia questo computer. I fogli continuano a sincronizzarsi tra le schede di questa macchina — quella non è rete.","O modo offline está ligado: sem verificação de atualizações, sem retransmissor. Nada sai deste computador. As planilhas continuam sincronizando entre abas nesta máquina como antes — isso não é rede."],
@@ -435,6 +439,8 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Rows": ["行","行","列","Filas","Lignes","Zeilen","Righe","Linhas"],
"Rule": ["規則","规则","規則","Regla","Règle","Regel","Regola","Regra"],
"Rules apply in order and the last one to set a colour wins it — none of them silences another.": ["ルールは順に適用され、色を最後に設定したものが優先されます。どのルールも他を打ち消しません。","规则按顺序应用,最后设置某个颜色的规则胜出;任何规则都不会让另一条失效。","規則依序套用,最後設定某個顏色的規則勝出;任何規則都不會讓另一條失效。","Las reglas se aplican en orden y la última que fija un color se lo lleva; ninguna silencia a otra.","Les règles s’appliquent dans l’ordre et la dernière à fixer une couleur l’emporte ; aucune n’en fait taire une autre.","Regeln gelten der Reihe nach, und wer eine Farbe zuletzt setzt, bekommt sie — keine Regel bringt eine andere zum Schweigen.","Le regole si applicano in ordine e l’ultima che imposta un colore se lo aggiudica: nessuna zittisce le altre.","As regras se aplicam em ordem e a última a definir uma cor fica com ela — nenhuma silencia a outra."],
+ "Same as column": ["列と同じ","与列相同","與欄相同","Igual que la columna","Comme la colonne","Wie Spalte","Come la colonna","Igual à coluna"],
+ "Sample": ["サンプル","示例","範例","Ejemplo","Aperçu","Beispiel","Esempio","Exemplo"],
"Save": ["保存","保存","儲存","Guardar","Enregistrer","Speichern","Salva","Salvar"],
"Save a copy…": ["コピーを保存…","保存副本…","儲存副本…","Guardar una copia…","Enregistrer une copie…","Kopie speichern…","Salva una copia…","Salvar uma cópia…"],
"Save an untouched copy": ["手を加えていないコピーを保存","保存一份原样副本","儲存一份未經更動的副本","Guardar una copia intacta","Enregistrer une copie intacte","Eine unveränderte Kopie speichern","Salva una copia intatta","Salvar uma cópia intacta"],
@@ -478,7 +484,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Show sheet tabs ([)": ["シートタブを表示 ([)","显示工作表标签 ([)","顯示工作表索引標籤 ([)","Mostrar las pestañas de hojas ([)","Afficher les onglets de feuilles ([)","Blattregister einblenden ([)","Mostra le schede dei fogli ([)","Mostrar as abas de planilha ([)"],
"Showing the first {n} of {total}.": ["{total} 件のうち先頭 {n} 件を表示しています。","正在显示 {total} 项中的前 {n} 项。","顯示 {total} 筆中的前 {n} 筆。","Se muestran las primeras {n} de {total}.","Affichage des {n} premières sur {total}.","Es werden die ersten {n} von {total} angezeigt.","Mostrate le prime {n} di {total}.","Mostrando os primeiros {n} de {total}."],
"Shown as bars — a scatter has no category to select.": ["棒グラフで表示しています — 散布図には選択できるカテゴリがありません。","以柱形显示 — 散点图没有可选择的类别。","以長條圖顯示 — 散佈圖沒有可供選取的類別。","Se muestra como barras: un gráfico de dispersión no tiene categoría que seleccionar.","Affiché en barres — un nuage de points n’a pas de catégorie à sélectionner.","Als Balken dargestellt — ein Punktdiagramm hat keine Kategorie zum Auswählen.","Mostrato a barre — un grafico a dispersione non ha una categoria da selezionare.","Exibido como barras — uma dispersão não tem categoria para selecionar."],
- "Shows as": ["表示例","显示为","顯示為","Se muestra como","Affiché comme","Wird angezeigt als","Mostrato come","Exibido como"],
"Shrink a little, then continue on later pages": ["少し縮小し、収まらない列は次のページへ","先略微缩小,放不下的列排到后续页面","先略為縮小,放不下的欄排到後續頁面","Reducir un poco y continuar en las páginas siguientes","Réduire un peu, puis continuer sur les pages suivantes","Etwas verkleinern, dann auf Folgeseiten weiterlaufen","Riduci un poco, poi continua nelle pagine successive","Reduzir um pouco, depois continuar nas páginas seguintes"],
"Shrink until the sheet fits the page width": ["ページ幅に収まるまで縮小する","缩小到适合页面宽度","縮小到符合頁面寬度","Reducir hasta que la hoja quepa en el ancho de la página","Réduire jusqu’à ce que la feuille tienne dans la largeur de la page","So weit verkleinern, dass das Blatt in die Seitenbreite passt","Riduci finché il foglio non rientra nella larghezza della pagina","Reduzir até a planilha caber na largura da página"],
"Size": ["サイズ","大小","大小","Tamaño","Taille","Größe","Dimensione","Tamanho"],
@@ -519,7 +524,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"That version has no table sheet to show.": ["そのバージョンには表示できるテーブルシートがありません。","该版本没有可显示的表格工作表。","該版本沒有可顯示的表格工作表。","Esa versión no tiene ninguna hoja de tabla que mostrar.","Cette version n’a aucune feuille de tableau à afficher.","Diese Version enthält kein Tabellenblatt zum Anzeigen.","Quella versione non ha alcun foglio tabella da mostrare.","Essa versão não tem planilha de conjunto de dados para mostrar."],
"That workbook has no table sheet to show.": ["そのブックには表示できるテーブルシートがありません。","该工作簿没有可显示的表格工作表。","該活頁簿沒有可顯示的表格工作表。","Ese libro no tiene ninguna hoja de tabla que mostrar.","Ce classeur n’a aucune feuille de tableau à afficher.","Diese Arbeitsmappe enthält kein Tabellenblatt zum Anzeigen.","Quella cartella di lavoro non ha alcun foglio tabella da mostrare.","Essa pasta de trabalho não tem planilha de conjunto de dados para mostrar."],
"The collaboration keys have been left out of what is shown and copied. “Save an untouched copy” keeps the file exactly as it arrived.": ["共同編集の鍵は、表示およびコピーされる内容から除かれています。「元のままのコピーを保存」は届いたままのファイルを保持します。","协作密钥已从显示和复制的内容中排除。“保存原样副本”会完整保留收到的文件。","協作金鑰已從顯示與複製的內容中排除。「儲存原樣副本」會完整保留收到的檔案。","Las claves de colaboración se han dejado fuera de lo que se muestra y se copia. «Guardar una copia intacta» conserva el archivo tal y como llegó.","Les clés de collaboration ont été retirées de ce qui est affiché et copié. « Enregistrer une copie intacte » conserve le fichier tel qu’il est arrivé.","Die Kollaborationsschlüssel wurden aus dem Angezeigten und Kopierten herausgelassen. „Unveränderte Kopie speichern“ behält die Datei genau so, wie sie ankam.","Le chiavi di collaborazione sono state escluse da ciò che viene mostrato e copiato. «Salva una copia intatta» conserva il file esattamente come è arrivato.","As chaves de colaboração foram deixadas de fora do que é exibido e copiado. “Salvar uma cópia intacta” preserva o arquivo exatamente como ele chegou."],
- "The column decides what these cells ARE. A pattern here only changes how they print.": ["これらのセルが何であるかは列が決めます。ここでの書式は表示のしかたを変えるだけです。","这些单元格是什么由列决定。这里的格式只改变显示方式。","這些儲存格是什麼由欄決定。這裡的格式只改變顯示方式。","La columna decide QUÉ SON estas celdas. Un patrón aquí solo cambia cómo se muestran.","C’est la colonne qui décide de CE QUE SONT ces cellules. Un format ici ne change que leur affichage.","Die Spalte entscheidet, WAS diese Zellen sind. Ein Muster hier ändert nur die Darstellung.","È la colonna a decidere COSA SONO queste celle. Un formato qui cambia solo come vengono mostrate.","A coluna decide o que estas células SÃO. Um padrão aqui só muda como elas são exibidas."],
"The document block is present but could not be read.": ["ドキュメントブロックはありますが、読み取れませんでした。","文档块存在,但无法读取。","文件區塊存在,但無法讀取。","El bloque del documento está presente, pero no se ha podido leer.","Le bloc document est présent mais n’a pas pu être lu.","Der Dokumentblock ist vorhanden, konnte aber nicht gelesen werden.","Il blocco del documento è presente ma non è stato possibile leggerlo.","O bloco do documento está presente, mas não pôde ser lido."],
"The first row holds the column names": ["先頭行を列名として使う","首行是列名","首列是欄名","La primera fila contiene los nombres de las columnas","La première ligne contient les noms de colonnes","Die erste Zeile enthält die Spaltennamen","La prima riga contiene i nomi delle colonne","A primeira linha contém os nomes das colunas"],
"The formula in {cols} was carried down to the new row. A column formula would fill every new row, without being asked.": ["{cols} の数式を新しい行に引き継ぎました。列の数式なら、頼まなくてもすべての新しい行が埋まります。","{cols} 中的公式已延续到新行。列公式无需请求即可填充每一个新行。","{cols} 中的公式已延續到新列。欄公式無須請求即可填滿每一個新列。","La fórmula de {cols} se ha extendido a la nueva fila. Una fórmula de columna rellenaría cada fila nueva, sin que se lo pidan.","La formule de {cols} a été reportée sur la nouvelle ligne. Une formule de colonne remplirait chaque nouvelle ligne, sans qu’on le lui demande.","Die Formel in {cols} wurde in die neue Zeile übernommen. Eine Spaltenformel würde jede neue Zeile füllen, ungefragt.","La formula in {cols} è stata riportata nella nuova riga. Una formula di colonna riempirebbe ogni nuova riga, senza che glielo si chieda.","A fórmula em {cols} foi levada para a nova linha. Uma coluna de fórmula preencheria toda linha nova, sem precisar pedir."],
@@ -539,6 +543,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Theme": ["テーマ","配色主题","佈景主題","Tema","Thème","Design","Tema","Tema"],
"There is nothing to paste. This browser will not hand a menu the system clipboard, so ⌘V pastes what a menu cannot reach.": ["貼り付けるものがありません。このブラウザーはメニューにシステムのクリップボードを渡さないため、メニューでは届かないものも ⌘V なら貼り付けられます。","没有可粘贴的内容。此浏览器不会把系统剪贴板交给菜单,因此菜单够不到的内容可以用 ⌘V 粘贴。","沒有可貼上的內容。此瀏覽器不會把系統剪貼簿交給選單,因此選單構不到的內容可以用 ⌘V 貼上。","No hay nada que pegar. Este navegador no le entrega el portapapeles del sistema a un menú, así que ⌘V pega lo que un menú no alcanza.","Il n’y a rien à coller. Ce navigateur ne donne pas le presse-papiers du système à un menu ; ⌘V colle donc ce qu’un menu ne peut pas atteindre.","Es gibt nichts zum Einfügen. Dieser Browser gibt einem Menü die Systemzwischenablage nicht heraus, deshalb fügt ⌘V ein, was ein Menü nicht erreichen kann.","Non c’è nulla da incollare. Questo browser non passa a un menu gli appunti di sistema, quindi ⌘V incolla ciò che un menu non riesce a raggiungere.","Não há nada para colar. Este navegador não entrega a área de transferência do sistema a um menu, então o ⌘V cola o que um menu não alcança."],
"These are yours, not the workbook’s: they are kept in this browser and never written into the file, so the same workbook can be English and light on your screen and Japanese and dark on someone else’s.": ["これらはブックのものではなく、あなたのものです。このブラウザにだけ保存され、ファイルには決して書き込まれません — 同じブックが、あなたの画面では英語でライト、別の人の画面では日本語でダークになることもあります。","这些设置属于你,而不属于工作簿:它们只保存在此浏览器中,永远不会写入文件 — 所以同一个工作簿可以在你的屏幕上是英语浅色,在别人的屏幕上是日语深色。","這些設定屬於你,而不屬於活頁簿:它們只保存在這個瀏覽器裡,永遠不會寫進檔案 — 所以同一份活頁簿可以在你的螢幕上是英文淺色,在別人的螢幕上是日文深色。","Son tuyos, no del libro: se guardan en este navegador y nunca se escriben en el archivo, así que el mismo libro puede verse en inglés y claro en tu pantalla y en japonés y oscuro en la de otra persona.","Ils sont à vous, pas au classeur : ils restent dans ce navigateur et ne sont jamais écrits dans le fichier — un même classeur peut donc être en anglais et clair sur votre écran, en japonais et sombre sur celui d’une autre personne.","Sie gehören Ihnen, nicht der Arbeitsmappe: Sie bleiben in diesem Browser und werden nie in die Datei geschrieben — dieselbe Arbeitsmappe kann also auf Ihrem Bildschirm englisch und hell sein und auf einem anderen japanisch und dunkel.","Sono tue, non della cartella di lavoro: restano in questo browser e non vengono mai scritte nel file, così la stessa cartella può essere in inglese e chiara sul tuo schermo e in giapponese e scura su quello di un altro.","Estas são suas, não da pasta de trabalho: ficam guardadas neste navegador e nunca são gravadas no arquivo, então a mesma pasta pode estar em inglês e no tema claro na sua tela e em japonês e escuro na de outra pessoa."],
+ "These cells": ["これらのセル","这些单元格","這些儲存格","Estas celdas","Ces cellules","Diese Zellen","Queste celle","Estas células"],
"This action needs a dataset sheet, and the sheet on screen is not one.": ["この操作にはデータセットのシートが必要ですが、表示中のシートはそれではありません。","此操作需要数据集工作表,而当前显示的不是。","此動作需要資料集工作表,而目前顯示的不是。","Esta acción necesita una hoja de conjunto de datos, y la que está en pantalla no lo es.","Cette action nécessite une feuille de jeu de données, et celle affichée n’en est pas une.","Diese Aktion braucht ein Datensatzblatt, und das angezeigte ist keines.","Questa azione richiede un foglio set di dati, e quello a schermo non lo è.","Esta ação precisa de uma planilha de conjunto de dados, e a planilha em tela não é uma."],
"This block is not readable as JSON, so its collaboration keys could not be removed from what is shown or copied. Use “Save an untouched copy” to keep the file, and take care where you paste this.": ["このブロックは JSON として読み取れないため、表示およびコピーされる内容から共同編集の鍵を取り除けませんでした。ファイルを残すには「元のままのコピーを保存」を使い、貼り付け先にご注意ください。","此数据块无法按 JSON 读取,因此未能从显示和复制的内容中移除协作密钥。请使用“保存原样副本”保留文件,并注意粘贴位置。","此資料區塊無法以 JSON 讀取,因此未能從顯示與複製的內容中移除協作金鑰。請使用「儲存原樣副本」保留檔案,並注意貼上的位置。","Este bloque no se puede leer como JSON, así que no se han podido quitar sus claves de colaboración de lo que se muestra y se copia. Usa «Guardar una copia intacta» para conservar el archivo y ten cuidado con dónde lo pegas.","Ce bloc n’est pas lisible en JSON : ses clés de collaboration n’ont pas pu être retirées de ce qui est affiché et copié. Utilisez « Enregistrer une copie intacte » pour conserver le fichier, et faites attention à l’endroit où vous collez ceci.","Dieser Block ist nicht als JSON lesbar, daher konnten seine Kollaborationsschlüssel nicht aus dem Angezeigten und Kopierten entfernt werden. Nutze „Unveränderte Kopie speichern“, um die Datei zu behalten, und achte darauf, wohin du dies einfügst.","Questo blocco non è leggibile come JSON, quindi le sue chiavi di collaborazione non sono state rimosse da ciò che viene mostrato e copiato. Usa «Salva una copia intatta» per conservare il file e attenzione a dove lo incolli.","Este bloco não é legível como JSON, então suas chaves de colaboração não puderam ser removidas do que é exibido ou copiado. Use “Salvar uma cópia intacta” para preservar o arquivo, e tome cuidado com onde você cola isto."],
"This browser cannot write back to the file, so every save makes a new copy. Chrome and Edge on a computer can save in place.": ["このブラウザはファイルに書き戻せないため、保存のたびに新しいコピーができます。パソコンの Chrome と Edge なら直接上書き保存できます。","此浏览器无法写回原文件,因此每次保存都会生成新副本。电脑上的 Chrome 和 Edge 可以就地保存。","此瀏覽器無法寫回檔案,因此每次儲存都會產生新的副本。電腦版的 Chrome 和 Edge 可以就地儲存。","Este navegador no puede reescribir el archivo, así que cada guardado crea una copia nueva. Chrome y Edge en un ordenador sí pueden guardar en el sitio.","Ce navigateur ne peut pas réécrire le fichier : chaque enregistrement crée donc une nouvelle copie. Chrome et Edge sur ordinateur enregistrent sur place.","Dieser Browser kann nicht in die Datei zurückschreiben, deshalb entsteht bei jedem Speichern eine neue Kopie. Chrome und Edge auf dem Computer können direkt speichern.","Questo browser non può riscrivere il file, quindi ogni salvataggio crea una nuova copia. Chrome ed Edge su computer possono salvare sul posto.","Este navegador não consegue gravar de volta no arquivo, então cada salvamento cria uma cópia nova. O Chrome e o Edge em computador conseguem salvar no lugar."],
@@ -551,6 +556,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"This chart is about {sheet}. You are looking at {other}.": ["このグラフは {sheet} のものです。今表示しているのは {other} です。","此图表针对 {sheet}。你正在查看 {other}。","此圖表針對 {sheet}。你正在檢視 {other}。","Este gráfico trata de {sheet}. Estás viendo {other}.","Ce graphique porte sur {sheet}. Vous regardez {other}.","Dieses Diagramm bezieht sich auf {sheet}. Sie sehen gerade {other}.","Questo grafico riguarda {sheet}. Stai guardando {other}.","Este gráfico é sobre {sheet}. Você está vendo {other}."],
"This chart was drawn from {cols}, and {sheet} does not have {n} of them any more.": ["このグラフは {cols} から作成されましたが、{sheet} にはそのうち {n} 個がありません。","此图表由 {cols} 绘制,而 {sheet} 中已缺少其中 {n} 个。","此圖表由 {cols} 繪製,而 {sheet} 中已缺少其中 {n} 個。","Este gráfico se dibujó a partir de {cols}, y {sheet} ya no tiene {n} de ellas.","Ce graphique a été tracé à partir de {cols}, et {sheet} n’en a plus {n}.","Dieses Diagramm entstand aus {cols}, und {sheet} hat {n} davon nicht mehr.","Questo grafico è stato tracciato da {cols}, e {sheet} non ne ha più {n}.","Este gráfico foi feito a partir de {cols}, e {sheet} não tem mais {n} delas."],
"This choice could not be saved — site data is blocked or full — so it holds for this tab and will be forgotten when you reload.": ["この選択は保存できませんでした(サイトデータがブロックされているか、容量がいっぱいです)。このタブでは有効ですが、再読み込みすると失われます。","此选择无法保存——站点数据被阻止或已满——因此它仅在此标签页中有效,重新加载后将会丢失。","此選擇無法儲存——網站資料遭到封鎖或已滿——因此僅在此分頁中有效,重新載入後將會遺失。","Esta elección no se pudo guardar —los datos del sitio están bloqueados o llenos—, así que solo se aplica a esta pestaña y se olvidará al recargar.","Ce choix n’a pas pu être enregistré — les données du site sont bloquées ou saturées — il ne vaut donc que pour cet onglet et sera oublié au rechargement.","Diese Auswahl konnte nicht gespeichert werden – Websitedaten sind blockiert oder voll –, sie gilt daher nur für diesen Tab und geht beim Neuladen verloren.","Questa scelta non è stata salvata — i dati del sito sono bloccati o pieni — quindi vale solo per questa scheda e andrà persa al ricaricamento.","Esta escolha não pôde ser salva — os dados do site estão bloqueados ou cheios — então ela vale para esta aba e será esquecida ao recarregar."],
+ "This column": ["この列","此列","此欄","Esta columna","Cette colonne","Diese Spalte","Questa colonna","Esta coluna"],
"This column is {type}, so its values print exactly as they are stored and this pattern changes nothing. Set the type to Number, Money or Percent for it to apply.": ["この列は {type} なので、値は保存されているとおりに表示され、この書式は何も変えません。適用するには型を数値・通貨・パーセントのいずれかにしてください。","此列是{type},因此其值按存储的原样显示,这个格式不起任何作用。要让它生效,请将类型设为数字、货币或百分比。","此欄是{type},因此其值按儲存的原樣顯示,這個格式不起任何作用。要讓它生效,請將型別設為數值、貨幣或百分比。","Esta columna es {type}, así que sus valores se muestran tal como están guardados y este patrón no cambia nada. Cambia el tipo a Número, Moneda o Porcentaje para que se aplique.","Cette colonne est de type {type} : ses valeurs s’affichent telles qu’elles sont stockées et ce format ne change rien. Passez le type à Numérique, Monétaire ou Pourcentage pour qu’il s’applique.","Diese Spalte ist {type}, ihre Werte werden also genau so ausgegeben, wie sie gespeichert sind, und dieses Muster ändert nichts. Setzen Sie den Typ auf Zahl, Währung oder Prozent, damit es greift.","Questa colonna è {type}, quindi i suoi valori vengono mostrati esattamente come sono memorizzati e questo formato non cambia nulla. Imposta il tipo su Numero, Valuta o Percentuale perché venga applicato.","Esta coluna é {type}, então seus valores aparecem exatamente como estão armazenados e este padrão não muda nada. Defina o tipo como Número, Monetário ou Porcentagem para que ele valha."],
"This dataset has no columns": ["このデータセットには列がありません","此数据集没有列","此資料集沒有欄","Este conjunto de datos no tiene columnas","Ce jeu de données n’a aucune colonne","Dieser Datensatz hat keine Spalten","Questo set di dati non ha colonne","Este conjunto de dados não tem colunas"],
"This dataset has no rows": ["このデータセットには行がありません","此数据集没有行","此資料集沒有列","Este conjunto de datos no tiene filas","Ce jeu de données n’a aucune ligne","Dieser Datensatz hat keine Zeilen","Questo set di dati non ha righe","Este conjunto de dados não tem linhas"],
@@ -593,6 +599,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Those changes could not be restored into this workbook.": ["その変更をこのブックに復元できませんでした。","这些更改无法恢复到此工作簿中。","那些變更無法還原到此活頁簿中。","No se han podido restaurar esos cambios en este libro.","Ces modifications n’ont pas pu être restaurées dans ce classeur.","Diese Änderungen konnten nicht in diese Arbeitsmappe zurückgeholt werden.","Non è stato possibile ripristinare quelle modifiche in questa cartella di lavoro.","Não foi possível restaurar essas alterações nesta pasta de trabalho."],
"Thousands separator": ["桁区切り","千位分隔符","千分位符號","Separador de miles","Séparateur de milliers","Tausendertrennzeichen","Separatore delle migliaia","Separador de milhares"],
"Ties are included: the top 1 of 10, 10, 9 is both tens, because highlighting one of two equal cells claims a difference the data does not have.": ["同順位も含みます。10, 10, 9 の「上位 1 件」は 2 つの 10 です。等しい 2 つのセルの片方だけを強調表示すると、データにない差があるように見えてしまうからです。","并列一并计入:10、10、9 的“最高 1 项”是两个 10——只突出显示两个相等单元格中的一个,等于宣称数据里存在并不存在的差异。","並列一併計入:10、10、9 的「最高 1 項」是兩個 10——只醒目提示兩個相等儲存格中的一個,等於宣稱資料裡存在並不存在的差異。","Los empates se incluyen: el «1 más alto» de 10, 10, 9 son los dos dieces, porque resaltar solo una de dos celdas iguales afirma una diferencia que los datos no tienen.","Les ex æquo sont inclus : le « premier » de 10, 10, 9 donne les deux dix, car surligner une seule de deux cellules égales affirmerait un écart absent des données.","Gleichstände zählen mit: die „obersten 1“ von 10, 10, 9 sind beide Zehner, denn nur eine von zwei gleichen Zellen hervorzuheben behauptet einen Unterschied, den die Daten nicht haben.","I pari merito sono inclusi: il «primo» di 10, 10, 9 sono entrambi i dieci, perché evidenziare una sola di due celle uguali afferma una differenza che i dati non hanno.","Empates entram: o 1 maior de 10, 10, 9 são os dois dez, porque destacar uma de duas células iguais afirma uma diferença que os dados não têm."],
+ "Time": ["時刻","时间","時間","Hora","Heure","Uhrzeit","Ora","Hora"],
"Top": ["上","上","上","Arriba","Haut","Oben","Alto","Superior"],
"Top or bottom": ["上位・下位","最高或最低","最高或最低","Más altos o más bajos","Extrêmes hauts ou bas","Oberste oder unterste","Più alti o più bassi","Primeiros ou últimos"],
"Top {n}": ["上位 {n} 件","最高 {n} 项","最高 {n} 項","Primeros {n}","{n} premiers","Obere {n}","Primi {n}","Primeiros {n}"],
@@ -622,7 +629,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Use the default colour": ["既定の色を使う","使用默认颜色","使用預設色彩","Usar el color predeterminado","Utiliser la couleur par défaut","Standardfarbe verwenden","Usa il colore predefinito","Usar a cor padrão"],
"Validation": ["入力規則","数据验证","資料驗證","Validación","Validation des données","Gültigkeitsprüfung","Convalida","Validação"],
"Value": ["値","值","值","Valor","Valeur","Wert","Valore","Valor"],
- "Value * Probability": [],
"Values": ["値","值","值","Valores","Valeurs","Werte","Valori","Valores"],
"Values only": ["値のみ","仅值","僅值","Solo valores","Valeurs uniquement","Nur Werte","Solo valori","Somente valores"],
"Values only, transposed": ["値のみ、行列を入れ替え","仅值,并转置","僅值,並轉置","Solo valores, transpuesto","Valeurs uniquement, transposées","Nur Werte, transponiert","Solo valori, trasposto","Somente valores, transposto"],
diff --git a/dash/src/i18n/pt.ts b/dash/src/i18n/pt.ts
index 93f04400..a05eff18 100644
--- a/dash/src/i18n/pt.ts
+++ b/dash/src/i18n/pt.ts
@@ -475,7 +475,6 @@ export const pt: Catalog = {
"Show sheet tabs ([)": "Mostrar as abas de planilha ([)",
"Showing the first {n} of {total}.": "Mostrando os primeiros {n} de {total}.",
"Shown as bars — a scatter has no category to select.": "Exibido como barras — uma dispersão não tem categoria para selecionar.",
- "Shows as": "Exibido como",
"Shrink a little, then continue on later pages": "Reduzir um pouco, depois continuar nas páginas seguintes",
"Shrink until the sheet fits the page width": "Reduzir até a planilha caber na largura da página",
"Size": "Tamanho",
@@ -515,7 +514,6 @@ export const pt: Catalog = {
"That version could not be read.": "Não foi possível ler essa versão.",
"That version has no table sheet to show.": "Essa versão não tem planilha de conjunto de dados para mostrar.",
"That workbook has no table sheet to show.": "Essa pasta de trabalho não tem planilha de conjunto de dados para mostrar.",
- "The column decides what these cells ARE. A pattern here only changes how they print.": "A coluna decide o que estas células SÃO. Um padrão aqui só muda como elas são exibidas.",
"The document block is present but could not be read.": "O bloco do documento está presente, mas não pôde ser lido.",
"The first row holds the column names": "A primeira linha contém os nomes das colunas",
"The formula in {cols} was carried down to the new row. A column formula would fill every new row, without being asked.": "A fórmula em {cols} foi levada para a nova linha. Uma coluna de fórmula preencheria toda linha nova, sem precisar pedir.",
@@ -769,4 +767,13 @@ export const pt: Catalog = {
"Copy saved — you are still editing the original": "Cópia salva — você continua editando o original",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "A recuperação de falhas está desativada para esta pasta de trabalho: ela é grande demais para manter uma cópia de segurança. Salve com frequência.",
"A backup of this workbook for yourself — same workbook, same live session.": "Um backup desta pasta de trabalho para você — mesma pasta de trabalho, mesma sessão ao vivo.",
+ "Apply to": "Aplicar a",
+ "Custom…": "Personalizado…",
+ "Not set": "Não definido",
+ "Number format": "Formato de número",
+ "Same as column": "Igual à coluna",
+ "Sample": "Exemplo",
+ "These cells": "Estas células",
+ "This column": "Esta coluna",
+ "Time": "Hora",
}
diff --git a/dash/src/i18n/zh-Hans.ts b/dash/src/i18n/zh-Hans.ts
index 6a01e482..f8307881 100644
--- a/dash/src/i18n/zh-Hans.ts
+++ b/dash/src/i18n/zh-Hans.ts
@@ -465,7 +465,6 @@ export const zhHans: Catalog = {
"Show sheet tabs ([)": "显示工作表标签 ([)",
"Showing the first {n} of {total}.": "正在显示 {total} 项中的前 {n} 项。",
"Shown as bars — a scatter has no category to select.": "以柱形显示 — 散点图没有可选择的类别。",
- "Shows as": "显示为",
"Shrink a little, then continue on later pages": "先略微缩小,放不下的列排到后续页面",
"Shrink until the sheet fits the page width": "缩小到适合页面宽度",
"Size": "大小",
@@ -505,7 +504,6 @@ export const zhHans: Catalog = {
"That version could not be read.": "无法读取该版本。",
"That version has no table sheet to show.": "该版本没有可显示的表格工作表。",
"That workbook has no table sheet to show.": "该工作簿没有可显示的表格工作表。",
- "The column decides what these cells ARE. A pattern here only changes how they print.": "这些单元格是什么由列决定。这里的格式只改变显示方式。",
"The document block is present but could not be read.": "文档块存在,但无法读取。",
"The first row holds the column names": "首行是列名",
"The formula in {cols} was carried down to the new row. A column formula would fill every new row, without being asked.": "{cols} 中的公式已延续到新行。列公式无需请求即可填充每一个新行。",
@@ -756,4 +754,13 @@ export const zhHans: Catalog = {
"Copy saved — you are still editing the original": "副本已保存 — 你仍在编辑原文件",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "此工作簿的崩溃恢复已关闭 — 文件太大,无法保留备份。请经常保存。",
"A backup of this workbook for yourself — same workbook, same live session.": "自己留存的备份 — 同一个工作簿、同一个实时会话。",
+ "Apply to": "应用于",
+ "Custom…": "自定义…",
+ "Not set": "未设置",
+ "Number format": "数字格式",
+ "Same as column": "与列相同",
+ "Sample": "示例",
+ "These cells": "这些单元格",
+ "This column": "此列",
+ "Time": "时间",
}
diff --git a/dash/src/i18n/zh-Hant.ts b/dash/src/i18n/zh-Hant.ts
index 73028f3f..86b4e381 100644
--- a/dash/src/i18n/zh-Hant.ts
+++ b/dash/src/i18n/zh-Hant.ts
@@ -465,7 +465,6 @@ export const zhHant: Catalog = {
"Show sheet tabs ([)": "顯示工作表索引標籤 ([)",
"Showing the first {n} of {total}.": "顯示 {total} 筆中的前 {n} 筆。",
"Shown as bars — a scatter has no category to select.": "以長條圖顯示 — 散佈圖沒有可供選取的類別。",
- "Shows as": "顯示為",
"Shrink a little, then continue on later pages": "先略為縮小,放不下的欄排到後續頁面",
"Shrink until the sheet fits the page width": "縮小到符合頁面寬度",
"Size": "大小",
@@ -505,7 +504,6 @@ export const zhHant: Catalog = {
"That version could not be read.": "無法讀取該版本。",
"That version has no table sheet to show.": "該版本沒有可顯示的表格工作表。",
"That workbook has no table sheet to show.": "該活頁簿沒有可顯示的表格工作表。",
- "The column decides what these cells ARE. A pattern here only changes how they print.": "這些儲存格是什麼由欄決定。這裡的格式只改變顯示方式。",
"The document block is present but could not be read.": "文件區塊存在,但無法讀取。",
"The first row holds the column names": "首列是欄名",
"The formula in {cols} was carried down to the new row. A column formula would fill every new row, without being asked.": "{cols} 中的公式已延續到新列。欄公式無須請求即可填滿每一個新列。",
@@ -756,4 +754,13 @@ export const zhHant: Catalog = {
"Copy saved — you are still editing the original": "副本已儲存 — 你仍在編輯原始檔案",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "此活頁簿的當機復原已關閉 — 檔案太大,無法保留備份。請經常儲存。",
"A backup of this workbook for yourself — same workbook, same live session.": "自己留存的備份 — 同一個活頁簿、同一個即時會話。",
+ "Apply to": "套用至",
+ "Custom…": "自訂…",
+ "Not set": "未設定",
+ "Number format": "數字格式",
+ "Same as column": "與欄相同",
+ "Sample": "範例",
+ "These cells": "這些儲存格",
+ "This column": "此欄",
+ "Time": "時間",
}
diff --git a/dash/src/main.ts b/dash/src/main.ts
index 829cdebd..15f5cb2f 100644
--- a/dash/src/main.ts
+++ b/dash/src/main.ts
@@ -74,7 +74,7 @@ import {
import { cellKey, isFormula, recalcWorkbook, workbookSources } from './cellformula.ts'
import { Store, type Patch, setColumnType } from './store.ts'
import { starterDoc } from './starter.ts'
-import { inferComputedType } from './computedtype.ts'
+import { inferComputedType, retypePatch } from './computedtype.ts'
import { validateDoc } from './validate.ts'
import { mountHelp } from './help.ts'
// The grid's three context menus, and the popover every menu in this file is
@@ -2361,11 +2361,14 @@ async function addFormula(store: Store, sheet: TableSheet): Promise<void> {
// to nothing. computedtype.ts runs the expression against this sheet and
// judges the values; when they cannot be judged it says text, which is the
// type that makes no claim.
+ // …and a number computed from Money is Money, with its format and unit, so
+ // `Value * 2` prints £8,600 beside £24,800 rather than 8600 beside 24,800.
+ const inferred = inferComputedType(sheet, got.expr)
store.commit({
op: 'addColumn', sheet: sheet.id,
column: {
id, name: got.name.trim() || t('Computed'),
- type: inferComputedType(sheet, got.expr).type, formula: got.expr,
+ type: inferred.type, ...inferred.carry, formula: got.expr,
},
})
}
@@ -2392,10 +2395,9 @@ async function editFormula(store: Store, sheet: TableSheet, col: Column): Promis
// is exactly the case "nobody has touched this".
const before = inferComputedType(sheet, col.formula ?? '', col.id)
const after = inferComputedType(sheet, got.expr, col.id)
- const retype = col.type === before.type && after.type !== col.type
store.commit({
op: 'setColumn', sheet: sheet.id, col: col.id,
- patch: retype ? { formula: got.expr, type: after.type } : { formula: got.expr },
+ patch: retypePatch(col, before, after, got.expr),
})
}
diff --git a/dash/src/panels.css b/dash/src/panels.css
index ff073c94..d0d2841e 100644
--- a/dash/src/panels.css
+++ b/dash/src/panels.css
@@ -356,76 +356,34 @@ body.dp-resizing { cursor: col-resize; user-select: none; }
}
.dp-row .dp-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
-/* ————— THE CHECKBOX IS A FIELD, LIKE EVERY OTHER CONTROL —————
- A native checkbox is 13px of box in a 26px row, and it ended 97px short of
- the line every other control in the panel ends on: a column of fields with
- one speck floating in it. Both of the obvious repairs are worse. Pushing it
- to the RIGHT edge (slides' `space-between`) buys the right edge by giving up
- the left one, so the state indicator no longer starts where every value in
- the panel starts. Leaving it small and starting it on the left — what this
- file did until now — is the speck.
-
- So it becomes a field: the same 26px box, the same border, the same radius,
- the same two edges, with the state drawn as a 14px box INSIDE it on the
- panel's content line. `row()` (panels.ts) already builds every row as a
- `<label>`, so the whole field was a hit target the moment it had a size —
- 110px × 26px instead of 13 × 13, and no markup or script to add.
-
- THE CHECKED STATE PAINTS IN --ink, NOT THE AMBER. Same argument tabs.css
- makes for the active-tab rule: the brand amber is 2.02:1 on white, under the
- 3:1 that a non-text indicator has to hold, and it is the ONLY thing saying
- whether this option is on. Ink is 14.51:1 light and 13.75:1 dark against the
- field, so one mark carries it on both grounds. (The old rule set
- `accent-color: var(--accent)`, i.e. it painted the state at 2.02:1.) */
+/* ————— THE CHECKBOX IS BARE, AS IN SLIDES —————
+ It used to be drawn as a FIELD: a 26px bordered box the width of the control
+ column with a 14px tick box inside it. Measured in review, that read as an
+ empty text field — six of them down the Appearance and Column sections, worse
+ in dark — and the one thing the eye looks for in a checkbox, the box, was the
+ smallest thing in the row. Slides draws a bare 16px checkbox (`.ed-toggle`),
+ and that is what this is now: the box alone, on the control column's START
+ line, so it still begins where every value in the panel begins.
+
+ THE ROW, NOT THE BOX, IS THE HIT TARGET. `row()` (panels.ts) builds every row
+ as a `<label>`, so clicking the label toggles it — the large target the field
+ version bought, kept without drawing a field.
+
+ The checked fill is slides' slate, not the brand amber: the amber is 2.02:1 on
+ white, under the 3:1 a non-text indicator has to hold, and it is the only
+ thing saying whether this option is on. */
.dp-row input[type='checkbox'] {
- appearance: none;
- -webkit-appearance: none;
- position: relative;
- width: 100%;
- min-width: 0;
- height: var(--dp-row);
+ justify-self: start;
+ width: 16px;
+ height: 16px;
margin: 0;
- padding: 0 6px;
- display: flex;
- align-items: center;
- border: 1px solid var(--line);
- border-radius: var(--dp-radius);
- background: var(--surface);
+ accent-color: #5e7699;
cursor: pointer;
}
-/* the box itself — 14px, on the same content line as an input's first glyph */
-.dp-row input[type='checkbox']::before {
- content: '';
- box-sizing: border-box;
- width: 14px;
- height: 14px;
- border: 1px solid var(--line-strong);
- border-radius: 4px;
- background: var(--surface);
-}
-.dp-row input[type='checkbox']:checked::before {
- border-color: var(--ink);
- background: var(--ink);
-}
-/* the tick, knocked out of the filled box in the field's own surface colour */
-.dp-row input[type='checkbox']:checked::after {
- content: '';
- position: absolute;
- left: 11px;
- top: 50%;
- width: 4px;
- height: 8px;
- margin-top: -5px;
- border: 2px solid var(--surface);
- border-block-start: 0;
- border-inline-start: 0;
- transform: rotate(43deg);
-}
-.dp-row input[type='checkbox']:hover { border-color: var(--line-strong); }
+.dp-row input[type='checkbox']:disabled { cursor: default; }
.dp-row input[type='checkbox']:focus-visible {
- outline: none;
- border-color: var(--blue);
- box-shadow: 0 0 0 1px var(--blue);
+ outline: 2px solid var(--blue);
+ outline-offset: 2px;
}
.dp-row-ro { cursor: default; }
diff --git a/dash/src/panels.ts b/dash/src/panels.ts
index 8a3fd7d6..be029472 100644
--- a/dash/src/panels.ts
+++ b/dash/src/panels.ts
@@ -34,10 +34,10 @@
import './panels.css'
import { t, locale } from './i18n.ts'
import { lsJson, lsSet } from '../../kernel/src/storage.ts'
-import { TYPE_LABEL } from './format.ts'
-import { buildCellProps, type CellRange, type PanelKit } from './cellprops.ts'
+import { TYPE_LABEL, formatValue } from './format.ts'
+import { buildCellProps, buildNumberFormat, type CellRange, type PanelKit } from './cellprops.ts'
import {
- appearancePatch, buildAppearanceSection, describeOverrideSelection, effectiveFormat,
+ appearancePatch, buildAppearanceSection, describeOverrideSelection,
overrideFormatPatch, overrideKeys, type Appearance, type AppearanceEdit,
} from './cellfmt.ts'
import {
@@ -45,7 +45,7 @@ import {
countViolations, columnRulePatch, boxRef, type DataRule,
} from './datavalid.ts'
import { mountTabs, renameSheetPatches } from './tabs.ts'
-import { inferComputedType } from './computedtype.ts'
+import { inferComputedType, retypePatch } from './computedtype.ts'
import { buildCondFmtSection, condFmtPatch, readCondFmt } from './condfmtui.ts'
import { toast } from './saveui.ts'
import type { CanvasSheet, Column, ColumnType, TableSheet } from './model.ts'
@@ -357,6 +357,12 @@ export function mountPanels(host: PanelsHost): Panels {
*/
let cellMessage = ''
+ /**
+ * The dataset Number format's "Apply to" choice, while the reader is on the
+ * column they chose it for. UI state, never the document's.
+ */
+ let fmtScope: { key: string; v: 'column' | 'cells' } | null = null
+
// --- the properties panel -------------------------------------------------
function renderProps(): void {
@@ -380,6 +386,8 @@ export function mountPanels(host: PanelsHost): Panels {
readOnly: ro(),
locale: locale(),
commit,
+ rerender: () => render(true),
+ value: grid.cursorValue(),
message: cellMessage,
say: (m) => {
// Shown until the next edit or the next selection — a refusal is
@@ -410,27 +418,24 @@ export function mountPanels(host: PanelsHost): Panels {
}
/**
- * The Cell section on a DATASET — the gap this closes.
+ * The Cell section on a DATASET.
*
- * The spreadsheet kind has had one since cellprops.ts landed; this kind had
- * nothing, so ⌘B and the panel both did different things depending on which
- * tab you were on. The Appearance rows below are literally the same builder
- * (cellfmt.ts `buildAppearanceSection`) the spreadsheet draws, so the two
- * cannot drift again.
+ * The Appearance rows below are literally the same builder (cellfmt.ts
+ * `buildAppearanceSection`) the spreadsheet draws, so the two cannot drift.
*
- * WHAT IS DELIBERATELY DIFFERENT is the two rows above it, and they are the
- * type boundary made visible rather than merely respected:
+ * TYPE is READ-ONLY here and says which column decides it. On a dataset the
+ * column owns the type — that is what earns the column formula, the import
+ * refusal and the chart binding — so the cell cannot have its own.
*
- * * TYPE is READ-ONLY here and says which column decides it. On a dataset
- * the column owns the type — that is what earns the column formula, the
- * import refusal and the chart binding — so the cell cannot have its own.
- * Showing it greyed beside the cell's own appearance is the honest way to
- * say "this you may change, that you may not"; an absent row would leave
- * a reader wondering whether the panel simply forgot.
- * * PATTERN is display only. Typing one here stamps how this cell PRINTS
- * and never re-reads the value, which is the opposite of what the same
- * control does on a spreadsheet (there it is a type declaration and rules
- * 6–8 recast). The note says so, because the two controls look identical.
+ * NUMBER FORMAT is the one control both kinds share (cellprops.ts
+ * `buildNumberFormat`), with an "Apply to" switch only this kind has: the
+ * COLUMN's pattern (`Column.format`) or the selected cells' own override.
+ * It used to be two controls in two sections — a cell "Pattern" here and a
+ * column "Format" under Column — and both showed on every column, Text
+ * included, with a money placeholder. Now it is drawn only for the types
+ * whose values print through the number path (`PRINTS_AS_TYPED` is the
+ * other side of that line), plus one escape: a pattern already sitting on a
+ * Text column is shown, with the warning, so it can be cleared.
*/
function buildDatasetCellSection(sheet: TableSheet): void {
section(right, t('Cell'))
@@ -450,25 +455,47 @@ export function mountPanels(host: PanelsHost): Panels {
describeOverrideSelection(keys, `${col.name} ${grid.sel.cursor.row + 1}`))
readonlyRow(right, t('Type'), t(TYPE_LABEL[col.type]))
- const own = typeof cell?.format === 'string' ? cell.format : ''
- const pat = text(own, (v) => {
- const next = v.trim()
- if (next === own) return
- const p = overrideFormatPatch(sheet, keys, next || undefined)
- if (p) commit(p)
- })
- // The COLUMN's pattern as the placeholder: what this cell prints with
- // today, when it has said nothing of its own.
- pat.placeholder = effectiveFormat(sheet, cursorKey) ?? '#,##0.00'
- pat.classList.add('dp-mono')
- pat.disabled = ro()
- row(right, t('Pattern'), pat)
- note(right, t('The column decides what these cells ARE. A pattern here only changes how they print.'))
- // …and on a column that prints its values as they are, "how they print" is
- // nothing at all. Read from the CELL's own pattern, not the effective one:
- // the placeholder above shows the column's, and warning about a pattern the
- // reader did not type here would send them to the wrong field.
- patternInertNote(right, col.type, own)
+ const own = typeof cell?.format === 'string' && cell.format ? cell.format : undefined
+ const colFmt = typeof col.format === 'string' && col.format ? col.format : undefined
+ const numeric = !PRINTS_AS_TYPED.has(col.type)
+ if (numeric || own || colFmt) {
+ // The scope a reader picked survives the rebuild that follows every
+ // commit; otherwise it follows the cell — a cell with its own pattern
+ // opens on "These cells", any other on "This column".
+ const scopeKey = `${sheet.id}\u001f${col.id}`
+ const scope = fmtScope?.key === scopeKey ? fmtScope.v : own ? 'cells' : 'column'
+ const fmt = scope === 'cells' ? own : colFmt
+ buildNumberFormat({
+ host: right,
+ kit: KIT,
+ fmt,
+ kinds: !numeric ? (scope === 'cells' ? ['inherit'] : ['general'])
+ : scope === 'cells' ? ['inherit', 'number', 'currency', 'percent']
+ : ['general', 'number', 'currency', 'percent'],
+ inherited: scope === 'cells' ? colFmt : undefined,
+ scope: {
+ value: scope,
+ set: (next) => { fmtScope = { key: scopeKey, v: next }; render(true) },
+ },
+ preview: (f) => datasetPreview(col, f),
+ key: `${scopeKey}\u001f${scope}`,
+ locale: locale(),
+ readOnly: ro(),
+ rerender: () => render(true),
+ write: (next) => {
+ if (scope === 'cells') {
+ const p = overrideFormatPatch(sheet, keys, next)
+ if (p) commit(p)
+ return
+ }
+ if (next === colFmt) return
+ // `undefined` clears it: JSON.stringify drops the key, so the file
+ // comes back exactly as it was before anyone chose a format.
+ commit({ op: 'setColumn', sheet: sheet.id, col: col.id, patch: { format: next } })
+ },
+ })
+ patternInertNote(right, col.type, own ?? colFmt ?? '')
+ }
buildAppearanceSection({
host: right,
@@ -482,6 +509,21 @@ export function mountPanels(host: PanelsHost): Panels {
})
}
+ /** The cell's own value (or a shape, when it is empty) printed with `fmt`. */
+ function datasetPreview(col: Column, fmt: string | undefined): { text: string; sample: boolean } {
+ const v = grid.cursorValue()
+ const empty = typeof v !== 'number' || !Number.isFinite(v)
+ return { text: formatValue(empty ? 1234.5 : v, { type: col.type, format: fmt }), sample: empty }
+ }
+
+ /**
+ * The Column section: what applies to EVERY type, and then only what applies
+ * to this one. A Text column shows no Total (there is nothing to add up) and
+ * no column shows an empty Formula field with somebody else's expression as
+ * its placeholder — the Formula row is for a COMPUTED column, which is made
+ * with + Formula; on any other column it was a field that, typed into,
+ * silently threw the column's stored values away.
+ */
function buildColumnSection(sheet: TableSheet): void {
section(right, t('Column'))
const col = currentColumn(sheet)
@@ -506,47 +548,30 @@ export function mountPanels(host: PanelsHost): Panels {
},
))
- // The Excel-style pattern (format.ts readPattern): a currency prefix,
- // thousands grouping and a fixed number of decimals. The GLYPHS stay the
- // viewer's, so this really is only "what to show".
- const fmt = text(typeof col.format === 'string' ? col.format : '', (v) => {
- const next = v.trim()
- if (next === (col.format ?? '')) return
- // `undefined` clears it: JSON.stringify drops the key, so the file comes
- // back exactly as it was before anyone typed a pattern. (Over a wire that
- // spelling would arrive as a no-op — the hazard rowcol.ts documents for
- // `hidden` — which is a live concern the day dash gets collab.)
- commit({ op: 'setColumn', sheet: sheet.id, col: col.id, patch: { format: next || undefined } })
- })
- fmt.placeholder = '£#,##0.00'
- row(right, t('Format'), fmt)
- patternInertNote(right, col.type, typeof col.format === 'string' ? col.format : '')
-
- // One expression for the WHOLE column. Editing it here beats the prompt()
- // the grid falls back to, because you can see the column while you type.
- const formula = text(typeof col.formula === 'string' ? col.formula : '', (v) => {
- const next = v.trim()
- if (next === (col.formula ?? '')) return
- if (!next) {
- commit({ op: 'setColumn', sheet: sheet.id, col: col.id, patch: { formula: undefined } })
- return
- }
- // The same rule main.ts's formula dialog follows, for the same reason: a
- // column whose expression now returns text must stop claiming NUMBER, and
- // a type chosen by hand in the dropdown two rows up must not be undone by
- // an unrelated edit here. See computedtype.ts.
- const before = inferComputedType(sheet, col.formula ?? '', col.id)
- const after = inferComputedType(sheet, next, col.id)
- commit({
- op: 'setColumn', sheet: sheet.id, col: col.id,
- patch: col.type === before.type && after.type !== col.type
- ? { formula: next, type: after.type }
- : { formula: next },
+ // One expression for the WHOLE column — shown for a computed column only.
+ if (typeof col.formula === 'string' && col.formula) {
+ const formula = text(col.formula, (v) => {
+ const next = v.trim()
+ if (next === (col.formula ?? '')) return
+ if (!next) {
+ commit({ op: 'setColumn', sheet: sheet.id, col: col.id, patch: { formula: undefined } })
+ return
+ }
+ // The same rule main.ts's formula dialog follows, for the same reason: a
+ // column whose expression now returns text must stop claiming NUMBER, and
+ // a type chosen by hand in the dropdown two rows up must not be undone by
+ // an unrelated edit here. See computedtype.ts.
+ const before = inferComputedType(sheet, col.formula ?? '', col.id)
+ const after = inferComputedType(sheet, next, col.id)
+ commit({
+ op: 'setColumn', sheet: sheet.id, col: col.id,
+ patch: retypePatch(col, before, after, next),
+ })
})
- })
- formula.placeholder = t('Value * Probability')
- formula.classList.add('dp-mono')
- row(right, t('Formula'), formula)
+ formula.classList.add('dp-mono')
+ formula.dataset.dpField = 'formula'
+ row(right, t('Formula'), formula)
+ }
row(right, t('Width'), number(col.w ?? 130, 10, (v) => {
// resizeColumn clamps and rounds — a width is a drag's output, so out of
@@ -554,18 +579,23 @@ export function mountPanels(host: PanelsHost): Panels {
commit(resizeColumn(sheet, col.id, v))
}))
+ // A total adds numbers up. Shown for the number types — and on any other
+ // column only while one is already set, so it can still be switched off.
const agg = sheet.totals?.[col.id]
- const aggValue = totalsChoice(agg)
- const aggSel = select(
- [['none', t('none')] as const, ...AGGS.map((a) => [a, t(a)] as const),
- ...(aggValue === 'custom' ? [['custom', t('custom formula')] as const] : [])],
- aggValue,
- (v) => {
- if (v === 'custom') return // a hand-written {f} is not ours to rewrite
- commit(totalsPatch(sheet, col.id, v === 'none' ? null : v as TotalsAgg))
- },
- )
- row(right, t('Total'), aggSel)
+ if (!PRINTS_AS_TYPED.has(col.type) || agg !== undefined) {
+ const aggValue = totalsChoice(agg)
+ const aggSel = select(
+ [['none', t('none')] as const, ...AGGS.map((a) => [a, t(a)] as const),
+ ...(aggValue === 'custom' ? [['custom', t('custom formula')] as const] : [])],
+ aggValue,
+ (v) => {
+ if (v === 'custom') return // a hand-written {f} is not ours to rewrite
+ commit(totalsPatch(sheet, col.id, v === 'none' ? null : v as TotalsAgg))
+ },
+ )
+ aggSel.dataset.dpField = 'total'
+ row(right, t('Total'), aggSel)
+ }
const frozen = readFrozen(sheet)
const upTo = visibleColumns(sheet).findIndex((c) => c.id === col.id) + 1
diff --git a/scripts/test-dash-computedtype.ts b/scripts/test-dash-computedtype.ts
index ea32a379..b6406ae0 100644
--- a/scripts/test-dash-computedtype.ts
+++ b/scripts/test-dash-computedtype.ts
@@ -150,8 +150,9 @@ console.log('\n5 · the caller calls it')
const panels = readFileSync(new URL('../dash/src/panels.ts', import.meta.url), 'utf8')
ok(!/type: 'number', formula:/.test(main),
'main.ts no longer hardcodes `type: \'number\', formula:` — the line the bug was')
- ok(/inferComputedType\(sheet, got\.expr\)\.type/.test(main),
- 'the New-formula-column dialog types the column from the expression')
+ ok(/const inferred = inferComputedType\(sheet, got\.expr\)/.test(main) &&
+ /type: inferred\.type, \.\.\.inferred\.carry/.test(main),
+ 'the New-formula-column dialog types the column from the expression, and carries money’s format')
ok(/inferComputedType\(sheet, got\.expr, col\.id\)/.test(main),
'and editing an existing expression re-asks the question')
ok(/inferComputedType\(sheet, next, col\.id\)/.test(panels),
@@ -187,5 +188,40 @@ console.log('\n6 · a computed column never trips the type/storage check')
'and the SAME column without the formula is reported — the check is awake, not asleep')
}
+console.log('\n7 · a number computed from Money is Money (review 3.6)')
+{
+ // `Value * 2` over a £ column arrived as a plain Number column: no £, and
+ // `8600` beside `24,800`. The column it reads is money, so the result is.
+ const sheet = sheetOf({ Value: [4300, 12400], Rate: [0.5, 0.25], Qty: [3, 4] })
+ const cols = sheet.columns as any[]
+ Object.assign(cols.find((c) => c.id === 'Value'), { type: 'money', format: '£#,##0', unit: 'GBP' })
+ Object.assign(cols.find((c) => c.id === 'Rate'), { type: 'percent' })
+ Object.assign(cols.find((c) => c.id === 'Qty'), { type: 'number' })
+
+ const dbl = inferComputedType(sheet, 'Value * 2')
+ ok(dbl.type === 'money' && dbl.why === 'money', '`Value * 2` over a Money column is Money')
+ ok(dbl.carry?.format === '£#,##0' && dbl.carry?.unit === 'GBP',
+ 'and carries the money column’s format and unit, so it prints £8,600 like its source')
+ ok(inferComputedType(sheet, 'Rate * Value').type === 'money',
+ 'a money column anywhere in the expression carries it — not only when it comes first')
+ ok(inferComputedType(sheet, 'value * 2').type === 'money',
+ 'references resolve case-insensitively, as recalc resolves them')
+ // NEGATIVE CONTROLS — the carry must not reach columns that read no money.
+ const qty = inferComputedType(sheet, 'Qty * 2')
+ ok(qty.type === 'number' && !qty.carry, 'a number computed from a plain Number stays a plain Number')
+ ok(inferComputedType(sheet, 'IF(Value > 5000, "big", "small")').type === 'text',
+ 'a TEXT result that reads money stays text — the carry applies to numeric results only')
+
+ const { retypePatch } = await import('../dash/src/computedtype.ts')
+ const col = { id: 'f', name: 'F', type: 'number', formula: 'Qty * 2' } as any
+ const before = inferComputedType(sheet, 'Qty * 2', undefined)
+ const p = retypePatch(col, before, dbl, 'Value * 2')
+ ok(p.type === 'money' && p.format === '£#,##0' && p.unit === 'GBP',
+ 'editing an untouched column to read money re-types it to Money, with the format')
+ const chosen = retypePatch({ ...col, type: 'percent' }, before, dbl, 'Value * 2')
+ ok(chosen.type === undefined && chosen.format === undefined,
+ 'a type chosen by hand is never overruled, and gets no format it did not ask for')
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/scripts/test-dash-panel-context-browser.mjs b/scripts/test-dash-panel-context-browser.mjs
new file mode 100644
index 00000000..f6bfd7a3
--- /dev/null
+++ b/scripts/test-dash-panel-context-browser.mjs
@@ -0,0 +1,299 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The properties panel shows what applies to the selection, and nothing else.
+//
+// npm run build:single --prefix dash && node scripts/test-dash-panel-context-browser.mjs
+//
+// Measured in the packaged document (headless Chromium), on both kinds of sheet:
+// 1. PER COLUMN TYPE on a dataset — Text, Number, Money, Percent, Date,
+// Yes/No, Category, and a computed Money column — the Number format
+// control appears for the three number types only; no column shows a
+// number pattern, a money placeholder or another column's formula as a
+// placeholder; Total appears for the number types only; Formula appears for
+// the computed column only.
+// 2. ONE number-format control. A spreadsheet cell shows a single "Number
+// format" select — no Pattern field (until Custom… is chosen, which reveals
+// it), no "Shows as" box, no "Format" row — and a dataset cell shows the
+// same control with an "Apply to" scope: "These cells" writes the cell's
+// override and leaves the column's pattern alone. Custom… → a typed pattern
+// lands in the file; the Time preset reads `2:30 pm` as `14:30`.
+// 3. AN UNSET COLOUR WELL READS UNSET, light and dark — measured from pixels,
+// not from a style read back: the well paints the field's own fill, not the
+// grey/cream fallback. Positive control: a well whose cell HAS a colour
+// paints that colour, so the sampler is awake.
+// 4. Checkboxes are bare boxes (≤ 18px), not full-width bordered fields.
+// 5. A formula column made from Money (`Value * 2`, through the toolbar's own
+// dialog) is Money with the source's £ format, and one column never mixes
+// grouped and ungrouped numbers (`8600` beside `24,800`).
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+
+let checks = 0
+let failures = 0
+function ok(cond, msg) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`)
+}
+
+const SHELL = new URL('../dash/dist-single/Bento_Dash.bento.html', import.meta.url).href
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+
+async function openPage(scheme) {
+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 1000 }, colorScheme: scheme, deviceScaleFactor: 1 })
+ const page = await ctx.newPage()
+ const errors = []
+ page.on('pageerror', (e) => errors.push(e.message))
+ await page.goto(SHELL)
+ await page.waitForFunction(() => window.bento && window.bento.doc, null, { timeout: 20000 })
+ // The fixture: the starter workbook plus the column types it lacks.
+ await page.evaluate(() => {
+ const doc = JSON.parse(JSON.stringify(window.bento.doc))
+ const sh = doc.sheets[0]
+ sh.columns.push(
+ { id: 'qty', name: 'Qty', type: 'number', w: 90 },
+ { id: 'done', name: 'Done', type: 'bool', w: 80 },
+ { id: 'tier', name: 'Tier', type: 'enum', w: 90 },
+ )
+ sh.data.qty = { enc: 'raw', v: [8600, 24800, 3, 12, 5, 7, 9, 11] }
+ sh.data.done = { enc: 'raw', v: [true, false, true, false, true, false, true, false] }
+ sh.data.tier = { enc: 'dict', dict: ['A', 'B'], idx: [0, 1, 0, 1, 0, 1, 0, 1] }
+ doc.sheets[1].cells.D30 = { v: '2:30 pm' }
+ window.bento.loadDoc(JSON.stringify(doc))
+ })
+ await page.waitForTimeout(300)
+ return { ctx, page, errors }
+}
+
+const cellAt = (page, row, col) =>
+ page.locator(`.dg-row[data-row="${row}"] .dg-cell:not(.dg-gutter)`).nth(col)
+
+async function select(page, row, col) {
+ await cellAt(page, row, col).click()
+ await page.waitForTimeout(120)
+}
+
+/** The visible panel rows, with their section — read by LABEL, which both the old and new panels have. */
+const panelRows = (page) => page.evaluate(() => {
+ const out = []
+ let sec = ''
+ for (const el of document.querySelectorAll('.dp-right .dp-section, .dp-right .dp-row')) {
+ if (!el.offsetParent) continue
+ if (el.classList.contains('dp-section')) { sec = el.textContent.trim(); continue }
+ const label = el.firstElementChild?.textContent.trim() ?? ''
+ const ctl = el.querySelector('input, select')
+ out.push({
+ sec, label,
+ tag: ctl ? (ctl.tagName === 'SELECT' ? 'select' : ctl.type) : 'text',
+ value: ctl ? ctl.value : el.textContent.trim(),
+ placeholder: ctl?.placeholder ?? '',
+ })
+ }
+ return out
+})
+const has = (rows, label) => rows.some((r) => r.label === label)
+const count = (rows, label) => rows.filter((r) => r.label === label).length
+
+async function chooseIn(page, label, value) {
+ const sel = page.locator('.dp-right .dp-row').filter({ has: page.locator(`span:text-is("${label}")`) }).locator('select').first()
+ await sel.selectOption(value)
+ await page.waitForTimeout(150)
+}
+
+// ============================================================ 1 · per column type
+console.log('\n1 · a dataset column shows only the fields its type uses')
+{
+ const { ctx, page, errors } = await openPage('light')
+ const cols = await page.evaluate(() => window.bento.doc.sheets[0].columns.map((c) => ({ name: c.name, type: c.type, formula: !!c.formula })))
+ const NUMERIC = new Set(['number', 'money', 'percent'])
+ let sawNumeric = 0
+ let sawPlain = 0
+ for (let ci = 0; ci < cols.length; ci++) {
+ const c = cols[ci]
+ await select(page, 1, ci)
+ const rows = await panelRows(page)
+ const what = `${c.name} (${c.type}${c.formula ? ', computed' : ''})`
+ const numeric = NUMERIC.has(c.type)
+ if (numeric) sawNumeric++; else sawPlain++
+ ok(numeric ? count(rows, 'Number format') === 1 : !has(rows, 'Number format'),
+ `${what}: Number format ${numeric ? 'shown once' : 'absent'}`)
+ ok(!has(rows, 'Format') && !has(rows, 'Shows as') && !has(rows, 'Pattern'),
+ `${what}: no separate Format / Pattern / Shows as control`)
+ const bad = rows.filter((r) => /£|#,##0|\*/.test(r.placeholder))
+ ok(bad.length === 0,
+ `${what}: no field shows a money, pattern or formula placeholder${bad.length ? ' — ' + bad.map((r) => `${r.label} "${r.placeholder}"`).join(', ') : ''}`)
+ ok(numeric ? has(rows, 'Total') : !has(rows, 'Total'), `${what}: Total ${numeric ? 'shown' : 'absent'}`)
+ ok(c.formula ? has(rows, 'Formula') : !has(rows, 'Formula'), `${what}: Formula ${c.formula ? 'shown' : 'absent'}`)
+ await page.locator('.dp-right').screenshot({ path: `${process.env.SHOT_DIR || '/tmp'}/panel-ctx-${ci}-${c.type}.png` }).catch(() => {})
+ }
+ ok(sawNumeric >= 4 && sawPlain >= 5, `the fixture covered every type (${sawNumeric} number-typed, ${sawPlain} other)`)
+ ok(errors.length === 0, `no page errors${errors.length ? ' — ' + errors.join('; ') : ''}`)
+ await ctx.close()
+}
+
+// ============================================================ 2 · one format control
+console.log('\n2 · one number-format control, on both kinds of sheet')
+{
+ const { ctx, page, errors } = await openPage('light')
+ // --- dataset: the scope switch writes the cell override, not the column
+ const valueCol = await page.evaluate(() => window.bento.doc.sheets[0].columns.findIndex((c) => c.id === 'value'))
+ await select(page, 1, valueCol)
+ let rows = await panelRows(page)
+ ok(has(rows, 'Apply to'), 'a dataset cell offers Apply to (this column / these cells)')
+ let wrote = false
+ try {
+ await chooseIn(page, 'Apply to', 'cells')
+ await chooseIn(page, 'Number format', 'percent')
+ wrote = true
+ } catch { /* old panel: no such control */ }
+ const after = await page.evaluate(() => {
+ const sh = window.bento.doc.sheets[0]
+ const over = Object.entries(sh.cells ?? {}).find(([k]) => k.startsWith('value:'))
+ return { over: over?.[1]?.format, col: sh.columns.find((c) => c.id === 'value').format }
+ })
+ ok(wrote && /%$/.test(after.over ?? '') && after.col === '£#,##0',
+ `"These cells" + Percent writes the cell override (${after.over}) and leaves the column at £#,##0 (${after.col})`)
+
+ // --- spreadsheet
+ await page.locator('[role=tab]').filter({ hasText: 'Scratch' }).first().click()
+ await page.waitForTimeout(300)
+ await select(page, 8, 1) // B9 — 100000, £#,##0
+ rows = await panelRows(page)
+ ok(count(rows, 'Number format') === 1, 'a spreadsheet cell shows ONE Number format select')
+ ok(!has(rows, 'Format') && !has(rows, 'Shows as') && !has(rows, 'Pattern'),
+ 'and no Format row, no Shows as box, no Pattern field beside it')
+ const sample = await page.locator('.dp-right .dc-sample').first().textContent().catch(() => null)
+ ok(sample === '£100,000', `a live sample prints the cell with its format (${sample})`)
+
+ let custom = false
+ try {
+ await chooseIn(page, 'Number format', 'custom')
+ custom = true
+ } catch { /* old panel offered Custom only for a pattern no preset spells */ }
+ rows = await panelRows(page)
+ ok(custom && has(rows, 'Pattern'), 'choosing Custom… reveals the Pattern field')
+ const focused = await page.evaluate(() => document.activeElement?.closest('.dp-row')?.firstElementChild?.textContent)
+ ok(focused === 'Pattern', 'and puts the cursor in it')
+ if (custom) {
+ await page.keyboard.type('0.0 "kg"')
+ await page.keyboard.press('Enter')
+ await page.waitForTimeout(200)
+ }
+ const fmt = await page.evaluate(() => window.bento.doc.sheets[1].cells.B9?.format)
+ ok(fmt === '0.0 "kg"', `the typed pattern lands in the file (${fmt})`)
+ rows = await panelRows(page)
+ ok(rows.find((r) => r.label === 'Number format')?.value === 'custom' && has(rows, 'Pattern'),
+ 'a pattern no preset spells reopens on Custom…, with its field')
+ await chooseIn(page, 'Number format', 'number').catch(() => {})
+ rows = await panelRows(page)
+ ok(!has(rows, 'Pattern') && has(rows, 'Decimals'), 'a preset hides the Pattern field again and shows its own options')
+
+ // --- Time
+ await select(page, 29, 3) // D30 — "2:30 pm"
+ let timed = false
+ try { await chooseIn(page, 'Number format', 'time'); timed = true } catch { /* no Time preset */ }
+ const d30 = await page.evaluate(() => window.bento.doc.sheets[1].cells.D30)
+ ok(timed && d30?.v === '14:30' && d30?.format === 'hh:mm', `Time reads "2:30 pm" as 14:30 (${JSON.stringify(d30)})`)
+ ok(errors.length === 0, `no page errors${errors.length ? ' — ' + errors.join('; ') : ''}`)
+ await ctx.close()
+}
+
+// ============================================================ 3 + 4 · wells and checkboxes
+/** The colour a well PAINTS, off its diagonal, read from a screenshot. */
+async function wellPixel(page, label) {
+ const well = page.locator('.dp-right .dp-row').filter({ has: page.locator(`span:text-is("${label}")`) }).locator('input[type=color]').first()
+ const box = await well.boundingBox()
+ if (!box) return null
+ // Below the bottom-left → top-right strike, away from the border.
+ const x = Math.round(box.x + box.width * 0.78)
+ const y = Math.round(box.y + box.height * 0.62)
+ const png = await page.screenshot({ clip: { x, y, width: 1, height: 1 } })
+ return page.evaluate(async (b64) => {
+ const img = new Image()
+ img.src = `data:image/png;base64,${b64}`
+ await img.decode()
+ const c = document.createElement('canvas')
+ c.width = c.height = 1
+ const g = c.getContext('2d')
+ g.drawImage(img, 0, 0)
+ return [...g.getImageData(0, 0, 1, 1).data.slice(0, 3)]
+ }, png.toString('base64'))
+}
+const hex = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16))
+const near = (a, b, tol = 10) => !!a && a.every((v, i) => Math.abs(v - b[i]) <= tol)
+
+for (const scheme of ['light', 'dark']) {
+ console.log(`\n3 · an unset colour well reads unset (${scheme})`)
+ const { ctx, page } = await openPage(scheme)
+ const field = await page.evaluate(() => {
+ const p = document.createElement('div')
+ p.style.color = getComputedStyle(document.documentElement).getPropertyValue('--field')
+ document.body.appendChild(p)
+ const m = getComputedStyle(p).color.match(/\d+/g).slice(0, 3).map(Number)
+ p.remove()
+ return m
+ })
+ await select(page, 1, 0) // Region 2 — nothing set
+ for (const [label, fallback] of [['Text colour', '#1e2a3a'], ['Background', '#fff3cd']]) {
+ const px = await wellPixel(page, label)
+ // (The fallback is only a separate test where it differs from the field —
+ // in dark the ink fallback and the field are both near-black.)
+ ok(near(px, field) && (near(field, hex(fallback), 30) || !near(px, hex(fallback), 30)),
+ `${label} with nothing set paints the field's own fill (${px}), not the ${fallback} fallback`)
+ }
+
+ // POSITIVE CONTROL: a well whose cell has colours paints them.
+ await page.locator('[role=tab]').filter({ hasText: 'Scratch' }).first().click()
+ await page.waitForTimeout(300)
+ await select(page, 9, 1) // B10 — bg #FFF4D6
+ const bg = await wellPixel(page, 'Background')
+ ok(near(bg, hex('#fff4d6')), `a SET background paints its colour (${bg}) — the sampler is awake`)
+ await select(page, 0, 3) // D1 — colour #5B6B80
+ const ink = await wellPixel(page, 'Text colour')
+ ok(near(ink, hex('#5b6b80')), `a SET text colour paints its colour (${ink})`)
+
+ console.log(`\n4 · checkboxes are bare (${scheme})`)
+ const boxes = await page.evaluate(() => [...document.querySelectorAll('.dp-right input[type=checkbox]')]
+ .filter((e) => e.offsetParent).map((e) => { const r = e.getBoundingClientRect(); return [Math.round(r.width), Math.round(r.height)] }))
+ ok(boxes.length >= 4, `the panel shows checkboxes to measure (${boxes.length})`)
+ ok(boxes.every(([w, h]) => w <= 18 && h <= 18),
+ `every checkbox is a bare box, not a full-width field (${[...new Set(boxes.map((b) => b.join('×')))].join(', ')})`)
+ await ctx.close()
+}
+
+// ============================================================ 5 · money carries, grouping is per column
+console.log('\n5 · a formula over Money is Money; a column never mixes grouping')
+{
+ const { ctx, page, errors } = await openPage('light')
+ const colText = (ci) => page.evaluate((ci) => [...document.querySelectorAll('.dg-row')]
+ .filter((r) => r.dataset.rid && r.querySelector('.dg-cell:not(.dg-gutter)'))
+ .map((r) => r.querySelectorAll('.dg-cell:not(.dg-gutter)')[ci]?.textContent.trim() ?? '')
+ .filter(Boolean), ci)
+ const mixed = (vals) => {
+ const big = vals.filter((v) => /\d{4,}|\d,\d{3}/.test(v))
+ return big.some((v) => v.includes(',')) && big.some((v) => /\d{4}/.test(v.replace(/[^\d,]/g, '')))
+ }
+ const qtyCol = await page.evaluate(() => window.bento.doc.sheets[0].columns.findIndex((c) => c.id === 'qty'))
+ const qty = await colText(qtyCol)
+ ok(qty.includes('8600') || qty.includes('8,600'), `the Qty column painted (${qty.slice(0, 3).join(' / ')})`)
+ ok(!mixed(qty), `a plain Number column groups all its values or none (${qty.slice(0, 2).join(' / ')})`)
+
+ await page.locator('[data-act=formula]').click()
+ await page.waitForSelector('.dx-ask')
+ const ins = page.locator('.dx-ask .dx-ask-in')
+ await ins.nth(0).fill('Value * 2')
+ await ins.nth(1).fill('Double')
+ await page.locator('.dx-ask-go').click()
+ await page.waitForTimeout(300)
+ const col = await page.evaluate(() => window.bento.doc.sheets[0].columns.find((c) => c.name === 'Double'))
+ ok(col?.type === 'money' && col?.format === '£#,##0',
+ `\`Value * 2\` over a £ column is a Money column with its format (${col?.type}, ${col?.format})`)
+ const dblCol = await page.evaluate(() => window.bento.doc.sheets[0].columns.findIndex((c) => c.name === 'Double'))
+ const dbl = await colText(dblCol)
+ ok(dbl.length >= 8 && dbl.every((v) => v.startsWith('£')), `every value prints in £ (${dbl.slice(0, 2).join(' / ')})`)
+ ok(!mixed(dbl), 'and the column never prints 8600 beside 24,800')
+ ok(errors.length === 0, `no page errors${errors.length ? ' — ' + errors.join('; ') : ''}`)
+ await ctx.close()
+}
+
+await browser.close()
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-dash-panelrhythm.ts b/scripts/test-dash-panelrhythm.ts
index 8284f0df..3e8d7bbd 100644
--- a/scripts/test-dash-panelrhythm.ts
+++ b/scripts/test-dash-panelrhythm.ts
@@ -181,8 +181,8 @@ const RAW_OK: Array<{ re: RegExp; props: readonly string[] | '*'; why: string }>
why: 'the resizer chevron is a 16×44 drawer pull, not a row control' },
{ re: /^\.dp-sec-toggle::before/, props: '*',
why: 'the disclosure triangle is drawn out of borders' },
- { re: /^\.dp-row input\[type='checkbox'\][^ ]*::(before|after)/, props: ['height', 'border-radius'],
- why: 'the 14px tick box inside the field, and the tick knocked out of it' },
+ { re: /^\.dp-row input\[type='checkbox'\]$/, props: ['height'],
+ why: 'a bare 16px checkbox, slides\' .ed-toggle — the ROW keeps --dp-row, the box is not a field' },
{ re: /^\.dp-centre/, props: ['height'], why: 'the centre column is layout, not a control' },
{ re: /^\.dv-|^\.dg-cell/, props: '*',
why: 'the in-cell dropdown, its menu and its marks are grid furniture, not panel rows' },
diff --git a/scripts/test-dash-rowcol.ts b/scripts/test-dash-rowcol.ts
index d489a7d9..a11ef16f 100644
--- a/scripts/test-dash-rowcol.ts
+++ b/scripts/test-dash-rowcol.ts
@@ -490,7 +490,7 @@ const from = (v: unknown[]) => (row: number) => v[row]
'eight characters of text get a lowercase weight')
ok(autoFitWidth(from([12345678]), col({ name: 'A', type: 'number', format: '0' }), 1) === 84,
'and eight DIGITS get a wider one — a clipped digit is a wrong number')
- ok(autoFitWidth(from([12345678]), col({ name: 'A', type: 'number' }), 1) === 100,
+ ok(autoFitWidth(from([12345678]), col({ name: 'A', type: 'number', format: '#,##0' }), 1) === 100,
'while the same number GROUPED is ten glyphs, not eight — the separators need room too')
}
{