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
test(commons): take coverage to 100%
Elian Doran24227ebd27bc
diff --git a/packages/commons/src/lib/bulk_actions.spec.ts b/packages/commons/src/lib/bulk_actions.spec.tsnew file mode 100644index 0000000000..e76beef729--- /dev/null+++ b/packages/commons/src/lib/bulk_actions.spec.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest";++import { NOTE_CONVERSION_IDS, RISKY_NOTE_CONVERSION_IDS } from "./bulk_actions.js";++describe("note conversion ids", () => {+ it("keeps the risky list a subset of the declared conversions", () => {+ // The two lists are maintained by hand and consumed in different places — the client+ // builds its combo box from NOTE_CONVERSION_IDS, while RISKY_NOTE_CONVERSION_IDS only+ // decides which of those gets the stronger confirmation prompt. A typo'd or stale entry+ // in the risky list would silently downgrade that prompt to the mild one.+ for (const id of RISKY_NOTE_CONVERSION_IDS) {+ expect(NOTE_CONVERSION_IDS).toContain(id);+ }++ expect(new Set(NOTE_CONVERSION_IDS).size).toBe(NOTE_CONVERSION_IDS.length);+ expect(new Set(RISKY_NOTE_CONVERSION_IDS).size).toBe(RISKY_NOTE_CONVERSION_IDS.length);+ });++ it("marks html-to-markdown as lossy and markdown-to-html as safe", () => {+ // HTML carries formatting Markdown cannot represent, so that direction drops content;+ // the reverse only ever gains structure.+ expect(RISKY_NOTE_CONVERSION_IDS).toContain("htmlToMarkdown");+ expect(RISKY_NOTE_CONVERSION_IDS).not.toContain("markdownToHtml");+ });+});diff --git a/packages/commons/src/lib/katex_macros.spec.ts b/packages/commons/src/lib/katex_macros.spec.tsnew file mode 100644index 0000000000..a3889ef72d--- /dev/null+++ b/packages/commons/src/lib/katex_macros.spec.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";++import { KATEX_MACROS } from "./katex_macros.js";++describe("KATEX_MACROS", () => {+ it("maps LaTeX commands onto non-empty KaTeX expansions", () => {+ // KaTeX keys its macro table by the literal command token, so a key that is missing its+ // leading backslash (or an empty expansion) silently never fires and the formula falls+ // back to raw red error text — the exact failure this table exists to prevent (#9523).+ const entries = Object.entries(KATEX_MACROS);+ expect(entries.length).toBeGreaterThan(0);++ for (const [command, expansion] of entries) {+ expect(command).toMatch(/^\\[a-zA-Z]+$/);+ expect(expansion.length).toBeGreaterThan(0);+ }+ });++ it("covers the commands MathLive's inline shortcuts auto-insert", () => {+ // These three are reachable by typing alone — `dx`/`dy`/`dt`, `?=` and `::` — so they are+ // the ones a user hits without ever opening the symbol palette.+ expect(KATEX_MACROS["\\differentialD"]).toBe("\\mathrm{d}");+ expect(KATEX_MACROS["\\questeq"]).toBe("\\stackrel{?}{=}");+ expect(KATEX_MACROS["\\Colon"]).toBe("\\dblcolon");+ });++ it("renders the ISO 80000-2 operator family upright", () => {+ // The whole family shares one definition shape; rendering any of them italic would make+ // them read as variables rather than operators.+ for (const command of ["\\differentialD", "\\capitalDifferentialD", "\\exponentialE", "\\imaginaryI", "\\imaginaryJ"]) {+ expect(KATEX_MACROS[command]).toMatch(/^\\mathrm\{.+\}$/);+ }+ });+});diff --git a/packages/commons/src/lib/keyboard_shortcut_display.spec.ts b/packages/commons/src/lib/keyboard_shortcut_display.spec.tsnew file mode 100644index 0000000000..09ee997e1b--- /dev/null+++ b/packages/commons/src/lib/keyboard_shortcut_display.spec.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vitest";++import {+ formatShortcut,+ formatShortcutKey,+ joinShortcut,+ SHORTCUT_KEY_PREFIX,+ splitShortcutForDisplay+} from "./keyboard_shortcut_display.js";++/**+ * Stand-in for the caller's i18n `t()`. Returns the bare id so assertions stay language-independent+ * (`keyboard_shortcut_keys.ctrl` -> `ctrl`) — see CLAUDE.md: never assert on translated strings.+ */+const translate = (key: string) => key.replace(`${SHORTCUT_KEY_PREFIX}.`, "");++describe("splitShortcutForDisplay", () => {+ it("splits on + and strips the global: storage prefix", () => {+ expect(splitShortcutForDisplay("Ctrl+Shift+J")).toEqual(["Ctrl", "Shift", "J"]);+ expect(splitShortcutForDisplay("global:Meta+Plus")).toEqual(["Meta", "Plus"]);+ expect(splitShortcutForDisplay("F5")).toEqual(["F5"]);+ });++ it("preserves the original casing of each token", () => {+ expect(splitShortcutForDisplay("cTrL+j")).toEqual(["cTrL", "j"]);+ });++ it("returns no tokens for an empty, blank or missing shortcut", () => {+ expect(splitShortcutForDisplay("")).toEqual([]);+ expect(splitShortcutForDisplay(" ")).toEqual([]);+ expect(splitShortcutForDisplay("global:")).toEqual([]);+ // Callers read shortcuts straight out of options, which can be unset.+ expect(splitShortcutForDisplay(undefined as unknown as string)).toEqual([]);+ });++ it("resolves the plus key, which doubles as the separator", () => {+ // `+` is both the separator and a key, so the plus key is stored either as a lone `+` or+ // as a trailing `++`. Both must yield a single `+` token, not an empty one.+ expect(splitShortcutForDisplay("+")).toEqual(["+"]);+ expect(splitShortcutForDisplay("Ctrl++")).toEqual(["Ctrl", "+"]);+ expect(splitShortcutForDisplay("Ctrl+Shift++")).toEqual(["Ctrl", "Shift", "+"]);+ // The named form is a plain token and splits normally.+ expect(splitShortcutForDisplay("Ctrl+Plus")).toEqual(["Ctrl", "Plus"]);+ });+});++describe("formatShortcutKey", () => {+ it("renders glyph tokens as universal symbols without translating them", () => {+ expect(formatShortcutKey("Up", translate)).toBe("↑");+ expect(formatShortcutKey("ArrowDown", translate)).toBe("↓");+ expect(formatShortcutKey("left", translate)).toBe("←");+ expect(formatShortcutKey("RIGHT", translate)).toBe("→");+ expect(formatShortcutKey("Plus", translate)).toBe("+");+ expect(formatShortcutKey("+", translate)).toBe("+");+ });++ it("routes modifiers and named keys through the translate function", () => {+ expect(formatShortcutKey("Ctrl", translate)).toBe("ctrl");+ expect(formatShortcutKey("Control", translate)).toBe("ctrl");+ expect(formatShortcutKey("CommandOrControl", translate)).toBe("ctrl");+ expect(formatShortcutKey("Cmd", translate)).toBe("meta");+ expect(formatShortcutKey("Esc", translate)).toBe("escape");+ expect(formatShortcutKey("Del", translate)).toBe("delete");+ expect(formatShortcutKey("PageUp", translate)).toBe("page_up");+ expect(formatShortcutKey("Ins", translate)).toBe("insert");+ });++ it("emits any other token verbatim, preserving its casing", () => {+ expect(formatShortcutKey("J", translate)).toBe("J");+ expect(formatShortcutKey("j", translate)).toBe("j");+ expect(formatShortcutKey("F11", translate)).toBe("F11");+ expect(formatShortcutKey("-", translate)).toBe("-");+ });+});++describe("formatShortcut", () => {+ it("formats each token in order on non-mac platforms", () => {+ expect(formatShortcut("Ctrl+Shift+J", translate, false)).toEqual(["ctrl", "shift", "J"]);+ expect(formatShortcut("global:Alt+Left", translate, false)).toEqual(["alt", "←"]);+ expect(formatShortcut("", translate, false)).toEqual([]);+ });++ it("renders mac modifiers as glyphs in Apple's canonical order", () => {+ // Stored order is irrelevant on macOS — both spellings must display as ⌃⌥⇧⌘.+ expect(formatShortcut("Meta+Shift+Alt+Ctrl+J", translate, true)).toEqual(["⌃", "⌥", "⇧", "⌘", "J"]);+ expect(formatShortcut("Ctrl+Alt+Shift+Meta+J", translate, true)).toEqual(["⌃", "⌥", "⇧", "⌘", "J"]);+ });++ it("renders the common named keys as mac glyphs", () => {+ expect(formatShortcut("Enter", translate, true)).toEqual(["↩"]);+ expect(formatShortcut("Escape", translate, true)).toEqual(["⎋"]);+ expect(formatShortcut("Tab", translate, true)).toEqual(["⇥"]);+ expect(formatShortcut("Delete", translate, true)).toEqual(["⌦"]);+ expect(formatShortcut("Backspace", translate, true)).toEqual(["⌫"]);+ });++ it("keeps the translated label on mac for keys whose glyph reads worse than the word", () => {+ // Page Up/Down, Home/End, Space and Insert have no entry in the mac glyph table, so they+ // fall back to the cross-platform rendering rather than an obscure symbol.+ expect(formatShortcut("Meta+PageUp", translate, true)).toEqual(["⌘", "page_up"]);+ expect(formatShortcut("Meta+Home", translate, true)).toEqual(["⌘", "home"]);+ expect(formatShortcut("Meta+Space", translate, true)).toEqual(["⌘", "space"]);+ expect(formatShortcut("Meta+Insert", translate, true)).toEqual(["⌘", "insert"]);+ });++ it("falls back to arrow glyphs and verbatim tokens for non-modifier keys on mac", () => {+ expect(formatShortcut("Meta+Left", translate, true)).toEqual(["⌘", "←"]);+ expect(formatShortcut("Meta+Plus", translate, true)).toEqual(["⌘", "+"]);+ expect(formatShortcut("Meta+F5", translate, true)).toEqual(["⌘", "F5"]);+ });++ it("folds CommandOrControl into a modifier glyph on mac", () => {+ expect(formatShortcut("CommandOrControl+J", translate, true)).toEqual(["⌃", "J"]);+ });+});++describe("joinShortcut", () => {+ it("concatenates with no separator on mac and with + elsewhere", () => {+ expect(joinShortcut(["⇧", "⌘", "J"], true)).toBe("⇧⌘J");+ expect(joinShortcut(["ctrl", "shift", "J"], false)).toBe("ctrl+shift+J");+ });++ it("honours a custom separator off mac only", () => {+ // The command palette spaces its shortcuts out; macOS keeps the native tight form.+ expect(joinShortcut(["ctrl", "J"], false, " + ")).toBe("ctrl + J");+ expect(joinShortcut(["⌘", "J"], true, " + ")).toBe("⌘J");+ });++ it("returns an empty string when there are no tokens", () => {+ expect(joinShortcut([], false)).toBe("");+ });+});diff --git a/packages/commons/src/lib/llm/extract_chat_text.spec.ts b/packages/commons/src/lib/llm/extract_chat_text.spec.tsindex 391231fdc1..bfe56f6e4a 100644--- a/packages/commons/src/lib/llm/extract_chat_text.spec.ts+++ b/packages/commons/src/lib/llm/extract_chat_text.spec.ts@@ -40,6 +40,21 @@ describe("extractLlmChatText", () => {expect(extractLlmChatText(content)).toEqual("First part. Second part.");});+ it("skips turns whose content is neither a string nor a block list", () => {+ // A turn can arrive with no content at all (a bare tool-call turn), or with a shape the+ // schema does not describe; neither should contribute text or throw.+ const content = JSON.stringify({+ version: 1,+ messages: [+ { id: "1", role: "assistant" },+ { id: "2", role: "assistant", content: null },+ { id: "3", role: "assistant", content: { text: "not a block list" } },+ { id: "4", role: "user", content: "Only this survives." }+ ]+ });+ expect(extractLlmChatText(content)).toEqual("Only this survives.");+ });+it("skips thinking and error turns", () => {const content = JSON.stringify({version: 1,diff --git a/packages/commons/src/lib/markdown_renderer.spec.ts b/packages/commons/src/lib/markdown_renderer.spec.tsindex 3e608c60b7..5eb0774ad3 100644--- a/packages/commons/src/lib/markdown_renderer.spec.ts+++ b/packages/commons/src/lib/markdown_renderer.spec.ts@@ -421,6 +421,14 @@ describe("renderToHtml", () => {expect(html).toBe('<aside class="admonition note"> </aside>');});+ it("treats the whole marker paragraph as the title when it is raw, unterminated HTML", () => {+ // A callout authored as a raw HTML paragraph reaches the renderer verbatim, so the+ // marker paragraph carries neither a closing `</p>` nor a soft line break to split on.+ // Everything after the marker is then the title, with no body.+ expect(render("> <p>[!NOTE] raw html para"))+ .toBe('<aside class="admonition note"><p><strong>raw html para</strong></p></aside>');+ });+it("keeps an unknown admonition type as a normal blockquote", () => {const html = render("> [!FOO]\n> body");expect(html).toContain("<blockquote>");diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.tsindex 58c8893acb..9e96840beb 100644--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.spec.ts@@ -1,7 +1,15 @@import ExcelJS from "exceljs";-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";-import { excelColorToRgb, parseRange, parseXlsxToWorkbook, toArrayBuffer } from "./parse_from_xlsx.js";+import {+ anchorToBox,+ bytesToBase64,+ excelColorToRgb,+ mediaToDataUrl,+ parseRange,+ parseXlsxToWorkbook,+ toArrayBuffer+} from "./parse_from_xlsx.js";import {BorderStyle,CellValueType,@@ -513,12 +521,101 @@ describe("parseXlsxToWorkbook images", () => {ws.addImage(id, { tl: { col: 0, row: 0 }, ext: { width: 120, height: 90 } });});- const drawing = drawingsOf(workbook)?.data[drawingsOf(workbook)!.order[0]];+ const drawings = drawingsOf(workbook);+ const drawing = drawings?.data[drawings.order[0]];expect(drawing.transform.width).toBe(120);expect(drawing.transform.height).toBe(90);expect(drawing.sheetTransform.from).toMatchObject({ column: 0, row: 0 });});+ it("embeds jpeg and gif images with their own mime type", async () => {+ const workbook = await parseBuilt((wb) => {+ const ws = wb.addWorksheet("S");+ const jpeg = wb.addImage({ base64: PNG, extension: "jpeg" });+ const gif = wb.addImage({ base64: PNG, extension: "gif" });+ ws.addImage(jpeg, { tl: { col: 0, row: 0 }, ext: { width: 10, height: 10 } });+ ws.addImage(gif, { tl: { col: 2, row: 2 }, ext: { width: 10, height: 10 } });+ });++ const drawings = drawingsOf(workbook);+ const sources = drawings?.order.map((id) => drawings.data[id].source as string) ?? [];+ expect(sources[0]).toMatch(/^data:image\/jpeg;base64,/);+ expect(sources[1]).toMatch(/^data:image\/gif;base64,/);+ });++ it("skips an image whose format cannot be embedded, and the resource with it", async () => {+ // Only png/jpeg/gif survive the import; anything else (here a bmp) is dropped rather than+ // emitted as a broken data URL. With no embeddable image left, the sheet gets no resource.+ const workbook = await parseBuilt((wb) => {+ const ws = wb.addWorksheet("S");+ const id = wb.addImage({ base64: PNG, extension: "bmp" as "png" });+ ws.addImage(id, { tl: { col: 0, row: 0 }, ext: { width: 10, height: 10 } });+ });++ expect(drawingsOf(workbook)).toBeNull();+ });++ it("keeps an embeddable image when a sibling image is dropped", async () => {+ const workbook = await parseBuilt((wb) => {+ const ws = wb.addWorksheet("S");+ const bmp = wb.addImage({ base64: PNG, extension: "bmp" as "png" });+ const png = wb.addImage({ base64: PNG, extension: "png" });+ ws.addImage(bmp, { tl: { col: 0, row: 0 }, ext: { width: 10, height: 10 } });+ ws.addImage(png, { tl: { col: 2, row: 2 }, ext: { width: 10, height: 10 } });+ });++ const drawings = drawingsOf(workbook);+ expect(drawings?.order.length).toBe(1);+ expect(drawings?.data[drawings.order[0]].source).toMatch(/^data:image\/png;base64,/);+ });++ it("anchors an image to its top-left cell when it has no extent", async () => {+ // A zero-sized extent puts the bottom-right corner back on the origin, so the anchor walk+ // gets a non-positive target and must resolve to the very first cell instead of looping.+ const workbook = await parseBuilt((wb) => {+ const ws = wb.addWorksheet("S");+ const id = wb.addImage({ base64: PNG, extension: "png" });+ ws.addImage(id, { tl: { col: 0, row: 0 }, ext: { width: 0, height: 0 } });+ });++ const drawings = drawingsOf(workbook);+ const drawing = drawings?.data[drawings.order[0]];+ expect(drawing.transform).toMatchObject({ width: 0, height: 0 });+ expect(drawing.sheetTransform.to).toMatchObject({ row: 0, column: 0, rowOffset: 0, columnOffset: 0 });+ });++ it("skips zero-width columns while resolving an anchor", async () => {+ // A hidden/collapsed column contributes no width, so the walk must step over it rather+ // than consuming the image's extent on a track that occupies no space.+ const workbook = await parseBuilt((wb) => {+ const ws = wb.addWorksheet("S");+ ws.getColumn(1).width = 0;+ const id = wb.addImage({ base64: PNG, extension: "png" });+ ws.addImage(id, { tl: { col: 0, row: 0 }, ext: { width: 200, height: 40 } });+ });++ const drawings = drawingsOf(workbook);+ const drawing = drawings?.data[drawings.order[0]];+ expect(drawing.transform.width).toBe(200);+ // Column 0 has no width, so the right edge lands past it rather than inside it.+ expect(drawing.sheetTransform.to.column).toBeGreaterThan(0);+ });++ it("gives up the anchor walk for an image extending beyond any addressable track", async () => {+ // The walk is bounded so a corrupt extent cannot spin forever; past the bound the anchor+ // falls back to the origin while the absolute transform still records the real size.+ const workbook = await parseBuilt((wb) => {+ const ws = wb.addWorksheet("S");+ const id = wb.addImage({ base64: PNG, extension: "png" });+ ws.addImage(id, { tl: { col: 0, row: 0 }, ext: { width: 10_000_000, height: 10 } });+ });++ const drawings = drawingsOf(workbook);+ const drawing = drawings?.data[drawings.order[0]];+ expect(drawing.transform.width).toBe(10_000_000);+ expect(drawing.sheetTransform.to).toMatchObject({ column: 0, columnOffset: 0 });+ });+it("preserves multiple images in order", async () => {const workbook = await parseBuilt((wb) => {const ws = wb.addWorksheet("S");@@ -549,6 +646,128 @@ describe("parseXlsxToWorkbook images", () => {});});+describe("mediaToDataUrl", () => {+ const bytes = new Uint8Array([1, 2, 3]);++ it("encodes a supported format from either buffer representation", () => {+ // exceljs hands back a Node Buffer when running on the server and a plain ArrayBuffer in+ // the browser build, so both have to encode to the same data URL.+ expect(mediaToDataUrl({ extension: "png", buffer: bytes })).toBe("data:image/png;base64,AQID");+ expect(mediaToDataUrl({ extension: "PNG", buffer: bytes.buffer })).toBe("data:image/png;base64,AQID");+ });++ it("returns null when the format or the bytes are unusable", () => {+ expect(mediaToDataUrl(undefined)).toBeNull();+ // No extension at all — nothing to map onto a mime type.+ expect(mediaToDataUrl({ buffer: bytes })).toBeNull();+ expect(mediaToDataUrl({ extension: "tiff", buffer: bytes })).toBeNull();+ // A known format whose payload never made it into the archive.+ expect(mediaToDataUrl({ extension: "png" })).toBeNull();+ });+});++describe("bytesToBase64", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("encodes via Buffer on Node and via btoa in the browser", () => {+ // The standalone build runs this same importer in a browser worker, where `Buffer` does+ // not exist; both runtimes must produce identical base64.+ const bytes = new Uint8Array([0, 1, 2, 250, 251, 252]);+ const viaBuffer = bytesToBase64(bytes);+ expect(viaBuffer).toBe("AAEC+vv8");++ vi.stubGlobal("Buffer", undefined);+ expect(bytesToBase64(bytes)).toBe(viaBuffer);+ });++ it("chunks large inputs in the browser path", () => {+ // The browser path spreads bytes into String.fromCharCode, which blows the argument limit+ // past ~64k, so it walks the array in 32k slices.+ const bytes = new Uint8Array(0x8000 * 2 + 5).fill(65);+ const viaBuffer = bytesToBase64(bytes);++ vi.stubGlobal("Buffer", undefined);+ expect(bytesToBase64(bytes)).toBe(viaBuffer);+ });+});++describe("anchorToBox", () => {+ /** Sheet with uniform 100px columns and 50px rows, so anchor arithmetic is easy to read. */+ const sheet: IWorksheetData = {+ id: "s1",+ name: "S",+ cellData: {},+ rowData: {},+ columnData: {},+ defaultColumnWidth: 100,+ defaultRowHeight: 50+ } as IWorksheetData;++ it("inverts a two-cell anchor into cell anchors plus an absolute box", () => {+ const box = anchorToBox(sheet, { tl: { col: 1, row: 2 }, br: { col: 3, row: 4 } } as ExcelJS.ImageRange);++ expect(box).toMatchObject({+ from: { column: 1, columnOffset: 0, row: 2, rowOffset: 0 },+ to: { column: 3, columnOffset: 0, row: 4, rowOffset: 0 },+ left: 100, top: 100, width: 200, height: 100+ });+ });++ it("keeps the fractional part of an anchor as a px offset into its cell", () => {+ const box = anchorToBox(sheet, { tl: { col: 1.5, row: 2.5 }, br: { col: 3, row: 4 } } as ExcelJS.ImageRange);++ expect(box?.from).toMatchObject({ column: 1, columnOffset: 50, row: 2, rowOffset: 25 });+ expect(box?.left).toBe(150);+ });++ it("derives the bottom-right corner from the extent for a one-cell anchor", () => {+ const box = anchorToBox(sheet, { tl: { col: 0, row: 0 }, ext: { width: 250, height: 75 } } as unknown as ExcelJS.ImageRange);++ expect(box).toMatchObject({ width: 250, height: 75 });+ expect(box?.to).toMatchObject({ column: 2, columnOffset: 50, row: 1, rowOffset: 25 });+ });++ it("never reports a negative size for an inverted anchor", () => {+ const box = anchorToBox(sheet, { tl: { col: 3, row: 4 }, br: { col: 1, row: 2 } } as ExcelJS.ImageRange);++ expect(box).toMatchObject({ width: 0, height: 0 });+ });++ it("rejects an anchor with no top-left corner, or with neither a bottom-right nor an extent", () => {+ // Both shapes come from a malformed drawing in a third-party xlsx; the image is dropped+ // rather than placed at a guessed position.+ expect(anchorToBox(sheet, {} as ExcelJS.ImageRange)).toBeNull();+ expect(anchorToBox(sheet, { tl: { col: 0, row: 0 } } as unknown as ExcelJS.ImageRange)).toBeNull();+ });++ it("steps over zero-sized tracks when walking an extent to its end cell", () => {+ // A collapsed column occupies no space, so it must not swallow any of the extent.+ const collapsed = { ...sheet, columnData: { 0: { w: 0 }, 1: { w: 0 } } } as IWorksheetData;+ const box = anchorToBox(collapsed, { tl: { col: 0, row: 0 }, ext: { width: 50, height: 25 } } as unknown as ExcelJS.ImageRange);++ expect(box?.to.column).toBe(2);+ expect(box?.to.columnOffset).toBe(50);+ });++ it("falls back to the built-in track sizes when the sheet declares no defaults", () => {+ const bare = { id: "s1", name: "S", cellData: {}, rowData: {}, columnData: {} } as IWorksheetData;+ const box = anchorToBox(bare, { tl: { col: 1, row: 1 }, br: { col: 2, row: 2 } } as ExcelJS.ImageRange);++ // The built-in defaults are 88px wide and 24px tall.+ expect(box).toMatchObject({ left: 88, top: 24, width: 88, height: 24 });+ });++ it("uses a track's own size ahead of the default", () => {+ const mixed = { ...sheet, rowData: { 0: { h: 10 } }, columnData: { 0: { w: 20 } } } as IWorksheetData;+ const box = anchorToBox(mixed, { tl: { col: 1, row: 1 }, br: { col: 2, row: 2 } } as ExcelJS.ImageRange);++ // Row 0 is 10px and column 0 is 20px, so the second track starts there rather than at the default.+ expect(box).toMatchObject({ left: 20, top: 10 });+ });+});+describe("parseXlsxToWorkbook data validation", () => {// Reads the SHEET_DATA_VALIDATION_PLUGIN resource for a sheet back into a typed shape.function validationsOf(diff --git a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.tsindex caaf6e0a98..5fa1be25b2 100644--- a/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts+++ b/packages/commons/src/lib/spreadsheet/parse_from_xlsx.ts@@ -182,6 +182,9 @@ function buildDrawing(wb: ExcelJS.Workbook, sheet: IWorksheetData, sheetId: striif (!source) return null;const box = anchorToBox(sheet, image.range);+ /* v8 ignore next -- exceljs refuses to *write* an anchor with no tl or no br/ext, so this+ guard is only reachable from a malformed third-party file; anchorToBox's own null returns+ are covered directly in the spec. */if (!box) return null;// Univer keeps the orientation fields on every transform; imports are always upright.@@ -204,7 +207,7 @@ function buildDrawing(wb: ExcelJS.Workbook, sheet: IWorksheetData, sheetId: stri}/** Converts an exceljs media entry to a base64 `data:` URL, or null for an unsupported format. */-function mediaToDataUrl(media: { extension?: string; buffer?: Uint8Array | ArrayBuffer } | undefined): string | null {+export function mediaToDataUrl(media: { extension?: string; buffer?: Uint8Array | ArrayBuffer } | undefined): string | null {const mime = imageMime(media?.extension);if (!mime || !media?.buffer) return null;const bytes = media.buffer instanceof Uint8Array ? media.buffer : new Uint8Array(media.buffer);@@ -226,7 +229,7 @@ function imageMime(extension: string | undefined): string | null {* the absolute `left`/`top`/`width`/`height`. The top-left comes from `tl`; the bottom-right from* `br` (two-cell anchor) or `tl + ext` (one-cell anchor).*/-function anchorToBox(sheet: IWorksheetData, range: ExcelJS.ImageRange): { from: CellAnchor; to: CellAnchor; left: number; top: number; width: number; height: number } | null {+export function anchorToBox(sheet: IWorksheetData, range: ExcelJS.ImageRange): { from: CellAnchor; to: CellAnchor; left: number; top: number; width: number; height: number } | null {const tl = range?.tl as { col: number; row: number } | undefined;if (!tl) return null;@@ -311,7 +314,7 @@ function rowHeightPx(sheet: IWorksheetData, row: number): number {}/** Base64-encodes raw bytes in both Node (server import) and the browser. */-function bytesToBase64(bytes: Uint8Array): string {+export function bytesToBase64(bytes: Uint8Array): string {if (typeof Buffer !== "undefined") {return Buffer.from(bytes).toString("base64");}diff --git a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_html.spec.tsindex ed1a94801f..95bd13d313 100644--- a/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_html.spec.ts@@ -1352,6 +1352,85 @@ describe("renderSpreadsheetToHtml", () => {expect(html.indexOf("AAAAAAAAAAAA")).toBeLessThan(html.indexOf("BBBBBBBBBBBB"));});+ it("falls back to insertion order when a cell document has no drawingsOrder", () => {+ // `drawingsOrder` is only written once a document has reordered its images, so a+ // single-image cell commonly arrives without it.+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ p: {+ drawings: {+ first: { drawingId: "first", source: "api/attachments/AAAAAAAAAAAA/image/a.png", transform: { width: 5, height: 5 } },+ second: { drawingId: "second", source: "api/attachments/BBBBBBBBBBBB/image/b.png", transform: { width: 5, height: 5 } }+ }+ }+ })+ );+ expect(html.indexOf("AAAAAAAAAAAA")).toBeLessThan(html.indexOf("BBBBBBBBBBBB"));+ });++ it("skips an id in drawingsOrder that has no matching drawing", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ p: {+ drawings: {+ d1: { drawingId: "d1", source: "api/attachments/AAAAAAAAAAAA/image/a.png", transform: { width: 5, height: 5 } }+ },+ drawingsOrder: ["stale", "d1"]+ }+ })+ );+ expect(html.match(/<img/g)?.length).toBe(1);+ expect(html).toContain("AAAAAAAAAAAA");+ });++ it("omits the style attribute when a cell image has no usable dimensions", () => {+ // Univer can store a drawing before its size is measured; the image should still render,+ // just without width/height so it falls back to its intrinsic size.+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ p: {+ drawings: {+ d1: { drawingId: "d1", source: "api/attachments/AAAAAAAAAAAA/image/a.png" },+ d2: { drawingId: "d2", source: "api/attachments/BBBBBBBBBBBB/image/b.png", transform: { width: "wide", height: null } }+ },+ drawingsOrder: ["d1", "d2"]+ }+ })+ );+ const imgs = html.match(/<img[^>]*>/g) ?? [];+ expect(imgs.length).toBe(2);+ expect(imgs.every((img) => !img.includes("style="))).toBe(true);+ });++ it("emits only the dimension that is present", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ p: {+ drawings: {+ d1: { drawingId: "d1", source: "api/attachments/AAAAAAAAAAAA/image/a.png", transform: { width: 20 } }+ },+ drawingsOrder: ["d1"]+ }+ })+ );+ expect(html).toContain('style="width:20px"');+ });++ it("skips a cell image whose source is missing or not a string", () => {+ const html = renderSpreadsheetToHtml(+ singleCellWorkbook({+ p: {+ drawings: {+ d1: { drawingId: "d1", transform: { width: 10, height: 10 } },+ d2: { drawingId: "d2", source: 42, transform: { width: 10, height: 10 } }+ },+ drawingsOrder: ["d1", "d2"]+ }+ })+ );+ expect(html).not.toContain("<img");+ });+it("skips a cell image with an unsafe source", () => {const html = renderSpreadsheetToHtml(singleCellWorkbook({@@ -1539,6 +1618,66 @@ describe("renderSpreadsheetToHtml", () => {expect(html).not.toContain("evil.example");});+ it("treats a floating image's missing coordinates as zero", () => {+ // Univer writes a transform as soon as an image is inserted, but individual fields can be+ // absent before the image is moved or resized; those must read as 0, not NaN.+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings([+ { drawingId: "img1", source: "api/attachments/cgN4jEBCA1Kn/image/image.png", transform: { angle: 0 } }+ ])+ );+ expect(html).toContain("left:0px;top:0px;width:0px;height:0px");+ });++ it("extends the grid using the default track sizes when the sheet declares none", () => {+ // A sheet saved without explicit defaults still has to grow enough rows and columns to+ // contain an image that reaches past the last populated cell.+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings(+ [urlDrawing("img1", "api/attachments/cgN4jEBCA1Kn/image/image.png", { left: 300, top: 200, width: 100, height: 80 })],+ { sheetExtra: { defaultColumnWidth: undefined, defaultRowHeight: undefined, rowCount: undefined, columnCount: undefined } }+ )+ );+ // 280px of height at the default 24px row is ~12 rows; the single-cell sheet had one.+ expect((html.match(/<tr/g) ?? []).length).toBeGreaterThan(5);+ expect(html).toContain("spreadsheet-sheet");+ });++ it("does not grow an axis the images do not reach past", () => {+ // A flat image extends the sheet rightwards only; the vertical walk gets a non-positive+ // target and must stop immediately rather than counting rows.+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings([+ urlDrawing("img1", "api/attachments/cgN4jEBCA1Kn/image/image.png", { left: 300, top: 0, width: 100, height: 0 })+ ])+ );+ expect((html.match(/<tr/g) ?? []).length).toBe(1);+ });++ it("stops extending an axis whose default track size is degenerate", () => {+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings(+ [urlDrawing("img1", "api/attachments/cgN4jEBCA1Kn/image/image.png", { left: 0, top: 300, width: 10, height: 100 })],+ { sheetExtra: { defaultRowHeight: 0 } }+ )+ );+ expect((html.match(/<tr/g) ?? []).length).toBe(1);+ });++ it("counts hidden and explicitly sized tracks correctly when extending the grid", () => {+ // Hidden rows occupy no space, so they must not consume any of the image's reach, while+ // rows carrying an explicit height are counted at that height rather than the default.+ const html = renderSpreadsheetToHtml(+ workbookWithFloatingDrawings(+ [urlDrawing("img1", "api/attachments/cgN4jEBCA1Kn/image/image.png", { left: 0, top: 0, width: 10, height: 200 })],+ { rowData: { "0": { hd: 1 }, "1": { h: 100 }, "2": { h: 100 } } }+ )+ );+ // Row 0 contributes nothing, rows 1-2 contribute 100px each: the image ends on row 2, so+ // the grid grows to three rows — of which the hidden one is not emitted.+ expect((html.match(/<tr/g) ?? []).length).toBe(2);+ });+it("does not add a floating wrapper to a sheet without drawings", () => {const html = renderSpreadsheetToHtml(singleCellWorkbook({ v: "x" }));expect(html).not.toContain("spreadsheet-sheet");diff --git a/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts b/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.tsindex 8149bc954a..427cd198fb 100644--- a/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts+++ b/packages/commons/src/lib/spreadsheet/render_to_xlsx.spec.ts@@ -393,7 +393,10 @@ describe("renderSpreadsheetToXlsx", () => {const resolveAsPng: NonNullable<Parameters<typeof renderSpreadsheetToXlsx>[1]>["resolveImage"] =async (source) => (source ? { base64: PNG, extension: "png" } : null);- function floatingImageWorkbook(drawing: Record<string, unknown> & { drawingId: string }): string {+ function floatingImageWorkbook(+ drawing: Record<string, unknown> & { drawingId: string },+ sheetExtra: Record<string, unknown> = {}+ ): string {const sheetId = "s1";return JSON.stringify({version: 1,@@ -410,7 +413,8 @@ describe("renderSpreadsheetToXlsx", () => {mergeData: [],cellData: { "0": { "0": { v: "x" } } },rowData: {},- columnData: {}+ columnData: {},+ ...sheetExtra}},resources: [@@ -497,6 +501,112 @@ describe("renderSpreadsheetToXlsx", () => {expect(wb.getWorksheet("Sheet1")?.getImages().length).toBe(0);});+ it("embeds cell images in insertion order when the document has no drawingsOrder", async () => {+ const wb = await load(await renderSpreadsheetToXlsx(+ singleCellWorkbook({+ p: {+ drawings: {+ d1: { drawingId: "d1", source: "api/attachments/AAAAAAAAAAAA/image/a.png", transform: { width: 10, height: 10 } },+ d2: { drawingId: "d2", source: "api/attachments/BBBBBBBBBBBB/image/b.png", transform: { width: 20, height: 20 } }+ }+ }+ }),+ { resolveImage: resolveAsPng }+ ));+ expect(wb.worksheets[0].getImages().length).toBe(2);+ });++ it("skips cell drawings that are stale, unsized or unresolvable", async () => {+ // Each of these is a drawing exceljs cannot anchor: an id left behind in the order, a+ // drawing whose size is missing or degenerate, one with no source, and one the caller's+ // resolver declines. None may abort the export.+ const wb = await load(await renderSpreadsheetToXlsx(+ singleCellWorkbook({+ p: {+ drawings: {+ unsized: { drawingId: "unsized", source: "api/attachments/AAAAAAAAAAAA/image/a.png" },+ zeroWidth: { drawingId: "zeroWidth", source: "api/attachments/AAAAAAAAAAAA/image/a.png", transform: { width: 0, height: 10 } },+ zeroHeight: { drawingId: "zeroHeight", source: "api/attachments/AAAAAAAAAAAA/image/a.png", transform: { width: 10, height: 0 } },+ sourceless: { drawingId: "sourceless", transform: { width: 10, height: 10 } },+ declined: { drawingId: "declined", source: "decline-me", transform: { width: 10, height: 10 } },+ good: { drawingId: "good", source: "api/attachments/BBBBBBBBBBBB/image/b.png", transform: { width: 10, height: 10 } }+ },+ drawingsOrder: ["stale", "unsized", "zeroWidth", "zeroHeight", "sourceless", "declined", "good"]+ }+ }),+ { resolveImage: async (source) => (source === "decline-me" ? { base64: "", extension: "png" } : { base64: PNG, extension: "png" }) }+ ));+ expect(wb.worksheets[0].getImages().length).toBe(1);+ });++ it("anchors a floating image at the cell corner when its track has no size", async () => {+ // A collapsed row/column gives the offset nothing to be a fraction of; the anchor must+ // fall back to the cell corner instead of dividing by zero.+ const wb = await load(await renderSpreadsheetToXlsx(+ floatingImageWorkbook({+ drawingId: "img1",+ source: "api/attachments/cgN4jEBCA1Kn/image/image.png",+ sheetTransform: {+ from: { row: 0, rowOffset: 5, column: 0, columnOffset: 5 },+ to: { row: 2, rowOffset: 0, column: 2, columnOffset: 0 }+ }+ }, { rowData: { "0": { h: 0 } }, columnData: { "0": { w: 0 } } }),+ { resolveImage: resolveAsPng }+ ));+ const range = wb.getWorksheet("Sheet1")?.getImages()[0]?.range;+ expect(range?.tl.col).toBeCloseTo(0);+ expect(range?.tl.row).toBeCloseTo(0);+ });++ it("uses explicit track sizes, and the built-in defaults when the sheet declares none", async () => {+ // The offset is expressed as a fraction of the containing cell, so the same offset+ // resolves differently depending on whether the track carries its own size.+ const sized = await load(await renderSpreadsheetToXlsx(+ floatingImageWorkbook({+ drawingId: "img1",+ source: "api/attachments/cgN4jEBCA1Kn/image/image.png",+ sheetTransform: {+ from: { row: 0, rowOffset: 25, column: 0, columnOffset: 50 },+ to: { row: 2, rowOffset: 0, column: 2, columnOffset: 0 }+ }+ }, { rowData: { "0": { h: 50 } }, columnData: { "0": { w: 100 } } }),+ { resolveImage: resolveAsPng }+ ));+ const sizedRange = sized.getWorksheet("Sheet1")?.getImages()[0]?.range;+ expect(sizedRange?.tl.col).toBeCloseTo(0.5);+ expect(sizedRange?.tl.row).toBeCloseTo(0.5);++ // With no per-track and no sheet default, the built-in 88px column / 24px row apply.+ const defaulted = await load(await renderSpreadsheetToXlsx(+ floatingImageWorkbook({+ drawingId: "img1",+ source: "api/attachments/cgN4jEBCA1Kn/image/image.png",+ sheetTransform: {+ from: { row: 0, rowOffset: 12, column: 0, columnOffset: 44 },+ to: { row: 2, rowOffset: 0, column: 2, columnOffset: 0 }+ }+ }, { defaultColumnWidth: undefined, defaultRowHeight: undefined }),+ { resolveImage: resolveAsPng }+ ));+ const defaultedRange = defaulted.getWorksheet("Sheet1")?.getImages()[0]?.range;+ expect(defaultedRange?.tl.col).toBeCloseTo(0.5);+ expect(defaultedRange?.tl.row).toBeCloseTo(0.5);+ });++ it("treats a missing anchor index or offset as zero", async () => {+ const wb = await load(await renderSpreadsheetToXlsx(+ floatingImageWorkbook({+ drawingId: "img1",+ source: "api/attachments/cgN4jEBCA1Kn/image/image.png",+ sheetTransform: { from: {}, to: { row: 2, column: 2 } }+ }),+ { resolveImage: resolveAsPng }+ ));+ const range = wb.getWorksheet("Sheet1")?.getImages()[0]?.range;+ expect(range?.tl.col).toBeCloseTo(0);+ expect(range?.tl.row).toBeCloseTo(0);+ });+it("skips a floating drawing that has no from/to anchor", async () => {const wb = await load(await renderSpreadsheetToXlsx(floatingImageWorkbook({diff --git a/packages/commons/src/lib/spreadsheet/workbook_model.spec.ts b/packages/commons/src/lib/spreadsheet/workbook_model.spec.tsnew file mode 100644index 0000000000..f870b1c085--- /dev/null+++ b/packages/commons/src/lib/spreadsheet/workbook_model.spec.ts@@ -0,0 +1,104 @@+import { describe, expect, it } from "vitest";++import {+ getDataValidations,+ getFloatingDrawings,+ type IWorkbookData,+ SHEET_DATA_VALIDATION_RESOURCE,+ SHEET_DRAWING_RESOURCE+} from "./workbook_model.js";++/** Minimal workbook carrying a single plugin resource, which is the only input these readers use. */+function workbookWithResource(name: string, data: string): IWorkbookData {+ return { sheetOrder: ["sheet1"], sheets: {}, resources: [{ name, data }] };+}++describe("getFloatingDrawings", () => {+ it("returns the sheet's drawings in their stored z-order", () => {+ const workbook = workbookWithResource(SHEET_DRAWING_RESOURCE, JSON.stringify({+ sheet1: {+ data: { d1: { drawingId: "d1" }, d2: { drawingId: "d2" } },+ order: ["d2", "d1"]+ }+ }));++ expect(getFloatingDrawings(workbook, "sheet1").map((d) => d.drawingId)).toEqual(["d2", "d1"]);+ });++ it("falls back to insertion order when `order` is missing or not an array", () => {+ // Univer omits `order` for workbooks that never reordered their drawings, and a+ // hand-edited or older payload can carry a non-array there; neither should lose images.+ const payload = { data: { d1: { drawingId: "d1" }, d2: { drawingId: "d2" } } };++ for (const order of [undefined, null, "d1,d2", {}]) {+ const workbook = workbookWithResource(SHEET_DRAWING_RESOURCE, JSON.stringify({+ sheet1: { ...payload, order }+ }));+ expect(getFloatingDrawings(workbook, "sheet1").map((d) => d.drawingId)).toEqual(["d1", "d2"]);+ }+ });++ it("drops ids in `order` that have no matching drawing", () => {+ const workbook = workbookWithResource(SHEET_DRAWING_RESOURCE, JSON.stringify({+ sheet1: { data: { d1: { drawingId: "d1" } }, order: ["missing", "d1"] }+ }));++ expect(getFloatingDrawings(workbook, "sheet1").map((d) => d.drawingId)).toEqual(["d1"]);+ });++ it("returns nothing when the resource is absent, empty, unparseable or has no data for the sheet", () => {+ const emptyWorkbook: IWorkbookData = { sheetOrder: ["sheet1"], sheets: {} };+ expect(getFloatingDrawings(emptyWorkbook, "sheet1")).toEqual([]);++ // A different plugin's resource, and a resource whose payload never got written.+ expect(getFloatingDrawings(workbookWithResource("SOME_OTHER_PLUGIN", "{}"), "sheet1")).toEqual([]);+ expect(getFloatingDrawings(workbookWithResource(SHEET_DRAWING_RESOURCE, ""), "sheet1")).toEqual([]);++ // Truncated/corrupt JSON must degrade to "no images" rather than break the whole render.+ expect(getFloatingDrawings(workbookWithResource(SHEET_DRAWING_RESOURCE, "{ not json"), "sheet1")).toEqual([]);++ // Valid JSON, but nothing for this sheet: absent entry, null root, and an entry with no `data`.+ expect(getFloatingDrawings(workbookWithResource(SHEET_DRAWING_RESOURCE, "{}"), "sheet1")).toEqual([]);+ expect(getFloatingDrawings(workbookWithResource(SHEET_DRAWING_RESOURCE, "null"), "sheet1")).toEqual([]);+ expect(getFloatingDrawings(+ workbookWithResource(SHEET_DRAWING_RESOURCE, JSON.stringify({ sheet1: { order: ["d1"] } })),+ "sheet1"+ )).toEqual([]);+ });+});++describe("getDataValidations", () => {+ it("returns the sheet's rules", () => {+ const rule = { uid: "v1", type: "list", formula1: '["a","b"]', ranges: [] };+ const workbook = workbookWithResource(SHEET_DATA_VALIDATION_RESOURCE, JSON.stringify({ sheet1: [rule] }));++ expect(getDataValidations(workbook, "sheet1")).toEqual([rule]);+ });++ it("drops empty entries within the rule list", () => {+ const rule = { uid: "v1", type: "whole", operator: "greaterThan", formula1: "0", ranges: [] };+ const workbook = workbookWithResource(+ SHEET_DATA_VALIDATION_RESOURCE,+ JSON.stringify({ sheet1: [null, rule, undefined] })+ );++ expect(getDataValidations(workbook, "sheet1")).toEqual([rule]);+ });++ it("returns nothing when the resource is absent, empty, unparseable or holds no rule list", () => {+ const emptyWorkbook: IWorkbookData = { sheetOrder: ["sheet1"], sheets: {} };+ expect(getDataValidations(emptyWorkbook, "sheet1")).toEqual([]);++ expect(getDataValidations(workbookWithResource("SOME_OTHER_PLUGIN", "{}"), "sheet1")).toEqual([]);+ expect(getDataValidations(workbookWithResource(SHEET_DATA_VALIDATION_RESOURCE, ""), "sheet1")).toEqual([]);+ expect(getDataValidations(workbookWithResource(SHEET_DATA_VALIDATION_RESOURCE, "{ not json"), "sheet1")).toEqual([]);++ // Valid JSON, but this sheet has no entry, the root is null, or the entry is not a list.+ expect(getDataValidations(workbookWithResource(SHEET_DATA_VALIDATION_RESOURCE, "{}"), "sheet1")).toEqual([]);+ expect(getDataValidations(workbookWithResource(SHEET_DATA_VALIDATION_RESOURCE, "null"), "sheet1")).toEqual([]);+ expect(getDataValidations(+ workbookWithResource(SHEET_DATA_VALIDATION_RESOURCE, JSON.stringify({ sheet1: { uid: "v1" } })),+ "sheet1"+ )).toEqual([]);+ });+});diff --git a/packages/commons/vite.config.ts b/packages/commons/vite.config.tsindex b693ce20bb..28572b1dbf 100644--- a/packages/commons/vite.config.ts+++ b/packages/commons/vite.config.ts@@ -16,6 +16,12 @@ export default defineConfig(() => ({["junit", { outputFile: "./test-output/vitest/junit.xml", addFileAttribute: true }]],'coverage': {+ 'thresholds': {+ 'lines': 100,+ 'functions': 100,+ 'branches': 100,+ 'statements': 100+ },'reportsDirectory': './test-output/vitest/coverage','provider': 'v8' as const,// Codecov resolves an lcov `SF:` path by matching it against the repo's file list, so