@open-slide/core 2.0.0-beta.1 → 2.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/{config-AtA2Bqtn.d.ts → config-DjWifhaA.d.ts} +1 -1
  2. package/dist/index.d.ts +3 -2
  3. package/dist/index.js +1 -1
  4. package/dist/locale/index.d.ts +1 -1
  5. package/dist/locale/index.js +1 -1
  6. package/dist/{types-BzPSOxe-.d.ts → types-BWg-Dtbg.d.ts} +1 -2
  7. package/dist/vite/index.d.ts +1 -1
  8. package/dist/{zh-tw-BxZ_pYqe.js → zh-tw-DlKyeNX7.js} +4 -8
  9. package/package.json +1 -1
  10. package/skills/slide-authoring/SKILL.md +3 -3
  11. package/skills/slide-authoring/references/morph.md +5 -5
  12. package/skills/slide-authoring/references/transitions.md +38 -37
  13. package/skills/slide-authoring/references/webfonts.md +25 -6
  14. package/src/app/components/command/slide-command-menu.tsx +10 -0
  15. package/src/app/components/slide-transition-layer.tsx +8 -1
  16. package/src/app/lib/export-pptx.ts +122 -193
  17. package/src/app/lib/pptx/color.ts +49 -0
  18. package/src/app/lib/pptx/css.test.ts +172 -0
  19. package/src/app/lib/pptx/css.ts +450 -0
  20. package/src/app/lib/pptx/fonts.ts +145 -0
  21. package/src/app/lib/pptx/images.ts +116 -0
  22. package/src/app/lib/pptx/measure.ts +1299 -0
  23. package/src/app/lib/pptx/ooxml.test.ts +199 -0
  24. package/src/app/lib/pptx/ooxml.ts +470 -0
  25. package/src/app/lib/pptx/raster.ts +189 -0
  26. package/src/app/lib/pptx/render.ts +102 -0
  27. package/src/app/lib/pptx/scene.ts +116 -0
  28. package/src/app/lib/pptx/text-lines.test.ts +82 -0
  29. package/src/app/lib/pptx/text-lines.ts +109 -0
  30. package/src/app/lib/pptx/units.ts +22 -0
  31. package/src/app/lib/transition.test.ts +31 -0
  32. package/src/app/lib/transition.ts +13 -0
  33. package/src/app/routes/slide.tsx +21 -27
  34. package/src/locale/en.ts +1 -3
  35. package/src/locale/ja.ts +1 -3
  36. package/src/locale/types.ts +1 -2
  37. package/src/locale/zh-cn.ts +1 -2
  38. package/src/locale/zh-tw.ts +1 -2
