Skip to content

Build your personal knowledge base with Trilium Notes

fix(office): send the preview fragment as the body instead of a JSON envelope

Elian Doran297c0f4a8ce6
diff --git a/apps/client/src/services/office_renderer.spec.ts b/apps/client/src/services/office_renderer.spec.ts
index 1026ae9a39..91a101aac4 100644
--- a/apps/client/src/services/office_renderer.spec.ts
+++ b/apps/client/src/services/office_renderer.spec.ts
@@ -1,8 +1,10 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
// --- Mock collaborators before importing the SUT. ---
-const serverGet = vi.fn(async (_url: string) => ({ html: "<h1>Doc</h1>" }));
-vi.mock("./server.js", () => ({ default: { get: (url: string) => serverGet(url) } }));
+const serverGet = vi.fn(async (_url: string, _componentId?: string, _raw?: boolean) => "<h1>Doc</h1>");
+vi.mock("./server.js", () => ({
+ default: { get: (url: string, componentId?: string, raw?: boolean) => serverGet(url, componentId, raw) }
+}));
const sanitizeNoteContentHtml = vi.fn((s: string) => `SANITIZED:${s}`);
vi.mock("./sanitize_content.js", () => ({ sanitizeNoteContentHtml: (s: string) => sanitizeNoteContentHtml(s) }));
@@ -15,22 +17,22 @@ describe("renderOfficeToHtml", () => {
it("fetches the server-rendered note preview and returns sanitized output", async () => {
const html = await renderOfficeToHtml("notes", "n1");
- expect(serverGet).toHaveBeenCalledWith("notes/n1/office-preview");
+ expect(serverGet).toHaveBeenCalledWith("notes/n1/office-preview", undefined, true);
expect(sanitizeNoteContentHtml).toHaveBeenCalledWith("<h1>Doc</h1>");
expect(html).toBe("SANITIZED:<h1>Doc</h1>");
});
it("builds the attachment URL variant", async () => {
await renderOfficeToHtml("attachments", "a9");
- expect(serverGet).toHaveBeenCalledWith("attachments/a9/office-preview");
+ expect(serverGet).toHaveBeenCalledWith("attachments/a9/office-preview", undefined, true);
});
it("strips default hyperlink colors so the theme's link color applies, keeping other styling", async () => {
- serverGet.mockResolvedValueOnce({
- html: '<p><a href="https://example.com"><span style="color: #000080; font-family: Arial"><u>x</u></span></a>'
+ serverGet.mockResolvedValueOnce(
+ '<p><a href="https://example.com"><span style="color: #000080; font-family: Arial"><u>x</u></span></a>'
+ '<a href="#b" style="color: #0563C1">y</a>'
+ '<span style="color: #000080">keep</span></p>'
- });
+ );
const html = await renderOfficeToHtml("notes", "n1");
@@ -46,9 +48,9 @@ describe("renderOfficeToHtml", () => {
});
it("keeps a link color the author chose, as text notes do", async () => {
- serverGet.mockResolvedValueOnce({
- html: '<p><a href="https://triliumnotes.org/"><span style="color:#ea7500;">Trilium</span></a></p>'
- });
+ serverGet.mockResolvedValueOnce(
+ '<p><a href="https://triliumnotes.org/"><span style="color:#ea7500;">Trilium</span></a></p>'
+ );
const html = await renderOfficeToHtml("notes", "n1");
diff --git a/apps/client/src/services/office_renderer.ts b/apps/client/src/services/office_renderer.ts
index 302eee8850..83e995fa92 100644
--- a/apps/client/src/services/office_renderer.ts
+++ b/apps/client/src/services/office_renderer.ts
@@ -6,11 +6,15 @@ import server from "./server.js";
* ODT/ODS/ODP, RTF and EPUB) and sanitizes it before it ever touches the DOM. The conversion
* itself happens server-side (officeparser) via the office-preview route.
*
+ * The route sends the fragment as the response body, so it is fetched as text rather than
+ * through a JSON envelope.
+ *
* Throws if the document is too large, unsupported, or conversion fails — callers should
* catch and fall back to the usual download / open-externally affordance.
*/
export async function renderOfficeToHtml(entityType: "notes" | "attachments", entityId: string): Promise<string> {
- const { html } = await server.get<{ html: string }>(`${entityType}/${entityId}/office-preview`);
+ // `raw` keeps the response a plain string; the route sends the fragment as the body.
+ const html = await server.get<string>(`${entityType}/${entityId}/office-preview`, undefined, true);
return stripLinkColors(sanitizeNoteContentHtml(html));
}
diff --git a/apps/standalone/src/lightweight/browser_router.spec.ts b/apps/standalone/src/lightweight/browser_router.spec.ts
index 09b0c8fd0a..6dd91342aa 100644
--- a/apps/standalone/src/lightweight/browser_router.spec.ts
+++ b/apps/standalone/src/lightweight/browser_router.spec.ts
@@ -171,6 +171,24 @@ describe("BrowserRouter result formatting", () => {
expect(JSON.parse(decodeBody(res.body))).toEqual({ id: "x" });
});
+ it("sends a string result as-is, so an HTML fragment is not JSON-escaped", async () => {
+ const router = new BrowserRouter();
+ router.get("/preview", () => "<table><td>a</td></table>");
+ const res = await router.dispatch("GET", "http://localhost/preview");
+ expect(res.status).toBe(200);
+ expect(res.headers["content-type"]).toContain("text/html");
+ expect(decodeBody(res.body)).toBe("<table><td>a</td></table>");
+ });
+
+ it("sends an error tuple's string as plain text, not a JSON-quoted copy", async () => {
+ const router = new BrowserRouter();
+ router.get("/bad", () => [400, "Description must be a string."]);
+ const res = await router.dispatch("GET", "http://localhost/bad");
+ expect(res.status).toBe(400);
+ expect(res.headers["content-type"]).toContain("text/plain");
+ expect(decodeBody(res.body)).toBe("Description must be a string.");
+ });
+
it("serializes a plain object as a 200 JSON response", async () => {
const router = new BrowserRouter();
router.get("/obj", () => ({ ok: true }));
diff --git a/apps/standalone/src/lightweight/browser_router.ts b/apps/standalone/src/lightweight/browser_router.ts
index 0b1396de33..8a24dee3ed 100644
--- a/apps/standalone/src/lightweight/browser_router.ts
+++ b/apps/standalone/src/lightweight/browser_router.ts
@@ -110,6 +110,21 @@ function textResponse(text: string, status = 200, extraHeaders: Record<string, s
};
}
+/**
+ * Builds the response for a handler's return value, mirroring the server's `send`: a string
+ * body goes out as-is (the office preview answers with an HTML fragment, which an envelope
+ * would escape), anything else is JSON. An error keeps text/plain so the client reads the
+ * message rather than a JSON-quoted copy of it.
+ */
+function sendResult(response: unknown, status: number): BrowserResponse {
+ if (typeof response === "string") {
+ return status >= 400
+ ? textResponse(response, status)
+ : textResponse(response, status, { "content-type": "text/html; charset=utf-8" });
+ }
+ return jsonResponse(response, status);
+}
+
/**
* Browser router class that handles route registration and dispatching.
*/
@@ -274,7 +289,7 @@ export class BrowserRouter {
// Handle [statusCode, response] format
if (Array.isArray(result) && result.length > 0 && Number.isInteger(result[0])) {
const [statusCode, response] = result;
- return jsonResponse(response, statusCode);
+ return sendResult(response, statusCode);
}
// Handle undefined (no content) - 204 should have no body
@@ -286,8 +301,7 @@ export class BrowserRouter {
};
}
- // Default: JSON response with 200
- return jsonResponse(result, 200);
+ return sendResult(result, 200);
}
/**
diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.ts
index 02c467c598..4323a956ac 100644
--- a/packages/trilium-core/src/routes/api/files.spec.ts
+++ b/packages/trilium-core/src/routes/api/files.spec.ts
@@ -361,12 +361,12 @@ describe("Files API (core)", () => {
it("converts an RTF file note to an embeddable HTML fragment", async () => {
const noteId = await createRtfNote();
- const res = await api.get<{ html: string }>(`/api/notes/${noteId}/office-preview`);
+ const res = await api.get<string>(`/api/notes/${noteId}/office-preview`);
expect(res.status).toBe(200);
- expect(res.body.html).toContain("Hello");
- expect(res.body.html).toContain("World");
+ expect(res.body).toContain("Hello");
+ expect(res.body).toContain("World");
// fragment mode — no full standalone document wrapper
- expect(res.body.html).not.toContain("<html");
+ expect(res.body).not.toContain("<html");
});
it("converts an RTF attachment to an embeddable HTML fragment", async () => {
@@ -377,9 +377,9 @@ describe("Files API (core)", () => {
expect(save.status).toBe(204);
const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
- const res = await api.get<{ html: string }>(`/api/attachments/${list.body[0].attachmentId}/office-preview`);
+ const res = await api.get<string>(`/api/attachments/${list.body[0].attachmentId}/office-preview`);
expect(res.status).toBe(200);
- expect(res.body.html).toContain("Hello");
+ expect(res.body).toContain("Hello");
});
it("rejects an unsupported MIME type with 400", async () => {
@@ -407,16 +407,16 @@ describe("Files API (core)", () => {
const noteId = await createXlsxNote(xlsxBuffer);
- const res = await api.get<{ html: string }>(`/api/notes/${noteId}/office-preview`);
+ const res = await api.get<string>(`/api/notes/${noteId}/office-preview`);
expect(res.status).toBe(200);
- expect(res.body.html).toContain("Merged header");
+ expect(res.body).toContain("Merged header");
// Native-renderer features officeparser's grid lacks: merged cells,
// number formatting (numfmt) and inline borders...
- expect(res.body.html).toContain('colspan="2"');
- expect(res.body.html).toContain("1,234.50");
- expect(res.body.html).toContain("border");
+ expect(res.body).toContain('colspan="2"');
+ expect(res.body).toContain("1,234.50");
+ expect(res.body).toContain("border");
// ...and none of officeparser's class-styled A/B/C header chrome.
- expect(res.body.html).not.toContain("excel-col-header");
+ expect(res.body).not.toContain("excel-col-header");
});
});
});
diff --git a/packages/trilium-core/src/routes/api/files.ts b/packages/trilium-core/src/routes/api/files.ts
index 8ecd187d5c..7565b8e70c 100644
--- a/packages/trilium-core/src/routes/api/files.ts
+++ b/packages/trilium-core/src/routes/api/files.ts
@@ -101,17 +101,21 @@ function updateAttachment(req: FileRequest<{ attachmentId: string }>) {
* Converts an office document note/attachment to an embeddable HTML fragment for the
* inline preview shown by the client. The returned HTML is unsanitized — the client
* sanitizes it before injecting it into the DOM.
+ *
+ * The fragment is sent as the response body rather than wrapped in a JSON object: a
+ * spreadsheet preview runs to megabytes, and an envelope would escape every attribute
+ * quote and make the client parse the whole document before it can use it.
*/
async function getNoteOfficePreview(req: Request<{ noteId: string }>) {
const note = becca.getNoteOrThrow(req.params.noteId);
- return { html: await convertOfficeToHtml(note.getContent(), note.mime) };
+ return await convertOfficeToHtml(note.getContent(), note.mime);
}
async function getAttachmentOfficePreview(req: Request<{ attachmentId: string }>) {
const attachment = becca.getAttachmentOrThrow(req.params.attachmentId);
- return { html: await convertOfficeToHtml(attachment.getContent(), attachment.mime) };
+ return await convertOfficeToHtml(attachment.getContent(), attachment.mime);
}
function openPartialInt(noteOrAttachment: BNote | BAttachment, req: Request, res: Response) {