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/XLS import: add support for links
Adorian Doran739fcdfb3839
diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.tsindex 9e96840beb..34630000d2 100644--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts@@ -10,9 +10,11 @@ import {parseXlsxToWorkbook,toArrayBuffer} from "./parse_from_xlsx.js";+import { renderSpreadsheetToXlsx } from "./render_to_xlsx.js";import {BorderStyle,CellValueType,+ CustomRangeType,type DataValidationRule,HorizontalAlign,type ICellData,@@ -970,3 +972,71 @@ describe("parseRange", () => {expect(parseRange("A1:zz")).toBeNull();});});++describe("hyperlinks", () => {+ it("carries the link into the document Univer stores it in", async () => {+ const sheet = await roundTrip((wb) => {+ const ws = wb.addWorksheet("Sheet1");+ ws.getCell("A1").value = { text: "Supplier", hyperlink: "https://example.com/pen" };+ });++ const cell = cellA1(sheet);+ expect(cell?.v).toBe("Supplier");+ expect(cell?.t).toBe(CellValueType.STRING);+ expect(cell?.p?.body).toEqual({+ dataStream: "Supplier\r\n",+ textRuns: [{ ts: {}, st: 0, ed: 8 }],+ paragraphs: [{ startIndex: 8 }],+ sectionBreaks: [{ startIndex: 9 }],+ customRanges: [{+ rangeId: "link-A1",+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: 7,+ properties: { url: "https://example.com/pen", refId: "link-A1" }+ }]+ });+ });++ it("keeps the display text alone when the target is unsafe", async () => {+ const sheet = await roundTrip((wb) => {+ const ws = wb.addWorksheet("Sheet1");+ ws.getCell("A1").value = { text: "Supplier", hyperlink: "javascript:alert(1)" };+ });++ expect(cellA1(sheet)?.v).toBe("Supplier");+ expect(cellA1(sheet)?.p).toBeUndefined();+ });++ it("survives an export and re-import of the same workbook", async () => {+ const exported = await renderSpreadsheetToXlsx(JSON.stringify({+ version: 1,+ workbook: {+ sheetOrder: ["s1"],+ styles: {},+ sheets: {+ s1: {+ id: "s1", name: "Sheet1", hidden: 0, mergeData: [], rowData: {}, columnData: {},+ cellData: {+ "0": {+ "0": {+ p: {+ body: {+ dataStream: "Pen\r\n",+ customRanges: [{ startIndex: 0, endIndex: 2, properties: { url: "https://example.com/pen" } }]+ }+ }+ }+ }+ }+ }+ }+ }+ }));++ const { workbook } = await parseXlsxToWorkbook(exported as ArrayBuffer);+ const cell = cellA1(workbook.sheets[workbook.sheetOrder[0]]);+ expect(cell?.v).toBe("Pen");+ expect(cell?.p?.body?.customRanges?.[0]?.properties?.url).toBe("https://example.com/pen");+ });+});diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.tsindex 5fa1be25b2..6dc0c0e401 100644--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts@@ -11,8 +11,8 @@* Known fidelity gaps (Excel features Univer's cell model — and our exporter — don't carry):* conditional formatting, filters, charts, comments, frozen panes and defined names are dropped.* Data validation is carried for the common constraint types (dropdown lists, numeric/date/text- * bounds) via the SHEET_DATA_VALIDATION_PLUGIN resource. Rich text is flattened to plain text and- * hyperlinks keep their display text but lose the link. Theme/indexed colors are resolved+ * bounds) via the SHEET_DATA_VALIDATION_PLUGIN resource. A hyperlink becomes the rich-text+ * document Univer stores a link in. Rich text is flattened to plain text. Theme/indexed colors are resolved* against the standard Office palette (see `THEME_COLORS`), which is approximate when the* file ships a custom theme.*/@@ -23,6 +23,7 @@ import "./exceljs_augmentation.js";import {BorderStyle,+ buildLinkedCellDocument,CellValueType,type DataValidationRule,HorizontalAlign,@@ -506,10 +507,7 @@ function applyCellValue(data: ICellData, cell: ExcelJS.Cell): void {data.t = CellValueType.NUMBER;break;case ExcelJS.ValueType.Hyperlink:- // Keep the display text; the link itself has no inline Univer equivalent.- /* v8 ignore next -- defensive: a hyperlink cell always carries display text */- data.v = String((cell.value as ExcelJS.CellHyperlinkValue)?.text ?? "");- data.t = CellValueType.STRING;+ applyHyperlink(data, cell);break;case ExcelJS.ValueType.RichText:data.v = flattenRichText(cell.value as ExcelJS.CellRichTextValue);@@ -530,6 +528,23 @@ function applyCellValue(data: ICellData, cell: ExcelJS.Cell): void {}}+/**+ * Carries a hyperlink cell across as text plus the document Univer keeps its link in. The cell's+ * address makes the range id unique within the workbook. An unsafe or missing target leaves the+ * display text behind on its own.+ */+function applyHyperlink(data: ICellData, cell: ExcelJS.Cell): void {+ const value = cell.value as ExcelJS.CellHyperlinkValue | null;+ /* v8 ignore next -- defensive: a hyperlink cell always carries display text */+ const text = String(value?.text ?? "");++ data.v = text;+ data.t = CellValueType.STRING;++ const linkDocument = buildLinkedCellDocument(text, value?.hyperlink, `link-${cell.address}`);+ if (linkDocument) data.p = linkDocument;+}+/** Maps a formula's cached result (number/bool/string/date) onto the cell value + type. */function assignPrimitive(data: ICellData, result: ExcelJS.Cell["result"]): void {if (result == null) return;diff --git a/packages/commons/src/lib/spreadsheet/workbook_model.ts b/packages/commons/src/lib/spreadsheet/workbook_model.tsindex 0a094f70f6..077f43142a 100644--- a/packages/commons/src/lib/spreadsheet/workbook_model.ts+++ b/packages/commons/src/lib/spreadsheet/workbook_model.ts@@ -70,6 +70,10 @@ export interface ICellData {}export interface ICellDocumentData {+ /** Univer's unit id for the cell document. */+ id?: string;+ /** Layout Univer recomputes from the cell's own style every time it renders the cell. */+ documentStyle?: Record<string, unknown>;drawings?: Record<string, ISheetDrawing>;drawingsOrder?: string[];/** Text content, present when the cell holds rich text such as a link or mixed formatting. */@@ -81,13 +85,19 @@ export interface ICellDocumentBody {dataStream?: string;/** Spans of `dataStream` carrying extra properties, hyperlinks among them. */customRanges?: ICellCustomRange[];+ /** Formatting runs and the paragraph/section markers Univer lays the text out from. */+ textRuns?: { ts: Record<string, unknown>; st: number; ed: number }[];+ paragraphs?: { startIndex: number }[];+ sectionBreaks?: { startIndex: number }[];}/** A span of a cell's document text. `startIndex` and `endIndex` are both inclusive. */export interface ICellCustomRange {+ rangeId?: string;+ rangeType?: CustomRangeType;startIndex?: number;endIndex?: number;- properties?: { url?: string };+ properties?: { url?: string; refId?: string };}export interface ISheetDrawing {@@ -197,6 +207,11 @@ export const enum CellValueType {FORCE_STRING = 4}+/** Univer's kinds of `ICellCustomRange` (`CustomRangeType` in @univerjs/core). */+export const enum CustomRangeType {+ HYPERLINK = 0+}+// Alignment enums (from UniversJS).export const enum HorizontalAlign {LEFT = 1,@@ -322,6 +337,38 @@ export function getCellDocumentText(cell: ICellData | undefined): string {return getCellDocumentSegments(cell).map((segment) => segment.text).join("");}+/**+ * Builds the rich-text document Univer stores for a hyperlinked cell: the text terminated by a+ * paragraph and a section break, plus one custom range covering it. `rangeId` identifies the link+ * inside the cell. Returns `null` when there is no text to link or the target is not safe to+ * store, so the caller keeps the cell as plain text.+ *+ * `documentStyle` stays empty because Univer overwrites its margins, page size and render config+ * from the cell's own style on every render.+ */+export function buildLinkedCellDocument(text: string, url: unknown, rangeId: string): ICellDocumentData | null {+ const target = sanitizeLinkUrl(url);+ if (!text || !target) return null;++ return {+ id: "d",+ documentStyle: {},+ body: {+ dataStream: `${text}\r\n`,+ textRuns: [{ ts: {}, st: 0, ed: text.length }],+ paragraphs: [{ startIndex: text.length }],+ sectionBreaks: [{ startIndex: text.length + 1 }],+ customRanges: [{+ rangeId,+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: text.length - 1,+ properties: { url: target, refId: rangeId }+ }]+ }+ };+}+/** Converts a whole `dataStream` to plain text, dropping the terminator it ends with. */export function normalizeDataStream(dataStream: unknown): string {if (typeof dataStream !== "string") return "";