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
perf(spreadsheet): dedupe cell styling into a generated stylesheet
Elian Doran18d585354498
diff --git a/apps/client/src/print.css b/apps/client/src/print.cssindex b12950e81d..d6d49162ac 100644--- a/apps/client/src/print.css+++ b/apps/client/src/print.css@@ -305,7 +305,9 @@ span[style] {than a box-shadow because print engines routinely drop shadows. At 0.5pt it is narrowerthan every real cell border (>= 1px from the workbook data), so under border-collapsethe custom border always wins the conflict and is never clobbered. */-.spreadsheet-table.show-gridlines td:not(.has-fill) {+/* The context is in :where() so this stays a default: the renderer emits a cell's own styling+ as `.spreadsheet-table .sst-*` rules, which have to win over it. */+:where(.spreadsheet-table.show-gridlines) td:not(.has-fill) {border: 0.5pt solid var(--spreadsheet-gridline-color, #ccc);}diff --git a/apps/client/src/services/content_renderer.css b/apps/client/src/services/content_renderer.cssindex d0fca253bc..44a28d9fc9 100644--- a/apps/client/src/services/content_renderer.css+++ b/apps/client/src/services/content_renderer.css@@ -88,13 +88,17 @@table-layout: fixed;}-.office-preview-body .spreadsheet-table td {+/* The context is in :where() so this stays a default: the renderer emits a cell's own styling+ as `.spreadsheet-table .sst-*` rules, which have to win over it. */+:where(.office-preview-body .spreadsheet-table) td {padding: 2px 4px;white-space: nowrap;overflow: visible;}-.office-preview-body .spreadsheet-table.show-gridlines td:not(.has-fill) {+/* The context is in :where() so this stays a default: the renderer emits a cell's own styling+ as `.spreadsheet-table .sst-*` rules, which have to win over it. */+:where(.office-preview-body .spreadsheet-table.show-gridlines) td:not(.has-fill) {border: 1px solid var(--spreadsheet-gridline-color, var(--main-border-color));}diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.tsindex 5dd770a6c2..bfa61f92d6 100644--- a/apps/client/src/services/content_renderer.spec.ts+++ b/apps/client/src/services/content_renderer.spec.ts@@ -62,7 +62,7 @@ vi.mock("./mermaid.js", () => ({// isOfficeMimeType comes (unmocked) from @triliumnext/commons; only the server// round-trip is stubbed out.-const renderOfficeToHtml = vi.fn(async (..._args: any[]) => `<div class="office-doc">converted</div>`);+const renderOfficeToHtml = vi.fn(async (..._args: any[]) => ({ css: "", html: `<div class="office-doc">converted</div>` }));vi.mock("./office_renderer.js", () => ({renderOfficeToHtml: (...a: any[]) => renderOfficeToHtml(...a)}));@@ -414,6 +414,22 @@ describe("getRenderedContent office rendering", () => {expect($renderedContent.find(".file-open").length).toBe(1);});+ it("attaches a spreadsheet's stylesheet inside the preview body, as an element", async () => {+ renderOfficeToHtml.mockResolvedValueOnce({+ css: ".spreadsheet-table .sst-1{font-weight:bold}",+ html: '<table class="spreadsheet-table"><td class="sst-1">x</td></table>'+ });+ const note = buildNote({ title: "Book", type: "file" });+ note.mime = DOCX;++ const { $renderedContent } = await getRenderedContent(note);++ const $style = $renderedContent.find(".office-preview-body > style");+ expect($style.length).toBe(1);+ // Set as text, so the rules are never parsed as markup on the way in.+ expect($style.text()).toBe(".spreadsheet-table .sst-1{font-weight:bold}");+ });+it("shows an admonition (and drops the preview body) when conversion fails", async () => {renderOfficeToHtml.mockRejectedValueOnce(new Error("bad zip"));const note = buildNote({ title: "DocBad", type: "file" });diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex e5069259ec..34abb4b7fa 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -364,7 +364,14 @@ async function renderOffice(entity: FNote | FAttachment, $renderedContent: JQuer$renderedContent.append($content);try {- $body.html(await renderOfficeToHtml(entityType, entityId));+ const { css, html } = await renderOfficeToHtml(entityType, entityId);+ $body.html(html);+ if (css) {+ // Built as an element with its text set, never parsed as markup, so a cell's styling+ // cannot escape the rule it belongs to. It sits inside the preview body, so the+ // browser drops it along with the rest when this note is closed.+ $body.prepend($("<style>").text(css));+ }} catch (e) {console.warn("Failed to render office document preview:", getErrorMessage(e));$scroll.remove();diff --git a/apps/client/src/services/office_renderer.spec.ts b/apps/client/src/services/office_renderer.spec.tsindex 91a101aac4..33cae1fbdc 100644--- a/apps/client/src/services/office_renderer.spec.ts+++ b/apps/client/src/services/office_renderer.spec.ts@@ -15,7 +15,7 @@ beforeEach(() => vi.clearAllMocks());describe("renderOfficeToHtml", () => {it("fetches the server-rendered note preview and returns sanitized output", async () => {- const html = await renderOfficeToHtml("notes", "n1");+ const { html } = await renderOfficeToHtml("notes", "n1");expect(serverGet).toHaveBeenCalledWith("notes/n1/office-preview", undefined, true);expect(sanitizeNoteContentHtml).toHaveBeenCalledWith("<h1>Doc</h1>");@@ -34,7 +34,7 @@ describe("renderOfficeToHtml", () => {+ '<span style="color: #000080">keep</span></p>');- const html = await renderOfficeToHtml("notes", "n1");+ const { html } = await renderOfficeToHtml("notes", "n1");// The default hyperlink character style's color is gone (both on runs inside the// link and on the <a> itself)...@@ -52,7 +52,7 @@ describe("renderOfficeToHtml", () => {'<p><a href="https://triliumnotes.org/"><span style="color:#ea7500;">Trilium</span></a></p>');- const html = await renderOfficeToHtml("notes", "n1");+ const { html } = await renderOfficeToHtml("notes", "n1");expect(html).toContain("#ea7500");});@@ -62,4 +62,25 @@ describe("renderOfficeToHtml", () => {await expect(renderOfficeToHtml("notes", "n1")).rejects.toThrow(/conversion failed/);expect(sanitizeNoteContentHtml).not.toHaveBeenCalled();});++ it("splits a leading stylesheet off the fragment, keeping it clear of the sanitizer", async () => {+ serverGet.mockResolvedValueOnce(+ '<style>.spreadsheet-table .sst-1{font-weight:bold}</style>\n<table><td class="sst-1">x</td></table>');++ const { css, html } = await renderOfficeToHtml("notes", "n1");++ expect(css).toBe(".spreadsheet-table .sst-1{font-weight:bold}");+ expect(sanitizeNoteContentHtml).toHaveBeenCalledWith('<table><td class="sst-1">x</td></table>');+ expect(html).not.toContain("<style>");+ });++ it("returns no stylesheet for a fragment that carries none, or an unterminated one", async () => {+ serverGet.mockResolvedValueOnce("<p>plain</p>");+ expect((await renderOfficeToHtml("notes", "n1")).css).toBe("");++ serverGet.mockResolvedValueOnce("<style>.a{b:c}");+ const truncated = await renderOfficeToHtml("notes", "n1");+ expect(truncated.css).toBe("");+ expect(sanitizeNoteContentHtml).toHaveBeenCalledWith("<style>.a{b:c}");+ });});diff --git a/apps/client/src/services/office_renderer.ts b/apps/client/src/services/office_renderer.tsindex 83e995fa92..c157abfa48 100644--- a/apps/client/src/services/office_renderer.ts+++ b/apps/client/src/services/office_renderer.ts@@ -9,14 +9,44 @@ import server from "./server.js";* The route sends the fragment as the response body, so it is fetched as text rather than* through a JSON envelope.*+ * A spreadsheet fragment starts with a `<style>` holding the cell styling, which the sanitizer+ * would strip. It is split off first and returned separately so the caller can attach it as an+ * element rather than as markup, keeping it clear of the sanitizer without reaching the DOM as+ * text. Every rule it carries is scoped under `.spreadsheet-table` by the renderer.+ ** Throws if the document is too large, unsupported, or conversion fails — callers should* catch and fall back to the usual download / open-externally affordance.*/-export async function renderOfficeToHtml(entityType: "notes" | "attachments", entityId: string): Promise<string> {+export async function renderOfficeToHtml(entityType: "notes" | "attachments", entityId: string): Promise<OfficePreview> {// `raw` keeps the response a plain string; the route sends the fragment as the body.- const html = await server.get<string>(`${entityType}/${entityId}/office-preview`, undefined, true);+ const body = await server.get<string>(`${entityType}/${entityId}/office-preview`, undefined, true);+ const { css, html } = splitStylesheet(body);++ return { css, html: stripLinkColors(sanitizeNoteContentHtml(html)) };+}++export interface OfficePreview {+ /** The rules the fragment's classes refer to, or "" when it carries none. */+ css: string;+ /** The sanitized markup. */+ html: string;+}++/**+ * Splits a leading `<style>` off the fragment. The renderer always emits it first, so this reads+ * a bounded prefix instead of parsing the document — which for a spreadsheet runs to megabytes.+ */+function splitStylesheet(body: string): OfficePreview {+ if (!body.startsWith("<style>")) {+ return { css: "", html: body };+ }++ const end = body.indexOf("</style>");+ if (end < 0) {+ return { css: "", html: body };+ }- return stripLinkColors(sanitizeNoteContentHtml(html));+ return { css: body.slice("<style>".length, end), html: body.slice(end + "</style>".length).trimStart() };}/**diff --git a/apps/client/src/services/spreadsheet_preview_styles.spec.ts b/apps/client/src/services/spreadsheet_preview_styles.spec.tsnew file mode 100644index 0000000000..17705aa96b--- /dev/null+++ b/apps/client/src/services/spreadsheet_preview_styles.spec.ts@@ -0,0 +1,58 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";++import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";+import { describe, expect, it } from "vitest";++/**+ * The renderer emits a workbook's cell styling as `.spreadsheet-table .sst-*` rules, while+ * content_renderer.css supplies the defaults every cell starts from. Those two have to stay on+ * speaking terms: if a default ever outranks a generated rule, cells silently lose their+ * borders, wrapping or clipping. This renders a workbook against the real stylesheet and reads+ * the computed styles back, which is the only way that contract shows up as a test failure.+ */+function spreadsheetRulesFrom(stylesheet: string): string {+ const css = readFileSync(join(__dirname, stylesheet), "utf-8");+ return (css.match(/[^{}]*spreadsheet-table[^{]*\{[^}]*\}/g) ?? []).join("\n");+}++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": {+ // Wraps and carries its own border, both of which the defaults also set.+ "0": { v: "a long wrapped label", t: 1, s: { tb: 3, bd: { t: { s: 3, cl: { rgb: "#FF0000" } } } } },+ "1": { v: "next", t: 1 }+ }+ },+ rowData: {}, columnData: {}+ }+ }+ }+});++describe("spreadsheet preview styling", () => {+ it("lets a cell's own styling outrank the preview defaults, which still reach a plain cell", () => {+ document.head.innerHTML = `<style>${spreadsheetRulesFrom("content_renderer.css")}</style>`;+ document.body.innerHTML = `<div class="ck-content office-preview-body">${renderSpreadsheetToHtml(WORKBOOK)}</div>`;++ const [styled, plain] = document.querySelectorAll("td");+ const styledCss = getComputedStyle(styled);++ expect(styledCss.whiteSpace).toBe("normal");+ expect(styledCss.borderTopStyle).toBe("dotted");+ expect(styledCss.borderTopColor).toBe("#FF0000");++ // A cell that styles nothing still picks up the gridline and padding defaults.+ const plainCss = getComputedStyle(plain);+ expect(plainCss.borderTopStyle).toBe("solid");+ expect(plainCss.paddingLeft).toBe("4px");+ });+});diff --git a/apps/client/src/widgets/type_widgets/file/Office.tsx b/apps/client/src/widgets/type_widgets/file/Office.tsxindex de2c906474..4b775cce40 100644--- a/apps/client/src/widgets/type_widgets/file/Office.tsx+++ b/apps/client/src/widgets/type_widgets/file/Office.tsx@@ -2,7 +2,7 @@ import { useEffect, useState } from "preact/hooks";import FNote from "../../../entities/fnote";import { t } from "../../../services/i18n";-import { renderOfficeToHtml } from "../../../services/office_renderer";+import { type OfficePreview, renderOfficeToHtml } from "../../../services/office_renderer";import Alert from "../../react/Alert";import LoadingSpinner from "../../react/LoadingSpinner";@@ -13,17 +13,17 @@ import LoadingSpinner from "../../react/LoadingSpinner";* affordances).*/export default function OfficePreview({ note }: { note: FNote }) {- const [html, setHtml] = useState<string | null>(null);+ const [preview, setPreview] = useState<OfficePreview | null>(null);const [failed, setFailed] = useState(false);useEffect(() => {let cancelled = false;- setHtml(null);+ setPreview(null);setFailed(false);renderOfficeToHtml("notes", note.noteId).then((result) => {- if (!cancelled) setHtml(result);+ if (!cancelled) setPreview(result);}).catch((e) => {console.warn("Failed to render office document preview:", e);@@ -43,7 +43,7 @@ export default function OfficePreview({ note }: { note: FNote }) {);}- if (html === null) {+ if (preview === null) {return (<div class="office-preview-loading"><LoadingSpinner />@@ -52,5 +52,12 @@ export default function OfficePreview({ note }: { note: FNote }) {);}- return <div class="ck-content office-preview-body selectable-text" dangerouslySetInnerHTML={{ __html: html }} />;+ return (+ <>+ {/* A spreadsheet's cell styling, which the sanitizer strips out of the markup. Rendered+ as an element with a text child rather than parsed, and unmounted with the preview. */}+ {preview.css && <style>{preview.css}</style>}+ <div class="ck-content office-preview-body selectable-text" dangerouslySetInnerHTML={{ __html: preview.html }} />+ </>+ );}diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_html.spec.tsindex 1bdc6a74d5..0316010618 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts@@ -1,5 +1,35 @@import { describe, expect, it } from "vitest";-import { renderSpreadsheetToHtml } from "./render_to_html.js";+import { renderSpreadsheetToHtml as renderRaw } from "./render_to_html.js";++/**+ * Renders, then expands the emitted `<style>` back into `style` attributes, so a test asserts on+ * the declarations a cell resolves to rather than on generated class names. What the renderer+ * actually emits is covered by the "style deduplication" block, which uses `renderRaw`.+ */+function renderSpreadsheetToHtml(jsonContent: string): string {+ return withInlineStyles(renderRaw(jsonContent));+}++function withInlineStyles(html: string): string {+ const stylesheet = /^<style>([\s\S]*?)<\/style>\n/.exec(html);+ if (!stylesheet) return html;++ const declarations = new Map<string, string>();+ for (const rule of stylesheet[1].matchAll(/\.spreadsheet-table \.([\w-]+)\{([^}]*)\}/g)) {+ declarations.set(rule[1], rule[2]);+ }++ return html.slice(stylesheet[0].length).replace(/ class="([^"]*)"/g, (_whole, names: string) => {+ const kept: string[] = [];+ const css: string[] = [];+ for (const name of names.split(" ")) {+ const declaration = declarations.get(name);+ if (declaration) css.push(declaration);+ else kept.push(name);+ }+ return (kept.length ? ` class="${kept.join(" ")}"` : "") + (css.length ? ` style="${css.join(";")}"` : "");+ });+}import { BorderStyle, HorizontalAlign, WrapStrategy } from "./workbook_model.js";describe("renderSpreadsheetToHtml", () => {@@ -376,9 +406,11 @@ describe("renderSpreadsheetToHtml", () => {}});- const html = renderSpreadsheetToHtml(input);+ const html = renderRaw(input);expect(html).not.toContain("<script>");- expect(html).not.toContain("</style>");+ // The value cannot close the stylesheet it is written into: exactly the one this+ // renderer emits, and nothing after it that a font name smuggled in.+ expect(html.match(/<\/style>/g)).toHaveLength(1);expect(html).toContain("font-family:Arial");});@@ -2176,3 +2208,63 @@ describe("renderSpreadsheetToHtml", () => {expect(html).not.toContain("Empty sheet");});});++describe("style deduplication", () => {+ const gridWorkbook = (cellData: Record<string, unknown>) => JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: ["s1"],+ styles: {},+ sheets: {+ s1: {+ id: "s1", name: "Sheet1", hidden: 0, rowCount: 1000, columnCount: 20,+ mergeData: [], cellData, rowData: {}, columnData: {}+ }+ }+ }+ });++ 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 } }));++ expect(html.startsWith("<style>")).toBe(true);+ // One rule for the three bold cells, not three copies of the declaration.+ expect(html.match(/font-weight:bold/g)).toHaveLength(1);++ const name = /\.spreadsheet-table \.(sst-[\w-]+)\{font-weight:bold\}/.exec(html)?.[1];+ expect(name).toBeTruthy();+ expect(html.match(new RegExp(`class="${name}"`, "g"))).toHaveLength(3);+ });++ 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] ?? "";++ expect(stylesheet).toBeTruthy();+ for (const rule of stylesheet.split("}").filter(Boolean)) {+ expect(rule).toMatch(/^\.spreadsheet-table \.sst-/);+ }+ });++ 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 } } } }));++ const nameIn = (html: string) => /\.spreadsheet-table \.(sst-[\w-]+)\{font-weight:bold\}/.exec(html)?.[1];+ 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]);+ });++ 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-]+"/);++ expect(renderRaw(JSON.stringify({ version: 1, workbook: { sheetOrder: [], styles: {}, sheets: {} } })))+ .not.toContain("<style>");+ });+});diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.tsindex 44f3cc2f3e..79e57171ed 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts@@ -41,7 +41,8 @@ import {/*** Parses the raw JSON content of a spreadsheet note and renders it as HTML.- * Returns an HTML string containing one `<table>` per visible sheet.+ * Returns an HTML string containing one `<table>` per visible sheet, preceded by a `<style>`+ * holding the cell styling (see {@link StyleClasses}) when the workbook has any.*/export function renderSpreadsheetToHtml(jsonContent: string): string {const { ok, data } = parseWorkbookData(jsonContent);@@ -60,17 +61,78 @@ export function renderSpreadsheetToHtml(jsonContent: string): string {return "<p>Empty spreadsheet.</p>";}+ const classes = new StyleClasses();const parts: string[] = [];for (const sheet of visibleSheets) {if (visibleSheets.length > 1) {parts.push(`<h3>${escapeHtml(sheet.name)}</h3>`);}const images = placeFloatingImages(sheet, getFloatingDrawings(workbook, sheet.id));- const table = renderSheet(sheet, workbook.styles ?? {}, images);+ const table = renderSheet(sheet, workbook.styles ?? {}, images, classes);parts.push(wrapWithFloatingImages(table, images));}- return parts.join("\n");+ // 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 = classes.toStylesheet();+ return stylesheet ? `${stylesheet}\n${parts.join("\n")}` : parts.join("\n");+}++/**+ * Collects the declarations a render emits and hands back a class for each distinct one, so a+ * style shared by thousands of cells is written once in a `<style>` instead of on every cell.+ * Workbooks have very few distinct cell styles (Excel itself stores them in a shared table), so+ * this trades a per-cell `style` attribute for a short class name.+ *+ * Class names are derived from the declarations, not from a counter: the same style yields the+ * same name in every document, so two spreadsheets rendered onto one page share a rule rather+ * than colliding, and nothing has to be threaded through the renderer to keep names unique.+ * Every rule is scoped under `.spreadsheet-table`, so a name that happened to match an+ * application class still cannot reach anything outside a rendered sheet.+ */+class StyleClasses {+ private readonly names = new Map<string, string>();++ /** Returns the class for `declarations`, or "" when there is nothing to style. */+ classFor(declarations: string): string {+ if (!declarations) return "";++ let name = this.names.get(declarations);+ if (!name) {+ name = `sst-${hashDeclarations(declarations)}`;+ this.names.set(declarations, name);+ }+ return name;+ }++ /** Builds the `<style>` element for everything collected, or "" when nothing was. */+ toStylesheet(): string {+ if (this.names.size === 0) return "";++ const rules: string[] = [];+ for (const [declarations, name] of this.names) {+ rules.push(`.spreadsheet-table .${name}{${declarations}}`);+ }++ // 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 this element or its rule.+ return `<style>${rules.join("")}</style>`;+ }+}++/**+ * Hashes a declaration string (FNV-1a, base36) for use in a class name. A collision would show+ * one style where another was meant, never a wrong document, and 32 bits is far more than the+ * handful of distinct styles a workbook carries.+ */+function hashDeclarations(declarations: string): string {+ let hash = 0x811c9dc5;+ for (let i = 0; i < declarations.length; i++) {+ hash ^= declarations.charCodeAt(i);+ hash = Math.imul(hash, 0x01000193);+ }+ return (hash >>> 0).toString(36);}// #region Images@@ -240,7 +302,7 @@ function trackIndexAtPx(targetPx: number, defaultSize: number, count: number | u// #endregion-function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData | null>, images: PlacedImage[]): string {+function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData | null>, images: PlacedImage[], classes: StyleClasses): string {const { cellData, mergeData = [], columnData = {}, rowData = {} } = sheet;// Determine the actual bounds (only cells with data), then extend them to cover any floating@@ -275,7 +337,7 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |lines.push("<colgroup>");for (const width of colWidths) {- lines.push(`<col style="width:${px(width)}px">`);+ lines.push(`<col class="${classes.classFor(`width:${px(width)}px`)}">`);}lines.push("</colgroup>");@@ -289,7 +351,7 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |// Univer leaves a cell at the bottom of its row unless it sets `vt`, while HTML centres it.// The row carries that default because a `td` inherits `vertical-align`, so a cell that// sets its own still wins.- lines.push(`<tr style="height:${height}px;vertical-align:bottom">`);+ lines.push(`<tr class="${classes.classFor(`height:${height}px;vertical-align:bottom`)}">`);const neighbours: RowNeighbours = { row, minCol, maxCol, cellData, columnData, mergeMap };@@ -310,8 +372,8 @@ 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).- if (cellStyle?.bg?.rgb) attrs.push(`class="has-fill"`);- if (cssText) attrs.push(`style="${cssText}"`);+ 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}"`);if (mergeInfo.colSpan > 1) attrs.push(`colspan="${mergeInfo.colSpan}"`);diff --git a/packages/share-theme/src/styles/content.css b/packages/share-theme/src/styles/content.cssindex 97407ed7f3..558bd899c8 100644--- a/packages/share-theme/src/styles/content.css+++ b/packages/share-theme/src/styles/content.css@@ -142,7 +142,9 @@ body.type-webView {A real data border at the same 1px width ties the gridline under collapse and wins bysource order, so heavier (>=2px) and filled-cell borders always show; an unfilled cell'sown 1px border may cede its top/left edge to a neighbour's gridline — fine for a faint grid. */-.spreadsheet-table.show-gridlines td:not(.has-fill) {+/* The context is in :where() so this stays a default: the renderer emits a cell's own styling+ as `.spreadsheet-table .sst-*` rules, which have to win over it. */+:where(.spreadsheet-table.show-gridlines) td:not(.has-fill) {border: 1px solid var(--spreadsheet-gridline-color, var(--background-highlight));}