Skip to content

Build your personal knowledge base with Trilium Notes

client/spreadsheet/print & PDF export: make the text wrapping behave like the editor

Adorian Doran395e5f1338ef
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 53d3d598cb..4bc4cf660c 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
@@ -581,52 +581,76 @@ describe("renderSpreadsheetToHtml", () => {
return grid({ "0": cells }, extra);
}
- /** Whether the workbook's cell at `column` clips its text. The render always starts at A1. */
- function clips(json: string, column: number): boolean {
- const cells = renderSpreadsheetToHtml(json).match(/<td[^>]*>/g) ?? [];
- return (cells[column] ?? "").includes("overflow:hidden");
+ /**
+ * The px of room the workbook's cell at `column` is given on each side, `[0, 0]` when it is
+ * held to its own edges, and `null` when nothing bounds it. The render always starts at A1.
+ */
+ function room(json: string, column: number): [number, number] | null {
+ const cells = renderSpreadsheetToHtml(json).match(/<td[^>]*>(?:<span style="[^"]*">)?/g) ?? [];
+ const cell = cells[column] ?? "";
+ if (!cell.includes("width:calc")) return cell.includes("overflow:hidden") ? [0, 0] : null;
+
+ const before = /margin-left:-([\d.]+)px/.exec(cell)?.[1] ?? "0";
+ const after = /margin-right:-([\d.]+)px/.exec(cell)?.[1] ?? "0";
+ return [Number(before), Number(after)];
}
- it("clips text only when the neighbour it would spill over holds a value", () => {
- const occupied = row({ 0: { v: "a long label", t: 1 }, 1: { v: "next", t: 1 } });
- expect(clips(occupied, 0)).toBe(true);
+ it("holds text to its own edge when the neighbour beside it holds a value", () => {
+ expect(room(row({ 0: { v: "a long label", t: 1 }, 1: { v: "next", t: 1 } }), 0)).toEqual([0, 0]);
- // An empty neighbour, or one carrying only a style, is spilled over as in the editor.
- expect(clips(row({ 0: { v: "a long label", t: 1 } }), 0)).toBe(false);
- expect(clips(row({ 0: { v: "a long label", t: 1 }, 1: { s: { bl: 1 } } }), 0)).toBe(false);
- expect(clips(row({ 0: { v: "a long label", t: 1 }, 1: { v: "", t: 1 } }), 0)).toBe(false);
+ // 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();
+ });
+
+ it("gives the text the width of the empty cells it may run across", () => {
+ const long = { v: "a long label", t: 1 };
+ const widths = { 1: { w: 30 }, 2: { w: 50 } };
+
+ // Two empty columns, then a value: the text runs over both and is cut before the value.
+ expect(room(row({ 0: long, 3: { v: "next", t: 1 } }, { columnData: widths }), 0)).toEqual([0, 80]);
+
+ // A hidden column between them contributes nothing, since none of it reaches the page.
+ expect(room(
+ row({ 0: long, 3: { v: "next", t: 1 } }, { columnData: { ...widths, 2: { w: 50, hd: 1 } } }),
+ 0
+ )).toEqual([0, 30]);
});
it("follows the alignment to decide which side the text spills towards", () => {
const rightAligned = { t: 1, s: { ht: HorizontalAlign.RIGHT } };
- expect(clips(row({ 0: { v: "before", t: 1 }, 1: { v: "x", ...rightAligned } }), 1)).toBe(true);
- expect(clips(row({ 1: { v: "x", ...rightAligned }, 2: { v: "after", t: 1 } }), 1)).toBe(false);
+ 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();
const centered = { t: 1, s: { ht: HorizontalAlign.CENTER } };
- expect(clips(row({ 0: { v: "before", t: 1 }, 1: { v: "x", ...centered } }), 1)).toBe(true);
- expect(clips(row({ 1: { v: "x", ...centered }, 2: { v: "after", t: 1 } }), 1)).toBe(true);
- expect(clips(row({ 1: { v: "x", ...centered } }), 1)).toBe(false);
+ 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();
+
+ // 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]);
});
- it("never spills a number, and never clips a wrapped or empty cell", () => {
- expect(clips(row({ 0: { v: 42, t: 2 } }), 0)).toBe(true);
- expect(clips(row({ 0: { v: true, t: 3 } }), 0)).toBe(true);
+ it("never spills a number, a boolean or a clipped cell, and never bounds a wrapped one", () => {
+ expect(room(row({ 0: { v: 42, t: 2 } }), 0)).toEqual([0, 0]);
+ 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(clips(row({ 0: { v: "a long label", t: 1, s: { tb: WrapStrategy.WRAP } }, 1: { v: "next", t: 1 } }), 0)).toBe(false);
- expect(clips(row({ 0: { s: { bl: 1 } }, 1: { v: "next", t: 1 } }), 0)).toBe(false);
+ 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: { s: { bl: 1 } }, 1: { v: "next", t: 1 } }), 0)).toBeNull();
});
it("judges adjacency on the rendered row rather than the cell matrix", () => {
const long = { v: "a long label", t: 1 };
// A hidden column reaches nobody, so the cell steps over it in both directions.
- expect(clips(row({ 0: long, 1: { v: "next", t: 1 } }, { columnData: { 1: { hd: 1 } } }), 0)).toBe(false);
- expect(clips(row({ 0: long, 1: {}, 2: { v: "next", t: 1 } }, { columnData: { 1: { hd: 1 } } }), 0)).toBe(true);
+ expect(room(row({ 0: long, 1: { v: "next", t: 1 } }, { columnData: { 1: { hd: 1 } } }), 0)).toBeNull();
+ 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(clips(row({ 0: long, 1: {}, 2: { v: "next", t: 1 } }, { mergeData: merged }), 0)).toBe(true);
- expect(clips(row({ 0: long, 1: {} }, { mergeData: merged }), 0)).toBe(false);
+ 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();
});
it("reads a column a merge spans into as holding that range's content", () => {
@@ -644,7 +668,7 @@ describe("renderSpreadsheetToHtml", () => {
0: { v: "a long label", t: 1 },
1: { p: { body: { dataStream: "linked\r\n" } } }
});
- expect(clips(html, 0)).toBe(true);
+ expect(room(html, 0)).toEqual([0, 0]);
});
});
@@ -1267,9 +1291,10 @@ describe("renderSpreadsheetToHtml", () => {
});
const html = renderSpreadsheetToHtml(input);
// Column 1 between A and C has no cell -> empty <td>.
- expect(html).toContain("<td>A</td>");
expect(html).toContain("<td></td>");
expect(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>`);
});
it("renders numeric cell values", () => {
diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.ts
index 44f3cc2f3e..7581886a72 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts
@@ -291,7 +291,7 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |
// sets its own still wins.
lines.push(`<tr style="height:${height}px;vertical-align:bottom">`);
- const neighbours: RowNeighbours = { row, minCol, maxCol, cellData, columnData, mergeMap };
+ const neighbours: RowNeighbours = { row, minCol, maxCol, cellData, columnData, mergeMap, defaultWidth };
for (let col = minCol; col <= maxCol; col++) {
if (columnData[col]?.hd) continue;
@@ -301,10 +301,11 @@ 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 declarations = [buildCssText(cellStyle, cell)];
- if (clipsOverflow(cell, cellStyle, col, mergeInfo, neighbours)) declarations.push("overflow:hidden");
+ if (bound && !bound.before && !bound.after) declarations.push("overflow:hidden");
const cssText = declarations.filter(Boolean).join(";");
- const value = rotate(formatCellValue(cell, cellStyle), cellStyle?.tr)
+ const value = spill(rotate(formatCellValue(cell, cellStyle), cellStyle?.tr), bound)
+ (cell ? renderCellImages(cell) : "");
const attrs: string[] = [];
@@ -496,52 +497,86 @@ interface RowNeighbours {
cellData: CellMatrix;
columnData: Record<number, IColumnData>;
mergeMap: Map<string, MergeInfo>;
+ defaultWidth: number;
+}
+
+/** How far a cell's text may run past its own edges, in px on each side. */
+interface SpillBound {
+ before: number;
+ after: number;
}
/**
- * Whether a cell has to clip its text at its own edge. A spreadsheet spills text into a
- * neighbouring cell only while that neighbour is empty, and never spills a number or a boolean
- * (the overflow check in `@univerjs/engine-render`). The stylesheets let every cell spill, so
- * without this a long value is drawn over the value beside it. The spill direction follows the
- * alignment, and a wrapped cell never spills to begin with.
+ * 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.
*/
-function clipsOverflow(
+function spillBound(
cell: ICellData | undefined,
style: IStyleData | null,
col: number,
merge: MergeOrigin | undefined,
neighbours: RowNeighbours
-): boolean {
- if (!hasContent(cell) || style?.tb === WrapStrategy.WRAP) return false;
- if (cell?.t === CellValueType.NUMBER || cell?.t === CellValueType.BOOLEAN) return true;
-
- // Rightwards, a merged cell starts looking past the last column its own range covers.
- const before = () => neighbourHasContent(col, -1, neighbours);
- const after = () => neighbourHasContent(merge?.endColumn ?? col, 1, neighbours);
- switch (style?.ht) {
- case HorizontalAlign.RIGHT: return before();
- case HorizontalAlign.CENTER: return before() || after();
- default: return after();
+): SpillBound | null {
+ if (!hasContent(cell) || style?.tb === WrapStrategy.WRAP) return null;
+ if (cell?.t === CellValueType.NUMBER || cell?.t === CellValueType.BOOLEAN || style?.tb === WrapStrategy.CLIP) {
+ return { before: 0, after: 0 };
}
+
+ // Text runs the way its alignment points; rightwards a merged cell starts past its own range.
+ const align = style?.ht;
+ const before = align === HorizontalAlign.RIGHT || align === HorizontalAlign.CENTER
+ ? spillRoom(col, -1, neighbours)
+ : null;
+ const after = align === HorizontalAlign.RIGHT
+ ? null
+ : spillRoom(merge?.endColumn ?? col, 1, neighbours);
+
+ if (!before?.stopped && !after?.stopped) return null;
+ return { before: before?.width ?? 0, after: after?.width ?? 0 };
}
/**
- * Whether the cell rendered beside `from` shows anything. Adjacency follows the rendered row, not
- * the cell matrix: hidden columns are stepped over because nothing of them reaches the page, and a
- * column a merge covers reports that range's anchor, whose text is what fills the space there.
+ * The rendered width beside `from`, and whether a cell showing something is what ended it. The walk
+ * follows the rendered row: a hidden column takes up no width because nothing of it reaches the
+ * page, and a column a merge covers shows that range's anchor.
*/
-function neighbourHasContent(from: number, step: -1 | 1, neighbours: RowNeighbours): boolean {
- const { row, minCol, maxCol, cellData, columnData, mergeMap } = neighbours;
+function spillRoom(from: number, step: -1 | 1, neighbours: RowNeighbours): { width: number; stopped: boolean } {
+ const { minCol, maxCol, columnData, defaultWidth } = neighbours;
+ let width = 0;
for (let col = from + step; col >= minCol && col <= maxCol; col += step) {
if (columnData[col]?.hd) continue;
+ if (hasContent(cellShownAt(col, neighbours))) return { width, stopped: true };
- const info = mergeMap.get(cellKey(row, col));
- return hasContent(info?.kind === "member"
- ? cellData[info.anchorRow]?.[info.anchorColumn]
- : cellData[row]?.[col]);
+ const columnWidth = columnData[col]?.w;
+ width += isFiniteNumber(columnWidth) ? columnWidth : defaultWidth;
}
- return false;
+ return { width, stopped: false };
+}
+
+/** The cell filling `col` in this row: a column a merge covers shows the range's anchor. */
+function cellShownAt(col: number, neighbours: RowNeighbours): ICellData | undefined {
+ const { row, cellData, mergeMap } = neighbours;
+
+ const info = mergeMap.get(cellKey(row, col));
+ return info?.kind === "member" ? cellData[info.anchorRow]?.[info.anchorColumn] : cellData[row]?.[col];
+}
+
+/**
+ * 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.
+ */
+function spill(html: string, bound: SpillBound | null): string {
+ if (!html || !bound || (!bound.before && !bound.after)) 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`);
+ return `<span style="${parts.join(";")}">${html}</span>`;
}
/** Whether a cell shows anything. A cell carrying only a style is empty, as it is in the editor. */
diff --git a/packages/commons/src/lib/spreadsheet/workbook_model.ts b/packages/commons/src/lib/spreadsheet/workbook_model.ts
index 077f43142a..e418c0d25a 100644
--- a/packages/commons/src/lib/spreadsheet/workbook_model.ts
+++ b/packages/commons/src/lib/spreadsheet/workbook_model.ts
@@ -225,7 +225,12 @@ export const enum VerticalAlign {
BOTTOM = 3
}
+// Wrap strategies (from UniversJS). OVERFLOW runs long text across the empty cells beside it,
+// CLIP cuts it at the cell edge, and WRAP breaks it inside the cell.
export const enum WrapStrategy {
+ UNSPECIFIED = 0,
+ OVERFLOW = 1,
+ CLIP = 2,
WRAP = 3
}