@@ -0,0 +1,450 @@
1
+ export type Rgba = { r: number; g: number; b: number; a: number };
2
+ export type ColorParser = (value: string) => Rgba | null;
3
+
4
+ export function splitTopLevel(value: string, separator = ','): string[] {
5
+ const parts: string[] = [];
6
+ let depth = 0;
7
+ let start = 0;
8
+ let quote: string | null = null;
9
+ for (let i = 0; i < value.length; i++) {
10
+ const ch = value[i];
11
+ if (quote) {
12
+ if (ch === quote) quote = null;
13
+ continue;
14
+ }
15
+ if (ch === '"' || ch === "'") quote = ch;
16
+ else if (ch === '(') depth++;
17
+ else if (ch === ')') depth = Math.max(0, depth - 1);
18
+ else if (ch === separator && depth === 0) {
19
+ parts.push(value.slice(start, i).trim());
20
+ start = i + 1;
21
+ }
22
+ }
23
+ parts.push(value.slice(start).trim());
24
+ return parts.filter((p) => p.length > 0);
25
+ }
26
+
27
+ function clamp01(n: number): number {
28
+ return Math.min(1, Math.max(0, n));
29
+ }
30
+
31
+ function channel(token: string): number {
32
+ const t = token.trim();
33
+ if (t.endsWith('%')) return Math.round((Number.parseFloat(t) / 100) * 255);
34
+ return Math.round(Number.parseFloat(t));
35
+ }
36
+
37
+ function alphaChannel(token: string | undefined): number {
38
+ if (token === undefined) return 1;
39
+ const t = token.trim();
40
+ if (t.endsWith('%')) return clamp01(Number.parseFloat(t) / 100);
41
+ return clamp01(Number.parseFloat(t));
42
+ }
43
+
44
+ export function parseColor(input: string): Rgba | null {
45
+ const value = input.trim().toLowerCase();
46
+ if (value === 'transparent') return { r: 0, g: 0, b: 0, a: 0 };
47
+ if (value.startsWith('#')) {
48
+ const hex = value.slice(1);
49
+ const expand = (s: string) => Number.parseInt(s.length === 1 ? s + s : s, 16);
50
+ if (hex.length === 3 || hex.length === 4) {
51
+ return {
52
+ r: expand(hex[0]),
53
+ g: expand(hex[1]),
54
+ b: expand(hex[2]),
55
+ a: hex.length === 4 ? expand(hex[3]) / 255 : 1,
56
+ };
57
+ }
58
+ if (hex.length === 6 || hex.length === 8) {
59
+ return {
60
+ r: expand(hex.slice(0, 2)),
61
+ g: expand(hex.slice(2, 4)),
62
+ b: expand(hex.slice(4, 6)),
63
+ a: hex.length === 8 ? expand(hex.slice(6, 8)) / 255 : 1,
64
+ };
65
+ }
66
+ return null;
67
+ }
68
+ const m = /^rgba?\((.*)\)$/.exec(value);
69
+ if (!m) return null;
70
+ const body = m[1].trim();
71
+ let parts: string[];
72
+ let alpha: string | undefined;
73
+ if (body.includes(',')) {
74
+ parts = body.split(',').map((p) => p.trim());
75
+ alpha = parts[3];
76
+ parts = parts.slice(0, 3);
77
+ } else {
78
+ const [channels, a] = body.split('/');
79
+ parts = channels.trim().split(/\s+/);
80
+ alpha = a?.trim();
81
+ }
82
+ if (parts.length !== 3) return null;
83
+ const [r, g, b] = parts.map(channel);
84
+ if ([r, g, b].some((n) => Number.isNaN(n))) return null;
85
+ return { r, g, b, a: alphaChannel(alpha) };
86
+ }
87
+
88
+ export function isVisibleColor(color: Rgba | null): color is Rgba {
89
+ return color !== null && color.a > 0.002;
90
+ }
91
+
92
+ export function toHex(color: Rgba): string {
93
+ const h = (n: number) =>
94
+ Math.min(255, Math.max(0, Math.round(n)))
95
+ .toString(16)
96
+ .padStart(2, '0');
97
+ return `${h(color.r)}${h(color.g)}${h(color.b)}`.toUpperCase();
98
+ }
99
+
100
+ export function withAlpha(color: Rgba, factor: number): Rgba {
101
+ return factor >= 1 ? color : { ...color, a: color.a * factor };
102
+ }
103
+
104
+ export function parsePx(value: string | null | undefined): number {
105
+ if (!value) return 0;
106
+ const n = Number.parseFloat(value);
107
+ return Number.isFinite(n) ? n : 0;
108
+ }
109
+
110
+ export type Mat = readonly [number, number, number, number, number, number];
111
+ export const IDENTITY: Mat = [1, 0, 0, 1, 0, 0];
112
+
113
+ export function parseTransform(value: string | null | undefined): Mat | null {
114
+ if (!value || value === 'none') return IDENTITY;
115
+ const m2 = /^matrix\((.*)\)$/.exec(value.trim());
116
+ if (m2) {
117
+ const n = m2[1].split(',').map((s) => Number.parseFloat(s));
118
+ if (n.length !== 6 || n.some((x) => !Number.isFinite(x))) return null;
119
+ return [n[0], n[1], n[2], n[3], n[4], n[5]];
120
+ }
121
+ const m3 = /^matrix3d\((.*)\)$/.exec(value.trim());
122
+ if (m3) {
123
+ const n = m3[1].split(',').map((s) => Number.parseFloat(s));
124
+ if (n.length !== 16 || n.some((x) => !Number.isFinite(x))) return null;
125
+ const eps = 1e-6;
126
+ const flat =
127
+ Math.abs(n[2]) < eps &&
128
+ Math.abs(n[3]) < eps &&
129
+ Math.abs(n[6]) < eps &&
130
+ Math.abs(n[7]) < eps &&
131
+ Math.abs(n[8]) < eps &&
132
+ Math.abs(n[9]) < eps &&
133
+ Math.abs(n[10] - 1) < eps &&
134
+ Math.abs(n[11]) < eps &&
135
+ Math.abs(n[14]) < eps &&
136
+ Math.abs(n[15] - 1) < eps;
137
+ if (!flat) return null;
138
+ return [n[0], n[1], n[4], n[5], n[12], n[13]];
139
+ }
140
+ return null;
141
+ }
142
+
143
+ export function multiply(m: Mat, n: Mat): Mat {
144
+ return [
145
+ m[0] * n[0] + m[2] * n[1],
146
+ m[1] * n[0] + m[3] * n[1],
147
+ m[0] * n[2] + m[2] * n[3],
148
+ m[1] * n[2] + m[3] * n[3],
149
+ m[0] * n[4] + m[2] * n[5] + m[4],
150
+ m[1] * n[4] + m[3] * n[5] + m[5],
151
+ ];
152
+ }
153
+
154
+ export function translation(x: number, y: number): Mat {
155
+ return [1, 0, 0, 1, x, y];
156
+ }
157
+
158
+ export function rotationDeg(deg: number): Mat {
159
+ const r = (deg * Math.PI) / 180;
160
+ const c = Math.cos(r);
161
+ const s = Math.sin(r);
162
+ return [c, s, -s, c, 0, 0];
163
+ }
164
+
165
+ export function scaling(sx: number, sy: number): Mat {
166
+ return [sx, 0, 0, sy, 0, 0];
167
+ }
168
+
169
+ export function applyToPoint(m: Mat, x: number, y: number): { x: number; y: number } {
170
+ return { x: m[0] * x + m[2] * y + m[4], y: m[1] * x + m[3] * y + m[5] };
171
+ }
172
+
173
+ export function isIdentity(m: Mat, eps = 1e-4): boolean {
174
+ return (
175
+ Math.abs(m[0] - 1) < eps &&
176
+ Math.abs(m[1]) < eps &&
177
+ Math.abs(m[2]) < eps &&
178
+ Math.abs(m[3] - 1) < eps &&
179
+ Math.abs(m[4]) < eps &&
180
+ Math.abs(m[5]) < eps
181
+ );
182
+ }
183
+
184
+ export function isTranslation(m: Mat, eps = 1e-4): boolean {
185
+ return (
186
+ Math.abs(m[0] - 1) < eps &&
187
+ Math.abs(m[1]) < eps &&
188
+ Math.abs(m[2]) < eps &&
189
+ Math.abs(m[3] - 1) < eps
190
+ );
191
+ }
192
+
193
+ export type Decomposed = {
194
+ rotationDeg: number;
195
+ scaleX: number;
196
+ scaleY: number;
197
+ flipV: boolean;
198
+ skewed: boolean;
199
+ };
200
+
201
+ export function decompose(m: Mat): Decomposed | null {
202
+ const [a, b, c, d] = m;
203
+ const scaleX = Math.hypot(a, b);
204
+ if (scaleX < 1e-9) return null;
205
+ const det = a * d - b * c;
206
+ const scaleY = det / scaleX;
207
+ if (Math.abs(scaleY) < 1e-9) return null;
208
+ const skew = (a * c + b * d) / (scaleX * scaleX);
209
+ const rotation = (Math.atan2(b, a) * 180) / Math.PI;
210
+ return {
211
+ rotationDeg: rotation,
212
+ scaleX,
213
+ scaleY: Math.abs(scaleY),
214
+ flipV: scaleY < 0,
215
+ skewed: Math.abs(skew) > 1e-3,
216
+ };
217
+ }
218
+
219
+ export function transformedBounds(
220
+ m: Mat,
221
+ x: number,
222
+ y: number,
223
+ w: number,
224
+ h: number,
225
+ ): { x: number; y: number; w: number; h: number } {
226
+ const pts = [
227
+ applyToPoint(m, x, y),
228
+ applyToPoint(m, x + w, y),
229
+ applyToPoint(m, x, y + h),
230
+ applyToPoint(m, x + w, y + h),
231
+ ];
232
+ const xs = pts.map((p) => p.x);
233
+ const ys = pts.map((p) => p.y);
234
+ const minX = Math.min(...xs);
235
+ const minY = Math.min(...ys);
236
+ return { x: minX, y: minY, w: Math.max(...xs) - minX, h: Math.max(...ys) - minY };
237
+ }
238
+
239
+ export function parseAngleDeg(token: string): number | null {
240
+ const m = /^(-?[\d.]+)(deg|turn|rad|grad)$/.exec(token.trim());
241
+ if (!m) return null;
242
+ const n = Number.parseFloat(m[1]);
243
+ switch (m[2]) {
244
+ case 'deg':
245
+ return n;
246
+ case 'turn':
247
+ return n * 360;
248
+ case 'rad':
249
+ return (n * 180) / Math.PI;
250
+ case 'grad':
251
+ return n * 0.9;
252
+ }
253
+ return null;
254
+ }
255
+
256
+ export type GradientStop = { color: Rgba; pos: number };
257
+ export type LinearGradient = { angleDeg: number; stops: GradientStop[] };
258
+
259
+ function sideOrCornerAngle(spec: string, w: number, h: number): number | null {
260
+ const words = spec
261
+ .replace(/^to\s+/, '')
262
+ .split(/\s+/)
263
+ .sort()
264
+ .join(' ');
265
+ const corner = (Math.atan2(w, h) * 180) / Math.PI;
266
+ switch (words) {
267
+ case 'top':
268
+ return 0;
269
+ case 'right':
270
+ return 90;
271
+ case 'bottom':
272
+ return 180;
273
+ case 'left':
274
+ return 270;
275
+ case 'right top':
276
+ return corner;
277
+ case 'bottom right':
278
+ return 180 - corner;
279
+ case 'bottom left':
280
+ return 180 + corner;
281
+ case 'left top':
282
+ return 360 - corner;
283
+ }
284
+ return null;
285
+ }
286
+
287
+ export function gradientLineLength(angleDeg: number, w: number, h: number): number {
288
+ const r = (angleDeg * Math.PI) / 180;
289
+ return Math.abs(w * Math.sin(r)) + Math.abs(h * Math.cos(r));
290
+ }
291
+
292
+ export function parseLinearGradient(
293
+ layer: string,
294
+ w: number,
295
+ h: number,
296
+ colorParser: ColorParser = parseColor,
297
+ ): LinearGradient | null {
298
+ const m = /^linear-gradient\((.*)\)$/s.exec(layer.trim());
299
+ if (!m) return null;
300
+ const args = splitTopLevel(m[1]);
301
+ if (args.length < 2) return null;
302
+ let angle = 180;
303
+ let first = args[0];
304
+ const explicitAngle = parseAngleDeg(first);
305
+ if (explicitAngle !== null) {
306
+ angle = explicitAngle;
307
+ args.shift();
308
+ } else if (first.startsWith('to ')) {
309
+ const a = sideOrCornerAngle(first, w, h);
310
+ if (a === null) return null;
311
+ angle = a;
312
+ args.shift();
313
+ }
314
+ first = args[0];
315
+ const length = gradientLineLength(angle, w, h) || 1;
316
+ const raw: { color: Rgba; pos: number | null }[] = [];
317
+ for (const arg of args) {
318
+ const tokens = splitTopLevel(arg, ' ');
319
+ const colorToken = tokens.find((t) => colorParser(t) !== null);
320
+ if (!colorToken) {
321
+ if (tokens.length === 1 && /^[\d.]+(%|px)$/.test(tokens[0])) continue;
322
+ return null;
323
+ }
324
+ const color = colorParser(colorToken);
325
+ if (!color) return null;
326
+ const positions = tokens.filter((t) => t !== colorToken);
327
+ if (positions.length === 0) {
328
+ raw.push({ color, pos: null });
329
+ continue;
330
+ }
331
+ for (const p of positions) {
332
+ const pos = parseStopPosition(p, length);
333
+ if (pos === null) return null;
334
+ raw.push({ color, pos });
335
+ }
336
+ }
337
+ if (raw.length < 2) return null;
338
+ if (raw[0].pos === null) raw[0].pos = 0;
339
+ if (raw[raw.length - 1].pos === null) raw[raw.length - 1].pos = 1;
340
+ let running = 0;
341
+ for (let i = 0; i < raw.length; i++) {
342
+ const stop = raw[i];
343
+ if (stop.pos === null) {
344
+ let j = i + 1;
345
+ while (raw[j].pos === null) j++;
346
+ const end = raw[j].pos as number;
347
+ const count = j - i + 1;
348
+ for (let k = i; k < j; k++) raw[k].pos = running + ((end - running) * (k - i + 1)) / count;
349
+ }
350
+ const pos = Math.max(running, stop.pos as number);
351
+ stop.pos = pos;
352
+ running = pos;
353
+ }
354
+ const stops = raw.map((s) => ({ color: s.color, pos: clamp01(s.pos as number) }));
355
+ return { angleDeg: ((angle % 360) + 360) % 360, stops };
356
+ }
357
+
358
+ function parseStopPosition(token: string, length: number): number | null {
359
+ const t = token.trim();
360
+ if (t.endsWith('%')) return Number.parseFloat(t) / 100;
361
+ if (t.endsWith('px')) return Number.parseFloat(t) / length;
362
+ if (t === '0') return 0;
363
+ return null;
364
+ }
365
+
366
+ export type Shadow = {
367
+ x: number;
368
+ y: number;
369
+ blur: number;
370
+ spread: number;
371
+ color: Rgba;
372
+ inset: boolean;
373
+ };
374
+
375
+ export function parseShadows(value: string, colorParser: ColorParser = parseColor): Shadow[] {
376
+ if (!value || value === 'none') return [];
377
+ const out: Shadow[] = [];
378
+ for (const layer of splitTopLevel(value)) {
379
+ const tokens = splitTopLevel(layer, ' ');
380
+ let inset = false;
381
+ let color: Rgba | null = null;
382
+ const lengths: number[] = [];
383
+ for (const token of tokens) {
384
+ if (token === 'inset') inset = true;
385
+ else if (/^-?[\d.]+(px)?$/.test(token)) lengths.push(Number.parseFloat(token));
386
+ else {
387
+ const c = colorParser(token);
388
+ if (c) color = c;
389
+ }
390
+ }
391
+ if (!color || lengths.length < 2) continue;
392
+ out.push({
393
+ x: lengths[0],
394
+ y: lengths[1],
395
+ blur: Math.max(0, lengths[2] ?? 0),
396
+ spread: lengths[3] ?? 0,
397
+ color,
398
+ inset,
399
+ });
400
+ }
401
+ return out;
402
+ }
403
+
404
+ export type CornerRadius = { x: number; y: number };
405
+ export type Radii = [CornerRadius, CornerRadius, CornerRadius, CornerRadius];
406
+
407
+ export function parseCornerRadius(value: string, w: number, h: number): CornerRadius {
408
+ const parts = value.trim().split(/\s+/);
409
+ const resolve = (token: string, base: number) =>
410
+ token.endsWith('%') ? (Number.parseFloat(token) / 100) * base : parsePx(token);
411
+ const x = Math.max(0, resolve(parts[0] ?? '0', w));
412
+ const y = Math.max(0, resolve(parts[1] ?? parts[0] ?? '0', h));
413
+ return { x, y };
414
+ }
415
+
416
+ export function normalizeRadii(radii: Radii, w: number, h: number): Radii {
417
+ const [tl, tr, br, bl] = radii;
418
+ const factors = [
419
+ w / Math.max(1e-9, tl.x + tr.x),
420
+ h / Math.max(1e-9, tr.y + br.y),
421
+ w / Math.max(1e-9, br.x + bl.x),
422
+ h / Math.max(1e-9, bl.y + tl.y),
423
+ ];
424
+ const f = Math.min(1, ...factors);
425
+ const scale = (c: CornerRadius): CornerRadius => ({ x: c.x * f, y: c.y * f });
426
+ return [scale(tl), scale(tr), scale(br), scale(bl)];
427
+ }
428
+
429
+ export function hasRadius(radii: Radii): boolean {
430
+ return radii.some((c) => c.x > 0.01 && c.y > 0.01);
431
+ }
432
+
433
+ export function parseBlurPx(filter: string): number {
434
+ if (!filter || filter === 'none') return 0;
435
+ let total = 0;
436
+ for (const m of filter.matchAll(/blur\(\s*(-?[\d.]+)px\s*\)/g)) total += Number.parseFloat(m[1]);
437
+ return total;
438
+ }
439
+
440
+ export function parseFontFamilies(value: string): string[] {
441
+ return splitTopLevel(value).map((f) => f.replace(/^["']|["']$/g, '').trim());
442
+ }
443
+
444
+ export function applyTextTransform(text: string, transform: string): string {
445
+ if (transform.includes('uppercase')) return text.toUpperCase();
446
+ if (transform.includes('lowercase')) return text.toLowerCase();
447
+ if (transform.includes('capitalize'))
448
+ return text.replace(/(^|[\s(\-"'])(\p{L})/gu, (_, p, c) => p + c.toUpperCase());
449
+ return text;
450
+ }
@@ -0,0 +1,145 @@
1
+ import { parseFontFamilies } from './css';
2
+
3
+ type Platform = 'mac' | 'win' | 'other';
4
+
5
+ const GENERIC = new Set([
6
+ 'system-ui',
7
+ '-apple-system',
8
+ 'blinkmacsystemfont',
9
+ 'ui-sans-serif',
10
+ 'ui-serif',
11
+ 'ui-monospace',
12
+ 'ui-rounded',
13
+ 'sans-serif',
14
+ 'serif',
15
+ 'monospace',
16
+ 'cursive',
17
+ 'fantasy',
18
+ 'math',
19
+ 'emoji',
20
+ 'fangsong',
21
+ ]);
22
+
23
+ const GENERIC_MAP: Record<Platform, Record<string, string>> = {
24
+ mac: {
25
+ system: 'Helvetica Neue',
26
+ sans: 'Helvetica',
27
+ serif: 'Times New Roman',
28
+ mono: 'Menlo',
29
+ cursive: 'Apple Chancery',
30
+ fantasy: 'Papyrus',
31
+ },
32
+ win: {
33
+ system: 'Segoe UI',
34
+ sans: 'Arial',
35
+ serif: 'Times New Roman',
36
+ mono: 'Consolas',
37
+ cursive: 'Comic Sans MS',
38
+ fantasy: 'Impact',
39
+ },
40
+ other: {
41
+ system: 'Arial',
42
+ sans: 'Arial',
43
+ serif: 'Times New Roman',
44
+ mono: 'Courier New',
45
+ cursive: 'Comic Sans MS',
46
+ fantasy: 'Impact',
47
+ },
48
+ };
49
+
50
+ function detectPlatform(): Platform {
51
+ if (typeof navigator === 'undefined') return 'other';
52
+ const nav = navigator as Navigator & { userAgentData?: { platform?: string } };
53
+ const p = (nav.userAgentData?.platform ?? navigator.platform ?? '').toLowerCase();
54
+ if (p.includes('mac') || p.includes('iphone') || p.includes('ipad')) return 'mac';
55
+ if (p.includes('win')) return 'win';
56
+ return 'other';
57
+ }
58
+
59
+ function mapGeneric(family: string, platform: Platform): string {
60
+ const map = GENERIC_MAP[platform];
61
+ switch (family.toLowerCase()) {
62
+ case 'system-ui':
63
+ case '-apple-system':
64
+ case 'blinkmacsystemfont':
65
+ case 'ui-sans-serif':
66
+ case 'ui-rounded':
67
+ return map.system;
68
+ case 'serif':
69
+ case 'ui-serif':
70
+ case 'fangsong':
71
+ return map.serif;
72
+ case 'monospace':
73
+ case 'ui-monospace':
74
+ return map.mono;
75
+ case 'cursive':
76
+ return map.cursive;
77
+ case 'fantasy':
78
+ return map.fantasy;
79
+ case 'math':
80
+ return 'Cambria Math';
81
+ default:
82
+ return map.sans;
83
+ }
84
+ }
85
+
86
+ const PROBE_TEXT = 'mmmmmmmmmmlliWWwwIIi@#0123';
87
+ const availability = new Map<string, boolean>();
88
+ const resolved = new Map<string, string>();
89
+ let probeCtx: CanvasRenderingContext2D | null | undefined;
90
+
91
+ function probe(): CanvasRenderingContext2D | null {
92
+ if (probeCtx === undefined) {
93
+ probeCtx = document.createElement('canvas').getContext('2d');
94
+ }
95
+ return probeCtx;
96
+ }
97
+
98
+ function widthWith(ctx: CanvasRenderingContext2D, font: string): number {
99
+ ctx.font = `72px ${font}`;
100
+ return ctx.measureText(PROBE_TEXT).width;
101
+ }
102
+
103
+ export function isFontAvailable(family: string): boolean {
104
+ const cached = availability.get(family);
105
+ if (cached !== undefined) return cached;
106
+ const ctx = probe();
107
+ let available = false;
108
+ if (ctx) {
109
+ const quoted = `"${family.replace(/"/g, '')}"`;
110
+ for (const base of ['monospace', 'serif', 'sans-serif']) {
111
+ if (Math.abs(widthWith(ctx, `${quoted}, ${base}`) - widthWith(ctx, base)) > 0.01) {
112
+ available = true;
113
+ break;
114
+ }
115
+ }
116
+ }
117
+ availability.set(family, available);
118
+ return available;
119
+ }
120
+
121
+ /**
122
+ * PowerPoint needs one concrete family name, so pick the first entry of the CSS
123
+ * stack that the browser can actually render, mapping generic keywords to the
124
+ * platform's default face.
125
+ */
126
+ export function resolveFontFamily(stack: string): string {
127
+ const cached = resolved.get(stack);
128
+ if (cached) return cached;
129
+ const platform = detectPlatform();
130
+ let result: string | null = null;
131
+ for (const family of parseFontFamilies(stack)) {
132
+ if (!family) continue;
133
+ if (GENERIC.has(family.toLowerCase())) {
134
+ result = mapGeneric(family, platform);
135
+ break;
136
+ }
137
+ if (isFontAvailable(family)) {
138
+ result = family;
139
+ break;
140
+ }
141
+ }
142
+ const out = result ?? mapGeneric('sans-serif', platform);
143
+ resolved.set(stack, out);
144
+ return out;
145
+ }
@@ -0,0 +1,116 @@
1
+ import type { ImageFormat, SceneImage } from './scene';
2
+
3
+ export type LoadedImage = { id: number; width: number; height: number };
4
+
5
+ function sniffFormat(bytes: Uint8Array): ImageFormat | 'other' {
6
+ if (bytes.length > 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e) return 'png';
7
+ if (bytes.length > 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff)
8
+ return 'jpeg';
9
+ if (bytes.length > 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) return 'gif';
10
+ const head = new TextDecoder('utf-8', { fatal: false })
11
+ .decode(bytes.subarray(0, Math.min(bytes.length, 512)))
12
+ .trimStart();
13
+ if (head.startsWith('<') && /<svg[\s>]/i.test(head)) return 'svg';
14
+ return 'other';
15
+ }
16
+
17
+ async function decodeSize(blob: Blob): Promise<{ width: number; height: number } | null> {
18
+ try {
19
+ const bitmap = await createImageBitmap(blob);
20
+ const size = { width: bitmap.width, height: bitmap.height };
21
+ bitmap.close();
22
+ return size;
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ async function encodePng(
29
+ source: CanvasImageSource,
30
+ width: number,
31
+ height: number,
32
+ ): Promise<Uint8Array | null> {
33
+ const canvas = document.createElement('canvas');
34
+ canvas.width = Math.max(1, Math.round(width));
35
+ canvas.height = Math.max(1, Math.round(height));
36
+ const ctx = canvas.getContext('2d');
37
+ if (!ctx) return null;
38
+ try {
39
+ ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
40
+ const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/png'));
41
+ return blob ? new Uint8Array(await blob.arrayBuffer()) : null;
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ function loadImageElement(url: string): Promise<HTMLImageElement | null> {
48
+ return new Promise((resolve) => {
49
+ const img = new Image();
50
+ img.crossOrigin = 'anonymous';
51
+ img.onload = () => resolve(img);
52
+ img.onerror = () => resolve(null);
53
+ img.src = url;
54
+ });
55
+ }
56
+
57
+ const SVG_RASTER_SCALE = 2;
58
+
59
+ export class ImageStore {
60
+ readonly images: SceneImage[] = [];
61
+ private readonly byKey = new Map<string, Promise<LoadedImage | null>>();
62
+ private nextId = 1;
63
+
64
+ add(bytes: Uint8Array, format: ImageFormat, svg?: Uint8Array): number {
65
+ const id = this.nextId++;
66
+ this.images.push({ id, bytes, format, svg });
67
+ return id;
68
+ }
69
+
70
+ fromUrl(url: string): Promise<LoadedImage | null> {
71
+ let pending = this.byKey.get(url);
72
+ if (!pending) {
73
+ pending = this.load(url);
74
+ this.byKey.set(url, pending);
75
+ }
76
+ return pending;
77
+ }
78
+
79
+ private async load(url: string): Promise<LoadedImage | null> {
80
+ let bytes: Uint8Array | null = null;
81
+ try {
82
+ const res = await fetch(url);
83
+ if (res.ok) bytes = new Uint8Array(await res.arrayBuffer());
84
+ } catch {}
85
+
86
+ if (bytes) {
87
+ const format = sniffFormat(bytes);
88
+ if (format === 'png' || format === 'jpeg' || format === 'gif') {
89
+ const size = await decodeSize(new Blob([bytes as BlobPart]));
90
+ if (!size) return null;
91
+ return { id: this.add(bytes, format), ...size };
92
+ }
93
+ if (format === 'svg') {
94
+ const img = await loadImageElement(url);
95
+ if (!img || img.naturalWidth === 0) return null;
96
+ const png = await encodePng(
97
+ img,
98
+ img.naturalWidth * SVG_RASTER_SCALE,
99
+ img.naturalHeight * SVG_RASTER_SCALE,
100
+ );
101
+ if (!png) return null;
102
+ return {
103
+ id: this.add(png, 'png', bytes),
104
+ width: img.naturalWidth,
105
+ height: img.naturalHeight,
106
+ };
107
+ }
108
+ }
109
+
110
+ const img = await loadImageElement(url);
111
+ if (!img || img.naturalWidth === 0) return null;
112
+ const png = await encodePng(img, img.naturalWidth, img.naturalHeight);
113
+ if (!png) return null;
114
+ return { id: this.add(png, 'png'), width: img.naturalWidth, height: img.naturalHeight };
115
+ }
116
+ }