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/PDF export: add support for links
Adorian Doran9ab97f10a0a8
diff --git a/apps/client/src/print.css b/apps/client/src/print.cssindex 54b8a1d212..93e511ac3b 100644--- a/apps/client/src/print.css+++ b/apps/client/src/print.css@@ -302,6 +302,13 @@ span[style] {.spreadsheet-table.show-gridlines td:not(.has-fill) {border: 0.5pt solid var(--spreadsheet-gridline-color, #ccc);}++/* On paper a link cannot be followed, so it keeps the cell's own text color and the underline+ is the only marker, matching how .ck-content links print. */+.spreadsheet-table a {+ text-decoration: underline;+ color: inherit;+}/* #endregion *//* #region AI chat */diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_html.spec.tsindex eecc2c3309..676bf14fee 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts@@ -424,6 +424,89 @@ describe("renderSpreadsheetToHtml", () => {expect(html).toContain("Senzor PIR");});+ it("renders a hyperlink whether or not the cell also has a plain value", () => {+ const link = (cell: Record<string, unknown>) => renderSpreadsheetToHtml(singleCellWorkbook({+ ...cell,+ p: {+ body: {+ dataStream: "Kit\r\n",+ customRanges: [{ startIndex: 0, endIndex: 2, properties: { url: "https://example.com/kit" } }]+ }+ }+ }));++ const expected = `<a href="https://example.com/kit" target="_blank" rel="noopener noreferrer">Kit</a>`;+ expect(link({})).toContain(expected);+ expect(link({ v: "Kit", t: 1 })).toContain(expected);+ });++ it("links only the run a range covers, leaving the rest as text", () => {+ const html = renderSpreadsheetToHtml(singleCellWorkbook({+ p: {+ body: {+ dataStream: "see spy-shop now\r\n",+ customRanges: [{ startIndex: 4, endIndex: 11, properties: { url: "https://example.com" } }]+ }+ }+ }));++ expect(html).toContain(`see <a href="https://example.com" target="_blank" rel="noopener noreferrer">spy-shop</a> now`);+ });++ it("drops an unsafe or malformed link target, keeping its text", () => {+ const withUrl = (url: unknown) => renderSpreadsheetToHtml(singleCellWorkbook({+ p: {+ body: {+ dataStream: "Kit\r\n",+ customRanges: [{ startIndex: 0, endIndex: 2, properties: { url } }]+ }+ }+ }));++ for (const url of ["javascript:alert(1)", "data:text/html,<script>", " ", 42, undefined]) {+ const html = withUrl(url);+ expect(html, String(url)).toContain("Kit");+ expect(html, String(url)).not.toContain("<a ");+ }+ });++ it("ignores link ranges that are out of order, overlapping or out of bounds", () => {+ const html = renderSpreadsheetToHtml(singleCellWorkbook({+ p: {+ body: {+ dataStream: "abcdef\r\n",+ customRanges: [+ { startIndex: 3, endIndex: 99, properties: { url: "https://example.com/second" } },+ { startIndex: 0, endIndex: 1, properties: { url: "https://example.com/first" } },+ { startIndex: 4, endIndex: 5, properties: { url: "https://example.com/overlapping" } },+ { startIndex: 2, properties: { url: "https://example.com/unbounded" } }+ ]+ }+ }+ }));++ expect(html).toContain(">ab</a>c<a ");+ expect(html).toContain(">def</a>");+ expect(html).not.toContain("overlapping");+ expect(html).not.toContain("unbounded");+ });++ it("keeps the number format of a linked numeric cell", () => {+ const html = renderSpreadsheetToHtml(singleCellWorkbook({+ v: 0.42,+ t: 2,+ s: { n: { pattern: "0.0%" } },+ p: {+ body: {+ dataStream: "42%\r\n",+ customRanges: [{ startIndex: 0, endIndex: 2, properties: { url: "https://example.com" } }]+ }+ }+ }));++ expect(html).toContain("42.0%");+ });+// Helper to wrap a single styled cell into a complete workbook payload.function singleCellWorkbook(cell: unknown, sheetExtra: Record<string, unknown> = {}): string {return JSON.stringify({diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.tsindex 7d0ab54244..40205da301 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts@@ -14,8 +14,9 @@ import { format as formatNumfmt, formatColor as formatNumfmtColor } from "numfmtimport {BorderStyle,+ type CellDocumentSegment,computeBounds,- getCellDocumentText,+ getCellDocumentSegments,getFloatingDrawings,getVisibleSheets,HorizontalAlign,@@ -523,8 +524,8 @@ function sanitizeCssColor(value: string): string {function formatCellValue(cell: ICellData | undefined, style: IStyleData | null): string {if (!cell) return "";- // A rich-text cell (a link, mixed formatting) can carry its text only in `p`.- if (cell.v == null || cell.v === "") return escapeHtml(getCellDocumentText(cell));+ const rendered = formatCellDocument(cell);+ if (rendered != null) return rendered;if (typeof cell.v === "boolean") {return cell.v ? "TRUE" : "FALSE";@@ -545,6 +546,39 @@ function formatCellValue(cell: ICellData | undefined, style: IStyleData | null):return escapeHtml(String(cell.v));}+/**+ * Renders a cell from its rich-text document, or returns `null` when the plain value is the+ * better source. The document wins when the cell has no plain value, which is how Univer stores+ * some cells, and when it carries hyperlinks that the plain value cannot express. A formatted+ * number keeps its own rendering, since the document holds a display string that can go stale.+ */+function formatCellDocument(cell: ICellData): string | null {+ const segments = getCellDocumentSegments(cell);+ const hasPlainValue = cell.v != null && cell.v !== "";+ if (hasPlainValue && (isFiniteNumber(cell.v) || !segments.some((segment) => segment.url))) {+ return null;+ }++ const parts: string[] = [];+ for (const segment of segments) {+ const href = sanitizeLinkHref(segment.url);+ const text = escapeHtml(segment.text);+ parts.push(href ? `<a href="${escapeHtml(href)}" target="_blank" rel="noopener noreferrer">${text}</a>` : text);+ }+ return parts.join("");+}++/**+ * Validates a hyperlink target for inclusion in shared/exported HTML. Accepts the absolute+ * `http`, `https` and `mailto` URLs Univer's link dialog writes; anything else, `javascript:`+ * among them, returns `null` so the run renders as plain text.+ */+function sanitizeLinkHref(url: string | undefined): string | null {+ if (typeof url !== "string") return null;+ const trimmed = url.trim();+ return /^(?:https?:\/\/|mailto:)[^\u0000-\u0020\u007F]+$/i.test(trimmed) ? trimmed : null;+}+/*** Returns the text color dictated by a number-format pattern for this cell's value* (e.g. `[Red]` on the negative section), or `null` when the pattern specifies nodiff --git a/packages/commons/src/lib/spreadsheet/workbook_model.spec.ts b/packages/commons/src/lib/spreadsheet/workbook_model.spec.tsindex 684f0b67a9..366f4670b9 100644--- a/packages/commons/src/lib/spreadsheet/workbook_model.spec.ts+++ b/packages/commons/src/lib/spreadsheet/workbook_model.spec.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import {+ getCellDocumentSegments,getCellDocumentText,getDataValidations,getFloatingDrawings,@@ -120,3 +121,33 @@ describe("getCellDocumentText", () => {expect(normalizeDataStream(42)).toBe("");});});++describe("getCellDocumentSegments", () => {+ it("cuts the document into plain and linked runs", () => {+ const segments = getCellDocumentSegments({+ p: {+ body: {+ dataStream: "see spy-shop now\r\n",+ customRanges: [{ startIndex: 4, endIndex: 11, properties: { url: "https://example.com" } }]+ }+ }+ });++ expect(segments).toEqual([+ { text: "see " },+ { text: "spy-shop", url: "https://example.com" },+ { text: " now" }+ ]);+ });++ it("keeps the trailing terminator out of a run that ends the document", () => {+ expect(getCellDocumentSegments({+ p: {+ body: {+ dataStream: "Kit\r\n",+ customRanges: [{ startIndex: 0, endIndex: 4, properties: { url: "https://example.com" } }]+ }+ }+ })).toEqual([{ text: "Kit", url: "https://example.com" }]);+ });+});diff --git a/packages/commons/src/lib/spreadsheet/workbook_model.ts b/packages/commons/src/lib/spreadsheet/workbook_model.tsindex 134157748b..224ed6a2ec 100644--- a/packages/commons/src/lib/spreadsheet/workbook_model.ts+++ b/packages/commons/src/lib/spreadsheet/workbook_model.ts@@ -79,6 +79,15 @@ export interface ICellDocumentData {export interface ICellDocumentBody {/** Univer's flat text buffer, with structure encoded as control characters. */dataStream?: string;+ /** Spans of `dataStream` carrying extra properties, hyperlinks among them. */+ customRanges?: ICellCustomRange[];+}++/** A span of a cell's document text. `startIndex` and `endIndex` are both inclusive. */+export interface ICellCustomRange {+ startIndex?: number;+ endIndex?: number;+ properties?: { url?: string };}export interface ISheetDrawing {@@ -270,27 +279,98 @@ export function resolveCellStyle(return s;}+/** A run of a cell's document text, carrying the hyperlink it sits inside. */+export interface CellDocumentSegment {+ text: string;+ url?: string;+}++/**+ * Splits a cell's rich-text document into runs of plain and linked text. Univer stores a+ * hyperlink as a `customRange` holding the target and the offsets it covers in `dataStream`,+ * so the runs are cut on those offsets. Returns an empty array when the cell carries no+ * document, which is the common case: Univer writes `p` only for a rich-text cell.+ */+export function getCellDocumentSegments(cell: ICellData | undefined): CellDocumentSegment[] {+ const body = cell?.p?.body;+ const stream = typeof body?.dataStream === "string" ? body.dataStream : "";+ if (!stream) return [];++ const segments: CellDocumentSegment[] = [];+ let cursor = 0;+ for (const link of linkRanges(body?.customRanges, stream.length)) {+ if (link.start > cursor) {+ segments.push({ text: stripDataStreamControls(stream.slice(cursor, link.start)) });+ }+ segments.push({ text: stripDataStreamControls(stream.slice(link.start, link.end + 1)), url: link.url });+ cursor = link.end + 1;+ }+ if (cursor < stream.length) {+ segments.push({ text: stripDataStreamControls(stream.slice(cursor)) });+ }++ return trimTrailingBreaks(segments);+}+/*** Returns the plain text of a cell Univer stored as a rich-text document. Univer writes `p`* without a matching `v` for some cells, such as a link typed into an empty cell, so an emitter* that reads only `v` renders them blank.*/export function getCellDocumentText(cell: ICellData | undefined): string {- return normalizeDataStream(cell?.p?.body?.dataStream);+ return getCellDocumentSegments(cell).map((segment) => segment.text).join("");}-/**- * Converts Univer's `dataStream` to plain text. A carriage return ends a paragraph and a line- * feed ends a section, so both become newlines and the trailing terminator every stream carries- * is dropped. The other C0 control characters are structural placeholders, the backspace- * character standing in for an embedded drawing.- */+/** Converts a whole `dataStream` to plain text, dropping the terminator it ends with. */export function normalizeDataStream(dataStream: unknown): string {if (typeof dataStream !== "string") return "";- return dataStream+ return stripDataStreamControls(dataStream).replace(/\n+$/, "");+}++/** The hyperlink ranges to cut on, in document order, clamped to the stream and non-overlapping. */+function linkRanges(customRanges: ICellCustomRange[] | undefined, length: number) {+ const links: { start: number; end: number; url: string }[] = [];+ for (const range of customRanges ?? []) {+ const url = range?.properties?.url;+ if (typeof url !== "string" || !url) continue;+ if (!isFiniteNumber(range.startIndex) || !isFiniteNumber(range.endIndex)) continue;++ const start = Math.max(0, Math.trunc(range.startIndex));+ const end = Math.min(length - 1, Math.trunc(range.endIndex));+ if (end >= start) links.push({ start, end, url });+ }+ links.sort((a, b) => a.start - b.start);++ const ordered: typeof links = [];+ let cursor = 0;+ for (const link of links) {+ if (link.start < cursor) continue;+ ordered.push(link);+ cursor = link.end + 1;+ }+ return ordered;+}++/**+ * Removes the structural placeholders Univer encodes as C0 control characters, the backspace+ * character standing in for an embedded drawing, and turns its paragraph and section breaks+ * into newlines.+ */+function stripDataStreamControls(text: string): string {+ return text.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "")- .replace(/\r\n|[\r\n]/g, "\n")- .replace(/\n+$/, "");+ .replace(/\r\n|[\r\n]/g, "\n");+}++/** Drops the terminator every stream ends with, along with any run it leaves empty. */+function trimTrailingBreaks(segments: CellDocumentSegment[]): CellDocumentSegment[] {+ while (segments.length > 0) {+ const last = segments[segments.length - 1];+ last.text = last.text.replace(/\n+$/, "");+ if (last.text) break;+ segments.pop();+ }+ return segments;}export interface Bounds {