From 0d385c805690e793ad6ffacb744aaded76582546 Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Fri, 20 Nov 2026 11:36:00 +0700 Subject: [PATCH] fix: numbers typed are read in the viewer's locale, whole or not at all (#17) `locale` (DocViewer prop, ``, `mount()`, the third argument of `xlsx.set`) is the BCP 47 tag the numbers a person types are read in: cells (numbers, percentages, amounts), the font size box, the Page setup margins and column spacing, the Header & footer size. One parser in the core (src/core/number-input.ts) takes the separators, signs and digits from Intl.NumberFormat.formatToParts: `1,5` and `1.234,5` are numbers in de-DE. The whole text is one number or none: a separator that is neither the decimal one nor a well-formed grouping makes the text no number (`1.5` in de-DE, `1,5` in en-US), and a prefix is never read (`12pt` keeps the font size it had). Grouping: the locale's character between groups of its sizes (3, or 3 then 2 in India), every space where it groups with a space, both apostrophes in Swiss German. Without a locale every input reads as before (a decimal point, commas by thousands), whatever the browser's language; the font size box alone still reads a decimal comma too (`12,5` is 12.5, as since c491ea7), a size needing no grouping, but not `1,234` or `1,2,5`. Saved values are numbers and formulas are not localized. A number edited again shows the locale's decimal separator, which reads back as the same number. A shared cell edit carries the locale, so every participant and `compact` read it alike. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + docs/api.md | 24 ++- docs/collaboration.md | 1 + docs/features.md | 19 +- e2e/app/main.tsx | 2 + e2e/docx-page.spec.ts | 23 ++ e2e/embed.spec.ts | 29 +++ e2e/harness.ts | 4 +- e2e/xlsx.spec.ts | 96 +++++++++ src/collab/xlsx-ops.ts | 12 +- src/collab/xlsx-worker.ts | 2 +- src/collab/xlsx.ts | 10 +- src/core/number-input.ts | 210 +++++++++++++++++++ src/core/worker/engine.ts | 4 +- src/core/worker/protocol.ts | 5 +- src/core/xlsx/editor.ts | 49 ++--- src/core/xlsx/types.ts | 9 + src/embed.ts | 5 +- src/react/DocViewer.tsx | 11 + src/react/common/locale.ts | 9 + src/react/docx/HeaderFooterDialog.tsx | 24 ++- src/react/docx/PageSetupDialog.tsx | 23 +- src/react/edit/Toolbar.tsx | 52 +++-- src/react/xlsx/XlsxView.tsx | 11 +- test/number-input.test.tsx | 284 +++++++++++++++++++++++++ test/xlsx-locale.test.ts | 289 ++++++++++++++++++++++++++ 26 files changed, 1129 insertions(+), 79 deletions(-) create mode 100644 src/core/number-input.ts create mode 100644 src/react/common/locale.ts create mode 100644 test/number-input.test.tsx create mode 100644 test/xlsx-locale.test.ts diff --git a/README.md b/README.md index b057e26..18bfb77 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ Also online at [p10node.github.io/office-engine](https://p10node.github.io/offic - **Comments**: threads with replies, resolve, edit / delete, @mentions; on DOCX text, XLSX cells and PPTX slides, stored in the file the way Word, Excel and PowerPoint store them - **Real-time collaboration**: live edits, avatars, collaborators' cursors, offline edits sync on reconnect - **Dark mode and theming**: `theme="dark"` or `"auto"` (follows the OS), or a theme object with design tokens for colors, type and shape ([Theming](docs/theming.md)); documents keep their own colors +- **Numbers typed in a locale**: `locale="de-DE"` reads `1,5` and `1.234,5` typed into cells and fields (font size, margins); the whole entry or nothing, saved as the number itself, formulas unchanged ([API](docs/api.md#numbers-typed-in-a-locale)) - **Embed anywhere**: React component, hook, vanilla `mount()`, `` web component, single ` ``` -``: attributes `src`, `name`, `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`; properties `.file = File` and `.icons` (map or resolver, as `icons` above); events `load`, `error`, `comment` (`detail`: a `CommentEvent`). +``: attributes `src`, `name`, `editable`, `toolbar="false"`, `thumbnails="false"`, `save="false"`, `download="false"`, `file-menu="false"`, `open="false"`, `capture-select-all="false"`, `theme="dark"` (or `"auto"`), `locale="de-DE"` (numbers typed, see [above](#numbers-typed-in-a-locale)), `collab` / `room` / `user` / `base` (real-time collaboration; `user` also writes the comments), `comments="false"`; properties `.file = File` and `.icons` (map or resolver, as `icons` above); events `load`, `error`, `comment` (`detail`: a `CommentEvent`). ## Core API (no React) @@ -225,6 +246,7 @@ doc.on('xlsx:progress', (p) => {}) await doc.call('xlsx.block', 0, 1000, 1100) // formatted cells, rows [1000, 1100) await doc.call('pptx.slide', 12) // slide model with layout/master/theme resolved await doc.call('xlsx.set', 0, [{ r: 4, c: 1, input: '=SUM(A1:A4)' }]) +await doc.call('xlsx.set', 0, [{ r: 5, c: 1, input: '1.234,5' }], { locale: 'de-DE' }) // numbers typed in a locale: 1234.5 const clip = await doc.call('xlsx.copy', 0, { r0: 0, c0: 0, r1: 9, c1: 2 }) // cells as they are (values, formats, formulas) + `text` for the clipboard await doc.call('xlsx.sheetOp', 0, { op: 'paste', range: { r0: 20, c0: 0, r1: 29, c1: 2 }, cells: clip.cells, from: { sheet: clip.sheet, r0: 0, c0: 0 } }) await doc.call('xlsx.sheetOp', 0, { op: 'clear', range: { r0: 0, c0: 3, r1: 1048575, c1: 3 } }) // a whole column, every row of it diff --git a/docs/collaboration.md b/docs/collaboration.md index 1c4d73d..e3e17b3 100644 --- a/docs/collaboration.md +++ b/docs/collaboration.md @@ -108,6 +108,7 @@ async function takeSnapshot(room: string) { - Undo / redo only touches your own changes: a cell someone else typed over since is left as they left it - A formula typed while someone else inserts / deletes rows or columns, or renames a sheet, is rewritten with that operation (it reads the cells meant) +- A cell edit carries the `locale` its numbers were typed in ([API](api.md#numbers-typed-in-a-locale)): every participant and `compact` read `1,5` typed with `de-DE` as 1.5, whatever their own `locale`. Each replica takes the locale's separators from its own `Intl` data; spaces and apostrophes are read in all their forms, so the usual differences between browser and server versions do not change a value. A participant running an older version reads such an edit with a decimal point - DOCX rooms are not snapshotted yet (their edits run in the view's editor): newcomers replay the whole history - Deleting rows / columns can't be undone while collaborating - One hub process per room; batches not yet flushed (up to 250 ms on S3) are lost if it crashes, and clients ahead of the stored log must reopen diff --git a/docs/features.md b/docs/features.md index c7ca46b..a34ae8e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -183,7 +183,7 @@ Diagram sources open as a document holding the drawing (an SVG picture, editable ### XLSX -- **Cells**: edit, line break inside a cell or the formula bar (`Alt+Enter` or `Shift+Enter`: the cell wraps and its row grows to show every line), range selection, select all (Ctrl/⌘+A), copy/cut/paste (within a workbook: exact values, formats and formulas, a cut moving the cells and what reads them; from other programs: tab separated text, quoted cells with line breaks included; a whole column or sheet is cleared and copied whole, the rows not shown yet too), fill down/right and the fill handle (drag the corner of the selection down or to the right: one row / column is copied, several are repeated), one copied value pasted into a selection fills it, a paste of HTML only (a table) pastes its cells, a paste that would drop data over merged cells is refused with a message, merging cells that hold data says what was dropped, sort (the rows of the table around the selection, its header left on top; in Excel's order: numbers, text, FALSE, TRUE, errors, cells without anything last in either direction; comments go with their rows; a range holding merged cells is refused with a message), find & replace (match case, entire cell, in formulas). A date or a percentage typed into a cell without a format shows as one; a cell formatted as Text keeps what is typed. `+A1+B1`, `-A1` and `@SUM(A1:A3)` are formulas (what reads a cell or calls a function: `-5` is a number, `- item` is text); `#N/A` and the other error values typed are errors; `1,234,567`, `$50`, `€1,200.50` and `50 ₫` are numbers shown as typed; a number of more than 15 digits (a card number) stays text. A formula typed into a cell without a format shows as what it computes (`=TODAY()`, `=DATE(…)`, `=A1+30` as dates, `=A1` as A1 is shown) +- **Cells**: edit, line break inside a cell or the formula bar (`Alt+Enter` or `Shift+Enter`: the cell wraps and its row grows to show every line), range selection, select all (Ctrl/⌘+A), copy/cut/paste (within a workbook: exact values, formats and formulas, a cut moving the cells and what reads them; from other programs: tab separated text, quoted cells with line breaks included; a whole column or sheet is cleared and copied whole, the rows not shown yet too), fill down/right and the fill handle (drag the corner of the selection down or to the right: one row / column is copied, several are repeated), one copied value pasted into a selection fills it, a paste of HTML only (a table) pastes its cells, a paste that would drop data over merged cells is refused with a message, merging cells that hold data says what was dropped, sort (the rows of the table around the selection, its header left on top; in Excel's order: numbers, text, FALSE, TRUE, errors, cells without anything last in either direction; comments go with their rows; a range holding merged cells is refused with a message), find & replace (match case, entire cell, in formulas). A date or a percentage typed into a cell without a format shows as one; a cell formatted as Text keeps what is typed. `+A1+B1`, `-A1` and `@SUM(A1:A3)` are formulas (what reads a cell or calls a function: `-5` is a number, `- item` is text); `#N/A` and the other error values typed are errors; `1,234,567`, `$50`, `€1,200.50` and `50 ₫` are numbers shown as typed; a number of more than 15 digits (a card number) stays text. With the viewer's `locale` these are read in its separators (`1,5`, `1.234,5`, `50 %` with `de-DE`): see [Numbers typed in a locale](#numbers-typed-in-a-locale). A formula typed into a cell without a format shows as what it computes (`=TODAY()`, `=DATE(…)`, `=A1+30` as dates, `=A1` as A1 is shown) - **Keyboard**: arrows, `Tab` / `Enter` (after Tabs, Enter returns to the column the row was started in), `Home` / `End` / `Ctrl+Home` / `Ctrl+End`, `Ctrl+Arrow` (to the edge of the block of filled cells), `Shift+Space` / `Ctrl+Space` (select the row / column), `Alt+=` (AutoSum), `Ctrl+;` (today; with Shift the time), `Ctrl+Enter` (the entry into every selected cell), `F4` (cycles `$` on the reference at the caret), `F2`, `Ctrl+S` (also in a cell being edited). Text that comes from an IME (Vietnamese Telex included), a virtual keyboard or an emoji picker starts the edit of the selected cell: the grid keeps a hidden text field for the keyboard, which becomes the cell editor. Its on-screen keyboard is not opened until a cell is edited - **Sizes**: `Wrap text` and a text rotation grow the rows to show the text (tilted text goes out over the cells to its right, as in Excel); double click on the edge of a column / row fits it; a column left at the default width widens when a number format (date, currency…) would show `####`. A number without a format is shown in what fits its column, measured in the font the browser has (fewer decimals, then the scientific form, `####` last). Pattern fills show as the mix of their colors, diagonal borders are drawn, shrink to fit scales the text; rich text (parts of a cell in fonts of their own) is shown, and typing over it leaves plain text. Not done: zoom; rows of a file that say no height are not fitted to wrapped or turned text when it is opened - **Formulas**: auto-calculated: the functions of Excel and of Google Sheets but those that ask a service or the application itself (543 of the 568 the two list: [formula-coverage.md](formula-coverage.md) says which, and what differs); shared and array formulas; `LET` and `LAMBDA` (with `MAP`, `REDUCE`, `SCAN`, `BYROW`, `BYCOL`, `MAKEARRAY`); defined names (of the workbook, or local to a sheet), structured references (`Table1[Qty]`, `[@Qty]`), 3-D references (`First:Last!A1`) and the intersection of references (a space: `B2:D4 C1:C9`, `North Q1`); `INDIRECT` / `OFFSET` / `NOW` / `RAND` at every change, `TODAY` / `NOW` / `RAND` also when the file is opened; a workbook that says to compute on load is computed when opened; a formula using a function the engine does not have, or a name the workbook does not, keeps the value the file holds @@ -206,7 +206,22 @@ Diagram sources open as a document holding the drawing (an SVG picture, editable ### Toolbar -Single row, buttons that don't fit collapse into `⋮`; custom-drawn dropdowns (font/style preview, number formats with examples, ↑↓/Enter/Esc/type-ahead keys, never steals focus from the document); font size box `− 11 +` accepts direct input; cell borders picked from an icon grid; color pickers have a palette plus a **Custom** row (`+` opens the system color picker, recent custom colors are remembered across sessions). Every icon can be replaced with the host's own set (Lucide, Phosphor or any other) through the `icons` prop, see [API](api.md#icons). +Single row, buttons that don't fit collapse into `⋮`; custom-drawn dropdowns (font/style preview, number formats with examples, ↑↓/Enter/Esc/type-ahead keys, never steals focus from the document); font size box `− 11 +` accepts direct input (one whole number: `12,5` with `de-DE`, `12.5` or `12,5` without a locale; anything else keeps the size it had, see [Numbers typed in a locale](#numbers-typed-in-a-locale)); cell borders picked from an icon grid; color pickers have a palette plus a **Custom** row (`+` opens the system color picker, recent custom colors are remembered across sessions). Every icon can be replaced with the host's own set (Lucide, Phosphor or any other) through the `icons` prop, see [API](api.md#icons). + +### Numbers typed in a locale + +The viewer's `locale` ([API](api.md#numbers-typed-in-a-locale)) sets how typed numbers are read: in cells, the font size box, the margins and column spacing of Page setup and the size in Header & footer. One parser in the core reads them all, by these rules: + +- **Without a locale** (or with a tag that is not one, or one `Intl` has no data for): a decimal point and commas grouping by thousands, exactly as before; the browser's language is never used. `en-US` reads the same. +- **Separators**: the locale's decimal separator, grouping separator, minus sign, percent sign and digits, from `Intl.NumberFormat(locale).formatToParts`. `1,5` in `de-DE`, `fr-FR`, `sv-SE`; `1.5` in `en-US`, `de-CH`, `en-IN`. +- **The whole text**: it is one number or none. A prefix is never read: `12,5` without a locale and `12,5pt` are not 12, `1.2.3` is not 1.2. In a cell what is not a number stays text (as before); in a field the previous value is kept. +- **The font size box, without a locale**: the one exception. It reads a decimal comma as well as a point (`12,5` and `12.5` are 12.5, as before), since a size from 1 to 400 needs no grouping; it still reads the whole text only, so `12pt`, `1.2.5`, `1,2,5`, `1,234` (a comma before three digits could group thousands) and an empty box keep the size it had. With a locale the box follows the locale like the rest: `12,5` is refused in `en-US`. Cells, Page setup and Header & footer have no such exception. +- **Grouping**: only the locale's grouping character, and only between groups of the size the locale writes (3 digits; in India 3 next to the decimal separator, then 2: `12,34,567` in `en-IN`), the same character throughout a number. A locale grouping with a space reads the ordinary space, the no-break space (U+00A0), the narrow no-break space (U+202F) and the thin space (U+2009) alike; one grouping with an apostrophe (`de-CH`) both `'` and `’`. Grouping is optional (`1234,5` = `1.234,5` in `de-DE`) and does not go with an exponent. +- **The other convention's separator is refused, not guessed**: `1,5` in `en-US` (a comma that does not group 3 digits) and `1.5` in `de-DE` (a point that does not) are not numbers, nor is `1,234.5` in `de-DE` (a grouping separator after the decimal one) or `1,234,567` in `en-IN`. A well-formed grouping is read as one: `1.234` in `de-DE` is 1234, as `1,234` is 1234 without a locale; the cell takes the `#,##0` format, which shows it grouped. +- **Forms**: a sign (`-`, `+`, and the locale's own minus such as `−` in `sv-SE`), digits, decimals (`,5` and `5,` in `de-DE`), an exponent (`1,5e3`, `1,5E-3`); in a cell also a percentage, the sign after the number (`12,5%`, and `50 %` where the locale writes a space before the sign: `de-DE`, `fr-FR`; not `%50`, also in Turkish) and an amount with a currency sign (`$ € £ ¥ ₫ ₩ ₹ ₽ ₱ ฿`) before or after it (`1.234,50 €`). Parentheses for negatives, fractions (`1 1/2`) and times are not read as numbers, with or without a locale. +- **Digits**: ASCII digits in every locale, and the locale's own digits where it writes others (Arabic-Indic `١٫٥` in `ar-EG`, Persian, Devanagari, Bengali…), not both in one number; the direction marks such locales write around signs are ignored. +- **Saved values**: a number, as OOXML stores it (`1234.5`), the same whatever the locale; number formats derived from what was typed (`0.0%`, `#,##0.00" €"`) are format codes, the same in every locale. Changing `locale` changes no value of a workbook. A number edited again (formula bar, `F2`) shows the locale's decimal separator and no grouping (`1,5`, `1234,5`), which reads back as the same number. +- **Not localized**: formulas (`=1.5+A1`, `=SUM(1,5)`, English function names and the comma between arguments, whatever the locale), dates typed (`2024-01-15`, `15/01/2024` as before), how cells show their values (their number format, with a point and commas), CSV / TSV files (read by their own rules, see [above](#csv-text-markdown-html-and-svg)), text pasted from other programs, and Find & Replace (it works on the text cells hold, numbers with a point). ### Dark mode diff --git a/e2e/app/main.tsx b/e2e/app/main.tsx index be08f97..05b4a8b 100644 --- a/e2e/app/main.tsx +++ b/e2e/app/main.tsx @@ -3,6 +3,7 @@ * ?src=samples/sample.docx&editable=1&allowSave=0&onSave=1&items=1&close=1&collab=ws://…&room=r * comments: &me=Ann&meId=u1 (author), &people=1 (mentions: Ann, Bob Stone, Cid), &comments=0 (hidden), &cmOpen=1 * &icons=1: every icon from a host resolver, as `` + * &locale=de-DE: the tag numbers typed are read in */ import { useState } from 'react' import { createRoot } from 'react-dom/client' @@ -48,6 +49,7 @@ const initial: DocViewerProps = { captureSelectAll: flag('captureSelectAll'), theme: (q.get('theme') as DocViewerProps['theme']) ?? undefined, injectStyles: flag('injectStyles'), + locale: q.get('locale') ?? undefined, onSave: q.has('onSave') ? async (blob, name) => void log({ type: 'save', name, b64: await b64(blob) }) : undefined, onDirtyChange: (dirty) => log({ type: 'dirty', dirty }), onRename: (name) => log({ type: 'rename', name }), diff --git a/e2e/docx-page.spec.ts b/e2e/docx-page.spec.ts index c93a282..e13fba4 100644 --- a/e2e/docx-page.spec.ts +++ b/e2e/docx-page.spec.ts @@ -74,4 +74,27 @@ describe('docx page setup', () => { await v.page.keyboard.press('Escape') expect(await dlg.count()).toBe(0) }) + + test('margins typed in the locale of the viewer (de-DE: 2,5 cm); one that is not a number is refused, never a prefix (#17)', async () => { + const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true, locale: 'de-DE' }) + await v.page.locator('.de-ebar').waitFor() + const before = (await metaOf((await v.save()).bytes)).page + await v.btn('Page setup').click() + const dlg = v.page.locator('form[aria-label="Page setup"]') + const left = dlg.locator('input[aria-label="Left margin (cm)"]') + expect(await left.inputValue()).toBe(String(+(before.ml / (72 / 2.54)).toFixed(2)).replace('.', ',')) + const apply = dlg.getByRole('button', { name: 'Apply' }) + for (const bad of ['2.5', '2,5cm', '']) { + await left.fill(bad) + expect([bad, await apply.isDisabled()]).toEqual([bad, true]) + } + await left.fill('2,5') + expect(await apply.isDisabled()).toBe(false) + await apply.click() + await v.page.waitForTimeout(600) + const after = (await metaOf((await v.save()).bytes)).page + expect(after.ml).toBeCloseTo(2.5 * (72 / 2.54), 1) + expect(after.mr).toBeCloseTo(before.mr, 1) + expect(v.errors).toEqual([]) + }) }) diff --git a/e2e/embed.spec.ts b/e2e/embed.spec.ts index d7d38f3..6538339 100644 --- a/e2e/embed.spec.ts +++ b/e2e/embed.spec.ts @@ -51,4 +51,33 @@ describe('embedding without React', () => { await v.page.evaluate(() => (window as any).__mounted.destroy()) expect(await host.innerHTML()).toBe('') }) + + test(': numbers typed are read in it; the attribute is live (#17)', async () => { + const v = await viewer({}, { page: 'embed.html' }) + const wc = v.page.locator('#wc') + await wc.locator('.de-page-inner').first().waitFor() + await v.page.evaluate(() => { + const el = document.getElementById('wc')! + el.setAttribute('locale', 'de-DE') + el.setAttribute('src', 'samples/sample.xlsx') + }) + await wc.locator('.de-grid').waitFor() + await wc.locator('.de-bar button.de-mode', { hasText: 'Edit' }).click() + const size = wc.locator('input[aria-label="Font size"]') + const typeSize = async (text: string) => { + await size.click() + await size.fill(text) + await size.press('Enter') + await v.page.waitForTimeout(300) + } + await typeSize('12,5') + expect(await size.inputValue()).toBe('12,5') + await v.page.evaluate(() => document.getElementById('wc')!.removeAttribute('locale')) + await v.page.waitForFunction(() => (document.getElementById('wc')!.shadowRoot!.querySelector('input[aria-label="Font size"]') as HTMLInputElement).value === '12.5') + await typeSize('1,234') + expect(await size.inputValue()).toBe('12.5') + await typeSize('10,5') + expect(await size.inputValue()).toBe('10.5') + expect(v.errors).toEqual([]) + }) }) diff --git a/e2e/harness.ts b/e2e/harness.ts index c2e8ce6..99ccf4f 100644 --- a/e2e/harness.ts +++ b/e2e/harness.ts @@ -56,9 +56,9 @@ export function useBrowser() { export type Params = Record /** Opens the fixture with DocViewer props from `params` and waits for the document. */ -export async function viewer(params: Params, opts: { wait?: boolean; page?: string; viewport?: { width: number; height: number } } = {}) { +export async function viewer(params: Params, opts: { wait?: boolean; page?: string; viewport?: { width: number; height: number }; locale?: string } = {}) { if (!shared) throw new Error('useBrowser() missing') - const ctx = await shared.browser.newContext({ viewport: opts.viewport ?? { width: 1600, height: 1000 }, acceptDownloads: true }) + const ctx = await shared.browser.newContext({ viewport: opts.viewport ?? { width: 1600, height: 1000 }, acceptDownloads: true, locale: opts.locale }) open.add(ctx) const page = await ctx.newPage() const v = new Viewer(page, ctx) diff --git a/e2e/xlsx.spec.ts b/e2e/xlsx.spec.ts index 303f51e..75efdc4 100644 --- a/e2e/xlsx.spec.ts +++ b/e2e/xlsx.spec.ts @@ -1096,3 +1096,99 @@ describe('xlsx dynamic arrays', () => { expect(v.errors).toEqual([]) }) }) + +describe('xlsx numbers typed in a locale (#17)', () => { + const openIn = async (locale?: string, browser?: string) => { + const v = await viewer({ src: 'samples/sample.xlsx', editable: true, onSave: true, ...(locale ? { locale } : {}) }, { locale: browser }) + await v.page.locator('.de-ebar').waitFor() + return v + } + /** type and value of saved cells (column A to Z) */ + const kinds = async (v: Viewer, refs: string[]) => { + const s = await saved(v) + const out: [string, string, string][] = [] + for (const ref of refs) { + const [, col, row] = /^([A-Z])(\d+)$/.exec(ref)! + const d: any = await s.engine.call('xlsx.cell', [0, Number(row) - 1, col.charCodeAt(0) - 65]) + out.push([ref, d?.type, d?.value]) + } + return out + } + const sizeBox = (v: Viewer) => v.page.locator('input[aria-label="Font size"]').first() + const typeSize = async (v: Viewer, text: string) => { + await sizeBox(v).click() + await sizeBox(v).fill(text) + await sizeBox(v).press('Enter') + await v.page.waitForTimeout(300) + } + const stylesXml = async (v: Viewer) => (await unzip(new Blob([(await v.save()).bytes]))).text('xl/styles.xml') + + test('de-DE: 1,5 and 1.234,5 are numbers, 1.5 is text; the formula bar shows 1,5 and an edit of it stays 1.5', async () => { + const v = await openIn('de-DE') + await v.typeCell('J10', '1,5') + await v.typeCell('J11', '1.234,5') + await v.typeCell('J12', '1.5') + await v.typeCell('J13', '=J10*2') + expect(await v.shown('J13')).toBe('3') + expect(await v.formula('J10')).toBe('1,5') + expect(await v.formula('J13')).toBe('=J10*2') + // edited again: what is shown is what is read + await v.clickCell('J10') + await v.page.keyboard.press('F2') + await v.page.keyboard.type('0') + await v.page.keyboard.press('Enter') + await v.page.waitForTimeout(200) + expect(await v.formula('J10')).toBe('1,5') + expect(await v.shown('J13')).toBe('3') + expect(await kinds(v, ['J10', 'J11', 'J12', 'J13'])).toEqual([ + ['J10', 'number', '1.5'], + ['J11', 'number', '1234.5'], + ['J12', 'string', '1.5'], + ['J13', 'number', '3'], + ]) + expect(v.errors).toEqual([]) + }) + + test('without a locale (in a German browser): 1,5 stays text, 1.5 is a number, as before', async () => { + const v = await openIn(undefined, 'de-DE') + await v.typeCell('J10', '1,5') + await v.typeCell('J11', '1.5') + await v.typeCell('J12', '1,234') + expect(await v.formula('J11')).toBe('1.5') + expect(await kinds(v, ['J10', 'J11', 'J12'])).toEqual([ + ['J10', 'string', '1,5'], + ['J11', 'number', '1.5'], + ['J12', 'number', '1234'], + ]) + expect(v.errors).toEqual([]) + }) + + test('the font size box: 12,5 in de-DE; 12,5 and 12.5 without a locale; what is not a size keeps the size it had', async () => { + const de = await openIn('de-DE') + await de.clickCell('J10') + const was = await sizeBox(de).inputValue() + await typeSize(de, '12.5') + expect(await sizeBox(de).inputValue()).toBe(was) + await typeSize(de, '12,5') + expect(await sizeBox(de).inputValue()).toBe('12,5') + expect(await stylesXml(de)).toContain('') + expect(de.errors).toEqual([]) + + const none = await openIn() + await none.clickCell('J10') + expect(await sizeBox(none).inputValue()).toBe(was) + for (const bad of ['12pt', '1.2.5', '1,2,5', '1,234', '']) { + await typeSize(none, bad) + expect([bad, await sizeBox(none).inputValue()]).toEqual([bad, was]) + } + expect(await stylesXml(none)).not.toContain('') + // without a locale the size box alone reads a decimal comma (#17): a size has no grouping + await typeSize(none, '12,5') + expect(await sizeBox(none).inputValue()).toBe('12.5') + expect(await stylesXml(none)).toContain('') + await typeSize(none, '14.5') + expect(await sizeBox(none).inputValue()).toBe('14.5') + expect(await stylesXml(none)).toContain('') + expect(none.errors).toEqual([]) + }) +}) diff --git a/src/collab/xlsx-ops.ts b/src/collab/xlsx-ops.ts index 37535c9..35eee89 100644 --- a/src/collab/xlsx-ops.ts +++ b/src/collab/xlsx-ops.ts @@ -1,6 +1,7 @@ /** XLSX collaboration operations (shared by the main-thread adapter and the worker) + their transforms. */ import { renameSheetInFormula, shiftFormula } from '../core/xlsx/formula' import type { CellInput, ClipCell, FindOptions, FmtPatch, Range, SheetOp } from '../core/xlsx/types' +import { numberSyntax } from '../core/number-input' import type { CommentOp } from './comments' /** sheets are addressed by part path: indexes move when sheets are added / reordered */ @@ -13,7 +14,8 @@ export type PBookOp = | { op: 'duplicate'; path: string } export type XOp = - | { t: 'set'; id: string; sheet: string; cells: CellInput[] } + /** `locale`: the tag numbers were typed in, for every replica to read them alike (left out: a decimal point) */ + | { t: 'set'; id: string; sheet: string; cells: CellInput[]; locale?: string } | { t: 'fmt'; id: string; sheet: string; range: Range; patch: FmtPatch } /** `name`: the sheet's name where the operation was made, for rows / columns inserted or deleted (formulas typed meanwhile elsewhere read it by that name) */ | { t: 'sheet'; id: string; sheet: string; op: SheetOp; name?: string } @@ -211,7 +213,13 @@ const ALL: Range = { r0: 0, c0: 0, r1: Number.MAX_SAFE_INTEGER, c1: Number.MAX_S const multiline = (op: XOp) => op.t === 'set' && op.cells.some((c) => c.input.includes('\n')) /** a cell edit that may give its cell a number format (derived style): a date or a percentage typed into a cell without one */ -const formats = (op: XOp) => op.t === 'set' && op.cells.some((c) => /^\s*[=+@-]|[$€£¥₫₩₹₽₱฿%]|^\s*\d{1,3}(,\d{3})+|^\s*\d{1,4}[-/]\d{1,2}[-/]\d{1,4}/.test(c.input)) +const formats = (op: XOp) => { + if (op.t !== 'set') return false + // in a locale: its percent sign, and a number grouped by its separator (1.234, 1 234, 12,34,567) + const s = op.locale ? numberSyntax(op.locale) : undefined + const local = (input: string) => !!s && (s.percent.some((p) => input.includes(p)) || s.group.some((g) => input.includes(g))) + return op.cells.some((c) => /^\s*[=+@-]|[$€£¥₫₩₹₽₱฿%]|^\s*\d{1,3}(,\d{3})+|^\s*\d{1,4}[-/]\d{1,2}[-/]\d{1,4}/.test(c.input) || local(c.input)) +} export function footprint(op: XOp): { sheet: string; range: Range } | null { switch (op.t) { diff --git a/src/collab/xlsx-worker.ts b/src/collab/xlsx-worker.ts index c803714..2a20764 100644 --- a/src/collab/xlsx-worker.ts +++ b/src/collab/xlsx-worker.ts @@ -93,7 +93,7 @@ export class XlsxCollabWorker { case 'comment': return null case 'set': - return ed.setCells(await this.sheet(op.sheet), op.cells) + return ed.setCells(await this.sheet(op.sheet), op.cells, op.locale ? { locale: op.locale } : {}) case 'fmt': return ed.format(await this.sheet(op.sheet), op.range, op.patch) case 'sheet': diff --git a/src/collab/xlsx.ts b/src/collab/xlsx.ts index 103e195..b413d58 100644 --- a/src/collab/xlsx.ts +++ b/src/collab/xlsx.ts @@ -6,7 +6,8 @@ */ import type { DocumentClient } from '../core/worker/client' import type { Methods } from '../core/worker/protocol' -import type { BookOp, Range, SheetOp, WorkbookMeta } from '../core/xlsx/types' +import type { BookOp, Range, SetOptions, SheetOp, WorkbookMeta } from '../core/xlsx/types' +import { inputLocale } from '../core/number-input' import { onLocal } from './hosts' import type { Adapter, ApplyResult } from './session' import { conflictsX, isStructural, STRUCTURAL, transformX, type PBookOp, type XOp } from './xlsx-ops' @@ -76,8 +77,11 @@ export class XlsxCollab implements Adapter { switch (method) { case 'comments.set': return this.submit({ t: 'comment', id: this.id(), cid: a[0], c: a[1] as CommentOp['c'] }) - case 'xlsx.set': - return this.local({ t: 'set', id: this.id(), sheet: this.path(a[0]), cells: a[1] }) + case 'xlsx.set': { + // (the locale goes with the op: each replica, and a server replaying the log, reads the numbers as typed) + const locale = inputLocale((a[2] as SetOptions | undefined)?.locale) + return this.local({ t: 'set', id: this.id(), sheet: this.path(a[0]), cells: a[1], ...(locale ? { locale } : {}) }) + } case 'xlsx.format': return this.local({ t: 'fmt', id: this.id(), sheet: this.path(a[0]), range: a[1], patch: a[2] }) case 'xlsx.sheetOp': { diff --git a/src/core/number-input.ts b/src/core/number-input.ts new file mode 100644 index 0000000..6f84585 --- /dev/null +++ b/src/core/number-input.ts @@ -0,0 +1,210 @@ +/** + * Numbers typed by a person, read in a locale: into a cell of a sheet, the font size, a margin. The separators, the + * minus and percent signs and the digits are the locale's, as `Intl.NumberFormat(locale).formatToParts` gives them; + * without a locale (or with a tag that is not one) a number has a decimal point and commas grouping by thousands, and + * nothing else is read. The whole text is one number or none: a prefix is never read ("12,5" in English is not 12), + * and a separator that is neither the locale's decimal one nor a grouping in its place makes it none ("1.5" in German, + * "1,5" in English). What is read is a number, the same in every locale: the file never holds a separator. + * + * Grouping: the locale's own character, between groups of the size it writes (3 digits; 3 then 2 in India: + * 12,34,567), the same character throughout the number; a locale grouping with a space reads U+0020, U+00A0, U+202F + * and U+2009 alike, one grouping with an apostrophe both ' and ’ (Swiss German). Digits: ASCII ones in every locale, + * and the locale's own when it writes others (Arabic-Indic, Devanagari…), one kind or the other in a number. + */ + +/** the currency signs a typed amount may carry, before or after it */ +export const MONEY = '$€£¥₫₩₹₽₱฿' + +export interface NumberSyntax { + /** canonical BCP 47 tag; undefined: no locale */ + locale?: string + decimal: string + /** the characters read as grouping */ + group: string[] + /** digits in the group next to the decimal separator, and in the ones before it */ + primary: number + secondary: number + /** the minus signs read: '-', and the locale's own (U+2212 in Swedish) */ + minus: string[] + /** the percent signs read: '%', and the locale's own (U+066A in Arabic) */ + percent: string[] + /** a space may stand before the percent sign: the locale writes one (50 % in German) */ + percentSpace: boolean + /** the locale's digits zero to nine, when they are not ASCII ones */ + digits?: string[] +} + +const SPACES = [' ', '\u00a0', '\u202f', '\u2009'] +const APOSTROPHES = ["'", '\u2019'] +/** the direction marks Intl writes around signs (Arabic, Persian, Hebrew): not typed as part of a number */ +const MARKS = /[\u061c\u200e\u200f]/g + +const NONE: NumberSyntax = { decimal: '.', group: [','], primary: 3, secondary: 3, minus: ['-'], percent: ['%'], percentSpace: false } + +/** + * The canonical form of a BCP 47 tag; undefined for none, for what is not one (`de_DE`) and for a locale Intl has no + * data for (it would fall back to the browser's own: never what numbers are read in). + */ +export function inputLocale(tag: string | null | undefined): string | undefined { + if (!tag) return undefined + try { + const canon = Intl.getCanonicalLocales(tag)[0] + return canon && Intl.NumberFormat.supportedLocalesOf([canon]).length ? canon : undefined + } catch { + return undefined + } +} + +const syntaxes = new Map() + +/** the separators, signs and digits numbers are read with in `locale` */ +export function numberSyntax(locale?: string | null): NumberSyntax { + const tag = inputLocale(locale) + if (!tag) return NONE + let s = syntaxes.get(tag) + if (!s) syntaxes.set(tag, (s = syntaxOf(tag))) + return s +} + +function syntaxOf(tag: string): NumberSyntax { + const unmarked = (s: string | undefined) => s?.replace(MARKS, '') ?? '' + const parts = new Intl.NumberFormat(tag).formatToParts(-1234567.5) + const part = (type: string) => unmarked(parts.find((p) => p.type === type)?.value) + const decimal = part('decimal') || '.' + const g = part('group') + const ints = parts.filter((p) => p.type === 'integer').map((p) => p.value) + const primary = ints.length > 1 ? ints[ints.length - 1].length : 3 + const secondary = ints.length > 2 ? ints[ints.length - 2].length : primary + const group = !g ? [] : SPACES.includes(g) ? SPACES : APOSTROPHES.includes(g) ? APOSTROPHES : [g] + const pct = new Intl.NumberFormat(tag, { style: 'percent' }).formatToParts(0.5) + const at = pct.findIndex((p) => p.type === 'percentSign') + const percent = unmarked(pct[at]?.value) || '%' + const before = pct[at - 1] + const minus = part('minusSign') || '-' + const digits = [...unmarked(new Intl.NumberFormat(tag, { useGrouping: false }).format(9876543210))].reverse() + return { + locale: tag, + decimal, + group: group.filter((c) => c !== decimal), + primary, + secondary, + minus: minus === '-' ? ['-'] : ['-', minus], + percent: percent === '%' ? ['%'] : ['%', percent], + percentSpace: before?.type === 'literal' && /^\s$/.test(unmarked(before.value)), + digits: digits.length === 10 && digits.join('') !== '0123456789' ? digits : undefined, + } +} + +const esc = (s: string) => s.replace(/[\\^$.*+?()[\]{}|/-]/g, '\\$&') + +interface Grammar { + plain: RegExp + percent: RegExp + amount: RegExp +} + +const grammars = new WeakMap() + +/** + * The forms a number is typed in (with ASCII digits, '-' and '%' by then), as a cell reads them: a number with an + * exponent but no grouping (-1.5, .5, 5., 1.5e3); a percentage (12.5%); an amount, grouped or with a currency sign + * before or after it (1,234.50, $50, -$3.75, 50 ₫). The locale's decimal and grouping separators in place of the + * point and the comma. + */ +function grammarOf(s: NumberSyntax): Grammar { + let g = grammars.get(s) + if (g) return g + const D = esc(s.decimal) + const num = `(?:\\d+${D}?\\d*|${D}\\d+)` + const G = `[${s.group.map(esc).join('')}]` + const grouped = s.group.length ? `\\d{1,${s.secondary}}(?:${G}\\d{${s.secondary}})*${G}\\d{${s.primary}}|` : '' + g = { + plain: new RegExp(`^[-+]?${num}(?:e[-+]?\\d+)?$`, 'i'), + percent: new RegExp(`^[-+]?${num}${s.percentSpace ? '\\s?' : ''}%$`), + amount: new RegExp(`^([-+]?)\\s*([${MONEY}]?)\\s*(${grouped}\\d+)(${D}\\d+)?\\s*([${MONEY}]?)$`), + } + grammars.set(s, g) + return g +} + +/** `text` with the locale's digits, minus and percent signs as ASCII ones and its direction marks dropped; null when it mixes two kinds of digits */ +function ascii(text: string, s: NumberSyntax): string | null { + if (!s.locale) return text + let t = text.replace(MARKS, '') + for (const m of s.minus) if (m !== '-') t = t.split(m).join('-') + for (const p of s.percent) if (p !== '%') t = t.split(p).join('%') + const own = s.digits + if (own && own.some((d) => t.includes(d))) { + if (/\d/.test(t)) return null + t = [...t].map((ch) => { + const i = own.indexOf(ch) + return i < 0 ? ch : String(i) + }).join('') + } + return t +} + +export interface TypedNumber { + /** the number (a percentage as typed: 50 for 50%) */ + value: number + kind: 'plain' | 'percent' | 'amount' + /** the number as JavaScript writes it: ASCII digits, a decimal point, no grouping ('-1234.5', '1.5e3') */ + canon: string + /** digits typed after the decimal separator */ + decimals: number + grouped: boolean + /** the currency sign typed, and whether it came after the number */ + currency?: string + after?: boolean +} + +/** + * What a cell reads `text` as when it is a number typed in `locale` (the forms of `grammarOf`); null when the whole + * of it is not one. A number too large to be one (1e999) is none. + */ +export function readTyped(text: string, locale?: string | null): TypedNumber | null { + const s = numberSyntax(locale) + const t = ascii(text.trim(), s) + if (!t) return null + const g = grammarOf(s) + const canon = (x: string) => (s.decimal === '.' ? x : x.replace(s.decimal, '.')) + const decimals = (x: string) => { + const i = x.indexOf(s.decimal) + return i < 0 ? 0 : x.length - i - 1 + } + if (g.plain.test(t)) { + const value = Number(canon(t)) + if (!Number.isFinite(value)) return null + return { value, kind: 'plain', canon: canon(t), decimals: decimals(t.replace(/e.*$/i, '')), grouped: false } + } + if (g.percent.test(t)) { + const body = t.slice(0, -1).trimEnd() + const value = Number(canon(body)) + if (!Number.isFinite(value)) return null + return { value, kind: 'percent', canon: canon(body), decimals: decimals(body), grouped: false } + } + const m = g.amount.exec(t) + if (!m || (m[2] && m[5])) return null + const grouped = /\D/.test(m[3]) + // (a plain number without a currency was read before; grouped by one character throughout, not "1 234.567") + if ((!m[2] && !m[5] && !grouped) || new Set(m[3].replace(/\d/g, '')).size > 1) return null + const c = (m[1] === '-' ? '-' : '') + m[3].replace(/\D/g, '') + (m[4] ? '.' + m[4].slice(1) : '') + const value = Number(c) + if (!Number.isFinite(value)) return null + return { value, kind: 'amount', canon: c, decimals: m[4] ? m[4].length - 1 : 0, grouped, ...(m[2] || m[5] ? { currency: m[2] || m[5], after: !!m[5] } : {}) } +} + +/** + * The number typed into a field (a size, a margin) in `locale`: the whole text, with a sign, grouped or not, with + * decimals or an exponent. Null when it is not one; a percentage or an amount of money is not. + */ +export function parseNumber(text: string, locale?: string | null): number | null { + const n = readTyped(text, locale) + return n && n.kind !== 'percent' && n.currency === undefined ? n.value : null +} + +/** `n` as it is typed in `locale` and read back the same: its shortest digits (ASCII), the locale's decimal separator, no grouping */ +export function numberText(n: number, locale?: string | null): string { + const s = numberSyntax(locale) + return s.decimal === '.' ? String(n) : String(n).replace('.', s.decimal) +} diff --git a/src/core/worker/engine.ts b/src/core/worker/engine.ts index fc0d0a4..b176711 100644 --- a/src/core/worker/engine.ts +++ b/src/core/worker/engine.ts @@ -10,7 +10,7 @@ import { XlsxWorkbook } from '../xlsx/workbook' import { XlsxEditor } from '../xlsx/editor' import { readSheetDrawings } from '../xlsx/drawings' import { loadDelimited } from '../xlsx/import' -import type { BookOp, CellInput, FindOptions, FmtPatch, Range, SheetOp } from '../xlsx/types' +import type { BookOp, CellInput, FindOptions, FmtPatch, Range, SetOptions, SheetOp } from '../xlsx/types' import type { PParaSpec, ShapeOp, SlideOp } from '../pptx/types' import { addSlideImage, shapeOps, slideOp, undoShapes } from '../pptx/edit' import { ZipArchive } from '../zip' @@ -192,7 +192,7 @@ export class Engine { return } case 'xlsx.set': - return this.xed().setCells(args[0] as number, args[1] as CellInput[]) + return this.xed().setCells(args[0] as number, args[1] as CellInput[], args[2] as SetOptions | undefined) case 'xlsx.copy': return this.xed().copy(args[0] as number, args[1] as Range) case 'xlsx.region': diff --git a/src/core/worker/protocol.ts b/src/core/worker/protocol.ts index f2ba4c9..a4ebc48 100644 --- a/src/core/worker/protocol.ts +++ b/src/core/worker/protocol.ts @@ -6,7 +6,7 @@ import type { XOp } from '../../collab/xlsx-ops' import type { POp } from '../../collab/pptx-ops' import type { PptxCollabResult } from '../../collab/pptx-worker' import type { CanonStyle, DocxMeta, Block, EditOp, EditResult, HFSet, HFSetResult, PageSet, PageSetResult, ParaSpec, StyleInfo, StyleLook, StyleSetResult, TableOp } from '../docx/types' -import type { BlockOut, BookOp, CellDetail, CellInput, FindMatch, FindOptions, FmtPatch, Range, SheetOp, SheetProgress, WorkbookMeta, XlsxClip, XlsxEditResult } from '../xlsx/types' +import type { BlockOut, BookOp, CellDetail, CellInput, FindMatch, FindOptions, FmtPatch, Range, SetOptions, SheetOp, SheetProgress, WorkbookMeta, XlsxClip, XlsxEditResult } from '../xlsx/types' import type { SheetDrawing } from '../xlsx/drawings' import type { PParaSpec, PresentationMeta, ShapeOp, SlideModel, SlideOp } from '../pptx/types' @@ -90,7 +90,8 @@ export interface Methods { 'xlsx.text'(sheet: number, sep: string): Blob /** replaces text in matching cells (or only `at`); null when nothing changed */ 'xlsx.replace'(sheet: number, query: string, by: string, opts?: FindOptions, at?: { r: number; c: number }): XlsxEditResult | null - 'xlsx.set'(sheet: number, cells: CellInput[]): XlsxEditResult + /** what was typed into cells; `opts.locale`: the BCP 47 tag numbers were typed in (`1,5` in `de-DE`), a decimal point without one */ + 'xlsx.set'(sheet: number, cells: CellInput[], opts?: SetOptions): XlsxEditResult /** the block of filled cells a range is part of (the table around it), and whether its first row reads as a header */ 'xlsx.region'(sheet: number, range: Range): { range: Range; header: boolean } /** the cells of a range as they are (values, formulas, formats) for the `paste` sheet operation, and as text for the clipboard; rows not shown yet included */ diff --git a/src/core/xlsx/editor.ts b/src/core/xlsx/editor.ts index 948ad21..194afb6 100644 --- a/src/core/xlsx/editor.ts +++ b/src/core/xlsx/editor.ts @@ -12,8 +12,9 @@ import { } from '../raw' import { decodeEntities, parseXml } from '../xml' import { BUILTIN_FORMATS, isDateFormat } from './numfmt' +import { readTyped, type TypedNumber } from '../number-input' import { parseSheetStyles } from './styles' -import type { BookOp, BorderKind, CellInput, ClipCell, ColInfo, FindOptions, FmtPatch, Merge, Range, RowAttrs, SheetOp, SheetProgress, XlsxClip, XlsxEditResult } from './types' +import type { BookOp, BorderKind, CellInput, ClipCell, ColInfo, FindOptions, FmtPatch, Merge, Range, RowAttrs, SetOptions, SheetOp, SheetProgress, XlsxClip, XlsxEditResult } from './types' import { expandShared, overflows, restore, setColStyle, setColWidth, setFormula, setMerge, setRowHeight, shiftSheet, snapshot, type Snapshot } from './structure' import { dropSheetInFormula, moveRefsInFormula, parseFormula, renameSheetInFormula, translateFormula, withFunctionPrefixes, type Ast, type MoveOp, type RefAddr } from './formula' import { loadDelimited, type DelimitedImport } from './import' @@ -193,27 +194,21 @@ interface InputContext { /** its number format ('' or "General": none) */ fmt: string date1904: boolean + /** the BCP 47 tag numbers are typed in (undefined: a decimal point) */ + locale?: string } const noQuotes = (fmt: string) => fmt.replace(/"[^"]*"|\\.|\[[^\]]*\]/g, '') const ERROR_INPUT = /^#(?:N\/A|DIV\/0!|VALUE!|REF!|NAME\?|NUM!|NULL!)$/i -const MONEY = '$€£¥₫₩₹₽₱฿' -const AMOUNT = new RegExp(`^([-+]?)\\s*([${MONEY}]?)\\s*(\\d{1,3}(?:,\\d{3})+|\\d+)(\\.\\d+)?\\s*([${MONEY}]?)$`) /** - * An amount typed with thousands separators and / or a currency sign ("1,234,567", "$50", "€1,200.50", "50 ₫"): the - * number, and the format that shows it as typed. Not a plain number (read before), not two signs. + * The format that shows an amount as typed ("1,234,567", "$50", "€1,200.50", "50 ₫"): grouped, with the decimals typed + * (a currency shows cents when cents were typed), the currency where it was. A format code, the same in every locale. */ -function amountInput(t: string): { n: number; fmt: string } | undefined { - const m = AMOUNT.exec(t) - if (!m || (m[2] && m[5]) || (!m[2] && !m[5] && !m[3].includes(','))) return undefined - const n = Number(m[3].replace(/,/g, '') + (m[4] ?? '')) - if (!Number.isFinite(n)) return undefined - // (a currency shows cents when cents were typed) - const digits = '#,##0' + (m[4] ? '.' + '0'.repeat(m[2] || m[5] ? Math.max(2, m[4].length - 1) : m[4].length - 1) : '') - const fmt = m[2] ? `"${m[2]}"${digits}` : m[5] ? `${digits}" ${m[5]}"` : digits - return { n: m[1] === '-' ? -n : n, fmt } +function amountFormat(n: TypedNumber): string { + const digits = '#,##0' + (n.decimals ? '.' + '0'.repeat(n.currency ? Math.max(2, n.decimals) : n.decimals) : '') + return !n.currency ? digits : n.after ? `${digits}" ${n.currency}"` : `"${n.currency}"${digits}` } /** whether text reads as a formula that reads a cell or calls a function (what makes "+A1+B1" one, and not "-5" or "- item") */ @@ -262,21 +257,16 @@ function parseInput(input: string, style: number, ctx: InputContext = { fmt: '', if (readsOrCalls(f)) return { e: [T_STR, '=' + f, style], f } } if (ERROR_INPUT.test(t)) return { e: [T_ERR, t.toUpperCase(), style] } + // a number in the separators of the locale it is typed in (a number too large to be one, 1e999, stays the text + // typed: the file has no way to say Infinity) + const n = readTyped(t, ctx.locale) // more digits than a number holds (a card number, an id): kept as typed, where a number would end in zeros - if (/^[-+]?\d{16,}$/.test(t)) return { e: [T_STR, input, style] } - // a number too large to be one (1e999) stays the text typed: the file has no way to say Infinity - if (/^[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?$/i.test(t) && Number.isFinite(Number(t))) { - const n = Number(t) - // in a cell that shows percentages, 50 is 50% (as Excel reads it); a number under 1 is the fraction itself - return { e: [T_NUM, Math.abs(n) >= 1 && noQuotes(ctx.fmt).includes('%') ? n / 100 : n, style] } - } - if (/^[-+]?(\d+\.?\d*|\.\d+)%$/.test(t) && Number.isFinite(Number(t.slice(0, -1)))) { - const dec = /\.(\d+)%$/.exec(t)?.[1].length ?? 0 - return { e: [T_NUM, Number(t.slice(0, -1)) / 100, style], want: general ? (dec ? `0.${'0'.repeat(Math.min(dec, 10))}%` : '0%') : undefined } - } + if (n?.kind === 'plain' && /^[-+]?\d{16,}$/.test(n.canon)) return { e: [T_STR, input, style] } + // in a cell that shows percentages, 50 is 50% (as Excel reads it); a number under 1 is the fraction itself + if (n?.kind === 'plain') return { e: [T_NUM, Math.abs(n.value) >= 1 && noQuotes(ctx.fmt).includes('%') ? n.value / 100 : n.value, style] } + if (n?.kind === 'percent') return { e: [T_NUM, n.value / 100, style], want: general ? (n.decimals ? `0.${'0'.repeat(Math.min(n.decimals, 10))}%` : '0%') : undefined } if (/^(true|false)$/i.test(t)) return { e: [T_BOOL, /^true$/i.test(t) ? 1 : 0, style] } - const amount = amountInput(t) - if (amount) return { e: [T_NUM, amount.n, style], want: general ? amount.fmt : undefined } + if (n) return { e: [T_NUM, n.value, style], want: general ? amountFormat(n) : undefined } if (general || isDateFormat(ctx.fmt)) { const date = dateInput(t, ctx.date1904) if (date) return { e: [T_NUM, date.serial, style], want: general ? date.fmt : undefined } @@ -706,7 +696,8 @@ export class XlsxEditor { return [...this.wb.calc.recalc([], all)] } - async setCells(sheet: number, inputs: CellInput[]): Promise { + /** `opts.locale`: the BCP 47 tag the numbers among `inputs` were typed in (undefined: a decimal point; formulas are never read in it) */ + async setCells(sheet: number, inputs: CellInput[], opts: SetOptions = {}): Promise { await this.ready() const d = this.sheet(sheet) if (d.protection) for (const { r, c } of inputs) this.denyLocked(d, { r0: r, c0: c, r1: r, c1: c }) @@ -722,7 +713,7 @@ export class XlsxEditor { const prev = getEntry(d, r, c) // (a cell typed into an empty place takes the format of its row, else of its column) const st = prev?.[2] ?? this.lockStyleAt(d, r, c) - const { e, f, want: typed } = parseInput(input, st, { fmt: xfs[st]?.numFmt ?? '', date1904: this.wb.date1904 }) + const { e, f, want: typed } = parseInput(input, st, { fmt: xfs[st]?.numFmt ?? '', date1904: this.wb.date1904, locale: opts?.locale }) // a formula typed into a cell without a format shows as what it computes: a date, or as the cell it is const want = typed ?? (e && f && !/[^\s]/.test((xfs[st]?.numFmt ?? '').replace(/^general$/i, '')) ? this.formulaFormat(sheet, f) : undefined) if (e && want) e[2] = (ed ??= await this.styles()).derive(st, { numFmt: want }) diff --git a/src/core/xlsx/types.ts b/src/core/xlsx/types.ts index ac813ec..dc84e77 100644 --- a/src/core/xlsx/types.ts +++ b/src/core/xlsx/types.ts @@ -111,6 +111,15 @@ export interface CellInput { input: string } +/** how the inputs of an `xlsx.set` are read */ +export interface SetOptions { + /** + * BCP 47 tag the numbers were typed in: its decimal and grouping separators (`1,5` and `1.234,5` in `de-DE`). + * Undefined: a decimal point and commas grouping by thousands. Formulas are read the same in every locale. + */ + locale?: string +} + export type BorderKind = 'all' | 'outer' | 'inner' | 'none' | 'top' | 'bottom' | 'left' | 'right' export interface FmtPatch { diff --git a/src/embed.ts b/src/embed.ts index 925e128..55f9607 100644 --- a/src/embed.ts +++ b/src/embed.ts @@ -36,12 +36,12 @@ export function mount(el: HTMLElement, options: MountOptions): MountedViewer { * `` * Rendered inside a shadow root so host page CSS cannot leak in. * Attributes: src, name, editable, toolbar / thumbnails / save / download / file-menu / open / capture-select-all ("false" to turn off), - * theme ("light" | "dark" | "auto"); + * theme ("light" | "dark" | "auto"), locale (BCP 47 tag numbers typed are read in: "de-DE" reads 1,5); * real-time collaboration: collab (hub WebSocket URL), room, user (display name), base (snapshot seq `src` was opened at). * Properties: `file` (File/Blob/ArrayBuffer) for local data; `icons` (map or resolver, as DocViewer's `icons`). */ export class OfficeViewerElement extends HTMLElement { - static observedAttributes = ['src', 'name', 'toolbar', 'thumbnails', 'editable', 'save', 'download', 'file-menu', 'open', 'capture-select-all', 'theme', 'collab', 'room', 'user', 'base', 'comments'] + static observedAttributes = ['src', 'name', 'toolbar', 'thumbnails', 'editable', 'save', 'download', 'file-menu', 'open', 'capture-select-all', 'theme', 'collab', 'room', 'user', 'base', 'comments', 'locale'] private viewer?: MountedViewer private _file?: Blob | ArrayBuffer private _icons?: Icons @@ -100,6 +100,7 @@ export class OfficeViewerElement extends HTMLElement { captureSelectAll: this.getAttribute('capture-select-all') !== 'false', theme: THEMES.find((t) => t === this.getAttribute('theme')), icons: this._icons, + locale: this.getAttribute('locale') ?? undefined, collab: this.getAttribute('collab') && this.getAttribute('room') ? { diff --git a/src/react/DocViewer.tsx b/src/react/DocViewer.tsx index 59ca633..7c7c907 100644 --- a/src/react/DocViewer.tsx +++ b/src/react/DocViewer.tsx @@ -26,6 +26,8 @@ import type { CollabOptions } from '../collab' import { CollabBar, PeerOverlay, useCollab } from '../collab/react' import { CommentsContext, CommentsCtl, useCommentsState, type CommentOptions } from './comments/Comments' import { COMMENT_KEYS, CommentsPanel } from './comments/CommentsPanel' +import { LocaleContext } from './common/locale' +import { inputLocale } from '../core/number-input' export interface DocViewerProps { /** @@ -112,6 +114,12 @@ export interface DocViewerProps { * Each is rendered in `span.de-icon`, sized by font-size (1em). */ icons?: Icons + /** + * BCP 47 tag numbers typed into the viewer are read in: a cell of a sheet, the font size, a margin (`1,5` and + * `1.234,5` with `de-DE`). Without it (or with a tag that is not one) a number has a decimal point, whatever the + * browser's language. Saved values and formulas are the same in every locale. + */ + locale?: string } const EXT: Record = { docx: '.docx', xlsx: '.xlsx', pptx: '.pptx' } @@ -163,6 +171,7 @@ function fmtBytes(n: number) { export function DocViewer(props: DocViewerProps) { const { src, name, className, style, toolbar = true, toolbarExtra, zoom, thumbnails, headers, credentials, worker, styleTarget, theme, onLoad, onError } = props + const locale = inputLocale(props.locale) const root = useThemeRoot(theme, style) const { allowEdit = true, allowSave = true, allowDownload = true, fileMenu = true, allowOpen = true, captureSelectAll = true, onSave, onDirtyChange } = props const [editing, setEditing] = useState(!!props.editable) @@ -584,6 +593,7 @@ export function DocViewer(props: DocViewerProps) { else body = return ( +
{toolbar && ( @@ -741,5 +751,6 @@ export function DocViewer(props: DocViewerProps) { )}
+ ) } diff --git a/src/react/common/locale.ts b/src/react/common/locale.ts new file mode 100644 index 0000000..43db3d6 --- /dev/null +++ b/src/react/common/locale.ts @@ -0,0 +1,9 @@ +import { createContext, useContext } from 'react' + +/** + * The BCP 47 tag numbers typed into the views are read in (DocViewer's `locale`, canonical); undefined: a decimal + * point and commas grouping by thousands. The host chooses it: the browser's language does not. + */ +export const LocaleContext = createContext(undefined) + +export const useLocale = () => useContext(LocaleContext) diff --git a/src/react/docx/HeaderFooterDialog.tsx b/src/react/docx/HeaderFooterDialog.tsx index 7653104..2f5bc95 100644 --- a/src/react/docx/HeaderFooterDialog.tsx +++ b/src/react/docx/HeaderFooterDialog.tsx @@ -1,5 +1,7 @@ import { useEffect, useRef, useState } from 'react' import type { Block, DocxMeta, HFKind, HFLine, HFSet } from '../../core/docx/types' +import { numberText, parseNumber } from '../../core/number-input' +import { useLocale } from '../common/locale' const KINDS: { k: HFKind; label: string }[] = [ { k: 'header', label: 'Header' }, @@ -27,8 +29,8 @@ interface Part { rich: boolean } -/** the editable form of a header / footer as converted for display */ -export function partOf(blocks: Block[] | undefined): Part { +/** the editable form of a header / footer as converted for display; its size as typed in `locale` */ +export function partOf(blocks: Block[] | undefined, locale?: string): Part { const paras = (blocks ?? []).filter((b) => b.t === 'p') const rich = (blocks ?? []).some((b) => b.t !== 'p' || b.runs.some((r) => r.t !== 'text' && r.t !== 'field')) const lines = paras.map((p) => (p.t === 'p' ? p.runs.map((r) => (r.t === 'text' ? r.text.replace(/\n/g, ' ') : r.t === 'field' ? `{${r.kind}}` : '')).join('') : '')) @@ -38,20 +40,24 @@ export function partOf(blocks: Block[] | undefined): Part { const first = runs[0] as { s?: { b?: boolean; sz?: number } } | undefined // trailing empty lines carry nothing while (lines.length && !lines[lines.length - 1].trim()) lines.pop() - return { text: lines.join('\n'), align, b: runs.length > 0 && runs.every((r) => (r as { s?: { b?: boolean } }).s?.b), sz: first?.s?.sz ? String(first.s.sz) : '', rich } + return { text: lines.join('\n'), align, b: runs.length > 0 && runs.every((r) => (r as { s?: { b?: boolean } }).s?.b), sz: first?.s?.sz ? numberText(first.s.sz, locale) : '', rich } } -const linesOf = (p: Part): HFLine[] => - p.text.split('\n').length === 1 && !p.text.trim() +/** the lines of a part; its size read in `locale` (one that is not a number from 4 up: the size of the text around, as before) */ +const linesOf = (p: Part, locale?: string): HFLine[] => { + const sz = parseNumber(p.sz, locale) + return p.text.split('\n').length === 1 && !p.text.trim() ? [] - : p.text.split('\n').map((text) => ({ text, align: p.align, ...(p.b ? { b: true } : {}), ...(Number(p.sz) >= 4 ? { sz: Number(p.sz) } : {}) })) + : p.text.split('\n').map((text) => ({ text, align: p.align, ...(p.b ? { b: true } : {}), ...(sz !== null && sz >= 4 ? { sz } : {}) })) +} /** * Headers and footers of the document: text (a line per paragraph), alignment, bold, size, page number / page count, * a different first page. `onOk` gets only the parts that changed. */ export function HeaderFooterDialog({ meta, focus, onOk, onClose }: { meta: DocxMeta; focus?: HFKind; onOk: (set: HFSet) => void; onClose: () => void }) { - const init = useRef(Object.fromEntries(KINDS.map(({ k }) => [k, partOf(meta[k])])) as Record) + const locale = useLocale() + const init = useRef(Object.fromEntries(KINDS.map(({ k }) => [k, partOf(meta[k], locale)])) as Record) const [parts, setParts] = useState(init.current) const [first, setFirst] = useState(!!meta.titlePg) const [active, setActive] = useState(focus && (first || !focus.startsWith('first')) ? focus : 'header') @@ -76,7 +82,7 @@ export function HeaderFooterDialog({ meta, focus, onOk, onClose }: { meta: DocxM for (const { k } of KINDS) { const a = parts[k] const b = init.current[k] - if (a.text !== b.text || a.align !== b.align || a.b !== b.b || a.sz !== b.sz) (set.parts ??= {})[k] = linesOf(a) + if (a.text !== b.text || a.align !== b.align || a.b !== b.b || a.sz !== b.sz) (set.parts ??= {})[k] = linesOf(a, locale) } if (first !== !!meta.titlePg) set.titlePg = first onClose() @@ -134,7 +140,7 @@ export function HeaderFooterDialog({ meta, focus, onOk, onClose }: { meta: DocxM
diff --git a/src/react/docx/PageSetupDialog.tsx b/src/react/docx/PageSetupDialog.tsx index ff2a3cb..0349420 100644 --- a/src/react/docx/PageSetupDialog.tsx +++ b/src/react/docx/PageSetupDialog.tsx @@ -1,5 +1,7 @@ import { useEffect, useRef, useState } from 'react' import type { PageSet, PageSetup } from '../../core/docx/types' +import { numberText, parseNumber } from '../../core/number-input' +import { useLocale } from '../common/locale' /** paper sizes in pt (portrait) */ export const PAPERS: { k: string; label: string; w: number; h: number }[] = [ @@ -36,17 +38,23 @@ const MARGIN_PRESETS: { label: string; cm: [number, number, number, number] }[] * `onOk` gets only what changed. */ export function PageSetupDialog({ page, onOk, onClose }: { page: PageSetup; onOk: (set: PageSet) => void; onClose: () => void }) { + // Numbers are typed in the viewer's locale (2,54 in de-DE) and read whole: one that is not a number (empty, 2,5 where + // the decimal separator is a point) is refused as one out of bounds is. Without a locale the fields are the + // browser's number fields, as they were. + const locale = useLocale() + const text = (cm: number) => numberText(cm, locale) const [paper, setPaper] = useState(paperOf(page)) const [land, setLand] = useState(page.w > page.h) // margins as typed (cm): top, right, bottom, left - const [mar, setMar] = useState([page.mt, page.mr, page.mb, page.ml].map((v) => String(toCm(v)))) + const [mar, setMar] = useState([page.mt, page.mr, page.mb, page.ml].map((v) => text(toCm(v)))) const [cols, setCols] = useState(page.cols ?? 1) - const [gap, setGap] = useState(String(toCm(page.colGap ?? 36))) + const [gap, setGap] = useState(text(toCm(page.colGap ?? 36))) const first = useRef(null) useEffect(() => first.current?.focus(), []) - const nums = mar.map(Number) - const gapN = Number(gap) + const num = (v: string) => parseNumber(v, locale) ?? NaN + const nums = mar.map(num) + const gapN = num(gap) const size = (() => { const p = PAPERS.find((x) => x.k === paper) const lo = p ? p.w : Math.min(page.w, page.h) @@ -80,7 +88,8 @@ export function PageSetupDialog({ page, onOk, onClose }: { page: PageSetup; onOk