Skip to content

Build your personal knowledge base with Trilium Notes

client/spreadsheet/XLS export: add support for links, rename some strings used in tests

Adorian Doran9411c784e541
diff --git a/packages/commons/src/lib/spreadsheet/extract_text.spec.ts b/packages/commons/src/lib/spreadsheet/extract_text.spec.ts
index 0c1c951d21..ddff95e37c 100644
--- a/packages/commons/src/lib/spreadsheet/extract_text.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/extract_text.spec.ts
@@ -518,7 +518,7 @@ describe("extractSpreadsheetText rich-text cells", () => {
name: "Sheet1",
hidden: 0,
cellData: {
- "0": { "0": { p: { body: { [dataStreamKey]: "Senzor PIR\r\n" } } } },
+ "0": { "0": { p: { body: { [dataStreamKey]: "Notebook\r\n" } } } },
"1": { "0": { v: "plain" } }
},
rowData: {},
@@ -528,7 +528,7 @@ describe("extractSpreadsheetText rich-text cells", () => {
}
});
- expect(extractSpreadsheetText(sheet("dataStream"))).toBe("Senzor PIR plain");
- expect(extractSpreadsheetText(sheet("datastream"))).toBe("Senzor PIR plain");
+ expect(extractSpreadsheetText(sheet("dataStream"))).toBe("Notebook plain");
+ expect(extractSpreadsheetText(sheet("datastream"))).toBe("Notebook plain");
});
});
diff --git a/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts
index e85f7421bf..5d452fd116 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_csv.spec.ts
@@ -348,8 +348,8 @@ describe("renderSpreadsheetToCsv (formatDate returns null)", () => {
describe("rich-text cells", () => {
it("exports the text of a cell that has no plain value", () => {
const csv = renderSpreadsheetToCsv(workbook({
- 0: { 0: { p: { body: { dataStream: "Telecomand\u0103\r\n" } } }, 1: { v: 135.99 } }
+ 0: { 0: { p: { body: { dataStream: "Caf\u00e9\r\n" } } }, 1: { v: 12.5 } }
}));
- expect(csv).toBe("Telecomand\u0103,135.99");
+ expect(csv).toBe("Caf\u00e9,12.5");
});
});
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 676bf14fee..ab0c5cb1f9 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts
@@ -420,8 +420,8 @@ describe("renderSpreadsheetToHtml", () => {
});
it("renders a cell whose text lives only in its rich-text document", () => {
- const html = renderSpreadsheetToHtml(singleCellWorkbook({ p: { body: { dataStream: "Senzor PIR\r\n" } } }));
- expect(html).toContain("Senzor PIR");
+ const html = renderSpreadsheetToHtml(singleCellWorkbook({ p: { body: { dataStream: "Notebook\r\n" } } }));
+ expect(html).toContain("Notebook");
});
it("renders a hyperlink whether or not the cell also has a plain value", () => {
@@ -429,35 +429,35 @@ describe("renderSpreadsheetToHtml", () => {
...cell,
p: {
body: {
- dataStream: "Kit\r\n",
- customRanges: [{ startIndex: 0, endIndex: 2, properties: { url: "https://example.com/kit" } }]
+ dataStream: "Pen\r\n",
+ customRanges: [{ startIndex: 0, endIndex: 2, properties: { url: "https://example.com/pen" } }]
}
}
}));
- const expected = `<a href="https://example.com/kit" target="_blank" rel="noopener noreferrer">Kit</a>`;
+ const expected = `<a href="https://example.com/pen" target="_blank" rel="noopener noreferrer">Pen</a>`;
expect(link({})).toContain(expected);
- expect(link({ v: "Kit", t: 1 })).toContain(expected);
+ expect(link({ v: "Pen", 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",
+ dataStream: "see supplier 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`);
+ expect(html).toContain(`see <a href="https://example.com" target="_blank" rel="noopener noreferrer">supplier</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",
+ dataStream: "Pen\r\n",
customRanges: [{ startIndex: 0, endIndex: 2, properties: { url } }]
}
}
@@ -465,7 +465,7 @@ describe("renderSpreadsheetToHtml", () => {
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)).toContain("Pen");
expect(html, String(url)).not.toContain("<a ");
}
});
diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.ts b/packages/commons/src/lib/spreadsheet/render_to_html.ts
index 40205da301..2e3484b5cc 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_html.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_html.ts
@@ -561,24 +561,14 @@ function formatCellDocument(cell: ICellData): string | 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);
+ parts.push(segment.url
+ ? `<a href="${escapeHtml(segment.url)}" 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 no
diff --git a/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts
index 9663604dc8..bd1329973e 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts
@@ -839,8 +839,73 @@ function workbookWithSheetNames(names: string[]): string {
}
describe("rich-text cells", () => {
+ /** Wrap a document with one link range covering `endIndex` characters from the start. */
+ function linkedCell(url: unknown, dataStream = "Pen\r\n", endIndex = 2, extra: Record<string, unknown> = {}) {
+ return singleCellWorkbook(
+ {
+ ...extra,
+ p: { body: { dataStream, customRanges: [{ startIndex: 0, endIndex, properties: { url } }] } }
+ },
+ {},
+ { s1: { ff: "Georgia", bl: 1, cl: { rgb: "#FF0000" } } }
+ );
+ }
+
it("writes the text of a cell that has no plain value", async () => {
- const wb = await roundTrip(singleCellWorkbook({ p: { body: { dataStream: "Kit\r\n" } } }));
- expect(wb.worksheets[0].getCell("A1").value).toBe("Kit");
+ const wb = await roundTrip(singleCellWorkbook({ p: { body: { dataStream: "Pen\r\n" } } }));
+ expect(wb.worksheets[0].getCell("A1").value).toBe("Pen");
+ });
+
+ it("writes an Excel hyperlink, whether or not the cell also has a plain value", async () => {
+ for (const extra of [{}, { v: "Pen", t: 1 }]) {
+ const wb = await roundTrip(linkedCell("https://example.com/pen", "Pen\r\n", 2, extra));
+ const cell = wb.worksheets[0].getCell("A1");
+ expect(cell.value).toEqual({ text: "Pen", hyperlink: "https://example.com/pen" });
+ expect(cell.hyperlink).toBe("https://example.com/pen");
+ }
+ });
+
+ it("gives a linked cell the built-in Hyperlink font, keeping the rest of its own style", async () => {
+ const plain = await roundTrip(linkedCell("https://example.com"));
+ expect(plain.worksheets[0].getCell("A1").font).toEqual({ color: { argb: "FF0563C1" }, underline: true });
+
+ const styled = await roundTrip(linkedCell("https://example.com", "Pen\r\n", 2, { s: "s1" }));
+ expect(styled.worksheets[0].getCell("A1").font).toEqual({
+ name: "Georgia",
+ bold: true,
+ color: { argb: "FF0563C1" },
+ underline: true
+ });
+ });
+
+ it("links the whole cell to the first target when the document has several", async () => {
+ const wb = await roundTrip(singleCellWorkbook({
+ p: {
+ body: {
+ dataStream: "see supplier now\r\n",
+ customRanges: [
+ { startIndex: 4, endIndex: 11, properties: { url: "https://example.com/first" } },
+ { startIndex: 13, endIndex: 15, properties: { url: "https://example.com/second" } }
+ ]
+ }
+ }
+ }));
+
+ expect(wb.worksheets[0].getCell("A1").value).toEqual({
+ text: "see supplier now",
+ hyperlink: "https://example.com/first"
+ });
+ });
+
+ it("drops an unsafe target, keeping the text", async () => {
+ const wb = await roundTrip(linkedCell("javascript:alert(1)"));
+ const cell = wb.worksheets[0].getCell("A1");
+ expect(cell.value).toBe("Pen");
+ expect(cell.hyperlink).toBeUndefined();
+ });
+
+ it("keeps a linked numeric cell as a number so its format and formulas survive", async () => {
+ const wb = await roundTrip(linkedCell("https://example.com", "1000\r\n", 3, { v: 1000, t: 2 }));
+ expect(wb.worksheets[0].getCell("A1").value).toBe(1000);
});
});
diff --git a/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts b/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts
index 02d40dff7d..457abef66d 100644
--- a/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts
+++ b/packages/commons/src/lib/spreadsheet/render_to_xlsx.ts
@@ -4,8 +4,8 @@
* Unlike the HTML renderer, this is a near-lossless mapping: Univer's cell model mirrors
* OOXML, so number formats pass through verbatim, the border-style enum maps almost 1:1 to
* Excel's, and fonts/fills/alignment/merges map directly. Data-validation rules (dropdown lists,
- * numeric/date/text bounds) invert their import counterparts. The heavy lifting (zip + XML) is
- * delegated to `exceljs`.
+ * numeric/date/text bounds) invert their import counterparts, and a cell's hyperlink becomes an
+ * Excel hyperlink. The heavy lifting (zip + XML) is delegated to `exceljs`.
*
* The workbook type subset, sheet selection, and style resolution live in the shared
* `workbook_model` reader; this module only owns the Univer→OOXML translation.
@@ -18,7 +18,7 @@ import "./exceljs_augmentation.js";
import {
BorderStyle,
type DataValidationRule,
- getCellDocumentText,
+ getCellDocumentSegments,
getDataValidations,
getFloatingDrawings,
getVisibleSheets,
@@ -364,43 +364,65 @@ function applyRows(ws: ExcelJS.Worksheet, sheet: IWorksheetData): void {
}
}
+/**
+ * The font of Excel's built-in Hyperlink cell style. Excel stores a link's appearance in the cell
+ * when the link is inserted rather than deriving it on open, so a file written from outside Excel
+ * has to carry it: without this a linked cell is clickable but looks like plain text.
+ */
+const HYPERLINK_FONT: Partial<ExcelJS.Font> = { color: { argb: "FF0563C1" }, underline: true };
+
function writeCell(target: ExcelJS.Cell, cell: ICellData | undefined, styles: Record<string, IStyleData | null>): void {
if (!cell) return;
- setCellValue(target, cell);
-
+ const isHyperlink = setCellValue(target, cell);
const style = resolveCellStyle(cell.s, styles);
- if (!style) return;
- if (style.n?.pattern) target.numFmt = style.n.pattern;
+ if (style) {
+ if (style.n?.pattern) target.numFmt = style.n.pattern;
+
+ const font = buildFont(style);
+ if (font) target.font = font;
- const font = buildFont(style);
- if (font) target.font = font;
+ const fill = buildFill(style);
+ if (fill) target.fill = fill;
- const fill = buildFill(style);
- if (fill) target.fill = fill;
+ const alignment = buildAlignment(style);
+ if (alignment) target.alignment = alignment;
- const alignment = buildAlignment(style);
- if (alignment) target.alignment = alignment;
+ const border = buildBorder(style.bd);
+ if (border) target.border = border;
+ }
- const border = buildBorder(style.bd);
- if (border) target.border = border;
+ if (isHyperlink) target.font = { ...target.font, ...HYPERLINK_FONT };
}
-function setCellValue(target: ExcelJS.Cell, cell: ICellData): void {
+/** Writes the cell's value, reporting whether it became an Excel hyperlink. */
+function setCellValue(target: ExcelJS.Cell, cell: ICellData): boolean {
if (cell.f) {
// Univer stores formulas with a leading "="; exceljs wants it stripped, plus the
// cached result so the value shows without a recalc.
target.value = { formula: cell.f.replace(/^=/, ""), result: cell.v ?? undefined } as ExcelJS.CellFormulaValue;
- return;
+ return false;
}
+
+ // A rich-text cell (a link, mixed formatting) can carry its text only in `p`.
+ const segments = getCellDocumentSegments(cell);
+ const text = segments.map((segment) => segment.text).join("");
+
+ // Excel holds at most one hyperlink per cell, so a document with several linked runs exports
+ // the first target over the whole cell. A number keeps its own value and format instead.
+ const url = isFiniteNumber(cell.v) ? undefined : segments.find((segment) => segment.url)?.url;
+ if (url) {
+ target.value = { text, hyperlink: url } as ExcelJS.CellHyperlinkValue;
+ return true;
+ }
+
if (cell.v == null || cell.v === "") {
- // A rich-text cell (a link, mixed formatting) can carry its text only in `p`.
- const text = getCellDocumentText(cell);
if (text) target.value = text;
- return;
+ return false;
}
target.value = cell.v;
+ return false;
}
function buildFont(style: IStyleData): Partial<ExcelJS.Font> | null {
diff --git a/packages/commons/src/lib/spreadsheet/workbook_model.spec.ts b/packages/commons/src/lib/spreadsheet/workbook_model.spec.ts
index 366f4670b9..d383d4801b 100644
--- a/packages/commons/src/lib/spreadsheet/workbook_model.spec.ts
+++ b/packages/commons/src/lib/spreadsheet/workbook_model.spec.ts
@@ -108,7 +108,7 @@ describe("getDataValidations", () => {
describe("getCellDocumentText", () => {
it("reads the rich-text document, dropping the terminator and structural characters", () => {
- expect(getCellDocumentText({ p: { body: { dataStream: "Kit\r\n" } } })).toBe("Kit");
+ expect(getCellDocumentText({ p: { body: { dataStream: "Pen\r\n" } } })).toBe("Pen");
expect(getCellDocumentText({ p: { body: { dataStream: "first\rsecond\r\n" } } })).toBe("first\nsecond");
expect(getCellDocumentText({ p: { body: { dataStream: "logo\b\r\n" } } })).toBe("logo");
});
@@ -127,7 +127,7 @@ describe("getCellDocumentSegments", () => {
const segments = getCellDocumentSegments({
p: {
body: {
- dataStream: "see spy-shop now\r\n",
+ dataStream: "see supplier now\r\n",
customRanges: [{ startIndex: 4, endIndex: 11, properties: { url: "https://example.com" } }]
}
}
@@ -135,7 +135,7 @@ describe("getCellDocumentSegments", () => {
expect(segments).toEqual([
{ text: "see " },
- { text: "spy-shop", url: "https://example.com" },
+ { text: "supplier", url: "https://example.com" },
{ text: " now" }
]);
});
@@ -144,10 +144,10 @@ describe("getCellDocumentSegments", () => {
expect(getCellDocumentSegments({
p: {
body: {
- dataStream: "Kit\r\n",
+ dataStream: "Pen\r\n",
customRanges: [{ startIndex: 0, endIndex: 4, properties: { url: "https://example.com" } }]
}
}
- })).toEqual([{ text: "Kit", url: "https://example.com" }]);
+ })).toEqual([{ text: "Pen", url: "https://example.com" }]);
});
});
diff --git a/packages/commons/src/lib/spreadsheet/workbook_model.ts b/packages/commons/src/lib/spreadsheet/workbook_model.ts
index 224ed6a2ec..0a094f70f6 100644
--- a/packages/commons/src/lib/spreadsheet/workbook_model.ts
+++ b/packages/commons/src/lib/spreadsheet/workbook_model.ts
@@ -288,7 +288,8 @@ export interface CellDocumentSegment {
/**
* 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
+ * so the runs are cut on those offsets. A run keeps its `url` only when the target is safe to
+ * export, so an emitter can use it as-is. 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[] {
@@ -331,8 +332,8 @@ export function normalizeDataStream(dataStream: unknown): string {
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;
+ const url = sanitizeLinkUrl(range?.properties?.url);
+ if (!url) continue;
if (!isFiniteNumber(range.startIndex) || !isFiniteNumber(range.endIndex)) continue;
const start = Math.max(0, Math.trunc(range.startIndex));
@@ -351,6 +352,17 @@ function linkRanges(customRanges: ICellCustomRange[] | undefined, length: number
return ordered;
}
+/**
+ * Validates a hyperlink target before it reaches an export. Accepts the absolute `http`, `https`
+ * and `mailto` URLs Univer's link dialog writes; anything else, `javascript:` among them, returns
+ * `null` so the run is exported as plain text.
+ */
+function sanitizeLinkUrl(url: unknown): string | null {
+ if (typeof url !== "string") return null;
+ const trimmed = url.trim();
+ return /^(?:https?:\/\/|mailto:)[^\u0000-\u0020\u007F]+$/i.test(trimmed) ? trimmed : null;
+}
+
/**
* 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