Skip to content

Build your personal knowledge base with Trilium Notes

perf(spreadsheet): reuse a cell's declarations across the cells sharing its style

Elian Doran5f98d570c6ba
diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
index 59994eb2bc..f7e87ab356 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
@@ -2759,3 +2759,109 @@ describe("dark mode", () => {
expect(html).toContain("background-color:light-dark(#DBDBDB,#242424)");
});
});
+/**
+ * The renderer builds a cell's declarations once per style and reuses them across the cells that
+ * share it. These cover what the reuse has to keep apart: two cells sharing a style still differ
+ * wherever the declarations depend on the cell rather than on the style alone. Each asserts on one
+ * cell at a time, since the `td` default completes the other rules with `inherit` and which style
+ * is folded depends on the sheet.
+ */
+describe("reuse of a style across cells", () => {
+ const workbook = (styles: Record<string, unknown>, cellData: Record<string, Record<string, unknown>>, mergeData: 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, rowData: {}, columnData: {}
+ }
+ }
+ }
+ });
+
+ /** The rendered cells in document order, with their sizing box and padding stripped. */
+ function cells(input: string): string[] {
+ return [...unboxed(renderSpreadsheetToHtml(input)).matchAll(/<td[^>]*>[\s\S]*?<\/td>/g)].map(([cell]) => cell);
+ }
+
+ it("keeps the alignment a value type implies, which the style does not carry", () => {
+ // Univer aligns a number right and a string left when the style sets none, so two cells on
+ // one style still align differently. The number comes first, so a reuse blind to the value
+ // type would align the string right as well.
+ const [number, string] = cells(workbook(
+ { st1: { ff: "Arial" } },
+ { "0": { "0": { v: 5, t: 2, s: "st1" }, "1": { v: "x", t: 1, s: "st1" } } }
+ ));
+
+ expect(number).toContain("text-align:right");
+ expect(string).not.toContain("text-align:right");
+ });
+
+ it("colors each value by its own number-format section", () => {
+ // `[Red]` applies to the negative section alone, so the color follows the value rather than
+ // the style the two cells share.
+ const [positive, negative] = cells(workbook(
+ { st1: { n: { pattern: "#,##0;[Red]#,##0" } } },
+ { "0": { "0": { v: 5, t: 2, s: "st1" }, "1": { v: -5, t: 2, s: "st1" } } }
+ ));
+
+ expect(positive).not.toContain("color:red");
+ expect(negative).toContain("color:red");
+ });
+
+ it("keeps a merged range's composed border off the cells that share its style", () => {
+ // A range takes its right border from the cell in its last column, so the anchor renders
+ // declarations its style does not resolve to on its own.
+ const [anchor, plain] = cells(workbook(
+ { st1: { bl: 1 }, edge: { bd: { r: { s: BorderStyle.THIN, cl: { rgb: "#ff0000" } } } } },
+ {
+ "0": { "0": { v: "merged", t: 1, s: "st1" }, "1": { v: "", t: 1, s: "edge" } },
+ "1": { "0": { v: "plain", t: 1, s: "st1" } }
+ },
+ [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 }]
+ ));
+
+ expect(anchor).toContain("border-right:1px solid #ff0000");
+ expect(plain).not.toContain("border-right");
+ });
+
+ it("tells two inline styles apart, which carry no shared id to reuse by", () => {
+ const [bold, italic] = cells(workbook(
+ {},
+ { "0": { "0": { v: "a", t: 1, s: { bl: 1 } }, "1": { v: "b", t: 1, s: { it: 1 } } } }
+ ));
+
+ expect(bold).toContain("font-weight:bold");
+ expect(bold).not.toContain("font-style:italic");
+ expect(italic).toContain("font-style:italic");
+ expect(italic).not.toContain("font-weight:bold");
+ });
+
+ it("darkens each color to its own dark half", () => {
+ // An inversion is reused per color within a render and between renders, so two fills must
+ // not collapse onto whichever was asked for first.
+ const input = workbook(
+ { pale: { bg: { rgb: "#FFE699" } }, grey: { bg: { rgb: "#DBDBDB" } } },
+ { "0": { "0": { v: "a", t: 1, s: "pale" }, "1": { v: "b", t: 1, s: "grey" } } }
+ );
+ const html = renderRaw(input);
+
+ expect(html).toContain("background-color:light-dark(#FFE699,#543b00)");
+ expect(html).toContain("background-color:light-dark(#DBDBDB,#242424)");
+ expect(renderRaw(input)).toBe(html);
+ });
+
+ it("escapes every character that has to be escaped, each on its own", () => {
+ // One character per cell: a cell holding all five would still be escaped by a check that
+ // recognised only one of them.
+ const raw = ["&", "<", ">", "\"", "'"];
+ const rendered = cells(workbook({}, {
+ "0": Object.fromEntries(raw.map((character, index) => [String(index), { v: character, t: 1 }]))
+ }));
+
+ expect(rendered.map((cell) => /<td[^>]*>([\s\S]*)<\/td>/.exec(cell)?.[1]))
+ .toEqual(["&amp;", "&lt;", "&gt;", "&quot;", "&#39;"]);
+ });
+});
diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.ts
index 5dd2284e71..46a6dd36ce 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts
@@ -530,6 +530,8 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |
// Build a set of cells that are hidden by merges (non-origin cells).
const mergeMap = buildMergeMap(mergeData, minRow, maxRow, minCol, maxCol);
+ const merged = mergeMap.size > 0;
+ const cssCache = new Map<string, string>();
// Visible column widths, reused for the colgroup and the table's fixed total width.
const defaultWidth = sheet.defaultColumnWidth ?? 88;
@@ -575,7 +577,7 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |
for (let col = minCol; col <= maxCol; col++) {
if (columnData[col]?.hd) continue;
- const mergeInfo = mergeMap.get(cellKey(row, col));
+ const mergeInfo = merged ? mergeMap.get(cellKey(row, col)) : undefined;
if (mergeInfo?.kind === "member") continue;
const cell = cellData[row]?.[col];
@@ -585,11 +587,10 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |
const boxHeight = spannedHeight(heights, row, mergeInfo?.endRow ?? row)
- padding.t - padding.b
- collapsedBorderHeight(cellStyle, row, mergeInfo?.endRow ?? row, col, rowData, cellData, styles);
- const declarations = [buildCssText(cellStyle, cell)];
- if (hasContent(cell)) {
- declarations.push(`padding:${px(padding.t)}px ${px(padding.r)}px ${px(padding.b)}px ${px(padding.l)}px`);
- }
- const cssText = declarations.filter(Boolean).join(";");
+ const base = cssTextFor(cellStyle, cell, mergeInfo, cssCache);
+ const cssText = hasContent(cell)
+ ? `${base ? `${base};` : ""}padding:${px(padding.t)}px ${px(padding.r)}px ${px(padding.b)}px ${px(padding.l)}px`
+ : base;
const text = rotate(formatCellValue(cell, cellStyle), cellStyle, classes);
const value = (isTurned(cellStyle?.tr)
? turnedBox(text, boxHeight, cellStyle, classes)
@@ -771,6 +772,18 @@ function themedDeclarations(property: string, color: string, build: (color: stri
* the two implementations agreeing to the byte.
*/
function invertColor(color: string): string | null {
+ let inverted = INVERTED_COLORS.get(color);
+ if (inverted === undefined) {
+ inverted = invertColorUncached(color);
+ INVERTED_COLORS.set(color, inverted);
+ }
+ return inverted;
+}
+
+/** A workbook draws from a handful of colors, and every cell using one asks for the same answer. */
+const INVERTED_COLORS = new Map<string, string | null>();
+
+function invertColorUncached(color: string): string | null {
const rgb = parseColor(color);
if (!rgb) return null;
@@ -801,6 +814,33 @@ function parseColor(color: string): [number, number, number] | null {
// #region Style resolution
+/**
+ * `buildCssText` for a cell, reusing the result across the cells that share a style. Beyond the
+ * style, the declarations depend on the cell's value type (`defaultHorizontalAlign`) and, where the
+ * style carries a number format, on the value itself (`resolvePatternColor`). So a formatted cell,
+ * a cell whose style is written inline rather than shared, and a merge origin (whose borders
+ * `mergeAwareStyle` rewrites per range) are all built every time.
+ */
+function cssTextFor(
+ style: IStyleData | null,
+ cell: ICellData | undefined,
+ merge: MergeOrigin | undefined,
+ cache: Map<string, string>
+): string {
+ const shared = cell?.s;
+ if (merge || style?.n?.pattern || (shared !== undefined && typeof shared !== "string")) {
+ return buildCssText(style, cell);
+ }
+
+ const key = `${shared ?? ""}|${cell?.t ?? ""}`;
+ let cssText = cache.get(key);
+ if (cssText === undefined) {
+ cssText = buildCssText(style, cell);
+ cache.set(key, cssText);
+ }
+ return cssText;
+}
+
function buildCssText(style: IStyleData | null, cell?: ICellData): string {
const parts: string[] = [];
@@ -939,7 +979,7 @@ function spillRoom(from: number, step: -1 | 1, neighbours: RowNeighbours): { wid
function cellShownAt(col: number, neighbours: RowNeighbours): ICellData | undefined {
const { row, cellData, mergeMap } = neighbours;
- const info = mergeMap.get(cellKey(row, col));
+ const info = mergeMap.size ? mergeMap.get(cellKey(row, col)) : undefined;
return info?.kind === "member" ? cellData[info.anchorRow]?.[info.anchorColumn] : cellData[row]?.[col];
}
@@ -1350,13 +1390,16 @@ function resolvePatternColor(style: IStyleData | null, cell: ICellData | undefin
}
function escapeHtml(text: string): string {
+ if (!ESCAPABLE.test(text)) return text;
+
return text
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
- ;
}
+const ESCAPABLE = /[&<>"']/;
+
// #endregion