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: fix text rotation
Adorian Doranbe6fd040556a
diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_html.spec.tsindex 9d2eef0f23..e2df8d5c09 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";import { renderSpreadsheetToHtml } from "./render_to_html.js";-import { BorderStyle, HorizontalAlign, WrapStrategy } from "./workbook_model.js";+import { BorderStyle, HorizontalAlign, VerticalAlign, WrapStrategy } from "./workbook_model.js";/*** The markup with the box model stripped: each cell's sizing box and the padding it is measured@@ -524,19 +524,68 @@ describe("renderSpreadsheetToHtml", () => {const rotated = (tr: unknown) => renderSpreadsheetToHtml(singleCellWorkbook({ v: "Days left", t: 1, s: { tr } }));// 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;vertical-align:top;writing-mode:vertical-rl;transform:rotate(180deg)">Days left</span>`);+ // Univer measures the angle the way CSS turns, so -90 lifts the text and reads upwards.expect(rotated({ a: -90 })).toContain(+ `<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;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;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.+ // Any other angle turns the glyphs about a bottom corner of the cell, shifted by the line+ // height the turn would otherwise swing past that corner: lifting text from the bottom+ // left, dropping text from the bottom right.+ expect(rotated({ a: -45 })).toContain(+ `transform:translateX(calc(1lh * 0.707)) rotate(-45deg);transform-origin:left bottom">Days left</span>`);expect(rotated({ a: 45 })).toContain(- `<span style="display:inline-block;vertical-align:top;transform:rotate(-45deg)">Days left</span>`);- expect(rotated({ a: -30.5 })).toContain(`transform:rotate(30.5deg)`);+ `transform:translateX(calc(1lh * -0.707)) rotate(45deg);transform-origin:right bottom">Days left</span>`);+ expect(rotated({ a: -30.5 })).toContain(`transform:translateX(calc(1lh * 0.508)) rotate(-30.5deg)`);+ });++ it("anchors turned text to the cell edge the string meets", () => {+ const tilted = (s: Record<string, unknown>) => renderSpreadsheetToHtml(singleCellWorkbook({ v: "Days left", t: 1, s }));++ // Against the bottom, lifting text meets the edge with its start, dropping text with its end.+ expect(tilted({ tr: { a: -45 } })).toContain("align-items:flex-end;justify-content:flex-start");+ expect(tilted({ tr: { a: 45 } })).toContain("align-items:flex-end;justify-content:flex-end");++ // Against the top the ends swap over; a middle-aligned cell keeps the bottom's sides.+ expect(tilted({ tr: { a: -45 }, vt: VerticalAlign.TOP })).toContain("align-items:flex-start;justify-content:flex-end");+ expect(tilted({ tr: { a: 45 }, vt: VerticalAlign.TOP })).toContain("align-items:flex-start;justify-content:flex-start");+ expect(tilted({ tr: { a: 45 }, vt: VerticalAlign.MIDDLE })).toContain("align-items:center;justify-content:flex-end");++ // A cell that states its own alignment keeps it.+ expect(tilted({ tr: { a: 45 }, ht: HorizontalAlign.CENTER })).toContain("justify-content:center");+ });++ it("turns text about the cell edge it hangs from", () => {+ const tilted = (a: number, vt?: number) =>+ renderSpreadsheetToHtml(singleCellWorkbook({ v: "Days left", t: 1, s: { tr: { a }, vt } }));++ expect(tilted(-45)).toContain(`translateX(calc(1lh * 0.707)) rotate(-45deg);transform-origin:left bottom`);+ expect(tilted(45)).toContain(`translateX(calc(1lh * -0.707)) rotate(45deg);transform-origin:right bottom`);++ expect(tilted(-45, VerticalAlign.TOP)).toContain(`translateX(calc(1lh * -0.707)) rotate(-45deg);transform-origin:right top`);+ expect(tilted(45, VerticalAlign.TOP)).toContain(`translateX(calc(1lh * 0.707)) rotate(45deg);transform-origin:left top`);++ // Turning about the centre needs no correction and leaves the shape centred in the cell.+ expect(tilted(45, VerticalAlign.MIDDLE)).toContain(`transform:rotate(45deg)">Days left</span>`);+ });++ it("holds turned text inside its own cell", () => {+ const rotated = (a: number) => renderSpreadsheetToHtml(singleCellWorkbook({ v: "Days left", t: 1, s: { tr: { a } } }));++ // Every turn sits in a box that fills the cell, so the cell is what cuts an overrun. A box+ // only as tall as the text would clip a band across the turn instead.+ for (const angle of [45, -45, 90, -90]) {+ expect(rotated(angle), `${angle} degrees`).toContain(`<span style="display:flex;overflow:hidden`);+ expect(rotated(angle), `${angle} degrees`).toContain("height:22px");+ }++ // An untouched cell keeps the box that only caps it, so its own alignment still places it.+ expect(rotated(0)).toContain(`<span style="display:block;overflow:hidden;max-height:22px">`);});it("leaves a cell unwrapped when it has no rotation to apply", () => {@@ -643,6 +692,12 @@ describe("renderSpreadsheetToHtml", () => {expect(room(row({ 1: { v: "x", ...centered }, 2: { v: "after", t: 1 } }), 1)).toEqual([88, 0]);});+ it("keeps turned text in its own cell rather than running it into a neighbour", () => {+ const turned = { v: "a long label", t: 1, s: { tr: { a: 45 } } };+ expect(room(row({ 0: turned }), 0)).toEqual([0, 0]);+ expect(room(row({ 0: turned, 1: {} }), 0)).toEqual([0, 0]);+ });+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]);diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.tsindex 41680fd853..58701f549b 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts@@ -337,8 +337,10 @@ function renderSheet(sheet: IWorksheetData, styles: Record<string, IStyleData |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 = cellBox(rotate(formatCellValue(cell, cellStyle), cellStyle?.tr), bound, boxHeight)- + (cell ? renderCellImages(cell) : "");+ const text = rotate(formatCellValue(cell, cellStyle), cellStyle);+ const value = (isTurned(cellStyle?.tr)+ ? turnedBox(text, boxHeight, cellStyle)+ : cellBox(text, bound, boxHeight)) + (cell ? renderCellImages(cell) : "");const attrs: string[] = [];// Cells with a background fill carry `has-fill` so the stylesheet can suppress@@ -554,7 +556,10 @@ function spillBound(neighbours: RowNeighbours): SpillBound | null {if (!hasContent(cell) || style?.tb === WrapStrategy.WRAP) return null;- if (cell?.t === CellValueType.NUMBER || cell?.t === CellValueType.BOOLEAN || style?.tb === WrapStrategy.CLIP) {++ // Turned text stays in its own cell, as do a number, a boolean and a cell set to CLIP.+ if (cell?.t === CellValueType.NUMBER || cell?.t === CellValueType.BOOLEAN+ || style?.tb === WrapStrategy.CLIP || isTurned(style?.tr)) {return { before: 0, after: 0 };}@@ -617,6 +622,56 @@ function cellBox(html: string, bound: SpillBound | null, height: number): stringreturn `<span style="${parts.join(";")}">${html}</span>`;}+/** Whether a cell's text is turned at all, in any of the ways Univer can turn it. */+function isTurned(rotation: ITextRotation | null | undefined): boolean {+ if (!rotation) return false;+ return Boolean(rotation.v) || (isFiniteNumber(rotation.a) && rotation.a !== 0);+}++/**+ * Whether a rotation is painted by a transform rather than laid out, which is every angle other+ * than a quarter turn. Only those hang from a cell edge; a quarter turn is a writing mode, which+ * the cell's own alignments already place.+ */+function rotatesByTransform(rotation: ITextRotation | null | undefined): boolean {+ if (!rotation || rotation.v) return false;++ const angle = isFiniteNumber(rotation.a) ? rotation.a : 0;+ return angle !== 0 && angle !== 90 && angle !== -90;+}++/**+ * The box a turned cell's text sits in. It fills the cell rather than hugging the text, so what it+ * clips is the cell itself: a box only as tall as the text's own line would cut a band across the+ * turn and drop everything above and below it. Filling the cell takes the placement away from the+ * cell's alignments, so the box carries them itself.+ */+function turnedBox(html: string, height: number, style: IStyleData | null): string {+ if (!html) return html;++ const parts = [+ "display:flex",+ "overflow:hidden",+ `align-items:${turnedAlign(style?.vt)}`,+ `justify-content:${turnedJustify(style)}`+ ];+ if (height > 0) parts.push(`height:${px(height)}px`);+ return `<span style="${parts.join(";")}">${html}</span>`;+}++/** Where a turned cell puts its text down the cell, following the cell's vertical alignment. */+function turnedAlign(verticalAlign: number | null | undefined): string {+ if (verticalAlign === VerticalAlign.MIDDLE) return "center";+ return verticalAlign === VerticalAlign.TOP ? "flex-start" : "flex-end";+}++/** Where it puts it across the cell: the cell's own alignment when it states one, else the side the turn is anchored to. */+function turnedJustify(style: IStyleData | null): string {+ const align = style?.ht ?? (tiltAnchor(style) === "right" ? HorizontalAlign.RIGHT : HorizontalAlign.LEFT);+ if (align === HorizontalAlign.CENTER) return "center";+ return align === HorizontalAlign.RIGHT ? "flex-end" : "flex-start";+}+/** The height a cell covers, summing the rows a `rowspan` reaches across. */function spannedHeight(heights: number[], from: number, to: number): number {let total = 0;@@ -784,20 +839,21 @@ function formatCellValue(cell: ICellData | undefined, style: IStyleData | null):* the `td` itself, which would take the background and borders with it, and images anchored in the* cell stay upright as they do in the editor.*/-function rotate(html: string, rotation: ITextRotation | null | undefined): string {+function rotate(html: string, style: IStyleData | null): string {if (!html) return html;- const css = rotationCss(rotation);+ const css = rotationCss(style?.tr, style?.vt);return css ? `<span style="${css}">${html}</span>` : html;}/**- * The CSS for Univer's text rotation. A quarter turn and stacked text become a vertical writing- * mode, which gives the text a real vertical box the row grows to fit; any other angle falls back- * to a transform, which turns the glyphs without reserving room for them. Excel measures the angle- * counter-clockwise and CSS turns clockwise, so the sign flips.+ * The CSS for Univer's text rotation. Univer measures the angle the way CSS turns, clockwise from+ * the horizontal, so a negative angle lifts the text and a positive one drops it. A quarter turn+ * and stacked text become a vertical writing mode, which gives the text a real vertical box the row+ * grows to fit; any other angle falls back to a transform, which turns the glyphs without reserving+ * room for them.*/-function rotationCss(rotation: ITextRotation | null | undefined): string | null {+function rotationCss(rotation: ITextRotation | null | undefined, verticalAlign: number | 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";@@ -808,9 +864,35 @@ function rotationCss(rotation: ITextRotation | null | undefined): string | nullconst angle = isFiniteNumber(rotation.a) ? rotation.a : 0;if (angle === 0) return null;- 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)`;+ if (angle === -90) return `${ROTATED};writing-mode:vertical-rl;transform:rotate(180deg)`;+ if (angle === 90) return `${ROTATED};writing-mode:vertical-rl`;++ // A middle-aligned cell turns its text about the centre, which leaves the shape centred.+ if (verticalAlign === VerticalAlign.MIDDLE) return `${ROTATED};transform:rotate(${px(angle)}deg)`;++ // Otherwise the text hangs from the cell edge it is aligned to, turning about the end of the+ // string that meets it: lifting text meets the bottom with its start and the top with its end.+ // Turning about that corner swings the text's own line height past it, so the shift takes that+ // back; `lh` is the line height itself, which keeps the correction right at any font size.+ const swing = Math.round(Math.sin(Math.abs(angle) * (Math.PI / 180)) * 1000) / 1000;+ const fromTop = verticalAlign === VerticalAlign.TOP;+ const lifts = angle < 0;+ const origin = `${lifts === fromTop ? "right" : "left"} ${fromTop ? "top" : "bottom"}`;+ return `${ROTATED};transform:translateX(calc(1lh * ${lifts === fromTop ? -swing : swing})) rotate(${px(angle)}deg)`+ + `;transform-origin:${origin}`;+}++/**+ * The side of its cell turned text is anchored to, or `null` when the cell has no turned text. The+ * string meets the cell edge it is aligned to with one of its ends, and which end that is flips+ * between an alignment to the top and one to the bottom or the middle.+ */+function tiltAnchor(style: IStyleData | null): "left" | "right" | null {+ const rotation = style?.tr;+ if (!rotatesByTransform(rotation) || !isFiniteNumber(rotation?.a)) return null;++ const lifts = rotation.a < 0;+ return lifts === (style?.vt === VerticalAlign.TOP) ? "right" : "left";}/**diff --git a/packages/trilium-e2e/src/note_types/spreadsheet.spec.ts b/packages/trilium-e2e/src/note_types/spreadsheet.spec.tsindex d30e22940b..2af31a5dd7 100644--- a/packages/trilium-e2e/src/note_types/spreadsheet.spec.ts+++ b/packages/trilium-e2e/src/note_types/spreadsheet.spec.ts@@ -28,7 +28,8 @@ const WORKBOOK = {"0": { ah: 30 },"1": { h: 40 },"2": { h: 24 },- "3": { h: 24 }+ "3": { h: 24 },+ "4": { h: 60 }},columnData: { "0": { w: 90 }, "1": { w: 90 } },cellData: {@@ -40,6 +41,11 @@ const WORKBOOK = {"0": { v: "turned a quarter turn", t: 1, s: { tr: { a: 90 } } },"1": { v: "stacked", t: 1, s: { tr: { a: 0, v: 1 } } }},+ // A transform paints outside its layout box but must not move the row.+ "4": {+ "0": { v: "tilted up", t: 1, s: { tr: { a: 45 } } },+ "1": { v: "tilted down", t: 1, s: { tr: { a: -45 } } }+ },"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 } } } }@@ -74,7 +80,7 @@ test("prints the grid at the row heights the sheet declares", async ({ page, con}));});- expect(rows.length).toBe(4);+ expect(rows.length).toBe(5);let expectedTop = 0;for (const [index, row] of rows.entries()) {