@open-slide/core 2.0.0-beta.0 → 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 (46) hide show
  1. package/dist/build-Bzy-qlGc.js +19 -0
  2. package/dist/cli/bin.js +201 -21
  3. package/dist/{config-AtA2Bqtn.d.ts → config-DjWifhaA.d.ts} +1 -1
  4. package/dist/{dev-BChELmc-.js → dev-MXa5Tod4.js} +36 -10
  5. package/dist/index.d.ts +3 -2
  6. package/dist/index.js +1 -1
  7. package/dist/locale/index.d.ts +1 -1
  8. package/dist/locale/index.js +1 -1
  9. package/dist/preview-DEpQcKz3.js +24 -0
  10. package/dist/{types-BzPSOxe-.d.ts → types-BWg-Dtbg.d.ts} +1 -2
  11. package/dist/vite/index.d.ts +1 -1
  12. package/dist/vite/index.js +1 -1
  13. package/dist/{zh-tw-BxZ_pYqe.js → zh-tw-DlKyeNX7.js} +4 -8
  14. package/package.json +1 -1
  15. package/skills/slide-authoring/SKILL.md +3 -3
  16. package/skills/slide-authoring/references/morph.md +5 -5
  17. package/skills/slide-authoring/references/transitions.md +38 -37
  18. package/skills/slide-authoring/references/webfonts.md +25 -6
  19. package/src/app/components/command/slide-command-menu.tsx +10 -0
  20. package/src/app/components/slide-transition-layer.tsx +8 -1
  21. package/src/app/lib/export-pptx.ts +122 -193
  22. package/src/app/lib/pptx/color.ts +49 -0
  23. package/src/app/lib/pptx/css.test.ts +172 -0
  24. package/src/app/lib/pptx/css.ts +450 -0
  25. package/src/app/lib/pptx/fonts.ts +145 -0
  26. package/src/app/lib/pptx/images.ts +116 -0
  27. package/src/app/lib/pptx/measure.ts +1299 -0
  28. package/src/app/lib/pptx/ooxml.test.ts +199 -0
  29. package/src/app/lib/pptx/ooxml.ts +470 -0
  30. package/src/app/lib/pptx/raster.ts +189 -0
  31. package/src/app/lib/pptx/render.ts +102 -0
  32. package/src/app/lib/pptx/scene.ts +116 -0
  33. package/src/app/lib/pptx/text-lines.test.ts +82 -0
  34. package/src/app/lib/pptx/text-lines.ts +109 -0
  35. package/src/app/lib/pptx/units.ts +22 -0
  36. package/src/app/lib/transition.test.ts +31 -0
  37. package/src/app/lib/transition.ts +13 -0
  38. package/src/app/routes/slide.tsx +21 -27
  39. package/src/locale/en.ts +1 -3
  40. package/src/locale/ja.ts +1 -3
  41. package/src/locale/types.ts +1 -2
  42. package/src/locale/zh-cn.ts +1 -2
  43. package/src/locale/zh-tw.ts +1 -2
  44. package/dist/build-CfAxF6Dm.js +0 -14
  45. package/dist/preview-CcCQa268.js +0 -14
  46. package/dist/{config-C_VI2EpT.js → config-nbSvY7z_.js} +2 -2
