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
fix(spreadsheet): scope the folded td default to its own workbook
Elian Doran1464b90fb87c
diff --git a/apps/client/src/services/spreadsheet_preview_styles.spec.ts b/apps/client/src/services/spreadsheet_preview_styles.spec.tsindex 0ac381d54d..ad91f4255a 100644--- a/apps/client/src/services/spreadsheet_preview_styles.spec.ts+++ b/apps/client/src/services/spreadsheet_preview_styles.spec.ts@@ -113,4 +113,35 @@ describe("spreadsheet preview styling", () => {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.tsindex 4f218b0813..fe98335a68 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts@@ -22,7 +22,8 @@ function withInlineStyles(html: string): string {// 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 td\{([^}]*)\}/.exec(stylesheet[1])?.[1] ?? "");+ 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[] = [];@@ -1706,7 +1707,7 @@ describe("renderSpreadsheetToHtml", () => {const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x" }, { showGridlines: 1 }));- expect(html).toContain('<table class="spreadsheet-table show-gridlines" style="width:88px">');+ expect(html).toMatch(/<table class="spreadsheet-table[^"]*\bshow-gridlines\b[^"]*" style="width:88px">/);});it("emits an explicit fixed table width summing the visible column widths", () => {@@ -1778,14 +1779,14 @@ describe("renderSpreadsheetToHtml", () => {it("shows gridlines by default when showGridlines is absent (editor default)", () => {// singleCellWorkbook does not set showGridlines.const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x" }));- expect(html).toContain("spreadsheet-table show-gridlines");+ expect(html).toMatch(/<table class="spreadsheet-table[^"]*\bshow-gridlines\b/);});it("omits show-gridlines when the sheet hides gridlines", () => {const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x" }, { showGridlines: 0 }));- expect(html).toContain('<table class="spreadsheet-table" style="width:88px">');+ expect(html).toMatch(/<table class="spreadsheet-table[^"]*" style="width:88px">/);expect(html).not.toContain("show-gridlines");});@@ -2586,7 +2587,7 @@ describe("style deduplication", () => {// 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).toMatch(/\.spreadsheet-table td\{[^}]*font-weight:bold/);+ 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.const name = /\.spreadsheet-table \.(sst-[\w-]+)\{font-style:italic/.exec(html)?.[1];@@ -2601,7 +2602,7 @@ describe("style deduplication", () => {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.- expect(rule).toMatch(/^(\.spreadsheet-table (\.sst-|td\{)|:where\(\.spreadsheet-table)/);+ expect(rule).toMatch(/^(\.spreadsheet-table(:where\(\.[\w-]+\))? (\.sst-|td\{)|:where\(\.spreadsheet-table)/);}});@@ -2640,7 +2641,7 @@ describe("style deduplication", () => {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 td\{[^}]*font-weight:bold/);+ 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);@@ -2652,7 +2653,7 @@ describe("style deduplication", () => {// what no declaration at all would have computed to.const html = renderRaw(gridWorkbook(rows(bold, bold, italic)));- expect(html).toMatch(/\.spreadsheet-table td\{[^}]*font-weight:bold/);+ expect(html).toMatch(/\.spreadsheet-table:where\(\.sstd-[\w-]+\) td\{[^}]*font-weight:bold/);expect(html).toMatch(/\.spreadsheet-table \.sst-[\w-]+\{[^}]*font-style:italic[^}]*font-weight:inherit\}/);});@@ -2662,7 +2663,7 @@ describe("style deduplication", () => {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).not.toMatch(/\.spreadsheet-table(?::where\(\.[\w-]+\))? td\{/);expect(html).toMatch(/<td class="has-fill sst-[\w-]+"/);});@@ -2675,7 +2676,7 @@ describe("style deduplication", () => {"1": { "0": bold }}));- expect(html).not.toContain(".spreadsheet-table td{");+ expect(html).not.toMatch(/\.spreadsheet-table(?::where\(\.[\w-]+\))? td\{/);expect(html).toContain("<td></td>");});});diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.tsindex dcb9807d65..fcb6a509ef 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts@@ -81,20 +81,21 @@ export function renderSpreadsheetToHtml(content: string | PersistedData): string// 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 ? dropFoldedClass(parts.join("\n"), fold.className) : parts.join("\n");+ const body = fold ? applyFold(parts.join("\n"), fold) : 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).+ * 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 dropFoldedClass(html: string, className: string): string {+function applyFold(html: string, fold: Fold): string {return html- .replaceAll(`<td class="${className}"`, "<td")- .replaceAll(`<td class="has-fill ${className}"`, `<td class="has-fill"`);+ .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"`);}/**@@ -105,8 +106,9 @@ function dropFoldedClass(html: string, className: string): string {function buildStylesheet(sheets: IWorksheetData[], classes: StyleClasses, fold: Fold | null): 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.- if (fold) rules.push(`.spreadsheet-table td{${fold.declarations}}`);+ // 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));return rules.length ? `<style>\n${rules.join("\n")}\n</style>` : "";@@ -200,7 +202,12 @@ class StyleClasses {if (missing.length) completions.set(other, missing.join(";"));}- return { declarations, className: this.nameFor(declarations), completions };+ return {+ declarations,+ className: this.nameFor(declarations),+ scope: `sstd-${hashDeclarations(declarations)}`,+ completions+ };}/**@@ -239,6 +246,14 @@ 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>;}