The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 22:15 UTC
fix(web): improve Excel spreadsheet previews (#34429)
Yash Singh committed
Nov 11, 2026 at 14:18 UTC
c8e8b58ee6f570a1a3f538e615aa800c406d73f4
14 files changed
+534
-113
apps/web/package.json
+1
-1
@@ -17,7 +17,7 @@
17
"@betteroffice/fonts": "0.4.0",
18
"@betteroffice/fonts-cjk": "0.4.0",
19
"@betteroffice/pptx": "0.2.0",
20
- "@betteroffice/xlsx": "0.3.0",
20
+ "@betteroffice/xlsx": "0.5.1",
21
"@clerk/clerk-js": "catalog:",
22
"@clerk/electron": "catalog:",
23
"@clerk/react": "catalog:",
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+149
-67
@@ -1039,71 +1039,90 @@ it.each(["utf-16le", "utf-16be", "windows-1252"])(
1039
);
1040
1041
it.each([
1042
- ["", "worksheets/./sheet1.xml", false],
1043
- ["x:", "../xl/worksheets/sheet1.xml", false],
1044
- ["", "/xl/worksheets/sheet1.xml", true],
1045
-])("preserves %sworksheet metadata with relationship target %s", async (prefix, target, empty) => {
1046
- const { default: JSZip } = await import("jszip");
1047
- const archive = new JSZip();
1048
- const ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
1049
- archive.file(
1050
- "xl/workbook.xml",
1051
- '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet" sheetId="1" r:id="s"/></sheets></workbook>',
1052
- );
1053
- archive.file(
1054
- "xl/_rels/workbook.xml.rels",
1055
- `<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${target}"/></Relationships>`,
1056
- );
1057
- archive.file(
1058
- "xl/worksheets/sheet1.xml",
1059
- `<${prefix}worksheet xmlns${prefix ? ":x" : ""}="${ns}"><${prefix}dimension ref="XFD1048576"/><${prefix}cols><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS - 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 10}" width="20"/><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS + 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 30}" hidden="1"/></${prefix}cols><${prefix}sheetData><${prefix}row ht="42" customHeight="1" hidden="1"><${prefix}c r="A50" t="inlineStr"><${prefix}is><${prefix}t>${"value".repeat(1000)}</${prefix}t></${prefix}is></${prefix}c></${prefix}row></${prefix}sheetData><${prefix}mergeCells><${prefix}mergeCell ref="XFD1048576"/></${prefix}mergeCells></${prefix}worksheet>`
1060
- .replace(/<((?:x:)?(?:col|dimension|mergeCell))\b([^>]*)\/>/g, prefix ? "<$1$2></$1>" : "$&")
1061
- .replace(/<sheetData>[\s\S]*?<\/sheetData>/, (data) => (empty ? "<sheetData/>" : data))
1062
- .replace(/="([^"]*)"/g, (attribute, value: string) =>
1063
- prefix || empty
1064
- ? ` = '${value.replace(/\d/g, (digit) => `&#${digit.charCodeAt(0)};`)}'`
1065
- : attribute,
1066
- ),
1067
- );
1068
- const bytes = await archive.generateAsync({ type: "arraybuffer" });
1069
- const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
1070
- type: "module",
1071
- });
1072
- try {
1073
- const result = await new Promise<OfficeWorkerResult>((resolve) => {
1074
- worker.addEventListener(
1075
- "message",
1076
- (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
1077
- { once: true },
1078
- );
1079
- worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
1080
- });
1081
- expect(result.type).toBe("xlsx");
1082
- if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
1083
- const bounded = await JSZip.loadAsync(result.bytes);
1084
- const sheet = new DOMParser().parseFromString(
1085
- await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
1086
- "application/xml",
1042
+ ["", "worksheets/./sheet1.xml", false, false],
1043
+ ["x:", "../xl/worksheets/sheet1.xml", false, false],
1044
+ ["", "/xl/worksheets/sheet1.xml", true, false],
1045
+ ["", "worksheets/sheet1.xml", false, true],
1046
+ ["", "worksheets/sheet1.xml", true, true],
1047
+])(
1048
+ "preserves %sworksheet metadata with relationship target %s",
1049
+ async (prefix, target, empty, localPrefix) => {
1050
+ const { default: JSZip } = await import("jszip");
1051
+ const archive = new JSZip();
1052
+ const ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
1053
+ archive.file(
1054
+ "xl/workbook.xml",
1055
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Chart" sheetId="2" r:id="c"/><sheet name="Sheet" sheetId="1" r:id="s"/></sheets></workbook>',
1056
);
1088
- expect(sheet.querySelector("parsererror")).toBeNull();
1089
- const row = sheet.getElementsByTagNameNS(ns, "row")[0];
1090
- if (empty) expect(row).toBeUndefined();
1091
- else {
1092
- expect(row!.getAttribute("ht")).toBe("42");
1093
- expect(row!.getAttribute("hidden")).toBe("1");
1094
- expect(row!.getElementsByTagNameNS(ns, "c")[0]!.getAttribute("r")).toBe("A50");
1095
- expect(row!.getElementsByTagNameNS(ns, "t")[0]!.textContent).toHaveLength(4096);
1057
+ archive.file(
1058
+ "xl/_rels/workbook.xml.rels",
1059
+ `<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${target}"/><Relationship Id="c" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="chartsheets/sheet1.xml"/></Relationships>`,
1060
+ );
1061
+ archive.file(
1062
+ "xl/worksheets/sheet1.xml",
1063
+ `<${prefix}worksheet xmlns${prefix ? ":x" : ""}="${ns}"><${prefix}dimension ref="XFD1048576"/><${prefix}sheetViews><${prefix}sheetView showGridLines="0"/></${prefix}sheetViews><${prefix}sheetFormatPr defaultColWidth="30"/><${prefix}cols><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS - 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 10}" width="20"/><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS + 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 30}" hidden="1"/></${prefix}cols><${prefix}sheetData><${prefix}row ht="42" customHeight="1" hidden="1"><${prefix}c r="A50" t="inlineStr"><${prefix}is><${prefix}t>${"value".repeat(1000)}</${prefix}t></${prefix}is></${prefix}c></${prefix}row></${prefix}sheetData><${prefix}mergeCells><${prefix}mergeCell ref="XFD1048576"/></${prefix}mergeCells></${prefix}worksheet>`
1064
+ .replace(
1065
+ /<((?:x:)?(?:col|dimension|mergeCell))\b([^>]*)\/>/g,
1066
+ prefix ? "<$1$2></$1>" : "$&",
1067
+ )
1068
+ .replace(/<sheetData>[\s\S]*?<\/sheetData>/, (data) => (empty ? "<sheetData/>" : data))
1069
+ .replace(/<(\/?)sheetData\b/g, (tag, closing: string) =>
1070
+ localPrefix ? `<${closing}x:sheetData${closing ? "" : ` xmlns:x="${ns}"`}` : tag,
1071
+ )
1072
+ .replace(/="([^"]*)"/g, (attribute, value: string) =>
1073
+ prefix || empty
1074
+ ? ` = '${value.replace(/\d/g, (digit) => `&#${digit.charCodeAt(0)};`)}'`
1075
+ : attribute,
1076
+ ),
1077
+ );
1078
+ const bytes = await archive.generateAsync({ type: "arraybuffer" });
1079
+ const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
1080
+ type: "module",
1081
+ });
1082
+ try {
1083
+ const result = await new Promise<OfficeWorkerResult>((resolve) => {
1084
+ worker.addEventListener(
1085
+ "message",
1086
+ (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
1087
+ { once: true },
1088
+ );
1089
+ worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
1090
+ });
1091
+ expect(result.type).toBe("xlsx");
1092
+ if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
1093
+ // The engine counts the chart sheet before it.
1094
+ expect(result.view?.hiddenGridlines).toEqual([1]);
1095
+ const bounded = await JSZip.loadAsync(result.bytes);
1096
+ const sheet = new DOMParser().parseFromString(
1097
+ await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
1098
+ "application/xml",
1099
+ );
1100
+ expect(sheet.querySelector("parsererror")).toBeNull();
1101
+ const row = sheet.getElementsByTagNameNS(ns, "row")[0];
1102
+ if (empty) expect(row).toBeUndefined();
1103
+ else {
1104
+ expect(row!.getAttribute("ht")).toBe("42");
1105
+ expect(row!.getAttribute("hidden")).toBe("1");
1106
+ expect(row!.getElementsByTagNameNS(ns, "c")[0]!.getAttribute("r")).toBe("A50");
1107
+ expect(row!.getElementsByTagNameNS(ns, "t")[0]!.textContent).toHaveLength(4096);
1108
+ }
1109
+ expect(sheet.getElementsByTagNameNS(ns, "dimension")).toHaveLength(0);
1110
+ expect(sheet.getElementsByTagNameNS(ns, "mergeCell")).toHaveLength(0);
1111
+ const columns = [...sheet.getElementsByTagNameNS(ns, "col")].map((column) =>
1112
+ ["min", "max", "width"].map((name) => column.getAttribute(name)),
1113
+ );
1114
+ // The engine ignores `defaultColWidth`, so the columns it sizes are spelled out.
1115
+ expect(columns).toEqual([
1116
+ [String(OFFICE_PREVIEW_MAX_COLUMNS - 1), String(OFFICE_PREVIEW_MAX_COLUMNS), "20"],
1117
+ // Hidden columns keep their span past the limit, so they stay hidden.
1118
+ [String(OFFICE_PREVIEW_MAX_COLUMNS + 1), String(OFFICE_PREVIEW_MAX_COLUMNS + 30), null],
1119
+ ["1", String(OFFICE_PREVIEW_MAX_COLUMNS - 2), "30"],
1120
+ ]);
1121
+ } finally {
1122
+ worker.terminate();
1123
}
1097
- expect(sheet.getElementsByTagNameNS(ns, "dimension")).toHaveLength(0);
1098
- expect(sheet.getElementsByTagNameNS(ns, "mergeCell")).toHaveLength(0);
1099
- const columns = sheet.getElementsByTagNameNS(ns, "col");
1100
- expect(columns).toHaveLength(1);
1101
- expect(columns[0]!.getAttribute("min")).toBe(String(OFFICE_PREVIEW_MAX_COLUMNS - 1));
1102
- expect(columns[0]!.getAttribute("max")).toBe(String(OFFICE_PREVIEW_MAX_COLUMNS));
1103
- } finally {
1104
- worker.terminate();
1105
- }
1106
-});
1124
+ },
1125
+);
1126
1127
it("reports the final slide at maximum scroll after page visibility changes", async () => {
1128
const { OfficePages } = await import("./office/OfficePages");
@@ -1717,7 +1736,7 @@ it.each(["repeated binary", "XML relationship alias", "duplicate relationship ID
1736
},
1737
);
1738
1720
-it.each(["XFD200", "XFD1048576", "AX500", "AZ9999999"])(
1739
+it.each(["XFD200", "XFD300", "XFD1048576", "AX500", "AZ9999999"])(
1740
"bounds spreadsheet cells at %s before padding",
1741
async (ref) => {
1742
const { default: JSZip } = await import("jszip");
@@ -1733,7 +1752,7 @@ it.each(["XFD200", "XFD1048576", "AX500", "AZ9999999"])(
1752
);
1753
archive.file(
1754
"xl/custom.xml",
1736
- `<worksheet><dimension ref="A1:${ref}"/><sheetData><row r="1"><c r="A1"><v>7</v></c></row><row r="${ref.replace(/\D/g, "")}"><c r="${ref}"><v>9</v></c></row></sheetData></worksheet>`,
1755
+ `<worksheet><dimension ref="A1:${ref}"/><sheetData><row r="1"><c r="A1"><v>7</v></c></row><row r="${ref.replace(/\D/g, "")}">${ref === "XFD300" ? `<c r="${ref}" s="1"/>` : `<c r="${ref}"><v>9</v></c>`}</row></sheetData></worksheet>`,
1756
);
1757
const bytes = await archive.generateAsync({ type: "arraybuffer" });
1758
const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
@@ -1763,7 +1782,7 @@ it.each(["XFD200", "XFD1048576", "AX500", "AZ9999999"])(
1782
);
1783
expect(sheet.querySelector('c[r="A1"] v')?.textContent).toBe("7");
1784
expect(sheet.querySelectorAll("row").length).toBeLessThanOrEqual(500);
1766
- expect(result.truncated).toBe(ref !== "AX500");
1785
+ expect(result.truncated).toBe(ref === "XFD200" || ref === "XFD300");
1786
if (ref === "AX500") expect(sheet.querySelector('c[r="AX500"] v')?.textContent).toBe("9");
1787
else expect(sheet.querySelector('c[r="' + ref + '"]')).toBeNull();
1788
}
@@ -1773,6 +1792,62 @@ it.each(["XFD200", "XFD1048576", "AX500", "AZ9999999"])(
1792
},
1793
);
1794
1795
+it.each(['<u val="double"/>', '<u val="double"></u>'])(
1796
+ "shows workbook formats and underline %s",
1797
+ async (underline) => {
1798
+ const { default: JSZip } = await import("jszip");
1799
+ const archive = new JSZip();
1800
+ archive.file(
1801
+ "xl/workbook.xml",
1802
+ '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Styles" sheetId="1" r:id="rId1"/></sheets></workbook>',
1803
+ );
1804
+ archive.file(
1805
+ "xl/_rels/workbook.xml.rels",
1806
+ '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
1807
+ );
1808
+ archive.file(
1809
+ "xl/styles.xml",
1810
+ `<styleSheet><numFmts count="4"><numFmt numFmtId="164" formatCode="0.000"/><numFmt numFmtId="65535" formatCode="0.0000"/><numFmt numFmtId="007" formatCode=""¥"#,##0.00"/><numFmt numFmtId="82" formatCode="[$-010409]dd-mmm-yyyy"/></numFmts><fonts count="2"><font><sz val="11"/></font><font>${underline}<sz val="11"/></font></fonts><cellXfs count="4"><xf numFmtId="0" fontId="0"/><xf numFmtId="7" fontId="0"/><xf numFmtId="82" fontId="0"/><xf numFmtId="0" fontId="1"/></cellXfs></styleSheet>`,
1811
+ );
1812
+ archive.file(
1813
+ "xl/worksheets/sheet1.xml",
1814
+ '<worksheet><sheetData><row r="1"><c r="A1" s="1"><v>100</v></c><c r="B1" s="2"><v>44986</v></c><c r="C1" s="3" t="inlineStr"><is><t>Total</t></is></c></row></sheetData></worksheet>',
1815
+ );
1816
+ const { prepareOffice } = await import("./officeArchive");
1817
+ const prepared = await prepareOffice(
1818
+ await archive.generateAsync({ type: "arraybuffer" }),
1819
+ "xlsx",
1820
+ );
1821
+ const styles = await (
1822
+ await JSZip.loadAsync(prepared.bytes)
1823
+ )
1824
+ .file("xl/styles.xml")!
1825
+ .async("string");
1826
+ expect(styles).toContain("<font><u/>");
1827
+ const worker = new Worker(new URL("./office/spreadsheet.worker.ts", import.meta.url), {
1828
+ type: "module",
1829
+ });
1830
+ try {
1831
+ const { createWorkerClient } = await import("./office/worker-rpc");
1832
+ const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
1833
+ const bytes = prepared.bytes;
1834
+ await client.call("open", { bytes, view: prepared.view! }, { transfer: [bytes] });
1835
+ const cells = await client.call("cells", {
1836
+ sheet: 0,
1837
+ range: { top: 0, bottom: 0, left: 0, right: 1 },
1838
+ });
1839
+ // Ids under 164 that a workbook defines keep its formats, not Excel's built-in ones.
1840
+ expect(cells[0]).toEqual(["¥100.00", "01-Mar-2023"]);
1841
+ } finally {
1842
+ worker.terminate();
1843
+ }
1844
+ archive.file("xl/styles.xml", "<styleSheet><numFmts/><numFmts/></styleSheet>");
1845
+ await expect(
1846
+ prepareOffice(await archive.generateAsync({ type: "arraybuffer" }), "xlsx"),
1847
+ ).rejects.toThrow("duplicate stylesheet blocks");
1848
+ },
1849
+);
1850
+
1851
it("keeps spreadsheet dates on their calendar day west of UTC", async () => {
1852
const { default: JSZip } = await import("jszip");
1853
const archive = new JSZip();
@@ -1831,7 +1906,14 @@ it("keeps spreadsheet dates on their calendar day west of UTC", async () => {
1906
});
1907
const { createWorkerClient } = await import("./office/worker-rpc");
1908
const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
1834
- await client.call("open", { bytes }, { transfer: [bytes] });
1909
+ await client.call(
1910
+ "open",
1911
+ {
1912
+ bytes,
1913
+ view: { hiddenGridlines: [], themeFonts: { major: "Calibri Light", minor: "Calibri" } },
1914
+ },
1915
+ { transfer: [bytes] },
1916
+ );
1917
const cells = await client.call("cells", {
1918
sheet: 0,
1919
range: { top: 0, bottom: 0, left: 0, right: 0 },
apps/web/src/components/files/OpenXmlOfficeViewer.tsx
+11
-3
@@ -104,8 +104,7 @@ export default function OfficeViewer(props: {
104
</div>
105
);
106
if (!prepared) return <FileSurfaceLoading />;
107
- const Viewer =
108
- props.kind === "docx" ? WordDocument : props.kind === "xlsx" ? Spreadsheet : Presentation;
107
+ const Viewer = props.kind === "docx" ? WordDocument : Presentation;
108
return (
109
<div className="flex min-h-0 flex-1 flex-col">
110
{details ? (
@@ -122,7 +121,16 @@ export default function OfficeViewer(props: {
121
</FileSurfaceNotice>
122
) : null}
123
<Suspense fallback={<FileSurfaceLoading />}>
125
- <Viewer bytes={prepared.bytes} onDetails={setDetails} onError={fail} />
124
+ {prepared.view ? (
125
+ <Spreadsheet
126
+ bytes={prepared.bytes}
127
+ view={prepared.view}
128
+ onDetails={setDetails}
129
+ onError={fail}
130
+ />
131
+ ) : (
132
+ <Viewer bytes={prepared.bytes} onDetails={setDetails} onError={fail} />
133
+ )}
134
</Suspense>
135
</div>
136
);
apps/web/src/components/files/office/Spreadsheet.tsx
+5
-3
@@ -14,6 +14,7 @@ import {
14
type CellAddr,
15
} from "@betteroffice/xlsx/headless";
16
import { FileSurfaceLoading, FileSurfaceNotice } from "../fileSurfaceChrome";
17
+import type { WorkbookView } from "../officePreviewProtocol";
18
import { createWorkerClient, SupersededError } from "./worker-rpc";
19
import type { SheetLayout, SheetMethods, SheetFrameRequest, SheetTab } from "./sheet-protocol";
20
import {
@@ -45,10 +46,11 @@ type Opened = {
46
};
47
export default function Spreadsheet(props: {
48
bytes: ArrayBuffer;
49
+ view: WorkbookView;
50
onDetails: (text: string) => void;
51
onError: (cause: unknown) => void;
52
}) {
51
- const { onError, bytes: source, onDetails } = props;
53
+ const { onError, bytes: source, onDetails, view } = props;
54
const [opened, setOpened] = useState<Opened>();
55
const [error, setError] = useState("");
56
const picking = useRef<AbortController | null>(null);
@@ -66,7 +68,7 @@ export default function Spreadsheet(props: {
68
worker.addEventListener("messageerror", fail);
69
const bytes = source.slice(0);
70
void engine
69
- .call("open", { bytes }, { transfer: [bytes], signal: controller.signal })
71
+ .call("open", { bytes, view }, { transfer: [bytes], signal: controller.signal })
72
.then((value) => {
73
if (!value) throw new Error("This workbook has no visible sheets.");
74
setOpened({ ...value, engine });
@@ -78,7 +80,7 @@ export default function Spreadsheet(props: {
80
picking.current?.abort();
81
engine.close();
82
};
81
- }, [source, onDetails, onError]);
83
+ }, [source, view, onDetails, onError]);
84
const show = (sheet: number, target?: CellAddr) => {
85
if (!opened) return;
86
picking.current?.abort();
apps/web/src/components/files/office/fonts.browser.test.ts
+12
-1
@@ -1,6 +1,6 @@
1
import { BUNDLED_FONTS } from "@betteroffice/fonts";
2
import { describe, expect, it } from "vite-plus/test";
3
-import { wordFonts } from "./fonts";
3
+import { sheetFace, wordFonts } from "./fonts";
4
5
const notoSansJp = BUNDLED_FONTS.find((face) => face.file === "NotoSansJP-Regular.otf")!;
6
const fonts = wordFonts();
@@ -16,3 +16,14 @@ describe("wordFonts", () => {
16
expect(bytes?.byteLength).toBe(notoSansJp.byteLength);
17
});
18
});
19
+
20
+it.each([false, true])(
21
+ "uses the available Comic Relief face for italic spreadsheet text (bold: %s)",
22
+ (bold) => {
23
+ expect(sheetFace("Comic Relief", bold, true)).toMatchObject({
24
+ family: "Comic Relief",
25
+ weight: bold ? 700 : 400,
26
+ style: "normal",
27
+ });
28
+ },
29
+);
apps/web/src/components/files/office/fonts.ts
+10
@@ -35,6 +35,16 @@ export function presentationFace(family: string, bold: boolean, italic: boolean)
35
);
36
}
37
38
+/** The face Excel's cells draw a family with when it is missing: its metric-compatible or bundled face, if any. */
39
+export function sheetFace(family: string, bold: boolean, italic: boolean) {
40
+ return (
41
+ resolveMetricCompatFace(family, bold, italic) ??
42
+ resolveBundledFamilyFace(family, bold, italic) ??
43
+ resolveBundledFamilyFace(family, bold, false) ??
44
+ resolveBundledFamilyFace(family, false, false)
45
+ );
46
+}
47
+
48
/**
49
* A bundled face's bytes. The font package caches them per worker, so a face loads once per open file; the browser's
50
* caches, which every worker shares, serve the files to the next.
apps/web/src/components/files/office/sheet-fonts.ts
new
+58
@@ -0,0 +1,58 @@
1
+import type { DisplayList } from "@betteroffice/xlsx";
2
+import { loadFace, sheetFace } from "./fonts";
3
+
4
+/**
5
+ * The metric-compatible faces a workbook's cells draw with, such as Carlito for Calibri, added to the worker's font set
6
+ * under the family name the painter asks for, so text widths, wrapping and overflow match Excel on machines without
7
+ * Office fonts. A family the app ships no face for stays with the browser's own fallback.
8
+ */
9
+export function sheetFonts() {
10
+ // SAFETY: a worker's global scope is a FontFaceSource, whose `fonts` is a FontFaceSet (CSS Font Loading, exposed to
11
+ // workers). The window's types declare it on documents only. Without one, cells keep the browser's fallback.
12
+ const fonts = "fonts" in self ? (self.fonts as FontFaceSet) : undefined;
13
+ const loads = new Map<string, Promise<void>>();
14
+
15
+ const load = (family: string, bold: boolean, italic: boolean) => {
16
+ const key = `${family}\u0000${bold}\u0000${italic}`;
17
+ const existing = loads.get(key);
18
+
19
+ if (existing) return existing;
20
+
21
+ const face = sheetFace(family, bold, italic);
22
+ const loading =
23
+ face && fonts
24
+ ? loadFace(face)
25
+ // A family without the requested style gets the face it has, which the browser then slants or emboldens.
26
+ .then((bytes) =>
27
+ new FontFace(family, bytes, {
28
+ weight: face.weight === 700 ? "700" : "400",
29
+ style: face.style === "italic" ? "italic" : "normal",
30
+ }).load(),
31
+ )
32
+ .then((loaded) => void fonts.add(loaded))
33
+ .catch(() => undefined)
34
+ : Promise.resolve();
35
+
36
+ loads.set(key, loading);
37
+
38
+ return loading;
39
+ };
40
+
41
+ /** Loads the faces a frame's cell text uses before it paints. */
42
+ return (lists: readonly DisplayList[]) =>
43
+ Promise.all(
44
+ lists.flatMap((list) =>
45
+ list.commands.flatMap((command) => {
46
+ // Chart text arrives as a CSS family list whose first family is the one to load.
47
+ const family =
48
+ command.op === "text"
49
+ ? (/^"([^"]+)"/.exec(command.fontFamily ?? "")?.[1] ?? command.fontFamily)
50
+ : undefined;
51
+
52
+ return command.op === "text" && family
53
+ ? [load(family, !!command.bold, !!command.italic)]
54
+ : [];
55
+ }),
56
+ ),
57
+ );
58
+}
apps/web/src/components/files/office/sheet-frame.ts
+65
-12
@@ -50,7 +50,7 @@ export function drawFrame(
50
frozen: { readonly rows: number; readonly cols: number },
51
wider?: SheetViewport,
52
): Frame | undefined {
53
- const around = wider && attempt(() => workbook.displayList(wider));
53
+ const around = wider && untruncated(workbook, wider);
54
55
if (wider && around)
56
return {
@@ -59,15 +59,15 @@ export function drawFrame(
59
viewport: wider,
60
};
61
62
- const whole = attempt(() => workbook.displayList(viewport));
62
+ const whole = untruncated(workbook, viewport);
63
64
if (whole)
65
return { list: whole, tiles: [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }], viewport };
66
67
// The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. One row and one column of
68
// the frame give its tracks, and so where its frozen panes end.
69
- const columns = attempt(() => workbook.displayList({ ...viewport, height: 1 }).grid);
70
- const rows = attempt(() => workbook.displayList({ ...viewport, width: 1 }).grid);
69
+ const columns = untruncated(workbook, { ...viewport, height: 1 })?.grid;
70
+ const rows = untruncated(workbook, { ...viewport, width: 1 })?.grid;
71
72
if (!columns || !rows) return undefined;
73
@@ -83,6 +83,54 @@ export function drawFrame(
83
return tiled(workbook, viewport, frozenSize(grid, frozen), grid, 2);
84
}
85
86
+/** The engine's screen gridlines: one-pixel solid lines in its gridline grey, unlike any border it draws. */
87
+const gridline = (command: DisplayList["commands"][number]) =>
88
+ command.op === "line" && command.color === "#d4d4d4" && command.width === 1 && !command.style;
89
+
90
+/** A frame without the gridlines the engine draws on every sheet, for a sheet whose view hides them. */
91
+export function withoutGridlines(frame: Frame): Frame {
92
+ return {
93
+ ...frame,
94
+ tiles: frame.tiles.map((tile) => ({
95
+ ...tile,
96
+ list: { ...tile.list, commands: tile.list.commands.filter((command) => !gridline(command)) },
97
+ })),
98
+ };
99
+}
100
+
101
+/**
102
+ * A frame whose chart text names real fonts. The engine leaves the theme's `+mj-lt` and `+mn-lt` in chart text and the
103
+ * painter sets chart families as CSS as they are, so an unresolved or missing family would keep the previous font.
104
+ */
105
+export function chartFonts(
106
+ frame: Frame,
107
+ theme: { readonly major: string; readonly minor: string },
108
+): Frame {
109
+ const family = (name: string) => {
110
+ const resolved = name.startsWith("+mj-")
111
+ ? theme.major
112
+ : name.startsWith("+mn-")
113
+ ? theme.minor
114
+ : name;
115
+ return `"${resolved.replaceAll('"', "")}", sans-serif`;
116
+ };
117
+
118
+ return {
119
+ ...frame,
120
+ tiles: frame.tiles.map((tile) => ({
121
+ ...tile,
122
+ list: {
123
+ ...tile.list,
124
+ commands: tile.list.commands.map((command) =>
125
+ command.op === "text" && command.chart
126
+ ? { ...command, fontFamily: family(command.fontFamily ?? theme.minor) }
127
+ : command,
128
+ ),
129
+ },
130
+ })),
131
+ };
132
+}
133
+
134
/**
135
* Draws a frame's tiles with the cells' top-left corner at `origin`, in device pixels, each tile from its seam on, so a
136
* tile covers the panes it repeats.
@@ -175,14 +223,12 @@ function tiled(
223
const right = column.end === viewport.width ? column.end : column.end + seamOverlap;
224
const bottom = row.end === viewport.height ? row.end : row.end + seamOverlap;
225
178
- const list = attempt(() =>
179
- workbook.displayList({
180
- x: viewport.x + x,
181
- y: viewport.y + y,
182
- width: right - x,
183
- height: bottom - y,
184
- }),
185
- );
226
+ const list = untruncated(workbook, {
227
+ x: viewport.x + x,
228
+ y: viewport.y + y,
229
+ width: right - x,
230
+ height: bottom - y,
231
+ });
232
233
if (list) tiles.push({ list, x, y, clipX: column.start, clipY: row.start });
234
@@ -205,6 +251,13 @@ function tiled(
251
return tiled(workbook, viewport, panes, grid, split + 1);
252
}
253
254
+/** A viewport's display list, or undefined where the engine refuses it or cuts it short at its cell limit. */
255
+function untruncated(workbook: WorkbookHandle, viewport: SheetViewport) {
256
+ const list = attempt(() => workbook.displayList(viewport));
257
+
258
+ return list?.truncated ? undefined : list;
259
+}
260
+
261
/** Even spans of a side, the first holding the frozen panes whole; a seam inside them is dropped. */
262
function segments(size: number, panes: number, split: number) {
263
const starts = Array.from({ length: split }, (_, part) =>
apps/web/src/components/files/office/sheet-protocol.ts
+2
-1
@@ -1,6 +1,7 @@
1
// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
import type { SheetInfo } from "@betteroffice/xlsx";
3
import type { CellAddr, CellRange, GridMeta, HyperlinkRegion } from "@betteroffice/xlsx/headless";
4
+import type { WorkbookView } from "../officePreviewProtocol";
5
import type { Span } from "./sheet-cells";
6
import type { Method } from "./worker-rpc";
7
@@ -70,7 +71,7 @@ export type SheetMethods = {
71
* saved on a hidden sheet. Undefined when no sheet is visible.
72
*/
73
readonly open: Method<
73
- { readonly bytes: ArrayBuffer },
74
+ { readonly bytes: ArrayBuffer; readonly view: WorkbookView },
75
{ readonly tabs: readonly SheetTab[]; readonly layout: SheetLayout } | undefined
76
>;
77
/** Makes a sheet the active one; rejects, leaving the sheet before it active, when it cannot open. */
apps/web/src/components/files/office/spreadsheet.worker.ts
+26
-5
@@ -10,7 +10,9 @@ import {
10
} from "@betteroffice/xlsx";
11
import type { CellRange } from "@betteroffice/xlsx/headless";
12
import { anchorRange, attempt, lastCell, parseRange, parseSpans } from "./sheet-cells";
13
-import { drawFrame, paintFrame } from "./sheet-frame";
13
+import type { WorkbookView } from "../officePreviewProtocol";
14
+import { chartFonts, drawFrame, paintFrame, withoutGridlines } from "./sheet-frame";
15
+import { sheetFonts } from "./sheet-fonts";
16
import { frozenSize } from "./sheet-paint";
17
import type { SheetLayout, SheetMethods, SheetTab } from "./sheet-protocol";
18
import { serveWorker, Transfer } from "./worker-rpc";
@@ -26,6 +28,9 @@ type Opened = {
28
readonly ends: Map<string, { readonly x: number; readonly y: number } | undefined>;
29
/** The one canvas every frame paints on and hands over as a bitmap. */
30
readonly surface: OffscreenCanvas;
31
+ /** The sheets whose view hides gridlines, which the engine draws on every sheet. */
32
+ readonly hiddenGridlines: ReadonlySet<number>;
33
+ readonly themeFonts: WorkbookView["themeFonts"];
34
};
35
36
/** The workbook this worker opened, once it has. */
@@ -33,6 +38,8 @@ type State = { opened: Opened | undefined };
38
39
const state: State = { opened: undefined };
40
41
+const loadFonts = sheetFonts();
42
+
43
serveWorker<SheetMethods>({
44
open: async (input) => {
45
if (state.opened) throw new Error("The worker already holds a workbook");
@@ -42,7 +49,14 @@ serveWorker<SheetMethods>({
49
const workbook = openWorkbook(new Uint8Array(input.bytes));
50
const info = workbook.sheetInfo();
51
45
- state.opened = { workbook, info, ends: new Map(), surface: new OffscreenCanvas(1, 1) };
52
+ state.opened = {
53
+ workbook,
54
+ info,
55
+ ends: new Map(),
56
+ surface: new OffscreenCanvas(1, 1),
57
+ hiddenGridlines: new Set(input.view.hiddenGridlines),
58
+ themeFonts: input.view.themeFonts,
59
+ };
60
61
const tabs = visibleTabs(workbook, info);
62
// A workbook saved on a hidden sheet opens on the first visible one, as Excel does.
@@ -64,13 +78,20 @@ serveWorker<SheetMethods>({
78
79
throw new Error(`Sheet ${input.sheet} could not open`);
80
},
67
- frame: (input) => {
81
+ frame: async (input) => {
82
const opened = active(input.sheet);
83
const frozen = { rows: opened.info.frozenRows, cols: opened.info.frozenCols };
84
const viewport = { x: input.x, y: input.y, width: input.width, height: input.height };
71
- const drawn = drawFrame(opened.workbook, viewport, frozen, input.wider);
85
+ const frame = drawFrame(opened.workbook, viewport, frozen, input.wider);
86
+
87
+ if (!frame) return undefined;
88
+
89
+ const drawn = chartFonts(
90
+ opened.hiddenGridlines.has(input.sheet) ? withoutGridlines(frame) : frame,
91
+ opened.themeFonts,
92
+ );
93
73
- if (!drawn) return undefined;
94
+ await loadFonts(drawn.tiles.map((tile) => tile.list));
95
96
const surface = opened.surface;
97
const width = Math.ceil(input.offset.x + drawn.viewport.width * input.ratio);
apps/web/src/components/files/officeArchive.ts
+179
-14
@@ -253,10 +253,21 @@ function boundedWorksheet(
253
const rowTags = new Map<number, string>();
254
const metadataAttributes = new Map<
255
string,
256
- { ref: string | undefined; min: string | undefined; max: string | undefined }
256
+ {
257
+ ref: string | undefined;
258
+ min: string | undefined;
259
+ max: string | undefined;
260
+ hidden: string | undefined;
261
+ }
262
>();
263
let dataStart = 0;
264
+ let dataTag = 0;
265
+ let dataPrefix = "";
266
+ let dataNamespace = "";
267
let dataEnd = 0;
268
+ let defaultWidth: number | undefined;
269
+ let gridlines: boolean | undefined;
270
+ const sizedColumns: { min: number; max: number }[] = [];
271
let emptyData = false;
272
let depth = 0;
273
let row = 0;
@@ -305,17 +316,42 @@ function boundedWorksheet(
316
ref: attribute("ref"),
317
min: attribute("min"),
318
max: attribute("max"),
319
+ hidden: attribute("hidden"),
320
},
321
);
322
+ // The engine draws gridlines on every sheet, so the first view's choice travels beside the bytes.
323
+ if (depth === 3 && tag.local === "sheetView" && gridlines === undefined) {
324
+ const shown = attribute("showGridLines");
325
+ gridlines = shown !== "0" && shown !== "false";
326
+ }
327
+ if (depth === 2 && tag.local === "sheetFormatPr") {
328
+ const width = Number(attribute("defaultColWidth") ?? Number.NaN);
329
+ if (width >= 0 && width <= 255) defaultWidth = width;
330
+ }
331
+ if (depth === 3 && tag.local === "col") {
332
+ const hidden = attribute("hidden");
333
+ const min = Number(attribute("min") ?? 1);
334
+ const max = Number(attribute("max") ?? min);
335
+ if (
336
+ (attribute("width") !== undefined || hidden === "1" || hidden === "true") &&
337
+ Number.isInteger(min) &&
338
+ Number.isInteger(max)
339
+ )
340
+ sizedColumns.push({ min, max });
341
+ }
342
if (depth === 2 && tag.local === "sheetData") {
343
dataStart = parser.position;
344
+ dataTag = xml.lastIndexOf("<", parser.position - 1);
345
+ dataPrefix = tag.prefix ? `${tag.prefix}:` : "";
346
+ dataNamespace = tag.uri
347
+ .replaceAll("&", "&")
348
+ .replaceAll('"', """)
349
+ .replaceAll("<", "<");
350
emptyData = tag.isSelfClosing;
351
}
352
+ // A dimension past the limits loses nothing by itself; the cells past them say whether content is lost.
353
if (depth === 2 && tag.local === "dimension") {
315
- for (const ref of (attribute("ref") ?? "").split(":")) {
316
- const { col, line } = coordinate(ref);
317
- if (col > OFFICE_PREVIEW_MAX_COLUMNS || line > OFFICE_PREVIEW_MAX_ROWS) truncated = true;
318
- }
354
+ for (const ref of (attribute("ref") ?? "").split(":")) coordinate(ref);
355
} else if (depth === 3 && tag.local === "row") {
356
explicitRow = attribute("r") !== undefined;
357
row = attribute("r") === undefined ? row + 1 : Number(attribute("r"));
@@ -441,7 +477,12 @@ function boundedWorksheet(
477
}
478
if (/<(?:\w+:)?col\b/.test(opening)) {
479
const min = Math.max(1, Number(attributes.min ?? 1));
444
- const max = Math.min(OFFICE_PREVIEW_MAX_COLUMNS, Number(attributes.max ?? 16384));
480
+ // Hidden columns keep their full span, or the columns past the limit would show again.
481
+ const hidden = attributes.hidden === "1" || attributes.hidden === "true";
482
+ const max = Math.min(
483
+ hidden ? 16384 : OFFICE_PREVIEW_MAX_COLUMNS,
484
+ Number(attributes.max ?? 16384),
485
+ );
486
if (!Number.isInteger(min) || !Number.isInteger(max) || min > max) return "";
487
replace("min", String(min));
488
replace("max", String(max));
@@ -449,10 +490,28 @@ function boundedWorksheet(
490
return tag;
491
},
492
);
493
+ // The engine sizes columns without a width at Excel's 8.43 characters and ignores `defaultColWidth`, so the
494
+ // columns it covers get that width spelled out. A second `<cols>` is valid: the schema allows any number.
495
+ let defaultColumns = "";
496
+ if (defaultWidth !== undefined) {
497
+ let next = 1;
498
+ for (const span of sizedColumns.toSorted((a, b) => a.min - b.min)) {
499
+ if (span.min > next)
500
+ defaultColumns += `<${dataPrefix}col min="${next}" max="${Math.min(span.min - 1, OFFICE_PREVIEW_MAX_COLUMNS)}" width="${defaultWidth}"/>`;
501
+ next = Math.max(next, span.max + 1);
502
+ if (next > OFFICE_PREVIEW_MAX_COLUMNS) break;
503
+ }
504
+ if (next <= OFFICE_PREVIEW_MAX_COLUMNS)
505
+ defaultColumns += `<${dataPrefix}col min="${next}" max="${OFFICE_PREVIEW_MAX_COLUMNS}" width="${defaultWidth}"/>`;
506
+ if (defaultColumns)
507
+ defaultColumns = `<${dataPrefix}cols xmlns${dataPrefix ? `:${dataPrefix.slice(0, -1)}` : ""}="${dataNamespace}">${defaultColumns}</${dataPrefix}cols>`;
508
+ }
509
+ const head = (part: string) =>
510
+ metadata(part.slice(0, dataTag) + defaultColumns + part.slice(dataTag));
511
return {
512
xml: emptyData
454
- ? metadata(xml)
455
- : `${metadata(xml.slice(0, dataStart))}${[...rows]
513
+ ? head(xml)
514
+ : `${head(xml.slice(0, dataStart))}${[...rows]
515
.sort(([a], [b]) => a - b)
516
.map(
517
([line, values]) =>
@@ -463,12 +522,84 @@ function boundedWorksheet(
522
)
523
.join("")}${metadata(xml.slice(dataEnd))}`,
524
truncated,
525
+ gridlines: gridlines ?? true,
526
};
527
}
528
529
+/**
530
+ * A stylesheet as Excel reads it, in the terms the engine understands. The engine takes a number format id under 164 as
531
+ * Excel's built-in one, though workbooks define their own there (Excel writes its locale formats 5 to 8 that way), so
532
+ * those move to free ids. It also reads `<u val="…">` as a boolean, which loses every named underline but the bare one.
533
+ */
534
+function engineStyles(xml: string) {
535
+ const name = (local: string) => `<((?:[\\w.-]+:)?)${local}\\b`;
536
+ const blocks = new Map<string, { start: number; end: number }>();
537
+ const parser = xmlParser();
538
+ let depth = 0;
539
+ parser.on("opentag", (tag) => {
540
+ if (++depth > 64) throw new Error("This workbook contains excessive XML nesting.");
541
+ if (depth !== 2 || !["numFmts", "cellStyleXfs", "cellXfs"].includes(tag.local)) return;
542
+ if (blocks.has(tag.local))
543
+ throw new Error("This workbook contains duplicate stylesheet blocks.");
544
+ blocks.set(tag.local, {
545
+ start: xml.lastIndexOf("<", parser.position - 1),
546
+ end: parser.position,
547
+ });
548
+ });
549
+ parser.on("closetag", (tag) => {
550
+ if (depth === 2) {
551
+ const block = blocks.get(tag.local);
552
+ if (block) block.end = parser.position;
553
+ }
554
+ depth--;
555
+ });
556
+ parser.write(xml).close();
557
+ const id = /(numFmtId\s*=\s*)(["'])(\d+)\2/g;
558
+ const moved = new Map<number, number>();
559
+ const formatBlock = blocks.get("numFmts");
560
+ const formats = formatBlock ? xml.slice(formatBlock.start, formatBlock.end) : "";
561
+ const used = new Set([...formats.matchAll(id)].map((match) => Number(match[3])));
562
+ let next = 164;
563
+ const renumber = (part: string, assign: boolean) =>
564
+ part.replace(id, (attribute: string, key: string, quote: string, value: string) => {
565
+ const number = Number(value);
566
+ if (assign && number < 164 && !moved.has(number)) {
567
+ while (used.has(next)) next++;
568
+ if (next > 65535) throw new Error("This workbook has too many custom number formats.");
569
+ moved.set(number, next++);
570
+ }
571
+ const to = moved.get(number);
572
+ return to === undefined ? attribute : `${key}${quote}${to}${quote}`;
573
+ });
574
+ const numberedFormats = renumber(formats, true);
575
+ const parts: string[] = [];
576
+ let offset = 0;
577
+ for (const [local, block] of blocks) {
578
+ parts.push(
579
+ xml.slice(offset, block.start),
580
+ local === "numFmts" ? numberedFormats : renumber(xml.slice(block.start, block.end), false),
581
+ );
582
+ offset = block.end;
583
+ }
584
+ parts.push(xml.slice(offset));
585
+ return parts
586
+ .join("")
587
+ .replace(
588
+ new RegExp(
589
+ `${name("u")}\\s+val\\s*=\\s*(["'])(?:single|double|singleAccounting|doubleAccounting)\\2\\s*(?:/>|>\\s*</\\1u\\s*>)`,
590
+ "g",
591
+ ),
592
+ "<$1u/>",
593
+ );
594
+}
595
+
596
async function boundWorkbook(archive: JSZip) {
597
const paths = new Map<string, string>();
598
+ // Chart sheets and other non-grid sheets hold no cells to bound.
599
+ const otherSheets = new Set<string>();
600
let sharedPath = "xl/sharedStrings.xml";
601
+ let stylesPath = "xl/styles.xml";
602
+ let themePath = "xl/theme/theme1.xml";
603
const relationships = xmlParser();
604
relationships.on("opentag", (tag) => {
605
if (tag.local !== "Relationship") return;
@@ -478,22 +609,44 @@ async function boundWorkbook(archive: JSZip) {
609
"https://docx.invalid/xl/workbook.xml",
610
).pathname.slice(1);
611
if (type?.endsWith("/worksheet")) paths.set(tag.attributes.Id?.value ?? "", path);
612
+ else if (/\/(?:chartsheet|dialogsheet|xlMacrosheet|xlIntlMacrosheet)$/.test(type ?? ""))
613
+ otherSheets.add(tag.attributes.Id?.value ?? "");
614
if (type?.endsWith("/sharedStrings")) sharedPath = path;
615
+ if (type?.endsWith("/styles")) stylesPath = path;
616
+ if (type?.endsWith("/theme")) themePath = path;
617
});
618
relationships
619
.write((await archive.file("xl/_rels/workbook.xml.rels")?.async("string")) ?? "")
620
.close();
621
const sheetPaths: string[] = [];
622
+ // Every sheet in workbook order, as the engine indexes them; chart sheets have no worksheet path.
623
+ const sheetOrder: (string | undefined)[] = [];
624
const workbook = xmlParser();
625
workbook.on("opentag", (tag) => {
626
if (tag.local !== "sheet") return;
627
const id = Object.values(tag.attributes).find((attribute) => attribute.local === "id")?.value;
628
+ if (otherSheets.has(id ?? "")) {
629
+ sheetOrder.push(undefined);
630
+ return;
631
+ }
632
const path = paths.get(id ?? "");
633
if (!path || sheetPaths.length === 100)
634
throw new Error("This workbook has invalid or too many sheets.");
635
sheetPaths.push(path);
636
+ sheetOrder.push(path);
637
});
638
workbook.write((await archive.file("xl/workbook.xml")?.async("string")) ?? "").close();
639
+ const theme = (await archive.file(themePath)?.async("string")) ?? "";
640
+ const typeface = (font: string, fallback: string) =>
641
+ new RegExp(
642
+ `<(?:[\\w.-]+:)?${font}\\b[^>]*>\\s*<(?:[\\w.-]+:)?latin\\b[^>]*\\btypeface\\s*=\\s*["']([^"']+)["']`,
643
+ ).exec(theme)?.[1] ?? fallback;
644
+ const themeFonts = {
645
+ major: typeface("majorFont", "Calibri Light"),
646
+ minor: typeface("minorFont", "Calibri"),
647
+ };
648
+ const styles = await archive.file(stylesPath)?.async("string");
649
+ if (styles) archive.file(stylesPath, engineStyles(styles));
650
const strings: string[] = [];
651
const shared = await archive.file(sharedPath)?.async("string");
652
if (shared) {
@@ -516,15 +669,20 @@ async function boundWorkbook(archive: JSZip) {
669
parser.write(shared).close();
670
}
671
const budget = { remaining: 1024 * 1024, cells: 0 };
519
- const limited = new Map<string, boolean>();
672
+ const bounded = new Map<string, { truncated: boolean; gridlines: boolean }>();
673
for (const path of new Set(sheetPaths)) {
674
const file = archive.file(path);
675
if (!file) throw new Error("This workbook has a missing worksheet.");
676
const sheet = boundedWorksheet(await file.async("string"), strings, budget);
677
archive.file(path, sheet.xml);
525
- limited.set(path, sheet.truncated);
678
+ bounded.set(path, sheet);
679
}
527
- return sheetPaths.map((path) => limited.get(path) ?? false);
680
+ return {
681
+ sheets: sheetOrder.map(
682
+ (path) => (path && bounded.get(path)) || { truncated: false, gridlines: true },
683
+ ),
684
+ themeFonts,
685
+ };
686
}
687
688
const WORD_RELATIONSHIP = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
@@ -1158,8 +1316,8 @@ export async function boundedArchive(input: Extract<OfficeWorkerRequest, { type:
1316
for (const path of mediaSizes.keys()) if (!usedImages.has(path)) archive.remove(path);
1317
archive.file("word/document.xml", documents[0]!);
1318
}
1161
- const truncatedSheets = input.kind === "xlsx" ? await boundWorkbook(archive) : [];
1162
- return { archive, word, truncatedSheets };
1319
+ const workbook = input.kind === "xlsx" ? await boundWorkbook(archive) : undefined;
1320
+ return { archive, word, workbook };
1321
}
1322
1323
export async function prepareOffice(
@@ -1214,7 +1372,14 @@ export async function prepareOffice(
1372
}
1373
return {
1374
bytes: await result.archive.generateAsync({ type: "arraybuffer", compression: "STORE" }),
1217
- truncated: result.word?.truncated || result.truncatedSheets.some(Boolean) || false,
1375
+ truncated:
1376
+ result.word?.truncated || result.workbook?.sheets.some((sheet) => sheet.truncated) || false,
1377
+ view: result.workbook && {
1378
+ hiddenGridlines: result.workbook.sheets.flatMap((sheet, index) =>
1379
+ sheet.gridlines ? [] : [index],
1380
+ ),
1381
+ themeFonts: result.workbook.themeFonts,
1382
+ },
1383
};
1384
}
1385
apps/web/src/components/files/officePreviewProtocol.ts
+10
@@ -4,6 +4,14 @@ export const OFFICE_PREVIEW_MAX_BYTES = 50 * 1024 * 1024;
4
export const OFFICE_PREVIEW_MAX_ROWS = 250_000;
5
export const OFFICE_PREVIEW_MAX_COLUMNS = 1024;
6
7
+/** What a workbook's views ask of the preview that its engine does not read. */
8
+export type WorkbookView = {
9
+ /** The sheets, by index in workbook order, whose view hides gridlines. */
10
+ readonly hiddenGridlines: readonly number[];
11
+ /** The theme's heading and body fonts, which chart text names as `+mj-lt` and `+mn-lt`. */
12
+ readonly themeFonts: { readonly major: string; readonly minor: string };
13
+};
14
+
15
export type OfficeWorkerRequest =
16
| { readonly type: "open"; readonly kind: OfficePreviewKind; readonly bytes: ArrayBuffer }
17
| { readonly type: "sheet-page"; readonly sheet: number; readonly index: number };
@@ -26,6 +34,8 @@ export type OfficeWorkerResult =
34
readonly type: "docx" | "xlsx" | "pptx";
35
readonly bytes: ArrayBuffer;
36
readonly truncated: boolean;
37
+ /** For a workbook; undefined for other files. */
38
+ readonly view: WorkbookView | undefined;
39
}
40
| {
41
readonly type: "ods";
pnpm-lock.yaml
+5
-5
@@ -1029,8 +1029,8 @@ importers:
1029
specifier: 0.2.0
1030
version: 0.2.0
1031
'@betteroffice/xlsx':
1032
- specifier: 0.3.0
1033
- version: 0.3.0
1032
+ specifier: 0.5.1
1033
+ version: 0.5.1
1034
'@clerk/clerk-js':
1035
specifier: 6.42.3
1036
version: 6.42.3(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
@@ -3274,8 +3274,8 @@ packages:
3274
'@betteroffice/pptx@0.2.0':
3275
resolution: {integrity: sha512-pNPQ58tlA+pVibERbLdQNskvP7a0GIMf4jhkCU/gPp8043Ichf6gB3PSb4ra9sfqoIaWqOaZKCWyptovA2+Q0A==}
3276
3277
- '@betteroffice/xlsx@0.3.0':
3278
- resolution: {integrity: sha512-K2bHtdk/epAxsmvxJlIWBRndjP3ltQU0Oh3p4gcZd2n5/YgXglo3SmMYX4nQe8WEm/yvz91p+aIasKyXXQP9Wg==}
3277
+ '@betteroffice/xlsx@0.5.1':
3278
+ resolution: {integrity: sha512-UHOnzcMML6Ud9D1M4d8FZKmw3AAg2/DttE/sVxM858SgiIpOtzGOqlh62RM9/8y/JW8bR8t+wN69EX8UJvR8EQ==}
3279
3280
'@blazediff/core@1.10.0':
3281
resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==}
@@ -13479,7 +13479,7 @@ snapshots:
13479
13480
'@betteroffice/pptx@0.2.0': {}
13481
13482
- '@betteroffice/xlsx@0.3.0': {}
13482
+ '@betteroffice/xlsx@0.5.1': {}
13483
13484
'@blazediff/core@1.10.0': {}
13485
third-party-licenses.config.json
+1
-1
@@ -261,7 +261,7 @@
261
},
262
{
263
"name": "@betteroffice/xlsx",
264
- "version": "0.3.0",
264
+ "version": "0.5.1",
265
"license": "Apache-2.0",
266
"sourceUrl": "https://github.com/openooxml/betteroffice",
267
"generatedNotice": {