@shotstack/shotstack-canvas 1.0.2 → 1.0.4

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.
@@ -0,0 +1,1285 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // src/schema/asset-schema.ts
6
+ import Joi from "joi";
7
+
8
+ // src/config/canvas-constants.ts
9
+ var CANVAS_CONFIG = {
10
+ DEFAULTS: {
11
+ width: 800,
12
+ height: 400,
13
+ pixelRatio: 2,
14
+ fontFamily: "Roboto",
15
+ fontSize: 48,
16
+ color: "#000000",
17
+ textAlign: "left"
18
+ },
19
+ LIMITS: {
20
+ minWidth: 1,
21
+ maxWidth: 4096,
22
+ minHeight: 1,
23
+ maxHeight: 4096,
24
+ minFontSize: 1,
25
+ maxFontSize: 512,
26
+ minDuration: 0.1,
27
+ maxDuration: 120,
28
+ maxTextLength: 1e4
29
+ },
30
+ ANIMATION_TYPES: [
31
+ "typewriter",
32
+ "fadeIn",
33
+ "slideIn",
34
+ "shift",
35
+ "ascend",
36
+ "movingLetters"
37
+ ]
38
+ };
39
+
40
+ // src/schema/asset-schema.ts
41
+ var HEX6 = /^#[A-Fa-f0-9]{6}$/;
42
+ var gradientSchema = Joi.object({
43
+ type: Joi.string().valid("linear", "radial").default("linear"),
44
+ angle: Joi.number().min(0).max(360).default(0),
45
+ stops: Joi.array().items(
46
+ Joi.object({
47
+ offset: Joi.number().min(0).max(1).required(),
48
+ color: Joi.string().pattern(HEX6).required()
49
+ }).unknown(false)
50
+ ).min(2).required()
51
+ }).unknown(false);
52
+ var shadowSchema = Joi.object({
53
+ offsetX: Joi.number().default(0),
54
+ offsetY: Joi.number().default(0),
55
+ blur: Joi.number().min(0).default(0),
56
+ color: Joi.string().pattern(HEX6).default("#000000"),
57
+ opacity: Joi.number().min(0).max(1).default(0.5)
58
+ }).unknown(false);
59
+ var strokeSchema = Joi.object({
60
+ width: Joi.number().min(0).default(0),
61
+ color: Joi.string().pattern(HEX6).default("#000000"),
62
+ opacity: Joi.number().min(0).max(1).default(1)
63
+ }).unknown(false);
64
+ var fontSchema = Joi.object({
65
+ family: Joi.string().default(CANVAS_CONFIG.DEFAULTS.fontFamily),
66
+ size: Joi.number().min(CANVAS_CONFIG.LIMITS.minFontSize).max(CANVAS_CONFIG.LIMITS.maxFontSize).default(CANVAS_CONFIG.DEFAULTS.fontSize),
67
+ weight: Joi.alternatives().try(Joi.string(), Joi.number()).default("400"),
68
+ style: Joi.string().valid("normal", "italic", "oblique").default("normal"),
69
+ color: Joi.string().pattern(HEX6).default(CANVAS_CONFIG.DEFAULTS.color),
70
+ opacity: Joi.number().min(0).max(1).default(1)
71
+ }).unknown(false);
72
+ var styleSchema = Joi.object({
73
+ letterSpacing: Joi.number().default(0),
74
+ lineHeight: Joi.number().min(0).max(10).default(1.2),
75
+ textTransform: Joi.string().valid("none", "uppercase", "lowercase", "capitalize").default("none"),
76
+ textDecoration: Joi.string().valid("none", "underline", "line-through").default("none"),
77
+ gradient: gradientSchema.optional()
78
+ }).unknown(false);
79
+ var alignmentSchema = Joi.object({
80
+ horizontal: Joi.string().valid("left", "center", "right").default(CANVAS_CONFIG.DEFAULTS.textAlign),
81
+ vertical: Joi.string().valid("top", "middle", "bottom").default("middle")
82
+ }).unknown(false);
83
+ var animationSchema = Joi.object({
84
+ preset: Joi.string().valid(...CANVAS_CONFIG.ANIMATION_TYPES),
85
+ speed: Joi.number().min(0.1).max(10).default(1),
86
+ duration: Joi.number().min(CANVAS_CONFIG.LIMITS.minDuration).max(CANVAS_CONFIG.LIMITS.maxDuration).optional(),
87
+ style: Joi.string().valid("character", "word").optional().when("preset", {
88
+ is: Joi.valid("typewriter", "shift"),
89
+ then: Joi.optional(),
90
+ otherwise: Joi.forbidden()
91
+ }),
92
+ direction: Joi.string().optional().when("preset", {
93
+ switch: [
94
+ { is: "ascend", then: Joi.valid("up", "down") },
95
+ { is: "shift", then: Joi.valid("left", "right", "up", "down") },
96
+ { is: "slideIn", then: Joi.valid("left", "right", "up", "down") },
97
+ { is: "movingLetters", then: Joi.valid("left", "right", "up", "down") }
98
+ ],
99
+ otherwise: Joi.forbidden()
100
+ })
101
+ }).unknown(false);
102
+ var backgroundSchema = Joi.object({
103
+ color: Joi.string().pattern(HEX6).optional(),
104
+ opacity: Joi.number().min(0).max(1).default(1),
105
+ borderRadius: Joi.number().min(0).default(0)
106
+ }).unknown(false);
107
+ var customFontSchema = Joi.object({
108
+ src: Joi.string().uri().required(),
109
+ family: Joi.string().required(),
110
+ weight: Joi.alternatives().try(Joi.string(), Joi.number()).optional(),
111
+ style: Joi.string().optional(),
112
+ originalFamily: Joi.string().optional()
113
+ }).unknown(false);
114
+ var RichTextAssetSchema = Joi.object({
115
+ type: Joi.string().valid("rich-text").required(),
116
+ text: Joi.string().allow("").max(CANVAS_CONFIG.LIMITS.maxTextLength).default(""),
117
+ width: Joi.number().min(CANVAS_CONFIG.LIMITS.minWidth).max(CANVAS_CONFIG.LIMITS.maxWidth).default(CANVAS_CONFIG.DEFAULTS.width).optional(),
118
+ height: Joi.number().min(CANVAS_CONFIG.LIMITS.minHeight).max(CANVAS_CONFIG.LIMITS.maxHeight).default(CANVAS_CONFIG.DEFAULTS.height).optional(),
119
+ font: fontSchema.optional(),
120
+ style: styleSchema.optional(),
121
+ stroke: strokeSchema.optional(),
122
+ shadow: shadowSchema.optional(),
123
+ background: backgroundSchema.optional(),
124
+ align: alignmentSchema.optional(),
125
+ animation: animationSchema.optional(),
126
+ customFonts: Joi.array().items(customFontSchema).optional(),
127
+ cacheEnabled: Joi.boolean().default(true),
128
+ pixelRatio: Joi.number().min(1).max(3).default(CANVAS_CONFIG.DEFAULTS.pixelRatio)
129
+ }).unknown(false);
130
+
131
+ // src/wasm/hb-loader.ts
132
+ var hbSingleton = null;
133
+ async function initHB(wasmBaseURL) {
134
+ if (hbSingleton) return hbSingleton;
135
+ const harfbuzzjs = await import("harfbuzzjs");
136
+ const hbPromise = harfbuzzjs.default;
137
+ if (typeof hbPromise === "function") {
138
+ hbSingleton = await hbPromise();
139
+ } else if (hbPromise && typeof hbPromise.then === "function") {
140
+ hbSingleton = await hbPromise;
141
+ } else {
142
+ hbSingleton = hbPromise;
143
+ }
144
+ if (!hbSingleton || typeof hbSingleton.createBuffer !== "function") {
145
+ throw new Error("Failed to initialize HarfBuzz: invalid API");
146
+ }
147
+ return hbSingleton;
148
+ }
149
+
150
+ // src/core/font-registry.ts
151
+ var FontRegistry = class {
152
+ constructor(wasmBaseURL) {
153
+ __publicField(this, "hb");
154
+ __publicField(this, "faces", /* @__PURE__ */ new Map());
155
+ __publicField(this, "fonts", /* @__PURE__ */ new Map());
156
+ __publicField(this, "blobs", /* @__PURE__ */ new Map());
157
+ __publicField(this, "wasmBaseURL");
158
+ this.wasmBaseURL = wasmBaseURL;
159
+ }
160
+ async init() {
161
+ if (!this.hb) this.hb = await initHB(this.wasmBaseURL);
162
+ }
163
+ getHB() {
164
+ if (!this.hb) throw new Error("FontRegistry not initialized - call init() first");
165
+ return this.hb;
166
+ }
167
+ key(desc) {
168
+ return `${desc.family}__${desc.weight ?? "400"}__${desc.style ?? "normal"}`;
169
+ }
170
+ async registerFromBytes(bytes, desc) {
171
+ if (!this.hb) await this.init();
172
+ const k = this.key(desc);
173
+ if (this.fonts.has(k)) return;
174
+ const blob = this.hb.createBlob(bytes);
175
+ const face = this.hb.createFace(blob, 0);
176
+ const font = this.hb.createFont(face);
177
+ const upem = face.upem || 1e3;
178
+ font.setScale(upem, upem);
179
+ this.blobs.set(k, blob);
180
+ this.faces.set(k, face);
181
+ this.fonts.set(k, font);
182
+ }
183
+ getFont(desc) {
184
+ const k = this.key(desc);
185
+ const f = this.fonts.get(k);
186
+ if (!f) throw new Error(`Font not registered for ${k}`);
187
+ return f;
188
+ }
189
+ getFace(desc) {
190
+ const k = this.key(desc);
191
+ return this.faces.get(k);
192
+ }
193
+ /** NEW: expose units-per-em for scaling glyph paths to px */
194
+ getUnitsPerEm(desc) {
195
+ const face = this.getFace(desc);
196
+ return face?.upem || 1e3;
197
+ }
198
+ glyphPath(desc, glyphId) {
199
+ const font = this.getFont(desc);
200
+ const path = font.glyphToPath(glyphId);
201
+ return path && path !== "" ? path : "M 0 0";
202
+ }
203
+ destroy() {
204
+ for (const [, f] of this.fonts) f.destroy?.();
205
+ for (const [, f] of this.faces) f.destroy?.();
206
+ for (const [, b] of this.blobs) b.destroy?.();
207
+ this.fonts.clear();
208
+ this.faces.clear();
209
+ this.blobs.clear();
210
+ }
211
+ };
212
+
213
+ // src/core/layout.ts
214
+ var LayoutEngine = class {
215
+ constructor(fonts) {
216
+ this.fonts = fonts;
217
+ }
218
+ transformText(t, tr) {
219
+ switch (tr) {
220
+ case "uppercase":
221
+ return t.toUpperCase();
222
+ case "lowercase":
223
+ return t.toLowerCase();
224
+ case "capitalize":
225
+ return t.replace(/\b\w/g, (c) => c.toUpperCase());
226
+ default:
227
+ return t;
228
+ }
229
+ }
230
+ shapeFull(text, desc) {
231
+ const hb = this.fonts.getHB();
232
+ const buffer = hb.createBuffer();
233
+ buffer.addText(text);
234
+ buffer.guessSegmentProperties();
235
+ const font = this.fonts.getFont(desc);
236
+ const face = this.fonts.getFace(desc);
237
+ const upem = face?.upem || 1e3;
238
+ font.setScale(upem, upem);
239
+ hb.shape(font, buffer);
240
+ const result = buffer.json();
241
+ buffer.destroy();
242
+ return result;
243
+ }
244
+ layout(params) {
245
+ const { textTransform, desc, fontSize, letterSpacing, width } = params;
246
+ const input = this.transformText(params.text, textTransform);
247
+ if (!input || input.length === 0) {
248
+ return [];
249
+ }
250
+ const shaped = this.shapeFull(input, desc);
251
+ const face = this.fonts.getFace(desc);
252
+ const upem = face?.upem || 1e3;
253
+ const scale = fontSize / upem;
254
+ const glyphs = shaped.map((g, i) => {
255
+ const charIndex = g.cl;
256
+ let char;
257
+ if (charIndex >= 0 && charIndex < input.length) {
258
+ char = input[charIndex];
259
+ }
260
+ return {
261
+ id: g.g,
262
+ xAdvance: g.ax * scale + letterSpacing,
263
+ xOffset: g.dx * scale,
264
+ yOffset: -g.dy * scale,
265
+ cluster: g.cl,
266
+ char
267
+ // This now correctly maps to the original character
268
+ };
269
+ });
270
+ const lines = [];
271
+ let currentLine = [];
272
+ let currentWidth = 0;
273
+ const spaceIndices = /* @__PURE__ */ new Set();
274
+ for (let i = 0; i < input.length; i++) {
275
+ if (input[i] === " ") {
276
+ spaceIndices.add(i);
277
+ }
278
+ }
279
+ let lastBreakIndex = -1;
280
+ for (let i = 0; i < glyphs.length; i++) {
281
+ const glyph = glyphs[i];
282
+ const glyphWidth = glyph.xAdvance;
283
+ if (glyph.char === "\n") {
284
+ if (currentLine.length > 0) {
285
+ lines.push({
286
+ glyphs: currentLine,
287
+ width: currentWidth,
288
+ y: 0
289
+ });
290
+ }
291
+ currentLine = [];
292
+ currentWidth = 0;
293
+ lastBreakIndex = i;
294
+ continue;
295
+ }
296
+ if (currentWidth + glyphWidth > width && currentLine.length > 0) {
297
+ if (lastBreakIndex > -1) {
298
+ const breakPoint = lastBreakIndex - (i - currentLine.length) + 1;
299
+ const nextLine = currentLine.splice(breakPoint);
300
+ const lineWidth = currentLine.reduce((sum, g) => sum + g.xAdvance, 0);
301
+ lines.push({
302
+ glyphs: currentLine,
303
+ width: lineWidth,
304
+ y: 0
305
+ });
306
+ currentLine = nextLine;
307
+ currentWidth = nextLine.reduce((sum, g) => sum + g.xAdvance, 0);
308
+ } else {
309
+ lines.push({
310
+ glyphs: currentLine,
311
+ width: currentWidth,
312
+ y: 0
313
+ });
314
+ currentLine = [];
315
+ currentWidth = 0;
316
+ }
317
+ lastBreakIndex = -1;
318
+ }
319
+ currentLine.push(glyph);
320
+ currentWidth += glyphWidth;
321
+ if (spaceIndices.has(glyph.cluster)) {
322
+ lastBreakIndex = i;
323
+ }
324
+ }
325
+ if (currentLine.length > 0) {
326
+ lines.push({
327
+ glyphs: currentLine,
328
+ width: currentWidth,
329
+ y: 0
330
+ });
331
+ }
332
+ const lineHeight = params.lineHeight * fontSize;
333
+ for (let i = 0; i < lines.length; i++) {
334
+ lines[i].y = (i + 1) * lineHeight;
335
+ }
336
+ return lines;
337
+ }
338
+ };
339
+
340
+ // src/core/gradients.ts
341
+ function gradientSpecFrom(g, opacity) {
342
+ if (g.type === "linear") {
343
+ return { kind: "linear", angle: g.angle, stops: g.stops, opacity };
344
+ } else {
345
+ return { kind: "radial", stops: g.stops, opacity };
346
+ }
347
+ }
348
+
349
+ // src/core/decoration.ts
350
+ function decorationGeometry(kind, p) {
351
+ const thickness = Math.max(1, Math.round(p.fontSize * 0.05));
352
+ let y = p.baselineY + Math.round(p.fontSize * 0.1);
353
+ if (kind === "line-through") y = p.baselineY - Math.round(p.fontSize * 0.3);
354
+ return { x1: p.xStart, x2: p.xStart + p.lineWidth, y, width: thickness };
355
+ }
356
+
357
+ // src/core/drawops.ts
358
+ function buildDrawOps(p) {
359
+ const ops = [];
360
+ ops.push({
361
+ op: "BeginFrame",
362
+ width: p.canvas.width,
363
+ height: p.canvas.height,
364
+ pixelRatio: p.canvas.pixelRatio,
365
+ clear: true,
366
+ bg: p.background ? { color: p.background.color, opacity: p.background.opacity, radius: p.background.borderRadius } : void 0
367
+ });
368
+ if (p.lines.length === 0) return ops;
369
+ const upem = Math.max(1, p.getUnitsPerEm?.() ?? 1e3);
370
+ const scale = p.font.size / upem;
371
+ const blockHeight = p.lines[p.lines.length - 1].y;
372
+ let blockY;
373
+ switch (p.align.vertical) {
374
+ case "top":
375
+ blockY = p.font.size;
376
+ break;
377
+ case "bottom":
378
+ blockY = p.textRect.height - blockHeight + p.font.size;
379
+ break;
380
+ case "middle":
381
+ default:
382
+ blockY = (p.textRect.height - blockHeight) / 2 + p.font.size;
383
+ break;
384
+ }
385
+ const fill = p.style.gradient ? gradientSpecFrom(p.style.gradient, 1) : { kind: "solid", color: p.font.color, opacity: p.font.opacity };
386
+ const decoColor = p.style.gradient ? p.style.gradient.stops[p.style.gradient.stops.length - 1]?.color ?? p.font.color : p.font.color;
387
+ let gMinX = Infinity, gMinY = Infinity, gMaxX = -Infinity, gMaxY = -Infinity;
388
+ for (const line of p.lines) {
389
+ let lineX;
390
+ switch (p.align.horizontal) {
391
+ case "left":
392
+ lineX = 0;
393
+ break;
394
+ case "right":
395
+ lineX = p.textRect.width - line.width;
396
+ break;
397
+ case "center":
398
+ default:
399
+ lineX = (p.textRect.width - line.width) / 2;
400
+ break;
401
+ }
402
+ let xCursor = lineX;
403
+ const baselineY = blockY + line.y - p.font.size;
404
+ for (const glyph of line.glyphs) {
405
+ const path = p.glyphPathProvider(glyph.id);
406
+ if (!path || path === "M 0 0") {
407
+ xCursor += glyph.xAdvance;
408
+ continue;
409
+ }
410
+ const glyphX = xCursor + glyph.xOffset;
411
+ const glyphY = baselineY + glyph.yOffset;
412
+ const pb = computePathBounds(path);
413
+ const x1 = glyphX + scale * pb.x;
414
+ const x2 = glyphX + scale * (pb.x + pb.w);
415
+ const y1 = glyphY - scale * (pb.y + pb.h);
416
+ const y2 = glyphY - scale * pb.y;
417
+ if (x1 < gMinX) gMinX = x1;
418
+ if (y1 < gMinY) gMinY = y1;
419
+ if (x2 > gMaxX) gMaxX = x2;
420
+ if (y2 > gMaxY) gMaxY = y2;
421
+ if (p.shadow && p.shadow.blur > 0) {
422
+ ops.push({
423
+ isShadow: true,
424
+ op: "FillPath",
425
+ path,
426
+ x: glyphX + p.shadow.offsetX,
427
+ y: glyphY + p.shadow.offsetY,
428
+ // @ts-ignore scale propagated to painters
429
+ scale,
430
+ fill: { kind: "solid", color: p.shadow.color, opacity: p.shadow.opacity }
431
+ });
432
+ }
433
+ if (p.stroke && p.stroke.width > 0) {
434
+ ops.push({
435
+ op: "StrokePath",
436
+ path,
437
+ x: glyphX,
438
+ y: glyphY,
439
+ // @ts-ignore scale propagated to painters
440
+ scale,
441
+ width: p.stroke.width,
442
+ color: p.stroke.color,
443
+ opacity: p.stroke.opacity
444
+ });
445
+ }
446
+ ops.push({
447
+ op: "FillPath",
448
+ path,
449
+ x: glyphX,
450
+ y: glyphY,
451
+ // @ts-ignore scale propagated to painters
452
+ scale,
453
+ fill
454
+ });
455
+ xCursor += glyph.xAdvance;
456
+ }
457
+ if (p.style.textDecoration !== "none") {
458
+ const deco = decorationGeometry(p.style.textDecoration, {
459
+ baselineY,
460
+ fontSize: p.font.size,
461
+ lineWidth: line.width,
462
+ xStart: lineX
463
+ });
464
+ ops.push({
465
+ op: "DecorationLine",
466
+ from: { x: deco.x1, y: deco.y },
467
+ to: { x: deco.x2, y: deco.y },
468
+ width: deco.width,
469
+ color: decoColor,
470
+ opacity: p.font.opacity
471
+ });
472
+ }
473
+ }
474
+ if (gMinX !== Infinity) {
475
+ const gbox = { x: gMinX, y: gMinY, w: Math.max(1, gMaxX - gMinX), h: Math.max(1, gMaxY - gMinY) };
476
+ for (const op of ops) {
477
+ if (op.op === "FillPath" && !op.isShadow) {
478
+ op.gradientBBox = gbox;
479
+ }
480
+ }
481
+ }
482
+ return ops;
483
+ }
484
+ function tokenizePath(d) {
485
+ return d.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi) ?? [];
486
+ }
487
+ function computePathBounds(d) {
488
+ const t = tokenizePath(d);
489
+ let i = 0;
490
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
491
+ const touch = (x, y) => {
492
+ if (x < minX) minX = x;
493
+ if (y < minY) minY = y;
494
+ if (x > maxX) maxX = x;
495
+ if (y > maxY) maxY = y;
496
+ };
497
+ while (i < t.length) {
498
+ const cmd = t[i++];
499
+ switch (cmd) {
500
+ case "M":
501
+ case "L": {
502
+ const x = parseFloat(t[i++]);
503
+ const y = parseFloat(t[i++]);
504
+ touch(x, y);
505
+ break;
506
+ }
507
+ case "C": {
508
+ const c1x = parseFloat(t[i++]);
509
+ const c1y = parseFloat(t[i++]);
510
+ const c2x = parseFloat(t[i++]);
511
+ const c2y = parseFloat(t[i++]);
512
+ const x = parseFloat(t[i++]);
513
+ const y = parseFloat(t[i++]);
514
+ touch(c1x, c1y);
515
+ touch(c2x, c2y);
516
+ touch(x, y);
517
+ break;
518
+ }
519
+ case "Q": {
520
+ const cx = parseFloat(t[i++]);
521
+ const cy = parseFloat(t[i++]);
522
+ const x = parseFloat(t[i++]);
523
+ const y = parseFloat(t[i++]);
524
+ touch(cx, cy);
525
+ touch(x, y);
526
+ break;
527
+ }
528
+ case "Z":
529
+ break;
530
+ }
531
+ }
532
+ if (minX === Infinity) return { x: 0, y: 0, w: 0, h: 0 };
533
+ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
534
+ }
535
+
536
+ // src/core/animations.ts
537
+ var DECORATION_DONE_THRESHOLD = 0.999;
538
+ function applyAnimation(ops, lines, p) {
539
+ if (!p.anim || !p.anim.preset) return ops;
540
+ const { preset } = p.anim;
541
+ const totalGlyphs = lines.reduce((s, l) => s + l.glyphs.length, 0);
542
+ const duration = p.anim.duration ?? Math.max(0.3, totalGlyphs / 30 / p.anim.speed);
543
+ const progress = Math.max(0, Math.min(1, p.t / duration));
544
+ switch (preset) {
545
+ case "typewriter":
546
+ return applyTypewriterAnimation(
547
+ ops,
548
+ lines,
549
+ progress,
550
+ p.anim.style,
551
+ p.fontSize,
552
+ p.t,
553
+ duration
554
+ );
555
+ case "fadeIn":
556
+ return applyFadeInAnimation(ops, progress);
557
+ case "slideIn":
558
+ return applySlideInAnimation(ops, progress, p.anim.direction ?? "left", p.fontSize);
559
+ case "shift":
560
+ return applyShiftAnimation(
561
+ ops,
562
+ lines,
563
+ progress,
564
+ p.anim.direction ?? "left",
565
+ p.fontSize,
566
+ p.anim.style,
567
+ duration
568
+ );
569
+ case "ascend":
570
+ return applyAscendAnimation(
571
+ ops,
572
+ lines,
573
+ progress,
574
+ p.anim.direction ?? "up",
575
+ p.fontSize,
576
+ duration
577
+ );
578
+ case "movingLetters":
579
+ return applyMovingLettersAnimation(ops, progress, p.anim.direction ?? "up", p.fontSize);
580
+ default:
581
+ return ops;
582
+ }
583
+ }
584
+ var isShadowFill = (op) => op.op === "FillPath" && op.isShadow === true;
585
+ var isGlyphFill = (op) => op.op === "FillPath" && !op.isShadow === true;
586
+ function getTextColorFromOps(ops) {
587
+ for (const op of ops) {
588
+ if (op.op === "FillPath") {
589
+ const fill = op.fill;
590
+ if (fill?.kind === "solid") return fill.color;
591
+ if ((fill?.kind === "linear" || fill?.kind === "radial") && Array.isArray(fill.stops) && fill.stops.length) {
592
+ return fill.stops[fill.stops.length - 1].color || "#000000";
593
+ }
594
+ }
595
+ }
596
+ return "#000000";
597
+ }
598
+ function applyTypewriterAnimation(ops, lines, progress, style, fontSize, time, duration) {
599
+ const byWord = style === "word";
600
+ if (byWord) {
601
+ const wordSegments = getWordSegments(lines);
602
+ const totalWords = wordSegments.length;
603
+ const visibleWords = Math.floor(progress * totalWords);
604
+ if (visibleWords === 0) return ops.filter((x) => x.op === "BeginFrame");
605
+ let totalVisibleGlyphs = 0;
606
+ for (let i = 0; i < Math.min(visibleWords, wordSegments.length); i++) {
607
+ totalVisibleGlyphs += wordSegments[i].glyphCount;
608
+ }
609
+ const visibleOpsRaw = sliceGlyphOps(ops, totalVisibleGlyphs);
610
+ const visibleOps = progress >= DECORATION_DONE_THRESHOLD ? visibleOpsRaw : visibleOpsRaw.filter((o) => o.op !== "DecorationLine");
611
+ if (progress < 1 && totalVisibleGlyphs > 0) {
612
+ return addTypewriterCursor(visibleOps, totalVisibleGlyphs, fontSize, time);
613
+ }
614
+ return visibleOps;
615
+ } else {
616
+ const totalGlyphs = lines.reduce((s, l) => s + l.glyphs.length, 0);
617
+ const visibleGlyphs = Math.floor(progress * totalGlyphs);
618
+ if (visibleGlyphs === 0) return ops.filter((x) => x.op === "BeginFrame");
619
+ const visibleOpsRaw = sliceGlyphOps(ops, visibleGlyphs);
620
+ const visibleOps = progress >= DECORATION_DONE_THRESHOLD ? visibleOpsRaw : visibleOpsRaw.filter((o) => o.op !== "DecorationLine");
621
+ if (progress < 1 && visibleGlyphs > 0) {
622
+ return addTypewriterCursor(visibleOps, visibleGlyphs, fontSize, time);
623
+ }
624
+ return visibleOps;
625
+ }
626
+ }
627
+ function applyAscendAnimation(ops, lines, progress, direction, fontSize, duration) {
628
+ const wordSegments = getWordSegments(lines);
629
+ const totalWords = wordSegments.length;
630
+ if (totalWords === 0) return ops;
631
+ const result = [];
632
+ let glyphIndex = 0;
633
+ for (const op of ops) {
634
+ if (op.op === "BeginFrame") {
635
+ result.push(op);
636
+ break;
637
+ }
638
+ }
639
+ for (const op of ops) {
640
+ if (op.op === "FillPath" || op.op === "StrokePath") {
641
+ let wordIndex = -1, acc = 0;
642
+ for (let i = 0; i < wordSegments.length; i++) {
643
+ const gcount = wordSegments[i].glyphCount;
644
+ if (glyphIndex >= acc && glyphIndex < acc + gcount) {
645
+ wordIndex = i;
646
+ break;
647
+ }
648
+ acc += gcount;
649
+ }
650
+ if (wordIndex >= 0) {
651
+ const startF = wordIndex / Math.max(1, totalWords) * (duration / duration);
652
+ const endF = Math.min(1, startF + 0.3);
653
+ if (progress >= endF) {
654
+ result.push(op);
655
+ } else if (progress > startF) {
656
+ const local = (progress - startF) / Math.max(1e-6, endF - startF);
657
+ const ease = easeOutCubic(Math.min(1, local));
658
+ const startOffset = direction === "up" ? fontSize * 0.4 : -fontSize * 0.4;
659
+ const animated = { ...op, y: op.y + startOffset * (1 - ease) };
660
+ if (op.op === "FillPath") {
661
+ if (animated.fill.kind === "solid")
662
+ animated.fill = { ...animated.fill, opacity: animated.fill.opacity * ease };
663
+ else animated.fill = { ...animated.fill, opacity: (animated.fill.opacity ?? 1) * ease };
664
+ } else {
665
+ animated.opacity = animated.opacity * ease;
666
+ }
667
+ result.push(animated);
668
+ }
669
+ }
670
+ if (isGlyphFill(op)) glyphIndex++;
671
+ } else if (op.op === "DecorationLine") {
672
+ if (progress >= DECORATION_DONE_THRESHOLD) {
673
+ result.push(op);
674
+ }
675
+ }
676
+ }
677
+ return result;
678
+ }
679
+ function applyShiftAnimation(ops, lines, progress, direction, fontSize, style, duration) {
680
+ const byWord = style === "word";
681
+ const startOffsets = {
682
+ left: { x: fontSize * 0.6, y: 0 },
683
+ right: { x: -fontSize * 0.6, y: 0 },
684
+ up: { x: 0, y: fontSize * 0.6 },
685
+ down: { x: 0, y: -fontSize * 0.6 }
686
+ };
687
+ const offset = startOffsets[direction];
688
+ const wordSegments = byWord ? getWordSegments(lines) : [];
689
+ const totalGlyphs = lines.reduce((s, l) => s + l.glyphs.length, 0);
690
+ const totalUnits = byWord ? wordSegments.length : totalGlyphs;
691
+ if (totalUnits === 0) return ops;
692
+ const result = [];
693
+ for (const op of ops) {
694
+ if (op.op === "BeginFrame") {
695
+ result.push(op);
696
+ break;
697
+ }
698
+ }
699
+ const windowDuration = 0.3;
700
+ const overlapFactor = 0.7;
701
+ const staggerDelay = duration * overlapFactor / Math.max(1, totalUnits - 1);
702
+ const windowFor = (unitIdx) => {
703
+ const startTime = unitIdx * staggerDelay;
704
+ const startF = startTime / duration;
705
+ const endF = Math.min(1, (startTime + windowDuration) / duration);
706
+ return { startF, endF };
707
+ };
708
+ let glyphIndex = 0;
709
+ for (const op of ops) {
710
+ if (op.op !== "FillPath" && op.op !== "StrokePath") {
711
+ if (op.op === "DecorationLine" && progress > 0.8) result.push(op);
712
+ continue;
713
+ }
714
+ let unitIndex;
715
+ if (!byWord) {
716
+ unitIndex = glyphIndex;
717
+ } else {
718
+ let wordIndex = -1, acc = 0;
719
+ for (let i = 0; i < wordSegments.length; i++) {
720
+ const gcount = wordSegments[i].glyphCount;
721
+ if (glyphIndex >= acc && glyphIndex < acc + gcount) {
722
+ wordIndex = i;
723
+ break;
724
+ }
725
+ acc += gcount;
726
+ }
727
+ unitIndex = Math.max(0, wordIndex);
728
+ }
729
+ const { startF, endF } = windowFor(unitIndex);
730
+ if (progress <= startF) {
731
+ const animated = { ...op, x: op.x + offset.x, y: op.y + offset.y };
732
+ if (op.op === "FillPath") {
733
+ if (animated.fill.kind === "solid") animated.fill = { ...animated.fill, opacity: 0 };
734
+ else animated.fill = { ...animated.fill, opacity: 0 };
735
+ } else {
736
+ animated.opacity = 0;
737
+ }
738
+ result.push(animated);
739
+ } else if (progress >= endF) {
740
+ result.push(op);
741
+ } else {
742
+ const local = (progress - startF) / Math.max(1e-6, endF - startF);
743
+ const ease = easeOutCubic(Math.min(1, local));
744
+ const dx = offset.x * (1 - ease);
745
+ const dy = offset.y * (1 - ease);
746
+ const animated = { ...op, x: op.x + dx, y: op.y + dy };
747
+ if (op.op === "FillPath") {
748
+ const targetOpacity = animated.fill.kind === "solid" ? animated.fill.opacity : animated.fill.opacity ?? 1;
749
+ if (animated.fill.kind === "solid")
750
+ animated.fill = { ...animated.fill, opacity: targetOpacity * ease };
751
+ else animated.fill = { ...animated.fill, opacity: targetOpacity * ease };
752
+ } else {
753
+ animated.opacity = animated.opacity * ease;
754
+ }
755
+ result.push(animated);
756
+ }
757
+ if (isGlyphFill(op)) glyphIndex++;
758
+ }
759
+ return result;
760
+ }
761
+ function applyFadeInAnimation(ops, progress) {
762
+ const alpha = easeOutQuad(progress);
763
+ const scale = 0.95 + 0.05 * alpha;
764
+ return scaleAndFade(ops, alpha, scale);
765
+ }
766
+ function applySlideInAnimation(ops, progress, direction, fontSize) {
767
+ const easeProgress = easeOutCubic(progress);
768
+ const shift = shiftFor(1 - easeProgress, direction, fontSize * 2);
769
+ const alpha = easeOutQuad(progress);
770
+ return translateGlyphOps(ops, shift.dx, shift.dy, alpha);
771
+ }
772
+ function applyMovingLettersAnimation(ops, progress, direction, fontSize) {
773
+ const amp = fontSize * 0.3;
774
+ return waveTransform(ops, direction, amp, progress);
775
+ }
776
+ function getWordSegments(lines) {
777
+ const segments = [];
778
+ let totalGlyphIndex = 0;
779
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
780
+ const line = lines[lineIndex];
781
+ const words = segmentLineBySpaces(line);
782
+ for (const word of words) {
783
+ if (word.length > 0)
784
+ segments.push({ startGlyph: totalGlyphIndex, glyphCount: word.length, lineIndex });
785
+ totalGlyphIndex += word.length;
786
+ }
787
+ }
788
+ return segments;
789
+ }
790
+ function segmentLineBySpaces(line) {
791
+ const words = [];
792
+ let current = [];
793
+ for (const g of line.glyphs) {
794
+ const isSpace = g.char === " " || g.char === " " || g.char === "\n";
795
+ if (isSpace) {
796
+ if (current.length) {
797
+ words.push([...current]);
798
+ current = [];
799
+ }
800
+ } else {
801
+ current.push(g);
802
+ }
803
+ }
804
+ if (current.length) words.push(current);
805
+ return words;
806
+ }
807
+ function sliceGlyphOps(ops, maxGlyphs) {
808
+ const result = [];
809
+ let glyphCount = 0;
810
+ let foundGlyphs = false;
811
+ for (const op of ops) {
812
+ if (op.op === "BeginFrame") {
813
+ result.push(op);
814
+ continue;
815
+ }
816
+ if (op.op === "FillPath" && !isShadowFill(op)) {
817
+ if (glyphCount < maxGlyphs) {
818
+ result.push(op);
819
+ foundGlyphs = true;
820
+ }
821
+ glyphCount++;
822
+ continue;
823
+ }
824
+ if (op.op === "StrokePath") {
825
+ if (glyphCount < maxGlyphs) result.push(op);
826
+ continue;
827
+ }
828
+ if (op.op === "FillPath" && isShadowFill(op)) {
829
+ if (glyphCount < maxGlyphs) result.push(op);
830
+ continue;
831
+ }
832
+ if (op.op === "DecorationLine" && foundGlyphs) {
833
+ result.push(op);
834
+ continue;
835
+ }
836
+ }
837
+ return result;
838
+ }
839
+ function addTypewriterCursor(ops, glyphCount, fontSize, time) {
840
+ const blinkRate = 2;
841
+ const cursorVisible = Math.floor(time * blinkRate * 2) % 2 === 0;
842
+ if (!cursorVisible || glyphCount === 0) return ops;
843
+ let last = null;
844
+ let count = 0;
845
+ for (const op of ops) {
846
+ if (op.op === "FillPath" && !isShadowFill(op)) {
847
+ count++;
848
+ if (count === glyphCount) {
849
+ last = op;
850
+ break;
851
+ }
852
+ }
853
+ }
854
+ if (last && last.op === "FillPath") {
855
+ const color = getTextColorFromOps(ops);
856
+ const cursorX = last.x + fontSize * 0.5;
857
+ const cursorY = last.y;
858
+ const cursorOp = {
859
+ op: "DecorationLine",
860
+ from: { x: cursorX, y: cursorY - fontSize * 0.7 },
861
+ to: { x: cursorX, y: cursorY + fontSize * 0.1 },
862
+ width: Math.max(2, fontSize / 25),
863
+ color,
864
+ opacity: 1
865
+ };
866
+ return [...ops, cursorOp];
867
+ }
868
+ return ops;
869
+ }
870
+ function scaleAndFade(ops, alpha, scale) {
871
+ let cx = 0, cy = 0, n = 0;
872
+ ops.forEach((op) => {
873
+ if (op.op === "FillPath") {
874
+ cx += op.x;
875
+ cy += op.y;
876
+ n++;
877
+ }
878
+ });
879
+ if (n > 0) {
880
+ cx /= n;
881
+ cy /= n;
882
+ }
883
+ return ops.map((op) => {
884
+ if (op.op === "FillPath") {
885
+ const out = { ...op };
886
+ if (out.fill.kind === "solid") out.fill = { ...out.fill, opacity: out.fill.opacity * alpha };
887
+ else out.fill = { ...out.fill, opacity: (out.fill.opacity ?? 1) * alpha };
888
+ if (scale !== 1 && n > 0) {
889
+ const dx = op.x - cx, dy = op.y - cy;
890
+ out.x = cx + dx * scale;
891
+ out.y = cy + dy * scale;
892
+ }
893
+ return out;
894
+ }
895
+ if (op.op === "StrokePath") {
896
+ const out = { ...op, opacity: op.opacity * alpha };
897
+ if (scale !== 1 && n > 0) {
898
+ const dx = op.x - cx, dy = op.y - cy;
899
+ out.x = cx + dx * scale;
900
+ out.y = cy + dy * scale;
901
+ }
902
+ return out;
903
+ }
904
+ if (op.op === "DecorationLine") return { ...op, opacity: op.opacity * alpha };
905
+ return op;
906
+ });
907
+ }
908
+ function translateGlyphOps(ops, dx, dy, alpha = 1) {
909
+ return ops.map((op) => {
910
+ if (op.op === "FillPath") {
911
+ const out = { ...op, x: op.x + dx, y: op.y + dy };
912
+ if (alpha < 1) {
913
+ if (out.fill.kind === "solid")
914
+ out.fill = { ...out.fill, opacity: out.fill.opacity * alpha };
915
+ else out.fill = { ...out.fill, opacity: (out.fill.opacity ?? 1) * alpha };
916
+ }
917
+ return out;
918
+ }
919
+ if (op.op === "StrokePath")
920
+ return { ...op, x: op.x + dx, y: op.y + dy, opacity: op.opacity * alpha };
921
+ if (op.op === "DecorationLine") {
922
+ return {
923
+ ...op,
924
+ from: { x: op.from.x + dx, y: op.from.y + dy },
925
+ to: { x: op.to.x + dx, y: op.to.y + dy },
926
+ opacity: op.opacity * alpha
927
+ };
928
+ }
929
+ return op;
930
+ });
931
+ }
932
+ function waveTransform(ops, dir, amp, p) {
933
+ let glyphIndex = 0;
934
+ return ops.map((op) => {
935
+ if (op.op === "FillPath" || op.op === "StrokePath") {
936
+ const phase = Math.sin(glyphIndex / 5 * Math.PI + p * Math.PI * 4);
937
+ const dx = dir === "left" || dir === "right" ? phase * amp * (dir === "left" ? -1 : 1) : 0;
938
+ const dy = dir === "up" || dir === "down" ? phase * amp * (dir === "up" ? -1 : 1) : 0;
939
+ const waveAlpha = Math.min(1, p * 2);
940
+ if (op.op === "FillPath") {
941
+ if (!isShadowFill(op)) glyphIndex++;
942
+ const out = { ...op, x: op.x + dx, y: op.y + dy };
943
+ if (out.fill.kind === "solid")
944
+ out.fill = { ...out.fill, opacity: out.fill.opacity * waveAlpha };
945
+ else out.fill = { ...out.fill, opacity: (out.fill.opacity ?? 1) * waveAlpha };
946
+ return out;
947
+ }
948
+ return { ...op, x: op.x + dx, y: op.y + dy, opacity: op.opacity * waveAlpha };
949
+ }
950
+ return op;
951
+ });
952
+ }
953
+ function shiftFor(progress, dir, dist) {
954
+ const d = progress * dist;
955
+ switch (dir) {
956
+ case "left":
957
+ return { dx: -d, dy: 0 };
958
+ case "right":
959
+ return { dx: d, dy: 0 };
960
+ case "up":
961
+ return { dx: 0, dy: -d };
962
+ case "down":
963
+ return { dx: 0, dy: d };
964
+ }
965
+ }
966
+ function easeOutQuad(t) {
967
+ return t * (2 - t);
968
+ }
969
+ function easeOutCubic(t) {
970
+ return 1 - Math.pow(1 - t, 3);
971
+ }
972
+
973
+ // src/core/colors.ts
974
+ function parseHex6(hex, alpha = 1) {
975
+ const m = /^#?([a-f0-9]{6})$/i.exec(hex);
976
+ if (!m) throw new Error(`Invalid color ${hex}`);
977
+ const n = parseInt(m[1], 16);
978
+ const r = n >> 16 & 255;
979
+ const g = n >> 8 & 255;
980
+ const b = n & 255;
981
+ return { r, g, b, a: alpha };
982
+ }
983
+
984
+ // src/painters/web.ts
985
+ function createWebPainter(canvas) {
986
+ const ctx = canvas.getContext("2d");
987
+ if (!ctx) throw new Error("2D context unavailable");
988
+ return {
989
+ async render(ops) {
990
+ const globalBox = computeGlobalTextBounds(ops);
991
+ for (const op of ops) {
992
+ if (op.op === "BeginFrame") {
993
+ const dpr = op.pixelRatio;
994
+ const w = op.width, h = op.height;
995
+ if ("width" in canvas && "height" in canvas) {
996
+ canvas.width = Math.floor(w * dpr);
997
+ canvas.height = Math.floor(h * dpr);
998
+ }
999
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
1000
+ if (op.clear) ctx.clearRect(0, 0, w, h);
1001
+ if (op.bg) {
1002
+ const { color, opacity, radius } = op.bg;
1003
+ if (color) {
1004
+ const c = parseHex6(color, opacity);
1005
+ ctx.fillStyle = `rgba(${c.r},${c.g},${c.b},${c.a})`;
1006
+ if (radius && radius > 0) {
1007
+ drawRoundedRect(ctx, 0, 0, w, h, radius);
1008
+ ctx.fill();
1009
+ } else {
1010
+ ctx.fillRect(0, 0, w, h);
1011
+ }
1012
+ }
1013
+ }
1014
+ continue;
1015
+ }
1016
+ if (op.op === "FillPath") {
1017
+ const p = new Path2D(op.path);
1018
+ ctx.save();
1019
+ ctx.translate(op.x, op.y);
1020
+ const s = op.scale ?? 1;
1021
+ ctx.scale(s, -s);
1022
+ const bbox = op.gradientBBox ?? globalBox;
1023
+ const fill = makeGradientFromBBox(ctx, op.fill, bbox);
1024
+ ctx.fillStyle = fill;
1025
+ ctx.fill(p);
1026
+ ctx.restore();
1027
+ continue;
1028
+ }
1029
+ if (op.op === "StrokePath") {
1030
+ const p = new Path2D(op.path);
1031
+ ctx.save();
1032
+ ctx.translate(op.x, op.y);
1033
+ const s = op.scale ?? 1;
1034
+ ctx.scale(s, -s);
1035
+ const invAbs = 1 / Math.abs(s);
1036
+ const c = parseHex6(op.color, op.opacity);
1037
+ ctx.strokeStyle = `rgba(${c.r},${c.g},${c.b},${c.a})`;
1038
+ ctx.lineWidth = op.width * invAbs;
1039
+ ctx.lineJoin = "round";
1040
+ ctx.lineCap = "round";
1041
+ ctx.stroke(p);
1042
+ ctx.restore();
1043
+ continue;
1044
+ }
1045
+ if (op.op === "DecorationLine") {
1046
+ ctx.save();
1047
+ const c = parseHex6(op.color, op.opacity);
1048
+ ctx.strokeStyle = `rgba(${c.r},${c.g},${c.b},${c.a})`;
1049
+ ctx.lineWidth = op.width;
1050
+ ctx.beginPath();
1051
+ ctx.moveTo(op.from.x, op.from.y);
1052
+ ctx.lineTo(op.to.x, op.to.y);
1053
+ ctx.stroke();
1054
+ ctx.restore();
1055
+ continue;
1056
+ }
1057
+ }
1058
+ }
1059
+ };
1060
+ }
1061
+ function drawRoundedRect(ctx, x, y, w, h, r) {
1062
+ const p = new Path2D();
1063
+ p.moveTo(x + r, y);
1064
+ p.arcTo(x + w, y, x + w, y + h, r);
1065
+ p.arcTo(x + w, y + h, x, y + h, r);
1066
+ p.arcTo(x, y + h, x, y, r);
1067
+ p.arcTo(x, y, x + w, y, r);
1068
+ p.closePath();
1069
+ ctx.save();
1070
+ ctx.fill(p);
1071
+ ctx.restore();
1072
+ }
1073
+ function makeGradientFromBBox(ctx, spec, box) {
1074
+ if (spec.kind === "solid") {
1075
+ const c = parseHex6(spec.color, spec.opacity);
1076
+ return `rgba(${c.r},${c.g},${c.b},${c.a})`;
1077
+ }
1078
+ const cx = box.x + box.w / 2, cy = box.y + box.h / 2, r = Math.max(box.w, box.h) / 2;
1079
+ const addStops = (g) => {
1080
+ const op = spec.opacity ?? 1;
1081
+ for (const s of spec.stops) {
1082
+ const c = parseHex6(s.color, op);
1083
+ g.addColorStop(s.offset, `rgba(${c.r},${c.g},${c.b},${c.a})`);
1084
+ }
1085
+ return g;
1086
+ };
1087
+ if (spec.kind === "linear") {
1088
+ const rad = (spec.angle || 0) * Math.PI / 180;
1089
+ const x1 = cx + Math.cos(rad + Math.PI) * r;
1090
+ const y1 = cy + Math.sin(rad + Math.PI) * r;
1091
+ const x2 = cx + Math.cos(rad) * r;
1092
+ const y2 = cy + Math.sin(rad) * r;
1093
+ return addStops(ctx.createLinearGradient(x1, y1, x2, y2));
1094
+ } else {
1095
+ return addStops(ctx.createRadialGradient(cx, cy, 0, cx, cy, r));
1096
+ }
1097
+ }
1098
+ function computeGlobalTextBounds(ops) {
1099
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
1100
+ for (const op of ops) {
1101
+ if (op.op !== "FillPath" || op.isShadow) continue;
1102
+ const b = computePathBounds2(op.path);
1103
+ const s = op.scale ?? 1;
1104
+ const x1 = op.x + s * b.x;
1105
+ const x2 = op.x + s * (b.x + b.w);
1106
+ const y1 = op.y - s * (b.y + b.h);
1107
+ const y2 = op.y - s * b.y;
1108
+ if (x1 < minX) minX = x1;
1109
+ if (y1 < minY) minY = y1;
1110
+ if (x2 > maxX) maxX = x2;
1111
+ if (y2 > maxY) maxY = y2;
1112
+ }
1113
+ if (minX === Infinity) return { x: 0, y: 0, w: 1, h: 1 };
1114
+ return { x: minX, y: minY, w: Math.max(1, maxX - minX), h: Math.max(1, maxY - minY) };
1115
+ }
1116
+ function computePathBounds2(d) {
1117
+ const tokens = tokenizePath2(d);
1118
+ let i = 0;
1119
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
1120
+ const touch = (x, y) => {
1121
+ if (x < minX) minX = x;
1122
+ if (y < minY) minY = y;
1123
+ if (x > maxX) maxX = x;
1124
+ if (y > maxY) maxY = y;
1125
+ };
1126
+ while (i < tokens.length) {
1127
+ const t = tokens[i++];
1128
+ switch (t) {
1129
+ case "M":
1130
+ case "L": {
1131
+ const x = parseFloat(tokens[i++]);
1132
+ const y = parseFloat(tokens[i++]);
1133
+ touch(x, y);
1134
+ break;
1135
+ }
1136
+ case "C": {
1137
+ const c1x = parseFloat(tokens[i++]);
1138
+ const c1y = parseFloat(tokens[i++]);
1139
+ const c2x = parseFloat(tokens[i++]);
1140
+ const c2y = parseFloat(tokens[i++]);
1141
+ const x = parseFloat(tokens[i++]);
1142
+ const y = parseFloat(tokens[i++]);
1143
+ touch(c1x, c1y);
1144
+ touch(c2x, c2y);
1145
+ touch(x, y);
1146
+ break;
1147
+ }
1148
+ case "Q": {
1149
+ const cx = parseFloat(tokens[i++]);
1150
+ const cy = parseFloat(tokens[i++]);
1151
+ const x = parseFloat(tokens[i++]);
1152
+ const y = parseFloat(tokens[i++]);
1153
+ touch(cx, cy);
1154
+ touch(x, y);
1155
+ break;
1156
+ }
1157
+ case "Z":
1158
+ break;
1159
+ }
1160
+ }
1161
+ if (minX === Infinity) return { x: 0, y: 0, w: 0, h: 0 };
1162
+ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
1163
+ }
1164
+ function tokenizePath2(d) {
1165
+ return d.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi) ?? [];
1166
+ }
1167
+
1168
+ // src/io/web.ts
1169
+ async function fetchToArrayBuffer(url) {
1170
+ const res = await fetch(url);
1171
+ if (!res.ok) throw new Error(`Failed to fetch ${url}: ${res.status}`);
1172
+ return await res.arrayBuffer();
1173
+ }
1174
+
1175
+ // src/env/entry.web.ts
1176
+ async function createTextEngine(opts = {}) {
1177
+ const width = opts.width ?? CANVAS_CONFIG.DEFAULTS.width;
1178
+ const height = opts.height ?? CANVAS_CONFIG.DEFAULTS.height;
1179
+ const pixelRatio = opts.pixelRatio ?? CANVAS_CONFIG.DEFAULTS.pixelRatio;
1180
+ const wasmBaseURL = opts.wasmBaseURL;
1181
+ const fonts = new FontRegistry(wasmBaseURL);
1182
+ const layout = new LayoutEngine(fonts);
1183
+ async function ensureFonts(asset) {
1184
+ if (asset.customFonts) {
1185
+ for (const cf of asset.customFonts) {
1186
+ const bytes = await fetchToArrayBuffer(cf.src);
1187
+ await fonts.registerFromBytes(bytes, {
1188
+ family: cf.family,
1189
+ weight: cf.weight ?? "400",
1190
+ style: cf.style ?? "normal"
1191
+ });
1192
+ }
1193
+ }
1194
+ const main = asset.font ?? {
1195
+ family: "Roboto",
1196
+ weight: "400",
1197
+ style: "normal",
1198
+ size: 48,
1199
+ color: "#000000",
1200
+ opacity: 1
1201
+ };
1202
+ return main;
1203
+ }
1204
+ return {
1205
+ validate(input) {
1206
+ const { value, error } = RichTextAssetSchema.validate(input, {
1207
+ abortEarly: false,
1208
+ convert: true
1209
+ });
1210
+ if (error) throw error;
1211
+ return { value };
1212
+ },
1213
+ async registerFontFromUrl(url, desc) {
1214
+ const bytes = await fetchToArrayBuffer(url);
1215
+ await fonts.registerFromBytes(bytes, desc);
1216
+ },
1217
+ async registerFontFromFile(source, desc) {
1218
+ let bytes;
1219
+ if (typeof source === "string") {
1220
+ bytes = await fetchToArrayBuffer(source);
1221
+ } else {
1222
+ bytes = await source.arrayBuffer();
1223
+ }
1224
+ await fonts.registerFromBytes(bytes, desc);
1225
+ },
1226
+ async renderFrame(asset, tSeconds) {
1227
+ const main = await ensureFonts(asset);
1228
+ const desc = { family: main.family, weight: `${main.weight}`, style: main.style };
1229
+ const lines = layout.layout({
1230
+ text: asset.text,
1231
+ width: asset.width ?? width,
1232
+ letterSpacing: asset.style?.letterSpacing ?? 0,
1233
+ fontSize: main.size,
1234
+ lineHeight: asset.style?.lineHeight ?? 1.2,
1235
+ desc,
1236
+ textTransform: asset.style?.textTransform ?? "none"
1237
+ });
1238
+ const textRect = { x: 0, y: 0, width: asset.width ?? width, height: asset.height ?? height };
1239
+ const ops0 = buildDrawOps({
1240
+ canvas: { width, height, pixelRatio },
1241
+ textRect,
1242
+ lines,
1243
+ font: {
1244
+ family: main.family,
1245
+ size: main.size,
1246
+ weight: `${main.weight}`,
1247
+ style: main.style,
1248
+ color: main.color,
1249
+ opacity: main.opacity
1250
+ },
1251
+ style: {
1252
+ lineHeight: asset.style?.lineHeight ?? 1.2,
1253
+ textDecoration: asset.style?.textDecoration ?? "none",
1254
+ gradient: asset.style?.gradient
1255
+ },
1256
+ stroke: asset.stroke,
1257
+ shadow: asset.shadow,
1258
+ align: asset.align ?? { horizontal: "left", vertical: "middle" },
1259
+ background: asset.background,
1260
+ glyphPathProvider: (gid) => fonts.glyphPath(desc, gid),
1261
+ /** NEW: provide UPEM so drawops can compute scale */
1262
+ getUnitsPerEm: () => fonts.getUnitsPerEm(desc)
1263
+ });
1264
+ const ops = applyAnimation(ops0, lines, {
1265
+ t: tSeconds,
1266
+ fontSize: main.size,
1267
+ anim: asset.animation ? {
1268
+ preset: asset.animation.preset,
1269
+ speed: asset.animation.speed,
1270
+ duration: asset.animation.duration,
1271
+ style: asset.animation.style,
1272
+ direction: asset.animation.direction
1273
+ } : void 0
1274
+ });
1275
+ return ops;
1276
+ },
1277
+ createRenderer(canvas) {
1278
+ return createWebPainter(canvas);
1279
+ }
1280
+ };
1281
+ }
1282
+ export {
1283
+ createTextEngine
1284
+ };
1285
+ //# sourceMappingURL=entry.web.js.map