The best way to control Claude Code, Codex and more from any computer or phone
| 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 | } |