Skip to content

Commit d5649f1

Browse files
fix(web): prefer Office attachment filename formats for legacy MIME
1 parent 4d33862 commit d5649f1

3 files changed

Lines changed: 167 additions & 2 deletions

File tree

‎apps/web/src/components/files/AttachmentFilePreview.test.tsx‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
import { EnvironmentId } from "@t3tools/contracts";
22
import { act, type ReactNode } from "react";
33
import { create, type ReactTestRenderer } from "react-test-renderer";
4+
import * as XLSX from "xlsx";
45
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
56

67
import { AttachmentFilePreview } from "./AttachmentFilePreview";
8+
import {
9+
parseOfficeDocument,
10+
type OfficeWorkerRequest,
11+
type OfficeWorkerResponse,
12+
} from "./officeDocumentParser";
713

814
const { refresh } = vi.hoisted(() => ({ refresh: vi.fn<() => Promise<string | null>>() }));
915

@@ -16,6 +22,13 @@ vi.mock("~/components/ChatMarkdown", () => ({ default: () => null }));
1622
vi.mock("~/components/ui/scroll-area", () => ({
1723
ScrollArea: ({ children }: { children: ReactNode }) => children,
1824
}));
25+
vi.mock("~/components/ui/button", () => ({
26+
Button: ({
27+
variant: _variant,
28+
size: _size,
29+
...props
30+
}: React.ComponentProps<"button"> & { variant?: string; size?: string }) => <button {...props} />,
31+
}));
1932
vi.mock("./ReadOnlySourcePreview", () => ({
2033
default: ({ text }: { text: string }) => <pre>{text}</pre>,
2134
}));
@@ -130,4 +143,87 @@ describe("attachment HTML preview recovery", () => {
130143
expect(renderer.root.findAllByProps({ role: "alert" })).toHaveLength(0);
131144
expect(renderer.root.findByType("iframe").props.title).toBe("document.html");
132145
});
146+
147+
it("renders an actual xlsx attachment with the legacy Excel MIME as Unicode cells and cached formulas", async () => {
148+
await import("./OfficeDocumentPreview");
149+
const workbook = XLSX.utils.book_new();
150+
const sheet = XLSX.utils.aoa_to_sheet([
151+
["商品 🐈", "数量", "単価", "合計"],
152+
["りんご café", 12, 150, 1800],
153+
]);
154+
sheet.D2 = { t: "n", f: "B2*C2", v: 1800 };
155+
XLSX.utils.book_append_sheet(workbook, sheet, "売上");
156+
const file = new Blob(
157+
[XLSX.write(workbook, { type: "array", bookType: "xlsx", bookSST: true })],
158+
{ type: "application/vnd.ms-excel" },
159+
);
160+
let complete: (() => void) | undefined;
161+
const parsed = new Promise<void>((resolve) => {
162+
complete = resolve;
163+
});
164+
const terminate = vi.fn();
165+
const formats: string[] = [];
166+
vi.stubGlobal(
167+
"Worker",
168+
class extends EventTarget {
169+
terminate = terminate;
170+
constructor() {
171+
super();
172+
queueMicrotask(() =>
173+
this.dispatchEvent(
174+
new MessageEvent<OfficeWorkerResponse>("message", { data: { type: "ready" } }),
175+
),
176+
);
177+
}
178+
postMessage(request: OfficeWorkerRequest) {
179+
formats.push(request.format);
180+
let response: OfficeWorkerResponse;
181+
try {
182+
response = {
183+
id: request.id,
184+
ok: true,
185+
document: parseOfficeDocument(new Uint8Array(request.buffer), request.format),
186+
};
187+
} catch (error) {
188+
response = {
189+
id: request.id,
190+
ok: false,
191+
error: error instanceof Error ? error.message : "Could not parse workbook",
192+
};
193+
}
194+
this.dispatchEvent(new MessageEvent<OfficeWorkerResponse>("message", { data: response }));
195+
complete?.();
196+
}
197+
},
198+
);
199+
await act(async () => {
200+
renderer = create(
201+
<AttachmentFilePreview
202+
name="report.xlsx"
203+
mimeType={file.type}
204+
sizeBytes={file.size}
205+
file={file}
206+
/>,
207+
);
208+
});
209+
await parsed;
210+
await act(async () => {});
211+
expect(formats).toEqual(["xlsx"]);
212+
expect(renderer.root.findByType("table").props["aria-label"]).toBe("売上 cell values");
213+
expect(renderer.root.findAllByType("td").map((cell) => cell.children.join(""))).toEqual([
214+
"商品 🐈",
215+
"数量",
216+
"単価",
217+
"合計",
218+
"りんご café",
219+
"12",
220+
"150",
221+
"1800",
222+
]);
223+
expect(renderer.root.findAllByProps({ role: "alert" })).toHaveLength(0);
224+
expect(renderer.root.findAllByType("pre")).toHaveLength(0);
225+
expect(fetch).not.toHaveBeenCalled();
226+
expect(refresh).not.toHaveBeenCalled();
227+
expect(terminate).toHaveBeenCalledOnce();
228+
});
133229
});

