Skip to content

Build your personal knowledge base with Trilium Notes

perf(spreadsheet): fold the commonest cell style into a td default

Elian Dorandb6e028e62b5
diff --git a/apps/client/src/print.css b/apps/client/src/print.css
index 512f0e494a..96b7dfeaa4 100644
--- a/apps/client/src/print.css
+++ b/apps/client/src/print.css
@@ -296,7 +296,9 @@ span[style] {
-webkit-print-color-adjust: exact;
}
-.spreadsheet-table td {
+/* The context is in :where() so this stays a default: the renderer emits the commonest cell
+ style as a `.spreadsheet-table td` rule, which has to win over it. */
+:where(.spreadsheet-table) td {
padding: 2pt 4pt;
/* Match the spreadsheet: long text runs into empty neighbouring cells instead of wrapping,
which keeps every row at its declared height. The renderer sets overflow:hidden on the cells
diff --git a/apps/client/src/services/spreadsheet_preview_styles.spec.ts b/apps/client/src/services/spreadsheet_preview_styles.spec.ts
index 90a49d15ca..365ab0e9de 100644
--- a/apps/client/src/services/spreadsheet_preview_styles.spec.ts
+++ b/apps/client/src/services/spreadsheet_preview_styles.spec.ts
@@ -75,4 +75,40 @@ describe("spreadsheet preview styling", () => {
expect(gridlineColor()).toBe("#aabbcc");
expect(gridlineColor("#00FF00")).toBe("#00FF00");
});
+
+ it("applies the folded td default to bare cells, and lets a classed cell override it", () => {
+ // Three bold cells and one italic: bold folds into the default, italic keeps a class and
+ // is completed with font-weight:inherit so it does not come out bold as well.
+ const workbook = JSON.stringify({
+ version: 1,
+ workbook: {
+ sheetOrder: ["s1"], styles: {},
+ sheets: {
+ s1: {
+ id: "s1", name: "S", hidden: 0, rowCount: 10, columnCount: 5, showGridlines: 1,
+ mergeData: [],
+ cellData: {
+ "0": { "0": { v: "a", t: 1, s: { bl: 1 } } },
+ "1": { "0": { v: "b", t: 1, s: { bl: 1 } } },
+ "2": { "0": { v: "c", t: 1, s: { bl: 1 } } },
+ "3": { "0": { v: "d", t: 1, s: { it: 1 } } }
+ },
+ rowData: {}, columnData: {}
+ }
+ }
+ }
+ });
+
+ document.head.innerHTML = `<style>${spreadsheetRulesFrom("content_renderer.css")}</style>`;
+ document.body.innerHTML =
+ `<div class="ck-content office-preview-body">${renderSpreadsheetToHtml(workbook)}</div>`;
+
+ const [folded, , , classed] = document.querySelectorAll("td");
+ expect(folded.getAttribute("class")).toBeNull();
+ expect(getComputedStyle(folded).fontWeight).toBe("bold");
+
+ // The cell that kept a class is not dragged bold by the default it sits under.
+ expect(getComputedStyle(classed).fontStyle).toBe("italic");
+ expect(getComputedStyle(classed).fontWeight).not.toBe("bold");
+ });
});
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 7333f96f90..45566f0bf6 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
@@ -18,8 +18,12 @@ function withInlineStyles(html: string): string {
for (const rule of stylesheet[1].matchAll(/\.spreadsheet-table \.([\w-]+)\{([^}]*)\}/g)) {
declarations.set(rule[1], 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] ?? "";
- return html.slice(stylesheet[0].length).replace(/ class="([^"]*)"/g, (_whole, names: string) => {
+ const body = html.slice(stylesheet[0].length).replace(/ class="([^"]*)"/g, (_whole, names: string) => {
const kept: string[] = [];
const css: string[] = [];
for (const name of names.split(" ")) {
@@ -29,6 +33,8 @@ function withInlineStyles(html: string): string {
}
return (kept.length ? ` class="${kept.join(" ")}"` : "") + (css.length ? ` style="${css.join(";")}"` : "");
});
+
+ return fallback ? body.replace(/<td(?=[ >])(?![^>]*style=")/g, `<td style="${fallback}"`) : body;
}
import { BorderStyle, HorizontalAlign, WrapStrategy } from "./workbook_model.js";
@@ -2224,30 +2230,34 @@ describe("style deduplication", () => {
}
});
+ // One cell per row, so none has an occupied neighbour and none of them clips.
+ const rows = (...cells: unknown[]) => Object.fromEntries(cells.map((cell, row) => [String(row), { "0": cell }]));
+ const bold = { v: "x", t: 1, s: { bl: 1 } };
+ const italic = { v: "y", t: 1, s: { it: 1 } };
+
it("writes a style shared by many cells once, and puts the stylesheet in front", () => {
- // One per row, so no cell has an occupied neighbour and none of them clips: the three
- // resolve to the same declarations.
- const bold = { v: "x", t: 1, s: { bl: 1 } };
- const html = renderRaw(gridWorkbook({ "0": { "0": bold }, "1": { "0": bold }, "2": { "0": bold } }));
+ const html = renderRaw(gridWorkbook(rows(bold, bold, bold, italic)));
expect(html.startsWith("<style>")).toBe(true);
- // One rule for the three bold cells, not three copies of the declaration.
+ // One rule for the three bold cells, not three copies of the declaration. Being the
+ // commonest style they carry, it is written as the folded `td` default.
expect(html.match(/font-weight:bold/g)).toHaveLength(1);
+ expect(html).toContain(".spreadsheet-table td{font-weight:bold}");
- const name = /\.spreadsheet-table \.(sst-[\w-]+)\{font-weight:bold\}/.exec(html)?.[1];
+ // The minority style keeps a class, used by the one cell that has it.
+ const name = /\.spreadsheet-table \.(sst-[\w-]+)\{font-style:italic/.exec(html)?.[1];
expect(name).toBeTruthy();
- expect(html.match(new RegExp(`class="${name}"`, "g"))).toHaveLength(3);
+ expect(html.match(new RegExp(`class="${name}"`, "g"))).toHaveLength(1);
});
it("scopes every rule under the table so a class cannot reach the rest of the page", () => {
- const html = renderRaw(gridWorkbook({ "0": { "0": { v: "x", t: 1, s: { bl: 1 } } } }));
- const stylesheet = /^<style>([\s\S]*?)<\/style>/.exec(html)?.[1] ?? "";
+ const stylesheet = /^<style>([\s\S]*?)<\/style>/.exec(renderRaw(gridWorkbook(rows(bold, italic))))?.[1] ?? "";
expect(stylesheet).toBeTruthy();
for (const rule of stylesheet.split("}").map((r) => r.trim()).filter(Boolean)) {
- // Cell rules, and the gridline rule whose context sits in :where(); neither can
- // match anything outside a rendered sheet.
- expect(rule).toMatch(/^(\.spreadsheet-table \.sst-|:where\(\.spreadsheet-table)/);
+ // Cell rules, the folded `td` default, and the gridline rule whose context sits in
+ // :where(); none of them can match anything outside a rendered sheet.
+ expect(rule).toMatch(/^(\.spreadsheet-table (\.sst-|td\{)|:where\(\.spreadsheet-table)/);
}
});
@@ -2262,21 +2272,63 @@ describe("style deduplication", () => {
});
it("names a class after its declarations, so two documents share rather than collide", () => {
- const one = renderRaw(gridWorkbook({ "0": { "0": { v: "a", t: 1, s: { bl: 1 } } } }));
- const other = renderRaw(gridWorkbook({ "0": { "0": { v: "b", t: 1, s: { bl: 1 } } } }));
+ // Bold dominates in both, so italic is the one left carrying a class.
+ const nameIn = (html: string) => /\.spreadsheet-table \.(sst-[\w-]+)\{font-style:italic/.exec(html)?.[1];
+ const one = renderRaw(gridWorkbook(rows(bold, bold, italic)));
+ const other = renderRaw(gridWorkbook(rows(bold, bold, italic, bold)));
- const nameIn = (html: string) => /\.spreadsheet-table \.(sst-[\w-]+)\{font-weight:bold\}/.exec(html)?.[1];
+ expect(nameIn(one)).toBeTruthy();
expect(nameIn(one)).toBe(nameIn(other));
// A different declaration gets a different name.
- const italic = renderRaw(gridWorkbook({ "0": { "0": { v: "a", t: 1, s: { it: 1 } } } }));
- expect(nameIn(one)).not.toBe(/\.spreadsheet-table \.(sst-[\w-]+)\{font-style/.exec(italic)?.[1]);
+ const underlined = renderRaw(gridWorkbook(rows(bold, bold, { v: "y", t: 1, s: { ul: { s: 1 } } })));
+ expect(nameIn(one)).not.toBe(/\.spreadsheet-table \.(sst-[\w-]+)\{text-decoration/.exec(underlined)?.[1]);
});
it("keeps has-fill alongside the generated class, and emits no stylesheet for an empty sheet", () => {
- const html = renderRaw(gridWorkbook({ "0": { "0": { v: "x", t: 1, s: { bg: { rgb: "#FFE699" } } } } }));
- expect(html).toMatch(/<td class="has-fill sst-[\w-]+"/);
+ const filled = { v: "x", t: 1, s: { bg: { rgb: "#FFE699" } } };
+ expect(renderRaw(gridWorkbook(rows(bold, bold, filled)))).toMatch(/<td class="has-fill sst-[\w-]+"/);
expect(renderRaw(JSON.stringify({ version: 1, workbook: { sheetOrder: [], styles: {}, sheets: {} } })))
.not.toContain("<style>");
});
+
+ describe("folding the commonest style into a td default", () => {
+ it("drops the class from the cells that used it, keeping it on the rest", () => {
+ const html = renderRaw(gridWorkbook(rows(bold, bold, bold, italic)));
+
+ expect(html).toContain(".spreadsheet-table td{font-weight:bold}");
+ // Three bare cells for the folded style, one still classed for the other.
+ expect(html.match(/<td>/g)).toHaveLength(3);
+ expect(html.match(/<td class="sst-[\w-]+">/g)).toHaveLength(1);
+ });
+
+ it("completes a rule that leaves an inherited property the default sets unset", () => {
+ // The default sets font-weight; the italic cell says nothing about it, and would
+ // otherwise come out bold. font-weight is inherited, so `inherit` restores exactly
+ // what no declaration at all would have computed to.
+ const html = renderRaw(gridWorkbook(rows(bold, bold, italic)));
+
+ expect(html).toContain(".spreadsheet-table td{font-weight:bold}");
+ expect(html).toMatch(/\.spreadsheet-table \.sst-[\w-]+\{font-style:italic;font-weight:inherit\}/);
+ });
+
+ it("declines when a rule would inherit a property that cannot be reset", () => {
+ // A background fill dominates, and no value means "as if never declared" for it, so
+ // the bold cell could not be kept from picking the fill up. Nothing is folded.
+ const filled = { v: "x", t: 1, s: { bg: { rgb: "#FFE699" } } };
+ const html = renderRaw(gridWorkbook(rows(filled, filled, filled, bold)));
+
+ expect(html).not.toContain(".spreadsheet-table td{");
+ expect(html).toMatch(/<td class="has-fill sst-[\w-]+"/);
+ });
+
+ it("declines when a cell styles nothing, having no rule to complete", () => {
+ // A left-aligned text cell emits no declarations at all, so it carries no class and
+ // would take the default whole.
+ const html = renderRaw(gridWorkbook(rows(bold, bold, { v: "plain", t: 1 })));
+
+ expect(html).not.toContain(".spreadsheet-table td{");
+ expect(html).toContain("<td>plain</td>");
+ });
+ });
});
diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.ts
index c81064797c..320c98c60f 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts
@@ -74,17 +74,35 @@ export function renderSpreadsheetToHtml(jsonContent: string): string {
// The stylesheet is only complete once every sheet has been rendered, so it is built last
// and put in front, where a consumer that has to lift it out finds it without a parse.
- const stylesheet = buildStylesheet(visibleSheets, classes);
- return stylesheet ? `${stylesheet}\n${parts.join("\n")}` : parts.join("\n");
+ const fold = classes.fold();
+ const stylesheet = buildStylesheet(visibleSheets, classes, fold);
+ const body = fold ? dropFoldedClass(parts.join("\n"), fold.className) : parts.join("\n");
+
+ return stylesheet ? `${stylesheet}\n${body}` : body;
+}
+
+/**
+ * Removes the class the `td` default now carries from the cells that were given it. Rows and
+ * columns keep theirs: the default reaches cells only, and a track never shares a cell's
+ * declarations (one sizes itself, the other styles its contents).
+ */
+function dropFoldedClass(html: string, className: string): string {
+ return html
+ .replaceAll(`<td class="${className}"`, "<td")
+ .replaceAll(`<td class="has-fill ${className}"`, `<td class="has-fill"`);
}
/**
* Builds the `<style>` a render is preceded by: the gridline rule when any sheet asks for
- * gridlines, then one rule per distinct cell style. Returns "" when there is nothing to write.
+ * gridlines, the folded `td` default when there is one, then one rule per distinct style left.
+ * Returns "" when there is nothing to write.
*/
-function buildStylesheet(sheets: IWorksheetData[], classes: StyleClasses): string {
+function buildStylesheet(sheets: IWorksheetData[], classes: StyleClasses, fold: Fold | null): string {
const rules = sheets.some((sheet) => sheet.showGridlines !== 0) ? [GRIDLINE_RULE] : [];
- rules.push(...classes.toRules());
+ // After the gridline rule, so a folded border wins the way a cell's own border does, and
+ // before the class rules, which are more specific and override it per cell.
+ if (fold) rules.push(`.spreadsheet-table td{${fold.declarations}}`);
+ rules.push(...classes.toRules(fold));
return rules.length ? `<style>\n${rules.join("\n")}\n</style>` : "";
}
@@ -116,33 +134,122 @@ const GRIDLINE_RULE = ":where(.spreadsheet-table.show-gridlines) td:not(.has-fil
*/
class StyleClasses {
private readonly names = new Map<string, string>();
+ /** How many cells used each set of declarations; a `td` default is chosen from this. */
+ private readonly cellUsage = new Map<string, number>();
+ /** Whether any cell styles nothing at all, which no `td` default can be safe for. */
+ private hasUnstyledCell = false;
- /** Returns the class for `declarations`, or "" when there is nothing to style. */
+ /** Returns the class for a row's or column's `declarations`, or "" when there is none. */
classFor(declarations: string): string {
- if (!declarations) return "";
+ return declarations ? this.nameFor(declarations) : "";
+ }
- let name = this.names.get(declarations);
- if (!name) {
- name = `sst-${hashDeclarations(declarations)}`;
- this.names.set(declarations, name);
+ /** Returns the class for a cell's `declarations`, recording it towards the `td` default. */
+ cellClassFor(declarations: string): string {
+ if (!declarations) {
+ this.hasUnstyledCell = true;
+ return "";
}
- return name;
+
+ this.cellUsage.set(declarations, (this.cellUsage.get(declarations) ?? 0) + 1);
+ return this.nameFor(declarations);
+ }
+
+ /**
+ * Picks the declarations to write as a `td` default, letting the cells that use them carry no
+ * class at all — on a large sheet that is the single biggest thing left in the document.
+ *
+ * A default reaches every cell, so it is only safe where no other cell can pick it up by
+ * accident. A rule that leaves one of the default's properties unset would inherit it, so
+ * every other rule has to either set that property itself or be completed here. Completion is
+ * only exact for an inherited property, where `inherit` computes to what no declaration at all
+ * would have computed to; for anything else there is no value that means "as if unset", so the
+ * fold is abandoned. Returns null when nothing can be folded.
+ */
+ fold(): Fold | null {
+ // A cell with no declarations has no rule to complete, so it would take the default whole.
+ if (this.hasUnstyledCell) return null;
+
+ let declarations = "";
+ let best = 0;
+ for (const [candidate, count] of this.cellUsage) {
+ if (count > best) {
+ declarations = candidate;
+ best = count;
+ }
+ }
+ if (!declarations) return null;
+
+ const defaulted = propertiesOf(declarations);
+ const completions = new Map<string, string>();
+ for (const other of this.cellUsage.keys()) {
+ if (other === declarations) continue;
+
+ const own = propertiesOf(other);
+ const missing: string[] = [];
+ for (const property of defaulted) {
+ if (own.has(property)) continue;
+ if (!INHERITED_PROPERTIES.has(property)) return null;
+ missing.push(`${property}:inherit`);
+ }
+ if (missing.length) completions.set(other, missing.join(";"));
+ }
+
+ return { declarations, className: this.nameFor(declarations), completions };
}
/**
- * Builds a rule per distinct style collected.
+ * Builds a rule per distinct style collected, less the one `fold` turned into the `td` default,
+ * and with any completions that fold demands. A row's or column's declarations always carry a
+ * height or width, which a cell's never do, so folding a cell style never removes a rule a
+ * track still needs.
*
* The declarations cannot contain `<` or `/`: colors are validated against a pattern and every
* other author-supplied value goes through `sanitizeCssValue`, which strips both. That is what
* keeps a cell's styling from closing its rule, or the element these rules are written into.
*/
- toRules(): string[] {
+ toRules(fold: Fold | null): string[] {
const rules: string[] = [];
for (const [declarations, name] of this.names) {
- rules.push(`.spreadsheet-table .${name}{${declarations}}`);
+ if (fold?.declarations === declarations) continue;
+
+ const completion = fold?.completions.get(declarations);
+ rules.push(`.spreadsheet-table .${name}{${declarations}${completion ? `;${completion}` : ""}}`);
}
return rules;
}
+
+ private nameFor(declarations: string): string {
+ let name = this.names.get(declarations);
+ if (!name) {
+ name = `sst-${hashDeclarations(declarations)}`;
+ this.names.set(declarations, name);
+ }
+ return name;
+ }
+}
+
+/** The declarations promoted to a `td` default, and what that costs the rules left behind. */
+interface Fold {
+ declarations: string;
+ /** The class the folded cells would otherwise carry, which is stripped from them. */
+ className: string;
+ /** Declarations of other rules, mapped to what has to be appended to keep them intact. */
+ completions: Map<string, string>;
+}
+
+/**
+ * The properties `buildCssText` emits that CSS inherits, and so the only ones a rule can be
+ * completed with `inherit` for. Everything else it emits — background-color, vertical-align,
+ * overflow, the borders, text-decoration — has no value meaning "as if never declared".
+ */
+const INHERITED_PROPERTIES = new Set([
+ "color", "font-family", "font-size", "font-style", "font-weight", "overflow-wrap",
+ "text-align", "white-space"
+]);
+
+function propertiesOf(declarations: string): Set<string> {
+ return new Set(declarations.split(";").filter(Boolean).map((declaration) => declaration.slice(0, declaration.indexOf(":"))));
}
/**
@@ -394,7 +501,7 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |
const attrs: string[] = [];
// Cells with a background fill carry `has-fill` so the stylesheet can suppress
// gridlines under the fill, matching the editor (a fill covers the grid).
- const names = [cellStyle?.bg?.rgb ? "has-fill" : "", classes.classFor(cssText)].filter(Boolean);
+ const names = [cellStyle?.bg?.rgb ? "has-fill" : "", classes.cellClassFor(cssText)].filter(Boolean);
if (names.length) attrs.push(`class="${names.join(" ")}"`);
if (mergeInfo) {
if (mergeInfo.rowSpan > 1) attrs.push(`rowspan="${mergeInfo.rowSpan}"`);
diff --git a/packages/share-theme/src/styles/content.css b/packages/share-theme/src/styles/content.css
index b5d5d6a617..b461b7fb24 100644
--- a/packages/share-theme/src/styles/content.css
+++ b/packages/share-theme/src/styles/content.css
@@ -127,7 +127,9 @@ body.type-webView {
table-layout: fixed;
}
-.spreadsheet-table td {
+/* The context is in :where() so this stays a default: the renderer emits the commonest cell
+ style as a `.spreadsheet-table td` rule, which has to win over it. */
+:where(.spreadsheet-table) td {
padding: 2px 4px;
/* Match the spreadsheet: long text overflows into empty neighbouring cells rather than
wrapping, which keeps every row at its declared height. Wrapping would grow rows and push