From bb11d002c5223c47c6fcdb3538113fd052287573 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Mon, 16 Nov 2026 14:10:16 +0100 Subject: [PATCH 1/6] JSE-18: javascript-excel/format number-format renderer (work in progress) --- .github/workflows/ci.yml | 2 +- packages/javascript-excel/package.json | 10 + .../javascript-excel/scripts/consumer.mjs | 13 + packages/javascript-excel/src/format.ts | 233 +++++++++ .../src/internal/format/date.ts | 179 +++++++ .../src/internal/format/locale.ts | 123 +++++ .../src/internal/format/number.ts | 457 ++++++++++++++++++ .../src/internal/format/parse.ts | 283 +++++++++++ .../javascript-excel/test/entries.test.ts | 5 + .../javascript-excel/test/format/cases.ts | 96 ++++ .../test/format/format.test.ts | 222 +++++++++ .../test/format/libreoffice.test.ts | 107 ++++ packages/javascript-excel/tsdown.config.ts | 1 + 13 files changed, 1730 insertions(+), 1 deletion(-) create mode 100644 packages/javascript-excel/src/format.ts create mode 100644 packages/javascript-excel/src/internal/format/date.ts create mode 100644 packages/javascript-excel/src/internal/format/locale.ts create mode 100644 packages/javascript-excel/src/internal/format/number.ts create mode 100644 packages/javascript-excel/src/internal/format/parse.ts create mode 100644 packages/javascript-excel/test/format/cases.ts create mode 100644 packages/javascript-excel/test/format/format.test.ts create mode 100644 packages/javascript-excel/test/format/libreoffice.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c4646bb..3281788 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,7 +66,7 @@ jobs: env: JSE_REQUIRE_LIBREOFFICE: "1" # One file at a time: headless LibreOffice instances sharing a profile block each other. - run: npm -w packages/javascript-excel exec -- vitest run --no-file-parallelism test/write/libreoffice.test.ts test/read/libreoffice.test.ts test/conformance/libreoffice.test.ts + run: npm -w packages/javascript-excel exec -- vitest run --no-file-parallelism test/write/libreoffice.test.ts test/read/libreoffice.test.ts test/conformance/libreoffice.test.ts test/format/libreoffice.test.ts # The conformance corpus (docs/conformance.md) as a downloadable artifact, # for the manual check in Excel and Numbers. - name: Build the conformance corpus diff --git a/packages/javascript-excel/package.json b/packages/javascript-excel/package.json index 26f4aec..5ff4845 100644 --- a/packages/javascript-excel/package.json +++ b/packages/javascript-excel/package.json @@ -83,6 +83,16 @@ "default": "./dist/worker.cjs" } }, + "./format": { + "import": { + "types": "./dist/format.d.ts", + "default": "./dist/format.js" + }, + "require": { + "types": "./dist/format.d.cts", + "default": "./dist/format.cjs" + } + }, "./package.json": "./package.json" }, "engines": { diff --git a/packages/javascript-excel/scripts/consumer.mjs b/packages/javascript-excel/scripts/consumer.mjs index 8603628..e2f624f 100644 --- a/packages/javascript-excel/scripts/consumer.mjs +++ b/packages/javascript-excel/scripts/consumer.mjs @@ -23,6 +23,7 @@ const expected = { "./csv": { CSV_MIME: "text/csv;charset=utf-8", parseCsv: FUNCTION, readCsv: FUNCTION, toCsv: FUNCTION, toCsvBlob: FUNCTION }, "./dom": { fromTable: FUNCTION, download: FUNCTION, DOWNLOAD_REVOKE_DELAY_MS: 40000 }, "./worker": { exposeWorker: FUNCTION, createWorkerClient: FUNCTION }, + "./format": { formatValue: FUNCTION, formatCell: FUNCTION }, }; // A string only that subpath's code contains, so the tree-shaking check can @@ -32,6 +33,7 @@ export const MARKERS = { "./csv": "CSV_STRAY_QUOTE", "./dom": "[data-export-ignore]", "./worker": "javascript-excel/worker", + "./format": "x-sysdate", }; const missing = SUBPATHS.filter((s) => !(s in expected)); @@ -187,6 +189,16 @@ const asText: Promise = client.toCsv([["a"]]); void bytes; void fromWorker; void asText; void exposeWorker; `; +const FORMAT_FIXTURE = ` +import { formatCell, formatValue, type FormatOptions, type FormattedValue } from ${JSON.stringify(`${pkg.name}/format`)}; +const fopts: FormatOptions = { locale: "de-DE", date1904: undefined, dateZone: "utc", generalWidth: 11, indexedColors: undefined }; +const shown: FormattedValue = formatValue(1234.5, "#,##0.00", fopts); +const fromCell: string = formatCell({ value: 45306, style: { numFmt: 14 } }).text; +const red: string | undefined = formatValue(-1, "0;[Red]-0").color; +const align: "left" | "center" | "right" = shown.align; +void fromCell; void red; void align; +`; + const CSV_FIXTURE = ` import { parseCsv, readCsv, toCsv, toCsvBlob, type CsvParseResult, type CsvWriteOptions } from ${JSON.stringify(`${pkg.name}/csv`)}; const parsed: CsvParseResult = parseCsv("a,b\\r\\n1,2\\r\\n", { delimiter: "auto", inferTypes: true, mode: undefined }); @@ -214,6 +226,7 @@ export function writeTypeFixture(app) { "\n" + MODEL_FIXTURE + CSV_FIXTURE + + FORMAT_FIXTURE + READ_FIXTURE + WORKER_FIXTURE; writeFileSync(join(app, "esm.mts"), typed); diff --git a/packages/javascript-excel/src/format.ts b/packages/javascript-excel/src/format.ts new file mode 100644 index 0000000..1151770 --- /dev/null +++ b/packages/javascript-excel/src/format.ts @@ -0,0 +1,233 @@ +/** + * javascript-excel/format: renders values with Excel number formats + * (docs/api.md §5.6), for viewers, previews and "as displayed" text. + * + * Dates are formatted from Excel serials, so the result does not depend on + * the time zone. Locale data (separators, month and day names, the short + * date) comes from Intl. Nothing here throws for a malformed code: unknown + * characters are shown as literal text. + * + * @module javascript-excel/format + */ + +import { cellText } from "./cells"; +import { dateToSerial } from "./dates"; +import { compile, type Compiled, type Section } from "./internal/format/parse"; +import { localeData, NAMED_COLORS, paletteColor, type LocaleData } from "./internal/format/locale"; +import { formatDate, shortDateSection } from "./internal/format/date"; +import { formatNumber, general } from "./internal/format/number"; +import type { Cell, CellErrorValue, CellInput, NumFmt, RichText } from "./model"; +import { BUILTIN_NUM_FMTS } from "./numfmt"; + +export type { Cell, CellErrorValue, CellInput, NumFmt, RichText } from "./model"; + +/** What `formatValue` accepts: a cell's value. A Date is converted to a serial first (`dateZone`, `date1904`). */ +export type FormatInput = number | string | boolean | Date | CellErrorValue | RichText | null | undefined; + +/** Options for `formatValue` and `formatCell`. */ +export interface FormatOptions { + /** BCP 47 locale for separators, month and day names and locale-dependent built-in formats. Default 'en-US'. */ + locale?: string | undefined; + /** The workbook uses the 1904 date system (`workbook.date1904`). Default false. */ + date1904?: boolean | undefined; + /** How a Date input becomes a serial: its local or its UTC fields. Default 'local', as the writer (§3.4.1). Serial inputs ignore it. */ + dateZone?: "local" | "utc" | undefined; + /** Characters available to the General format before it rounds or switches to scientific notation. Default 11 `[to verify]`. */ + generalWidth?: number | undefined; + /** The workbook's custom indexed palette (`workbook.indexedColors`), for [ColorN] colours. */ + indexedColors?: readonly string[] | undefined; +} + +/** A formatted value. */ +export interface FormattedValue { + /** The text Excel shows, without the repeat characters of a `*x` fill. */ + text: string; + /** Colour from the format section ([Red], [Color10]) as ARGB 'FFRRGGBB'. Overrides the font colour. */ + color?: string | undefined; + /** + * A `*x` fill: repeat `char` at `at` (an index into `text`) until the cell is full. + * Also used with `char: '#'` and `text: ''` for a date Excel cannot show (negative or past 9999-12-31): the cell fills with '#'. + */ + fill?: { char: string; at: number } | undefined; + /** How Excel aligns the value under 'general' horizontal alignment: numbers and dates right, text left, booleans and errors centred. */ + align: "left" | "center" | "right"; +} + +const BUILTIN_EXTRA: Readonly> = { + // Locale-dependent currency and accounting ids, as Excel en-US shows them `[to verify for other locales]`. + 5: '"$"#,##0_);\\("$"#,##0\\)', + 6: '"$"#,##0_);[Red]\\("$"#,##0\\)', + 7: '"$"#,##0.00_);\\("$"#,##0.00\\)', + 8: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)', + 41: '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)', + 42: '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)', + 43: '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)', + 44: '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)', +}; +/** Ids that show the locale's short date: 14, and the East Asian ids 27–36 and 50–58 `[to verify per locale]`. */ +const SHORT_DATE_IDS = new Set([14, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 50, 51, 52, 53, 54, 55, 56, 57, 58]); + +const compiled = new Map(); +const GENERAL: Compiled = compile("General"); + +function compileCached(code: string): Compiled { + let c = compiled.get(code); + if (!c) { + c = compile(code); + if (compiled.size >= 1000) compiled.clear(); + compiled.set(code, c); + } + return c; +} + +/** The compiled format for a NumFmt, or null for the locale short date (with or without time). */ +function resolve(numFmt: NumFmt | undefined, loc: LocaleData): Compiled { + if (numFmt === undefined || numFmt === 0 || numFmt === "General") return GENERAL; + if (typeof numFmt === "number") { + if (SHORT_DATE_IDS.has(numFmt)) return { sections: [shortDateSection(loc, false)] }; + if (numFmt === 22) return { sections: [shortDateSection(loc, true)] }; + const code = BUILTIN_NUM_FMTS[numFmt] ?? BUILTIN_EXTRA[numFmt]; + return code === undefined ? GENERAL : compileCached(code); + } + return compileCached(numFmt); +} + +const holds = (cond: { op: string; v: number }, x: number): boolean => { + switch (cond.op) { + case "<": + return x < cond.v; + case "<=": + return x <= cond.v; + case ">": + return x > cond.v; + case ">=": + return x >= cond.v; + case "=": + return x === cond.v; + default: + return x !== cond.v; + } +}; + +/** + * Picks the section for a number and whether its minus sign is shown. + * Without conditions: one section for all; two: non-negative, negative (shown without its sign); + * three: positive, negative, zero. With a condition on the first or second section, the first + * section whose condition holds wins, and the next section without a condition takes the rest. + * A conditional section that only admits negative numbers ([<0], [<=-1]) drops the sign, like the + * implicit negative section; other conditional sections keep it `[to verify against Excel]`. + */ +function pick(sections: Section[], v: number): { sec: Section | undefined; signed: boolean } { + const n = Math.min(sections.length, 3); + const [a, b, c] = sections; + const signed = (s: Section | undefined): boolean => !(s?.cond && (s.cond.op === "<" ? s.cond.v <= 0 : s.cond.op === "<=" ? s.cond.v < 0 : false)); + if (a?.cond || (n >= 2 && b?.cond)) { + if (!a?.cond || holds(a.cond, v)) return { sec: a, signed: signed(a) }; + if (n < 2) return { sec: undefined, signed: true }; + if (!b!.cond || holds(b!.cond, v)) return { sec: b, signed: signed(b) }; + return { sec: n >= 3 ? c : undefined, signed: true }; + } + if (n >= 3 && v === 0) return { sec: c, signed: false }; + if (n >= 2 && v < 0) return { sec: b, signed: false }; + return { sec: a, signed: true }; +} + +function colorOf(sec: Section | undefined, opts: FormatOptions | undefined): string | undefined { + const c = sec?.color; + if (!c) return undefined; + return "name" in c ? NAMED_COLORS[c.name] : paletteColor(c.index, opts?.indexedColors); +} + +function done(text: string, align: FormattedValue["align"], sec?: Section, opts?: FormatOptions, fill?: { char: string; at: number }): FormattedValue { + const out: FormattedValue = { text, align }; + const color = colorOf(sec, opts); + if (color) out.color = color; + if (fill) out.fill = fill; + return out; +} + +function formatNumberValue(v: number, fmt: Compiled, loc: LocaleData, opts: FormatOptions | undefined): FormattedValue { + const width = opts?.generalWidth ?? 11; + if (!Number.isFinite(v)) return done("#NUM!", "center"); + const { sec, signed } = pick(fmt.sections, v); + if (!sec) return done(general(v, loc, width), "right"); + const minus = signed && v < 0 ? "-" : ""; + const abs = Math.abs(v); + switch (sec.kind) { + case "date": { + const r = formatDate(sec, signed ? v : abs, opts?.date1904 === true, loc); + if (r === null) return done("", "right", undefined, undefined, { char: "#", at: 0 }); + return done(r.text, "right", sec, opts, r.fill); + } + case "general": + case "number": { + const r = formatNumber(sec, abs, loc, width); + // A minus sign only when something non-zero is shown (Excel shows 0.00, not -0.00, for -0.001) `[to verify]`. + const showMinus = minus && /[1-9]/.test(r.text); + const text = showMinus ? `-${r.text}` : r.text; + return done(text, "right", sec, opts, r.fill ? { char: r.fill.char, at: r.fill.at + (showMinus ? 1 : 0) } : undefined); + } + case "text": + // A text-only format such as "@" shows numbers as General. + return done(general(v, loc, width), "right", sec, opts); + default: { + const r = formatNumber(sec, abs, loc, width); + return done(minus + r.text, "right", sec, opts, r.fill ? { char: r.fill.char, at: r.fill.at + minus.length } : undefined); + } + } +} + +function formatText(s: string, fmt: Compiled, opts: FormatOptions | undefined, loc: LocaleData): FormattedValue { + const sections = fmt.sections; + const sec = sections.length === 4 ? sections[3] : sections.find((x) => x.kind === "text"); + if (!sec) return done(s, "left"); + let text = ""; + let fill: { char: string; at: number } | undefined; + for (const t of sec.toks) { + if (t.t === "text") text += s; + else if (t.t === "lit") text += t.s; + else if (t.t === "space") text += " "; + else if (t.t === "fill") fill ??= { char: t.c, at: text.length }; + else if (t.t === "point") text += loc.decimal; + else if (t.t === "digit") text += t.c; + } + return done(text, "left", sec, opts, fill); +} + +/** + * Formats a value with a number format, as Excel shows it in a cell. + * + * `numFmt` is a built-in id or a format code (§3.5.5); undefined is General. + * Numbers are serials for date formats. A Date is converted with + * `dateToSerial` (`dateZone`, `date1904`). Text uses the format's text + * section; booleans show TRUE/FALSE and errors as written, whatever the format. + */ +export function formatValue(value: FormatInput, numFmt?: NumFmt, options?: FormatOptions): FormattedValue { + const loc = localeData(options?.locale); + if (value === null || value === undefined) return { text: "", align: "left" }; + if (typeof value === "boolean") return { text: value ? "TRUE" : "FALSE", align: "center" }; + if (value instanceof Date) { + let serial: number; + try { + serial = dateToSerial(value, { date1904: options?.date1904, dateZone: options?.dateZone }); + } catch { + return { text: "", align: "right", fill: { char: "#", at: 0 } }; + } + return formatNumberValue(serial, resolve(numFmt, loc), loc, options); + } + if (typeof value === "number") return formatNumberValue(value === 0 ? 0 : value, resolve(numFmt, loc), loc, options); + if (typeof value === "string") return formatText(value, resolve(numFmt, loc), options, loc); + if ("error" in value) return { text: value.error, align: "center" }; + return formatText(cellText(value), resolve(numFmt, loc), options, loc); +} + +/** + * Formats a cell (§3.4) with its own number format (`cell.style.numFmt`). + * A formula cell shows its cached value; without one the text is empty. + */ +export function formatCell(cell: CellInput, options?: FormatOptions): FormattedValue { + if (cell === null || cell === undefined) return { text: "", align: "left" }; + if (typeof cell !== "object" || cell instanceof Date || "error" in cell || "richText" in cell) return formatValue(cell as FormatInput, undefined, options); + const c = cell as Cell; + return formatValue(c.value as FormatInput, c.style?.numFmt, options); +} diff --git a/packages/javascript-excel/src/internal/format/date.ts b/packages/javascript-excel/src/internal/format/date.ts new file mode 100644 index 0000000..865c25d --- /dev/null +++ b/packages/javascript-excel/src/internal/format/date.ts @@ -0,0 +1,179 @@ +/** + * Date and time rendering from Excel serials (docs/api.md §5.6). Pure + * arithmetic on the serial: no Date in the local zone is ever built, so the + * output does not depend on the machine's time zone. + */ + +import { compile, type Section } from "./parse"; +import { lcidLocale, localeData, type LocaleData } from "./locale"; + +const DAY = 86_400; +/** Largest serial Excel shows as a date: 9999-12-31 in the 1900 system. */ +const MAX_1900 = 2_958_465; +const MAX_1904 = MAX_1900 - 1462; + +interface Parts { + y: number; + mo: number; // 1..12 + d: number; // 0..31 (0 only for Excel's 1900-01-00) + wd: number; // 0 = Sunday + H: number; + M: number; + S: number; + sub: number; // sub-second units at `digits` precision + // Elapsed totals + totalH: number; + totalM: number; + totalS: number; +} + +function parts(serial: number, date1904: boolean, digits: number): Parts { + const unit = 10 ** digits; + // Round the whole value to the displayed precision first, as Excel does: 0.99999999 days shows as the next day 00:00. + const units = Math.round(serial * DAY * unit); + const totalS = Math.floor(units / unit); + const sub = units - totalS * unit; + const days = Math.floor(totalS / DAY); + const secs = totalS - days * DAY; + let y: number; + let mo: number; + let d: number; + if (!date1904 && days === 60) [y, mo, d] = [1900, 2, 29]; + else if (!date1904 && days === 0) [y, mo, d] = [1900, 1, 0]; + else { + const base = date1904 ? Date.UTC(1904, 0, 1) : days < 60 ? Date.UTC(1899, 11, 31) : Date.UTC(1899, 11, 30); + const t = new Date(base + days * DAY * 1000); + [y, mo, d] = [t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate()]; + } + // Weekdays follow Excel, where serial 1 (1900-01-01) is a Sunday; from 1900-03-01 on they match the calendar. + const wd = date1904 ? (((days + 5) % 7) + 7) % 7 : (((days + 6) % 7) + 7) % 7; + return { + y, mo, d, wd, + H: Math.floor(secs / 3600), + M: Math.floor((secs % 3600) / 60), + S: secs % 60, + sub, + totalH: Math.floor(totalS / 3600), + totalM: Math.floor(totalS / 60), + totalS, + }; +} + +const two = (n: number): string => String(n).padStart(2, "0"); + +export interface DateOut { + text: string; + fill?: { char: string; at: number } | undefined; +} + +/** Formats a serial with a date section. Returns null when Excel would show a cell full of '#'. */ +export function formatDate(sec: Section, serial: number, date1904: boolean, loc: LocaleData): DateOut | null { + const hasElapsed = sec.toks.some((t) => t.t === "elapsed"); + if (!Number.isFinite(serial) || (serial < 0 && !hasElapsed) || serial > (date1904 ? MAX_1904 : MAX_1900) + 1) return null; + if (sec.system) return { text: systemFormat(sec.system, serial, date1904, loc) }; + const names = sec.lcid !== undefined ? localeData(lcidLocale(sec.lcid) ?? loc.tag) : loc; + const digits = sec.toks.reduce((m, t) => (t.t === "subsec" ? Math.max(m, t.n) : m), 0); + const neg = serial < 0; + const p = parts(Math.abs(serial), date1904, digits); + const ampm = sec.toks.some((t) => t.t === "ampm"); + // With [h], minutes and seconds are within the hour; with [m], seconds within the minute. + const elapsedKind = sec.toks.find((t) => t.t === "elapsed") as { k: "h" | "m" | "s" } | undefined; + let text = neg ? "-" : ""; + let fill: { char: string; at: number } | undefined; + for (const t of sec.toks) { + switch (t.t) { + case "lit": + text += t.s; + break; + case "space": + text += " "; + break; + case "fill": + if (!fill) fill = { char: t.c, at: text.length }; + break; + case "elapsed": { + const v = t.k === "h" ? p.totalH : t.k === "m" ? (elapsedKind?.k === "h" ? p.M : p.totalM) : elapsedKind?.k === "s" ? p.totalS : p.S; + text += String(v).padStart(t.n, "0"); + break; + } + case "minute": { + const m = elapsedKind?.k === "m" ? p.totalM : p.M; + text += t.n >= 2 ? two(m) : String(m); + break; + } + case "subsec": + text += loc.decimal + String(p.sub).padStart(digits, "0").slice(0, t.n); + break; + case "ampm": { + const pm = p.H >= 12; + const lower = t.s[0] === t.s[0]!.toLowerCase(); + const word = t.s.length === 3 ? (pm ? "P" : "A") : pm ? "PM" : "AM"; + text += lower ? word.toLowerCase() : word; + break; + } + case "date": + text += dateToken(t.k, t.n, p, ampm, names); + break; + default: + break; + } + } + return fill ? { text, fill } : { text }; +} + +function dateToken(k: string, n: number, p: Parts, ampm: boolean, loc: LocaleData): string { + switch (k) { + case "y": + case "e": + // 'e' is the era year; for the Gregorian calendar it is the full year `[to verify for East Asian locales]`. + return k === "y" && n <= 2 ? two(p.y % 100) : String(p.y); + case "b": { + // Buddhist era year (Gregorian + 543) `[to verify]`. + const by = p.y + 543; + return n <= 2 ? two(by % 100) : String(by); + } + case "g": + // Era names (Japanese, Taiwanese calendars) are not rendered `[to verify]`. + return ""; + case "m": + if (n === 1) return String(p.mo); + if (n === 2) return two(p.mo); + if (n === 3) return loc.monthsShort[p.mo - 1] ?? ""; + if (n === 5) return (loc.monthsLong[p.mo - 1] ?? "").slice(0, 1); + return loc.monthsLong[p.mo - 1] ?? ""; + case "d": + if (n === 1) return String(p.d); + if (n === 2) return two(p.d); + if (n === 3) return loc.daysShort[p.wd] ?? ""; + return loc.daysLong[p.wd] ?? ""; + case "h": { + const h = ampm ? p.H % 12 || 12 : p.H; + return n >= 2 ? two(h) : String(h); + } + case "s": + return n >= 2 ? two(p.S) : String(p.S); + default: + return ""; + } +} + +const systemCache = new Map(); + +/** Excel's system long date ([$-F800]) and time ([$-F400]), from Intl `[to verify against Windows settings]`. */ +function systemFormat(kind: "longDate" | "time", serial: number, date1904: boolean, loc: LocaleData): string { + const p = parts(serial, date1904, 0); + const t = Date.UTC(p.y, p.mo - 1, Math.max(1, p.d), p.H, p.M, p.S); + const opts: Intl.DateTimeFormatOptions = kind === "longDate" ? { dateStyle: "full", timeZone: "UTC" } : { timeStyle: "medium", timeZone: "UTC" }; + return new Intl.DateTimeFormat(loc.tag, opts).format(t); +} + +/** The locale's numeric short date with a four-digit year, as a compiled section (built-in id 14). */ +export function shortDateSection(loc: LocaleData, withTime: boolean): Section { + const code = loc.shortDate.join("") + (withTime ? " h:mm" : ""); + let sec = systemCache.get(code); + if (!sec) { + sec = compile(code).sections[0]!; + systemCache.set(code, sec); + } + return sec; +} diff --git a/packages/javascript-excel/src/internal/format/locale.ts b/packages/javascript-excel/src/internal/format/locale.ts new file mode 100644 index 0000000..dd0b12f --- /dev/null +++ b/packages/javascript-excel/src/internal/format/locale.ts @@ -0,0 +1,123 @@ +/** + * Locale data for number formats, taken from the platform's Intl API so the + * module ships no locale tables (docs/api.md §5.6). All date work is done on + * UTC dates built from Excel serials, so nothing depends on the time zone. + */ + +export interface LocaleData { + decimal: string; + group: string; + monthsShort: string[]; + monthsLong: string[]; + daysShort: string[]; // Sunday first + daysLong: string[]; + /** Order and separators of a numeric short date, e.g. ["m", "/", "d", "/", "yyyy"] for en-US. */ + shortDate: string[]; + tag: string; +} + +const cache = new Map(); + +function supported(tag: string): string { + try { + return Intl.getCanonicalLocales(tag)[0] ?? "en-US"; + } catch { + return "en-US"; + } +} + +export function localeData(requested: string | undefined): LocaleData { + const tag = supported(requested ?? "en-US"); + let data = cache.get(tag); + if (!data) { + data = build(tag); + if (cache.size > 50) cache.clear(); + cache.set(tag, data); + } + return data; +} + +function build(tag: string): LocaleData { + const parts = new Intl.NumberFormat(tag, { useGrouping: true, minimumFractionDigits: 1 }).formatToParts(1234567.5); + const decimal = parts.find((p) => p.type === "decimal")?.value ?? "."; + const group = parts.find((p) => p.type === "group")?.value ?? ","; + const names = (opts: Intl.DateTimeFormatOptions, n: number, at: (i: number) => number): string[] => { + const f = new Intl.DateTimeFormat(tag, { ...opts, timeZone: "UTC" }); + return Array.from({ length: n }, (_, i) => f.format(at(i))); + }; + const month = (i: number): number => Date.UTC(2021, i, 15); + const day = (i: number): number => Date.UTC(2021, 0, 3 + i); // 2021-01-03 was a Sunday + const shortDate: string[] = []; + for (const p of new Intl.DateTimeFormat(tag, { year: "numeric", month: "numeric", day: "numeric", timeZone: "UTC" }).formatToParts(Date.UTC(2021, 10, 25))) { + if (p.type === "year") shortDate.push("yyyy"); + else if (p.type === "month") shortDate.push("m"); + else if (p.type === "day") shortDate.push("d"); + else if (p.type === "literal") shortDate.push(`"${p.value.replace(/"/g, "")}"`); + } + // Zero padding of day and month follows the locale's short date style (en-US 1/5/21, de-DE 05.01.21); + // the year is always shown with four digits, as Windows short dates usually are `[to verify per locale]`. + const short = new Intl.DateTimeFormat(tag, { dateStyle: "short", timeZone: "UTC" }).formatToParts(Date.UTC(2021, 0, 5)); + if (short.find((p) => p.type === "day")?.value === "05") for (let i = 0; i < shortDate.length; i++) if (shortDate[i] === "d") shortDate[i] = "dd"; + if (short.find((p) => p.type === "month")?.value === "01") for (let i = 0; i < shortDate.length; i++) if (shortDate[i] === "m") shortDate[i] = "mm"; + return { + tag, + decimal, + group, + monthsShort: names({ month: "short" }, 12, month), + monthsLong: names({ month: "long" }, 12, month), + daysShort: names({ weekday: "short" }, 7, day), + daysLong: names({ weekday: "long" }, 7, day), + shortDate, + }; +} + +/** + * Windows locale ids (LCIDs) seen in [$-xxxx] tags, mapped to BCP 47 tags. + * Only the common ones; an unknown id falls back to the caller's locale. + * Source: [MS-LCID] `[to verify for each entry used in real files]`. + */ +const LCIDS: ReadonlyMap = new Map([ + [0x0401, "ar-SA"], [0x0404, "zh-TW"], [0x0405, "cs-CZ"], [0x0406, "da-DK"], [0x0407, "de-DE"], + [0x0408, "el-GR"], [0x0409, "en-US"], [0x040a, "es-ES"], [0x040b, "fi-FI"], [0x040c, "fr-FR"], + [0x040d, "he-IL"], [0x040e, "hu-HU"], [0x0410, "it-IT"], [0x0411, "ja-JP"], [0x0412, "ko-KR"], + [0x0413, "nl-NL"], [0x0414, "nb-NO"], [0x0415, "pl-PL"], [0x0416, "pt-BR"], [0x0419, "ru-RU"], + [0x041d, "sv-SE"], [0x041e, "th-TH"], [0x041f, "tr-TR"], [0x0421, "id-ID"], [0x0422, "uk-UA"], + [0x042a, "vi-VN"], [0x0439, "hi-IN"], [0x0804, "zh-CN"], [0x0807, "de-CH"], [0x0809, "en-GB"], + [0x080a, "es-MX"], [0x0816, "pt-PT"], [0x0c07, "de-AT"], [0x0c09, "en-AU"], [0x0c0a, "es-ES"], + [0x0c0c, "fr-CA"], [0x1009, "en-CA"], [0x100c, "fr-CH"], [0x1409, "en-NZ"], [0x1809, "en-IE"], + [0x4009, "en-IN"], +]); + +export function lcidLocale(id: number): string | undefined { + return LCIDS.get(id); +} + +/** The eight colour names of format codes, as ARGB. */ +export const NAMED_COLORS: Readonly> = { + black: "FF000000", + blue: "FF0000FF", + cyan: "FF00FFFF", + green: "FF00FF00", + magenta: "FFFF00FF", + red: "FFFF0000", + white: "FFFFFFFF", + yellow: "FFFFFF00", +}; + +/** + * The default indexed palette, entries 8–63 (ECMA-376 §18.8.27), as RGB. + * [ColorN] is entry N + 7. `[to verify: conformance.md, 12-colours]` + */ +const PALETTE = ( + "000000 FFFFFF FF0000 00FF00 0000FF FFFF00 FF00FF 00FFFF 800000 008000 000080 808000 800080 008080 C0C0C0 808080 " + + "9999FF 993366 FFFFCC CCFFFF 660066 FF8080 0066CC CCCCFF 000080 FF00FF FFFF00 00FFFF 800080 800000 008080 0000FF " + + "00CCFF CCFFFF CCFFCC FFFF99 99CCFF FF99CC CC99FF FFCC99 3366FF 33CCCC 99CC00 FFCC00 FF9900 FF6600 666699 969696 " + + "003366 339966 003300 333300 993300 993366 333399 333333" +).split(" "); + +/** ARGB of [ColorN], from the workbook's palette when given (64 entries, ARGB), else the default. */ +export function paletteColor(n: number, indexedColors: readonly string[] | undefined): string { + const custom = indexedColors?.[n + 7]; + if (custom && /^[0-9a-f]{8}$/i.test(custom)) return custom.toUpperCase(); + return `FF${PALETTE[n - 1] ?? "000000"}`; +} diff --git a/packages/javascript-excel/src/internal/format/number.ts b/packages/javascript-excel/src/internal/format/number.ts new file mode 100644 index 0000000..9d525e6 --- /dev/null +++ b/packages/javascript-excel/src/internal/format/number.ts @@ -0,0 +1,457 @@ +/** + * Number rendering for format sections: plain, percent, scaled, grouped, + * scientific, fractions and General (docs/api.md §5.6). + * + * Arithmetic is done on decimal strings taken from `toPrecision(15)`, the + * precision Excel keeps, so 1.005 rounds to 1.01 as Excel shows it rather + * than to 1.00 as binary floating point would. + */ + +import type { LocaleData } from "./locale"; +import type { Section, Tok } from "./parse"; + +/** A non-negative decimal: value = 0.digits × 10^point (digits has no leading zeros; "" is zero). */ +interface Dec { + digits: string; + point: number; +} + +export function decimalOf(v: number): Dec { + if (v === 0) return { digits: "", point: 0 }; + const [mant, e] = Math.abs(v).toPrecision(15).split("e") as [string, string | undefined]; + const [ip, fp = ""] = mant.split(".") as [string, string | undefined]; + let digits = ip + fp; + let point = ip.length + (e ? Number(e) : 0); + let i = 0; + while (i < digits.length - 1 && digits[i] === "0") { + i++; + point--; + } + digits = digits.slice(i).replace(/0+$/, ""); + return digits === "" ? { digits: "", point: 0 } : { digits, point }; +} + +const shift = (d: Dec, k: number): Dec => (d.digits === "" ? d : { digits: d.digits, point: d.point + k }); + +/** Rounds half away from zero to `decimals` places: integer digits ("" for zero) and exactly `decimals` fraction digits. */ +export function roundDec(d: Dec, decimals: number): { int: string; frac: string } { + const keep = d.point + decimals; + if (d.digits === "" || keep < 0) return { int: "", frac: "0".repeat(decimals) }; + let kept = d.digits.slice(0, keep).padEnd(keep, "0"); + const next = d.digits[keep]; + if (next !== undefined && next >= "5") kept = increment(kept); + const full = kept.padStart(decimals, "0"); + const int = full.slice(0, full.length - decimals).replace(/^0+/, ""); + return { int, frac: decimals > 0 ? full.slice(full.length - decimals) : "" }; +} + +function increment(s: string): string { + const a = s.split(""); + let i = a.length - 1; + while (i >= 0) { + if (a[i] === "9") { + a[i] = "0"; + i--; + } else { + a[i] = String(Number(a[i]) + 1); + return a.join(""); + } + } + return `1${a.join("")}`; +} + +export interface NumberOut { + text: string; + fill?: { char: string; at: number } | undefined; +} + +/** Collects the output, tracking a `*x` fill position. */ +class Out { + text = ""; + fill: { char: string; at: number } | undefined; + push(s: string): void { + this.text += s; + } + tok(t: Tok, text?: string): boolean { + switch (t.t) { + case "lit": + this.text += t.s; + return true; + case "space": + this.text += " "; + return true; + case "fill": + if (!this.fill) this.fill = { char: t.c, at: this.text.length }; + return true; + case "text": + this.text += text ?? ""; + return true; + default: + return false; + } + } + result(): NumberOut { + return this.fill ? { text: this.text, fill: this.fill } : { text: this.text }; + } +} + +/** Formats a non-negative value with a number section (the caller adds any minus sign). */ +export function formatNumber(sec: Section, v: number, loc: LocaleData, generalWidth: number): NumberOut { + const toks = sec.toks; + const expAt = toks.findIndex((t) => t.t === "exp"); + if (expAt !== -1) return scientific(toks, expAt, v, loc); + const slashAt = fractionSlash(toks); + if (slashAt !== -1) return fraction(toks, slashAt, v, loc); + return plain(toks, v, loc, generalWidth); +} + +/** Index of a slash with digit placeholders before it and placeholders or digits after it, else -1. */ +function fractionSlash(toks: Tok[]): number { + for (let i = 0; i < toks.length; i++) { + if (toks[i]!.t !== "slash") continue; + const before = toks[i - 1]; + const after = toks[i + 1]; + if (before?.t === "digit" && (after?.t === "digit" || (after?.t === "lit" && /^[1-9]/.test(after.s)))) return i; + } + return -1; +} + +interface Layout { + intToks: number[]; // indices of digit placeholders before the decimal point + fracToks: number[]; + pointAt: number; // index of the decimal point token, or -1 + grouping: boolean; + scale: number; // power of ten applied: +2 per %, -3 per scaling comma + commaRole: Map; +} + +function layout(toks: Tok[], from: number, to: number): Layout { + const intToks: number[] = []; + const fracToks: number[] = []; + let pointAt = -1; + let scale = 0; + for (let i = from; i < to; i++) { + const t = toks[i]!; + if (t.t === "point" && pointAt === -1) pointAt = i; + else if (t.t === "digit") (pointAt === -1 ? intToks : fracToks).push(i); + else if (t.t === "pct") scale += 2; + } + const commaRole = new Map(); + let grouping = false; + const lastInt = intToks[intToks.length - 1] ?? -1; + const firstInt = intToks[0] ?? -1; + const lastDigit = fracToks[fracToks.length - 1] ?? lastInt; + for (let i = from; i < to; i++) { + if (toks[i]!.t !== "comma") continue; + if (i > firstInt && i < lastInt && firstInt !== -1) { + commaRole.set(i, "group"); + grouping = true; + } else if (lastDigit !== -1 && i > lastDigit) { + // Commas right after the last digit placeholder (possibly several) scale by 1,000 each. + let j = lastDigit + 1; + while (j < i && toks[j]!.t === "comma") j++; + if (j === i) { + commaRole.set(i, "scale"); + scale -= 3; + } else commaRole.set(i, "lit"); + } else commaRole.set(i, "lit"); + } + return { intToks, fracToks, pointAt, grouping, scale, commaRole }; +} + +/** Places integer digits into placeholders, right to left; extra digits go to the leftmost one. */ +function placeInt(toks: Tok[], idx: number[], digits: string): Map { + const out = new Map(); + let d = digits.length; + for (let k = idx.length - 1; k >= 0; k--) { + const c = (toks[idx[k]!] as { c: "0" | "#" | "?" }).c; + let s = d > 0 ? digits[--d]! : c === "0" ? "0" : c === "?" ? " " : ""; + if (k === 0 && d > 0) s = digits.slice(0, d) + s; + out.set(idx[k]!, s); + } + return out; +} + +function group(s: string, sep: string): string { + // Insert the separator between real digits, counting from the right. + let out = ""; + let count = 0; + for (let i = s.length - 1; i >= 0; i--) { + const ch = s[i]!; + if (ch >= "0" && ch <= "9") { + if (count > 0 && count % 3 === 0) out = sep + out; + count++; + } + out = ch + out; + } + return out; +} + +function placeFrac(toks: Tok[], idx: number[], frac: string): Map { + const out = new Map(); + // Trailing zeros are dropped for '#' and shown as spaces for '?', from the right, up to the last '0' placeholder. + let trim = true; + for (let k = idx.length - 1; k >= 0; k--) { + const c = (toks[idx[k]!] as { c: "0" | "#" | "?" }).c; + const digit = frac[k] ?? "0"; + if (trim && digit === "0" && c !== "0") out.set(idx[k]!, c === "?" ? " " : ""); + else { + trim = false; + out.set(idx[k]!, digit); + } + } + return out; +} + +function plain(toks: Tok[], v: number, loc: LocaleData, generalWidth: number): NumberOut { + const lay = layout(toks, 0, toks.length); + const r = roundDec(shift(decimalOf(v), lay.scale), lay.fracToks.length); + const ints = placeInt(toks, lay.intToks, r.int); + const fracs = placeFrac(toks, lay.fracToks, r.frac); + const out = new Out(); + let intText = ""; + const flushInt = (): void => { + if (intText) out.push(lay.grouping ? group(intText, loc.group) : intText); + intText = ""; + }; + const firstInt = lay.intToks[0] ?? -1; + const lastInt = lay.intToks[lay.intToks.length - 1] ?? -1; + for (let i = 0; i < toks.length; i++) { + const t = toks[i]!; + const inInt = i >= firstInt && i <= lastInt && firstInt !== -1; + if (t.t === "digit") { + if (ints.has(i)) intText += ints.get(i)!; + else out.push(fracs.get(i) ?? ""); + if (i === lastInt) flushInt(); + continue; + } + if (inInt) { + if (t.t === "comma") continue; // grouping commas between placeholders + if (t.t === "lit" || t.t === "space") { + intText += t.t === "lit" ? t.s : " "; + continue; + } + } + switch (t.t) { + case "point": + if (i === lay.pointAt) out.push(loc.decimal); + else out.push("."); + break; + case "comma": + if (lay.commaRole.get(i) === "lit") out.push(","); + break; + case "pct": + out.push("%"); + break; + case "slash": + out.push("/"); + break; + case "exp": + out.push(t.s); + break; + case "general": + out.push(general(v, loc, generalWidth)); + break; + default: + out.tok(t); + } + } + flushInt(); + return out.result(); +} + +function scientific(toks: Tok[], expAt: number, v: number, loc: LocaleData): NumberOut { + const lay = layout(toks, 0, expAt); + const intCount = Math.max(1, lay.intToks.length); + const engineering = lay.intToks.some((i) => (toks[i] as { c: string }).c === "#") && lay.intToks.length > 1; + const d = decimalOf(v); + let exp = 0; + let r = { int: "", frac: "0".repeat(lay.fracToks.length) }; + if (d.digits !== "") { + const e10 = d.point - 1; + exp = engineering ? Math.floor(e10 / intCount) * intCount : e10 - (intCount - 1); + r = roundDec(shift(d, -exp), lay.fracToks.length); + // Rounding can carry into a new digit (9.99 → 10.0): step the exponent and redo. + if (r.int.length > intCount) { + exp += engineering ? intCount : 1; + r = roundDec(shift(d, -exp), lay.fracToks.length); + } + } + const ints = placeInt(toks, lay.intToks, r.int); + const fracs = placeFrac(toks, lay.fracToks, r.frac); + const out = new Out(); + for (let i = 0; i < expAt; i++) { + const t = toks[i]!; + if (t.t === "digit") out.push(ints.get(i) ?? fracs.get(i) ?? ""); + else if (t.t === "point") out.push(i === lay.pointAt ? loc.decimal : "."); + else if (t.t === "pct") out.push("%"); + else if (t.t === "comma") continue; + else out.tok(t); + } + const expTok = toks[expAt] as { s: string }; + out.push(expTok.s[0]!); + if (exp < 0) out.push("-"); + else if (expTok.s[1] === "+") out.push("+"); + const expDigits = String(Math.abs(exp)); + const after = toks.slice(expAt + 1); + const minDigits = after.filter((t) => t.t === "digit" && t.c === "0").length; + let placed = false; + for (const t of after) { + if (t.t === "digit") { + if (!placed) { + out.push(expDigits.padStart(minDigits, "0")); + placed = true; + } + continue; + } + out.tok(t); + } + if (!placed) out.push(expDigits); + return out.result(); +} + +function fraction(toks: Tok[], slashAt: number, v: number, loc: LocaleData): NumberOut { + // Numerator: the run of placeholders right before the slash. Integer part: an earlier run, if any. + let numStart = slashAt - 1; + while (numStart > 0 && toks[numStart - 1]!.t === "digit") numStart--; + const numIdx = range(numStart, slashAt); + const intIdx: number[] = []; + for (let i = 0; i < numStart; i++) if (toks[i]!.t === "digit") intIdx.push(i); + const after = toks[slashAt + 1]!; + let denEnd = slashAt + 1; + let fixedDen = 0; + let denIdx: number[] = []; + if (after.t === "lit") { + const m = /^[1-9]\d*/.exec(after.s)!; + fixedDen = Number(m[0]); + denEnd = slashAt + 2; + } else { + while (toks[denEnd]?.t === "digit") denEnd++; + denIdx = range(slashAt + 1, denEnd); + } + const hasInt = intIdx.length > 0; + let whole = hasInt ? Math.floor(v) : 0; + const part = hasInt ? v - whole : v; + let num: number; + let den: number; + if (fixedDen) { + den = fixedDen; + num = Math.round(part * den); + } else { + [num, den] = approximate(part, 10 ** denIdx.length - 1); + } + if (hasInt && num === den) { + whole += 1; + num = 0; + } + + const out = new Out(); + // Zero shows as "0" in the integer part, with the fraction blanked. + const intDigits = whole === 0 && !(hasInt && num === 0) ? "" : String(whole); + const ints = placeInt(toks, intIdx, intDigits); + const blankFraction = hasInt && num === 0; + const numText = pad(String(num), numIdx.map((i) => (toks[i] as { c: string }).c), true); + const denText = fixedDen ? String(fixedDen) : pad(String(den), denIdx.map((i) => (toks[i] as { c: string }).c), false); + for (let i = 0; i < toks.length; i++) { + const t = toks[i]!; + if (i < numStart) { + if (t.t === "digit") { + out.push(ints.get(i) ?? ""); + } else if (t.t === "point") out.push(loc.decimal); + else if (t.t === "comma") continue; + else out.tok(t); + continue; + } + if (i === numStart) { + out.push(blankFraction ? " ".repeat(numText.length) : numText); + continue; + } + if (i > numStart && i < slashAt) continue; + if (i === slashAt) { + out.push(blankFraction ? " " : "/"); + continue; + } + if (i === slashAt + 1) { + out.push(blankFraction ? " ".repeat(denText.length) : denText); + if (fixedDen && t.t === "lit") { + const rest = t.s.slice(String(fixedDen).length); + if (rest) out.push(rest); + } + continue; + } + if (i < denEnd) continue; + out.tok(t); + } + return out.result(); +} + +function range(a: number, b: number): number[] { + return Array.from({ length: Math.max(0, b - a) }, (_, i) => a + i); +} + +/** Pads per placeholders: '0' zero, '?' space, '#' nothing. Numerators pad on the left, denominators on the right. */ +function pad(s: string, cs: string[], left: boolean): string { + if (s.length >= cs.length) return s; + const fill = cs.slice(0, cs.length - s.length).map((c) => (c === "0" ? "0" : c === "?" ? " " : "")); + if (left) return fill.join("") + s; + // Denominators: zeros would change the value, so '0' pads with spaces too on the right. + return s + fill.map((f) => (f === "" ? "" : " ")).join(""); +} + +/** Best fraction num/den ≈ x with den ≤ maxDen (continued fractions, then the closest semiconvergent). */ +export function approximate(x: number, maxDen: number): [number, number] { + if (maxDen < 1) maxDen = 1; + let [p0, q0, p1, q1] = [0, 1, 1, 0]; + let y = x; + for (let iter = 0; iter < 64; iter++) { + const a = Math.floor(y); + const q2 = q0 + a * q1; + if (q2 > maxDen) { + const k = Math.floor((maxDen - q0) / q1); + const [pk, qk] = [p0 + k * p1, q0 + k * q1]; + return Math.abs(x - pk / qk) < Math.abs(x - p1 / q1) ? [pk, qk] : [p1, q1]; + } + [p0, q0, p1, q1] = [p1, q1, p0 + a * p1, q2]; + const frac = y - a; + if (frac < 1e-12 || Math.abs(x - p1 / q1) < 1e-15) break; + y = 1 / frac; + } + return [p1, q1]; +} + +/** + * Excel's General format for a number: as many digits as fit in `width` + * characters (11 by default, the standard column), switching to scientific + * notation for numbers of 1E+11 and above, and below 1E-04 `[to verify]`. + */ +export function general(v: number, loc: LocaleData, width: number): string { + if (!Number.isFinite(v)) return "#NUM!"; + if (v === 0) return "0"; + const neg = v < 0; + const d = decimalOf(v); + const e10 = d.point - 1; + const room = width - (neg ? 1 : 0); + const sign = neg ? "-" : ""; + if (e10 >= -4 && e10 < room) { + const intLen = Math.max(1, d.point); + const decimals = Math.max(0, room - intLen - 1); + const r = roundDec(d, decimals); + if ((r.int || "0").length <= room) { + const frac = r.frac.replace(/0+$/, ""); + return sign + (r.int || "0") + (frac ? loc.decimal + frac : ""); + } + } + // Scientific: d.ddddE+XX within the width. + let exp = e10; + let expText = (exp < 0 ? "-" : "+") + String(Math.abs(exp)).padStart(2, "0"); + let decimals = Math.max(0, room - 2 - 1 - expText.length); + let r = roundDec(shift(d, -exp), decimals); + if (r.int.length > 1) { + exp += 1; + expText = (exp < 0 ? "-" : "+") + String(Math.abs(exp)).padStart(2, "0"); + decimals = Math.max(0, room - 2 - 1 - expText.length); + r = roundDec(shift(d, -exp), decimals); + } + const frac = r.frac.replace(/0+$/, ""); + return `${sign}${r.int || "0"}${frac ? loc.decimal + frac : ""}E${expText}`; +} diff --git a/packages/javascript-excel/src/internal/format/parse.ts b/packages/javascript-excel/src/internal/format/parse.ts new file mode 100644 index 0000000..74a2a88 --- /dev/null +++ b/packages/javascript-excel/src/internal/format/parse.ts @@ -0,0 +1,283 @@ +/** + * Number-format code parser (docs/api.md §5.6). Turns a code such as + * `#,##0.00;[Red](#,##0.00)` into compiled sections. Linear in the code's + * length, no regular expressions with nested quantifiers, and it never + * throws: anything it does not recognise is kept as literal text, as Excel + * shows most stray characters. + */ + +/** One token of a section. */ +export type Tok = + | { t: "lit"; s: string } + | { t: "digit"; c: "0" | "#" | "?" } + | { t: "point" } + | { t: "comma" } + | { t: "pct" } + | { t: "exp"; s: string } // "E+", "E-", "e+", "e-" as written + | { t: "slash" } + | { t: "text" } // @ + | { t: "space" } // _x: a space as wide as x; rendered as one space + | { t: "fill"; c: string } // *x: repeat x to fill the cell + | { t: "general" } + | { t: "date"; k: "y" | "m" | "d" | "h" | "s" | "e" | "b" | "g"; n: number } + | { t: "minute"; n: number } // an "m" run that means minutes (resolved after tokenising) + | { t: "elapsed"; k: "h" | "m" | "s"; n: number } + | { t: "ampm"; s: string } // "AM/PM", "am/pm", "A/P", "a/p" as written + | { t: "subsec"; n: number }; // ".0" to ".000" after seconds + +export type Op = "<" | "<=" | ">" | ">=" | "=" | "<>"; + +export interface Section { + toks: Tok[]; + kind: "number" | "date" | "text" | "general" | "literal"; + /** Format colour as 'RRGGBB' name or [ColorN] palette index. */ + color?: { name: string } | { index: number } | undefined; + cond?: { op: Op; v: number } | undefined; + /** Locale id from a [$-xxxx] or [$sym-xxxx] tag, lower 16 bits. */ + lcid?: number | undefined; + /** [$-F800] / [$-x-sysdate]: the system long date; [$-F400] / [$-x-systime]: the system time. */ + system?: "longDate" | "time" | undefined; +} + +export interface Compiled { + sections: Section[]; +} + +const COLOR_NAMES = new Set(["black", "blue", "cyan", "green", "magenta", "red", "white", "yellow"]); + +/** Splits a code at top-level semicolons (not inside quotes, brackets or after a backslash). */ +function splitSections(code: string): string[] { + const out: string[] = []; + let start = 0; + for (let i = 0; i < code.length; i++) { + const ch = code[i]!; + if (ch === "\\" || ch === "_" || ch === "*") i++; + else if (ch === '"') { + const end = code.indexOf('"', i + 1); + i = end === -1 ? code.length : end; + } else if (ch === "[") { + const end = code.indexOf("]", i + 1); + if (end !== -1) i = end; + } else if (ch === ";") { + out.push(code.slice(start, i)); + start = i + 1; + } + } + out.push(code.slice(start)); + return out; +} + +const COND = /^(<=|>=|<>|<|>|=)\s*(-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)$/; + +function bracket(sec: Section, toks: Tok[], inner: string): void { + const lower = inner.toLowerCase(); + if (COLOR_NAMES.has(lower)) { + sec.color = { name: lower }; + return; + } + const colorN = /^color\s*(\d{1,2})$/.exec(lower); + if (colorN) { + const n = Number(colorN[1]); + if (n >= 1 && n <= 56) sec.color = { index: n }; + return; + } + const cond = COND.exec(inner.trim()); + if (cond) { + sec.cond = { op: cond[1] as Op, v: Number(cond[2]) }; + return; + } + if (/^(h+|m+|s+)$/.test(lower)) { + toks.push({ t: "elapsed", k: lower[0] as "h" | "m" | "s", n: lower.length }); + return; + } + if (inner.startsWith("$")) { + // [$€-407]: currency symbol, then an optional locale id in hex. [$-409]: locale only. + // [$-x-sysdate] / [$-x-systime]: Excel's system date and time formats. + const dash = inner.indexOf("-", 1); + const symbol = dash === -1 ? inner.slice(1) : inner.slice(1, dash); + const tag = dash === -1 ? "" : inner.slice(dash + 1).toLowerCase(); + if (symbol) toks.push({ t: "lit", s: symbol }); + if (tag === "x-sysdate") sec.system = "longDate"; + else if (tag === "x-systime") sec.system = "time"; + else if (/^[0-9a-f]{1,8}$/.test(tag)) { + const id = Number.parseInt(tag, 16) & 0xffff; + if (id === 0xf800) sec.system = "longDate"; + else if (id === 0xf400) sec.system = "time"; + else sec.lcid = id; + } + return; + } + // Other bracket codes ([DBNum1], [NatNum1], …) are not rendered. +} + +function tokenize(src: string): Section { + const sec: Section = { toks: [], kind: "literal" }; + const toks = sec.toks; + const lit = (s: string): void => { + const last = toks[toks.length - 1]; + if (last?.t === "lit") last.s += s; + else toks.push({ t: "lit", s }); + }; + for (let i = 0; i < src.length; i++) { + const ch = src[i]!; + const rest = (n: number): string => src.slice(i, i + n).toLowerCase(); + switch (ch) { + case '"': { + const end = src.indexOf('"', i + 1); + const stop = end === -1 ? src.length : end; + if (stop > i + 1) lit(src.slice(i + 1, stop)); + i = stop; + continue; + } + case "\\": + if (i + 1 < src.length) lit(src[++i]!); + continue; + case "_": + if (i + 1 < src.length) i++; + toks.push({ t: "space" }); + continue; + case "*": + if (i + 1 < src.length) toks.push({ t: "fill", c: src[++i]! }); + continue; + case "[": { + const end = src.indexOf("]", i + 1); + if (end === -1) { + lit(src.slice(i)); + i = src.length; + continue; + } + bracket(sec, toks, src.slice(i + 1, end)); + i = end; + continue; + } + case "0": + case "#": + case "?": + toks.push({ t: "digit", c: ch }); + continue; + case ".": + toks.push({ t: "point" }); + continue; + case ",": + toks.push({ t: "comma" }); + continue; + case "%": + toks.push({ t: "pct" }); + continue; + case "/": + toks.push({ t: "slash" }); + continue; + case "@": + toks.push({ t: "text" }); + continue; + } + if (rest(7) === "general") { + toks.push({ t: "general" }); + i += 6; + continue; + } + if (rest(5) === "am/pm") { + toks.push({ t: "ampm", s: src.slice(i, i + 5) }); + i += 4; + continue; + } + if (rest(3) === "a/p") { + toks.push({ t: "ampm", s: src.slice(i, i + 3) }); + i += 2; + continue; + } + if ((ch === "E" || ch === "e") && (src[i + 1] === "+" || src[i + 1] === "-")) { + toks.push({ t: "exp", s: src.slice(i, i + 2) }); + i++; + continue; + } + const k = ch.toLowerCase(); + if (k === "y" || k === "m" || k === "d" || k === "h" || k === "s" || k === "e" || k === "b" || k === "g") { + let n = 1; + while (i + n < src.length && src[i + n]!.toLowerCase() === k) n++; + toks.push({ t: "date", k, n }); + i += n - 1; + continue; + } + lit(ch); + } + return sec; +} + +const isDateTok = (t: Tok): boolean => t.t === "date" || t.t === "elapsed" || t.t === "ampm" || t.t === "minute"; + +/** Classifies a section and resolves date-only tokens (minutes vs months, sub-seconds). */ +function finish(sec: Section): Section { + const toks = sec.toks; + if (toks.some(isDateTok)) { + sec.kind = "date"; + // "m"/"mm" is minutes right after an hour token or right before a seconds token (literals skipped). + const dateIdx = toks.map((t, i) => (isDateTok(t) ? i : -1)).filter((i) => i >= 0); + dateIdx.forEach((idx, j) => { + const t = toks[idx]!; + if (t.t !== "date" || t.k !== "m" || t.n > 2) return; + const prev = j > 0 ? toks[dateIdx[j - 1]!] : undefined; + const next = j + 1 < dateIdx.length ? toks[dateIdx[j + 1]!] : undefined; + const afterHour = (prev?.t === "date" && prev.k === "h") || (prev?.t === "elapsed" && prev.k === "h"); + const beforeSecond = (next?.t === "date" && next.k === "s") || (next?.t === "elapsed" && next.k === "s"); + if (afterHour || beforeSecond) toks[idx] = { t: "minute", n: t.n }; + }); + // In a date section, "." followed by 0s after seconds is a fraction of a second; other number tokens are literal. + const out: Tok[] = []; + let seenSeconds = false; + for (let i = 0; i < toks.length; i++) { + const t = toks[i]!; + if ((t.t === "date" && t.k === "s") || (t.t === "elapsed" && t.k === "s")) seenSeconds = true; + if (t.t === "point" && seenSeconds && toks[i + 1]?.t === "digit" && (toks[i + 1] as { c: string }).c === "0") { + let n = 0; + while (toks[i + 1 + n]?.t === "digit" && (toks[i + 1 + n] as { c: string }).c === "0") n++; + out.push({ t: "subsec", n: Math.min(n, 3) }); + i += n; + continue; + } + out.push(literalInDate(t)); + } + sec.toks = mergeLits(out); + return sec; + } + if (toks.some((t) => t.t === "text")) sec.kind = "text"; + else if (toks.some((t) => t.t === "digit")) sec.kind = "number"; + else if (toks.some((t) => t.t === "general")) sec.kind = "general"; + else sec.kind = "literal"; + return sec; +} + +function literalInDate(t: Tok): Tok { + switch (t.t) { + case "digit": + return { t: "lit", s: t.c }; + case "point": + return { t: "lit", s: "." }; + case "comma": + return { t: "lit", s: "," }; + case "pct": + return { t: "lit", s: "%" }; + case "slash": + return { t: "lit", s: "/" }; + case "exp": + return { t: "lit", s: t.s }; + default: + return t; + } +} + +function mergeLits(toks: Tok[]): Tok[] { + const out: Tok[] = []; + for (const t of toks) { + const last = out[out.length - 1]; + if (t.t === "lit" && last?.t === "lit") last.s += t.s; + else out.push(t); + } + return out; +} + +/** Compiles a format code. At most four sections are used, as in Excel. */ +export function compile(code: string): Compiled { + const sections = splitSections(code).slice(0, 4).map((s) => finish(tokenize(s))); + return { sections }; +} diff --git a/packages/javascript-excel/test/entries.test.ts b/packages/javascript-excel/test/entries.test.ts index 069dcda..e865f59 100644 --- a/packages/javascript-excel/test/entries.test.ts +++ b/packages/javascript-excel/test/entries.test.ts @@ -3,6 +3,7 @@ import pkg from "../package.json" with { type: "json" }; import { VERSION } from "../src/index"; import * as csv from "../src/csv"; import * as dom from "../src/dom"; +import * as format from "../src/format"; import * as read from "../src/read"; import * as worker from "../src/worker"; @@ -23,6 +24,10 @@ describe("entries", () => { expect(Object.keys(dom).sort()).toEqual(["DOWNLOAD_REVOKE_DELAY_MS", "download", "fromTable"]); }); + it("/format exports the documented API", () => { + expect(Object.keys(format).sort()).toEqual(["formatCell", "formatValue"]); + }); + it("/csv exports the documented API", () => { expect(Object.keys(csv).sort()).toEqual(["CSV_MIME", "parseCsv", "readCsv", "toCsv", "toCsvBlob"]); }); diff --git a/packages/javascript-excel/test/format/cases.ts b/packages/javascript-excel/test/format/cases.ts new file mode 100644 index 0000000..94ccacd --- /dev/null +++ b/packages/javascript-excel/test/format/cases.ts @@ -0,0 +1,96 @@ +// The number-format reference corpus: format codes and the values each is +// shown with. test/format/libreoffice.test.ts writes them to a workbook, has +// LibreOffice export it "as shown" and compares every cell with formatValue. +// The cells of the conformance corpus's number-format files (10 and 11) are +// added there too. + +import type { NumFmt } from "../../src/model"; + +const NUMBERS = [1234.5678, -1234.5678, 0, 0.5, -0.5, 1e-5, 123456789.123, 7]; +const SMALL = [0.256, -0.03125, 0, 1.5, 12.5]; +const DATES = [1, 59, 60, 61, 45306, 45306.6458333, 45306.99999999, 2958465, 0.5]; +const TIMES = [0, 0.25, 0.5, 0.6458333, 0.999999, 1.5215278, 0.0215278, 2.75]; + +export interface FormatCase { + code: NumFmt; + values: Array; +} + +export const FORMAT_CASES: FormatCase[] = [ + // General and plain numbers + { code: "General", values: [1234.5678, 0.1 + 0.2, 42, -3.5, 1 / 3, -1 / 3, 1e21, 1e-7, 123456789012, 12345678901, 0.0001, 0.00001, 1e15 + 0.5, 99999999999.5, -0.000123456789] }, + { code: "0", values: [...NUMBERS, 2.5, -2.5, 1e20] }, + { code: "0.00", values: [...NUMBERS, 1.005, -0.001, 0.125] }, + { code: "0.000", values: NUMBERS }, + { code: "#,##0", values: NUMBERS }, + { code: "#,##0.00", values: NUMBERS }, + { code: "#,##0.###", values: NUMBERS }, + { code: "#.##", values: [0.5, 1, 12.345, 0] }, + { code: "0.##", values: [1, 1.5, 1.555] }, + { code: "0.0?", values: [1.5, 1.25, 1] }, + { code: "??0.0", values: [1.5, 123.25] }, + { code: "00000", values: [42, 123456] }, + { code: "000-00-0000", values: [123456789] }, + { code: "#,##0,", values: [1234567, 999] }, + { code: "0.0,,", values: [1234567, 98765432] }, + { code: "#,##0.00,,\"M\"", values: [1234567890] }, + // Percent and scientific + { code: "0%", values: SMALL }, + { code: "0.00%", values: SMALL }, + { code: "0.00E+00", values: [...NUMBERS, 0.000123] }, + { code: "0.0E+0", values: [99999, 0.00051] }, + { code: "##0.0E+0", values: [12345.678, 0.000123, 1234567] }, + { code: "0.00e-00", values: [12345, 0.00012] }, + // Fractions + { code: "# ?/?", values: [1.25, 0.5, 2, 0, -1.75, 3.14159] }, + { code: "# ??/??", values: [1.3125, 3.14159, 0.1] }, + { code: "# ???/???", values: [3.14159] }, + { code: "?/?", values: [0.75, 1.5] }, + { code: "# ?/8", values: [1.3, 0.5] }, + { code: "# ??/16", values: [2.6] }, + // Sections, conditions, colours and literals + { code: "0;(0)", values: [5, -5, 0] }, + { code: "0;-0;\"zero\"", values: [5, -5, 0] }, + { code: '0.0;-0.0;"zero";"text: "@', values: [5, -5, 0, "abc"] }, + { code: "[Blue]0.0;[Red]-0.0;0", values: [12.5, -12.5, 0] }, + { code: '[>100]"big";[<0]"neg";"small"', values: [150, -1, 5] }, + { code: "[<1000]0;[>=1000]#,##0", values: [999, 12345] }, + { code: "[Red][<=100]0;[Blue][>100]0", values: [50, 150] }, + { code: '#,##0.00 "€"', values: [1234.5, -1234.5] }, + { code: '"Total: "General', values: [12.5, -3] }, + { code: "\\$#,##0.00", values: [1234.5] }, + { code: "_(0_)", values: [5, -5] }, + { code: "[$€-407]#,##0.00", values: [1234.5] }, + { code: "[$$-409]#,##0.00", values: [1234.5] }, + { code: ";;;", values: [5, -5, 0, "x"] }, + // Text + { code: "@", values: [1234.5, "abc"] }, + { code: '"<"@">"', values: ["abc", 5] }, + // Dates + { code: "yyyy-mm-dd", values: DATES }, + { code: "yyyy-mm-dd hh:mm:ss", values: DATES }, + { code: "d-mmm-yy", values: DATES }, + { code: "dd/mm/yyyy", values: DATES }, + { code: "m/d/yy", values: DATES }, + { code: "dddd, mmmm d, yyyy", values: [45306, 61, 1] }, + { code: "ddd d mmm yy", values: [45306] }, + { code: "mmmmm", values: [45306, 45337] }, + { code: "yy", values: [45306] }, + { code: 'yyyy-mm-dd"T"hh:mm', values: [45306.37847222] }, + // Times and elapsed time + { code: "h:mm", values: TIMES }, + { code: "h:mm:ss", values: TIMES }, + { code: "hh:mm:ss.000", values: [0.5000014236] }, + { code: "ss.00", values: [1.5 / 86400] }, + { code: "h:mm AM/PM", values: TIMES }, + { code: "h am/pm", values: [0.5, 0.1] }, + { code: "h:mm A/P", values: [0.75] }, + { code: "mm:ss", values: [0.0215278, 0.5] }, + { code: "[h]:mm", values: [1.5, 0.5, 30.25] }, + { code: "[h]:mm:ss", values: [1.5215278] }, + { code: "[mm]:ss", values: [0.0215278, 1] }, + { code: "[ss]", values: [0.0215278] }, + // Built-in ids (en-US) + ...[1, 2, 3, 4, 9, 10, 11, 12, 13, 37, 38, 39, 40, 48, 49].map((id) => ({ code: id, values: [1234.5678, -1234.5678, 0.256] })), + ...[14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47].map((id) => ({ code: id, values: [45306.6458333, 0.0215278] })), +]; diff --git a/packages/javascript-excel/test/format/format.test.ts b/packages/javascript-excel/test/format/format.test.ts new file mode 100644 index 0000000..5a57f17 --- /dev/null +++ b/packages/javascript-excel/test/format/format.test.ts @@ -0,0 +1,222 @@ +import { describe, expect, it } from "vitest"; +import { formatCell, formatValue } from "../../src/format"; + +const f = (v: Parameters[0], fmt?: string | number, opts?: Parameters[2]): string => formatValue(v, fmt, opts).text; +const serial = (y: number, m: number, d: number, hh = 0, mm = 0, ss = 0): number => (Date.UTC(y, m - 1, d, hh, mm, ss) - Date.UTC(1899, 11, 30)) / 86_400_000; + +describe("General", () => { + it.each([ + [1234.5678, "1234.5678"], + [0.1 + 0.2, "0.3"], + [42, "42"], + [0, "0"], + [-3.5, "-3.5"], + [1 / 3, "0.333333333"], + [1e21, "1E+21"], + [1e-7, "1E-07"], + [123456789012, "1.23457E+11"], + [12345678901, "12345678901"], + [0.0001, "0.0001"], + ])("%s → %s", (v, out) => { + expect(f(v)).toBe(out); + expect(f(v, 0)).toBe(out); + expect(f(v, "General")).toBe(out); + }); + + it("aligns by value type", () => { + expect(formatValue(1).align).toBe("right"); + expect(formatValue("a").align).toBe("left"); + expect(formatValue(true).align).toBe("center"); + expect(formatValue({ error: "#N/A" }).align).toBe("center"); + }); +}); + +describe("built-in ids (en-US)", () => { + it.each<[number, number, string]>([ + [1, 1234.5678, "1235"], + [2, 1234.5678, "1234.57"], + [3, 1234.5678, "1,235"], + [4, 1234.5678, "1,234.57"], + [9, 0.256, "26%"], + [10, 0.256, "25.60%"], + [11, 1234.5678, "1.23E+03"], + [12, 1.25, "1 1/4"], + [13, 1.3125, "1 5/16"], + [14, 45306, "1/15/2024"], + [15, 45306, "15-Jan-24"], + [16, 45306, "15-Jan"], + [17, 45306, "Jan-24"], + [18, 0.6458333, "3:30 PM"], + [19, 0.6458333, "3:30:00 PM"], + [20, 0.6458333, "15:30"], + [21, 0.6458333, "15:30:00"], + [22, 45306.6458333, "1/15/2024 15:30"], + [37, 1234, "1,234 "], + [37, -1234, "(1,234)"], + [39, -1234.5, "(1,234.50)"], + [45, 0.0215278, "31:00"], + [46, 1.5215278, "36:31:00"], + [47, 0.0215278, "3100.0"], + [48, 12345.678, "12.3E+3"], + [49, 1234.5678, "1234.5678"], + ])("id %i: %s → %s", (id, v, out) => { + expect(f(v, id)).toBe(out); + }); + + it("id 38 shows negatives in red", () => { + expect(formatValue(-1234, 38)).toMatchObject({ text: "(1,234)", color: "FFFF0000" }); + expect(formatValue(1234, 38).color).toBeUndefined(); + }); + + it("unknown ids fall back to General", () => { + expect(f(1234.5, 200)).toBe("1234.5"); + }); +}); + +describe("numbers", () => { + it.each<[string, number, string]>([ + ["0.000", 1234.5678, "1234.568"], + ['#,##0.00 "€"', 1234.5, "1,234.50 €"], + ["#,##0,", 1234567, "1,235"], + ["0.0,,", 1234567, "1.2"], + ["0%", 0.5, "50%"], + ["000-00-0000", 123456789, "123-45-6789"], + ["#.##", 0.5, ".5"], + ["0.##", 1, "1."], + ["0.00", 1.005, "1.01"], + ["0", 2.5, "3"], + ["0", -2.5, "-3"], + ["0.0", 0.05, "0.1"], + ["0", 1e20, "100000000000000000000"], + ["0.00", -0.001, "0.00"], + ["00000", 42, "00042"], + ["0;(0)", -5, "(5)"], + ["0.00E+00", 0.000123, "1.23E-04"], + ["0.00E+00", 0, "0.00E+00"], + ["0.0E+0", 99999, "1.0E+5"], + ["##0.0E+0", 0.000123, "123.0E-6"], + ["_(0_)", 5, " 5 "], + ["\\$0", 5, "$5"], + ['"Total: "General', 12.5, "Total: 12.5"], + ['[$€-407]#,##0.00', 1234.5, "€1,234.50"], + ])("%s with %s → %s", (code, v, out) => { + expect(f(v, code)).toBe(out); + }); + + it("uses the locale's separators", () => { + expect(f(1234.5, "#,##0.00", { locale: "de-DE" })).toBe("1.234,50"); + expect(f(0.5, "0.0%", { locale: "de-DE" })).toBe("50,0%"); + expect(f(1234.5, undefined, { locale: "de-DE" })).toBe("1234,5"); + }); + + it("selects sections with and without conditions", () => { + const code = '0;-0;"zero";"text: "@'; + expect(f(5, code)).toBe("5"); + expect(f(-5, code)).toBe("-5"); + expect(f(0, code)).toBe("zero"); + expect(f("x", code)).toBe("text: x"); + const cond = '[>100]"big";[<0]"neg";"small"'; + expect(f(150, cond)).toBe("big"); + expect(f(-1, cond)).toBe("neg"); + expect(f(5, cond)).toBe("small"); + }); + + it("returns format colours as ARGB", () => { + expect(formatValue(-12.5, "[Blue]0.0;[Red]-0.0;0")).toMatchObject({ text: "-12.5", color: "FFFF0000" }); + expect(formatValue(1, "[Color10]0").color).toBe("FF008000"); + expect(formatValue(1, "[Color10]0", { indexedColors: Array.from({ length: 64 }, (_, i) => (i === 17 ? "FF123456" : "FF000000")) }).color).toBe("FF123456"); + }); + + it("reports a *x fill without repeating it", () => { + expect(formatValue(5, "*-0")).toMatchObject({ text: "5", fill: { char: "-", at: 0 } }); + expect(formatValue(5, '"$"* 0')).toMatchObject({ text: "$5", fill: { char: " ", at: 1 } }); + }); + + it("fractions", () => { + expect(f(1.3, "# ?/8")).toBe("1 2/8"); + expect(f(0.75, "?/?")).toBe("3/4"); + expect(f(2, "# ?/?")).toBe("2 "); + expect(f(3.14159, "# ???/???")).toBe("3 16/113"); + }); +}); + +describe("dates and times from serials", () => { + it.each<[string, number, string]>([ + ['yyyy-mm-dd"T"hh:mm', serial(2024, 1, 15, 9, 5), "2024-01-15T09:05"], + ["dddd, mmmm d, yyyy", 45306, "Monday, January 15, 2024"], + ["ddd d mmm yy", 45306, "Mon 15 Jan 24"], + ["mmmmm", 45306, "J"], + ["h:mm AM/PM", 0, "12:00 AM"], + ["h am/pm", 0.5, "12 pm"], + ["h:mm A/P", 0.75, "6:00 P"], + ["[h]:mm", 1.5, "36:00"], + ["[mm]:ss", 0.0215278, "31:00"], + ["[ss]", 0.0215278, "1860"], + ["ss.00", 1.5 / 86400, "01.50"], + ["hh:mm:ss.000", 0.5 + 0.123 / 86400, "12:00:00.123"], + ["d-mmm-yy", 60, "29-Feb-00"], + ["yyyy-mm-dd", 0, "1900-01-00"], + ["dddd", 1, "Sunday"], + ["dddd", 61, "Thursday"], + ["yyyy-mm-dd hh:mm", 45306.99999999, "2024-01-16 00:00"], + ["m/d/yy", 2958465, "12/31/99"], + ["yyyy", 45306, "2024"], + ["mm:ss", serial(2024, 1, 15, 10, 30, 15) % 1, "30:15"], + ["h:mm", serial(2024, 1, 15, 10, 30, 15) % 1, "10:30"], + ])("%s with %s → %s", (code, v, out) => { + expect(f(v, code)).toBe(out); + }); + + it("1904 system", () => { + expect(f(0, "yyyy-mm-dd", { date1904: true })).toBe("1904-01-01"); + expect(f(0, "dddd", { date1904: true })).toBe("Friday"); + }); + + it("Date inputs become serials in the chosen zone", () => { + expect(f(new Date(2024, 0, 15), 14)).toBe("1/15/2024"); + expect(f(new Date(Date.UTC(2024, 0, 15, 12)), "yyyy-mm-dd hh:mm", { dateZone: "utc" })).toBe("2024-01-15 12:00"); + }); + + it("locale names and short dates", () => { + expect(f(45306, "dddd d mmmm", { locale: "de-DE" })).toBe("Montag 15 Januar"); + expect(f(45306, 14, { locale: "de-DE" })).toBe("15.01.2024"); + expect(f(45306, 14, { locale: "en-GB" })).toBe("15/01/2024"); + expect(f(45306, "[$-407]mmmm", { locale: "en-US" })).toBe("Januar"); + }); + + it("dates Excel cannot show fill the cell with #", () => { + expect(formatValue(-1, "yyyy-mm-dd")).toMatchObject({ text: "", fill: { char: "#", at: 0 } }); + expect(formatValue(3e6, "yyyy-mm-dd")).toMatchObject({ text: "", fill: { char: "#", at: 0 } }); + expect(f(-1.5, "[h]:mm")).toBe("-36:00"); + }); +}); + +describe("other values", () => { + it("booleans, errors, text and empty", () => { + expect(f(true, "0.00")).toBe("TRUE"); + expect(f(false)).toBe("FALSE"); + expect(f({ error: "#DIV/0!" }, "0")).toBe("#DIV/0!"); + expect(f("abc", '"<"@">"')).toBe(""); + expect(f("abc", "0.00")).toBe("abc"); + expect(f({ richText: [{ text: "a" }, { text: "b" }] })).toBe("ab"); + expect(f(null)).toBe(""); + expect(f(5, "@")).toBe("5"); + }); + + it("formatCell uses the cell's number format and cached value", () => { + expect(formatCell({ value: 45306, style: { numFmt: 14 } }).text).toBe("1/15/2024"); + expect(formatCell({ formula: "SUM(A1:A2)", value: 3, style: { numFmt: "0.00" } }).text).toBe("3.00"); + expect(formatCell({ formula: "NOW()" }).text).toBe(""); + expect(formatCell(12.5).text).toBe("12.5"); + expect(formatCell(undefined).text).toBe(""); + }); + + it("never throws on odd codes", () => { + for (const code of ['"abc', "[Red", "[>abc]0", "0.0.0", ";;;", "\\", "_", "*", "[$-ZZZ]0", "[h", "0/0", "#,##0,,,,", "E+0", "?/"]) { + expect(() => formatValue(1234.5, code)).not.toThrow(); + expect(() => formatValue(-1, code)).not.toThrow(); + expect(() => formatValue("t", code)).not.toThrow(); + } + expect(f(5, ";;;")).toBe(""); + }); +}); diff --git a/packages/javascript-excel/test/format/libreoffice.test.ts b/packages/javascript-excel/test/format/libreoffice.test.ts new file mode 100644 index 0000000..a8484ac --- /dev/null +++ b/packages/javascript-excel/test/format/libreoffice.test.ts @@ -0,0 +1,107 @@ +/// +// Reference check for javascript-excel/format: every case of test/format/cases.ts +// and every number-formatted cell of the conformance corpus's number-format files +// is written to one workbook, LibreOffice exports it to CSV "as shown", and each +// cell must equal formatCell(cell, { locale: "en-US" }).text. +// +// LibreOffice is the automated reference, Excel is the authority: where the two are +// known to differ, the case is listed in LIBREOFFICE_DIFFERS with LibreOffice's +// output and the reason, and docs/api.md §5.6 records it as [to verify] in Excel. +// Runs in the `LibreOffice` CI job (JSE_REQUIRE_LIBREOFFICE=1); skipped elsewhere +// unless $JSE_SOFFICE is available. +import { execFileSync, spawnSync } from "node:child_process"; +import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { afterAll, describe, expect, it } from "vitest"; +import { toUint8Array, type Cell, type CellInput, type Workbook } from "../../src/index"; +import { parseCsv } from "../../src/csv"; +import { formatCell } from "../../src/format"; +import { CORPUS } from "../conformance/corpus"; +import { FORMAT_CASES } from "./cases"; + +const SOFFICE = process.env["JSE_SOFFICE"] ?? "soffice"; +const hasSoffice = spawnSync(SOFFICE, ["--version"], { stdio: "ignore", timeout: 120_000 }).status === 0; +if (process.env["JSE_REQUIRE_LIBREOFFICE"] === "1" && !hasSoffice) throw new Error(`LibreOffice check required but soffice (${SOFFICE}) is missing`); + +/** `${code} | ${value}` → LibreOffice's output, where LibreOffice is known to differ from formatValue (and why). */ +const LIBREOFFICE_DIFFERS: Record = {}; + +interface Probe { + label: string; + cell: Cell; +} + +function probes(): Probe[] { + const out: Probe[] = []; + for (const c of FORMAT_CASES) { + for (const value of c.values) out.push({ label: `${String(c.code)} | ${String(value)}`, cell: { value, style: { numFmt: c.code } } }); + } + // The conformance corpus's number-format files. + for (const entry of CORPUS.filter((e) => e.id === "10-number-formats" || e.id === "11-number-formats-locale")) { + for (const sheet of entry.workbook().sheets) { + sheet.rows.forEach((row) => + row?.forEach((c: CellInput) => { + if (typeof c !== "object" || c === null || c instanceof Date || "error" in c || "richText" in c) return; + const cell = c as Cell; + if (cell.style?.numFmt === undefined || cell.formula) return; + out.push({ label: `${String(cell.style.numFmt)} | ${cell.value instanceof Date ? cell.value.toISOString() : String(cell.value)} (conformance)`, cell }); + }), + ); + } + } + return out; +} + +const dir = mkdtempSync(join(tmpdir(), "jse-lo-format-")); +const profile = `-env:UserInstallation=${pathToFileURL(join(dir, "profile")).href}`; +afterAll(() => rmSync(dir, { recursive: true, force: true })); + +describe.skipIf(!hasSoffice)("javascript-excel/format against LibreOffice", () => { + it("every probe matches LibreOffice's 'as shown' CSV, except the listed differences", { timeout: 300_000 }, async () => { + const list = probes(); + // One probe per row: column A is the label (text), column B the formatted cell. + const wb: Workbook = { sheets: [{ name: "Formats", rows: list.map((p) => [p.label, p.cell]) }] }; + const file = join(dir, "formats.xlsx"); + writeFileSync(file, await toUint8Array(wb)); + // Filter options: comma, double quote, UTF-8, from line 1, no column types, en-US, + // quoted as text off, detect special numbers on, save cell contents AS SHOWN on. + const filter = "csv:Text - txt - csv (StarCalc):44,34,76,1,,1033,false,true,true,false,false"; + execFileSync(SOFFICE, [profile, "--headless", "--norestore", "--convert-to", filter, "--outdir", dir, file], { + stdio: "ignore", + timeout: 300_000, + env: { ...process.env, LC_ALL: "en_US.UTF-8", LANG: "en_US.UTF-8" }, + }); + const csv = readFileSync(join(dir, "formats.csv"), "utf8").replace(/^/, ""); + const rows = parseCsv(csv, { delimiter: ",", inferTypes: false }).rows; + + const mismatches: string[] = []; + const stale: string[] = []; + let matched = 0; + list.forEach((p, i) => { + const lo = String(rows[i]?.[1] ?? ""); + const ours = formatCell(p.cell, { locale: "en-US" }).text; + const known = LIBREOFFICE_DIFFERS[p.label]; + if (known) { + if (lo !== known.libreoffice) stale.push(`${p.label}: LibreOffice now gives ${JSON.stringify(lo)}, listed ${JSON.stringify(known.libreoffice)}`); + return; + } + if (lo === ours) matched++; + else mismatches.push(`| \`${p.label}\` | \`${JSON.stringify(lo)}\` | \`${JSON.stringify(ours)}\` |`); + }); + + const report = [ + `### javascript-excel/format vs LibreOffice`, + ``, + `${list.length} probes: ${matched} match, ${Object.keys(LIBREOFFICE_DIFFERS).length} listed differences, ${mismatches.length} unexpected mismatches, ${stale.length} stale entries.`, + ``, + ...(mismatches.length ? [`| probe | LibreOffice | formatValue |`, `|---|---|---|`, ...mismatches, ``] : []), + ...stale.map((s) => `- stale: ${s}`), + ].join("\n"); + console.log(report); + if (process.env["GITHUB_STEP_SUMMARY"]) appendFileSync(process.env["GITHUB_STEP_SUMMARY"], `${report}\n`); + expect(mismatches, "unexpected differences from LibreOffice").toEqual([]); + expect(stale, "listed differences that changed").toEqual([]); + }); +}); diff --git a/packages/javascript-excel/tsdown.config.ts b/packages/javascript-excel/tsdown.config.ts index 28dc201..8fa1513 100644 --- a/packages/javascript-excel/tsdown.config.ts +++ b/packages/javascript-excel/tsdown.config.ts @@ -10,6 +10,7 @@ const config: UserConfig = defineConfig({ csv: "src/csv.ts", dom: "src/dom.ts", worker: "src/worker.ts", + format: "src/format.ts", }, format: ["esm", "cjs"], platform: "neutral", From 961ff46d24974b6b49f5c1b7cc37f3885e3f3879 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Mon, 16 Nov 2026 14:14:09 +0100 Subject: [PATCH 2/6] JSE-18: ids 32-35 as times; LibreOffice differences as proven rules --- docs/api.md | 92 +++++++++++++++++-- packages/javascript-excel/src/format.ts | 7 +- .../test/format/format.test.ts | 4 + .../test/format/libreoffice.test.ts | 54 +++++++---- 4 files changed, 133 insertions(+), 24 deletions(-) diff --git a/docs/api.md b/docs/api.md index 22c7eaa..1a834e6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -15,7 +15,7 @@ Conventions in this document: 2. [Entry points](#2-entry-points) 3. [Data model](#3-data-model) 4. [Builders and helpers](#4-builders-and-helpers) -5. [Write, read, CSV, DOM and worker APIs](#5-write-read-csv-dom-and-worker-apis) +5. [Write, read, CSV, DOM, worker and format APIs](#5-write-read-csv-dom-worker-and-format-apis) 6. [Zip codec](#6-zip-codec) 7. [Errors and warnings](#7-errors-and-warnings) 8. [Security model](#8-security-model) @@ -79,6 +79,7 @@ One npm package, `javascript-excel`, with subpath exports. `package.json` declar | `javascript-excel/csv` | `parseCsv`, `readCsv`, `toCsv`, `toCsvBlob`, option types | Nothing from the xlsx code | CSV-only apps ship a few kB of CSV code and the model types. | | `javascript-excel/dom` | `fromTable`, `download` | DOM APIs, called only inside functions | The only module that touches `document`. Safe to import during SSR; calling it without a DOM throws `ENVIRONMENT_UNSUPPORTED`. | | `javascript-excel/worker` | `exposeWorker` (worker side), `createWorkerClient` (main-thread side) | Writer and reader, inside the worker only | Moves big jobs off the main thread. Main-thread code that imports only `createWorkerClient` does not ship the engine. | +| `javascript-excel/format` (2.x) | `formatValue`, `formatCell`, `FormatOptions`, `FormattedValue` | Format-code parser and renderer; locale data from `Intl` | Only apps that show formatted values (viewers, previews) pay for it. | Rules: @@ -449,7 +450,7 @@ export type NumFmt = number | string; - **Strings are custom codes**, written as `` with ids allocated from 164 upward, one per distinct code. The one exception is `'General'`, which maps to id 0. The writer does not map other strings to built-in ids, because a built-in id such as 14 renders in the user's locale while the string `'mm-dd-yy'` should render literally (§12 Q5). - The reader returns built-in ids as numbers and custom codes as strings, so `read` then `write` keeps formats unchanged. - `BUILTIN_NUM_FMTS` exports the spec table (§11.2), `isDateFormat(fmt)` the detection rule from §3.4.1. -- Number formats are not rendered (no "format 1234.5 as `#,##0.00`") in 2.0 (§12 Q14). +- Number formats are not rendered in 2.0.0 itself. `javascript-excel/format` (§5.6) renders them, in a 2.x minor (§12 Q14). #### 3.5.6 Colour @@ -721,7 +722,7 @@ export function validateSheetName(name: string): null | 'empty' | 'too-long' | ' --- -## 5. Write, read, CSV, DOM and worker APIs +## 5. Write, read, CSV, DOM, worker and format APIs ### 5.1 Write (`javascript-excel`) @@ -1014,6 +1015,85 @@ export interface WorkerLike extends MessageEndpoint { terminate(): void } - Code that imports only `createWorkerClient` does not ship the engine: the smoke test bundles it alone and finds no writer, reader or CSV code (5.2 KiB unminified). - Node `worker_threads` is not supported by `/worker` in 2.0 out of the box (its `Worker` is an `EventEmitter`, not an `EventTarget`). A three-line adapter works, and the tests use one. Node users usually call `read`/`toUint8Array` directly. +### 5.6 Format (`javascript-excel/format`) + +Renders a value with an Excel number format, as Excel shows it in a cell: `1234.5` with `#,##0.00` is `1,234.50`, serial `45306` with `dddd, mmmm d, yyyy` is `Monday, January 15, 2024`. It is used by viewers, previews and anything that needs a cell's displayed text. Added in a 2.x minor (§12 Q14); not part of 2.0.0. + +```ts +export function formatValue(value: FormatInput, numFmt?: NumFmt, options?: FormatOptions): FormattedValue; +export function formatCell(cell: CellInput, options?: FormatOptions): FormattedValue; // value + cell.style.numFmt + +export type FormatInput = number | string | boolean | Date | CellErrorValue | RichText | null | undefined; + +export interface FormatOptions { + locale?: string; // BCP 47; default 'en-US' + date1904?: boolean; // workbook.date1904 + dateZone?: 'local' | 'utc'; // only for Date inputs; default 'local', as the writer + generalWidth?: number; // characters for General; default 11 + indexedColors?: readonly string[]; // workbook.indexedColors, for [ColorN] +} + +export interface FormattedValue { + text: string; // without the repeat characters of a *x fill + color?: string; // ARGB from [Red], [Color10], ...; overrides the font colour + fill?: { char: string; at: number }; // *x: repeat char at index `at` until the cell is full + align: 'left' | 'center' | 'right'; // Excel's 'general' alignment for the value type +} +``` + +**Inputs.** +- **Numbers are serials for date formats.** Formatting is pure arithmetic on the serial, never a `Date` in the local zone, so the output is the same in every time zone. For exact results, a viewer reads with `dates: 'serial'` (§5.2). A `Date` input is first converted with `dateToSerial`, using `dateZone` and `date1904`, which is what the writer stores for it. +- **Text** uses the format's text section: the fourth section, or a section with `@`. Without one, text is shown as is. +- **Booleans** show `TRUE`/`FALSE`, errors as written, rich text as its plain text, whatever the format. +- **`formatCell`** formats a cell's value with its own `numFmt`. A formula cell shows its cached value; without one the text is empty. + +**Never throws.** Format codes come from files. Characters the parser does not recognise are shown as literal text, unbalanced quotes and brackets end at the end of the section, and at most four sections are used. Parsing is linear in the code's length. Compiled codes are cached (up to 1,000). + +#### 5.6.1 What is rendered + +| Feature | Codes | Notes | +|---|---|---| +| Sections | `pos;neg;zero;text` | One section: all numbers, with a minus sign for negatives. Two: non-negative; negative without its sign. Three: positive; negative; zero. The fourth is for text | +| Conditions | `[>100]`, `[<=-5]`, `[=0]`, `[<>1]` | The first section whose condition holds wins, and the next section without a condition takes the rest. A section whose condition only admits negatives (`[<0]`) drops the minus sign, like the implicit negative section; other conditional sections keep it `[to verify]` | +| Colours | `[Black] [Blue] [Cyan] [Green] [Magenta] [Red] [White] [Yellow]`, `[Color1]`–`[Color56]` | Returned as `color` (ARGB). `[ColorN]` is indexed colour N + 7, from `indexedColors` or the default palette (§3.5.6) | +| Digit placeholders | `0 # ?` | `0` pads with zeros, `?` with spaces, `#` with nothing; extra integer digits go to the leftmost placeholder; literals between placeholders stay in place (`000-00-0000`) | +| Decimal point, grouping, scaling | `.` `,` | A comma between integer placeholders groups thousands; commas after the last placeholder divide by 1,000 each (`0.0,,` shows millions) | +| Percent | `%` | Multiplies by 100 per `%` | +| Scientific | `E+ E- e+ e-` | `0.00E+00`; with `#` in a multi-digit integer part, the exponent is a multiple of its length (`##0.0E+0`, engineering) | +| Fractions | `# ?/?`, `# ??/??`, `?/8`, `# ??/16` | Best approximation with at most as many denominator digits as placeholders, or a fixed denominator; a whole number blanks the fraction | +| Text | `@`, `"…"`, `\x`, and characters Excel shows unquoted | | +| Spacing and fill | `_x`, `*x` | `_x` gives one space; `*x` is returned as `fill`, not repeated in `text` | +| General | `General`, also inside a section (`"Total: "General`) | Up to `generalWidth` (11) characters: rounded to fit, scientific from 1E+11 and below 1E-04 | +| Dates | `d dd ddd dddd`, `m mm mmm mmmm mmmmm`, `yy yyyy` | `m`/`mm` are minutes right after an hour or right before seconds. Day 0 of the 1900 system shows as `1900-01-00`, serial 60 as `1900-02-29`, and weekdays follow Excel (serial 1 is a Sunday) | +| Times | `h hh m mm s ss`, `AM/PM am/pm A/P a/p`, `.0`–`.000` | Times are rounded to the shown precision before splitting, so `0.99999999` days is the next day `00:00` | +| Elapsed time | `[h] [hh] [m] [mm] [s] [ss]` | Totals beyond 24 hours / 60 minutes; negative values get a minus sign | +| Dates Excel can't show | negative serials, past 9999-12-31 | `text: ''` with `fill: { char: '#' }`: the cell fills with `#`, as in Excel | +| Locale tags | `[$€-407]`, `[$-409]`, `[$-F800]`, `[$-F400]`, `[$-x-sysdate]`, `[$-x-systime]` | The symbol is printed. The locale id switches month and day names for that section (common ids only, `[to verify]` per id). `F800`/`x-sysdate` is the locale's long date and `F400`/`x-systime` its time, from Intl `[to verify against Windows settings]` | +| Era and calendar tokens | `e`, `b`, `bb`, `g` | `e` is the year; `b`/`bb` the Buddhist-era year (+543); `g` era names are not rendered `[to verify]` | +| Not rendered | `[DBNum1]`, `[NatNum1]` and other bracket codes, `B1`/`B2` calendar prefixes | Ignored | + +#### 5.6.2 Built-in ids + +- **Fixed ids:** 1–4, 9–13, 15–21, 37–40 and 45–49 render the codes of §11.2. +- **Short-date ids:** 14 is the locale's short date, numeric with a four-digit year (`1/15/2024` in en-US, `15.01.2024` in de-DE). 22 is that plus ` h:mm`. The East Asian ids 27–36 and 50–58 show the short date too `[to verify per locale]`. +- **Currency and accounting:** ids 5–8 and 41–44 use their en-US codes (`"$"#,##0_);\("$"#,##0\)` and so on) `[to verify for other locales]`. +- **Other ids** render as General. + +#### 5.6.3 Locale + +- **Platform data.** Separators, month and day names and the short-date pattern come from `Intl.NumberFormat` and `Intl.DateTimeFormat` for `locale`, so the module ships no locale tables. +- **Separators.** The `.` and `,` of a format code are replaced by the locale's decimal and group separators, as Excel does with the system settings `[to verify]`. The group separator is the locale's own character; for fr-FR it is a narrow no-break space. +- **Unchanged parts.** Booleans stay `TRUE`/`FALSE`, `AM`/`PM` is shown as written in the code, and grouping is always by three digits `[to verify for locales such as en-IN]`. +- **Invalid locales.** A locale tag Intl rejects falls back to en-US. + +#### 5.6.4 Reference results + +Excel is the authority; LibreOffice is the automated reference. +- **The check.** The `LibreOffice` CI job writes every case of `test/format/cases.ts`, plus every number-formatted cell of the conformance files `10-number-formats` and `11-number-formats-locale`, to one workbook. It has LibreOffice export the workbook to CSV with "save cell contents as shown" in en-US, and compares each cell with `formatCell(cell, { locale: 'en-US' })` (`test/format/libreoffice.test.ts`). +- **Where LibreOffice differs.** Every case where LibreOffice is known to differ is listed in that test with LibreOffice's output. The table below records it, with what this module does and why. Each is `[to verify]` against Excel in the conformance checklist. + +RESULTS_PLACEHOLDER + --- ## 6. Zip codec @@ -1429,7 +1509,7 @@ These were the open questions of the review. Each one is decided, and the sectio **Q13. `toDataset` in 2.0.** Decided (2026-11-16): 2.0 ships the minimal version in §4.3: a fixed header row, deduplicated keys and null-prototype rows. Header auto-detection, multi-row header flattening, column mapping and type inference follow with react-data-import, and live in the engine. -**Q14. Number-format rendering.** Decided (2026-11-16): not in 2.0 (§3.5.5). It is planned as `javascript-excel/format` in a 2.x minor. 2.0's `autoWidth` uses `cellText()`. +**Q14. Number-format rendering.** Decided (2026-11-16): not in 2.0 (§3.5.5). It is planned as `javascript-excel/format` in a 2.x minor. 2.0's `autoWidth` uses `cellText()`. Moved ahead of the other 2.x work (2026-11-16, react-xlsx-viewer's design): the viewer's 1.0 needs it. Designed in §5.6 (JSE-18), independent of the 2.1–2.5 phases because it touches no file parts. **Q15. Worker packaging.** Decided (2026-11-16): the app writes a two-line worker file (§5.5). Every major bundler handles `new Worker(new URL(...))` in app code. Node `worker_threads` support may come later. @@ -1450,8 +1530,8 @@ These were the open questions of the review. Each one is decided, and the sectio | Phase | Adds | |---|---| | 2.0 | xlsx read and write (cells, styles, sheet features), CSV/TSV read and write, HTML table input | -| 2.x | `.xlsm` / `.xltx` / `.xltm` read and write-back with their extra parts preserved; preservation of unknown parts for lossless round trips; comments and notes; data validation; conditional formatting; images (read and write) | -| 3.x | formula parser and evaluator (`javascript-excel/formula`), number-format renderer (`javascript-excel/format`, §12 Q14), charts and drawings (read, plus a render model for the viewer) | +| 2.x | `.xlsm` / `.xltx` / `.xltm` read and write-back with their extra parts preserved; preservation of unknown parts for lossless round trips; comments and notes; data validation; conditional formatting; images (read and write); the number-format renderer `javascript-excel/format` (§5.6, §12 Q14), as its own minor ahead of the others | +| 3.x | formula parser and evaluator (`javascript-excel/formula`), charts and drawings (read, plus a render model for the viewer) | | 4.x | legacy `.xls` (BIFF8) read, then write; `.xlsb` read; encrypted files (password, ECMA-376 agile encryption) | The 2.x row is designed in [design/2x.md](design/2x.md) (decided 2026-11-16: phases 2.1–2.5, dependency order, and what each phase will not do). diff --git a/packages/javascript-excel/src/format.ts b/packages/javascript-excel/src/format.ts index 1151770..c35c52b 100644 --- a/packages/javascript-excel/src/format.ts +++ b/packages/javascript-excel/src/format.ts @@ -64,8 +64,10 @@ const BUILTIN_EXTRA: Readonly> = { 43: '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)', 44: '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)', }; -/** Ids that show the locale's short date: 14, and the East Asian ids 27–36 and 50–58 `[to verify per locale]`. */ -const SHORT_DATE_IDS = new Set([14, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 50, 51, 52, 53, 54, 55, 56, 57, 58]); +/** Ids that show the locale's short date: 14, and the East Asian ids 27–31, 36 and 50–58 `[to verify per locale]`. */ +const SHORT_DATE_IDS = new Set([14, 27, 28, 29, 30, 31, 36, 50, 51, 52, 53, 54, 55, 56, 57, 58]); +/** Ids 32–35 are times in the East Asian locales that define them; shown as h:mm:ss, as LibreOffice does in en-US `[to verify]`. */ +const TIME_IDS = new Set([32, 33, 34, 35]); const compiled = new Map(); const GENERAL: Compiled = compile("General"); @@ -86,6 +88,7 @@ function resolve(numFmt: NumFmt | undefined, loc: LocaleData): Compiled { if (typeof numFmt === "number") { if (SHORT_DATE_IDS.has(numFmt)) return { sections: [shortDateSection(loc, false)] }; if (numFmt === 22) return { sections: [shortDateSection(loc, true)] }; + if (TIME_IDS.has(numFmt)) return compileCached("h:mm:ss"); const code = BUILTIN_NUM_FMTS[numFmt] ?? BUILTIN_EXTRA[numFmt]; return code === undefined ? GENERAL : compileCached(code); } diff --git a/packages/javascript-excel/test/format/format.test.ts b/packages/javascript-excel/test/format/format.test.ts index 5a57f17..80eb7e8 100644 --- a/packages/javascript-excel/test/format/format.test.ts +++ b/packages/javascript-excel/test/format/format.test.ts @@ -68,6 +68,10 @@ describe("built-in ids (en-US)", () => { expect(formatValue(1234, 38).color).toBeUndefined(); }); + it("ids 32–35 are times", () => { + expect(f(0.6458333, 32)).toBe("15:30:00"); + }); + it("unknown ids fall back to General", () => { expect(f(1234.5, 200)).toBe("1234.5"); }); diff --git a/packages/javascript-excel/test/format/libreoffice.test.ts b/packages/javascript-excel/test/format/libreoffice.test.ts index a8484ac..1102d81 100644 --- a/packages/javascript-excel/test/format/libreoffice.test.ts +++ b/packages/javascript-excel/test/format/libreoffice.test.ts @@ -5,8 +5,8 @@ // cell must equal formatCell(cell, { locale: "en-US" }).text. // // LibreOffice is the automated reference, Excel is the authority: where the two are -// known to differ, the case is listed in LIBREOFFICE_DIFFERS with LibreOffice's -// output and the reason, and docs/api.md §5.6 records it as [to verify] in Excel. +// known to differ, a rule in RULES names the reason, and docs/api.md §5.6.4 records +// it as [to verify] in Excel. Any other difference fails the test. // Runs in the `LibreOffice` CI job (JSE_REQUIRE_LIBREOFFICE=1); skipped elsewhere // unless $JSE_SOFFICE is available. import { execFileSync, spawnSync } from "node:child_process"; @@ -15,9 +15,10 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { afterAll, describe, expect, it } from "vitest"; -import { toUint8Array, type Cell, type CellInput, type Workbook } from "../../src/index"; +import { toUint8Array, type Cell, type CellInput, type NumFmt, type Workbook } from "../../src/index"; import { parseCsv } from "../../src/csv"; -import { formatCell } from "../../src/format"; +import { isDateFormat } from "../../src/numfmt"; +import { formatCell, formatValue } from "../../src/format"; import { CORPUS } from "../conformance/corpus"; import { FORMAT_CASES } from "./cases"; @@ -25,8 +26,29 @@ const SOFFICE = process.env["JSE_SOFFICE"] ?? "soffice"; const hasSoffice = spawnSync(SOFFICE, ["--version"], { stdio: "ignore", timeout: 120_000 }).status === 0; if (process.env["JSE_REQUIRE_LIBREOFFICE"] === "1" && !hasSoffice) throw new Error(`LibreOffice check required but soffice (${SOFFICE}) is missing`); -/** `${code} | ${value}` → LibreOffice's output, where LibreOffice is known to differ from formatValue (and why). */ -const LIBREOFFICE_DIFFERS: Record = {}; +/** + * Known ways LibreOffice differs from Excel (and from formatValue). Each rule must prove its + * cause where it can (for example by formatting the value truncated to the second), so an + * unrelated mismatch is never explained away. docs/api.md §5.6.4 lists them. + */ +type Rule = { id: string; why: string; test: (p: Probe, lo: string, ours: string) => boolean }; +const num = (p: Probe): number | undefined => (typeof p.cell.value === "number" ? p.cell.value : undefined); +const code = (p: Probe): NumFmt | undefined => p.cell.style?.numFmt; +const fmt = (v: number, c: NumFmt | undefined): string => formatValue(v, c, { locale: "en-US" }).text; +const truncated = (p: Probe, lo: string): boolean => { + const v = num(p); + if (v === undefined) return false; + return [86_400, 864_000, 1_440].some((n) => fmt(Math.floor(v * n + 1e-9) / n, code(p)) === lo); +}; +const RULES: Rule[] = [ + { id: "1900-calendar", why: "LibreOffice counts every serial from 1899-12-30, so serials below 61 are one day earlier than in Excel, which keeps the fictitious 1900-02-29 (serial 60) and shows serials below 1 as day 0 (1900-01-00)", test: (p) => (num(p) ?? 99) < 61 && isDateFormat(code(p)) }, + { id: "time-rounding", why: "LibreOffice truncates to the shown second (15:29:59.997 shows 15:29:59); Excel rounds to it (15:30:00)", test: (p, lo) => truncated(p, lo) }, + { id: "general", why: "LibreOffice's General shows up to 15 significant digits with no width limit and 3-digit exponents; Excel's General fits the number into 11 characters", test: (p) => code(p) === "General" || code(p) === 0 }, + { id: "dangling-point", why: "LibreOffice drops a decimal point with no digits after it (#,##0.### shows 7); Excel keeps it (7.)", test: (_p, lo, ours) => ours.endsWith(".") && lo === ours.slice(0, -1) }, + { id: "question-mark-space", why: "LibreOffice pads ? placeholders with U+2007 FIGURE SPACE; formatValue uses a plain space, as text copied from Excel has", test: (_p, lo, ours) => lo.replace(/\u2007/g, " ") === ours }, + { id: "builtin-39-40-47", why: "LibreOffice's built-in ids 39, 40 and 47 are #,##0.00_);(#,##0.00), its [Red] twin and mm:ss.0; formatValue renders the codes of ECMA-376 §18.8.30 (§11.2), which conformance file 10 asks to check in Excel", test: (p, lo, ours) => [39, 40, 47].includes(code(p) as number) && (lo === `${ours} ` || lo === fmt(num(p) ?? 0, "mm:ss.0") || truncated({ ...p, cell: { ...p.cell, style: { numFmt: "mm:ss.0" } } }, lo)) }, + { id: "ampm-case", why: "LibreOffice shows am/pm as AM/PM and A/P as a/p; formatValue keeps the case written in the code", test: (_p, lo, ours) => lo.toLowerCase() === ours.toLowerCase() }, +]; interface Probe { label: string; @@ -76,32 +98,32 @@ describe.skipIf(!hasSoffice)("javascript-excel/format against LibreOffice", () = const csv = readFileSync(join(dir, "formats.csv"), "utf8").replace(/^/, ""); const rows = parseCsv(csv, { delimiter: ",", inferTypes: false }).rows; + const escape = (t: string): string => JSON.stringify(t).replace(/[^\x20-\x7e]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`); const mismatches: string[] = []; - const stale: string[] = []; + const explained = new Map(); let matched = 0; list.forEach((p, i) => { const lo = String(rows[i]?.[1] ?? ""); const ours = formatCell(p.cell, { locale: "en-US" }).text; - const known = LIBREOFFICE_DIFFERS[p.label]; - if (known) { - if (lo !== known.libreoffice) stale.push(`${p.label}: LibreOffice now gives ${JSON.stringify(lo)}, listed ${JSON.stringify(known.libreoffice)}`); + if (lo === ours) { + matched++; return; } - if (lo === ours) matched++; - else mismatches.push(`| \`${p.label}\` | \`${JSON.stringify(lo)}\` | \`${JSON.stringify(ours)}\` |`); + const rule = RULES.find((r) => r.test(p, lo, ours)); + if (rule) explained.set(rule.id, [...(explained.get(rule.id) ?? []), `\`${p.label}\`: LibreOffice ${escape(lo)}, formatValue ${escape(ours)}`]); + else mismatches.push(`| \`${p.label}\` | \`${escape(lo)}\` | \`${escape(ours)}\` |`); }); const report = [ `### javascript-excel/format vs LibreOffice`, ``, - `${list.length} probes: ${matched} match, ${Object.keys(LIBREOFFICE_DIFFERS).length} listed differences, ${mismatches.length} unexpected mismatches, ${stale.length} stale entries.`, + `${list.length} probes: ${matched} match, ${[...explained.values()].reduce((n, l) => n + l.length, 0)} differ for a known reason, ${mismatches.length} unexplained.`, ``, ...(mismatches.length ? [`| probe | LibreOffice | formatValue |`, `|---|---|---|`, ...mismatches, ``] : []), - ...stale.map((s) => `- stale: ${s}`), + ...RULES.filter((r) => explained.has(r.id)).flatMap((r) => [`**${r.id}** (${explained.get(r.id)!.length}): ${r.why}`, ...explained.get(r.id)!.map((l) => `- ${l}`), ``]), ].join("\n"); console.log(report); if (process.env["GITHUB_STEP_SUMMARY"]) appendFileSync(process.env["GITHUB_STEP_SUMMARY"], `${report}\n`); - expect(mismatches, "unexpected differences from LibreOffice").toEqual([]); - expect(stale, "listed differences that changed").toEqual([]); + expect(mismatches, "unexplained differences from LibreOffice").toEqual([]); }); }); From 68d2df8dca452b1ecd9182effef1a55e1bc2a850 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Mon, 16 Nov 2026 14:20:52 +0100 Subject: [PATCH 3/6] =?UTF-8?q?JSE-18:=20docs=20(=C2=A75.6),=20conformance?= =?UTF-8?q?=20Display=20sheet,=20README=20snippet,=20API=20reference,=20ch?= =?UTF-8?q?angeset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .changeset/number-format-renderer.md | 5 +++++ docs/api.md | 16 +++++++++++++-- docs/conformance.md | 2 ++ examples/snippets/src/format.ts | 10 ++++++++++ packages/javascript-excel/README.md | 17 ++++++++++++++++ packages/javascript-excel/src/format.ts | 4 ++-- .../test/conformance/corpus.ts | 20 +++++++++++++++++++ .../test/format/libreoffice.test.ts | 5 +++-- tools/api-docs/typedoc.json | 3 ++- 9 files changed, 75 insertions(+), 7 deletions(-) create mode 100644 .changeset/number-format-renderer.md create mode 100644 examples/snippets/src/format.ts diff --git a/.changeset/number-format-renderer.md b/.changeset/number-format-renderer.md new file mode 100644 index 0000000..f8018d8 --- /dev/null +++ b/.changeset/number-format-renderer.md @@ -0,0 +1,5 @@ +--- +"javascript-excel": minor +--- + +New entry `javascript-excel/format`: `formatValue(value, numFmt, options)` and `formatCell(cell, options)` render values the way Excel shows them in a cell. They cover number-format sections, conditions and colours, digit placeholders, grouping and scaling, percent, scientific, fractions, text, `_x` spacing and `*x` fills, General, dates and times from serials (time-zone free), elapsed time, built-in ids and locale tags. Separators, month and day names and the short date come from `Intl` for the given locale. diff --git a/docs/api.md b/docs/api.md index 1a834e6..7a8d409 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1075,7 +1075,7 @@ export interface FormattedValue { #### 5.6.2 Built-in ids - **Fixed ids:** 1–4, 9–13, 15–21, 37–40 and 45–49 render the codes of §11.2. -- **Short-date ids:** 14 is the locale's short date, numeric with a four-digit year (`1/15/2024` in en-US, `15.01.2024` in de-DE). 22 is that plus ` h:mm`. The East Asian ids 27–36 and 50–58 show the short date too `[to verify per locale]`. +- **Short-date ids:** 14 is the locale's short date, numeric with a four-digit year (`1/15/2024` in en-US, `15.01.2024` in de-DE). 22 is that plus ` h:mm`. The East Asian ids 27–31, 36 and 50–58 show the short date too, and 32–35 show `h:mm:ss` `[to verify per locale]`. - **Currency and accounting:** ids 5–8 and 41–44 use their en-US codes (`"$"#,##0_);\("$"#,##0\)` and so on) `[to verify for other locales]`. - **Other ids** render as General. @@ -1092,7 +1092,19 @@ Excel is the authority; LibreOffice is the automated reference. - **The check.** The `LibreOffice` CI job writes every case of `test/format/cases.ts`, plus every number-formatted cell of the conformance files `10-number-formats` and `11-number-formats-locale`, to one workbook. It has LibreOffice export the workbook to CSV with "save cell contents as shown" in en-US, and compares each cell with `formatCell(cell, { locale: 'en-US' })` (`test/format/libreoffice.test.ts`). - **Where LibreOffice differs.** Every case where LibreOffice is known to differ is listed in that test with LibreOffice's output. The table below records it, with what this module does and why. Each is `[to verify]` against Excel in the conformance checklist. -RESULTS_PLACEHOLDER +Result in CI (LibreOffice 26.2, en-US): RESULT_COUNTS. Every difference has one of the known causes below. Any other difference fails the job. + +| Difference | LibreOffice | `formatValue` (Excel's behaviour, `[to verify]`) | +|---|---|---| +| Serials below 61 (the 1900 calendar) | Counts from 1899-12-30: serial 1 is 1899-12-31, no 1900-02-29, no day 0 | Serial 1 is 1900-01-01, 60 is 1900-02-29, below 1 is day 0 (`1900-01-00`), as Excel | +| Time rounding | Truncates to the shown unit: 0.6458333 is `15:29:59`, `3:29 PM` | Rounds to the shown second first: `15:30:00`, `3:30 PM`; 45306.99999999 with `yyyy-mm-dd` is the next day | +| General | Up to 15 significant digits, no width limit, 3-digit exponents (`0.333333333333333`, `1E+021`) | Fits 11 characters (`0.333333333`, `1E+21`, `1.23457E+11`) | +| A decimal point with no digits after it | Dropped: `#,##0.###` shows `7` | Kept: `7.` | +| `?` padding | U+2007 FIGURE SPACE | A plain space, as text copied from Excel has | +| Built-in ids 39, 40, 47 | Excel's actual codes, `#,##0.00_);(#,##0.00)` and `mm:ss.0` | The ECMA-376 codes in §11.2 (`#,##0.00;(#,##0.00)`, `mmss.0`); conformance file 10 asks for the codes Excel shows | +| `am/pm` and `A/P` case | `AM/PM` upper-cased, `A/P` lower-cased | As written in the code | + +Built-in ids 32–35 are rendered as `h:mm:ss`, which matches LibreOffice in en-US: they are times in the East Asian locales that define them `[to verify]`. --- diff --git a/docs/conformance.md b/docs/conformance.md index 48e1005..4af305d 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -130,6 +130,7 @@ Covers every built-in id the spec defines (0–4, 9–22, 37–40, 45–49) and |---|---|---|---|---|---| | Built-in!C2:C29 | For each row, open Format Cells > Number > Custom and read the selected code. | The code matches column B (ids 14 and 22 may show your locale's date format). Write down the exact code Excel shows for ids 37, 38, 39, 40 and 47, including spaces. **(open item)** | | | | | Custom!B2:B7 | Compare column B with column C. | Everything matches. | | | | +| Display!B2:B17 | Compare column B with column C. Widen column B if a value shows ####. | Everything matches. Write down every row that differs. **(open item)** | | | | ### 11-number-formats-locale.xlsx: Locale-dependent built-in number formats @@ -231,6 +232,7 @@ These facts are marked `[to verify]` in `docs/api.md`. Each one is checked by th |---|---|---| | indent maximum 250 (§3.5.4) | `09-alignment.xlsx` | Alignment!B20 | | codes and spacing of built-in formats 37–40 and 47 (§11.2) | `10-number-formats.xlsx` | Built-in!C2:C29 | +| how Excel displays day 0, rounded times, General, a dangling decimal point, am/pm case, conditional sections, built-in id 32 and bbbb (§5.6.4) | `10-number-formats.xlsx` | Display!B2:B17 | | ids 27–36 and 50–58 are date formats (§3.4.1) | `11-number-formats-locale.xlsx` | Locale ids!B2:C32 | | theme index order: 0 = lt1, 1 = dk1, 2 = lt2, 3 = dk2 (§3.5.6) | `12-colours.xlsx` | Theme!B2:B13 | | indexed 64 = system foreground, 65 = system background (§3.5.6) | `12-colours.xlsx` | Indexed!C66:C67 | diff --git a/examples/snippets/src/format.ts b/examples/snippets/src/format.ts new file mode 100644 index 0000000..521fa91 --- /dev/null +++ b/examples/snippets/src/format.ts @@ -0,0 +1,10 @@ +import { formatCell, formatValue } from "javascript-excel/format"; +import { read } from "javascript-excel/read"; + +formatValue(1234.5, "#,##0.00"); // { text: "1,234.50", align: "right" } +formatValue(-12.5, "0.0;[Red]-0.0").color; // "FFFF0000" +formatValue(45306, "dddd, mmmm d, yyyy", { locale: "de-DE" }).text; // "Montag, Januar 15, 2024" + +declare const file: Blob; +const { workbook } = await read(file, { dates: "serial" }); // serials: formatting does not depend on the time zone +const shown = formatCell(workbook.sheets[0]?.rows[0]?.[0], { locale: navigator.language, date1904: workbook.date1904 }); diff --git a/packages/javascript-excel/README.md b/packages/javascript-excel/README.md index adc6d13..6722b53 100644 --- a/packages/javascript-excel/README.md +++ b/packages/javascript-excel/README.md @@ -15,6 +15,7 @@ npm install javascript-excel@next | `javascript-excel/csv` | CSV parse and serialize | | `javascript-excel/dom` | HTML `` to sheet, `download()` | | `javascript-excel/worker` | run big jobs in a Web Worker | +| `javascript-excel/format` | show values as Excel does: number formats, dates, colours (2.x) | Each entry pulls in only what it needs: a writer-only app never ships the reader, the CSV code or the DOM code. @@ -107,6 +108,22 @@ const sheet = fromTable(table, { styles: "computed", freezeHeader: true, autoWid download(await toBlob({ sheets: [sheet] }), "report.xlsx"); ``` +## Number formats + + +```ts +import { formatCell, formatValue } from "javascript-excel/format"; +import { read } from "javascript-excel/read"; + +formatValue(1234.5, "#,##0.00"); // { text: "1,234.50", align: "right" } +formatValue(-12.5, "0.0;[Red]-0.0").color; // "FFFF0000" +formatValue(45306, "dddd, mmmm d, yyyy", { locale: "de-DE" }).text; // "Montag, Januar 15, 2024" + +declare const file: Blob; +const { workbook } = await read(file, { dates: "serial" }); // serials: formatting does not depend on the time zone +const shown = formatCell(workbook.sheets[0]?.rows[0]?.[0], { locale: navigator.language, date1904: workbook.date1904 }); +``` + ## In a Web Worker diff --git a/packages/javascript-excel/src/format.ts b/packages/javascript-excel/src/format.ts index c35c52b..3f95d50 100644 --- a/packages/javascript-excel/src/format.ts +++ b/packages/javascript-excel/src/format.ts @@ -10,6 +10,8 @@ * @module javascript-excel/format */ +export type { Cell, CellErrorValue, CellInput, NumFmt, RichText } from "./model"; + import { cellText } from "./cells"; import { dateToSerial } from "./dates"; import { compile, type Compiled, type Section } from "./internal/format/parse"; @@ -19,8 +21,6 @@ import { formatNumber, general } from "./internal/format/number"; import type { Cell, CellErrorValue, CellInput, NumFmt, RichText } from "./model"; import { BUILTIN_NUM_FMTS } from "./numfmt"; -export type { Cell, CellErrorValue, CellInput, NumFmt, RichText } from "./model"; - /** What `formatValue` accepts: a cell's value. A Date is converted to a serial first (`dateZone`, `date1904`). */ export type FormatInput = number | string | boolean | Date | CellErrorValue | RichText | null | undefined; diff --git a/packages/javascript-excel/test/conformance/corpus.ts b/packages/javascript-excel/test/conformance/corpus.ts index a47082e..fd66a05 100644 --- a/packages/javascript-excel/test/conformance/corpus.ts +++ b/packages/javascript-excel/test/conformance/corpus.ts @@ -355,11 +355,31 @@ export const CORPUS: CorpusEntry[] = [ ["Text placeholder", { value: "abc", style: { numFmt: '"<"@">"' } }, ""], ["'General' as a string", { value: 1234.5, style: { numFmt: "General" } }, "1234.5 (built-in General)"], ]), + // How javascript-excel/format (docs/api.md §5.6.4) expects Excel to display these; LibreOffice differs on most. + labelled("Display", [ + ["Day 0 (serial 0.5)", { value: 0.5, style: { numFmt: "yyyy-mm-dd hh:mm" } }, "1900-01-00 12:00"], + ["Serial 1 weekday", { value: 1, style: { numFmt: "dddd" } }, "Sunday"], + ["Seconds round (0.6458333)", { value: 0.6458333, style: { numFmt: "h:mm:ss" } }, "15:30:00"], + ["Rounds into the next day", { value: 45306.99999999, style: { numFmt: "yyyy-mm-dd hh:mm:ss" } }, "2024-01-16 00:00:00"], + ["Date only, same value", { value: 45306.99999999, style: { numFmt: "yyyy-mm-dd" } }, "2024-01-16"], + ["General 1/3 (default width)", { value: 1 / 3, style: { numFmt: "General" } }, "0.333333333"], + ["General 123456789012", { value: 123456789012, style: { numFmt: "General" } }, "1.23457E+11"], + ["General 0.00001", { value: 0.00001, style: { numFmt: "General" } }, "1E-05"], + ["Dangling decimal point", { value: 7, style: { numFmt: "#,##0.###" } }, "7."], + ["Lower-case am/pm", { value: 0.5, style: { numFmt: "h am/pm" } }, "12 pm"], + ["A/P", { value: 0.75, style: { numFmt: "h:mm A/P" } }, "6:00 P"], + ["Negative in a [<0] section", { value: -1, style: { numFmt: '[>100]"big";[<0]"neg";"small"' } }, "neg"], + ["Negative in [<1000]", { value: -5, style: { numFmt: "[<1000]0;[>=1000]#,##0" } }, "-5"], + ["-0.001 as 0.00", { value: -0.001, style: { numFmt: "0.00" } }, "0.00 (no minus sign)"], + ["Built-in id 32", { value: 0.6458333, style: { numFmt: 32 } }, "15:30:00, or your locale's time format"], + ["Buddhist year (bbbb)", { value: 45306, style: { numFmt: "bbbb" } }, "2567"], + ]), ], }), checks: [ { where: "Built-in!C2:C29", look: "For each row, open Format Cells > Number > Custom and read the selected code.", expect: "The code matches column B (ids 14 and 22 may show your locale's date format). Write down the exact code Excel shows for ids 37, 38, 39, 40 and 47, including spaces.", verifies: "codes and spacing of built-in formats 37–40 and 47 (§11.2)" }, { where: "Custom!B2:B7", look: "Compare column B with column C.", expect: "Everything matches." }, + { where: "Display!B2:B17", look: "Compare column B with column C. Widen column B if a value shows ####.", expect: "Everything matches. Write down every row that differs.", verifies: "how Excel displays day 0, rounded times, General, a dangling decimal point, am/pm case, conditional sections, built-in id 32 and bbbb (§5.6.4)" }, ], }, { diff --git a/packages/javascript-excel/test/format/libreoffice.test.ts b/packages/javascript-excel/test/format/libreoffice.test.ts index 1102d81..2b0b4ea 100644 --- a/packages/javascript-excel/test/format/libreoffice.test.ts +++ b/packages/javascript-excel/test/format/libreoffice.test.ts @@ -29,7 +29,8 @@ if (process.env["JSE_REQUIRE_LIBREOFFICE"] === "1" && !hasSoffice) throw new Err /** * Known ways LibreOffice differs from Excel (and from formatValue). Each rule must prove its * cause where it can (for example by formatting the value truncated to the second), so an - * unrelated mismatch is never explained away. docs/api.md §5.6.4 lists them. + * unrelated mismatch is never explained away. The first rule that holds wins, so the broad + * calendar rule comes last. docs/api.md §5.6.4 lists them. */ type Rule = { id: string; why: string; test: (p: Probe, lo: string, ours: string) => boolean }; const num = (p: Probe): number | undefined => (typeof p.cell.value === "number" ? p.cell.value : undefined); @@ -41,13 +42,13 @@ const truncated = (p: Probe, lo: string): boolean => { return [86_400, 864_000, 1_440].some((n) => fmt(Math.floor(v * n + 1e-9) / n, code(p)) === lo); }; const RULES: Rule[] = [ - { id: "1900-calendar", why: "LibreOffice counts every serial from 1899-12-30, so serials below 61 are one day earlier than in Excel, which keeps the fictitious 1900-02-29 (serial 60) and shows serials below 1 as day 0 (1900-01-00)", test: (p) => (num(p) ?? 99) < 61 && isDateFormat(code(p)) }, { id: "time-rounding", why: "LibreOffice truncates to the shown second (15:29:59.997 shows 15:29:59); Excel rounds to it (15:30:00)", test: (p, lo) => truncated(p, lo) }, { id: "general", why: "LibreOffice's General shows up to 15 significant digits with no width limit and 3-digit exponents; Excel's General fits the number into 11 characters", test: (p) => code(p) === "General" || code(p) === 0 }, { id: "dangling-point", why: "LibreOffice drops a decimal point with no digits after it (#,##0.### shows 7); Excel keeps it (7.)", test: (_p, lo, ours) => ours.endsWith(".") && lo === ours.slice(0, -1) }, { id: "question-mark-space", why: "LibreOffice pads ? placeholders with U+2007 FIGURE SPACE; formatValue uses a plain space, as text copied from Excel has", test: (_p, lo, ours) => lo.replace(/\u2007/g, " ") === ours }, { id: "builtin-39-40-47", why: "LibreOffice's built-in ids 39, 40 and 47 are #,##0.00_);(#,##0.00), its [Red] twin and mm:ss.0; formatValue renders the codes of ECMA-376 §18.8.30 (§11.2), which conformance file 10 asks to check in Excel", test: (p, lo, ours) => [39, 40, 47].includes(code(p) as number) && (lo === `${ours} ` || lo === fmt(num(p) ?? 0, "mm:ss.0") || truncated({ ...p, cell: { ...p.cell, style: { numFmt: "mm:ss.0" } } }, lo)) }, { id: "ampm-case", why: "LibreOffice shows am/pm as AM/PM and A/P as a/p; formatValue keeps the case written in the code", test: (_p, lo, ours) => lo.toLowerCase() === ours.toLowerCase() }, + { id: "1900-calendar", why: "LibreOffice counts every serial from 1899-12-30, so serials below 61 are one day earlier than in Excel, which keeps the fictitious 1900-02-29 (serial 60) and shows serials below 1 as day 0 (1900-01-00)", test: (p, lo, ours) => (num(p) ?? 99) < 61 && isDateFormat(code(p)) && !truncated(p, lo) && lo.toLowerCase() !== ours.toLowerCase() }, ]; interface Probe { diff --git a/tools/api-docs/typedoc.json b/tools/api-docs/typedoc.json index 0dc6d21..eb30124 100644 --- a/tools/api-docs/typedoc.json +++ b/tools/api-docs/typedoc.json @@ -6,7 +6,8 @@ "../../packages/javascript-excel/dist/read.d.ts", "../../packages/javascript-excel/dist/csv.d.ts", "../../packages/javascript-excel/dist/dom.d.ts", - "../../packages/javascript-excel/dist/worker.d.ts" + "../../packages/javascript-excel/dist/worker.d.ts", + "../../packages/javascript-excel/dist/format.d.ts" ], "tsconfig": "./tsconfig.json", "out": "out", From 605a522e428d29805e733ffd1000c57becf412a3 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Mon, 16 Nov 2026 14:21:37 +0100 Subject: [PATCH 4/6] JSE-18: cache locale data by the requested tag --- packages/javascript-excel/src/internal/format/locale.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/javascript-excel/src/internal/format/locale.ts b/packages/javascript-excel/src/internal/format/locale.ts index dd0b12f..5184aec 100644 --- a/packages/javascript-excel/src/internal/format/locale.ts +++ b/packages/javascript-excel/src/internal/format/locale.ts @@ -26,12 +26,15 @@ function supported(tag: string): string { } } +/** Locale data for a requested tag, cached by the tag as given (canonicalising is not free). */ export function localeData(requested: string | undefined): LocaleData { - const tag = supported(requested ?? "en-US"); - let data = cache.get(tag); + const key = requested ?? "en-US"; + let data = cache.get(key); if (!data) { - data = build(tag); + const tag = supported(key); + data = (tag !== key ? cache.get(tag) : undefined) ?? build(tag); if (cache.size > 50) cache.clear(); + cache.set(key, data); cache.set(tag, data); } return data; From c7641c25233cd7291afb960d219319009d7febc7 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Mon, 16 Nov 2026 14:24:19 +0100 Subject: [PATCH 5/6] JSE-18: LibreOffice has no Buddhist-year tokens --- docs/api.md | 1 + packages/javascript-excel/test/format/libreoffice.test.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/api.md b/docs/api.md index 7a8d409..2e4a4a9 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1103,6 +1103,7 @@ Result in CI (LibreOffice 26.2, en-US): RESULT_COUNTS. Every difference has one | `?` padding | U+2007 FIGURE SPACE | A plain space, as text copied from Excel has | | Built-in ids 39, 40, 47 | Excel's actual codes, `#,##0.00_);(#,##0.00)` and `mm:ss.0` | The ECMA-376 codes in §11.2 (`#,##0.00;(#,##0.00)`, `mmss.0`); conformance file 10 asks for the codes Excel shows | | `am/pm` and `A/P` case | `AM/PM` upper-cased, `A/P` lower-cased | As written in the code | +| `b`, `bb`, `bbbb` | Not known; printed as text | The Buddhist-era year (Gregorian + 543) | Built-in ids 32–35 are rendered as `h:mm:ss`, which matches LibreOffice in en-US: they are times in the East Asian locales that define them `[to verify]`. diff --git a/packages/javascript-excel/test/format/libreoffice.test.ts b/packages/javascript-excel/test/format/libreoffice.test.ts index 2b0b4ea..701118a 100644 --- a/packages/javascript-excel/test/format/libreoffice.test.ts +++ b/packages/javascript-excel/test/format/libreoffice.test.ts @@ -47,6 +47,7 @@ const RULES: Rule[] = [ { id: "dangling-point", why: "LibreOffice drops a decimal point with no digits after it (#,##0.### shows 7); Excel keeps it (7.)", test: (_p, lo, ours) => ours.endsWith(".") && lo === ours.slice(0, -1) }, { id: "question-mark-space", why: "LibreOffice pads ? placeholders with U+2007 FIGURE SPACE; formatValue uses a plain space, as text copied from Excel has", test: (_p, lo, ours) => lo.replace(/\u2007/g, " ") === ours }, { id: "builtin-39-40-47", why: "LibreOffice's built-in ids 39, 40 and 47 are #,##0.00_);(#,##0.00), its [Red] twin and mm:ss.0; formatValue renders the codes of ECMA-376 §18.8.30 (§11.2), which conformance file 10 asks to check in Excel", test: (p, lo, ours) => [39, 40, 47].includes(code(p) as number) && (lo === `${ours} ` || lo === fmt(num(p) ?? 0, "mm:ss.0") || truncated({ ...p, cell: { ...p.cell, style: { numFmt: "mm:ss.0" } } }, lo)) }, + { id: "buddhist-year", why: "LibreOffice does not know the b/bb/bbbb Buddhist-era year tokens and prints them as text", test: (p, lo) => typeof code(p) === "string" && /b/i.test(code(p) as string) && /b/i.test(lo) }, { id: "ampm-case", why: "LibreOffice shows am/pm as AM/PM and A/P as a/p; formatValue keeps the case written in the code", test: (_p, lo, ours) => lo.toLowerCase() === ours.toLowerCase() }, { id: "1900-calendar", why: "LibreOffice counts every serial from 1899-12-30, so serials below 61 are one day earlier than in Excel, which keeps the fictitious 1900-02-29 (serial 60) and shows serials below 1 as day 0 (1900-01-00)", test: (p, lo, ours) => (num(p) ?? 99) < 61 && isDateFormat(code(p)) && !truncated(p, lo) && lo.toLowerCase() !== ours.toLowerCase() }, ]; From 83bc5e2343ecd3bb8efbe9c775734b5f8d77ff55 Mon Sep 17 00:00:00 2001 From: Afzal Ahmad Date: Mon, 16 Nov 2026 14:26:30 +0100 Subject: [PATCH 6/6] =?UTF-8?q?JSE-18:=20reference=20results=20in=20=C2=A7?= =?UTF-8?q?5.6.4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api.md b/docs/api.md index 2e4a4a9..ac6266b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1092,7 +1092,7 @@ Excel is the authority; LibreOffice is the automated reference. - **The check.** The `LibreOffice` CI job writes every case of `test/format/cases.ts`, plus every number-formatted cell of the conformance files `10-number-formats` and `11-number-formats-locale`, to one workbook. It has LibreOffice export the workbook to CSV with "save cell contents as shown" in en-US, and compares each cell with `formatCell(cell, { locale: 'en-US' })` (`test/format/libreoffice.test.ts`). - **Where LibreOffice differs.** Every case where LibreOffice is known to differ is listed in that test with LibreOffice's output. The table below records it, with what this module does and why. Each is `[to verify]` against Excel in the conformance checklist. -Result in CI (LibreOffice 26.2, en-US): RESULT_COUNTS. Every difference has one of the known causes below. Any other difference fails the job. +Result in CI (LibreOffice 26.2, en-US): 439 probes, 344 identical, 95 different for a known reason (1900 calendar 27, time rounding 27, General 12, dangling point 7, built-in ids 39/40/47 7, `?` padding 9, am/pm case 5, Buddhist year 1), 0 unexplained. Every difference has one of the known causes below. Any other difference fails the job. | Difference | LibreOffice | `formatValue` (Excel's behaviour, `[to verify]`) | |---|---|---|