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(spreadsheet): darken cell colors the way Univer does
Elian Doran827a583351e2
diff --git a/apps/client/src/services/spreadsheet_dark_mode.spec.ts b/apps/client/src/services/spreadsheet_dark_mode.spec.tsnew file mode 100644index 0000000000..968206cd1b--- /dev/null+++ b/apps/client/src/services/spreadsheet_dark_mode.spec.ts@@ -0,0 +1,59 @@+import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";+import { invertColorByMatrix } from "@univerjs/core";+import { describe, expect, it } from "vitest";++/**+ * A previewed sheet has to darken the way the editor does, so the renderer inverts colors with+ * Univer's own matrix. This checks the two agree by running Univer's function, which lives in a+ * dependency only the client has — hence a spec here rather than beside the renderer.+ *+ * What happy-dom cannot help with is `light-dark()`: it does not evaluate the function, so the+ * pairing is asserted as emitted CSS in render_to_html.spec.ts rather than as a computed color.+ */+function darkHalfOf(rgb: string): string | undefined {+ const workbook = JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: ["s1"], styles: {},+ sheets: {+ s1: {+ id: "s1", name: "S", hidden: 0, rowCount: 5, columnCount: 5, showGridlines: 0,+ mergeData: [], cellData: { "0": { "0": { v: "x", t: 1, s: { cl: { rgb } } } } },+ rowData: {}, columnData: {}+ }+ }+ }+ });+ return /color:light-dark\([^,]+,(#[0-9a-f]{6})\)/.exec(renderSpreadsheetToHtml(workbook))?.[1];+}++function univerDarkHalfOf(rgb: string): string {+ const channel = (at: number) => Number.parseInt(rgb.slice(at, at + 2), 16);+ const inverted = invertColorByMatrix([channel(1), channel(3), channel(5)]);++ return "#" + inverted.map((value) => Math.round(value).toString(16).padStart(2, "0")).join("");+}++describe("dark-mode colors match Univer", () => {+ it("agrees on the fills, text and edges a real workbook carries", () => {+ for (const color of [+ "#FFE699", "#FFD966", "#DBDBDB", "#F2F2F2", // fills from the sample workbooks+ "#000000", "#FFFFFF", "#7F7F7F", // the ends and middle of the grey axis+ "#0563C1", "#203864", "#FF0000", "#00FF00", // saturated, where a naive invert diverges+ "#010203", "#FEFDFC" // just inside each clamp+ ]) {+ expect(darkHalfOf(color)).toBe(univerDarkHalfOf(color));+ }+ });++ it("agrees across the color space", () => {+ // A fixed sequence rather than Math.random, so a failure is reproducible.+ let seed = 0x2f6e2b1;+ const next = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) % 256;++ for (let i = 0; i < 300; i++) {+ const color = "#" + [next(), next(), next()].map((c) => c.toString(16).padStart(2, "0")).join("");+ expect(darkHalfOf(color)).toBe(univerDarkHalfOf(color));+ }+ });+});diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_html.spec.tsindex 90b3ef04b3..f2fd66ac29 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts@@ -16,12 +16,12 @@ function withInlineStyles(html: string): string {const declarations = new Map<string, string>();for (const rule of stylesheet[1].matchAll(/\.spreadsheet-table \.([\w-]+)\{([^}]*)\}/g)) {- declarations.set(rule[1], rule[2]);+ declarations.set(rule[1], withoutThemedColors(rule[2]));}// The renderer folds the commonest cell style into a `td` default, leaving those cells without// a class; every other rule sets what the default does, so a classed cell resolves to its rule// alone. Putting the default back on the bare cells is what the browser works out.- const fallback = /\.spreadsheet-table td\{([^}]*)\}/.exec(stylesheet[1])?.[1] ?? "";+ const fallback = withoutThemedColors(/\.spreadsheet-table td\{([^}]*)\}/.exec(stylesheet[1])?.[1] ?? "");const body = html.slice(stylesheet[0].length).replace(/ class="([^"]*)"/g, (_whole, names: string) => {const kept: string[] = [];@@ -36,6 +36,15 @@ function withInlineStyles(html: string): string {return fallback ? body.replace(/<td(?=[ >])(?![^>]*style=")/g, `<td style="${fallback}"`) : body;}++/**+ * Drops the `light-dark()` declaration each color is followed by, leaving the plain one in front+ * of it — which is what a light theme renders, and what every assertion here is written against.+ * The pairing itself is covered by the "dark mode" block, reading what is actually emitted.+ */+function withoutThemedColors(declarations: string): string {+ return declarations.split(";").filter((part) => !part.includes("light-dark(")).join(";");+}import { BorderStyle, HorizontalAlign, WrapStrategy } from "./workbook_model.js";describe("renderSpreadsheetToHtml", () => {@@ -2384,3 +2393,59 @@ describe("style deduplication", () => {});});});++describe("dark mode", () => {+ const cellWorkbook = (cell: Record<string, unknown>) => JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: ["s1"], styles: {},+ sheets: {+ s1: {+ id: "s1", name: "S", hidden: 0, rowCount: 5, columnCount: 5, showGridlines: 0,+ mergeData: [], cellData: { "0": { "0": cell } }, rowData: {}, columnData: {}+ }+ }+ }+ });++ it("pairs a fill and its text with what a dark theme shows instead", () => {+ const html = renderRaw(cellWorkbook({ v: "x", t: 1, s: { bg: { rgb: "#FFE699" } } }));++ // Pale yellow darkens to brown rather than to the blue a plain 255-c would give, and the+ // automatic font colour it sits on flips the other way.+ expect(html).toContain("background-color:light-dark(#FFE699,#543b00)");+ expect(html).toContain("color:light-dark(#000,#ffffff)");+ });++ it("pairs a border colour too, as Univer inverts every colour it paints", () => {+ const html = renderRaw(cellWorkbook({+ v: "x", t: 1, s: { bd: { t: { s: 1, cl: { rgb: "#203864" } }, b: { s: 1 } } }+ }));++ expect(html).toContain("border-top:1px solid light-dark(#203864,#a2bae6)");+ // A border with no colour of its own defaults to black, which inverts to white.+ expect(html).toContain("border-bottom:1px solid light-dark(#000,#ffffff)");+ });++ it("inverts a named colour a number format asks for", () => {+ const html = renderRaw(cellWorkbook({+ v: -8800.2, t: 2, s: { n: { pattern: "#,##0.00;[Red]#,##0.00" } }+ }));++ expect(html).toContain("color:light-dark(red,#ff5555)");+ });++ it("leaves a colour it cannot read alone rather than dropping it", () => {+ // sanitizeCssColor passes rgb() through, and nothing in a workbook produces one, so it has+ // no dark half; emitting it unpaired is better than emitting nothing.+ const html = renderRaw(cellWorkbook({ v: "x", t: 1, s: { cl: { rgb: "rgb(1,2,3)" } } }));++ expect(html).toContain("color:rgb(1,2,3)");+ expect(html).not.toContain("light-dark(rgb");+ });++ it("inverts a grey to its exact complement", () => {+ const html = renderRaw(cellWorkbook({ v: "x", t: 1, s: { bg: { rgb: "#DBDBDB" } } }));+ expect(html).toContain("background-color:light-dark(#DBDBDB,#242424)");+ });+});diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.tsindex 24470dcc08..a0c1a63757 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts@@ -626,7 +626,7 @@ function buildMergeMap(mergeData: IRange[], minRow: number, maxRow: number, minC// #endregion-// #region Style resolution+// #region Dark mode/*** What Excel renders an automatic font in. `parse_from_xlsx` drops that default so a cell can@@ -634,6 +634,77 @@ function buildMergeMap(mergeData: IRange[], minRow: number, maxRow: number, minC*/const AUTOMATIC_TEXT_COLOR = "#000";+/** The CSS values of the color names `numfmt` answers with for a `[Red]`-style pattern. */+const NAMED_COLORS: Record<string, string> = {+ black: "#000000", blue: "#0000ff", cyan: "#00ffff", green: "#008000",+ magenta: "#ff00ff", red: "#ff0000", white: "#ffffff", yellow: "#ffff00"+};++/**+ * The declarations setting `property` to `color`: the color as it stands, then again paired with+ * what a dark theme shows instead, for the browser to choose between by `color-scheme` — which the+ * client sets from `--theme-style` and the share theme sets outright. Print declares none and so+ * takes the light half, which is what belongs on paper.+ *+ * The plain declaration comes first and is never dropped. A browser that does not know+ * `light-dark()` discards the second and renders as it always did, which matters as far down as+ * the iOS 15 the mobile app still builds for: an unrecognised value takes its whole declaration+ * with it, so a cell would lose the fill or border entirely rather than merely fail to darken.+ *+ * `build` wraps the color in whatever else the property needs, a border's width and style.+ */+function themedDeclarations(property: string, color: string, build: (color: string) => string = (it) => it): string[] {+ const declarations = [`${property}:${build(color)}`];++ const inverted = invertColor(color);+ if (inverted) declarations.push(`${property}:${build(`light-dark(${color},${inverted})`)}`);++ return declarations;+}++/**+ * Inverts a color the way Univer does on a dark theme, so a preview matches the editor+ * (`invertColorByMatrix`, which its canvas color service runs over every color it paints).+ *+ * Each channel keeps a third of its own value and loses two thirds of the other two, then gains+ * one. That inverts lightness while leaving the channel ordering — the hue — alone: a pale yellow+ * fill comes back dark brown rather than the blue a plain `255 - c` would give, and a dark fill+ * comes back pale. A grey inverts to its exact complement either way.+ *+ * The coefficients are Univer's own rounded literals rather than exact thirds, which is what keeps+ * the two implementations agreeing to the byte.+ */+function invertColor(color: string): string | null {+ const rgb = parseColor(color);+ if (!rgb) return null;++ const [r, g, b] = rgb.map((channel) => channel / 255);+ const inverted = [+ 0.333 * r - 0.667 * g - 0.667 * b + 1,+ -0.667 * r + 0.333 * g - 0.667 * b + 1,+ -0.667 * r - 0.667 * g + 0.333 * b + 1+ ];++ return `#${inverted+ .map((channel) => Math.round(Math.min(1, Math.max(0, channel)) * 255))+ .map((channel) => channel.toString(16).padStart(2, "0"))+ .join("")}`;+}++/** Reads `#rgb`, `#rrggbb` and the named colors, which is every form the renderer emits. */+function parseColor(color: string): [number, number, number] | null {+ const named = NAMED_COLORS[color.toLowerCase()];+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(named ?? color)?.[1];+ if (!hex) return null;++ const pairs = hex.length === 3 ? [...hex].map((c) => c + c) : [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4, 6)];+ return pairs.map((pair) => Number.parseInt(pair, 16)) as [number, number, number];+}++// #endregion++// #region Style resolution+function buildCssText(style: IStyleData | null, cell?: ICellData): string {const parts: string[] = [];@@ -659,7 +730,7 @@ function buildCssText(style: IStyleData | null, cell?: ICellData): 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.bg?.rgb) parts.push(...themedDeclarations("background-color", sanitizeCssColor(style.bg.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. A filled cell that@@ -668,7 +739,7 @@ function buildCssText(style: IStyleData | null, cell?: ICellData): string {// theme around it, so a pale fill is unreadable wherever the theme is dark.const patternColor = resolvePatternColor(style, cell);const textColor = patternColor ?? style.cl?.rgb ?? (style.bg?.rgb ? AUTOMATIC_TEXT_COLOR : undefined);- if (textColor) parts.push(`color:${sanitizeCssColor(textColor)}`);+ if (textColor) parts.push(...themedDeclarations("color", sanitizeCssColor(textColor)));if (style.vt != null) {const valign = verticalAlignToCss(style.vt);@@ -789,7 +860,7 @@ function appendBorderCss(parts: string[], property: string, border: IBorderStyleconst width = borderStyleToWidth(border.s);const color = sanitizeCssColor(border.cl?.rgb ?? "#000");const style = borderStyleToCss(border.s);- parts.push(`${property}:${width} ${style} ${color}`);+ parts.push(...themedDeclarations(property, color, (it) => `${width} ${style} ${it}`));}function borderStyleToWidth(style: number | undefined): string {