Skip to content

Build your personal knowledge base with Trilium Notes

revert(spreadsheet): drop the folded td default

Elian Dorana5662a29d31c
diff --git a/apps/client/src/services/spreadsheet_preview_styles.spec.ts b/apps/client/src/services/spreadsheet_preview_styles.spec.ts
index ad91f4255a..34f36c1492 100644
--- a/apps/client/src/services/spreadsheet_preview_styles.spec.ts
+++ b/apps/client/src/services/spreadsheet_preview_styles.spec.ts
@@ -78,70 +78,4 @@ describe("spreadsheet preview styling", () => {
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");
- });
-
- it("keeps one workbook's folded default off another shown beside it", () => {
- // Split view puts two previews on one page, each adding its own stylesheet. The folded
- // cells have no class left to say which default is theirs, so the rule has to name it.
- const sheet = (cell: Record<string, unknown>) => JSON.stringify({
- version: 1,
- workbook: {
- sheetOrder: ["s1"], styles: {},
- sheets: {
- s1: {
- id: "s1", name: "S", hidden: 0, rowCount: 10, columnCount: 5, showGridlines: 0,
- mergeData: [], cellData: { "0": { "0": cell }, "1": { "0": cell } },
- rowData: {}, columnData: {}
- }
- }
- }
- });
-
- document.head.innerHTML = "";
- document.body.innerHTML =
- `<div id="bold">${renderSpreadsheetToHtml(sheet({ v: "a", t: 1, s: { bl: 1 } }))}</div>`
- + `<div id="italic">${renderSpreadsheetToHtml(sheet({ v: "b", t: 1, s: { it: 1 } }))}</div>`;
-
- const bold = getComputedStyle(document.querySelector("#bold td") as Element);
- const italic = getComputedStyle(document.querySelector("#italic td") as Element);
-
- expect(bold.fontWeight).toBe("bold");
- expect(bold.fontStyle).not.toBe("italic");
- expect(italic.fontStyle).toBe("italic");
- expect(italic.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 f7e87ab356..59fae026aa 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
@@ -19,12 +19,6 @@ function withInlineStyles(html: string): string {
for (const rule of stylesheet[1].matchAll(/\.spreadsheet-table(?::where\(\.[\w-]+\))? \.([\w-]+)\{([^}]*)\}/g)) {
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 = withoutThemedColors(
- /\.spreadsheet-table(?::where\(\.[\w-]+\))? td\{([^}]*)\}/.exec(stylesheet[1])?.[1] ?? "");
-
const body = html.slice(stylesheet[0].length).replace(/ class="([^"]*)"/g, (_whole, names: string) => {
const kept: string[] = [];
const css: string[] = [];
@@ -36,7 +30,7 @@ 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;
+ return body;
}
/**
@@ -2584,12 +2578,10 @@ describe("style deduplication", () => {
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. Being the
- // commonest style they carry, it is written as the folded `td` default.
+ // One rule for the three bold cells, not three copies of the declaration.
expect(html.match(/font-weight:bold/g)).toHaveLength(1);
- expect(html).toMatch(/\.spreadsheet-table:where\(\.sstd-[\w-]+\) td\{[^}]*font-weight:bold/);
- // The minority style keeps a class, used by the one cell that has it.
+ // The minority style gets its own rule, used by the one cell that has it.
const name = /\.spreadsheet-table(?::where\(\.[\w-]+\))? \.(sst-[\w-]+)\{font-style:italic/.exec(html)?.[1];
expect(name).toBeTruthy();
expect(html.match(new RegExp(`class="${name}"`, "g"))).toHaveLength(1);
@@ -2600,8 +2592,8 @@ describe("style deduplication", () => {
expect(stylesheet).toBeTruthy();
for (const rule of stylesheet.split("}").map((r) => r.trim()).filter(Boolean)) {
- // 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.
+ // Cell rules, and the gridline rule whose context sits in :where(); neither can
+ // match anything outside a rendered sheet.
expect(rule).toMatch(/^(\.spreadsheet-table(:where\(\.[\w-]+\))? (\.sst-|td\{)|:where\(\.spreadsheet-table)/);
}
});
@@ -2638,70 +2630,6 @@ describe("style deduplication", () => {
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).toMatch(/\.spreadsheet-table:where\(\.sstd-[\w-]+\) 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).toMatch(/\.spreadsheet-table:where\(\.sstd-[\w-]+\) td\{[^}]*font-weight:bold/);
- expect(html).toMatch(
- /\.spreadsheet-table:where\(\.sstd-[\w-]+\) \.sst-[\w-]+\{[^}]*font-style:italic[^}]*font-weight:inherit\}/);
- });
-
- it("scopes a completed rule, so two workbooks sharing a style do not collide", () => {
- // Both fold something different, and both complete the same italic style — which is
- // named after the declarations it started with, so the two would otherwise write one
- // selector twice with different bodies.
- const red = { v: "x", t: 1, s: { cl: { rgb: "#FF0000" } } };
- const italicRule = (html: string) =>
- [...html.matchAll(/(\.spreadsheet-table[^{]*\.sst-[\w-]+)\{([^}]*)\}/g)]
- .find((match) => match[2].includes("font-style:italic"));
-
- const bolds = italicRule(renderRaw(gridWorkbook(rows(bold, bold, bold, italic))));
- const reds = italicRule(renderRaw(gridWorkbook(rows(red, red, red, italic))));
-
- expect(bolds?.[2]).toContain("font-weight:inherit");
- expect(reds?.[2]).toContain("color:inherit");
- // Same class, different rule: the selectors have to tell them apart.
- expect(bolds?.[0]).not.toBe(reds?.[0]);
- expect(bolds?.[0]).toMatch(/\.spreadsheet-table:where\(\.sstd-[\w-]+\) \.sst-/);
- });
-
- 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.toMatch(/\.spreadsheet-table(?::where\(\.[\w-]+\))? td\{/);
- expect(html).toMatch(/<td class="has-fill sst-[\w-]+"/);
- });
-
- it("declines when a cell styles nothing, having no rule to complete", () => {
- // A cell holding nothing takes neither a style nor the padding a cell with content
- // gets, so it carries no class and would take the default whole. Here one sits in the
- // gap between two bold cells, inside the bounds their content sets.
- const html = renderRaw(gridWorkbook({
- "0": { "0": bold, "2": bold },
- "1": { "0": bold }
- }));
-
- expect(html).not.toMatch(/\.spreadsheet-table(?::where\(\.[\w-]+\))? td\{/);
- expect(html).toContain("<td></td>");
- });
- });
});
describe("dark mode", () => {
@@ -2762,9 +2690,7 @@ describe("dark mode", () => {
/**
* 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.
+ * wherever the declarations depend on the cell rather than on the style alone.
*/
describe("reuse of a style across cells", () => {
const workbook = (styles: Record<string, unknown>, cellData: Record<string, Record<string, unknown>>, mergeData: unknown[] = []) =>
diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.ts
index 88f516ece9..793be60ad4 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts
@@ -80,37 +80,19 @@ export function renderSpreadsheetToHtml(content: string | PersistedData): 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 fold = classes.fold();
- const stylesheet = buildStylesheet(visibleSheets, classes, fold);
- const body = fold ? applyFold(parts.join("\n"), fold) : parts.join("\n");
+ const stylesheet = buildStylesheet(visibleSheets, classes);
+ const body = parts.join("\n");
return stylesheet ? `${stylesheet}\n${body}` : body;
}
-/**
- * Marks the tables the `td` default applies to, and takes the class it replaces off 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 applyFold(html: string, fold: Fold): string {
- return html
- .replaceAll(`<table class="spreadsheet-table`, `<table class="spreadsheet-table ${fold.scope}`)
- .replaceAll(`<td class="${fold.className}"`, "<td")
- .replaceAll(`<td class="has-fill ${fold.className}"`, `<td class="has-fill"`);
-}
-
/**
* Builds the `<style>` a render is preceded by: the gridline rule when any sheet asks for
- * gridlines, the folded `td` default when there is one, then one rule per distinct style left.
- * Returns "" when there is nothing to write.
+ * gridlines, then one rule per distinct style. Returns "" when there is nothing to write.
*/
-function buildStylesheet(sheets: IWorksheetData[], classes: StyleClasses, fold: Fold | null): string {
+function buildStylesheet(sheets: IWorksheetData[], classes: StyleClasses): string {
const rules = sheets.some((sheet) => sheet.showGridlines !== 0) ? [GRIDLINE_RULE] : [];
- // 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. The scope sits in
- // `:where()` so it costs no specificity, leaving those two comparisons as they were.
- if (fold) rules.push(`.spreadsheet-table:where(.${fold.scope}) td{${fold.declarations}}`);
- rules.push(...classes.toRules(fold));
+ rules.push(...classes.toRules());
return rules.length ? `<style>\n${rules.join("\n")}\n</style>` : "";
}
@@ -142,140 +124,33 @@ 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 a row's or column's `declarations`, or "" when there is none. */
+ /** Returns the class for `declarations`, or "" when there is nothing to style. */
classFor(declarations: string): string {
- return declarations ? this.nameFor(declarations) : "";
- }
+ if (!declarations) return "";
- /** Returns the class for a cell's `declarations`, recording it towards the `td` default. */
- cellClassFor(declarations: string): string {
- if (!declarations) {
- this.hasUnstyledCell = true;
- return "";
- }
-
- 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(";"));
+ let name = this.names.get(declarations);
+ if (!name) {
+ name = `sst-${hashDeclarations(declarations)}`;
+ this.names.set(declarations, name);
}
-
- return {
- declarations,
- className: this.nameFor(declarations),
- scope: `sstd-${hashDeclarations(declarations)}`,
- completions
- };
+ return name;
}
/**
- * 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.
+ * Builds a rule per distinct style collected.
*
* 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(fold: Fold | null): string[] {
+ toRules(): string[] {
const rules: string[] = [];
for (const [declarations, name] of this.names) {
- if (fold?.declarations === declarations) continue;
-
- // A completed rule says something only true of the workbook that folded it, while its
- // name comes from the declarations it started with — so two workbooks sharing a style
- // would write one selector twice with different bodies. Completed rules take the same
- // scope the default does; the rest stay global, which is what lets them be shared.
- const completion = fold?.completions.get(declarations);
- const scope = completion ? `:where(.${fold?.scope})` : "";
- rules.push(`.spreadsheet-table${scope} .${name}{${declarations}${completion ? `;${completion}` : ""}}`);
+ rules.push(`.spreadsheet-table .${name}{${declarations}}`);
}
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;
- /**
- * The class this document's tables take, which the default is scoped to. Two workbooks shown
- * together each add their own stylesheet to the one page, so an unscoped `.spreadsheet-table
- * td` rule would style the other's cells as well — and the cells it folded have no class of
- * their own left to say otherwise. Deriving it from the declarations keeps the sharing that
- * every other rule here relies on: two workbooks folding the same style scope to one class.
- */
- scope: 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(":"))));
}
/**
@@ -600,7 +475,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.cellClassFor(cssText)].filter(Boolean);
+ const names = [cellStyle?.bg?.rgb ? "has-fill" : "", classes.classFor(cssText)].filter(Boolean);
if (names.length) attrs.push(`class="${names.join(" ")}"`);
if (mergeInfo) {
if (mergeInfo.rowSpan > 1) attrs.push(`rowspan="${mergeInfo.rowSpan}"`);
@@ -1011,8 +886,7 @@ function cellBox(html: string, bound: SpillBound | null, height: number, classes
parts.push(CELL_LINE_HEIGHT);
// A box is shaped by its row's height rather than by anything the cell says, so a sheet has
- // only a handful of distinct ones however many cells it holds. `classFor`, not `cellClassFor`:
- // a box is not a cell, and must not count towards the style folded into the `td` default.
+ // only a handful of distinct ones however many cells it holds.
return `<span class="${classes.classFor(parts.join(";"))}">${html}</span>`;
}