‎packages/shared/src/filePreview.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,70 @@ import {
1616
} from "./filePreview.ts";
1717

1818
describe("bounded web Office previews", () => {
19+
it.each([
20+
{
21+
name: "report.xlsx",
22+
mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
23+
expected: "xlsx",
24+
},
25+
{ name: "report.xlsx", mimeType: "application/vnd.ms-excel", expected: "xlsx" },
26+
{ name: "report.xls", mimeType: "application/vnd.ms-excel", expected: "xls" },
27+
{
28+
name: "report.xls",
29+
mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
30+
expected: "xls",
31+
},
32+
{
33+
name: "slides.pptx",
34+
mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
35+
expected: "pptx",
36+
},
37+
{ name: "slides.pptx", mimeType: "application/vnd.ms-powerpoint", expected: "pptx" },
38+
{
39+
name: "report.xlsx",
40+
mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
41+
expected: "xlsx",
42+
},
43+
{ name: "slides.pptx", mimeType: "application/vnd.ms-excel", expected: "pptx" },
44+
{ name: "REPORT.XlSx", mimeType: " Application/Vnd.Ms-Excel ; version=1 ", expected: "xlsx" },
45+
{
46+
name: "REPORT.XLS",
47+
mimeType:
48+
" APPLICATION/VND.OPENXMLFORMATS-OFFICEDOCUMENT.SPREADSHEETML.SHEET; charset=binary",
49+
expected: "xls",
50+
},
51+
{
52+
name: "SLIDES.PpTx",
53+
mimeType: " APPLICATION/VND.MS-POWERPOINT ; version=1",
54+
expected: "pptx",
55+
},
56+
])(
57+
"selects the supported filename format for $name with Office MIME $mimeType",
58+
({ name, mimeType, expected }: { name: string; mimeType: string; expected: string }) => {
59+
expect(officePreviewFormat({ name, mimeType })).toBe(expected);
60+
expect(filePreviewKind({ name, mimeType })).toBe("unsupported");
61+
},
62+
);
63+
64+
it.each([
65+
{ name: "report.xlsx", mimeType: "image/png" },
66+
{ name: "report.xls", mimeType: "application/zip" },
67+
{ name: "slides.pptx", mimeType: "text/html" },
68+
{ name: "report.xlsx", mimeType: " Application/PDF ; version=1" },
69+
])(
70+
"preserves a non-Office content type conflict for $name ($mimeType)",
71+
({ name, mimeType }: { name: string; mimeType: string }) => {
72+
expect(officePreviewFormat({ name, mimeType })).toBeNull();
73+
},
74+
);
75+
76+
it.each(["legacy.ppt", "download"])(
77+
"keeps legacy PowerPoint MIME unsupported for $name",
78+
(name: string) => {
79+
expect(officePreviewFormat({ name, mimeType: "application/vnd.ms-powerpoint" })).toBeNull();
80+
},
81+
);
82+
1983
it.each(["xlsx", "xls", "pptx"] as const)(
2084
"recognizes %s without changing native fallback",
2185
(format) => {

‎packages/shared/src/filePreview.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,12 +87,17 @@ export function officePreviewFormat(file: {
8787
}): OfficePreviewFormat | null {
8888
const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
8989
const generic = !mime || mime === "application/octet-stream" || mime === "text/plain";
90+
const office =
91+
mime === "application/vnd.ms-powerpoint" ||
92+
Object.values(OFFICE_PREVIEW_MIME_TYPES).some((type) => mime === type);
93+
let mimeFormat: OfficePreviewFormat | null = null;
9094
for (const [extension, expectedMime] of Object.entries(OFFICE_PREVIEW_MIME_TYPES)) {
91-
if (mime === expectedMime || (generic && file.name.toLowerCase().endsWith(extension))) {
95+
if ((generic || office) && file.name.toLowerCase().endsWith(extension)) {
9296
return extension.slice(1) as OfficePreviewFormat;
9397
}
98+
if (mime === expectedMime) mimeFormat = extension.slice(1) as OfficePreviewFormat;
9499
}
95-
return null;
100+
return mimeFormat;
96101
}
97102

98103
export function officePreviewMimeTypeFromExtension(extension: string): string | null {

0 commit comments

Comments
 (0)