Skip to content

Build your personal knowledge base with Trilium Notes

test(office): cover the preview widgets, service guards and buffer polyfill

Elian Doran4178f143c608
diff --git a/apps/client/src/widgets/type_widgets/File.spec.tsx b/apps/client/src/widgets/type_widgets/File.spec.tsx
index 8fb8f621df..486cead826 100644
--- a/apps/client/src/widgets/type_widgets/File.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/File.spec.tsx
@@ -18,6 +18,7 @@ vi.mock("../react/ActionButton", () => ({ default: () => <button class="code-blo
// the module graph; the markers let FileTypeWidget's mime routing be asserted without rendering them.
vi.mock("../react/hooks", () => ({ useNoteBlob: vi.fn(() => null) }));
vi.mock("./file/MediaPreview", () => ({ default: () => <div class="media-preview-stub" /> }));
+vi.mock("./file/Office", () => ({ default: () => <div class="office-preview-stub" /> }));
vi.mock("./file/Pdf", () => ({ default: () => <div class="pdf-preview-stub" /> }));
const { useNoteBlob } = await import("../react/hooks");
@@ -72,6 +73,25 @@ describe("FileTypeWidget", () => {
expect(container.querySelector(".media-preview-stub")).toBeNull();
expect(container.querySelector(".alert")).not.toBeNull();
});
+
+ it("routes office documents to OfficePreview without fetching the blob", () => {
+ vi.mocked(useNoteBlob).mockReturnValue(null);
+
+ mount("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
+ expect(container.querySelector(".office-preview-stub")).not.toBeNull();
+ // The preview is server-rendered — fetching the blob would download the file twice.
+ expect(vi.mocked(useNoteBlob).mock.calls[0][0]).toBeNull();
+ });
+
+ it("prefers OfficePreview over the text branch for RTF, whose blob content is a string", () => {
+ // text/rtf arrives as string content; without the office check running first it
+ // would fall into the blob.content branch and render as raw markup.
+ vi.mocked(useNoteBlob).mockReturnValue({ content: "{\\rtf1 raw}" } as ReturnType<typeof useNoteBlob>);
+
+ mount("text/rtf");
+ expect(container.querySelector(".office-preview-stub")).not.toBeNull();
+ expect(container.querySelector("pre.file-preview-content")).toBeNull();
+ });
});
describe("TextPreview", () => {
diff --git a/apps/client/src/widgets/type_widgets/file/Office.spec.tsx b/apps/client/src/widgets/type_widgets/file/Office.spec.tsx
new file mode 100644
index 0000000000..a00564a46b
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/Office.spec.tsx
@@ -0,0 +1,87 @@
+import { render } from "preact";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const renderOfficeToHtml = vi.fn<(entityType: string, entityId: string) => Promise<string>>();
+
+vi.mock("../../../services/office_renderer", () => ({
+ renderOfficeToHtml: (...args: [string, string]) => renderOfficeToHtml(...args)
+}));
+
+const { default: OfficePreview } = await import("./Office");
+
+type OfficeNote = Parameters<typeof OfficePreview>[0]["note"];
+
+let container: HTMLDivElement;
+
+beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+});
+
+afterEach(() => {
+ render(null, container);
+ container.remove();
+ vi.clearAllMocks();
+});
+
+function mount(noteId = "office1", blobId = "blob1") {
+ const note = { noteId, blobId } as unknown as OfficeNote;
+ render(<OfficePreview note={note} />, container);
+}
+
+describe("OfficePreview", () => {
+ it("shows the loading state, then the sanitized server-rendered HTML for the note", async () => {
+ let resolve: (html: string) => void = () => {};
+ renderOfficeToHtml.mockReturnValue(new Promise((r) => { resolve = r; }));
+
+ mount("note42");
+ // While the conversion is in flight, only the loading placeholder is shown.
+ expect(container.querySelector(".office-preview-loading")).not.toBeNull();
+ expect(container.querySelector(".office-preview-body")).toBeNull();
+ // Effects run after the render tick, so the fetch is observed asynchronously.
+ await vi.waitFor(() => expect(renderOfficeToHtml).toHaveBeenCalledWith("notes", "note42"));
+
+ resolve('<p class="converted-doc">Hello</p>');
+ await vi.waitFor(() => expect(container.querySelector(".converted-doc")?.textContent).toBe("Hello"));
+
+ const body = container.querySelector(".office-preview-body");
+ // The preview body opts into text selection (the app disables it globally).
+ expect(body?.classList.contains("selectable-text")).toBe(true);
+ expect(container.querySelector(".office-preview-loading")).toBeNull();
+ });
+
+ it("falls back to the not-available notice when the conversion fails", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ renderOfficeToHtml.mockRejectedValue(new Error("conversion exploded"));
+
+ mount();
+ await vi.waitFor(() => expect(container.querySelector(".file-preview-not-available")).not.toBeNull());
+ expect(container.querySelector(".office-preview-body")).toBeNull();
+ });
+
+ it("re-fetches when the note's content (blobId) changes", async () => {
+ renderOfficeToHtml.mockResolvedValue("<p>v1</p>");
+ mount("note1", "blobA");
+ await vi.waitFor(() => expect(container.querySelector(".office-preview-body")).not.toBeNull());
+
+ renderOfficeToHtml.mockResolvedValue('<p class="v2">v2</p>');
+ mount("note1", "blobB");
+ await vi.waitFor(() => expect(container.querySelector(".v2")).not.toBeNull());
+ expect(renderOfficeToHtml).toHaveBeenCalledTimes(2);
+ });
+
+ it("discards a conversion that resolves after unmount without touching the DOM", async () => {
+ let resolve: (html: string) => void = () => {};
+ renderOfficeToHtml.mockReturnValue(new Promise((r) => { resolve = r; }));
+
+ mount();
+ // Wait for the effect to start the fetch before unmounting, so the cleanup
+ // path (not a never-started effect) is what's exercised.
+ await vi.waitFor(() => expect(renderOfficeToHtml).toHaveBeenCalled());
+ render(null, container);
+ resolve("<p>too late</p>");
+ // Let the microtask run; the cancelled effect must not re-render into the container.
+ await Promise.resolve();
+ expect(container.innerHTML).toBe("");
+ });
+});
diff --git a/apps/standalone/src/office_preview.spec.ts b/apps/standalone/src/office_preview.spec.ts
index f0156ee580..15807c24ee 100644
--- a/apps/standalone/src/office_preview.spec.ts
+++ b/apps/standalone/src/office_preview.spec.ts
@@ -29,11 +29,43 @@ describe("office preview with aliased officeparser", () => {
});
});
+describe("convertOfficeToHtml guards", () => {
+ it("rejects a non-office MIME type", async () => {
+ await expect(convertOfficeToHtml(new Uint8Array([1]), "application/pdf"))
+ .rejects.toThrow(/not a supported office format/);
+ });
+
+ it("refuses a document above the preview size cap", async () => {
+ const oversized = new Uint8Array(20 * 1024 * 1024 + 1);
+
+ await expect(convertOfficeToHtml(oversized, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
+ .rejects.toThrow(/too large/);
+ });
+
+ it("rejects a buffer that neither the spreadsheet pipeline nor officeparser can read", async () => {
+ // Garbage with an XLSX MIME exercises the exceljs -> officeparser fallback; since the
+ // bytes are not any known format, the officeparser attempt then fails too.
+ const garbage = new Uint8Array([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]);
+
+ await expect(convertOfficeToHtml(garbage, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
+ .rejects.toThrow();
+ });
+});
+
function readFixture(name: string): Uint8Array {
- // Vitest serves transformed modules from Vite's virtual /@fs/ root — strip it
- // to get a real filesystem path (no-op when the prefix is absent).
- const path = fileURLToPath(new URL(`../../server/src/services/ocr/processors/samples/${name}`, import.meta.url))
- .replace(/^[/\\]@fs/, "");
+ // Vitest serves transformed modules from Vite's virtual /@fs/ root — strip it to get
+ // a real filesystem path (no-op when the marker is absent). On Windows the marker
+ // lands mid-path (`C:\@fs\C:\Users\…`) rather than at the start, so everything up to
+ // and including it is dropped; POSIX paths lose their leading slash in that cut and
+ // get it restored.
+ let path = fileURLToPath(new URL(`../../server/src/services/ocr/processors/samples/${name}`, import.meta.url));
+ const marker = path.match(/[/\\]@fs[/\\]/);
+ if (marker?.index !== undefined) {
+ path = path.slice(marker.index + marker[0].length);
+ if (!/^[A-Za-z]:/.test(path)) {
+ path = `/${path}`;
+ }
+ }
return new Uint8Array(readFileSync(path));
}
diff --git a/apps/standalone/src/stubs/buffer_polyfill.spec.ts b/apps/standalone/src/stubs/buffer_polyfill.spec.ts
new file mode 100644
index 0000000000..379a06f018
--- /dev/null
+++ b/apps/standalone/src/stubs/buffer_polyfill.spec.ts
@@ -0,0 +1,38 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * The polyfill installs the npm `buffer` implementation as the global Buffer, but only
+ * when the environment doesn't already provide one (in the browser it must; under the
+ * node-driven test runner a native Buffer already exists). The module runs its check at
+ * import time, so each case re-imports it with a fresh module registry.
+ */
+describe("buffer_polyfill", () => {
+ const globalWithBuffer = globalThis as { Buffer?: unknown };
+ const nativeBuffer = globalWithBuffer.Buffer;
+
+ afterEach(() => {
+ globalWithBuffer.Buffer = nativeBuffer;
+ vi.resetModules();
+ });
+
+ it("installs the npm buffer polyfill when the global is missing", async () => {
+ delete globalWithBuffer.Buffer;
+
+ await import("./buffer_polyfill.js");
+
+ expect(globalWithBuffer.Buffer).toBeDefined();
+ expect(globalWithBuffer.Buffer).not.toBe(nativeBuffer);
+ // It behaves like Buffer: officeparser round-trips content through from().
+ const polyfill = globalWithBuffer.Buffer as { from(s: string): { toString(): string } };
+ expect(polyfill.from("office").toString()).toBe("office");
+ });
+
+ it("leaves an existing global Buffer untouched", async () => {
+ const sentinel = { marker: true };
+ globalWithBuffer.Buffer = sentinel;
+
+ await import("./buffer_polyfill.js");
+
+ expect(globalWithBuffer.Buffer).toBe(sentinel);
+ });
+});
diff --git a/packages/trilium-core/src/services/office_preview.ts b/packages/trilium-core/src/services/office_preview.ts
index 9e694ab052..4419ab61a0 100644
--- a/packages/trilium-core/src/services/office_preview.ts
+++ b/packages/trilium-core/src/services/office_preview.ts
@@ -60,7 +60,9 @@ export async function convertOfficeToHtml(content: string | Uint8Array, mime: st
}
});
- // value is a string for the 'html' destination.
+ // Defensive: officeparser types `value` as string for the 'html' destination, so the
+ // fallback arm is unreachable unless the library breaks its own contract.
+ /* v8 ignore next */
return typeof value === "string" ? value : "";
}