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
client/spreadsheet/print & PDF export: accurately follow row heights, fix image positioning drift
Adorian Doran9f1f5f9758e3
diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_html.spec.tsindex 4bc4cf660c..9d2eef0f23 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts@@ -2,6 +2,18 @@ import { describe, expect, it } from "vitest";import { renderSpreadsheetToHtml } from "./render_to_html.js";import { BorderStyle, HorizontalAlign, WrapStrategy } from "./workbook_model.js";+/**+ * The markup with the box model stripped: each cell's sizing box and the padding it is measured+ * against, leaving the content and the cell's own theming.+ */+function unboxed(html: string): string {+ return html+ .replace(/<td([^>]*)><span style="display:block;overflow:hidden[^"]*">([\s\S]*?)<\/span><\/td>/g, "<td$1>$2</td>")+ .replace(/padding:[^;"]*;?/g, "")+ .replace(/;"/g, '"')+ .replace(/ style=""/g, "");+}+describe("renderSpreadsheetToHtml", () => {it("renders a basic spreadsheet with values and styles", () => {const input = JSON.stringify({@@ -513,22 +525,22 @@ describe("renderSpreadsheetToHtml", () => {// A quarter turn either way becomes a vertical writing mode, so the row can grow to fit it.expect(rotated({ a: 90 })).toContain(- `<span style="display:inline-block;writing-mode:vertical-rl;transform:rotate(180deg)">Days left</span>`);+ `<span style="display:inline-block;vertical-align:top;writing-mode:vertical-rl;transform:rotate(180deg)">Days left</span>`);expect(rotated({ a: -90 })).toContain(- `<span style="display:inline-block;writing-mode:vertical-rl">Days left</span>`);+ `<span style="display:inline-block;vertical-align:top;writing-mode:vertical-rl">Days left</span>`);// Stacked text reads downwards with upright characters.expect(rotated({ v: 1 })).toContain(- `<span style="display:inline-block;writing-mode:vertical-rl;text-orientation:upright">Days left</span>`);+ `<span style="display:inline-block;vertical-align:top;writing-mode:vertical-rl;text-orientation:upright">Days left</span>`);// Any other angle turns the glyphs; CSS rotates clockwise, so the sign flips.expect(rotated({ a: 45 })).toContain(- `<span style="display:inline-block;transform:rotate(-45deg)">Days left</span>`);+ `<span style="display:inline-block;vertical-align:top;transform:rotate(-45deg)">Days left</span>`);expect(rotated({ a: -30.5 })).toContain(`transform:rotate(30.5deg)`);});it("leaves a cell unwrapped when it has no rotation to apply", () => {- const plain = (s: unknown) => renderSpreadsheetToHtml(singleCellWorkbook({ v: "Days left", t: 1, s }));+ const plain = (s: unknown) => unboxed(renderSpreadsheetToHtml(singleCellWorkbook({ v: "Days left", t: 1, s })));expect(plain({})).toContain("<td>Days left</td>");expect(plain({ tr: { a: 0, v: 0 } })).toContain("<td>Days left</td>");@@ -549,7 +561,7 @@ describe("renderSpreadsheetToHtml", () => {}}));- expect(html).toContain(`Days left</span><img class="spreadsheet-cell-image"`);+ expect(html).toContain(`Days left</span></span><img class="spreadsheet-cell-image"`);});describe("overflow into neighbouring cells", () => {@@ -599,9 +611,9 @@ describe("renderSpreadsheetToHtml", () => {expect(room(row({ 0: { v: "a long label", t: 1 }, 1: { v: "next", t: 1 } }), 0)).toEqual([0, 0]);// Nothing in the way, so the stylesheets are left to spill the cell as the editor does.- expect(room(row({ 0: { v: "a long label", t: 1 } }), 0)).toBeNull();- expect(room(row({ 0: { v: "a long label", t: 1 }, 1: { s: { bl: 1 } } }), 0)).toBeNull();- expect(room(row({ 0: { v: "a long label", t: 1 }, 1: { v: "", t: 1 } }), 0)).toBeNull();+ expect(room(row({ 0: { v: "a long label", t: 1 } }), 0)).toEqual([0, 0]);+ expect(room(row({ 0: { v: "a long label", t: 1 }, 1: { s: { bl: 1 } } }), 0)).toEqual([0, 88]);+ expect(room(row({ 0: { v: "a long label", t: 1 }, 1: { v: "", t: 1 } }), 0)).toEqual([0, 88]);});it("gives the text the width of the empty cells it may run across", () => {@@ -621,11 +633,11 @@ describe("renderSpreadsheetToHtml", () => {it("follows the alignment to decide which side the text spills towards", () => {const rightAligned = { t: 1, s: { ht: HorizontalAlign.RIGHT } };expect(room(row({ 0: { v: "before", t: 1 }, 1: { v: "x", ...rightAligned } }), 1)).toEqual([0, 0]);- expect(room(row({ 1: { v: "x", ...rightAligned }, 2: { v: "after", t: 1 } }), 1)).toBeNull();+ expect(room(row({ 1: { v: "x", ...rightAligned }, 2: { v: "after", t: 1 } }), 1)).toEqual([88, 0]);const centered = { t: 1, s: { ht: HorizontalAlign.CENTER } };expect(room(row({ 0: { v: "before", t: 1 }, 1: { v: "x", ...centered } }), 1)).toEqual([0, 0]);- expect(room(row({ 1: { v: "x", ...centered } }), 1)).toBeNull();+ expect(room(row({ 1: { v: "x", ...centered } }), 1)).toEqual([88, 0]);// Stopped on the right, with the empty column on its left still open to it.expect(room(row({ 1: { v: "x", ...centered }, 2: { v: "after", t: 1 } }), 1)).toEqual([88, 0]);@@ -636,7 +648,7 @@ describe("renderSpreadsheetToHtml", () => {expect(room(row({ 0: { v: true, t: 3 } }), 0)).toEqual([0, 0]);expect(room(row({ 0: { v: "a long label", t: 1, s: { tb: WrapStrategy.CLIP } } }), 0)).toEqual([0, 0]);- expect(room(row({ 0: { v: "a long label", t: 1, s: { tb: WrapStrategy.WRAP } }, 1: { v: "next", t: 1 } }), 0)).toBeNull();+ expect(room(row({ 0: { v: "a long label", t: 1, s: { tb: WrapStrategy.WRAP } }, 1: { v: "next", t: 1 } }), 0)).toEqual([0, 0]);expect(room(row({ 0: { s: { bl: 1 } }, 1: { v: "next", t: 1 } }), 0)).toBeNull();});@@ -644,13 +656,13 @@ describe("renderSpreadsheetToHtml", () => {const long = { v: "a long label", t: 1 };// A hidden column reaches nobody, so the cell steps over it in both directions.- expect(room(row({ 0: long, 1: { v: "next", t: 1 } }, { columnData: { 1: { hd: 1 } } }), 0)).toBeNull();+ expect(room(row({ 0: long, 1: { v: "next", t: 1 } }, { columnData: { 1: { hd: 1 } } }), 0)).toEqual([0, 0]);expect(room(row({ 0: long, 1: {}, 2: { v: "next", t: 1 } }, { columnData: { 1: { hd: 1 } } }), 0)).toEqual([0, 0]);// A merged cell starts looking past the last column its own range covers.const merged = [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 }];expect(room(row({ 0: long, 1: {}, 2: { v: "next", t: 1 } }, { mergeData: merged }), 0)).toEqual([0, 0]);- expect(room(row({ 0: long, 1: {} }, { mergeData: merged }), 0)).toBeNull();+ expect(room(row({ 0: long, 1: {} }, { mergeData: merged }), 0)).toEqual([0, 0]);});it("reads a column a merge spans into as holding that range's content", () => {@@ -660,7 +672,7 @@ describe("renderSpreadsheetToHtml", () => {{ mergeData: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }] }));- expect(html.split("</tr>")[1]).toContain(`<td style="text-align:right;overflow:hidden">x</td>`);+ expect(unboxed(html).split("</tr>")[1]).toContain(`<td style="text-align:right">x</td>`);});it("counts a cell whose text lives only in its rich-text document as occupied", () => {@@ -887,7 +899,7 @@ describe("renderSpreadsheetToHtml", () => {const html = renderSpreadsheetToHtml(input);expect(html).toContain("noStyle");// Missing style id resolves to null -> no inline style attribute.- expect(html).toContain("<td>noStyle</td>");+ expect(unboxed(html)).toContain("<td>noStyle</td>");});it("renders bold, italic and underline inline styles", () => {@@ -953,7 +965,7 @@ describe("renderSpreadsheetToHtml", () => {it("omits text-align for an unknown horizontal alignment", () => {const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x", s: { ht: 9 } }));expect(html).not.toContain("text-align");- expect(html).toContain("<td>x</td>");+ expect(unboxed(html)).toContain("<td>x</td>");});it("wraps a cell whose style enables the wrap strategy", () => {@@ -1009,7 +1021,7 @@ describe("renderSpreadsheetToHtml", () => {it("omits vertical-align for an unknown vertical alignment", () => {const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x", s: { vt: 9 } }));// The cell contributes none, so it falls back to the row's.- expect(html).toContain("<td>x</td>");+ expect(unboxed(html)).toContain("<td>x</td>");expect(html).toContain(`<tr style="height:24px;vertical-align:bottom">`);});@@ -1017,10 +1029,10 @@ describe("renderSpreadsheetToHtml", () => {// Univer leaves a cell at the bottom of its row unless it sets `vt`, unlike HTML.const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x" }));expect(html).toContain(`<tr style="height:24px;vertical-align:bottom">`);- expect(html).toContain("<td>x</td>");+ expect(unboxed(html)).toContain("<td>x</td>");const middle = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x", s: { vt: 2 } }));- expect(middle).toContain(`<td style="vertical-align:middle">x</td>`);+ expect(unboxed(middle)).toContain(`<td style="vertical-align:middle">x</td>`);});it("renders borders on all four sides with the correct Univer widths and styles", () => {@@ -1165,8 +1177,8 @@ describe("renderSpreadsheetToHtml", () => {expect(html).toContain("color:#ff0000");expect(html).toContain("byId");// null style id and empty style object -> no styling of their own.- expect(html).toContain(`<td style="overflow:hidden">nulled</td>`);- expect(html).toContain("<td>emptyStyle</td>");+ expect(unboxed(html)).toContain("<td>nulled</td>");+ expect(unboxed(html)).toContain("<td>emptyStyle</td>");});it("skips hidden rows and hidden columns", () => {@@ -1229,6 +1241,37 @@ describe("renderSpreadsheetToHtml", () => {expect(html).toContain('<tr style="height:50px;vertical-align:bottom">');});+ it("takes a self-sizing row's height from the height Univer measured for it", () => {+ const html = renderSpreadsheetToHtml(JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: ["s1"],+ styles: {},+ sheets: {+ s1: {+ id: "s1",+ name: "Sheet1",+ hidden: 0,+ mergeData: [],+ cellData: { "0": { "0": { v: "a" } }, "1": { "0": { v: "b" } }, "2": { "0": { v: "c" } }, "3": { "0": { v: "d" } } },+ rowData: {+ // Measured with no `ia`, and measured while explicitly self-sizing.+ "0": { ah: 34 },+ "1": { ah: 40, h: 20, ia: 1 },+ // Sized by hand, so the measurement is ignored even when both are there.+ "2": { ah: 24, h: 99, ia: 0 },+ "3": { h: 55, ia: 0 }+ },+ columnData: {}+ }+ }+ }+ }));++ const heights = [...html.matchAll(/<tr style="height:([\d.]+)px/g)].map((match) => Number(match[1]));+ expect(heights).toEqual([34, 40, 99, 55]);+ });+it("falls back to default column width and row height when absent", () => {const input = JSON.stringify({version: 1,@@ -1292,29 +1335,29 @@ describe("renderSpreadsheetToHtml", () => {const html = renderSpreadsheetToHtml(input);// Column 1 between A and C has no cell -> empty <td>.expect(html).toContain("<td></td>");- expect(html).toContain("<td>C</td>");+ expect(unboxed(html)).toContain("<td>C</td>");// A may run across the empty column, so its text carries the room it has.- expect(html).toContain(`<td><span style="display:inline-block;width:calc(100% + 88px);overflow:hidden;margin-right:-88px">A</span></td>`);+ expect(html).toContain(`<td style="padding:0px 2px 2px 2px"><span style="display:block;overflow:hidden;max-height:22px;width:calc(100% + 88px);margin-right:-88px">A</span></td>`);});it("renders numeric cell values", () => {const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: 42, t: 2 }));- expect(html).toContain(">42</td>");+ expect(unboxed(html)).toContain(">42</td>");});it("aligns a cell by its value type when it sets no alignment of its own", () => {// Univer right-aligns numbers and centers booleans; text keeps the table default.- expect(renderSpreadsheetToHtml(singleCellWorkbook({ v: 42, t: 2 }))).toContain(`<td style="text-align:right;overflow:hidden">`);- expect(renderSpreadsheetToHtml(singleCellWorkbook({ v: true, t: 3 }))).toContain(`<td style="text-align:center;overflow:hidden">`);- expect(renderSpreadsheetToHtml(singleCellWorkbook({ v: "A", t: 1 }))).toContain("<td>A</td>");+ expect(unboxed(renderSpreadsheetToHtml(singleCellWorkbook({ v: 42, t: 2 })))).toContain(`<td style="text-align:right">`);+ expect(unboxed(renderSpreadsheetToHtml(singleCellWorkbook({ v: true, t: 3 })))).toContain(`<td style="text-align:center">`);+ expect(unboxed(renderSpreadsheetToHtml(singleCellWorkbook({ v: "A", t: 1 })))).toContain("<td>A</td>");// A number formatted and styled by the workbook still gets the fallback alignment.- expect(renderSpreadsheetToHtml(singleCellWorkbook({ v: 42, t: 2, s: { bl: 1 } })))- .toContain(`<td style="text-align:right;font-weight:bold;overflow:hidden">`);+ expect(unboxed(renderSpreadsheetToHtml(singleCellWorkbook({ v: 42, t: 2, s: { bl: 1 } }))))+ .toContain(`<td style="text-align:right;font-weight:bold">`);// An explicit alignment wins over the fallback.- expect(renderSpreadsheetToHtml(singleCellWorkbook({ v: 42, t: 2, s: { ht: HorizontalAlign.LEFT } })))- .toContain(`<td style="text-align:left;overflow:hidden">`);+ expect(unboxed(renderSpreadsheetToHtml(singleCellWorkbook({ v: 42, t: 2, s: { ht: HorizontalAlign.LEFT } }))))+ .toContain(`<td style="text-align:left">`);});it("emits colspan only for a purely horizontal merge", () => {@@ -1373,7 +1416,7 @@ describe("renderSpreadsheetToHtml", () => {const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: 1234.5, t: 2, s: { n: { pattern: "#,##0.00" } } }));- expect(html).toContain(">1,234.50</td>");+ expect(unboxed(html)).toContain(">1,234.50</td>");expect(html).not.toContain("1234.5<");});@@ -1473,7 +1516,7 @@ describe("renderSpreadsheetToHtml", () => {const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "n/a", t: 1, s: { n: { pattern: "#,##0.00" } } }));- expect(html).toContain("<td>n/a</td>");+ expect(unboxed(html)).toContain("<td>n/a</td>");});it("falls back to the raw value for an invalid pattern instead of throwing", () => {@@ -1487,7 +1530,7 @@ describe("renderSpreadsheetToHtml", () => {it("renders an unformatted number when no pattern is set", () => {const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: 1234.5, t: 2 }));- expect(html).toContain(">1234.5</td>");+ expect(unboxed(html)).toContain(">1234.5</td>");});it("marks the table with show-gridlines when the sheet has gridlines enabled", () => {diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.tsindex 7581886a72..41680fd853 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts@@ -15,6 +15,8 @@ import { format as formatNumfmt, formatColor as formatNumfmtColor } from "numfmtimport {BorderStyle,type CellDocumentSegment,+ DEFAULT_CELL_PADDING,+ type IPaddingData,type CellMatrix,CellValueType,computeBounds,@@ -29,6 +31,7 @@ import {type IColumnData,isFiniteNumber,type IRange,+ type IRowData,type ISheetDrawing,type IStyleData,type ITextRotation,@@ -213,29 +216,49 @@ function extendBoundsForImages(sheet: IWorksheetData, maxRow: number, maxCol: nu}if (bottomPx <= 0 && rightPx <= 0) return { maxRow, maxCol };+ const defaultHeight = sheet.defaultRowHeight ?? 24;+ const defaultWidth = sheet.defaultColumnWidth ?? 88;return {- maxRow: Math.max(maxRow, trackIndexAtPx(bottomPx, sheet.defaultRowHeight ?? 24, sheet.rowCount, (i) => sheet.rowData?.[i])),- maxCol: Math.max(maxCol, trackIndexAtPx(rightPx, sheet.defaultColumnWidth ?? 88, sheet.columnCount, (i) => sheet.columnData?.[i]))+ maxRow: Math.max(maxRow, trackIndexAtPx(bottomPx, sheet.rowCount, (i) => {+ const meta = sheet.rowData?.[i];+ return meta?.hd ? 0 : rowHeight(meta, defaultHeight);+ })),+ maxCol: Math.max(maxCol, trackIndexAtPx(rightPx, sheet.columnCount, (i) => {+ const meta = sheet.columnData?.[i];+ return meta?.hd ? 0 : (isFiniteNumber(meta?.w) ? meta.w : defaultWidth);+ }))};}+/**+ * A row's rendered height. Univer keeps the height it measured for a self-sizing row in `ah` and+ * uses that unless the row was sized by hand (`ia === 0`), where `h` wins (`getRowHeight` in+ * `@univerjs/core`). Reading only `h` leaves a self-sizing row at the sheet default, which shortens+ * the grid and pulls the floating images, placed in the editor's coordinates, out of line with it.+ */+function rowHeight(meta: IRowData | undefined, defaultHeight: number): number {+ const measured = meta?.ah;+ if ((meta?.ia == null || meta.ia === 1) && isFiniteNumber(measured)) return measured;++ const height = meta?.h;+ return isFiniteNumber(height) ? height : defaultHeight;+}+/*** Returns the 0-based index of the last row/column needed to reach `targetPx` from the sheet- * origin, walking the per-track sizes (`h`/`w`, hidden tracks contributing 0) and falling back to- * `defaultSize`. Bounded by `count` (or a large cap) so a zero/degenerate size can't loop forever.+ * origin, walking the per-track sizes. Bounded by `count` (or a large cap) so a degenerate size+ * can't loop forever, and an axis whose tracks all measure zero extends by nothing at all.*/-function trackIndexAtPx(targetPx: number, defaultSize: number, count: number | undefined, meta: (index: number) => { hd?: number; h?: number; w?: number } | undefined): number {- if (targetPx <= 0 || defaultSize <= 0) return 0;+function trackIndexAtPx(targetPx: number, count: number | undefined, size: (index: number) => number): number {+ if (targetPx <= 0) return 0;const cap = isFiniteNumber(count) && count > 0 ? count : 100000;let cumulative = 0;let index = 0;while (cumulative < targetPx && index < cap) {- const track = meta(index);- const size = track?.h ?? track?.w;- cumulative += track?.hd ? 0 : (isFiniteNumber(size) ? size : defaultSize);+ cumulative += size(index);index++;}- return index - 1;+ return cumulative > 0 ? index - 1 : 0;}// #endregion@@ -280,12 +303,16 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |lines.push("</colgroup>");const defaultHeight = sheet.defaultRowHeight ?? 24;+ const heights: number[] = [];+ for (let row = minRow; row <= maxRow; row++) {+ heights[row] = rowData[row]?.hd ? 0 : rowHeight(rowData[row], defaultHeight);+ }for (let row = minRow; row <= maxRow; row++) {const rowMeta = rowData[row];if (rowMeta?.hd) continue;- const height = isFiniteNumber(rowMeta?.h) ? rowMeta.h : defaultHeight;+ const height = heights[row];// 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.@@ -302,10 +329,15 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |const cell = cellData[row]?.[col];const cellStyle = mergeAwareStyle(resolveCellStyle(cell?.s, styles), mergeInfo, row, col, cellData, styles);const bound = spillBound(cell, cellStyle, col, mergeInfo, neighbours);+ const padding = cellPadding(cellStyle);+ const boxHeight = spannedHeight(heights, row, mergeInfo?.endRow ?? row)+ - padding.t - padding.b - collapsedBorderHeight(cellStyle);const declarations = [buildCssText(cellStyle, cell)];- if (bound && !bound.before && !bound.after) declarations.push("overflow:hidden");+ 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 value = spill(rotate(formatCellValue(cell, cellStyle), cellStyle?.tr), bound)+ const value = cellBox(rotate(formatCellValue(cell, cellStyle), cellStyle?.tr), bound, boxHeight)+ (cell ? renderCellImages(cell) : "");const attrs: string[] = [];@@ -510,8 +542,9 @@ interface SpillBound {* The room a cell's text has before it reaches a cell that shows something. A spreadsheet runs text* across the empty cells beside it and cuts it at the first occupied one, and keeps a number, a* boolean or a cell set to CLIP inside its own edges (the overflow check in- * `@univerjs/engine-render`, and `WrapStrategy` in `@univerjs/core`). Returns `null` when nothing- * stops the text, which is what the stylesheets already do by letting a cell spill.+ * `@univerjs/engine-render`, and `WrapStrategy` in `@univerjs/core`). Text that nothing stops is+ * given the room to the edge of the sheet, since the box that carries it clips both axes at once+ * and so always needs a width. Returns `null` only when there is nothing to bound.*/function spillBound(cell: ICellData | undefined,@@ -534,7 +567,6 @@ function spillBound(? null: spillRoom(merge?.endColumn ?? col, 1, neighbours);- if (!before?.stopped && !after?.stopped) return null;return { before: before?.width ?? 0, after: after?.width ?? 0 };}@@ -566,19 +598,55 @@ function cellShownAt(col: number, neighbours: RowNeighbours): ICellData | undefi}/**- * Widens a cell's text box by the room it has on either side and clips it there, so the text runs- * across the empty cells beside it and stops at the one holding a value. The negative margins- * cancel the extra width, leaving the table's own geometry untouched.+ * Wraps a cell's text in the box that fixes its size. An HTML row grows to whatever it holds, while+ * a spreadsheet row is exactly as tall as it says and clips what does not fit, so without this the+ * grid drifts from the geometry the sheet declares and every absolutely placed image drifts with+ * it. The box also carries the room the text has to run sideways, widened by it and clipped there,+ * with the negative margins cancelling the extra width so the table's own layout is untouched.*/-function spill(html: string, bound: SpillBound | null): string {- if (!html || !bound || (!bound.before && !bound.after)) return html;+function cellBox(html: string, bound: SpillBound | null, height: number): string {+ if (!html) return html;- const parts = ["display:inline-block", `width:calc(100% + ${px(bound.before + bound.after)}px)`, "overflow:hidden"];- if (bound.before) parts.push(`margin-left:${px(-bound.before)}px`);- if (bound.after) parts.push(`margin-right:${px(-bound.after)}px`);+ const parts = ["display:block", "overflow:hidden"];+ if (height > 0) parts.push(`max-height:${px(height)}px`);+ if (bound && (bound.before || bound.after)) {+ parts.push(`width:calc(100% + ${px(bound.before + bound.after)}px)`);+ if (bound.before) parts.push(`margin-left:${px(-bound.before)}px`);+ if (bound.after) parts.push(`margin-right:${px(-bound.after)}px`);+ }return `<span style="${parts.join(";")}">${html}</span>`;}+/** The height a cell covers, summing the rows a `rowspan` reaches across. */+function spannedHeight(heights: number[], from: number, to: number): number {+ let total = 0;+ for (let row = from; row <= to; row++) total += heights[row] ?? 0;+ return total;+}++/**+ * The height a cell's own borders take from its row. Under `border-collapse` a border is shared+ * with the cell across it, so each side keeps half, and the sheet's row heights count the gridline+ * as drawn inside the row rather than added to it.+ */+function collapsedBorderHeight(style: IStyleData | null): number {+ const half = (border: IBorderStyleData | null | undefined) =>+ (!border || border.s === BorderStyle.NONE ? 0 : Number.parseFloat(borderStyleToWidth(border.s)) / 2);+ return half(style?.bd?.t) + half(style?.bd?.b);+}++/** The padding a cell is laid out with, which the box has to leave room for inside the row. */+function cellPadding(style: IStyleData | null): Required<IPaddingData> {+ const padding = style?.pd;+ const side = (value: number | undefined, fallback: number) => (isFiniteNumber(value) ? value : fallback);+ return {+ t: side(padding?.t, DEFAULT_CELL_PADDING.t),+ r: side(padding?.r, DEFAULT_CELL_PADDING.r),+ b: side(padding?.b, DEFAULT_CELL_PADDING.b),+ l: side(padding?.l, DEFAULT_CELL_PADDING.l)+ };+}+/** Whether a cell shows anything. A cell carrying only a style is empty, as it is in the editor. */function hasContent(cell: ICellData | undefined): boolean {if (!cell) return false;@@ -730,15 +798,19 @@ function rotate(html: string, rotation: ITextRotation | null | undefined): strin* counter-clockwise and CSS turns clockwise, so the sign flips.*/function rotationCss(rotation: ITextRotation | null | undefined): string | null {+ // `vertical-align` keeps the turned text off the line box's baseline, whose descender gap+ // would otherwise add height the row has to absorb.+ const ROTATED = "display:inline-block;vertical-align:top";+if (!rotation) return null;// Stacked text: upright characters reading downwards.- if (rotation.v) return "display:inline-block;writing-mode:vertical-rl;text-orientation:upright";+ if (rotation.v) return `${ROTATED};writing-mode:vertical-rl;text-orientation:upright`;const angle = isFiniteNumber(rotation.a) ? rotation.a : 0;if (angle === 0) return null;- if (angle === 90) return "display:inline-block;writing-mode:vertical-rl;transform:rotate(180deg)";- if (angle === -90) return "display:inline-block;writing-mode:vertical-rl";- return `display:inline-block;transform:rotate(${px(-angle)}deg)`;+ if (angle === 90) return `${ROTATED};writing-mode:vertical-rl;transform:rotate(180deg)`;+ if (angle === -90) return `${ROTATED};writing-mode:vertical-rl`;+ return `${ROTATED};transform:rotate(${px(-angle)}deg)`;}/**diff --git a/packages/commons/src/lib/spreadsheet/workbook_model.ts b/packages/commons/src/lib/spreadsheet/workbook_model.tsindex e418c0d25a..e0db535c42 100644--- a/packages/commons/src/lib/spreadsheet/workbook_model.ts+++ b/packages/commons/src/lib/spreadsheet/workbook_model.ts@@ -149,8 +149,20 @@ export interface IStyleData {tr?: ITextRotation | null;bd?: IBorderData | null;n?: INumberFormat | null;+ pd?: IPaddingData | null;}+/** Cell padding in px. Univer leaves out the sides it does not set; see `DEFAULT_CELL_PADDING`. */+export interface IPaddingData {+ t?: number;+ r?: number;+ b?: number;+ l?: number;+}++/** The padding Univer lays a cell out with when its style names none. */+export const DEFAULT_CELL_PADDING = { t: 0, r: 2, b: 2, l: 2 };+export interface INumberFormat {pattern?: string | null;}@@ -190,6 +202,10 @@ export interface IRange {export interface IRowData {h?: number;hd?: number;+ /** Height Univer measured for a row that sizes itself to its content. */+ ah?: number;+ /** Whether the row sizes itself to its content. Absent counts as yes. */+ ia?: number;}export interface IColumnData {diff --git a/packages/trilium-e2e/src/note_types/spreadsheet.spec.ts b/packages/trilium-e2e/src/note_types/spreadsheet.spec.tsnew file mode 100644index 0000000000..d30e22940b--- /dev/null+++ b/packages/trilium-e2e/src/note_types/spreadsheet.spec.ts@@ -0,0 +1,121 @@+import { expect, test } from "@playwright/test";++import App from "../support/app";++/**+ * A sheet whose every row would outgrow the height it declares if the renderer let it: text that+ * wraps, text turned a quarter turn, and cells carrying borders. The printed grid has to stay at+ * the declared heights, because a floating image is placed in those coordinates and drifts away+ * from the cells as soon as they do not hold.+ */+const WORKBOOK = {+ version: 1,+ workbook: {+ sheetOrder: ["s1"],+ styles: {},+ sheets: {+ s1: {+ id: "s1",+ name: "Sheet1",+ hidden: 0,+ // Gridlines are drawn by the stylesheets, not the emitter, and their width differs+ // between print and the share view, so they are left off to keep this about the+ // geometry the emitter itself states.+ showGridlines: 0,+ mergeData: [],+ rowData: {+ // A row Univer measured for itself, which is stored as `ah` rather than `h`.+ "0": { ah: 30 },+ "1": { h: 40 },+ "2": { h: 24 },+ "3": { h: 24 }+ },+ columnData: { "0": { w: 90 }, "1": { w: 90 } },+ cellData: {+ "0": {+ "0": { v: "wraps onto several lines when it is allowed to", t: 1, s: { tb: 3 } },+ "1": { v: "plain", t: 1 }+ },+ "1": {+ "0": { v: "turned a quarter turn", t: 1, s: { tr: { a: 90 } } },+ "1": { v: "stacked", t: 1, s: { tr: { a: 0, v: 1 } } }+ },+ "2": {+ "0": { v: "bordered", t: 1, s: { bd: { t: { s: 1 }, b: { s: 1 } } } },+ "1": { v: 42, t: 2, s: { bd: { t: { s: 8 }, b: { s: 8 } } } }+ },+ "3": {+ "0": { v: "a long single line that runs past its own column", t: 1 },+ "1": { v: "stops it", t: 1 }+ }+ }+ }+ }+ }+};++test("prints the grid at the row heights the sheet declares", async ({ page, context }) => {+ const app = new App(page, context);+ await app.goto();++ const noteId = await createSpreadsheet(app, JSON.stringify(WORKBOOK));++ try {+ await app.goto({ url: `/?print=#root/${noteId}` });+ await page.waitForSelector(".spreadsheet-table");++ const rows = await page.evaluate(() => {+ const table = document.querySelector(".spreadsheet-table");+ const base = table?.getBoundingClientRect().top ?? 0;+ return [...(table?.querySelectorAll("tr") ?? [])].map((row) => ({+ declared: Number.parseFloat((row as HTMLElement).style.height),+ top: row.getBoundingClientRect().top - base,+ rendered: row.getBoundingClientRect().height+ }));+ });++ expect(rows.length).toBe(4);++ let expectedTop = 0;+ for (const [index, row] of rows.entries()) {+ expect(row.rendered, `row ${index} keeps the height it declares`).toBeCloseTo(row.declared, 0);+ expect(row.top, `row ${index} starts where the rows above it end`).toBeCloseTo(expectedTop, 0);+ expectedTop += row.declared;+ }+ } finally {+ await deleteNote(app, noteId);+ }+});++/**+ * Creates a spreadsheet note under the root and returns its id. The request goes from inside the+ * page so standalone's service worker routes it to the SQLite worker, as `setOption` does.+ */+async function createSpreadsheet(app: App, content: string): Promise<string> {+ const result = await app.page.evaluate(async (body) => {+ const csrfToken = (window as any).glob.csrfToken;+ const response = await fetch("/api/notes/root/children?target=into", {+ method: "POST",+ headers: { "content-type": "application/json", "x-csrf-token": csrfToken },+ body: JSON.stringify({+ title: "Spreadsheet geometry fixture",+ type: "spreadsheet",+ mime: "application/json",+ content: body+ })+ });+ if (!response.ok) return { ok: false, status: response.status, noteId: "" };+ const created = await response.json();+ return { ok: true, status: response.status, noteId: created.note.noteId as string };+ }, content);++ expect(result.ok, `creating the fixture note failed (status=${result.status})`).toBe(true);+ return result.noteId;+}++async function deleteNote(app: App, noteId: string): Promise<void> {+ await app.page.evaluate(async (id) => {+ const csrfToken = (window as any).glob.csrfToken;+ await fetch(`/api/notes/${id}`, { method: "DELETE", headers: { "x-csrf-token": csrfToken } });+ }, noteId);+}