Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(share/spreadsheet): display proper number & date formats
Elian Doranb8d77924eeb8
diff --git a/packages/commons/package.json b/packages/commons/package.jsonindex ed078385c6..151c106d95 100644--- a/packages/commons/package.json+++ b/packages/commons/package.json@@ -17,6 +17,7 @@"dependencies": {"dayjs": "1.11.21","marked": "18.0.4",- "marked-footnote": "1.4.0"+ "marked-footnote": "1.4.0",+ "numfmt": "3.2.6"}}\ No newline at end of filediff --git a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_html.spec.tsindex 853e18b5cb..1e245cf6dd 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts@@ -935,6 +935,127 @@ describe("renderSpreadsheetToHtml", () => {expect(html).not.toContain("colspan");});+ it("formats a numeric cell using its number-format pattern", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({ v: 1234.5, t: 2, s: { n: { pattern: "#,##0.00" } } })+ );+ expect(html).toContain("<td>1,234.50</td>");+ expect(html).not.toContain("1234.5<");+ });++ it("formats a numeric cell via a style referenced by id", () => {+ const input = JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: ["s1"],+ styles: {+ money: { n: { pattern: "#,##0.00" } }+ },+ sheets: {+ s1: {+ id: "s1",+ name: "Sheet1",+ hidden: 0,+ rowCount: 10,+ columnCount: 5,+ mergeData: [],+ cellData: { "0": { "0": { s: "money", v: 1000000, t: 2 } } },+ rowData: {},+ columnData: {}+ }+ }+ }+ });+ const html = renderSpreadsheetToHtml(input);+ expect(html).toContain("1,000,000.00");+ });++ it("applies the [Red] negative color from the pattern as a text color", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({ v: -8800.2, t: 2, s: { n: { pattern: "#,##0.00;[Red]#,##0.00" } } })+ );+ // Negative section has no minus sign -> value shown unsigned, in red.+ expect(html).toContain("8,800.20");+ expect(html).not.toContain("-8,800.20");+ expect(html).toContain("color:red");+ });++ it("does not apply the pattern color to a positive value", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({ v: 12.5, t: 2, s: { n: { pattern: "#,##0.00;[Red]#,##0.00" } } })+ );+ expect(html).toContain("12.50");+ expect(html).not.toContain("color:red");+ });++ it("lets the pattern's negative color win over an explicit cell color (matching Univer)", () => {+ // In the Univer editor, a [Red] negative section overrides an explicit text+ // color: setting a different color on a negative cell does not take effect.+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ v: -5,+ t: 2,+ s: { n: { pattern: "#,##0.00;[Red]#,##0.00" }, cl: { rgb: "#0da471" } }+ })+ );+ expect(html).toContain("color:red");+ expect(html).not.toContain("color:#0da471");+ });++ it("uses the explicit cell color when the pattern yields no color for the value", () => {+ // Positive value -> the [Red] section never applies, so cl is used.+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ v: 5,+ t: 2,+ s: { n: { pattern: "#,##0.00;[Red]#,##0.00" }, cl: { rgb: "#0da471" } }+ })+ );+ expect(html).toContain("color:#0da471");+ });++ it("formats percentages and dates", () => {+ const percent = renderSpreadsheetToHtml(+ singleCellWorkbook({ v: 0.156, t: 2, s: { n: { pattern: "0.0%" } } })+ );+ expect(percent).toContain("15.6%");++ const date = renderSpreadsheetToHtml(+ singleCellWorkbook({ v: 45000, t: 2, s: { n: { pattern: "yyyy-mm-dd" } } })+ );+ expect(date).toContain("2023-03-15");+ });++ it("escapes formatted output that contains HTML-significant characters", () => {+ // A pattern that wraps the number in literal angle brackets.+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({ v: 5, t: 2, s: { n: { pattern: "\"<b>\"0\"</b>\"" } } })+ );+ expect(html).not.toContain("<b>5</b>");+ expect(html).toContain("<b>5</b>");+ });++ it("leaves a string cell untouched even when a number pattern is present", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({ v: "n/a", t: 1, s: { n: { pattern: "#,##0.00" } } })+ );+ expect(html).toContain("<td>n/a</td>");+ });++ it("falls back to the raw value for an invalid pattern instead of throwing", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({ v: 42, t: 2, s: { n: { pattern: "[" } } })+ );+ // Must not throw; the cell still renders something containing the digits.+ expect(html).toContain("<table");+ expect(html).toContain("42");+ });++ it("renders an unformatted number when no pattern is set", () => {+ const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: 1234.5, t: 2 }));+ expect(html).toContain("<td>1234.5</td>");+ });+it("extends bounds to cover a merge range that exceeds the cell data", () => {const input = JSON.stringify({version: 1,diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.tsindex ca6a845acd..483b8c6ac7 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts@@ -4,8 +4,14 @@** Only the subset of UniversJS types needed for rendering is defined here,* to avoid depending on @univerjs/core.+ *+ * Number formatting is delegated to the `numfmt` library — the same ECMA-376+ * formatter Univer itself uses internally (`@univerjs/core` re-exports it) — so+ * shared output matches what the editor displays.*/+import { format as formatNumfmt, formatColor as formatNumfmtColor } from "numfmt";+// #region UniversJS type subsetinterface PersistedData {@@ -54,6 +60,11 @@ interface IStyleData {ht?: number | null;vt?: number | null;bd?: IBorderData | null;+ n?: INumberFormat | null;+}++interface INumberFormat {+ pattern?: string | null;}interface ITextDecoration {@@ -199,8 +210,8 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |const cell = cellData[row]?.[col];const cellStyle = resolveCellStyle(cell, styles);- const cssText = buildCssText(cellStyle);- const value = formatCellValue(cell);+ const cssText = buildCssText(cellStyle, cell);+ const value = formatCellValue(cell, cellStyle);const attrs: string[] = [];if (cssText) attrs.push(`style="${cssText}"`);@@ -312,7 +323,7 @@ function resolveCellStyle(cell: ICellData | undefined, styles: Record<string, ISreturn cell.s;}-function buildCssText(style: IStyleData | null): string {+function buildCssText(style: IStyleData | null, cell?: ICellData): string {if (!style) return "";const parts: string[] = [];@@ -332,7 +343,12 @@ function buildCssText(style: IStyleData | null): string {if (style.fs && isFiniteNumber(style.fs)) parts.push(`font-size:${style.fs}pt`);if (style.ff) parts.push(`font-family:${sanitizeCssValue(style.ff)}`);if (style.bg?.rgb) parts.push(`background-color:${sanitizeCssColor(style.bg.rgb)}`);- if (style.cl?.rgb) parts.push(`color:${sanitizeCssColor(style.cl.rgb)}`);++ // A color produced by the number-format pattern (e.g. `[Red]` for negatives) takes+ // precedence over the cell's own text color, matching Univer's rendering.+ const patternColor = resolvePatternColor(style, cell);+ const textColor = patternColor ?? style.cl?.rgb;+ if (textColor) parts.push(`color:${sanitizeCssColor(textColor)}`);if (style.ht != null) {const align = horizontalAlignToCss(style.ht);@@ -428,16 +444,45 @@ function sanitizeCssColor(value: string): string {// #region Value formatting-function formatCellValue(cell: ICellData | undefined): string {+function formatCellValue(cell: ICellData | undefined, style: IStyleData | null): string {if (!cell || cell.v == null) return "";if (typeof cell.v === "boolean") {return cell.v ? "TRUE" : "FALSE";}+ // Apply the number-format pattern to numeric values (this also covers dates,+ // which Univer stores as serial numbers with a date pattern). On an invalid or+ // unsupported pattern, fall back to the raw value rather than losing the data.+ const pattern = style?.n?.pattern;+ if (pattern && isFiniteNumber(cell.v)) {+ try {+ return escapeHtml(formatNumfmt(pattern, cell.v));+ } catch {+ // Fall through to the raw value.+ }+ }+return escapeHtml(String(cell.v));}+/**+ * Returns the text color dictated by a number-format pattern for this cell's value+ * (e.g. `[Red]` on the negative section), or `null` when the pattern specifies no+ * color for the value or the cell is not a formatted number.+ */+function resolvePatternColor(style: IStyleData | null, cell: ICellData | undefined): string | null {+ const pattern = style?.n?.pattern;+ if (!pattern || !cell || !isFiniteNumber(cell.v)) return null;++ try {+ const color = formatNumfmtColor(pattern, cell.v);+ return typeof color === "string" ? color : null;+ } catch {+ return null;+ }+}+function escapeHtml(text: string): string {return text.replace(/&/g, "&")diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex eba88ff05c..51ee7bca98 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1529,6 +1529,9 @@ importers:marked-footnote:specifier: 1.4.0version: 1.4.0([email protected])+ numfmt:+ specifier: 3.2.6+ version: 3.2.6packages/express-partial-content: {}@@ -2530,7 +2533,7 @@ packages:engines: {node: '>=14'}'@electron/node-gyp@https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2':- resolution: {gitHosted: true, integrity: sha512-MXgzlTDEEndJB3TBbvd5uFQO/8gaINo1Hfen8vef5rq/VHVPeB63uuv/uO5+8GFsAJ/rauu6XB79S6K4+aXc+w==, tarball: https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2}+ resolution: {gitHosted: true, tarball: https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2}version: 10.2.0-electron.1engines: {node: '>=12.13.0'}hasBin: true