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