@@ -0,0 +1,470 @@
1
+ import { strToU8 } from 'fflate';
2
+ import { type Radii, type Rgba, toHex } from './css';
3
+ import type {
4
+ Bullet,
5
+ DeckScene,
6
+ Fill,
7
+ Geometry,
8
+ ImageFormat,
9
+ Outline,
10
+ Paragraph,
11
+ PictureNode,
12
+ Rect,
13
+ Run,
14
+ SceneImage,
15
+ SceneNode,
16
+ ShadowEffect,
17
+ ShapeNode,
18
+ SlideScene,
19
+ TextNode,
20
+ } from './scene';
21
+ import { degrees, percent, px, pxToHundredthsPt, SLIDE_EMU_H, SLIDE_EMU_W } from './units';
22
+
23
+ const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
24
+ const REL_NS = 'http://schemas.openxmlformats.org/package/2006/relationships';
25
+ const OD_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
26
+ const NS_A = 'http://schemas.openxmlformats.org/drawingml/2006/main';
27
+ const NS_P = 'http://schemas.openxmlformats.org/presentationml/2006/main';
28
+ const NS_SVG = 'http://schemas.microsoft.com/office/drawing/2016/SVG/main';
29
+ const SVG_BLIP_URI = '{96DAC541-7B7A-43D3-8B79-37D633B846F1}';
30
+ const CT_PREFIX = 'application/vnd.openxmlformats-officedocument.presentationml';
31
+
32
+ const CONTENT_TYPES: Record<ImageFormat, string> = {
33
+ png: 'image/png',
34
+ jpeg: 'image/jpeg',
35
+ gif: 'image/gif',
36
+ svg: 'image/svg+xml',
37
+ };
38
+
39
+ export const PPTX_MIME = `${CT_PREFIX}.presentation`;
40
+
41
+ function isXmlChar(code: number): boolean {
42
+ if (code === 0x9 || code === 0xa || code === 0xd) return true;
43
+ return code >= 0x20 && code !== 0xfffe && code !== 0xffff;
44
+ }
45
+
46
+ export function escapeXml(value: string): string {
47
+ let clean = '';
48
+ for (const ch of value) {
49
+ if (isXmlChar(ch.codePointAt(0) ?? 0)) clean += ch;
50
+ }
51
+ return clean
52
+ .replace(/&/g, '&amp;')
53
+ .replace(/</g, '&lt;')
54
+ .replace(/>/g, '&gt;')
55
+ .replace(/"/g, '&quot;');
56
+ }
57
+
58
+ export function buildPptxFiles(deck: DeckScene): Record<string, Uint8Array> {
59
+ const files: Record<string, Uint8Array> = {};
60
+ const n = deck.slides.length;
61
+ const hasNotes = deck.slides.some((s) => s.notes);
62
+ const imageById = new Map(deck.images.map((img) => [img.id, img]));
63
+
64
+ files['[Content_Types].xml'] = strToU8(contentTypesXml(deck, hasNotes));
65
+ files['_rels/.rels'] = strToU8(rootRelsXml());
66
+ files['ppt/presentation.xml'] = strToU8(presentationXml(n, hasNotes));
67
+ files['ppt/_rels/presentation.xml.rels'] = strToU8(presentationRelsXml(n, hasNotes));
68
+ files['ppt/presProps.xml'] = strToU8(presPropsXml());
69
+ files['ppt/theme/theme1.xml'] = strToU8(themeXml());
70
+ files['ppt/slideMasters/slideMaster1.xml'] = strToU8(slideMasterXml());
71
+ files['ppt/slideMasters/_rels/slideMaster1.xml.rels'] = strToU8(slideMasterRelsXml());
72
+ files['ppt/slideLayouts/slideLayout1.xml'] = strToU8(slideLayoutXml());
73
+ files['ppt/slideLayouts/_rels/slideLayout1.xml.rels'] = strToU8(slideLayoutRelsXml());
74
+ if (hasNotes) {
75
+ files['ppt/notesMasters/notesMaster1.xml'] = strToU8(notesMasterXml());
76
+ files['ppt/notesMasters/_rels/notesMaster1.xml.rels'] = strToU8(notesMasterRelsXml());
77
+ files['ppt/theme/theme2.xml'] = strToU8(themeXml());
78
+ }
79
+
80
+ for (const image of deck.images) {
81
+ files[`ppt/media/${imageFileName(image)}`] = image.bytes;
82
+ if (image.svg) files[`ppt/media/image${image.id}.svg`] = image.svg;
83
+ }
84
+
85
+ deck.slides.forEach((slide, i) => {
86
+ const idx = i + 1;
87
+ const rels = new SlideRels();
88
+ const xml = slideXml(slide, rels, imageById);
89
+ files[`ppt/slides/slide${idx}.xml`] = strToU8(xml);
90
+ files[`ppt/slides/_rels/slide${idx}.xml.rels`] = strToU8(
91
+ slideRelsXml(rels, slide.notes ? idx : null),
92
+ );
93
+ if (slide.notes) {
94
+ files[`ppt/notesSlides/notesSlide${idx}.xml`] = strToU8(notesSlideXml(slide.notes));
95
+ files[`ppt/notesSlides/_rels/notesSlide${idx}.xml.rels`] = strToU8(notesSlideRelsXml(idx));
96
+ }
97
+ });
98
+
99
+ return files;
100
+ }
101
+
102
+ export function imageFileName(image: SceneImage): string {
103
+ return `image${image.id}.${image.format}`;
104
+ }
105
+
106
+ class SlideRels {
107
+ readonly entries: { id: string; type: string; target: string }[] = [
108
+ { id: 'rId1', type: `${OD_REL}/slideLayout`, target: '../slideLayouts/slideLayout1.xml' },
109
+ ];
110
+ private readonly byTarget = new Map<string, string>();
111
+
112
+ image(target: string): string {
113
+ const existing = this.byTarget.get(target);
114
+ if (existing) return existing;
115
+ const id = `rId${this.entries.length + 1}`;
116
+ this.entries.push({ id, type: `${OD_REL}/image`, target: `../media/${target}` });
117
+ this.byTarget.set(target, id);
118
+ return id;
119
+ }
120
+
121
+ notes(idx: number): void {
122
+ this.entries.push({
123
+ id: `rId${this.entries.length + 1}`,
124
+ type: `${OD_REL}/notesSlide`,
125
+ target: `../notesSlides/notesSlide${idx}.xml`,
126
+ });
127
+ }
128
+ }
129
+
130
+ function contentTypesXml(deck: DeckScene, hasNotes: boolean): string {
131
+ const defaults = [
132
+ `<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>`,
133
+ `<Default Extension="xml" ContentType="application/xml"/>`,
134
+ ...(['png', 'jpeg', 'gif', 'svg'] as const).map(
135
+ (ext) => `<Default Extension="${ext}" ContentType="${CONTENT_TYPES[ext]}"/>`,
136
+ ),
137
+ ];
138
+ const overrides = [
139
+ override('/ppt/presentation.xml', `${CT_PREFIX}.presentation.main+xml`),
140
+ override('/ppt/presProps.xml', `${CT_PREFIX}.presProps+xml`),
141
+ override('/ppt/slideMasters/slideMaster1.xml', `${CT_PREFIX}.slideMaster+xml`),
142
+ override('/ppt/slideLayouts/slideLayout1.xml', `${CT_PREFIX}.slideLayout+xml`),
143
+ override('/ppt/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'),
144
+ ];
145
+ if (hasNotes) {
146
+ overrides.push(
147
+ override('/ppt/notesMasters/notesMaster1.xml', `${CT_PREFIX}.notesMaster+xml`),
148
+ override('/ppt/theme/theme2.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'),
149
+ );
150
+ }
151
+ deck.slides.forEach((slide, i) => {
152
+ overrides.push(override(`/ppt/slides/slide${i + 1}.xml`, `${CT_PREFIX}.slide+xml`));
153
+ if (slide.notes) {
154
+ overrides.push(
155
+ override(`/ppt/notesSlides/notesSlide${i + 1}.xml`, `${CT_PREFIX}.notesSlide+xml`),
156
+ );
157
+ }
158
+ });
159
+ return `${XML_DECL}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${defaults.join('')}${overrides.join('')}</Types>`;
160
+ }
161
+
162
+ function override(partName: string, contentType: string): string {
163
+ return `<Override PartName="${partName}" ContentType="${contentType}"/>`;
164
+ }
165
+
166
+ function rootRelsXml(): string {
167
+ return `${XML_DECL}<Relationships xmlns="${REL_NS}"><Relationship Id="rId1" Type="${OD_REL}/officeDocument" Target="ppt/presentation.xml"/></Relationships>`;
168
+ }
169
+
170
+ function presentationXml(n: number, hasNotes: boolean): string {
171
+ const sldIds = Array.from(
172
+ { length: n },
173
+ (_, i) => `<p:sldId id="${256 + i}" r:id="rId${i + 3}"/>`,
174
+ ).join('');
175
+ const notesMaster = hasNotes
176
+ ? `<p:notesMasterIdLst><p:notesMasterId r:id="rId${n + 3}"/></p:notesMasterIdLst>`
177
+ : '';
178
+ return `${XML_DECL}<p:presentation xmlns:a="${NS_A}" xmlns:r="${OD_REL}" xmlns:p="${NS_P}" saveSubsetFonts="1"><p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst>${notesMaster}<p:sldIdLst>${sldIds}</p:sldIdLst><p:sldSz cx="${SLIDE_EMU_W}" cy="${SLIDE_EMU_H}"/><p:notesSz cx="6858000" cy="9144000"/></p:presentation>`;
179
+ }
180
+
181
+ function presentationRelsXml(n: number, hasNotes: boolean): string {
182
+ const rels = [
183
+ `<Relationship Id="rId1" Type="${OD_REL}/slideMaster" Target="slideMasters/slideMaster1.xml"/>`,
184
+ `<Relationship Id="rId2" Type="${OD_REL}/presProps" Target="presProps.xml"/>`,
185
+ ];
186
+ for (let i = 0; i < n; i++) {
187
+ rels.push(
188
+ `<Relationship Id="rId${i + 3}" Type="${OD_REL}/slide" Target="slides/slide${i + 1}.xml"/>`,
189
+ );
190
+ }
191
+ if (hasNotes) {
192
+ rels.push(
193
+ `<Relationship Id="rId${n + 3}" Type="${OD_REL}/notesMaster" Target="notesMasters/notesMaster1.xml"/>`,
194
+ );
195
+ }
196
+ return `${XML_DECL}<Relationships xmlns="${REL_NS}">${rels.join('')}</Relationships>`;
197
+ }
198
+
199
+ function presPropsXml(): string {
200
+ return `${XML_DECL}<p:presentationPr xmlns:a="${NS_A}" xmlns:r="${OD_REL}" xmlns:p="${NS_P}"/>`;
201
+ }
202
+
203
+ const EMPTY_GROUP = `<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>`;
204
+ const CLR_MAP = `bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"`;
205
+
206
+ function slideMasterXml(): string {
207
+ return `${XML_DECL}<p:sldMaster xmlns:a="${NS_A}" xmlns:r="${OD_REL}" xmlns:p="${NS_P}"><p:cSld><p:spTree>${EMPTY_GROUP}</p:spTree></p:cSld><p:clrMap ${CLR_MAP}/><p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst></p:sldMaster>`;
208
+ }
209
+
210
+ function slideMasterRelsXml(): string {
211
+ return `${XML_DECL}<Relationships xmlns="${REL_NS}"><Relationship Id="rId1" Type="${OD_REL}/slideLayout" Target="../slideLayouts/slideLayout1.xml"/><Relationship Id="rId2" Type="${OD_REL}/theme" Target="../theme/theme1.xml"/></Relationships>`;
212
+ }
213
+
214
+ function slideLayoutXml(): string {
215
+ return `${XML_DECL}<p:sldLayout xmlns:a="${NS_A}" xmlns:r="${OD_REL}" xmlns:p="${NS_P}" type="blank" preserve="1"><p:cSld name="Blank"><p:spTree>${EMPTY_GROUP}</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>`;
216
+ }
217
+
218
+ function slideLayoutRelsXml(): string {
219
+ return `${XML_DECL}<Relationships xmlns="${REL_NS}"><Relationship Id="rId1" Type="${OD_REL}/slideMaster" Target="../slideMasters/slideMaster1.xml"/></Relationships>`;
220
+ }
221
+
222
+ function notesMasterXml(): string {
223
+ return `${XML_DECL}<p:notesMaster xmlns:a="${NS_A}" xmlns:r="${OD_REL}" xmlns:p="${NS_P}"><p:cSld><p:bg><p:bgRef idx="1001"><a:schemeClr val="bg1"/></p:bgRef></p:bg><p:spTree>${EMPTY_GROUP}<p:sp><p:nvSpPr><p:cNvPr id="2" name="Slide Image Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1" noRot="1" noChangeAspect="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldImg" idx="2"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="1371600" y="685800"/><a:ext cx="4114800" cy="2314575"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln w="12700"><a:solidFill><a:prstClr val="black"/></a:solidFill></a:ln></p:spPr></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Notes Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" sz="quarter" idx="3"/></p:nvPr></p:nvSpPr><p:spPr><a:xfrm><a:off x="685800" y="4343400"/><a:ext cx="5486400" cy="4114800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr><p:txBody><a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0"/><a:lstStyle/><a:p><a:endParaRPr lang="en-US"/></a:p></p:txBody></p:sp></p:spTree></p:cSld><p:clrMap ${CLR_MAP}/><p:notesStyle><a:lvl1pPr marL="0" algn="l" defTabSz="914400" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"><a:defRPr sz="1200" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl1pPr></p:notesStyle></p:notesMaster>`;
224
+ }
225
+
226
+ function notesMasterRelsXml(): string {
227
+ return `${XML_DECL}<Relationships xmlns="${REL_NS}"><Relationship Id="rId1" Type="${OD_REL}/theme" Target="../theme/theme2.xml"/></Relationships>`;
228
+ }
229
+
230
+ function notesSlideXml(notes: string): string {
231
+ const paragraphs = notes
232
+ .split(/\r?\n/)
233
+ .map((line) =>
234
+ line.length === 0
235
+ ? `<a:p><a:endParaRPr lang="en-US"/></a:p>`
236
+ : `<a:p><a:r><a:rPr lang="en-US" dirty="0"/><a:t>${escapeXml(line)}</a:t></a:r></a:p>`,
237
+ )
238
+ .join('');
239
+ return `${XML_DECL}<p:notes xmlns:a="${NS_A}" xmlns:r="${OD_REL}" xmlns:p="${NS_P}"><p:cSld><p:spTree>${EMPTY_GROUP}<p:sp><p:nvSpPr><p:cNvPr id="2" name="Slide Image Placeholder 1"/><p:cNvSpPr><a:spLocks noGrp="1" noRot="1" noChangeAspect="1"/></p:cNvSpPr><p:nvPr><p:ph type="sldImg"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp><p:sp><p:nvSpPr><p:cNvPr id="3" name="Notes Placeholder 2"/><p:cNvSpPr><a:spLocks noGrp="1"/></p:cNvSpPr><p:nvPr><p:ph type="body" idx="1"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/>${paragraphs}</p:txBody></p:sp></p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:notes>`;
240
+ }
241
+
242
+ function notesSlideRelsXml(idx: number): string {
243
+ return `${XML_DECL}<Relationships xmlns="${REL_NS}"><Relationship Id="rId1" Type="${OD_REL}/notesMaster" Target="../notesMasters/notesMaster1.xml"/><Relationship Id="rId2" Type="${OD_REL}/slide" Target="../slides/slide${idx}.xml"/></Relationships>`;
244
+ }
245
+
246
+ function slideRelsXml(rels: SlideRels, notesIdx: number | null): string {
247
+ if (notesIdx !== null) rels.notes(notesIdx);
248
+ const body = rels.entries
249
+ .map((r) => `<Relationship Id="${r.id}" Type="${r.type}" Target="${r.target}"/>`)
250
+ .join('');
251
+ return `${XML_DECL}<Relationships xmlns="${REL_NS}">${body}</Relationships>`;
252
+ }
253
+
254
+ export function slideXml(
255
+ slide: SlideScene,
256
+ rels: SlideRels,
257
+ imageById: Map<number, SceneImage>,
258
+ ): string {
259
+ const ctx: EmitContext = { rels, imageById, nextId: 2 };
260
+ const bg = slide.background
261
+ ? `<p:bg><p:bgPr>${fillXml(slide.background, ctx)}<a:effectLst/></p:bgPr></p:bg>`
262
+ : '';
263
+ const shapes = slide.nodes.map((node) => nodeXml(node, ctx)).join('');
264
+ return `${XML_DECL}<p:sld xmlns:a="${NS_A}" xmlns:r="${OD_REL}" xmlns:p="${NS_P}"><p:cSld>${bg}<p:spTree>${EMPTY_GROUP}${shapes}</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>`;
265
+ }
266
+
267
+ type EmitContext = {
268
+ rels: SlideRels;
269
+ imageById: Map<number, SceneImage>;
270
+ nextId: number;
271
+ };
272
+
273
+ function nodeXml(node: SceneNode, ctx: EmitContext): string {
274
+ switch (node.kind) {
275
+ case 'shape':
276
+ return shapeXml(node, ctx);
277
+ case 'picture':
278
+ return pictureXml(node, ctx);
279
+ case 'text':
280
+ return textXml(node, ctx);
281
+ }
282
+ }
283
+
284
+ function nvPr(id: number, name: string): string {
285
+ return `<p:cNvPr id="${id}" name="${escapeXml(name.slice(0, 200))}"/>`;
286
+ }
287
+
288
+ function shapeXml(node: ShapeNode, ctx: EmitContext): string {
289
+ const id = ctx.nextId++;
290
+ return `<p:sp><p:nvSpPr>${nvPr(id, node.name)}<p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr>${xfrmXml(node)}${geometryXml(node.geometry, node.box)}${node.fill ? fillXml(node.fill, ctx) : '<a:noFill/>'}${outlineXml(node.outline)}${shadowXml(node.shadow, node.box)}</p:spPr></p:sp>`;
291
+ }
292
+
293
+ function pictureXml(node: PictureNode, ctx: EmitContext): string {
294
+ const id = ctx.nextId++;
295
+ const image = ctx.imageById.get(node.imageId);
296
+ if (!image) return '';
297
+ return `<p:pic><p:nvPicPr>${nvPr(id, node.name)}<p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr><p:blipFill>${blipXml(image, node.alpha, ctx)}${cropXml(node.crop)}<a:stretch><a:fillRect/></a:stretch></p:blipFill><p:spPr>${xfrmXml(node)}${geometryXml(node.geometry, node.box)}${outlineXml(node.outline)}${shadowXml(node.shadow, node.box)}</p:spPr></p:pic>`;
298
+ }
299
+
300
+ function blipXml(image: SceneImage, alpha: number, ctx: EmitContext): string {
301
+ const rId = ctx.rels.image(imageFileName(image));
302
+ const alphaMod = alpha < 0.999 ? `<a:alphaModFix amt="${percent(alpha)}"/>` : '';
303
+ let ext = '';
304
+ if (image.svg) {
305
+ const svgId = ctx.rels.image(`image${image.id}.svg`);
306
+ ext = `<a:extLst><a:ext uri="${SVG_BLIP_URI}"><asvg:svgBlip xmlns:asvg="${NS_SVG}" r:embed="${svgId}"/></a:ext></a:extLst>`;
307
+ }
308
+ return `<a:blip r:embed="${rId}">${alphaMod}${ext}</a:blip>`;
309
+ }
310
+
311
+ function cropXml(crop: PictureNode['crop']): string {
312
+ if (!crop) return '';
313
+ const v = (n: number) => Math.round(Math.min(0.999, Math.max(0, n)) * 100000);
314
+ if (v(crop.l) === 0 && v(crop.t) === 0 && v(crop.r) === 0 && v(crop.b) === 0) return '';
315
+ return `<a:srcRect l="${v(crop.l)}" t="${v(crop.t)}" r="${v(crop.r)}" b="${v(crop.b)}"/>`;
316
+ }
317
+
318
+ function textXml(node: TextNode, ctx: EmitContext): string {
319
+ const id = ctx.nextId++;
320
+ const paragraphs = node.paragraphs.map(paragraphXml).join('');
321
+ return `<p:sp><p:nvSpPr>${nvPr(id, node.name)}<p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr><p:spPr>${xfrmXml(node)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></p:spPr><p:txBody><a:bodyPr wrap="none" lIns="0" tIns="0" rIns="0" bIns="0" rtlCol="0" anchor="t"><a:noAutofit/></a:bodyPr><a:lstStyle/>${paragraphs}</p:txBody></p:sp>`;
322
+ }
323
+
324
+ function paragraphXml(p: Paragraph): string {
325
+ const marL = p.marginLeftPx > 0 ? ` marL="${px(p.marginLeftPx)}"` : '';
326
+ const indent = p.indentPx !== 0 ? ` indent="${px(p.indentPx)}"` : '';
327
+ const pPr = `<a:pPr${marL}${indent} algn="${p.align}"><a:lnSpc><a:spcPts val="${pxToHundredthsPt(p.lineSpacingPx)}"/></a:lnSpc><a:spcBef><a:spcPts val="0"/></a:spcBef><a:spcAft><a:spcPts val="0"/></a:spcAft>${bulletXml(p.bullet)}</a:pPr>`;
328
+ const body = p.lines
329
+ .map((line, i) => {
330
+ const runs = line.runs.map(runXml).join('');
331
+ const br =
332
+ i < p.lines.length - 1 ? `<a:br><a:rPr lang="en-US" sz="${sz(line.sizePx)}"/></a:br>` : '';
333
+ return runs + br;
334
+ })
335
+ .join('');
336
+ return `<a:p>${pPr}${body}<a:endParaRPr lang="en-US" sz="${sz(p.endSizePx)}" dirty="0"/></a:p>`;
337
+ }
338
+
339
+ function bulletXml(bullet: Bullet | null): string {
340
+ if (!bullet) return '<a:buNone/>';
341
+ const color = `<a:buClr>${colorXml(bullet.color)}</a:buClr>`;
342
+ if (bullet.kind === 'number') {
343
+ return `${color}<a:buFont typeface="+mj-lt"/><a:buAutoNum type="${bullet.scheme}" startAt="${Math.max(1, bullet.startAt)}"/>`;
344
+ }
345
+ const font = bullet.font ? `<a:buFont typeface="${escapeXml(bullet.font)}"/>` : '';
346
+ return `${color}${font}<a:buChar char="${escapeXml(bullet.char)}"/>`;
347
+ }
348
+
349
+ function sz(sizePx: number): number {
350
+ return Math.max(100, pxToHundredthsPt(sizePx));
351
+ }
352
+
353
+ function runXml(run: Run): string {
354
+ const s = run.style;
355
+ const attrs = [
356
+ 'lang="en-US"',
357
+ `sz="${sz(s.sizePx)}"`,
358
+ s.bold ? 'b="1"' : '',
359
+ s.italic ? 'i="1"' : '',
360
+ s.underline ? 'u="sng"' : '',
361
+ s.strike ? 'strike="sngStrike"' : '',
362
+ Math.abs(s.letterSpacingPx) > 0.01 ? `spc="${pxToHundredthsPt(s.letterSpacingPx)}"` : '',
363
+ s.baselineShift === 'super'
364
+ ? 'baseline="30000"'
365
+ : s.baselineShift === 'sub'
366
+ ? 'baseline="-25000"'
367
+ : '',
368
+ 'dirty="0"',
369
+ ]
370
+ .filter(Boolean)
371
+ .join(' ');
372
+ const outline = s.outline
373
+ ? `<a:ln w="${px(s.outline.width)}"><a:solidFill>${colorXml(s.outline.color)}</a:solidFill></a:ln>`
374
+ : '';
375
+ const shadow = s.shadow
376
+ ? `<a:effectLst><a:outerShdw blurRad="${px(s.shadow.blur)}" dist="${px(s.shadow.dist)}" dir="${degrees(s.shadow.dirDeg)}" algn="ctr" rotWithShape="0">${colorXml(s.shadow.color)}</a:outerShdw></a:effectLst>`
377
+ : '';
378
+ const font = escapeXml(s.font);
379
+ return `<a:r><a:rPr ${attrs}>${outline}<a:solidFill>${colorXml(s.color)}</a:solidFill>${shadow}<a:latin typeface="${font}"/><a:ea typeface="${font}"/><a:cs typeface="${font}"/></a:rPr><a:t>${escapeXml(run.text)}</a:t></a:r>`;
380
+ }
381
+
382
+ function xfrmXml(node: { box: Rect; rotationDeg: number; flipV: boolean }): string {
383
+ const rot = Math.abs(node.rotationDeg) > 1e-4 ? ` rot="${degrees(node.rotationDeg)}"` : '';
384
+ const flip = node.flipV ? ' flipV="1"' : '';
385
+ return `<a:xfrm${rot}${flip}><a:off x="${px(node.box.x)}" y="${px(node.box.y)}"/><a:ext cx="${Math.max(0, px(node.box.w))}" cy="${Math.max(0, px(node.box.h))}"/></a:xfrm>`;
386
+ }
387
+
388
+ export function geometryXml(geometry: Geometry, box: Rect): string {
389
+ switch (geometry.kind) {
390
+ case 'rect':
391
+ return '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>';
392
+ case 'ellipse':
393
+ return '<a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom>';
394
+ case 'roundRect': {
395
+ const side = Math.max(1e-6, Math.min(box.w, box.h));
396
+ const adj = Math.min(50000, Math.round((geometry.radius / side) * 100000));
397
+ return `<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val ${adj}"/></a:avLst></a:prstGeom>`;
398
+ }
399
+ case 'custom':
400
+ return roundedPathXml(geometry.radii, box);
401
+ }
402
+ }
403
+
404
+ function roundedPathXml(radii: Radii, box: Rect): string {
405
+ const w = Math.max(1, px(box.w));
406
+ const h = Math.max(1, px(box.h));
407
+ const [tl, tr, br, bl] = radii.map((c) => ({ x: px(c.x), y: px(c.y) }));
408
+ const arc = (c: { x: number; y: number }, start: number) =>
409
+ c.x > 0 && c.y > 0
410
+ ? `<a:arcTo wR="${c.x}" hR="${c.y}" stAng="${start * 60000}" swAng="5400000"/>`
411
+ : '';
412
+ const ln = (x: number, y: number) => `<a:lnTo><a:pt x="${x}" y="${y}"/></a:lnTo>`;
413
+ const path =
414
+ `<a:moveTo><a:pt x="${tl.x}" y="0"/></a:moveTo>` +
415
+ ln(w - tr.x, 0) +
416
+ arc(tr, 270) +
417
+ ln(w, h - br.y) +
418
+ arc(br, 0) +
419
+ ln(bl.x, h) +
420
+ arc(bl, 90) +
421
+ ln(0, tl.y) +
422
+ arc(tl, 180) +
423
+ '<a:close/>';
424
+ return `<a:custGeom><a:avLst/><a:gdLst/><a:ahLst/><a:cxnLst/><a:rect l="0" t="0" r="r" b="b"/><a:pathLst><a:path w="${w}" h="${h}">${path}</a:path></a:pathLst></a:custGeom>`;
425
+ }
426
+
427
+ export function colorXml(color: Rgba): string {
428
+ const alpha = color.a < 0.999 ? `<a:alpha val="${percent(color.a)}"/>` : '';
429
+ return `<a:srgbClr val="${toHex(color)}">${alpha}</a:srgbClr>`;
430
+ }
431
+
432
+ function fillXml(fill: Fill, ctx: EmitContext): string {
433
+ switch (fill.kind) {
434
+ case 'solid':
435
+ return `<a:solidFill>${colorXml(fill.color)}</a:solidFill>`;
436
+ case 'gradient': {
437
+ const stops = fill.stops
438
+ .map((s) => `<a:gs pos="${percent(s.pos)}">${colorXml(s.color)}</a:gs>`)
439
+ .join('');
440
+ const ang = degrees(fill.angleDeg - 90);
441
+ return `<a:gradFill rotWithShape="1"><a:gsLst>${stops}</a:gsLst><a:lin ang="${ang}" scaled="0"/></a:gradFill>`;
442
+ }
443
+ case 'image': {
444
+ const image = ctx.imageById.get(fill.imageId);
445
+ if (!image) return '<a:noFill/>';
446
+ return `<a:blipFill dpi="0" rotWithShape="1">${blipXml(image, fill.alpha, ctx)}${cropXml(fill.crop)}<a:stretch><a:fillRect/></a:stretch></a:blipFill>`;
447
+ }
448
+ }
449
+ }
450
+
451
+ function outlineXml(outline: Outline | null): string {
452
+ if (!outline) return '<a:ln><a:noFill/></a:ln>';
453
+ const dash = outline.dash === 'solid' ? '' : `<a:prstDash val="${outline.dash}"/>`;
454
+ return `<a:ln w="${Math.max(0, px(outline.width))}" cap="flat" cmpd="sng" algn="ctr"><a:solidFill>${colorXml(outline.color)}</a:solidFill>${dash}<a:miter lim="800000"/></a:ln>`;
455
+ }
456
+
457
+ function shadowXml(shadow: ShadowEffect | null, box: Rect): string {
458
+ if (!shadow) return '';
459
+ const color = colorXml(shadow.color);
460
+ if (shadow.inner) {
461
+ return `<a:effectLst><a:innerShdw blurRad="${px(shadow.blur)}" dist="${px(shadow.dist)}" dir="${degrees(shadow.dirDeg)}">${color}</a:innerShdw></a:effectLst>`;
462
+ }
463
+ const sx = box.w > 0 ? Math.round(((box.w + 2 * shadow.spread) / box.w) * 100000) : 100000;
464
+ const sy = box.h > 0 ? Math.round(((box.h + 2 * shadow.spread) / box.h) * 100000) : 100000;
465
+ return `<a:effectLst><a:outerShdw blurRad="${px(shadow.blur)}" dist="${px(shadow.dist)}" dir="${degrees(shadow.dirDeg)}" sx="${Math.max(0, sx)}" sy="${Math.max(0, sy)}" algn="ctr" rotWithShape="0">${color}</a:outerShdw></a:effectLst>`;
466
+ }
467
+
468
+ function themeXml(): string {
469
+ return `${XML_DECL}<a:theme xmlns:a="${NS_A}" name="Office Theme"><a:themeElements><a:clrScheme name="Office"><a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1><a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="44546A"/></a:dk2><a:lt2><a:srgbClr val="E7E6E6"/></a:lt2><a:accent1><a:srgbClr val="4472C4"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2><a:accent3><a:srgbClr val="A5A5A5"/></a:accent3><a:accent4><a:srgbClr val="FFC000"/></a:accent4><a:accent5><a:srgbClr val="5B9BD5"/></a:accent5><a:accent6><a:srgbClr val="70AD47"/></a:accent6><a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink></a:clrScheme><a:fontScheme name="Office"><a:majorFont><a:latin typeface="Calibri Light"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont></a:fontScheme><a:fmtScheme name="Office"><a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:lumMod val="110000"/><a:satMod val="105000"/><a:tint val="67000"/></a:schemeClr></a:gs><a:gs pos="50000"><a:schemeClr val="phClr"><a:lumMod val="105000"/><a:satMod val="103000"/><a:tint val="73000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:lumMod val="105000"/><a:satMod val="109000"/><a:tint val="81000"/></a:schemeClr></a:gs></a:gsLst><a:lin ang="5400000" scaled="0"/></a:gradFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:satMod val="103000"/><a:lumMod val="102000"/><a:tint val="94000"/></a:schemeClr></a:gs><a:gs pos="50000"><a:schemeClr val="phClr"><a:satMod val="110000"/><a:lumMod val="100000"/><a:shade val="100000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:lumMod val="99000"/><a:satMod val="120000"/><a:shade val="78000"/></a:schemeClr></a:gs></a:gsLst><a:lin ang="5400000" scaled="0"/></a:gradFill></a:fillStyleLst><a:lnStyleLst><a:ln w="6350" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/><a:miter lim="800000"/></a:ln><a:ln w="12700" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/><a:miter lim="800000"/></a:ln><a:ln w="19050" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/><a:miter lim="800000"/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"><a:tint val="95000"/><a:satMod val="170000"/></a:schemeClr></a:solidFill><a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="93000"/><a:satMod val="150000"/><a:shade val="98000"/><a:lumMod val="102000"/></a:schemeClr></a:gs><a:gs pos="50000"><a:schemeClr val="phClr"><a:tint val="98000"/><a:satMod val="130000"/><a:shade val="90000"/><a:lumMod val="103000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="63000"/><a:satMod val="120000"/></a:schemeClr></a:gs></a:gsLst><a:lin ang="5400000" scaled="0"/></a:gradFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements></a:theme>`;
470
+ }
@@ -0,0 +1,189 @@
1
+ import { CANVAS_HEIGHT, CANVAS_WIDTH } from '../sdk';
2
+ import type { Rect } from './scene';
3
+
4
+ const MAX_PIXEL_RATIO = 2;
5
+ const MAX_RASTER_PIXELS = 3_000_000;
6
+ const JPEG_QUALITY = 0.92;
7
+ const ISOLATE_CLASS = 'os-pptx-isolate';
8
+ const TARGET_ATTR = 'data-os-raster-target';
9
+ const ALPHA_THRESHOLD = 2;
10
+
11
+ export type RasterMode = 'subtree' | 'self';
12
+
13
+ export type RasterRequest = {
14
+ target: Element;
15
+ mode: RasterMode;
16
+ /** Frame-space region to keep, already expanded for bleed and clamped to the slide. */
17
+ region: Rect;
18
+ /** Trim transparent margins so the picture box hugs the painted pixels. */
19
+ trim: boolean;
20
+ };
21
+
22
+ export type RasterResult = { bytes: Uint8Array; rect: Rect; format: 'png' | 'jpeg' };
23
+
24
+ function pixelRatioFor(region: Rect): number {
25
+ const area = Math.max(1, region.w * region.h);
26
+ return Math.min(MAX_PIXEL_RATIO, Math.max(1, Math.sqrt(MAX_RASTER_PIXELS / area)));
27
+ }
28
+
29
+ const isolateStyleText = `
30
+ .${ISOLATE_CLASS} { background: transparent !important; }
31
+ .${ISOLATE_CLASS} * { visibility: hidden !important; }
32
+ .${ISOLATE_CLASS} [${TARGET_ATTR}], .${ISOLATE_CLASS} [${TARGET_ATTR}] * { visibility: visible !important; }
33
+ .${ISOLATE_CLASS} [${TARGET_ATTR}="self"] * { visibility: hidden !important; }
34
+ `;
35
+
36
+ export function clampToSlide(rect: Rect): Rect {
37
+ const x = Math.max(0, Math.floor(rect.x));
38
+ const y = Math.max(0, Math.floor(rect.y));
39
+ const right = Math.min(CANVAS_WIDTH, Math.ceil(rect.x + rect.w));
40
+ const bottom = Math.min(CANVAS_HEIGHT, Math.ceil(rect.y + rect.h));
41
+ return { x, y, w: Math.max(0, right - x), h: Math.max(0, bottom - y) };
42
+ }
43
+
44
+ export function expandRect(rect: Rect, by: number): Rect {
45
+ return { x: rect.x - by, y: rect.y - by, w: rect.w + 2 * by, h: rect.h + 2 * by };
46
+ }
47
+
48
+ function intersects(a: Rect, b: Rect): boolean {
49
+ return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
50
+ }
51
+
52
+ type Batch = { ratio: number; requests: RasterRequest[] };
53
+
54
+ function batchRequests(requests: RasterRequest[]): Batch[] {
55
+ const batches: Batch[] = [];
56
+ for (const req of requests) {
57
+ const ratio = pixelRatioFor(req.region);
58
+ const batch = batches.find(
59
+ (b) =>
60
+ b.ratio === ratio && b.requests.every((other) => !intersects(other.region, req.region)),
61
+ );
62
+ if (batch) batch.requests.push(req);
63
+ else batches.push({ ratio, requests: [req] });
64
+ }
65
+ return batches;
66
+ }
67
+
68
+ export class Rasterizer {
69
+ private fontCss: string | null = null;
70
+ private toCanvas: typeof import('html-to-image').toCanvas | null = null;
71
+
72
+ constructor(private readonly frame: HTMLElement) {}
73
+
74
+ async rasterize(requests: RasterRequest[]): Promise<(RasterResult | null)[]> {
75
+ const results: (RasterResult | null)[] = requests.map(() => null);
76
+ const live = requests.filter((r) => r.region.w > 0 && r.region.h > 0);
77
+ if (live.length === 0) return results;
78
+
79
+ const lib = await import('html-to-image');
80
+ this.toCanvas = lib.toCanvas;
81
+ if (this.fontCss === null) {
82
+ this.fontCss = await lib.getFontEmbedCSS(this.frame).catch(() => '');
83
+ }
84
+
85
+ const style = document.createElement('style');
86
+ style.textContent = isolateStyleText;
87
+ document.head.appendChild(style);
88
+ this.frame.classList.add(ISOLATE_CLASS);
89
+ try {
90
+ for (const batch of batchRequests(live)) {
91
+ for (const req of batch.requests) req.target.setAttribute(TARGET_ATTR, req.mode);
92
+ try {
93
+ const canvas = await this.toCanvas(this.frame, {
94
+ width: CANVAS_WIDTH,
95
+ height: CANVAS_HEIGHT,
96
+ pixelRatio: batch.ratio,
97
+ cacheBust: true,
98
+ skipAutoScale: true,
99
+ fontEmbedCSS: this.fontCss,
100
+ });
101
+ for (const req of batch.requests) {
102
+ results[requests.indexOf(req)] = await crop(canvas, req, batch.ratio);
103
+ }
104
+ } catch (err) {
105
+ console.warn(
106
+ '[open-slide] pptx export: could not rasterize an element, skipping it',
107
+ err,
108
+ );
109
+ } finally {
110
+ for (const req of batch.requests) req.target.removeAttribute(TARGET_ATTR);
111
+ }
112
+ }
113
+ } finally {
114
+ this.frame.classList.remove(ISOLATE_CLASS);
115
+ style.remove();
116
+ }
117
+ return results;
118
+ }
119
+ }
120
+
121
+ async function crop(
122
+ source: HTMLCanvasElement,
123
+ req: RasterRequest,
124
+ ratio: number,
125
+ ): Promise<RasterResult | null> {
126
+ const { region } = req;
127
+ const sx = Math.round(region.x * ratio);
128
+ const sy = Math.round(region.y * ratio);
129
+ const sw = Math.round(region.w * ratio);
130
+ const sh = Math.round(region.h * ratio);
131
+ if (sw <= 0 || sh <= 0) return null;
132
+ const ctx = source.getContext('2d');
133
+ if (!ctx) return null;
134
+ const data = ctx.getImageData(sx, sy, sw, sh);
135
+ const bounds = req.trim ? opaqueBounds(data) : { x: 0, y: 0, w: sw, h: sh };
136
+ if (!bounds) return null;
137
+
138
+ const out = document.createElement('canvas');
139
+ out.width = bounds.w;
140
+ out.height = bounds.h;
141
+ const octx = out.getContext('2d');
142
+ if (!octx) return null;
143
+ octx.putImageData(data, -bounds.x, -bounds.y);
144
+ const opaque = isFullyOpaque(octx.getImageData(0, 0, bounds.w, bounds.h));
145
+ const blob = await new Promise<Blob | null>((resolve) =>
146
+ opaque ? out.toBlob(resolve, 'image/jpeg', JPEG_QUALITY) : out.toBlob(resolve, 'image/png'),
147
+ );
148
+ if (!blob) return null;
149
+ return {
150
+ bytes: new Uint8Array(await blob.arrayBuffer()),
151
+ format: opaque ? 'jpeg' : 'png',
152
+ rect: {
153
+ x: region.x + bounds.x / ratio,
154
+ y: region.y + bounds.y / ratio,
155
+ w: bounds.w / ratio,
156
+ h: bounds.h / ratio,
157
+ },
158
+ };
159
+ }
160
+
161
+ function isFullyOpaque(data: ImageData): boolean {
162
+ const px = data.data;
163
+ for (let i = 3; i < px.length; i += 4) {
164
+ if (px[i] !== 255) return false;
165
+ }
166
+ return true;
167
+ }
168
+
169
+ function opaqueBounds(data: ImageData): Rect | null {
170
+ const { width, height } = data;
171
+ const px = data.data;
172
+ let minX = width;
173
+ let minY = height;
174
+ let maxX = -1;
175
+ let maxY = -1;
176
+ for (let y = 0; y < height; y++) {
177
+ const rowStart = y * width * 4 + 3;
178
+ for (let x = 0; x < width; x++) {
179
+ if (px[rowStart + x * 4] > ALPHA_THRESHOLD) {
180
+ if (x < minX) minX = x;
181
+ if (x > maxX) maxX = x;
182
+ if (y < minY) minY = y;
183
+ if (y > maxY) maxY = y;
184
+ }
185
+ }
186
+ }
187
+ if (maxX < 0) return null;
188
+ return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
189
+ }