Open History to see the last commit
1// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4import { inspectPresentation, type DeckSnapshot } from "@betteroffice/pptx";
5
6/** A text style a deck draws with. */
7export type FontStyle = { readonly bold: boolean; readonly italic: boolean };
8
9/** A family the deck names, with the styles its text asks for. */
10export type DeckFamily = { readonly name: string; readonly styles: readonly FontStyle[] };
11
12/** The scripts the bundled Latin faces may lack, which have a bundled fallback face. */
13export type FallbackScript = "hebrew" | "arabic";
14
15/** What a deck's text needs from the fonts, and which slides it hides. */
16export type DeckText = {
17 /** Most important first: the face registered first also draws every family the deck names but nobody found. */
18 readonly families: readonly DeckFamily[];
19 readonly scripts: readonly FallbackScript[];
20 /** One flag per slide, in deck order. */
21 readonly hidden: readonly boolean[];
22};
23
24const RunStyle = Schema.Struct({
25 bold: Schema.optional(Schema.NullOr(Schema.Boolean)),
26 italic: Schema.optional(Schema.NullOr(Schema.Boolean)),
27 fontFamily: Schema.optional(Schema.NullOr(Schema.String)),
28});
29
30const Body = Schema.Struct({
31 paragraphs: Schema.Array(
32 Schema.Struct({
33 properties: Schema.optional(
34 Schema.NullOr(
35 Schema.Struct({
36 defaultRun: Schema.optional(Schema.NullOr(RunStyle)),
37 }),
38 ),
39 ),
40 runs: Schema.Array(
41 Schema.Struct({
42 text: Schema.String,
43 properties: Schema.optional(Schema.NullOr(RunStyle)),
44 }),
45 ),
46 }),
47 ),
48});
49
50type Drawing = {
51 readonly text?: typeof Body.Type | null | undefined;
52 readonly children?: readonly Drawing[] | undefined;
53 readonly data?: typeof Table.Type | null | undefined;
54};
55
56const Table = Schema.Struct({
57 rows: Schema.optional(
58 Schema.Array(
59 Schema.Struct({
60 cells: Schema.Array(Schema.Struct({ text: Schema.optional(Schema.NullOr(Body)) })),
61 }),
62 ),
63 ),
64});
65
66/** A slide object: a shape, group, picture or graphic frame. */
67const Drawing: Schema.Codec<Drawing> = Schema.Struct({
68 text: Schema.optional(Schema.NullOr(Body)),
69 children: Schema.optional(Schema.Array(Schema.suspend((): Schema.Codec<Drawing> => Drawing))),
70 // A table's cells; other frames, such as charts, carry no rows.
71 data: Schema.optional(Schema.NullOr(Table)),
72});
73
74const ThemeFont = Schema.Struct({ latin: Schema.String });
75
76const Inspected = Schema.Struct({
77 slides: Schema.Array(
78 Schema.Struct({
79 hidden: Schema.optional(Schema.Boolean),
80 drawings: Schema.Array(Drawing),
81 }).pipe(Schema.encodeKeys({ drawings: "shapes" })),
82 ),
83 layouts: Schema.optional(
84 Schema.Array(
85 Schema.Struct({ drawings: Schema.Array(Drawing) }).pipe(
86 Schema.encodeKeys({ drawings: "shapes" }),
87 ),
88 ),
89 ),
90 masters: Schema.optional(
91 Schema.Array(
92 Schema.Struct({
93 drawings: Schema.Array(Drawing),
94 textStyles: Schema.optional(
95 Schema.NullOr(
96 Schema.Record(
97 Schema.String,
98 Schema.Array(Schema.Struct({ defaultRun: Schema.optional(Schema.NullOr(RunStyle)) })),
99 ),
100 ),
101 ),
102 }).pipe(Schema.encodeKeys({ drawings: "shapes" })),
103 ),
104 ),
105 themes: Schema.optional(
106 Schema.Array(
107 Schema.Struct({
108 theme: Schema.optional(
109 Schema.NullOr(
110 Schema.Struct({
111 fontScheme: Schema.optional(
112 Schema.NullOr(Schema.Struct({ majorFont: ThemeFont, minorFont: ThemeFont })),
113 ),
114 }),
115 ),
116 ),
117 }),
118 ),
119 ),
120});
121
122const decodeInspected = Schema.decodeUnknownOption(Inspected);
123
124const scriptRanges: readonly (readonly [FallbackScript, RegExp])[] = [
125 ["hebrew", /[\u0590-\u05FF\uFB1D-\uFB4F]/u],
126 ["arabic", /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/u],
127];
128
129/**
130 * Reads the families, styles and scripts a deck's text uses, from its slides, layouts, masters and theme. When the
131 * engine's inspection does not decode, the slides' own runs stand in, without theme fonts or hidden flags.
132 */
133export function deckText(bytes: Uint8Array, snapshot: DeckSnapshot): DeckText {
134 return Option.match(decodeInspected(inspectPresentation(withoutMedia(bytes))), {
135 onNone: () => fromSnapshot(snapshot),
136 onSome: (inspected) => {
137 const schemes =
138 inspected.themes?.flatMap((theme) =>
139 theme.theme?.fontScheme ? [theme.theme.fontScheme] : [],
140 ) ?? [];
141 const minor = schemes[0]?.minorFont.latin ?? "";
142
143 const drawings = [
144 ...inspected.slides.flatMap((slide) => slide.drawings),
145 ...(inspected.layouts ?? []).flatMap((layout) => layout.drawings),
146 ...(inspected.masters ?? []).flatMap((master) => master.drawings),
147 ];
148
149 const defaults = (inspected.masters ?? []).flatMap((master) =>
150 Object.values(master.textStyles ?? {}).flatMap((levels) =>
151 levels.flatMap((level) =>
152 level.defaultRun ? [{ text: "", style: level.defaultRun }] : [],
153 ),
154 ),
155 );
156
157 return summarize(
158 [...drawings.flatMap(drawingRuns), ...defaults].flatMap((run) => {
159 const family = run.style?.fontFamily;
160 if (!schemes.length || (family && !family.startsWith("+mn") && !family.startsWith("+mj")))
161 return [run];
162 return schemes.map((scheme) => ({
163 ...run,
164 style: {
165 ...run.style,
166 fontFamily: family?.startsWith("+mj")
167 ? scheme.majorFont.latin
168 : scheme.minorFont.latin,
169 },
170 }));
171 }),
172 (family) => (family?.startsWith("+") ? "" : (family ?? "")),
173 minor,
174 inspected.slides.map((slide) => slide.hidden ?? false),
175 );
176 },
177 });
178}
179
180/** A file in the deck's zip package: where its central directory record and its local data sit. */
181type Entry = {
182 readonly name: string;
183 readonly record: number;
184 readonly length: number;
185 readonly local: number;
186};
187
188/**
189 * The package without its pictures and media. The inspection reads only the deck's text and styles, but returns every
190 * picture as base64, which for a deck of photos costs tens of megabytes of engine memory the worker never gives back.
191 * Entries keep their compressed bytes. A package this cannot read, such as a ZIP64 one, stays as it is.
192 */
193function withoutMedia(bytes: Uint8Array): Uint8Array {
194 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
195 const end = endOfDirectory(view);
196
197 if (end === undefined) return bytes;
198
199 const count = view.getUint16(end + 10, true);
200 const directory = view.getUint32(end + 16, true);
201
202 if (count === 0xffff || directory === 0xffffffff || directory > end) return bytes;
203
204 const entries = readEntries(view, directory, end, count);
205
206 if (!entries || !entries.some((entry) => entry.name.startsWith("ppt/media/"))) return bytes;
207
208 // An entry's local header and data run up to the next entry's, or to the central directory.
209 const starts = entries.map((entry) => entry.local).toSorted((left, right) => left - right);
210
211 const kept = entries
212 .filter((entry) => !entry.name.startsWith("ppt/media/"))
213 .map((entry) => ({
214 entry,
215 start: entry.local,
216 end: starts.find((start) => start > entry.local) ?? directory,
217 }));
218
219 // Where each kept entry's local data and directory record land in the new package.
220 const locals = offsets(kept.map((part) => part.end - part.start));
221 const records = offsets(kept.map((part) => part.entry.length));
222 const size = locals.at(-1) ?? 0;
223 const directorySize = records.at(-1) ?? 0;
224 const out = new Uint8Array(size + directorySize + 22);
225 const writer = new DataView(out.buffer);
226
227 kept.forEach((part, index) => {
228 const local = locals[index] ?? 0;
229 const record = size + (records[index] ?? 0);
230
231 out.set(bytes.subarray(part.start, part.end), local);
232 out.set(bytes.subarray(part.entry.record, part.entry.record + part.entry.length), record);
233 writer.setUint32(record + 42, local, true);
234 });
235
236 const tail = size + directorySize;
237
238 out.set(bytes.subarray(end, end + 22), tail);
239 writer.setUint16(tail + 8, kept.length, true);
240 writer.setUint16(tail + 10, kept.length, true);
241 writer.setUint32(tail + 12, directorySize, true);
242 writer.setUint32(tail + 16, size, true);
243 writer.setUint16(tail + 20, 0, true);
244
245 return out;
246}
247
248/** Where each length starts when they are laid end to end, then where the last ends. */
249function offsets(lengths: readonly number[]) {
250 return lengths.reduce(
251 (list, length) => {
252 list.push((list.at(-1) ?? 0) + length);
253
254 return list;
255 },
256 [0],
257 );
258}
259
260/** Where the end of central directory record starts, searched back from the end past any comment. */
261function endOfDirectory(view: DataView) {
262 const last = view.byteLength - 22;
263 const first = Math.max(0, last - 0xffff);
264
265 for (let at = last; at >= first; at--) if (view.getUint32(at, true) === 0x06054b50) return at;
266
267 return undefined;
268}
269
270/**
271 * The central directory's records, from `directory` up to the end record at `end`; undefined when one is malformed: it
272 * runs past the directory, or its local header does not sit before it.
273 */
274function readEntries(view: DataView, directory: number, end: number, count: number) {
275 const decoder = new TextDecoder();
276
277 return Array.from({ length: count }).reduce<{ at: number; entries: Entry[] } | undefined>(
278 (state) => {
279 if (!state || state.at + 46 > end || view.getUint32(state.at, true) !== 0x02014b50)
280 return undefined;
281
282 const nameLength = view.getUint16(state.at + 28, true);
283 const length =
284 46 + nameLength + view.getUint16(state.at + 30, true) + view.getUint16(state.at + 32, true);
285 const local = view.getUint32(state.at + 42, true);
286
287 // A local header is 30 bytes before its name and data.
288 if (state.at + length > end || local + 30 > directory) return undefined;
289
290 const name = decoder.decode(
291 new Uint8Array(view.buffer, view.byteOffset + state.at + 46, nameLength),
292 );
293
294 state.entries.push({ name, record: state.at, length, local });
295
296 return { at: state.at + length, entries: state.entries };
297 },
298 { at: directory, entries: [] },
299 )?.entries;
300}
301
302type Run = { readonly text: string; readonly style: typeof RunStyle.Type | null | undefined };
303
304function drawingRuns(drawing: Drawing): Run[] {
305 return [
306 ...bodyRuns(drawing.text),
307 ...(drawing.data?.rows ?? []).flatMap((row) =>
308 row.cells.flatMap((cell) => bodyRuns(cell.text)),
309 ),
310 ...(drawing.children ?? []).flatMap(drawingRuns),
311 ];
312}
313
314function bodyRuns(body: typeof Body.Type | null | undefined): Run[] {
315 return (body?.paragraphs ?? []).flatMap((paragraph) =>
316 paragraph.runs.map((run) => ({
317 text: run.text,
318 style: {
319 fontFamily: run.properties?.fontFamily ?? paragraph.properties?.defaultRun?.fontFamily,
320 bold: run.properties?.bold ?? paragraph.properties?.defaultRun?.bold,
321 italic: run.properties?.italic ?? paragraph.properties?.defaultRun?.italic,
322 },
323 })),
324 );
325}
326
327function fromSnapshot(snapshot: DeckSnapshot): DeckText {
328 const runs = (drawings: DeckSnapshot["slides"][number]["shapes"]): Run[] =>
329 drawings.flatMap((drawing) => [
330 ...drawing.textStories.flatMap((story) =>
331 story.paragraphs.flatMap((paragraph) =>
332 paragraph.runs.map((run) => ({ text: run.text, style: run.style })),
333 ),
334 ),
335 ...runs(drawing.children),
336 ]);
337
338 return summarize(
339 snapshot.slides.flatMap((slide) => runs(slide.shapes)),
340 (family) => family ?? "",
341 "",
342 snapshot.slides.map(() => false),
343 );
344}
345
346/**
347 * Groups runs by the family they resolve to: the theme's body font first, then by how much text each draws. The
348 * masters' default runs count too, so a theme font that placeholders inherit without naming it is still found.
349 */
350function summarize(
351 runs: readonly Run[],
352 resolve: (family: string | null | undefined) => string,
353 theme: string,
354 hidden: readonly boolean[],
355): DeckText {
356 const families = new Map<
357 string,
358 { name: string; weight: number; styles: Map<string, FontStyle> }
359 >();
360 const body = theme.trim().toLowerCase();
361 const text = runs.map((run) => run.text).join("");
362
363 runs.forEach((run) => {
364 const name = resolve(run.style?.fontFamily).trim();
365
366 if (!name) return;
367
368 const style = { bold: run.style?.bold ?? false, italic: run.style?.italic ?? false };
369 const family = families.get(name.toLowerCase()) ?? {
370 name,
371 weight: 0,
372 styles: new Map<string, FontStyle>(),
373 };
374
375 family.weight += run.text.length;
376 family.styles.set(`${style.bold}|${style.italic}`, style);
377 families.set(name.toLowerCase(), family);
378 });
379
380 return {
381 families: [...families.entries()]
382 .toSorted((left, right) => rank(right, body) - rank(left, body))
383 .map((entry) => ({
384 name: entry[1].name,
385 // Regular first, so a family's first face is the one its unstyled text draws with.
386 styles: [...entry[1].styles.values()].toSorted(
387 (left, right) => styleRank(left) - styleRank(right),
388 ),
389 })),
390 scripts: scriptRanges.flatMap((entry) => (entry[1].test(text) ? [entry[0]] : [])),
391 hidden,
392 };
393}
394
395function rank(entry: readonly [string, { readonly weight: number }], body: string) {
396 return entry[0] === body ? Number.POSITIVE_INFINITY : entry[1].weight;
397}
398
399function styleRank(style: FontStyle) {
400 return (style.bold ? 1 : 0) + (style.italic ? 2 : 0);
401}