@clypra-studio/engine 1.4.0 → 1.5.0

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 (36) hide show
  1. package/dist/{chunk-E6O6LZME.js → chunk-7ORA5BPW.js} +14 -299
  2. package/dist/chunk-7ORA5BPW.js.map +1 -0
  3. package/dist/chunk-NG4F55V7.js +300 -0
  4. package/dist/chunk-NG4F55V7.js.map +1 -0
  5. package/dist/chunk-Q7XYDP4X.js +1898 -0
  6. package/dist/chunk-Q7XYDP4X.js.map +1 -0
  7. package/dist/{chunk-3UEOLDJJ.js → chunk-SH7HOGVX.js} +1 -1
  8. package/dist/chunk-SH7HOGVX.js.map +1 -0
  9. package/dist/index-B1lFl4p2.d.ts +122 -0
  10. package/dist/index-Cpps1DKP.d.ts +489 -0
  11. package/dist/index-DrzRbR7G.d.cts +122 -0
  12. package/dist/index-WsvrOpAy.d.cts +489 -0
  13. package/dist/index.cjs +3131 -482
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +185 -103
  16. package/dist/index.d.ts +185 -103
  17. package/dist/index.js +1599 -792
  18. package/dist/index.js.map +1 -1
  19. package/dist/rendering/index.cjs +3694 -0
  20. package/dist/rendering/index.cjs.map +1 -0
  21. package/dist/rendering/index.d.cts +2 -0
  22. package/dist/rendering/index.d.ts +2 -0
  23. package/dist/rendering/index.js +21 -0
  24. package/dist/rendering/index.js.map +1 -0
  25. package/dist/textEffects/index.cjs +13 -5
  26. package/dist/textEffects/index.cjs.map +1 -1
  27. package/dist/textEffects/index.d.cts +2 -1
  28. package/dist/textEffects/index.d.ts +2 -1
  29. package/dist/textEffects/index.js +6 -4
  30. package/dist/{index-C18SQ-y6.d.cts → types-IYwXGYkB.d.cts} +141 -129
  31. package/dist/{index-C18SQ-y6.d.ts → types-IYwXGYkB.d.ts} +141 -129
  32. package/dist/videoEffects/index.cjs.map +1 -1
  33. package/dist/videoEffects/index.js +1 -1
  34. package/package.json +6 -1
  35. package/dist/chunk-3UEOLDJJ.js.map +0 -1
  36. package/dist/chunk-E6O6LZME.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var index_exports = {};
21
21
  __export(index_exports, {
22
22
  ALL_TRANSITIONS: () => ALL_TRANSITIONS,
23
+ ASPECT_RATIO_PRESETS: () => ASPECT_RATIO_PRESETS,
23
24
  AnimationPresetSchema: () => AnimationPresetSchema,
24
25
  AnimationRuntime: () => AnimationRuntime,
25
26
  AnimationSchema: () => AnimationSchema,
@@ -73,7 +74,7 @@ __export(index_exports, {
73
74
  FrameGraphBuilder: () => FrameGraphBuilder,
74
75
  GifEncoder: () => GifEncoder,
75
76
  GradientStopSchema: () => GradientStopSchema,
76
- GraphHelper: () => import_types.GraphHelper,
77
+ GraphHelper: () => import_types2.GraphHelper,
77
78
  GraphValidator: () => GraphValidator,
78
79
  GridEngine: () => GridEngine,
79
80
  ImageLayerSchema: () => ImageLayerSchema,
@@ -113,6 +114,9 @@ __export(index_exports, {
113
114
  SmartOverlayRenderer: () => SmartOverlayRenderer,
114
115
  SnapEngine: () => SnapEngine,
115
116
  TEMPLATE_CATEGORIES: () => TEMPLATE_CATEGORIES,
117
+ TEXT_TEMPLATE_KIND: () => TEXT_TEMPLATE_KIND,
118
+ TEXT_TEMPLATE_RENDERER_VERSION: () => TEXT_TEMPLATE_RENDERER_VERSION,
119
+ TEXT_TEMPLATE_SCHEMA_VERSION: () => TEXT_TEMPLATE_SCHEMA_VERSION,
116
120
  TRANSITION_CATEGORIES: () => TRANSITION_CATEGORIES,
117
121
  TRANSITION_PRESETS: () => TRANSITION_PRESETS,
118
122
  TemplateCategorySchema: () => TemplateCategorySchema,
@@ -145,6 +149,7 @@ __export(index_exports, {
145
149
  alignToLottieJ: () => alignToLottieJ,
146
150
  animationRuntime: () => animationRuntime,
147
151
  animationValidator: () => animationValidator,
152
+ applyEasing: () => applyEasing,
148
153
  applyFillColorToAll: () => applyFillColorToAll,
149
154
  applyLetterSpacing: () => applyLetterSpacing,
150
155
  applyMaskReveal: () => applyMaskReveal,
@@ -152,6 +157,7 @@ __export(index_exports, {
152
157
  applyStyleToLottie: () => applyStyleToLottie,
153
158
  applyStyleToLottieLayer: () => applyStyleToLottieLayer,
154
159
  applyTimelineAtTime: () => applyTimelineAtTime,
160
+ assertValidTextTemplateArtifact: () => assertValidTextTemplateArtifact,
155
161
  assetRegistry: () => assetRegistry,
156
162
  bakeAnimationIntoLayer: () => bakeAnimationIntoLayer,
157
163
  blendColors: () => blendColors,
@@ -169,6 +175,7 @@ __export(index_exports, {
169
175
  calculateResizeBounds: () => calculateResizeBounds,
170
176
  calculateRotationAngle: () => calculateRotationAngle,
171
177
  canonicalContentHash: () => canonicalContentHash,
178
+ canonicalTemplateHash: () => canonicalTemplateHash,
172
179
  canonicalizeSceneDocument: () => canonicalizeSceneDocument,
173
180
  captureImageSourceDimensions: () => captureImageSourceDimensions,
174
181
  captureLottieFrames: () => captureLottieFrames,
@@ -181,6 +188,7 @@ __export(index_exports, {
181
188
  cloneSceneWithNewIds: () => cloneSceneWithNewIds,
182
189
  commandExecutor: () => commandExecutor,
183
190
  compileSemanticOverlay: () => compileSemanticOverlay,
191
+ compileTextTemplate: () => compileTextTemplate,
184
192
  componentRegistry: () => componentRegistry,
185
193
  computeAutoFitFontSize: () => computeAutoFitFontSize,
186
194
  computeFitZoom: () => computeFitZoom,
@@ -225,6 +233,7 @@ __export(index_exports, {
225
233
  evaluateExportFrame: () => evaluateExportFrame,
226
234
  evaluateOverlayDocument: () => evaluateOverlayDocument,
227
235
  evaluateScene: () => evaluateScene,
236
+ evaluateSplitTextTransforms: () => evaluateSplitTextTransforms,
228
237
  evaluateTextEffect: () => evaluateTextEffect,
229
238
  evaluateTextTemplate: () => evaluateTextTemplate,
230
239
  exportLottieToMp4: () => exportLottieToMp4,
@@ -257,9 +266,11 @@ __export(index_exports, {
257
266
  getRenderCapabilities: () => getRenderCapabilities,
258
267
  getSceneTime: () => getSceneTime,
259
268
  getSourceCropRect: () => getSourceCropRect,
269
+ getSpanForCharIndex: () => getSpanForCharIndex,
260
270
  getSupportedWebMMimeType: () => getSupportedWebMMimeType,
261
271
  getTemplatePreset: () => getTemplatePreset,
262
272
  getTemplatesByCategory: () => getTemplatesByCategory,
273
+ getTextTemplateControls: () => getTextTemplateControls,
263
274
  getTransitionById: () => getTransitionById,
264
275
  getTransitionByRenderer: () => getTransitionByRenderer,
265
276
  getTransitionCategories: () => getTransitionCategories,
@@ -279,6 +290,8 @@ __export(index_exports, {
279
290
  injectSolidColor: () => injectSolidColor,
280
291
  injectText: () => injectText,
281
292
  injectTextStyle: () => injectTextStyle,
293
+ interpolateColorString: () => interpolateColorString,
294
+ interpolateValue: () => interpolateValue,
282
295
  isKeyframed: () => isKeyframed,
283
296
  isMp4ExportSupported: () => isMp4ExportSupported,
284
297
  isWebMExportSupported: () => isWebMExportSupported,
@@ -297,6 +310,7 @@ __export(index_exports, {
297
310
  newLayerId: () => newLayerId,
298
311
  normalizeTextEffect: () => normalizeTextEffect,
299
312
  normalizeTextTemplate: () => normalizeTextTemplate,
313
+ normalizeTextTemplateArtifact: () => normalizeTextTemplateArtifact,
300
314
  parseHistorySnapshot: () => parseHistorySnapshot,
301
315
  parseLottieJson: () => parseLottieJson,
302
316
  preloadGoogleFont: () => preloadGoogleFont,
@@ -314,12 +328,17 @@ __export(index_exports, {
314
328
  removeKeyframe: () => removeKeyframe,
315
329
  removeTemplateKeyframe: () => removeTemplateKeyframe,
316
330
  removeTrack: () => removeTrack,
331
+ renderCanonicalToCanvas: () => renderCanonicalToCanvas,
332
+ renderEvaluatedSceneToCanvas: () => renderEvaluatedSceneToCanvas,
317
333
  renderPngSequence: () => renderPngSequence,
318
334
  renderSceneWebM: () => renderSceneWebM,
319
335
  renderTextEffectCore: () => renderTextEffectCore,
336
+ renderTextEffectToCanvas: () => renderTextEffectToCanvas,
337
+ renderTextTemplateToCanvas: () => renderTextTemplateToCanvas,
320
338
  resetFontLoader: () => resetFontLoader,
321
339
  resetSceneTime: () => resetSceneTime,
322
340
  resizeCharFillColors: () => resizeCharFillColors,
341
+ resolveAnchorPosition: () => resolveAnchorPosition,
323
342
  resolveAnimatedScalar: () => resolveAnimatedScalar,
324
343
  resolveBehaviorToAnimationSpec: () => resolveBehaviorToAnimationSpec,
325
344
  resolveConform: () => resolveConform,
@@ -329,6 +348,7 @@ __export(index_exports, {
329
348
  resolveMediaLayout: () => resolveMediaLayout,
330
349
  resolveNodeForBreakpoint: () => resolveNodeForBreakpoint,
331
350
  resolveSpatialConstraints: () => resolveSpatialConstraints,
351
+ resolveTextTemplateArtifact: () => resolveTextTemplateArtifact,
332
352
  restoreLetterSpacing: () => restoreLetterSpacing,
333
353
  rgbaToComponents: () => rgbaToComponents,
334
354
  rotateCrop: () => rotateCrop,
@@ -349,7 +369,9 @@ __export(index_exports, {
349
369
  smartOverlayRegistry: () => smartOverlayRegistry,
350
370
  snapEngine: () => snapEngine,
351
371
  snapshotScene: () => snapshotScene,
372
+ solveSpring: () => solveSpring,
352
373
  sortKeyframes: () => sortKeyframes,
374
+ splitTextContent: () => splitTextContent,
353
375
  streamExportFrames: () => streamExportFrames,
354
376
  supportsCtxFilter: () => supportsCtxFilter,
355
377
  supportsLetterSpacing: () => supportsLetterSpacing,
@@ -378,6 +400,7 @@ __export(index_exports, {
378
400
  validateTextEffectDefinition: () => validateTextEffectDefinition,
379
401
  validateTextEffectDefinitionStrict: () => validateTextEffectDefinitionStrict,
380
402
  validateTextTemplate: () => validateTextTemplate,
403
+ validateTextTemplateArtifact: () => validateTextTemplateArtifact,
381
404
  validateTextTemplateStrict: () => validateTextTemplateStrict,
382
405
  viewportTransform: () => viewportTransform,
383
406
  waitForFontsReady: () => waitForFontsReady,
@@ -967,12 +990,20 @@ var _roundRect = null;
967
990
  var _letterSpacing = null;
968
991
  var _offscreenCanvas = null;
969
992
  function probe2d() {
970
- if (typeof document === "undefined") return null;
971
- try {
972
- return document.createElement("canvas").getContext("2d");
973
- } catch {
974
- return null;
993
+ if (typeof OffscreenCanvas !== "undefined") {
994
+ try {
995
+ return new OffscreenCanvas(1, 1).getContext("2d");
996
+ } catch {
997
+ }
998
+ }
999
+ if (typeof document !== "undefined") {
1000
+ try {
1001
+ return document.createElement("canvas").getContext("2d");
1002
+ } catch {
1003
+ return null;
1004
+ }
975
1005
  }
1006
+ return null;
976
1007
  }
977
1008
  function supportsCtxFilter() {
978
1009
  if (_ctxFilter !== null) return _ctxFilter;
@@ -2022,9 +2053,9 @@ function renderTextEffectCore(ctx, cfg) {
2022
2053
  const isLight = rand() > 0.5;
2023
2054
  const grad = patCtx.createLinearGradient(x, 0, x + w, 0);
2024
2055
  const baseColor = isLight ? "255,255,255" : "0,0,0";
2025
- const alpha = 0.01 + rand() * 0.04;
2056
+ const alpha2 = 0.01 + rand() * 0.04;
2026
2057
  grad.addColorStop(0, `rgba(${baseColor}, 0)`);
2027
- grad.addColorStop(0.5, `rgba(${baseColor}, ${alpha})`);
2058
+ grad.addColorStop(0.5, `rgba(${baseColor}, ${alpha2})`);
2028
2059
  grad.addColorStop(1, `rgba(${baseColor}, 0)`);
2029
2060
  patCtx.fillStyle = grad;
2030
2061
  patCtx.globalAlpha = 1;
@@ -2042,10 +2073,10 @@ function renderTextEffectCore(ctx, cfg) {
2042
2073
  const r = 40 + rand() * 70;
2043
2074
  const grad = patCtx.createRadialGradient(cx, cy, 0, cx, cy, r);
2044
2075
  const isLight = rand() > 0.45;
2045
- const alpha = 0.06 + rand() * 0.12;
2076
+ const alpha2 = 0.06 + rand() * 0.12;
2046
2077
  const cStr = isLight ? "255,255,255" : "0,0,0";
2047
- grad.addColorStop(0, `rgba(${cStr}, ${alpha})`);
2048
- grad.addColorStop(0.5, `rgba(${cStr}, ${alpha * 0.4})`);
2078
+ grad.addColorStop(0, `rgba(${cStr}, ${alpha2})`);
2079
+ grad.addColorStop(0.5, `rgba(${cStr}, ${alpha2 * 0.4})`);
2049
2080
  grad.addColorStop(1, `rgba(${cStr}, 0)`);
2050
2081
  patCtx.fillStyle = grad;
2051
2082
  patCtx.globalAlpha = 1;
@@ -2150,10 +2181,10 @@ function renderTextEffectCore(ctx, cfg) {
2150
2181
  const p3 = points[Math.floor(rand() * points.length)];
2151
2182
  if (p1 !== p2 && p2 !== p3) {
2152
2183
  const grad = patCtx.createLinearGradient(p1[0], p1[1], p2[0], p2[1]);
2153
- const alpha = 0.01 + rand() * 0.06;
2184
+ const alpha2 = 0.01 + rand() * 0.06;
2154
2185
  const isDark = rand() > 0.5;
2155
2186
  const cStr = isDark ? "0,0,0" : "255,255,255";
2156
- grad.addColorStop(0, `rgba(${cStr}, ${alpha})`);
2187
+ grad.addColorStop(0, `rgba(${cStr}, ${alpha2})`);
2157
2188
  grad.addColorStop(1, `rgba(${cStr}, 0)`);
2158
2189
  patCtx.fillStyle = grad;
2159
2190
  patCtx.globalAlpha = 1;
@@ -3792,16 +3823,16 @@ function reindexLayers(lottieData) {
3792
3823
  });
3793
3824
  }
3794
3825
  function addSolidLayer(lottieData, name, color, w, h) {
3795
- const clone2 = JSON.parse(JSON.stringify(lottieData));
3796
- if (!Array.isArray(clone2.layers)) clone2.layers = [];
3826
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
3827
+ if (!Array.isArray(clone4.layers)) clone4.layers = [];
3797
3828
  const newLayer = {
3798
3829
  ty: 1,
3799
3830
  nm: name,
3800
3831
  sr: 1,
3801
3832
  st: 0,
3802
3833
  ip: 0,
3803
- op: clone2.op,
3804
- ind: clone2.layers.length + 1,
3834
+ op: clone4.op,
3835
+ ind: clone4.layers.length + 1,
3805
3836
  sw: w,
3806
3837
  sh: h,
3807
3838
  sc: color,
@@ -3814,23 +3845,23 @@ function addSolidLayer(lottieData, name, color, w, h) {
3814
3845
  o: { a: 0, k: 100 }
3815
3846
  }
3816
3847
  };
3817
- clone2.layers.push(newLayer);
3818
- reindexLayers(clone2);
3819
- return clone2;
3848
+ clone4.layers.push(newLayer);
3849
+ reindexLayers(clone4);
3850
+ return clone4;
3820
3851
  }
3821
3852
  function addTextLayer(lottieData, name, text) {
3822
- const clone2 = JSON.parse(JSON.stringify(lottieData));
3823
- if (!Array.isArray(clone2.layers)) clone2.layers = [];
3824
- const w = clone2.w || 1920;
3825
- const h = clone2.h || 1080;
3853
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
3854
+ if (!Array.isArray(clone4.layers)) clone4.layers = [];
3855
+ const w = clone4.w || 1920;
3856
+ const h = clone4.h || 1080;
3826
3857
  const newLayer = {
3827
3858
  ty: 5,
3828
3859
  nm: name,
3829
3860
  sr: 1,
3830
3861
  st: 0,
3831
3862
  ip: 0,
3832
- op: clone2.op,
3833
- ind: clone2.layers.length + 1,
3863
+ op: clone4.op,
3864
+ ind: clone4.layers.length + 1,
3834
3865
  ks: {
3835
3866
  a: { a: 0, k: [0, 0, 0] },
3836
3867
  p: { a: 0, k: [w / 2, h / 2, 0] },
@@ -3872,23 +3903,23 @@ function addTextLayer(lottieData, name, text) {
3872
3903
  }
3873
3904
  }
3874
3905
  };
3875
- clone2.layers.unshift(newLayer);
3876
- reindexLayers(clone2);
3877
- return clone2;
3906
+ clone4.layers.unshift(newLayer);
3907
+ reindexLayers(clone4);
3908
+ return clone4;
3878
3909
  }
3879
3910
  function addShapeLayer(lottieData, name) {
3880
- const clone2 = JSON.parse(JSON.stringify(lottieData));
3881
- if (!Array.isArray(clone2.layers)) clone2.layers = [];
3882
- const w = clone2.w || 1920;
3883
- const h = clone2.h || 1080;
3911
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
3912
+ if (!Array.isArray(clone4.layers)) clone4.layers = [];
3913
+ const w = clone4.w || 1920;
3914
+ const h = clone4.h || 1080;
3884
3915
  const newLayer = {
3885
3916
  ty: 4,
3886
3917
  nm: name,
3887
3918
  sr: 1,
3888
3919
  st: 0,
3889
3920
  ip: 0,
3890
- op: clone2.op,
3891
- ind: clone2.layers.length + 1,
3921
+ op: clone4.op,
3922
+ ind: clone4.layers.length + 1,
3892
3923
  ks: {
3893
3924
  a: { a: 0, k: [0, 0, 0] },
3894
3925
  p: { a: 0, k: [w / 2, h / 2, 0] },
@@ -3898,14 +3929,14 @@ function addShapeLayer(lottieData, name) {
3898
3929
  },
3899
3930
  shapes: []
3900
3931
  };
3901
- clone2.layers.unshift(newLayer);
3902
- reindexLayers(clone2);
3903
- return clone2;
3932
+ clone4.layers.unshift(newLayer);
3933
+ reindexLayers(clone4);
3934
+ return clone4;
3904
3935
  }
3905
3936
  function addVectorShape(lottieData, layerIndex, shapeType, colorHex) {
3906
- const clone2 = JSON.parse(JSON.stringify(lottieData));
3907
- const layer2 = clone2.layers[layerIndex];
3908
- if (!layer2 || layer2.ty !== 4) return clone2;
3937
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
3938
+ const layer2 = clone4.layers[layerIndex];
3939
+ if (!layer2 || layer2.ty !== 4) return clone4;
3909
3940
  if (!Array.isArray(layer2.shapes)) layer2.shapes = [];
3910
3941
  const cleanHex = colorHex.startsWith("#") ? colorHex.slice(1) : colorHex;
3911
3942
  const r = parseInt(cleanHex.slice(0, 2), 16) / 255 || 0.5;
@@ -3979,7 +4010,7 @@ function addVectorShape(lottieData, layerIndex, shapeType, colorHex) {
3979
4010
  };
3980
4011
  }
3981
4012
  layer2.shapes.push(shapeContent);
3982
- return clone2;
4013
+ return clone4;
3983
4014
  }
3984
4015
  function getProperty(layer2, path) {
3985
4016
  if (!layer2) return null;
@@ -3992,9 +4023,9 @@ function getProperty(layer2, path) {
3992
4023
  return current;
3993
4024
  }
3994
4025
  function updateStaticProperty(lottieData, layerIndex, path, value) {
3995
- const clone2 = JSON.parse(JSON.stringify(lottieData));
3996
- const layer2 = clone2.layers[layerIndex];
3997
- if (!layer2) return clone2;
4026
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4027
+ const layer2 = clone4.layers[layerIndex];
4028
+ if (!layer2) return clone4;
3998
4029
  const propObj = getProperty(layer2, path);
3999
4030
  if (propObj) {
4000
4031
  propObj.a = 0;
@@ -4004,7 +4035,7 @@ function updateStaticProperty(lottieData, layerIndex, path, value) {
4004
4035
  propObj.k = value;
4005
4036
  }
4006
4037
  }
4007
- return clone2;
4038
+ return clone4;
4008
4039
  }
4009
4040
  var EASING_CURVES = {
4010
4041
  linear: {
@@ -4025,9 +4056,9 @@ var EASING_CURVES = {
4025
4056
  }
4026
4057
  };
4027
4058
  function enableKeyframing(lottieData, layerIndex, path) {
4028
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4029
- const layer2 = clone2.layers[layerIndex];
4030
- if (!layer2) return clone2;
4059
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4060
+ const layer2 = clone4.layers[layerIndex];
4061
+ if (!layer2) return clone4;
4031
4062
  const propObj = getProperty(layer2, path);
4032
4063
  if (propObj && propObj.a === 0) {
4033
4064
  const staticValue = propObj.k;
@@ -4041,14 +4072,14 @@ function enableKeyframing(lottieData, layerIndex, path) {
4041
4072
  }
4042
4073
  ];
4043
4074
  }
4044
- return clone2;
4075
+ return clone4;
4045
4076
  }
4046
4077
  function addOrUpdateKeyframe(lottieData, layerIndex, path, frame, value, easing = "easeInOut") {
4047
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4048
- const layer2 = clone2.layers[layerIndex];
4049
- if (!layer2) return clone2;
4078
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4079
+ const layer2 = clone4.layers[layerIndex];
4080
+ if (!layer2) return clone4;
4050
4081
  const propObj = getProperty(layer2, path);
4051
- if (!propObj) return clone2;
4082
+ if (!propObj) return clone4;
4052
4083
  if (propObj.a === 0) {
4053
4084
  propObj.a = 1;
4054
4085
  propObj.k = [
@@ -4089,14 +4120,14 @@ function addOrUpdateKeyframe(lottieData, layerIndex, path, frame, value, easing
4089
4120
  kf2.o = kf2.o || curves.o;
4090
4121
  }
4091
4122
  });
4092
- return clone2;
4123
+ return clone4;
4093
4124
  }
4094
4125
  function deleteKeyframe(lottieData, layerIndex, path, frame) {
4095
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4096
- const layer2 = clone2.layers[layerIndex];
4097
- if (!layer2) return clone2;
4126
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4127
+ const layer2 = clone4.layers[layerIndex];
4128
+ if (!layer2) return clone4;
4098
4129
  const propObj = getProperty(layer2, path);
4099
- if (!propObj || propObj.a === 0) return clone2;
4130
+ if (!propObj || propObj.a === 0) return clone4;
4100
4131
  let keyframes = propObj.k;
4101
4132
  keyframes = keyframes.filter((kf2) => kf2.t !== frame);
4102
4133
  if (keyframes.length === 0) {
@@ -4111,14 +4142,14 @@ function deleteKeyframe(lottieData, layerIndex, path, frame) {
4111
4142
  }
4112
4143
  });
4113
4144
  }
4114
- return clone2;
4145
+ return clone4;
4115
4146
  }
4116
4147
  function addImageLayer(lottieData, name, base64Data, w, h) {
4117
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4118
- if (!Array.isArray(clone2.assets)) clone2.assets = [];
4119
- if (!Array.isArray(clone2.layers)) clone2.layers = [];
4148
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4149
+ if (!Array.isArray(clone4.assets)) clone4.assets = [];
4150
+ if (!Array.isArray(clone4.layers)) clone4.layers = [];
4120
4151
  const assetId = `img_${Date.now()}`;
4121
- clone2.assets.push({
4152
+ clone4.assets.push({
4122
4153
  id: assetId,
4123
4154
  w,
4124
4155
  h,
@@ -4127,8 +4158,8 @@ function addImageLayer(lottieData, name, base64Data, w, h) {
4127
4158
  // data:image/png;base64,...
4128
4159
  e: 1
4129
4160
  });
4130
- const compW = clone2.w || 1920;
4131
- const compH = clone2.h || 1080;
4161
+ const compW = clone4.w || 1920;
4162
+ const compH = clone4.h || 1080;
4132
4163
  const newLayer = {
4133
4164
  ty: 2,
4134
4165
  nm: name,
@@ -4136,8 +4167,8 @@ function addImageLayer(lottieData, name, base64Data, w, h) {
4136
4167
  sr: 1,
4137
4168
  st: 0,
4138
4169
  ip: 0,
4139
- op: clone2.op,
4140
- ind: clone2.layers.length + 1,
4170
+ op: clone4.op,
4171
+ ind: clone4.layers.length + 1,
4141
4172
  ks: {
4142
4173
  a: { a: 0, k: [w / 2, h / 2, 0] },
4143
4174
  p: { a: 0, k: [compW / 2, compH / 2, 0] },
@@ -4146,20 +4177,20 @@ function addImageLayer(lottieData, name, base64Data, w, h) {
4146
4177
  o: { a: 0, k: 100 }
4147
4178
  }
4148
4179
  };
4149
- clone2.layers.unshift(newLayer);
4150
- reindexLayers(clone2);
4151
- return clone2;
4180
+ clone4.layers.unshift(newLayer);
4181
+ reindexLayers(clone4);
4182
+ return clone4;
4152
4183
  }
4153
4184
  function updateTrackMatte(lottieData, layerIndex, matteType) {
4154
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4155
- const layer2 = clone2.layers[layerIndex];
4156
- if (!layer2) return clone2;
4185
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4186
+ const layer2 = clone4.layers[layerIndex];
4187
+ if (!layer2) return clone4;
4157
4188
  if (matteType === 0) {
4158
4189
  delete layer2.tt;
4159
4190
  } else {
4160
4191
  layer2.tt = matteType;
4161
4192
  }
4162
- return clone2;
4193
+ return clone4;
4163
4194
  }
4164
4195
 
4165
4196
  // src/engine/lottieParser.ts
@@ -4286,9 +4317,9 @@ function traverseAllLayers(lottieData, fn) {
4286
4317
  }
4287
4318
  function injectText(lottieData, customization, textLayers) {
4288
4319
  if (!lottieData) return lottieData;
4289
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4320
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4290
4321
  const configMap = new Map(textLayers.map((l) => [l.layerName, l]));
4291
- traverseAllLayers(clone2, (layer2) => {
4322
+ traverseAllLayers(clone4, (layer2) => {
4292
4323
  if (layer2.ty !== 5) return;
4293
4324
  const config = configMap.get(layer2.nm);
4294
4325
  if (!config) return;
@@ -4296,29 +4327,29 @@ function injectText(lottieData, customization, textLayers) {
4296
4327
  const text = raw.slice(0, config.maxCharacters);
4297
4328
  mutateTextLayer(layer2, { text });
4298
4329
  });
4299
- return clone2;
4330
+ return clone4;
4300
4331
  }
4301
4332
  function injectTextStyle(lottieData, layerName, override) {
4302
4333
  if (!lottieData) return lottieData;
4303
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4304
- traverseAllLayers(clone2, (layer2) => {
4334
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4335
+ traverseAllLayers(clone4, (layer2) => {
4305
4336
  if (layer2.ty !== 5 || layer2.nm !== layerName) return;
4306
4337
  mutateTextLayer(layer2, override);
4307
4338
  });
4308
- return clone2;
4339
+ return clone4;
4309
4340
  }
4310
4341
  function injectGlobalTextStyle(lottieData, override) {
4311
4342
  if (!lottieData) return lottieData;
4312
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4313
- traverseAllLayers(clone2, (layer2) => {
4343
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4344
+ traverseAllLayers(clone4, (layer2) => {
4314
4345
  if (layer2.ty !== 5) return;
4315
4346
  mutateTextLayer(layer2, override);
4316
4347
  });
4317
- return clone2;
4348
+ return clone4;
4318
4349
  }
4319
4350
  function injectColor(lottieData, layerName, hexColor) {
4320
4351
  if (!lottieData || !layerName) return lottieData;
4321
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4352
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4322
4353
  const targetRgb = hexToLottieRgb(hexColor);
4323
4354
  function traverseShapes(obj) {
4324
4355
  if (!obj || typeof obj !== "object") return;
@@ -4338,33 +4369,33 @@ function injectColor(lottieData, layerName, hexColor) {
4338
4369
  else if (val && typeof val === "object") traverseShapes(val);
4339
4370
  }
4340
4371
  }
4341
- traverseAllLayers(clone2, (layer2) => {
4372
+ traverseAllLayers(clone4, (layer2) => {
4342
4373
  if (layer2.nm === layerName) traverseShapes(layer2);
4343
4374
  });
4344
- return clone2;
4375
+ return clone4;
4345
4376
  }
4346
4377
  function injectSolidColor(lottieData, layerName, hexColor) {
4347
4378
  if (!lottieData) return lottieData;
4348
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4349
- traverseAllLayers(clone2, (layer2) => {
4379
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4380
+ traverseAllLayers(clone4, (layer2) => {
4350
4381
  if (layer2.ty === 1 && layer2.nm === layerName) {
4351
4382
  layer2.sc = hexColor;
4352
4383
  }
4353
4384
  });
4354
- return clone2;
4385
+ return clone4;
4355
4386
  }
4356
4387
  function injectBatch(lottieData, batch) {
4357
4388
  if (!lottieData) return lottieData;
4358
- let clone2 = JSON.parse(JSON.stringify(lottieData));
4359
- if (batch.hiddenLayers && Array.isArray(clone2.layers)) {
4360
- clone2.layers.forEach((layer2, idx) => {
4389
+ let clone4 = JSON.parse(JSON.stringify(lottieData));
4390
+ if (batch.hiddenLayers && Array.isArray(clone4.layers)) {
4391
+ clone4.layers.forEach((layer2, idx) => {
4361
4392
  layer2.hd = batch.hiddenLayers.has(idx);
4362
4393
  });
4363
4394
  }
4364
4395
  if (batch.textCustomization) {
4365
4396
  const { customization, layers } = batch.textCustomization;
4366
4397
  const configMap = new Map(layers.map((l) => [l.layerName, l]));
4367
- traverseAllLayers(clone2, (layer2) => {
4398
+ traverseAllLayers(clone4, (layer2) => {
4368
4399
  if (layer2.ty !== 5) return;
4369
4400
  const config = configMap.get(layer2.nm);
4370
4401
  if (!config) return;
@@ -4374,7 +4405,7 @@ function injectBatch(lottieData, batch) {
4374
4405
  }
4375
4406
  if (batch.styleOverrides) {
4376
4407
  const styleMap = new Map(batch.styleOverrides.map((s) => [s.layerName, s.override]));
4377
- traverseAllLayers(clone2, (layer2) => {
4408
+ traverseAllLayers(clone4, (layer2) => {
4378
4409
  if (layer2.ty !== 5) return;
4379
4410
  const override = styleMap.get(layer2.nm);
4380
4411
  if (override) mutateTextLayer(layer2, override);
@@ -4382,15 +4413,15 @@ function injectBatch(lottieData, batch) {
4382
4413
  }
4383
4414
  if (batch.colorOverrides) {
4384
4415
  for (const { layerName, color } of batch.colorOverrides) {
4385
- clone2 = injectColor(clone2, layerName, color);
4416
+ clone4 = injectColor(clone4, layerName, color);
4386
4417
  }
4387
4418
  }
4388
4419
  if (batch.solidOverrides) {
4389
4420
  for (const { layerName, color } of batch.solidOverrides) {
4390
- clone2 = injectSolidColor(clone2, layerName, color);
4421
+ clone4 = injectSolidColor(clone4, layerName, color);
4391
4422
  }
4392
4423
  }
4393
- return clone2;
4424
+ return clone4;
4394
4425
  }
4395
4426
 
4396
4427
  // src/engine/lottieTextAnimations.ts
@@ -4890,9 +4921,9 @@ function getAnimPreset(id) {
4890
4921
  return LOTTIE_ANIM_PRESETS.find((p) => p.id === id);
4891
4922
  }
4892
4923
  function bakeAnimationIntoLayer(lottieData, layerIndex, preset, opts) {
4893
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4894
- const layer2 = clone2.layers?.[layerIndex];
4895
- if (!layer2) return clone2;
4924
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4925
+ const layer2 = clone4.layers?.[layerIndex];
4926
+ if (!layer2) return clone4;
4896
4927
  const tracks = preset.buildTracks({ ...opts, layerIndex });
4897
4928
  for (const track of tracks) {
4898
4929
  const keys = track.path.split(".");
@@ -4924,12 +4955,12 @@ function bakeAnimationIntoLayer(lottieData, layerIndex, preset, opts) {
4924
4955
  });
4925
4956
  prop.k = existing;
4926
4957
  }
4927
- return clone2;
4958
+ return clone4;
4928
4959
  }
4929
4960
  function clearAnimationFromLayer(lottieData, layerIndex, paths = ["ks.p", "ks.s", "ks.r", "ks.o"]) {
4930
- const clone2 = JSON.parse(JSON.stringify(lottieData));
4931
- const layer2 = clone2.layers?.[layerIndex];
4932
- if (!layer2) return clone2;
4961
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
4962
+ const layer2 = clone4.layers?.[layerIndex];
4963
+ if (!layer2) return clone4;
4933
4964
  for (const path of paths) {
4934
4965
  const keys = path.split(".");
4935
4966
  let prop = layer2;
@@ -4945,7 +4976,7 @@ function clearAnimationFromLayer(lottieData, layerIndex, paths = ["ks.p", "ks.s"
4945
4976
  }
4946
4977
  }
4947
4978
  }
4948
- return clone2;
4979
+ return clone4;
4949
4980
  }
4950
4981
 
4951
4982
  // src/engine/lottieTextStyle.ts
@@ -5081,9 +5112,9 @@ function readStyleFromLottieLayer(layer2) {
5081
5112
  return style;
5082
5113
  }
5083
5114
  function applyStyleToLottieLayer(layer2, style) {
5084
- const clone2 = JSON.parse(JSON.stringify(layer2));
5085
- if (!clone2 || clone2.ty !== 5) return clone2;
5086
- const ks = clone2.ks || {};
5115
+ const clone4 = JSON.parse(JSON.stringify(layer2));
5116
+ if (!clone4 || clone4.ty !== 5) return clone4;
5117
+ const ks = clone4.ks || {};
5087
5118
  if (ks.p) {
5088
5119
  if (ks.p.a === 0) {
5089
5120
  const base = Array.isArray(ks.p.k) ? ks.p.k : [0, 0, 0];
@@ -5101,9 +5132,9 @@ function applyStyleToLottieLayer(layer2, style) {
5101
5132
  if (ks.o) {
5102
5133
  if (ks.o.a === 0) ks.o.k = style.opacity;
5103
5134
  }
5104
- clone2.ks = ks;
5105
- const td = clone2.t?.d;
5106
- if (!td) return clone2;
5135
+ clone4.ks = ks;
5136
+ const td = clone4.t?.d;
5137
+ if (!td) return clone4;
5107
5138
  const applyToDoc = (doc) => {
5108
5139
  if (!doc) return;
5109
5140
  doc.s = style.fontSize;
@@ -5127,21 +5158,21 @@ function applyStyleToLottieLayer(layer2, style) {
5127
5158
  } else if (td.k?.s) {
5128
5159
  applyToDoc(td.k.s);
5129
5160
  }
5130
- return clone2;
5161
+ return clone4;
5131
5162
  }
5132
5163
  function applyStyleToLottie(lottieData, layerIndex, style) {
5133
- const clone2 = JSON.parse(JSON.stringify(lottieData));
5134
- if (!clone2.layers?.[layerIndex]) return clone2;
5135
- clone2.layers[layerIndex] = applyStyleToLottieLayer(clone2.layers[layerIndex], style);
5136
- return clone2;
5164
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
5165
+ if (!clone4.layers?.[layerIndex]) return clone4;
5166
+ clone4.layers[layerIndex] = applyStyleToLottieLayer(clone4.layers[layerIndex], style);
5167
+ return clone4;
5137
5168
  }
5138
5169
  function ensureFontInLottie(lottieData, entry) {
5139
- const clone2 = JSON.parse(JSON.stringify(lottieData));
5140
- if (!clone2.fonts) clone2.fonts = { list: [] };
5141
- if (!Array.isArray(clone2.fonts.list)) clone2.fonts.list = [];
5142
- const exists = clone2.fonts.list.some((f) => f.fName === entry.fName);
5143
- if (!exists) clone2.fonts.list.push(entry);
5144
- return clone2;
5170
+ const clone4 = JSON.parse(JSON.stringify(lottieData));
5171
+ if (!clone4.fonts) clone4.fonts = { list: [] };
5172
+ if (!Array.isArray(clone4.fonts.list)) clone4.fonts.list = [];
5173
+ const exists = clone4.fonts.list.some((f) => f.fName === entry.fName);
5174
+ if (!exists) clone4.fonts.list.push(entry);
5175
+ return clone4;
5145
5176
  }
5146
5177
  var SUPPORTED_FONT_FAMILIES = ["Poppins", "Montserrat", "Inter", "Roboto", "Open Sans", "Lato", "Raleway", "Oswald", "Bebas Neue", "Anton", "Playfair Display", "Merriweather", "Nunito", "Ubuntu", "Source Sans Pro", "PT Sans", "Noto Sans", "Exo 2", "Barlow", "Kanit", "Righteous", "Pacifico", "Lobster", "Dancing Script", "Satisfy", "Permanent Marker", "Arial", "Georgia", "Times New Roman", "Courier New"];
5147
5178
  var FONT_WEIGHT_OPTIONS = [
@@ -5179,7 +5210,7 @@ function hex2lottie(hex) {
5179
5210
  return [parseInt(c.slice(0, 2), 16) / 255, parseInt(c.slice(2, 4), 16) / 255, parseInt(c.slice(4, 6), 16) / 255];
5180
5211
  }
5181
5212
  function applyTextDoc(layer2, opts) {
5182
- const clone2 = JSON.parse(JSON.stringify(layer2));
5213
+ const clone4 = JSON.parse(JSON.stringify(layer2));
5183
5214
  const applyDoc = (doc) => {
5184
5215
  doc.t = opts.text;
5185
5216
  doc.f = opts.font;
@@ -5193,22 +5224,22 @@ function applyTextDoc(layer2, opts) {
5193
5224
  doc.sw = opts.strokeWidth;
5194
5225
  }
5195
5226
  };
5196
- const td = clone2.t?.d;
5197
- if (!td) return clone2;
5227
+ const td = clone4.t?.d;
5228
+ if (!td) return clone4;
5198
5229
  if (Array.isArray(td.k))
5199
5230
  td.k.forEach((kf2) => {
5200
5231
  if (kf2?.s) applyDoc(kf2.s);
5201
5232
  });
5202
5233
  else if (td.k?.s) applyDoc(td.k.s);
5203
- return clone2;
5234
+ return clone4;
5204
5235
  }
5205
5236
  function setLayerPos(layer2, x, y) {
5206
- const clone2 = JSON.parse(JSON.stringify(layer2));
5207
- if (clone2.ks?.p?.a === 0) clone2.ks.p.k = [x, y, 0];
5208
- return clone2;
5237
+ const clone4 = JSON.parse(JSON.stringify(layer2));
5238
+ if (clone4.ks?.p?.a === 0) clone4.ks.p.k = [x, y, 0];
5239
+ return clone4;
5209
5240
  }
5210
5241
  function addRoundedRect(lottie, name, cx, cy, w, h, r, color) {
5211
- let clone2 = JSON.parse(JSON.stringify(lottie));
5242
+ let clone4 = JSON.parse(JSON.stringify(lottie));
5212
5243
  const [cr, cg, cb] = hex2lottie(color);
5213
5244
  const shapeLayer = {
5214
5245
  ty: 4,
@@ -5216,7 +5247,7 @@ function addRoundedRect(lottie, name, cx, cy, w, h, r, color) {
5216
5247
  sr: 1,
5217
5248
  st: 0,
5218
5249
  ip: 0,
5219
- op: clone2.op,
5250
+ op: clone4.op,
5220
5251
  ind: 1,
5221
5252
  ks: {
5222
5253
  a: { a: 0, k: [0, 0, 0] },
@@ -5237,9 +5268,9 @@ function addRoundedRect(lottie, name, cx, cy, w, h, r, color) {
5237
5268
  }
5238
5269
  ]
5239
5270
  };
5240
- clone2.layers.push(shapeLayer);
5241
- reindexLayers(clone2);
5242
- return clone2;
5271
+ clone4.layers.push(shapeLayer);
5272
+ reindexLayers(clone4);
5273
+ return clone4;
5243
5274
  }
5244
5275
  function buildCleanLowerThird() {
5245
5276
  let l = createBlankLottie(1920, 1080, 30, 120);
@@ -5847,8 +5878,8 @@ function quantizeTopalette(pixels, maxColors) {
5847
5878
  function mapPixelsToPalette(pixels, palette, transparentIndex) {
5848
5879
  const indices = new Uint8Array(pixels.length / 4);
5849
5880
  for (let i = 0; i < pixels.length; i += 4) {
5850
- const alpha = pixels[i + 3];
5851
- if (alpha < 128) {
5881
+ const alpha2 = pixels[i + 3];
5882
+ if (alpha2 < 128) {
5852
5883
  indices[i / 4] = transparentIndex;
5853
5884
  continue;
5854
5885
  }
@@ -6209,9 +6240,9 @@ async function renderSceneWebM(doc, options = {}) {
6209
6240
  recorder.stop();
6210
6241
  return;
6211
6242
  }
6212
- const now = performance.now();
6243
+ const now2 = performance.now();
6213
6244
  const expectedTime = startTime + currentFrame * 1e3 / fps;
6214
- if (!pace || now >= expectedTime) {
6245
+ if (!pace || now2 >= expectedTime) {
6215
6246
  const time = currentFrame / fps;
6216
6247
  ctx.clearRect(0, 0, width, height);
6217
6248
  evaluateScene(doc, time, ctx);
@@ -7457,6 +7488,51 @@ var TextEffectBuilder = class _TextEffectBuilder {
7457
7488
  };
7458
7489
 
7459
7490
  // src/templates/keyframes.ts
7491
+ function cubicBezier(x1, y1, x2, y2) {
7492
+ return function(t) {
7493
+ if (t <= 0) return 0;
7494
+ if (t >= 1) return 1;
7495
+ let tApprox = t;
7496
+ for (let i = 0; i < 8; i++) {
7497
+ const currentX = 3 * (1 - tApprox) * (1 - tApprox) * tApprox * x1 + 3 * (1 - tApprox) * tApprox * tApprox * x2 + tApprox * tApprox * tApprox;
7498
+ const slope = 3 * (1 - tApprox) * (1 - tApprox) * x1 + 6 * (1 - tApprox) * tApprox * (x2 - x1) + 3 * tApprox * tApprox * (1 - x2);
7499
+ if (Math.abs(slope) < 1e-6) break;
7500
+ tApprox -= (currentX - t) / slope;
7501
+ }
7502
+ tApprox = Math.max(0, Math.min(1, tApprox));
7503
+ return 3 * (1 - tApprox) * (1 - tApprox) * tApprox * y1 + 3 * (1 - tApprox) * tApprox * tApprox * y2 + tApprox * tApprox * tApprox;
7504
+ };
7505
+ }
7506
+ function solveSpring(t, params) {
7507
+ const mass = params?.mass ?? 1;
7508
+ const stiffness = params?.stiffness ?? 100;
7509
+ const damping = params?.damping ?? 10;
7510
+ const omega0 = Math.sqrt(stiffness / mass);
7511
+ const zeta = damping / (2 * Math.sqrt(stiffness * mass));
7512
+ if (zeta < 1) {
7513
+ const omegaD = omega0 * Math.sqrt(1 - zeta * zeta);
7514
+ const envelope = Math.exp(-zeta * omega0 * t);
7515
+ return 1 - envelope * (Math.cos(omegaD * t) + zeta / Math.sqrt(1 - zeta * zeta) * Math.sin(omegaD * t));
7516
+ } else {
7517
+ return 1 - (1 + omega0 * t) * Math.exp(-omega0 * t);
7518
+ }
7519
+ }
7520
+ function easeOutBounce(t) {
7521
+ const n1 = 7.5625;
7522
+ const d1 = 2.75;
7523
+ if (t < 1 / d1) {
7524
+ return n1 * t * t;
7525
+ } else if (t < 2 / d1) {
7526
+ let tVal = t - 1.5 / d1;
7527
+ return n1 * tVal * tVal + 0.75;
7528
+ } else if (t < 2.5 / d1) {
7529
+ let tVal = t - 2.25 / d1;
7530
+ return n1 * tVal * tVal + 0.9375;
7531
+ } else {
7532
+ let tVal = t - 2.625 / d1;
7533
+ return n1 * tVal * tVal + 0.984375;
7534
+ }
7535
+ }
7460
7536
  function isKeyframed(value) {
7461
7537
  return typeof value === "object" && value !== null && "keyframes" in value && Array.isArray(value.keyframes);
7462
7538
  }
@@ -7489,10 +7565,10 @@ function evaluateAnimatable(value, time, templateDuration) {
7489
7565
  const right = sorted[leftIdx + 1];
7490
7566
  const range = right.time - left.time;
7491
7567
  const t = range === 0 ? 0 : (time - left.time) / range;
7492
- const easedT = applyEasing(t, right.easing || "linear");
7568
+ const easedT = applyEasing(t, right.easing || "linear", right.bezier, right.spring);
7493
7569
  return interpolateValue(left.value, right.value, easedT);
7494
7570
  }
7495
- function applyEasing(t, easing) {
7571
+ function applyEasing(t, easing, bezier, spring) {
7496
7572
  switch (easing) {
7497
7573
  case "linear":
7498
7574
  return t;
@@ -7503,7 +7579,16 @@ function applyEasing(t, easing) {
7503
7579
  case "ease-in-out":
7504
7580
  return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
7505
7581
  case "ease":
7506
- return t * t * (3 - 2 * t);
7582
+ return cubicBezier(0.25, 0.1, 0.25, 1)(t);
7583
+ case "cubic-bezier":
7584
+ if (bezier) {
7585
+ return cubicBezier(bezier.x1, bezier.y1, bezier.x2, bezier.y2)(t);
7586
+ }
7587
+ return cubicBezier(0.4, 0, 0.2, 1)(t);
7588
+ case "spring":
7589
+ return solveSpring(t, spring);
7590
+ case "bounce":
7591
+ return easeOutBounce(t);
7507
7592
  default:
7508
7593
  return t;
7509
7594
  }
@@ -7512,49 +7597,93 @@ function interpolateValue(from, to, t) {
7512
7597
  if (typeof from === "number" && typeof to === "number") {
7513
7598
  return from + (to - from) * t;
7514
7599
  }
7515
- if (typeof from === "string" && typeof to === "string" && from.startsWith("#") && to.startsWith("#")) {
7516
- return interpolateColor(from, to, t);
7600
+ if (typeof from === "string" && typeof to === "string") {
7601
+ const isFromColor = from.startsWith("#") || from.startsWith("rgb");
7602
+ const isToColor = to.startsWith("#") || to.startsWith("rgb");
7603
+ if (isFromColor && isToColor) {
7604
+ return interpolateColorString(from, to, t);
7605
+ }
7517
7606
  }
7518
7607
  return t < 0.5 ? from : to;
7519
7608
  }
7520
- function interpolateColor(from, to, t) {
7521
- const fromRgb = hexToRgb2(from);
7522
- const toRgb = hexToRgb2(to);
7523
- if (!fromRgb || !toRgb) {
7524
- return t < 0.5 ? from : to;
7609
+ function parseColor(color) {
7610
+ if (!color) return null;
7611
+ const trimmed = color.trim().toLowerCase();
7612
+ if (trimmed.startsWith("#")) {
7613
+ const hex = trimmed.slice(1);
7614
+ if (hex.length === 3) {
7615
+ return {
7616
+ r: parseInt(hex[0] + hex[0], 16),
7617
+ g: parseInt(hex[1] + hex[1], 16),
7618
+ b: parseInt(hex[2] + hex[2], 16),
7619
+ a: 1
7620
+ };
7621
+ }
7622
+ if (hex.length === 4) {
7623
+ return {
7624
+ r: parseInt(hex[0] + hex[0], 16),
7625
+ g: parseInt(hex[1] + hex[1], 16),
7626
+ b: parseInt(hex[2] + hex[2], 16),
7627
+ a: parseInt(hex[3] + hex[3], 16) / 255
7628
+ };
7629
+ }
7630
+ if (hex.length === 6) {
7631
+ return {
7632
+ r: parseInt(hex.slice(0, 2), 16),
7633
+ g: parseInt(hex.slice(2, 4), 16),
7634
+ b: parseInt(hex.slice(4, 6), 16),
7635
+ a: 1
7636
+ };
7637
+ }
7638
+ if (hex.length === 8) {
7639
+ return {
7640
+ r: parseInt(hex.slice(0, 2), 16),
7641
+ g: parseInt(hex.slice(2, 4), 16),
7642
+ b: parseInt(hex.slice(4, 6), 16),
7643
+ a: parseInt(hex.slice(6, 8), 16) / 255
7644
+ };
7645
+ }
7525
7646
  }
7526
- const r = Math.round(fromRgb.r + (toRgb.r - fromRgb.r) * t);
7527
- const g = Math.round(fromRgb.g + (toRgb.g - fromRgb.g) * t);
7528
- const b = Math.round(fromRgb.b + (toRgb.b - fromRgb.b) * t);
7529
- return rgbToHex(r, g, b);
7530
- }
7531
- function hexToRgb2(hex) {
7532
- const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
7533
- return result ? {
7534
- r: parseInt(result[1], 16),
7535
- g: parseInt(result[2], 16),
7536
- b: parseInt(result[3], 16)
7537
- } : null;
7647
+ const match = trimmed.match(/^rgba?\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)$/);
7648
+ if (match) {
7649
+ return {
7650
+ r: Math.min(255, Math.max(0, parseFloat(match[1]))),
7651
+ g: Math.min(255, Math.max(0, parseFloat(match[2]))),
7652
+ b: Math.min(255, Math.max(0, parseFloat(match[3]))),
7653
+ a: match[4] !== void 0 ? Math.min(1, Math.max(0, parseFloat(match[4]))) : 1
7654
+ };
7655
+ }
7656
+ return null;
7538
7657
  }
7539
- function rgbToHex(r, g, b) {
7540
- return "#" + [r, g, b].map((x) => {
7541
- const hex = x.toString(16);
7542
- return hex.length === 1 ? "0" + hex : hex;
7543
- }).join("");
7658
+ function interpolateColorString(from, to, t) {
7659
+ const c1 = parseColor(from);
7660
+ const c2 = parseColor(to);
7661
+ if (!c1 || !c2) {
7662
+ return t < 0.5 ? from : to;
7663
+ }
7664
+ const r = Math.round(c1.r + (c2.r - c1.r) * t);
7665
+ const g = Math.round(c1.g + (c2.g - c1.g) * t);
7666
+ const b = Math.round(c1.b + (c2.b - c1.b) * t);
7667
+ const a = Math.round((c1.a + (c2.a - c1.a) * t) * 100) / 100;
7668
+ if (a >= 1) {
7669
+ return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
7670
+ }
7671
+ return `rgba(${r}, ${g}, ${b}, ${a})`;
7544
7672
  }
7545
7673
  function createKeyframed(keyframes) {
7546
7674
  return { keyframes };
7547
7675
  }
7548
- function addKeyframe(value, time, newValue, easing = "ease-in-out") {
7676
+ function addKeyframe(value, time, newValue, easing = "ease-in-out", bezier, spring) {
7549
7677
  const existing = isKeyframed(value) ? value.keyframes : [{ time: 0, value, easing: "linear" }];
7550
7678
  const existingIndex = existing.findIndex((kf2) => Math.abs(kf2.time - time) < 0.01);
7679
+ const newKf = { time, value: newValue, easing, bezier, spring };
7551
7680
  if (existingIndex >= 0) {
7552
7681
  const updated = [...existing];
7553
- updated[existingIndex] = { time, value: newValue, easing };
7682
+ updated[existingIndex] = newKf;
7554
7683
  return { keyframes: updated.sort((a, b) => a.time - b.time) };
7555
7684
  }
7556
7685
  return {
7557
- keyframes: [...existing, { time, value: newValue, easing }].sort((a, b) => a.time - b.time)
7686
+ keyframes: [...existing, newKf].sort((a, b) => a.time - b.time)
7558
7687
  };
7559
7688
  }
7560
7689
  function removeTemplateKeyframe(value, time) {
@@ -7573,7 +7702,7 @@ function removeTemplateKeyframe(value, time) {
7573
7702
 
7574
7703
  // src/contracts.ts
7575
7704
  var CANONICAL_SCHEMA_VERSION = 2;
7576
- var CANONICAL_RENDERER_VERSION = "1.3.0";
7705
+ var CANONICAL_RENDERER_VERSION = "1.4.0";
7577
7706
  function clone(value) {
7578
7707
  return JSON.parse(JSON.stringify(value));
7579
7708
  }
@@ -7614,7 +7743,8 @@ function canonicalizeSceneDocument(input) {
7614
7743
  "dripMaxLength",
7615
7744
  "grainDensity",
7616
7745
  "skewX"
7617
- ]) delete legacyConfig[key];
7746
+ ])
7747
+ delete legacyConfig[key];
7618
7748
  }
7619
7749
  const idMap = /* @__PURE__ */ new Map();
7620
7750
  const counts = /* @__PURE__ */ new Map();
@@ -7665,7 +7795,8 @@ function effectDefinitionToConfig(input) {
7665
7795
  };
7666
7796
  }
7667
7797
  function normalizeTextEffect(input, metadata) {
7668
- if (!input || typeof input !== "object") throw new Error("Invalid text effect document");
7798
+ if (!input || typeof input !== "object")
7799
+ throw new Error("Invalid text effect document");
7669
7800
  const raw = input;
7670
7801
  const scene = Array.isArray(raw.effectLayers) ? canonicalizeSceneDocument(raw) : canonicalizeSceneDocument(
7671
7802
  textEffectConfigToScene(
@@ -7691,7 +7822,9 @@ function normalizeTemplateLayer(layer2, index) {
7691
7822
  if (normalized.kind === "text") {
7692
7823
  const text = normalized;
7693
7824
  if (!text.styleRef && text.styleDefinition) {
7694
- const snapshot = normalizeTextEffect(text.styleDefinition, { assetId: text.styleId ?? "legacy-effect" });
7825
+ const snapshot = normalizeTextEffect(text.styleDefinition, {
7826
+ assetId: text.styleId ?? "legacy-effect"
7827
+ });
7695
7828
  text.styleRef = {
7696
7829
  effectId: text.styleId ?? snapshot.effectName,
7697
7830
  revisionId: String(text.styleVersion ?? "legacy"),
@@ -7753,11 +7886,16 @@ function normalizeTemplateElement(element, index) {
7753
7886
  };
7754
7887
  }
7755
7888
  function normalizeTextTemplate(input, metadata) {
7756
- if (!input || typeof input !== "object") throw new Error("Invalid text template document");
7889
+ if (!input || typeof input !== "object")
7890
+ throw new Error("Invalid text template document");
7757
7891
  const raw = input;
7758
7892
  const sourceLayers = Array.isArray(raw.layers) ? raw.layers : Array.isArray(raw.elements) ? raw.elements.map(normalizeTemplateElement) : [];
7759
7893
  const layers = sourceLayers.map(normalizeTemplateLayer);
7760
- const dependencies = layers.map((layer2) => layer2.kind === "text" ? layer2.styleRef : void 0).filter((ref) => !!ref).filter((ref, index, all) => all.findIndex((other) => other.effectId === ref.effectId && other.revisionId === ref.revisionId) === index);
7894
+ const dependencies = layers.map((layer2) => layer2.kind === "text" ? layer2.styleRef : void 0).filter((ref) => !!ref).filter(
7895
+ (ref, index, all) => all.findIndex(
7896
+ (other) => other.effectId === ref.effectId && other.revisionId === ref.revisionId
7897
+ ) === index
7898
+ );
7761
7899
  const document2 = {
7762
7900
  schemaVersion: CANONICAL_SCHEMA_VERSION,
7763
7901
  id: String(raw.id),
@@ -7794,7 +7932,9 @@ function normalizeTextTemplate(input, metadata) {
7794
7932
  }
7795
7933
  function activeEffectDiagnostics(scene) {
7796
7934
  const config = sceneToConfig(scene);
7797
- const glowLayers = scene.effectLayers.filter((layer2) => layer2.type === "glow");
7935
+ const glowLayers = scene.effectLayers.filter(
7936
+ (layer2) => layer2.type === "glow"
7937
+ );
7798
7938
  return scene.effectLayers.map((layer2) => {
7799
7939
  const glowIndex = glowLayers.indexOf(layer2);
7800
7940
  const semanticEnabled = (() => {
@@ -7911,12 +8051,12 @@ function renderLightLeak(ctx, params, intensity, time) {
7911
8051
  }
7912
8052
 
7913
8053
  // src/videoEffects/utils/colorUtils.ts
7914
- function hexToRgba(hex, alpha) {
8054
+ function hexToRgba(hex, alpha2) {
7915
8055
  hex = hex.replace("#", "");
7916
8056
  const r = parseInt(hex.substring(0, 2), 16);
7917
8057
  const g = parseInt(hex.substring(2, 4), 16);
7918
8058
  const b = parseInt(hex.substring(4, 6), 16);
7919
- return `rgba(${r}, ${g}, ${b}, ${alpha})`;
8059
+ return `rgba(${r}, ${g}, ${b}, ${alpha2})`;
7920
8060
  }
7921
8061
  function rgbaToComponents(rgba) {
7922
8062
  const match = rgba.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
@@ -7967,11 +8107,11 @@ function renderLightLeak2(ctx, params, intensity, time) {
7967
8107
  const color1 = params.color1 || "#FF6B35";
7968
8108
  const color2 = params.color2 || "#FF8C42";
7969
8109
  const color3 = params.color3 || "#FFA500";
7970
- const alpha = intensity * fadeMultiplier;
7971
- gradient.addColorStop(0, hexToRgba(color1, alpha * 0.9));
7972
- gradient.addColorStop(0.2, hexToRgba(color2, alpha * 0.7));
7973
- gradient.addColorStop(0.5, hexToRgba(color3, alpha * 0.4));
7974
- gradient.addColorStop(0.8, hexToRgba(color3, alpha * 0.1));
8110
+ const alpha2 = intensity * fadeMultiplier;
8111
+ gradient.addColorStop(0, hexToRgba(color1, alpha2 * 0.9));
8112
+ gradient.addColorStop(0.2, hexToRgba(color2, alpha2 * 0.7));
8113
+ gradient.addColorStop(0.5, hexToRgba(color3, alpha2 * 0.4));
8114
+ gradient.addColorStop(0.8, hexToRgba(color3, alpha2 * 0.1));
7975
8115
  gradient.addColorStop(1, "rgba(255, 165, 0, 0)");
7976
8116
  ctx.globalCompositeOperation = "screen";
7977
8117
  ctx.fillStyle = gradient;
@@ -8049,8 +8189,8 @@ function renderFire(ctx, params, intensity, time) {
8049
8189
  const particleProgress = (time * 0.5 + i * 0.1) % 1;
8050
8190
  const y = height - particleProgress * fireHeight * 1.2;
8051
8191
  const size = (1 - particleProgress) * 8 * intensity;
8052
- const alpha = (1 - particleProgress) * intensity;
8053
- ctx.globalAlpha = alpha;
8192
+ const alpha2 = (1 - particleProgress) * intensity;
8193
+ ctx.globalAlpha = alpha2;
8054
8194
  ctx.fillStyle = i % 3 === 0 ? fireColor1 : i % 3 === 1 ? fireColor2 : fireColor3;
8055
8195
  ctx.beginPath();
8056
8196
  ctx.arc(x, y, size, 0, Math.PI * 2);
@@ -8075,15 +8215,15 @@ function renderParticles(ctx, params, intensity, time) {
8075
8215
  const y = (time * driftSpeed * 20 + i * 15) % (height + 100) - 50;
8076
8216
  const sizeVariation = Math.sin(time * 2 + seed) * 0.3 + 0.7;
8077
8217
  const size = particleSize * sizeVariation;
8078
- let alpha = intensity * 0.8;
8218
+ let alpha2 = intensity * 0.8;
8079
8219
  if (fadeEffect) {
8080
8220
  if (y < 100) {
8081
- alpha *= y / 100;
8221
+ alpha2 *= y / 100;
8082
8222
  } else if (y > height - 100) {
8083
- alpha *= (height - y) / 100;
8223
+ alpha2 *= (height - y) / 100;
8084
8224
  }
8085
8225
  }
8086
- ctx.globalAlpha = Math.max(0, alpha);
8226
+ ctx.globalAlpha = Math.max(0, alpha2);
8087
8227
  ctx.fillStyle = particleColor;
8088
8228
  ctx.beginPath();
8089
8229
  ctx.arc(x, y, size, 0, Math.PI * 2);
@@ -9214,8 +9354,8 @@ function getEffectRenderer(id) {
9214
9354
  for (let i = 0; i < 120 * intensity; i++) {
9215
9355
  const x = Math.random() * width;
9216
9356
  const y = Math.random() * height;
9217
- const alpha = 0.04 + Math.random() * 0.05;
9218
- ctx.fillStyle = Math.random() > 0.5 ? `rgba(255, 255, 255, ${alpha})` : `rgba(0, 0, 0, ${alpha})`;
9357
+ const alpha2 = 0.04 + Math.random() * 0.05;
9358
+ ctx.fillStyle = Math.random() > 0.5 ? `rgba(255, 255, 255, ${alpha2})` : `rgba(0, 0, 0, ${alpha2})`;
9219
9359
  ctx.fillRect(x, y, 2, 2);
9220
9360
  }
9221
9361
  ctx.restore();
@@ -9227,8 +9367,8 @@ function getEffectRenderer(id) {
9227
9367
  for (let i = 0; i < 120 * intensity; i++) {
9228
9368
  const x = Math.random() * width;
9229
9369
  const y = Math.random() * height;
9230
- const alpha = 0.04 + Math.random() * 0.05;
9231
- ctx.fillStyle = Math.random() > 0.5 ? `rgba(255, 255, 255, ${alpha})` : `rgba(0, 0, 0, ${alpha})`;
9370
+ const alpha2 = 0.04 + Math.random() * 0.05;
9371
+ ctx.fillStyle = Math.random() > 0.5 ? `rgba(255, 255, 255, ${alpha2})` : `rgba(0, 0, 0, ${alpha2})`;
9232
9372
  ctx.fillRect(x, y, 2, 2);
9233
9373
  }
9234
9374
  ctx.restore();
@@ -10903,21 +11043,233 @@ var ALL_TRANSITIONS = TRANSITION_PRESETS.map((preset) => ({
10903
11043
  }))
10904
11044
  }));
10905
11045
 
10906
- // src/templates/TemplateRenderer.ts
10907
- function cubicBezier(x1, y1, x2, y2) {
10908
- return function(t) {
10909
- if (t <= 0) return 0;
10910
- if (t >= 1) return 1;
10911
- let tApprox = t;
10912
- for (let i = 0; i < 8; i++) {
10913
- const x = 3 * (1 - tApprox) * (1 - tApprox) * tApprox * x1 + 3 * (1 - tApprox) * tApprox * tApprox * x2 + tApprox * tApprox * tApprox;
10914
- const slope = 3 * (1 - tApprox) * (1 - tApprox) * x1 + 6 * (1 - tApprox) * tApprox * (x2 - x1) + 3 * tApprox * tApprox * (1 - x2);
10915
- if (Math.abs(slope) < 1e-6) break;
10916
- tApprox -= (x - t) / slope;
11046
+ // src/templates/textSplitter.ts
11047
+ function splitTextContent(text, mode) {
11048
+ if (!text) return [];
11049
+ const units = [];
11050
+ if (mode === "character") {
11051
+ const chars = Array.from(text);
11052
+ let charPos = 0;
11053
+ chars.forEach((char, idx) => {
11054
+ units.push({
11055
+ text: char,
11056
+ index: idx,
11057
+ totalUnits: chars.length,
11058
+ charStartIndex: charPos,
11059
+ charEndIndex: charPos + char.length,
11060
+ isWhitespace: char === " " || char === " " || char === "\n"
11061
+ });
11062
+ charPos += char.length;
11063
+ });
11064
+ } else if (mode === "word") {
11065
+ const tokens = text.match(/\S+|\s+/g) || [text];
11066
+ let wordIdx = 0;
11067
+ let charPos = 0;
11068
+ tokens.forEach((token) => {
11069
+ const isWhitespace = /^\s+$/.test(token);
11070
+ units.push({
11071
+ text: token,
11072
+ index: isWhitespace ? -1 : wordIdx++,
11073
+ totalUnits: 0,
11074
+ // Assigned below
11075
+ charStartIndex: charPos,
11076
+ charEndIndex: charPos + token.length,
11077
+ isWhitespace
11078
+ });
11079
+ charPos += token.length;
11080
+ });
11081
+ const totalWords = wordIdx;
11082
+ units.forEach((u) => {
11083
+ u.totalUnits = totalWords;
11084
+ });
11085
+ } else if (mode === "line") {
11086
+ const lines = text.split("\n");
11087
+ let charPos = 0;
11088
+ lines.forEach((line, idx) => {
11089
+ units.push({
11090
+ text: line,
11091
+ index: idx,
11092
+ totalUnits: lines.length,
11093
+ charStartIndex: charPos,
11094
+ charEndIndex: charPos + line.length,
11095
+ isWhitespace: line.length === 0
11096
+ });
11097
+ charPos += line.length + 1;
11098
+ });
11099
+ }
11100
+ return units;
11101
+ }
11102
+ function getStaggerRank(index, totalUnits, direction, seed = 42) {
11103
+ if (totalUnits <= 1) return 0;
11104
+ switch (direction) {
11105
+ case "start-to-end":
11106
+ return index;
11107
+ case "end-to-start":
11108
+ return totalUnits - 1 - index;
11109
+ case "center-out": {
11110
+ const center = (totalUnits - 1) / 2;
11111
+ return Math.abs(index - center);
11112
+ }
11113
+ case "edges-in": {
11114
+ const center = (totalUnits - 1) / 2;
11115
+ return center - Math.abs(index - center);
11116
+ }
11117
+ case "random": {
11118
+ let t = (index + 1) * (seed + 1831565813);
11119
+ t = Math.imul(t ^ t >>> 15, t | 1);
11120
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
11121
+ const rand = ((t ^ t >>> 14) >>> 0) / 4294967296;
11122
+ return rand * totalUnits;
10917
11123
  }
10918
- return 3 * (1 - tApprox) * (1 - tApprox) * tApprox * y1 + 3 * (1 - tApprox) * tApprox * tApprox * y2 + tApprox * tApprox * tApprox;
10919
- };
11124
+ default:
11125
+ return index;
11126
+ }
10920
11127
  }
11128
+ function evaluateSplitTextTransforms(units, animator, progress, direction = "in") {
11129
+ const {
11130
+ direction: staggerDir,
11131
+ delayPerUnit,
11132
+ overlap,
11133
+ randomSeed = 1234,
11134
+ initialTransform,
11135
+ easing = "ease",
11136
+ bezier,
11137
+ durationPerUnit = 0.4
11138
+ } = animator;
11139
+ const validUnits = units.filter((u) => !u.isWhitespace || animator.splitBy === "character");
11140
+ const totalUnits = validUnits.length;
11141
+ if (totalUnits === 0) return [];
11142
+ const maxRank = Math.max(
11143
+ ...validUnits.map((u) => getStaggerRank(u.index >= 0 ? u.index : 0, totalUnits, staggerDir, randomSeed))
11144
+ );
11145
+ return units.map((unit) => {
11146
+ if (unit.isWhitespace && animator.splitBy !== "character") {
11147
+ return {
11148
+ unit,
11149
+ progress: 1,
11150
+ x: 0,
11151
+ y: 0,
11152
+ z: 0,
11153
+ scale: 1,
11154
+ scaleX: 1,
11155
+ scaleY: 1,
11156
+ rotation: 0,
11157
+ rotateX: 0,
11158
+ rotateY: 0,
11159
+ opacity: 1,
11160
+ blur: 0,
11161
+ letterSpacingOffset: 0
11162
+ };
11163
+ }
11164
+ const rank = getStaggerRank(unit.index >= 0 ? unit.index : 0, totalUnits, staggerDir, randomSeed);
11165
+ const staggerNormalized = maxRank > 0 ? rank / maxRank * (1 - overlap) : 0;
11166
+ const unitTimeSpan = 1 - staggerNormalized;
11167
+ let unitProgress = unitTimeSpan > 0 ? Math.max(0, Math.min(1, (progress - staggerNormalized) / unitTimeSpan)) : 1;
11168
+ const easedT = applyEasing(unitProgress, easing, bezier);
11169
+ const p = direction === "in" ? easedT : 1 - easedT;
11170
+ const init = initialTransform;
11171
+ const x = (init.x ?? 0) * (1 - p);
11172
+ const y = (init.y ?? 0) * (1 - p);
11173
+ const z2 = (init.z ?? 0) * (1 - p);
11174
+ const scale = (init.scale ?? 1) * (1 - p) + 1 * p;
11175
+ const scaleX = (init.scaleX ?? 1) * (1 - p) + 1 * p;
11176
+ const scaleY = (init.scaleY ?? 1) * (1 - p) + 1 * p;
11177
+ const rotation = (init.rotation ?? 0) * (1 - p);
11178
+ const rotateX = (init.rotateX ?? 0) * (1 - p);
11179
+ const rotateY = (init.rotateY ?? 0) * (1 - p);
11180
+ const opacity = (init.opacity ?? 0) * (1 - p) + 1 * p;
11181
+ const blur = (init.blur ?? 0) * (1 - p);
11182
+ const letterSpacingOffset = (init.letterSpacingOffset ?? 0) * (1 - p);
11183
+ return {
11184
+ unit,
11185
+ progress: p,
11186
+ x,
11187
+ y,
11188
+ z: z2,
11189
+ scale,
11190
+ scaleX,
11191
+ scaleY,
11192
+ rotation,
11193
+ rotateX,
11194
+ rotateY,
11195
+ opacity,
11196
+ blur,
11197
+ letterSpacingOffset
11198
+ };
11199
+ });
11200
+ }
11201
+ function getSpanForCharIndex(spans, charIndex) {
11202
+ if (!spans || spans.length === 0) return void 0;
11203
+ return spans.find((s) => charIndex >= s.start && charIndex < s.end);
11204
+ }
11205
+
11206
+ // src/templates/responsiveLayout.ts
11207
+ function resolveAnchorPosition(anchor, currentBounds, canvasWidth, canvasHeight) {
11208
+ if (!anchor) {
11209
+ return currentBounds;
11210
+ }
11211
+ let { width, height } = currentBounds;
11212
+ if (anchor.maxWidthPercentage && anchor.maxWidthPercentage > 0) {
11213
+ const maxW = canvasWidth * anchor.maxWidthPercentage / 100;
11214
+ if (width > maxW) {
11215
+ width = maxW;
11216
+ }
11217
+ }
11218
+ const point = anchor.anchorPoint || "center";
11219
+ const pctX = (anchor.offsetPercentageX ?? 0) / 100;
11220
+ const pctY = (anchor.offsetPercentageY ?? 0) / 100;
11221
+ const pxX = anchor.pixelOffsetX ?? 0;
11222
+ const pxY = anchor.pixelOffsetY ?? 0;
11223
+ let x = currentBounds.x;
11224
+ let y = currentBounds.y;
11225
+ switch (point) {
11226
+ case "top-left":
11227
+ x = canvasWidth * pctX + pxX;
11228
+ y = canvasHeight * pctY + pxY;
11229
+ break;
11230
+ case "top-center":
11231
+ x = canvasWidth / 2 - width / 2 + canvasWidth * pctX + pxX;
11232
+ y = canvasHeight * pctY + pxY;
11233
+ break;
11234
+ case "top-right":
11235
+ x = canvasWidth - width - canvasWidth * pctX + pxX;
11236
+ y = canvasHeight * pctY + pxY;
11237
+ break;
11238
+ case "middle-left":
11239
+ x = canvasWidth * pctX + pxX;
11240
+ y = canvasHeight / 2 - height / 2 + canvasHeight * pctY + pxY;
11241
+ break;
11242
+ case "center":
11243
+ x = canvasWidth / 2 - width / 2 + canvasWidth * pctX + pxX;
11244
+ y = canvasHeight / 2 - height / 2 + canvasHeight * pctY + pxY;
11245
+ break;
11246
+ case "middle-right":
11247
+ x = canvasWidth - width - canvasWidth * pctX + pxX;
11248
+ y = canvasHeight / 2 - height / 2 + canvasHeight * pctY + pxY;
11249
+ break;
11250
+ case "bottom-left":
11251
+ x = canvasWidth * pctX + pxX;
11252
+ y = canvasHeight - height - canvasHeight * pctY + pxY;
11253
+ break;
11254
+ case "bottom-center":
11255
+ x = canvasWidth / 2 - width / 2 + canvasWidth * pctX + pxX;
11256
+ y = canvasHeight - height - canvasHeight * pctY + pxY;
11257
+ break;
11258
+ case "bottom-right":
11259
+ x = canvasWidth - width - canvasWidth * pctX + pxX;
11260
+ y = canvasHeight - height - canvasHeight * pctY + pxY;
11261
+ break;
11262
+ }
11263
+ return { x, y, width, height };
11264
+ }
11265
+ var ASPECT_RATIO_PRESETS = {
11266
+ "16:9": { width: 1920, height: 1080, label: "16:9 Widescreen (1920x1080)" },
11267
+ "9:16": { width: 1080, height: 1920, label: "9:16 Vertical (1080x1920)" },
11268
+ "1:1": { width: 1080, height: 1080, label: "1:1 Square (1080x1080)" },
11269
+ "4:5": { width: 1080, height: 1350, label: "4:5 Social (1080x1350)" }
11270
+ };
11271
+
11272
+ // src/templates/TemplateRenderer.ts
10921
11273
  var TemplateRenderer = class {
10922
11274
  template;
10923
11275
  editedValues;
@@ -10926,6 +11278,7 @@ var TemplateRenderer = class {
10926
11278
  currentTime = 0;
10927
11279
  // Track current time for keyframe evaluation
10928
11280
  lastLayerLayouts = /* @__PURE__ */ new Map();
11281
+ computedFlexLayouts = /* @__PURE__ */ new Map();
10929
11282
  constructor(template) {
10930
11283
  this.template = normalizeTextTemplate(template);
10931
11284
  this.editedValues = /* @__PURE__ */ new Map();
@@ -10936,7 +11289,10 @@ var TemplateRenderer = class {
10936
11289
  }
10937
11290
  updateLayer(layerId, changes) {
10938
11291
  const existing = this.editedValues.get(layerId) ?? {};
10939
- this.editedValues.set(layerId, { ...existing, ...changes });
11292
+ this.editedValues.set(layerId, {
11293
+ ...existing,
11294
+ ...changes
11295
+ });
10940
11296
  }
10941
11297
  getLayerLayout(layerId) {
10942
11298
  return this.lastLayerLayouts.get(layerId) ?? null;
@@ -10955,7 +11311,11 @@ var TemplateRenderer = class {
10955
11311
  evaluateTextDimension(layer2, prop) {
10956
11312
  const value = layer2[prop];
10957
11313
  if (value === "auto") return "auto";
10958
- return evaluateAnimatable(value, this.currentTime, this.template.duration);
11314
+ return evaluateAnimatable(
11315
+ value,
11316
+ this.currentTime,
11317
+ this.template.duration
11318
+ );
10959
11319
  }
10960
11320
  // Compute animation parameters (transforms, opacity, scale, typewriter, etc.)
10961
11321
  computeTransform(layer2, time) {
@@ -11019,12 +11379,47 @@ var TemplateRenderer = class {
11019
11379
  case "typewriter":
11020
11380
  typewriterProgress = p;
11021
11381
  break;
11382
+ case "3d-flip":
11383
+ opacity = p;
11384
+ scale = 0.6 + p * 0.4;
11385
+ y = (1 - p) * 25;
11386
+ break;
11387
+ case "scale-pop":
11388
+ opacity = p;
11389
+ scale = p < 0.7 ? p / 0.7 * 1.15 : 1.15 - (p - 0.7) / 0.3 * 0.15;
11390
+ break;
11391
+ case "track-in":
11392
+ opacity = p;
11393
+ blur = (1 - p) * 8;
11394
+ break;
11395
+ case "wave":
11396
+ opacity = p;
11397
+ y = Math.sin(p * Math.PI) * -15;
11398
+ break;
11399
+ case "glitch":
11400
+ opacity = p > 0.05 ? 1 : 0;
11401
+ x = Math.sin(p * 25) * 6 * (1 - p);
11402
+ break;
11022
11403
  case "none":
11023
11404
  default:
11024
11405
  break;
11025
11406
  }
11026
11407
  return { opacity, x, y, scale, blur, typewriterProgress };
11027
11408
  }
11409
+ /** Resolve dynamic {{variable}} tokens in string content */
11410
+ resolveDynamicContent(rawContent) {
11411
+ if (!rawContent || !rawContent.includes("{{")) return rawContent;
11412
+ const vars = this.template.variables || {};
11413
+ return rawContent.replace(/\{\{([^}]+)\}\}/g, (_, key) => {
11414
+ const trimmed = key.trim();
11415
+ const override = this.template.variableValues?.[trimmed];
11416
+ if (override !== void 0) return String(override);
11417
+ const def = vars[trimmed];
11418
+ if (def && def.defaultValue !== void 0)
11419
+ return String(def.defaultValue);
11420
+ return `{{${trimmed}}}`;
11421
+ });
11422
+ }
11028
11423
  drawFrame(ctx, time, fitToContentOrOpts = false) {
11029
11424
  const fitToContent = typeof fitToContentOrOpts === "boolean" ? fitToContentOrOpts : !!fitToContentOrOpts?.fitToContent;
11030
11425
  const skipClear = typeof fitToContentOrOpts === "object" ? !!fitToContentOrOpts?.skipClear : false;
@@ -11037,15 +11432,26 @@ var TemplateRenderer = class {
11037
11432
  const bounds = this.getContentBounds();
11038
11433
  if (bounds && bounds.width > 0 && bounds.height > 0) {
11039
11434
  if (!skipClear) {
11040
- ctx.clearRect(0, 0, this.template.canvasWidth, this.template.canvasHeight);
11435
+ ctx.clearRect(
11436
+ 0,
11437
+ 0,
11438
+ this.template.canvasWidth,
11439
+ this.template.canvasHeight
11440
+ );
11041
11441
  }
11042
11442
  ctx.save();
11043
11443
  const padding = 0.85;
11044
- const scale = Math.min(this.template.canvasWidth / bounds.width, this.template.canvasHeight / bounds.height) * padding;
11444
+ const scale = Math.min(
11445
+ this.template.canvasWidth / bounds.width,
11446
+ this.template.canvasHeight / bounds.height
11447
+ ) * padding;
11045
11448
  const finalScale = Math.min(3, scale);
11046
11449
  const cx = bounds.x + bounds.width / 2;
11047
11450
  const cy = bounds.y + bounds.height / 2;
11048
- ctx.translate(this.template.canvasWidth / 2, this.template.canvasHeight / 2);
11451
+ ctx.translate(
11452
+ this.template.canvasWidth / 2,
11453
+ this.template.canvasHeight / 2
11454
+ );
11049
11455
  ctx.scale(finalScale, finalScale);
11050
11456
  ctx.translate(-cx, -cy);
11051
11457
  this.drawLayers(ctx, time);
@@ -11054,7 +11460,12 @@ var TemplateRenderer = class {
11054
11460
  }
11055
11461
  }
11056
11462
  if (!skipClear) {
11057
- ctx.clearRect(0, 0, this.template.canvasWidth, this.template.canvasHeight);
11463
+ ctx.clearRect(
11464
+ 0,
11465
+ 0,
11466
+ this.template.canvasWidth,
11467
+ this.template.canvasHeight
11468
+ );
11058
11469
  }
11059
11470
  this.drawLayers(ctx, time);
11060
11471
  }
@@ -11067,6 +11478,7 @@ var TemplateRenderer = class {
11067
11478
  let hasTextLayers = false;
11068
11479
  for (const [layerId, layout] of this.lastLayerLayouts.entries()) {
11069
11480
  const layer2 = this.template?.layers?.find((l) => l.id === layerId);
11481
+ if (layer2 && layer2.visible === false) continue;
11070
11482
  if (layer2 && layer2.kind === "text") {
11071
11483
  hasTextLayers = true;
11072
11484
  minX = Math.min(minX, layout.x);
@@ -11091,28 +11503,449 @@ var TemplateRenderer = class {
11091
11503
  height: maxY - minY
11092
11504
  };
11093
11505
  }
11506
+ computeFlexLayouts(time) {
11507
+ this.computedFlexLayouts.clear();
11508
+ if (!this.template || !Array.isArray(this.template.layers)) return;
11509
+ const layers = this.template.layers.map((l) => this.resolveLayer(l));
11510
+ const containers = layers.filter(
11511
+ (l) => l.kind === "container"
11512
+ );
11513
+ if (containers.length === 0) return;
11514
+ const measuredBounds = /* @__PURE__ */ new Map();
11515
+ for (const layer2 of layers) {
11516
+ if (layer2.kind === "text") {
11517
+ const textLayer = layer2;
11518
+ const rawW = this.evaluateTextDimension(textLayer, "width");
11519
+ const rawH = this.evaluateTextDimension(textLayer, "height");
11520
+ const fontSize = Number(
11521
+ evaluateAnimatable(
11522
+ textLayer.fontSize,
11523
+ this.currentTime,
11524
+ this.template.duration
11525
+ )
11526
+ ) || 48;
11527
+ const fontWeight = evaluateAnimatable(
11528
+ textLayer.fontWeight,
11529
+ this.currentTime,
11530
+ this.template.duration
11531
+ ) || 400;
11532
+ const rawFontFamily = textLayer.fontFamily || "Space Grotesk";
11533
+ const fontFamily = resolveFontFamilyName(rawFontFamily);
11534
+ const legacyPad = Number(
11535
+ evaluateAnimatable(
11536
+ textLayer.padding ?? 0,
11537
+ this.currentTime,
11538
+ this.template.duration
11539
+ )
11540
+ ) || 0;
11541
+ const padL = Number(
11542
+ evaluateAnimatable(
11543
+ textLayer.paddingLeft ?? legacyPad,
11544
+ this.currentTime,
11545
+ this.template.duration
11546
+ )
11547
+ ) || 0;
11548
+ const padR = Number(
11549
+ evaluateAnimatable(
11550
+ textLayer.paddingRight ?? legacyPad,
11551
+ this.currentTime,
11552
+ this.template.duration
11553
+ )
11554
+ ) || 0;
11555
+ const padT = Number(
11556
+ evaluateAnimatable(
11557
+ textLayer.paddingTop ?? legacyPad,
11558
+ this.currentTime,
11559
+ this.template.duration
11560
+ )
11561
+ ) || 0;
11562
+ const padB = Number(
11563
+ evaluateAnimatable(
11564
+ textLayer.paddingBottom ?? legacyPad,
11565
+ this.currentTime,
11566
+ this.template.duration
11567
+ )
11568
+ ) || 0;
11569
+ const text = this.resolveDynamicContent(textLayer.content || "");
11570
+ const lines = text.split("\n");
11571
+ let textW = 0;
11572
+ if (typeof document !== "undefined") {
11573
+ const mCanvas = document.createElement("canvas");
11574
+ const mCtx = mCanvas.getContext("2d");
11575
+ if (mCtx) {
11576
+ mCtx.font = `${fontWeight} ${fontSize}px "${fontFamily}", "${rawFontFamily}", sans-serif`;
11577
+ textW = Math.max(
11578
+ ...lines.map((l) => mCtx.measureText(l || "Ag").width),
11579
+ 20
11580
+ );
11581
+ }
11582
+ }
11583
+ if (!textW) {
11584
+ const charFactor = Number(fontWeight) >= 600 ? 0.72 : 0.65;
11585
+ textW = Math.max(
11586
+ ...lines.map((l) => l.length * fontSize * charFactor),
11587
+ 20
11588
+ );
11589
+ }
11590
+ const lineHeightMultiplier = Number(
11591
+ evaluateAnimatable(
11592
+ textLayer.lineHeight,
11593
+ this.currentTime,
11594
+ this.template.duration
11595
+ )
11596
+ ) || 1.25;
11597
+ const lineAdvance = fontSize * lineHeightMultiplier;
11598
+ const textH = lines.length === 1 ? fontSize * 1.2 : fontSize * 1 + (lines.length - 1) * lineAdvance;
11599
+ const isAutoOrBox = rawW === "auto" || textLayer.overflow === "expand-panel" || textLayer.backgroundColor !== void 0 && textLayer.backgroundColor !== null;
11600
+ const w = isAutoOrBox ? textW + padL + padR : Number(rawW);
11601
+ const h = rawH === "auto" ? textH + padT + padB : Number(rawH);
11602
+ measuredBounds.set(layer2.id, { width: w, height: h });
11603
+ } else if (layer2.kind === "shape" || layer2.kind === "image") {
11604
+ const w = Number(
11605
+ evaluateAnimatable(
11606
+ layer2.width,
11607
+ this.currentTime,
11608
+ this.template.duration
11609
+ )
11610
+ ) || 100;
11611
+ const h = Number(
11612
+ evaluateAnimatable(
11613
+ layer2.height,
11614
+ this.currentTime,
11615
+ this.template.duration
11616
+ )
11617
+ ) || 100;
11618
+ measuredBounds.set(layer2.id, { width: w, height: h });
11619
+ }
11620
+ }
11621
+ for (const container of containers) {
11622
+ const children = layers.filter(
11623
+ (l) => l.parentId === container.id && l.visible !== false
11624
+ );
11625
+ const layout = container.layout || {
11626
+ type: "flex",
11627
+ direction: "column",
11628
+ gap: 0,
11629
+ alignItems: "start",
11630
+ justifyContent: "start"
11631
+ };
11632
+ const direction = layout.direction || "column";
11633
+ const gap = Number(
11634
+ evaluateAnimatable(
11635
+ layout.gap,
11636
+ this.currentTime,
11637
+ this.template.duration
11638
+ )
11639
+ ) || 0;
11640
+ const padTop = Number(
11641
+ evaluateAnimatable(
11642
+ layout.paddingTop,
11643
+ this.currentTime,
11644
+ this.template.duration
11645
+ )
11646
+ ) || 0;
11647
+ const padRight = Number(
11648
+ evaluateAnimatable(
11649
+ layout.paddingRight,
11650
+ this.currentTime,
11651
+ this.template.duration
11652
+ )
11653
+ ) || 0;
11654
+ const padBottom = Number(
11655
+ evaluateAnimatable(
11656
+ layout.paddingBottom,
11657
+ this.currentTime,
11658
+ this.template.duration
11659
+ )
11660
+ ) || 0;
11661
+ const padLeft = Number(
11662
+ evaluateAnimatable(
11663
+ layout.paddingLeft,
11664
+ this.currentTime,
11665
+ this.template.duration
11666
+ )
11667
+ ) || 0;
11668
+ const alignItems = layout.alignItems || "center";
11669
+ const containerX = Number(
11670
+ evaluateAnimatable(
11671
+ container.x,
11672
+ this.currentTime,
11673
+ this.template.duration
11674
+ )
11675
+ ) || 0;
11676
+ const containerY = Number(
11677
+ evaluateAnimatable(
11678
+ container.y,
11679
+ this.currentTime,
11680
+ this.template.duration
11681
+ )
11682
+ ) || 0;
11683
+ if (direction === "column") {
11684
+ let totalChildHeight = 0;
11685
+ let maxChildWidth = 0;
11686
+ const childSizes = [];
11687
+ for (const child of children) {
11688
+ const sz = measuredBounds.get(child.id) || { width: 100, height: 50 };
11689
+ childSizes.push({ id: child.id, width: sz.width, height: sz.height });
11690
+ totalChildHeight += sz.height;
11691
+ maxChildWidth = Math.max(maxChildWidth, sz.width);
11692
+ }
11693
+ if (children.length > 1) {
11694
+ totalChildHeight += (children.length - 1) * gap;
11695
+ }
11696
+ const rawContainerW = container.width;
11697
+ const rawContainerH = container.height;
11698
+ const declaredW = rawContainerW === "auto" || !rawContainerW ? 0 : Number(
11699
+ evaluateAnimatable(
11700
+ rawContainerW,
11701
+ this.currentTime,
11702
+ this.template.duration
11703
+ )
11704
+ ) || 0;
11705
+ const declaredH = rawContainerH === "auto" || !rawContainerH ? 0 : Number(
11706
+ evaluateAnimatable(
11707
+ rawContainerH,
11708
+ this.currentTime,
11709
+ this.template.duration
11710
+ )
11711
+ ) || 0;
11712
+ const containerW = Math.max(
11713
+ declaredW,
11714
+ maxChildWidth + padLeft + padRight
11715
+ );
11716
+ const containerH = Math.max(
11717
+ declaredH,
11718
+ totalChildHeight + padTop + padBottom
11719
+ );
11720
+ this.computedFlexLayouts.set(container.id, {
11721
+ x: containerX,
11722
+ y: containerY,
11723
+ width: containerW,
11724
+ height: containerH
11725
+ });
11726
+ let currentY = containerY + padTop;
11727
+ const innerW = Math.max(0, containerW - padLeft - padRight);
11728
+ for (const child of childSizes) {
11729
+ let childW = child.width;
11730
+ let childX = containerX + padLeft;
11731
+ if (alignItems === "center") {
11732
+ childX = containerX + padLeft + (innerW - childW) / 2;
11733
+ } else if (alignItems === "end") {
11734
+ childX = containerX + padLeft + (innerW - childW);
11735
+ } else if (alignItems === "stretch") {
11736
+ childW = innerW;
11737
+ }
11738
+ this.computedFlexLayouts.set(child.id, {
11739
+ x: childX,
11740
+ y: currentY,
11741
+ width: childW,
11742
+ height: child.height
11743
+ });
11744
+ currentY += child.height + gap;
11745
+ }
11746
+ } else {
11747
+ let totalChildWidth = 0;
11748
+ let maxChildHeight = 0;
11749
+ const childSizes = [];
11750
+ for (const child of children) {
11751
+ const sz = measuredBounds.get(child.id) || { width: 100, height: 50 };
11752
+ childSizes.push({ id: child.id, width: sz.width, height: sz.height });
11753
+ totalChildWidth += sz.width;
11754
+ maxChildHeight = Math.max(maxChildHeight, sz.height);
11755
+ }
11756
+ if (children.length > 1) {
11757
+ totalChildWidth += (children.length - 1) * gap;
11758
+ }
11759
+ const rawContainerW = container.width;
11760
+ const rawContainerH = container.height;
11761
+ const declaredW = rawContainerW === "auto" || !rawContainerW ? 0 : Number(
11762
+ evaluateAnimatable(
11763
+ rawContainerW,
11764
+ this.currentTime,
11765
+ this.template.duration
11766
+ )
11767
+ ) || 0;
11768
+ const declaredH = rawContainerH === "auto" || !rawContainerH ? 0 : Number(
11769
+ evaluateAnimatable(
11770
+ rawContainerH,
11771
+ this.currentTime,
11772
+ this.template.duration
11773
+ )
11774
+ ) || 0;
11775
+ const containerW = Math.max(
11776
+ declaredW,
11777
+ totalChildWidth + padLeft + padRight
11778
+ );
11779
+ const containerH = Math.max(
11780
+ declaredH,
11781
+ maxChildHeight + padTop + padBottom
11782
+ );
11783
+ this.computedFlexLayouts.set(container.id, {
11784
+ x: containerX,
11785
+ y: containerY,
11786
+ width: containerW,
11787
+ height: containerH
11788
+ });
11789
+ let currentX = containerX + padLeft;
11790
+ const innerH = Math.max(0, containerH - padTop - padBottom);
11791
+ for (const child of childSizes) {
11792
+ let childH = child.height;
11793
+ let childY = containerY + padTop;
11794
+ if (alignItems === "center") {
11795
+ childY = containerY + padTop + (innerH - childH) / 2;
11796
+ } else if (alignItems === "end") {
11797
+ childY = containerY + padTop + (innerH - childH);
11798
+ } else if (alignItems === "stretch") {
11799
+ childH = innerH;
11800
+ }
11801
+ this.computedFlexLayouts.set(child.id, {
11802
+ x: currentX,
11803
+ y: childY,
11804
+ width: child.width,
11805
+ height: childH
11806
+ });
11807
+ currentX += child.width + gap;
11808
+ }
11809
+ }
11810
+ }
11811
+ }
11812
+ drawContainerLayer(ctx, layer2) {
11813
+ const resolved = layer2;
11814
+ const layout = this.computedFlexLayouts.get(resolved.id);
11815
+ const x = layout?.x ?? (Number(
11816
+ evaluateAnimatable(
11817
+ resolved.x,
11818
+ this.currentTime,
11819
+ this.template.duration
11820
+ )
11821
+ ) || 0);
11822
+ const y = layout?.y ?? (Number(
11823
+ evaluateAnimatable(
11824
+ resolved.y,
11825
+ this.currentTime,
11826
+ this.template.duration
11827
+ )
11828
+ ) || 0);
11829
+ const width = layout?.width ?? (resolved.width === "auto" ? 400 : Number(
11830
+ evaluateAnimatable(
11831
+ resolved.width,
11832
+ this.currentTime,
11833
+ this.template.duration
11834
+ )
11835
+ ) || 400);
11836
+ const height = layout?.height ?? (resolved.height === "auto" ? 200 : Number(
11837
+ evaluateAnimatable(
11838
+ resolved.height,
11839
+ this.currentTime,
11840
+ this.template.duration
11841
+ )
11842
+ ) || 200);
11843
+ this.lastLayerLayouts.set(resolved.id, { x, y, width, height });
11844
+ const bgColor = resolved.backgroundColor ? evaluateAnimatable(
11845
+ resolved.backgroundColor,
11846
+ this.currentTime,
11847
+ this.template.duration
11848
+ ) : null;
11849
+ const bgOpacity = resolved.backgroundOpacity !== void 0 ? Number(
11850
+ evaluateAnimatable(
11851
+ resolved.backgroundOpacity,
11852
+ this.currentTime,
11853
+ this.template.duration
11854
+ )
11855
+ ) : 1;
11856
+ const bgRadius = resolved.backgroundRadius !== void 0 ? Number(
11857
+ evaluateAnimatable(
11858
+ resolved.backgroundRadius,
11859
+ this.currentTime,
11860
+ this.template.duration
11861
+ )
11862
+ ) : 0;
11863
+ const borderColor = resolved.backgroundBorderColor ? evaluateAnimatable(
11864
+ resolved.backgroundBorderColor,
11865
+ this.currentTime,
11866
+ this.template.duration
11867
+ ) : null;
11868
+ const borderWidth = resolved.backgroundBorderWidth !== void 0 ? Number(
11869
+ evaluateAnimatable(
11870
+ resolved.backgroundBorderWidth,
11871
+ this.currentTime,
11872
+ this.template.duration
11873
+ )
11874
+ ) : 0;
11875
+ if (bgColor || borderColor && borderWidth > 0) {
11876
+ const currentAlpha = ctx.globalAlpha;
11877
+ ctx.save();
11878
+ ctx.globalAlpha = currentAlpha * bgOpacity;
11879
+ ctx.beginPath();
11880
+ if (bgRadius > 0) {
11881
+ ctx.moveTo(x + bgRadius, y);
11882
+ ctx.lineTo(x + width - bgRadius, y);
11883
+ ctx.quadraticCurveTo(x + width, y, x + width, y + bgRadius);
11884
+ ctx.lineTo(x + width, y + height - bgRadius);
11885
+ ctx.quadraticCurveTo(
11886
+ x + width,
11887
+ y + height,
11888
+ x + width - bgRadius,
11889
+ y + height
11890
+ );
11891
+ ctx.lineTo(x + bgRadius, y + height);
11892
+ ctx.quadraticCurveTo(x, y + height, x, y + height - bgRadius);
11893
+ ctx.lineTo(x, y + bgRadius);
11894
+ ctx.quadraticCurveTo(x, y, x + bgRadius, y);
11895
+ } else {
11896
+ ctx.rect(x, y, width, height);
11897
+ }
11898
+ ctx.closePath();
11899
+ if (bgColor) {
11900
+ ctx.fillStyle = bgColor;
11901
+ ctx.fill();
11902
+ }
11903
+ if (borderColor && borderWidth > 0) {
11904
+ ctx.strokeStyle = borderColor;
11905
+ ctx.lineWidth = borderWidth;
11906
+ ctx.globalAlpha = currentAlpha;
11907
+ ctx.stroke();
11908
+ }
11909
+ ctx.restore();
11910
+ }
11911
+ }
11094
11912
  drawLayers(ctx, time) {
11095
11913
  if (!this.template || !Array.isArray(this.template.layers)) return;
11096
11914
  this.lastLayerLayouts.clear();
11915
+ this.computeFlexLayouts(time);
11097
11916
  for (const layer2 of this.template.layers) {
11098
11917
  const resolved = this.resolveLayer(layer2);
11918
+ if (resolved.visible === false) continue;
11099
11919
  const transform = this.computeTransform(resolved, time);
11100
- const layerOpacity = resolved.opacity !== void 0 ? evaluateAnimatable(resolved.opacity, this.currentTime, this.template.duration) : 1;
11920
+ const layerOpacity = resolved.opacity !== void 0 ? evaluateAnimatable(
11921
+ resolved.opacity,
11922
+ this.currentTime,
11923
+ this.template.duration
11924
+ ) : 1;
11101
11925
  ctx.save();
11102
11926
  ctx.globalAlpha = transform.opacity * layerOpacity;
11103
- const x = this.evaluateLayerProperty(resolved, "x");
11104
- const y = this.evaluateLayerProperty(resolved, "y");
11927
+ const flexLayout = this.computedFlexLayouts.get(resolved.id);
11928
+ const x = flexLayout?.x ?? this.evaluateLayerProperty(resolved, "x");
11929
+ const y = flexLayout?.y ?? this.evaluateLayerProperty(resolved, "y");
11105
11930
  let cx;
11106
11931
  let cy;
11107
11932
  if (resolved.kind === "text") {
11108
11933
  const textLayer = resolved;
11109
- const rawW = this.evaluateTextDimension(textLayer, "width");
11110
- const rawH = this.evaluateTextDimension(textLayer, "height");
11934
+ const rawW = flexLayout?.width ?? this.evaluateTextDimension(textLayer, "width");
11935
+ const rawH = flexLayout?.height ?? this.evaluateTextDimension(textLayer, "height");
11111
11936
  cx = rawW === "auto" ? x : x + rawW / 2;
11112
11937
  cy = rawH === "auto" ? y : y + rawH / 2;
11113
11938
  } else {
11114
- const width = evaluateAnimatable(resolved.width, this.currentTime, this.template.duration);
11115
- const height = evaluateAnimatable(resolved.height, this.currentTime, this.template.duration);
11939
+ const width = flexLayout?.width ?? evaluateAnimatable(
11940
+ resolved.width,
11941
+ this.currentTime,
11942
+ this.template.duration
11943
+ );
11944
+ const height = flexLayout?.height ?? evaluateAnimatable(
11945
+ resolved.height,
11946
+ this.currentTime,
11947
+ this.template.duration
11948
+ );
11116
11949
  cx = x + width / 2;
11117
11950
  cy = y + height / 2;
11118
11951
  }
@@ -11123,59 +11956,142 @@ var TemplateRenderer = class {
11123
11956
  ctx.filter = `blur(${transform.blur}px)`;
11124
11957
  }
11125
11958
  if (resolved.kind === "text") {
11126
- this.drawTextLayer(ctx, resolved, transform);
11959
+ this.drawTextLayer(
11960
+ ctx,
11961
+ resolved,
11962
+ transform
11963
+ );
11127
11964
  } else if (resolved.kind === "shape") {
11128
- this.drawShapeLayer(ctx, resolved);
11965
+ this.drawShapeLayer(
11966
+ ctx,
11967
+ resolved
11968
+ );
11129
11969
  } else if (resolved.kind === "image") {
11130
- this.drawImageLayer(ctx, resolved);
11970
+ this.drawImageLayer(
11971
+ ctx,
11972
+ resolved
11973
+ );
11974
+ } else if (resolved.kind === "container") {
11975
+ this.drawContainerLayer(
11976
+ ctx,
11977
+ resolved
11978
+ );
11131
11979
  }
11132
11980
  ctx.restore();
11133
11981
  }
11134
11982
  }
11135
11983
  drawTextLayer(ctx, layer2, transform) {
11136
11984
  const resolved = layer2;
11137
- const content = resolved.content;
11985
+ const rawContent = resolved.content;
11986
+ const content = this.resolveDynamicContent(rawContent);
11138
11987
  const rawFontFamily = resolved.fontFamily;
11139
11988
  const fontFamily = resolveFontFamilyName(rawFontFamily);
11140
- const fontSize = evaluateAnimatable(resolved.fontSize, this.currentTime, this.template.duration);
11141
- const fontWeight = evaluateAnimatable(resolved.fontWeight, this.currentTime, this.template.duration);
11142
- const color = evaluateAnimatable(resolved.color, this.currentTime, this.template.duration);
11989
+ const fontSize = evaluateAnimatable(
11990
+ resolved.fontSize,
11991
+ this.currentTime,
11992
+ this.template.duration
11993
+ );
11994
+ const fontWeight = evaluateAnimatable(
11995
+ resolved.fontWeight,
11996
+ this.currentTime,
11997
+ this.template.duration
11998
+ );
11999
+ const color = evaluateAnimatable(
12000
+ resolved.color,
12001
+ this.currentTime,
12002
+ this.template.duration
12003
+ );
11143
12004
  const align = resolved.align;
11144
- const x = evaluateAnimatable(resolved.x, this.currentTime, this.template.duration);
11145
- const y = evaluateAnimatable(resolved.y, this.currentTime, this.template.duration);
11146
- const rawWidth = this.evaluateTextDimension(resolved, "width");
11147
- const rawHeight = this.evaluateTextDimension(resolved, "height");
11148
- const backgroundColor = resolved.backgroundColor ? evaluateAnimatable(resolved.backgroundColor, this.currentTime, this.template.duration) : null;
11149
- const backgroundOpacity = resolved.backgroundOpacity !== void 0 ? evaluateAnimatable(resolved.backgroundOpacity, this.currentTime, this.template.duration) : 1;
11150
- const backgroundRadius = resolved.backgroundRadius !== void 0 ? evaluateAnimatable(resolved.backgroundRadius, this.currentTime, this.template.duration) : 0;
11151
- const backgroundBorderColor = resolved.backgroundBorderColor ? evaluateAnimatable(resolved.backgroundBorderColor, this.currentTime, this.template.duration) : null;
11152
- const backgroundBorderWidth = resolved.backgroundBorderWidth !== void 0 ? evaluateAnimatable(resolved.backgroundBorderWidth, this.currentTime, this.template.duration) : 0;
11153
- const legacyPadding = resolved.padding !== void 0 ? evaluateAnimatable(resolved.padding, this.currentTime, this.template.duration) : 0;
11154
- const pt = resolved.paddingTop !== void 0 ? evaluateAnimatable(resolved.paddingTop, this.currentTime, this.template.duration) : legacyPadding;
11155
- const pr = resolved.paddingRight !== void 0 ? evaluateAnimatable(resolved.paddingRight, this.currentTime, this.template.duration) : legacyPadding;
11156
- const pb = resolved.paddingBottom !== void 0 ? evaluateAnimatable(resolved.paddingBottom, this.currentTime, this.template.duration) : legacyPadding;
11157
- const pl = resolved.paddingLeft !== void 0 ? evaluateAnimatable(resolved.paddingLeft, this.currentTime, this.template.duration) : legacyPadding;
12005
+ const flexLayout = this.computedFlexLayouts.get(resolved.id);
12006
+ const x = flexLayout?.x ?? evaluateAnimatable(resolved.x, this.currentTime, this.template.duration);
12007
+ const y = flexLayout?.y ?? evaluateAnimatable(resolved.y, this.currentTime, this.template.duration);
12008
+ const rawWidth = flexLayout?.width ?? this.evaluateTextDimension(resolved, "width");
12009
+ const rawHeight = flexLayout?.height ?? this.evaluateTextDimension(resolved, "height");
12010
+ const backgroundColor = resolved.backgroundColor ? evaluateAnimatable(
12011
+ resolved.backgroundColor,
12012
+ this.currentTime,
12013
+ this.template.duration
12014
+ ) : null;
12015
+ const backgroundOpacity = resolved.backgroundOpacity !== void 0 ? evaluateAnimatable(
12016
+ resolved.backgroundOpacity,
12017
+ this.currentTime,
12018
+ this.template.duration
12019
+ ) : 1;
12020
+ const backgroundRadius = resolved.backgroundRadius !== void 0 ? evaluateAnimatable(
12021
+ resolved.backgroundRadius,
12022
+ this.currentTime,
12023
+ this.template.duration
12024
+ ) : 0;
12025
+ const backgroundBorderColor = resolved.backgroundBorderColor ? evaluateAnimatable(
12026
+ resolved.backgroundBorderColor,
12027
+ this.currentTime,
12028
+ this.template.duration
12029
+ ) : null;
12030
+ const backgroundBorderWidth = resolved.backgroundBorderWidth !== void 0 ? evaluateAnimatable(
12031
+ resolved.backgroundBorderWidth,
12032
+ this.currentTime,
12033
+ this.template.duration
12034
+ ) : 0;
12035
+ const legacyPadding = resolved.padding !== void 0 ? evaluateAnimatable(
12036
+ resolved.padding,
12037
+ this.currentTime,
12038
+ this.template.duration
12039
+ ) : 0;
12040
+ const pt = resolved.paddingTop !== void 0 ? evaluateAnimatable(
12041
+ resolved.paddingTop,
12042
+ this.currentTime,
12043
+ this.template.duration
12044
+ ) : legacyPadding;
12045
+ const pr = resolved.paddingRight !== void 0 ? evaluateAnimatable(
12046
+ resolved.paddingRight,
12047
+ this.currentTime,
12048
+ this.template.duration
12049
+ ) : legacyPadding;
12050
+ const pb = resolved.paddingBottom !== void 0 ? evaluateAnimatable(
12051
+ resolved.paddingBottom,
12052
+ this.currentTime,
12053
+ this.template.duration
12054
+ ) : legacyPadding;
12055
+ const pl = resolved.paddingLeft !== void 0 ? evaluateAnimatable(
12056
+ resolved.paddingLeft,
12057
+ this.currentTime,
12058
+ this.template.duration
12059
+ ) : legacyPadding;
11158
12060
  const overflow = resolved.overflow;
11159
12061
  const verticalAlign = resolved.verticalAlign || "middle";
11160
- const visibleCharsCount = Math.floor(transform.typewriterProgress * content.length);
12062
+ const visibleCharsCount = Math.floor(
12063
+ transform.typewriterProgress * content.length
12064
+ );
11161
12065
  const textToDraw = content.slice(0, visibleCharsCount);
11162
12066
  ctx.save();
11163
12067
  ctx.font = `${fontWeight} ${fontSize}px "${fontFamily}", "${rawFontFamily}", sans-serif`;
11164
12068
  ctx.textBaseline = "alphabetic";
11165
12069
  ctx.textAlign = align;
11166
12070
  let adjustedFontSize = fontSize;
11167
- let lines = [textToDraw];
12071
+ const lineHeightMultiplier = Number(
12072
+ evaluateAnimatable(
12073
+ resolved.lineHeight,
12074
+ this.currentTime,
12075
+ this.template.duration
12076
+ )
12077
+ ) || 1.25;
12078
+ const rawLines = textToDraw.split("\n");
12079
+ let lines = rawLines;
12080
+ const maxLineTextWidth = Math.max(
12081
+ ...rawLines.map((l) => ctx.measureText(l || "Ag").width),
12082
+ 20
12083
+ );
11168
12084
  let resolvedWidth;
11169
- if (rawWidth === "auto") {
11170
- const measured = ctx.measureText(textToDraw || "Ag").width;
11171
- resolvedWidth = measured + pl + pr;
12085
+ if (rawWidth === "auto" || overflow === "expand-panel" || backgroundColor && !rawWidth) {
12086
+ resolvedWidth = maxLineTextWidth + pl + pr;
12087
+ } else if (flexLayout) {
12088
+ resolvedWidth = overflow === "shrink" || overflow === "wrap" ? flexLayout.width : Math.max(flexLayout.width, maxLineTextWidth + pl + pr);
11172
12089
  } else {
11173
12090
  resolvedWidth = rawWidth;
11174
12091
  }
11175
12092
  const contentW = Math.max(0, resolvedWidth - pl - pr);
11176
12093
  if (overflow === "shrink") {
11177
- const measuredWidth = ctx.measureText(textToDraw).width;
11178
- let scale = measuredWidth > contentW && contentW > 0 ? contentW / measuredWidth : 1;
12094
+ let scale = maxLineTextWidth > contentW && contentW > 0 ? contentW / maxLineTextWidth : 1;
11179
12095
  if (rawHeight !== "auto") {
11180
12096
  const declaredContentH = Math.max(0, rawHeight - pt - pb);
11181
12097
  const singleLineH = fontSize * 1;
@@ -11187,20 +12103,22 @@ var TemplateRenderer = class {
11187
12103
  adjustedFontSize = fontSize * scale;
11188
12104
  ctx.font = `${fontWeight} ${adjustedFontSize}px "${fontFamily}", "${rawFontFamily}", sans-serif`;
11189
12105
  }
11190
- } else if (overflow === "wrap") {
11191
- lines = wrapTextToWidth(ctx, textToDraw, contentW, 0);
12106
+ } else if (overflow === "wrap" && contentW > 0) {
12107
+ lines = [];
12108
+ for (const rLine of rawLines) {
12109
+ lines.push(...wrapTextToWidth(ctx, rLine, contentW, 0));
12110
+ }
11192
12111
  } else if (overflow === "expand-panel") {
11193
- const measuredWidth = ctx.measureText(textToDraw).width;
11194
- resolvedWidth = measuredWidth + pl + pr;
12112
+ resolvedWidth = maxLineTextWidth + pl + pr;
11195
12113
  }
12114
+ const lineAdvance = adjustedFontSize * lineHeightMultiplier;
12115
+ const sampleMetrics = ctx.measureText(lines[0] || "Ag");
12116
+ const ascent = sampleMetrics.actualBoundingBoxAscent ?? adjustedFontSize * 0.8;
12117
+ const descent = sampleMetrics.actualBoundingBoxDescent ?? adjustedFontSize * 0.2;
12118
+ const inkLineH = ascent + descent;
12119
+ const totalInkH = lines.length === 1 ? inkLineH : inkLineH + (lines.length - 1) * lineAdvance;
11196
12120
  let resolvedHeight;
11197
12121
  if (rawHeight === "auto") {
11198
- const sampleMetrics2 = ctx.measureText(lines[0] || "Ag");
11199
- const ascent2 = sampleMetrics2.actualBoundingBoxAscent ?? adjustedFontSize * 0.8;
11200
- const descent2 = sampleMetrics2.actualBoundingBoxDescent ?? adjustedFontSize * 0.2;
11201
- const inkLineH2 = ascent2 + descent2;
11202
- const lineAdvance = adjustedFontSize * 1.2;
11203
- const totalInkH = lines.length === 1 ? inkLineH2 : inkLineH2 + (lines.length - 1) * lineAdvance;
11204
12122
  resolvedHeight = totalInkH + pt + pb;
11205
12123
  } else {
11206
12124
  resolvedHeight = rawHeight;
@@ -11218,10 +12136,30 @@ var TemplateRenderer = class {
11218
12136
  bgX = x;
11219
12137
  }
11220
12138
  }
11221
- this.lastLayerLayouts.set(resolved.id, { x: bgX, y: bgY, width: bgWidth, height: bgHeight });
12139
+ if (resolved.anchor) {
12140
+ const anchored = resolveAnchorPosition(
12141
+ resolved.anchor,
12142
+ { x: bgX, y: bgY, width: bgWidth, height: bgHeight },
12143
+ this.template.canvasWidth,
12144
+ this.template.canvasHeight
12145
+ );
12146
+ bgX = anchored.x;
12147
+ bgY = anchored.y;
12148
+ bgWidth = anchored.width;
12149
+ bgHeight = anchored.height;
12150
+ }
12151
+ this.lastLayerLayouts.set(resolved.id, {
12152
+ x: bgX,
12153
+ y: bgY,
12154
+ width: bgWidth,
12155
+ height: bgHeight
12156
+ });
11222
12157
  const styleRef = resolved.styleRef;
11223
12158
  if (styleRef?.snapshot?.effectLayers) {
11224
- const effectCanvas = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(Math.max(1, Math.ceil(bgWidth)), Math.max(1, Math.ceil(bgHeight))) : typeof document !== "undefined" ? Object.assign(document.createElement("canvas"), {
12159
+ const effectCanvas = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(
12160
+ Math.max(1, Math.ceil(bgWidth)),
12161
+ Math.max(1, Math.ceil(bgHeight))
12162
+ ) : typeof document !== "undefined" ? Object.assign(document.createElement("canvas"), {
11225
12163
  width: Math.max(1, Math.ceil(bgWidth)),
11226
12164
  height: Math.max(1, Math.ceil(bgHeight))
11227
12165
  }) : null;
@@ -11237,7 +12175,13 @@ var TemplateRenderer = class {
11237
12175
  effectScene.text.textPosX = "center";
11238
12176
  effectScene.text.textPosY = "middle";
11239
12177
  evaluateScene(effectScene, this.currentTime, effectCtx);
11240
- ctx.drawImage(effectCanvas, bgX, bgY, bgWidth, bgHeight);
12178
+ ctx.drawImage(
12179
+ effectCanvas,
12180
+ bgX,
12181
+ bgY,
12182
+ bgWidth,
12183
+ bgHeight
12184
+ );
11241
12185
  ctx.restore();
11242
12186
  return;
11243
12187
  }
@@ -11246,22 +12190,39 @@ var TemplateRenderer = class {
11246
12190
  let contentY = bgY + pt;
11247
12191
  let contentH = Math.max(0, bgHeight - pt - pb);
11248
12192
  ctx.save();
11249
- ctx.beginPath();
11250
- if (backgroundRadius > 0) {
11251
- ctx.moveTo(bgX + backgroundRadius, bgY);
11252
- ctx.lineTo(bgX + bgWidth - backgroundRadius, bgY);
11253
- ctx.quadraticCurveTo(bgX + bgWidth, bgY, bgX + bgWidth, bgY + backgroundRadius);
11254
- ctx.lineTo(bgX + bgWidth, bgY + bgHeight - backgroundRadius);
11255
- ctx.quadraticCurveTo(bgX + bgWidth, bgY + bgHeight, bgX + bgWidth - backgroundRadius, bgY + bgHeight);
11256
- ctx.lineTo(bgX + backgroundRadius, bgY + bgHeight);
11257
- ctx.quadraticCurveTo(bgX, bgY + bgHeight, bgX, bgY + bgHeight - backgroundRadius);
11258
- ctx.lineTo(bgX, bgY + backgroundRadius);
11259
- ctx.quadraticCurveTo(bgX, bgY, bgX + backgroundRadius, bgY);
11260
- } else {
11261
- ctx.rect(bgX, bgY, bgWidth, bgHeight);
12193
+ if (overflow === "clip") {
12194
+ ctx.beginPath();
12195
+ if (backgroundRadius > 0) {
12196
+ ctx.moveTo(bgX + backgroundRadius, bgY);
12197
+ ctx.lineTo(bgX + bgWidth - backgroundRadius, bgY);
12198
+ ctx.quadraticCurveTo(
12199
+ bgX + bgWidth,
12200
+ bgY,
12201
+ bgX + bgWidth,
12202
+ bgY + backgroundRadius
12203
+ );
12204
+ ctx.lineTo(bgX + bgWidth, bgY + bgHeight - backgroundRadius);
12205
+ ctx.quadraticCurveTo(
12206
+ bgX + bgWidth,
12207
+ bgY + bgHeight,
12208
+ bgX + bgWidth - backgroundRadius,
12209
+ bgY + bgHeight
12210
+ );
12211
+ ctx.lineTo(bgX + backgroundRadius, bgY + bgHeight);
12212
+ ctx.quadraticCurveTo(
12213
+ bgX,
12214
+ bgY + bgHeight,
12215
+ bgX,
12216
+ bgY + bgHeight - backgroundRadius
12217
+ );
12218
+ ctx.lineTo(bgX, bgY + backgroundRadius);
12219
+ ctx.quadraticCurveTo(bgX, bgY, bgX + backgroundRadius, bgY);
12220
+ } else {
12221
+ ctx.rect(bgX, bgY, bgWidth, bgHeight);
12222
+ }
12223
+ ctx.closePath();
12224
+ ctx.clip();
11262
12225
  }
11263
- ctx.closePath();
11264
- ctx.clip();
11265
12226
  if (backgroundColor) {
11266
12227
  const currentAlpha = ctx.globalAlpha;
11267
12228
  ctx.save();
@@ -11271,11 +12232,26 @@ var TemplateRenderer = class {
11271
12232
  ctx.beginPath();
11272
12233
  ctx.moveTo(bgX + backgroundRadius, bgY);
11273
12234
  ctx.lineTo(bgX + bgWidth - backgroundRadius, bgY);
11274
- ctx.quadraticCurveTo(bgX + bgWidth, bgY, bgX + bgWidth, bgY + backgroundRadius);
12235
+ ctx.quadraticCurveTo(
12236
+ bgX + bgWidth,
12237
+ bgY,
12238
+ bgX + bgWidth,
12239
+ bgY + backgroundRadius
12240
+ );
11275
12241
  ctx.lineTo(bgX + bgWidth, bgY + bgHeight - backgroundRadius);
11276
- ctx.quadraticCurveTo(bgX + bgWidth, bgY + bgHeight, bgX + bgWidth - backgroundRadius, bgY + bgHeight);
12242
+ ctx.quadraticCurveTo(
12243
+ bgX + bgWidth,
12244
+ bgY + bgHeight,
12245
+ bgX + bgWidth - backgroundRadius,
12246
+ bgY + bgHeight
12247
+ );
11277
12248
  ctx.lineTo(bgX + backgroundRadius, bgY + bgHeight);
11278
- ctx.quadraticCurveTo(bgX, bgY + bgHeight, bgX, bgY + bgHeight - backgroundRadius);
12249
+ ctx.quadraticCurveTo(
12250
+ bgX,
12251
+ bgY + bgHeight,
12252
+ bgX,
12253
+ bgY + bgHeight - backgroundRadius
12254
+ );
11279
12255
  ctx.lineTo(bgX, bgY + backgroundRadius);
11280
12256
  ctx.quadraticCurveTo(bgX, bgY, bgX + backgroundRadius, bgY);
11281
12257
  ctx.closePath();
@@ -11307,13 +12283,93 @@ var TemplateRenderer = class {
11307
12283
  } else {
11308
12284
  drawX = contentX;
11309
12285
  }
11310
- const sampleMetrics = ctx.measureText(lines[0] || "Ag");
11311
- const ascent = sampleMetrics.actualBoundingBoxAscent ?? adjustedFontSize * 0.8;
11312
- const descent = sampleMetrics.actualBoundingBoxDescent ?? adjustedFontSize * 0.2;
11313
- const inkLineH = ascent + descent;
11314
- const lineHeight = adjustedFontSize * 1.2;
11315
- if (overflow === "wrap") {
11316
- const totalInkHeight = inkLineH + (lines.length - 1) * lineHeight;
12286
+ if (resolved.splitAnimator) {
12287
+ const inEnd = resolved.animation.inDuration;
12288
+ const animProgress = inEnd > 0 ? Math.min(1, Math.max(0, this.currentTime / inEnd)) : 1;
12289
+ const splitUnits = splitTextContent(
12290
+ textToDraw,
12291
+ resolved.splitAnimator.splitBy
12292
+ );
12293
+ const computedUnits = evaluateSplitTextTransforms(
12294
+ splitUnits,
12295
+ resolved.splitAnimator,
12296
+ animProgress,
12297
+ "in"
12298
+ );
12299
+ let currentX = drawX;
12300
+ if (align === "center") {
12301
+ const fullW = ctx.measureText(textToDraw).width;
12302
+ currentX = contentX + (contentW - fullW) / 2;
12303
+ } else if (align === "right") {
12304
+ const fullW = ctx.measureText(textToDraw).width;
12305
+ currentX = contentX + contentW - fullW;
12306
+ }
12307
+ const drawY = verticalAlign === "top" ? contentY + ascent : verticalAlign === "bottom" ? contentY + contentH - descent : contentY + (contentH - inkLineH) / 2 + ascent;
12308
+ computedUnits.forEach((item, unitIdx) => {
12309
+ const span = getSpanForCharIndex(
12310
+ resolved.spans,
12311
+ item.unit.charStartIndex
12312
+ );
12313
+ const charColor = resolved.perCharFillEnabled && resolved.charFillColors?.[unitIdx] ? resolved.charFillColors[unitIdx] : span?.color || color;
12314
+ ctx.save();
12315
+ ctx.globalAlpha = ctx.globalAlpha * item.opacity;
12316
+ ctx.fillStyle = charColor;
12317
+ const uW = ctx.measureText(item.unit.text).width;
12318
+ const uCX = currentX + uW / 2 + item.x;
12319
+ const uCY = drawY - ascent / 2 + item.y;
12320
+ ctx.translate(uCX, uCY);
12321
+ ctx.scale(item.scale * item.scaleX, item.scale * item.scaleY);
12322
+ if (item.rotation !== 0) ctx.rotate(item.rotation * Math.PI / 180);
12323
+ ctx.translate(-uCX, -uCY);
12324
+ if (item.blur > 0 && "filter" in ctx) {
12325
+ ctx.filter = `blur(${item.blur}px)`;
12326
+ }
12327
+ ctx.fillText(
12328
+ item.unit.text,
12329
+ currentX + item.x,
12330
+ drawY + item.y + (span?.baselineShift || 0)
12331
+ );
12332
+ ctx.restore();
12333
+ currentX += uW + (item.letterSpacingOffset || 0);
12334
+ });
12335
+ } else if (resolved.spans && resolved.spans.length > 0) {
12336
+ const totalInkHeight = lines.length === 1 ? inkLineH : inkLineH + (lines.length - 1) * lineAdvance;
12337
+ let firstBaselineY = verticalAlign === "top" ? contentY + ascent : verticalAlign === "bottom" ? contentY + contentH - totalInkHeight + ascent : contentY + (contentH - totalInkHeight) / 2 + ascent;
12338
+ let globalCharIndex = 0;
12339
+ ctx.textAlign = "left";
12340
+ lines.forEach((line, lineIndex) => {
12341
+ let curX = contentX;
12342
+ if (align === "center") {
12343
+ const lW = ctx.measureText(line).width;
12344
+ curX = contentX + (contentW - lW) / 2;
12345
+ } else if (align === "right") {
12346
+ const lW = ctx.measureText(line).width;
12347
+ curX = contentX + contentW - lW;
12348
+ }
12349
+ const chars = Array.from(line);
12350
+ chars.forEach((ch) => {
12351
+ const span = getSpanForCharIndex(resolved.spans, globalCharIndex);
12352
+ const chColor = resolved.perCharFillEnabled && resolved.charFillColors?.[globalCharIndex] ? resolved.charFillColors[globalCharIndex] : span?.color || color;
12353
+ ctx.save();
12354
+ if (span?.fontFamily || span?.fontWeight || span?.fontSize) {
12355
+ ctx.font = `${span.fontWeight || fontWeight} ${span.fontSize || adjustedFontSize}px "${resolveFontFamilyName(
12356
+ span.fontFamily || rawFontFamily
12357
+ )}", sans-serif`;
12358
+ }
12359
+ ctx.fillStyle = chColor;
12360
+ ctx.fillText(
12361
+ ch,
12362
+ curX,
12363
+ firstBaselineY + lineIndex * lineAdvance + (span?.baselineShift || 0)
12364
+ );
12365
+ ctx.restore();
12366
+ curX += ctx.measureText(ch).width + (span?.letterSpacing || 0);
12367
+ globalCharIndex += ch.length;
12368
+ });
12369
+ globalCharIndex += 1;
12370
+ });
12371
+ } else {
12372
+ const totalInkHeight = lines.length === 1 ? inkLineH : inkLineH + (lines.length - 1) * lineAdvance;
11317
12373
  let firstBaselineY;
11318
12374
  if (verticalAlign === "top") {
11319
12375
  firstBaselineY = contentY + ascent;
@@ -11322,19 +12378,10 @@ var TemplateRenderer = class {
11322
12378
  } else {
11323
12379
  firstBaselineY = contentY + (contentH - totalInkHeight) / 2 + ascent;
11324
12380
  }
12381
+ ctx.textAlign = align;
11325
12382
  lines.forEach((line, index) => {
11326
- ctx.fillText(line, drawX, firstBaselineY + index * lineHeight);
12383
+ ctx.fillText(line, drawX, firstBaselineY + index * lineAdvance);
11327
12384
  });
11328
- } else {
11329
- let drawY;
11330
- if (verticalAlign === "top") {
11331
- drawY = contentY + ascent;
11332
- } else if (verticalAlign === "bottom") {
11333
- drawY = contentY + contentH - descent;
11334
- } else {
11335
- drawY = contentY + (contentH - inkLineH) / 2 + ascent;
11336
- }
11337
- ctx.fillText(lines[0], drawX, drawY);
11338
12385
  }
11339
12386
  ctx.restore();
11340
12387
  ctx.restore();
@@ -11342,11 +12389,24 @@ var TemplateRenderer = class {
11342
12389
  drawShapeLayer(ctx, layer2) {
11343
12390
  const resolved = layer2;
11344
12391
  const shape = resolved.shape;
11345
- const fill = evaluateAnimatable(resolved.fill, this.currentTime, this.template.duration);
11346
- const x = evaluateAnimatable(resolved.x, this.currentTime, this.template.duration);
11347
- const y = evaluateAnimatable(resolved.y, this.currentTime, this.template.duration);
11348
- const width = evaluateAnimatable(resolved.width, this.currentTime, this.template.duration);
11349
- const height = evaluateAnimatable(resolved.height, this.currentTime, this.template.duration);
12392
+ const fill = evaluateAnimatable(
12393
+ resolved.fill,
12394
+ this.currentTime,
12395
+ this.template.duration
12396
+ );
12397
+ const flexLayout = this.computedFlexLayouts.get(resolved.id);
12398
+ const x = flexLayout?.x ?? evaluateAnimatable(resolved.x, this.currentTime, this.template.duration);
12399
+ const y = flexLayout?.y ?? evaluateAnimatable(resolved.y, this.currentTime, this.template.duration);
12400
+ const width = flexLayout?.width ?? evaluateAnimatable(
12401
+ resolved.width,
12402
+ this.currentTime,
12403
+ this.template.duration
12404
+ );
12405
+ const height = flexLayout?.height ?? evaluateAnimatable(
12406
+ resolved.height,
12407
+ this.currentTime,
12408
+ this.template.duration
12409
+ );
11350
12410
  const stroke = resolved.stroke;
11351
12411
  this.lastLayerLayouts.set(resolved.id, { x, y, width, height });
11352
12412
  ctx.fillStyle = fill;
@@ -11363,8 +12423,16 @@ var TemplateRenderer = class {
11363
12423
  }
11364
12424
  ctx.fill();
11365
12425
  if (stroke && stroke.width) {
11366
- const strokeWidth = evaluateAnimatable(stroke.width, this.currentTime, this.template.duration);
11367
- const strokeColor = evaluateAnimatable(stroke.color, this.currentTime, this.template.duration);
12426
+ const strokeWidth = evaluateAnimatable(
12427
+ stroke.width,
12428
+ this.currentTime,
12429
+ this.template.duration
12430
+ );
12431
+ const strokeColor = evaluateAnimatable(
12432
+ stroke.color,
12433
+ this.currentTime,
12434
+ this.template.duration
12435
+ );
11368
12436
  if (strokeWidth > 0) {
11369
12437
  ctx.strokeStyle = strokeColor;
11370
12438
  ctx.lineWidth = strokeWidth;
@@ -11375,10 +12443,19 @@ var TemplateRenderer = class {
11375
12443
  drawImageLayer(ctx, layer2) {
11376
12444
  const resolved = layer2;
11377
12445
  const url = resolved.url;
11378
- const x = evaluateAnimatable(resolved.x, this.currentTime, this.template.duration);
11379
- const y = evaluateAnimatable(resolved.y, this.currentTime, this.template.duration);
11380
- const width = evaluateAnimatable(resolved.width, this.currentTime, this.template.duration);
11381
- const height = evaluateAnimatable(resolved.height, this.currentTime, this.template.duration);
12446
+ const flexLayout = this.computedFlexLayouts.get(resolved.id);
12447
+ const x = flexLayout?.x ?? evaluateAnimatable(resolved.x, this.currentTime, this.template.duration);
12448
+ const y = flexLayout?.y ?? evaluateAnimatable(resolved.y, this.currentTime, this.template.duration);
12449
+ const width = flexLayout?.width ?? evaluateAnimatable(
12450
+ resolved.width,
12451
+ this.currentTime,
12452
+ this.template.duration
12453
+ );
12454
+ const height = flexLayout?.height ?? evaluateAnimatable(
12455
+ resolved.height,
12456
+ this.currentTime,
12457
+ this.template.duration
12458
+ );
11382
12459
  this.lastLayerLayouts.set(resolved.id, { x, y, width, height });
11383
12460
  if (!url) return;
11384
12461
  let img = this.imageCache.get(url);
@@ -11391,6 +12468,33 @@ var TemplateRenderer = class {
11391
12468
  ctx.drawImage(img, x, y, width, height);
11392
12469
  }
11393
12470
  }
12471
+ /**
12472
+ * Renders multi-frame ghost/onion-skin frames onto the canvas for precision motion tuning.
12473
+ */
12474
+ drawOnionSkin(ctx, time, options = {}) {
12475
+ const frameCount = options.frameCount ?? 2;
12476
+ const delta = options.frameDelta ?? 0.066;
12477
+ const duration = this.template.duration || 3;
12478
+ for (let i = frameCount; i >= 1; i--) {
12479
+ const ghostTime = Math.max(0, time - i * delta);
12480
+ if (ghostTime !== time) {
12481
+ ctx.save();
12482
+ ctx.globalAlpha = 0.25 / i;
12483
+ this.drawLayers(ctx, ghostTime);
12484
+ ctx.restore();
12485
+ }
12486
+ }
12487
+ for (let i = frameCount; i >= 1; i--) {
12488
+ const ghostTime = Math.min(duration, time + i * delta);
12489
+ if (ghostTime !== time) {
12490
+ ctx.save();
12491
+ ctx.globalAlpha = 0.25 / i;
12492
+ this.drawLayers(ctx, ghostTime);
12493
+ ctx.restore();
12494
+ }
12495
+ }
12496
+ this.drawFrame(ctx, time, { skipClear: true });
12497
+ }
11394
12498
  };
11395
12499
 
11396
12500
  // src/templates/presets.ts
@@ -11693,66 +12797,1408 @@ var BUILTIN_CANVAS_TEMPLATES = [
11693
12797
  hold: "full"
11694
12798
  }
11695
12799
  }
11696
- ]
11697
- },
11698
- {
11699
- id: "countdown-timer",
11700
- label: "Futuristic Countdown",
11701
- category: "countdown",
11702
- duration: 5,
11703
- canvasWidth: 1920,
11704
- canvasHeight: 1080,
11705
- layers: [
11706
- {
11707
- kind: "shape",
11708
- id: "outer-ring",
11709
- shape: "circle",
11710
- fill: "rgba(124, 111, 255, 0.1)",
11711
- stroke: { color: "#7c6fff", width: 4 },
11712
- x: 810,
11713
- // Centered: (1920 - 300) / 2
11714
- y: 390,
11715
- // Centered vertically
11716
- width: 300,
11717
- height: 300,
11718
- animation: {
11719
- in: "scale-in",
11720
- out: "fade",
11721
- inDuration: 0.6,
11722
- outDuration: 0.4,
11723
- hold: "full"
12800
+ ]
12801
+ },
12802
+ {
12803
+ id: "countdown-timer",
12804
+ label: "Futuristic Countdown",
12805
+ category: "countdown",
12806
+ duration: 5,
12807
+ canvasWidth: 1920,
12808
+ canvasHeight: 1080,
12809
+ layers: [
12810
+ {
12811
+ kind: "shape",
12812
+ id: "outer-ring",
12813
+ shape: "circle",
12814
+ fill: "rgba(124, 111, 255, 0.1)",
12815
+ stroke: { color: "#7c6fff", width: 4 },
12816
+ x: 810,
12817
+ // Centered: (1920 - 300) / 2
12818
+ y: 390,
12819
+ // Centered vertically
12820
+ width: 300,
12821
+ height: 300,
12822
+ animation: {
12823
+ in: "scale-in",
12824
+ out: "fade",
12825
+ inDuration: 0.6,
12826
+ outDuration: 0.4,
12827
+ hold: "full"
12828
+ }
12829
+ },
12830
+ {
12831
+ kind: "text",
12832
+ id: "timer-digits",
12833
+ content: "5",
12834
+ fontFamily: "Poppins",
12835
+ fontSize: 120,
12836
+ fontWeight: 700,
12837
+ color: "#ffffff",
12838
+ align: "center",
12839
+ x: 810,
12840
+ y: 440,
12841
+ width: 300,
12842
+ height: 200,
12843
+ role: "primary",
12844
+ animation: {
12845
+ in: "fade",
12846
+ out: "fade",
12847
+ inDuration: 0.3,
12848
+ outDuration: 0.3,
12849
+ hold: "full"
12850
+ }
12851
+ }
12852
+ ]
12853
+ },
12854
+ {
12855
+ id: "kinetic-split-title",
12856
+ label: "Kinetic Stagger Opener",
12857
+ category: "kinetic-type",
12858
+ duration: 4,
12859
+ canvasWidth: 1920,
12860
+ canvasHeight: 1080,
12861
+ variables: {
12862
+ title: {
12863
+ key: "title",
12864
+ label: "Title Text",
12865
+ type: "string",
12866
+ defaultValue: "FUTURE MOTION"
12867
+ },
12868
+ subtitle: {
12869
+ key: "subtitle",
12870
+ label: "Subtitle Text",
12871
+ type: "string",
12872
+ defaultValue: "ADVANCED TYPOGRAPHY STUDIO"
12873
+ }
12874
+ },
12875
+ layers: [
12876
+ {
12877
+ kind: "text",
12878
+ id: "main-title",
12879
+ content: "{{title}}",
12880
+ fontFamily: "Poppins",
12881
+ fontSize: 72,
12882
+ fontWeight: 900,
12883
+ color: "#ffffff",
12884
+ align: "center",
12885
+ x: 460,
12886
+ y: 440,
12887
+ width: 1e3,
12888
+ height: 100,
12889
+ role: "primary",
12890
+ animation: {
12891
+ in: "scale-pop",
12892
+ out: "fade",
12893
+ inDuration: 0.8,
12894
+ outDuration: 0.4,
12895
+ hold: "full"
12896
+ },
12897
+ splitAnimator: {
12898
+ splitBy: "character",
12899
+ direction: "start-to-end",
12900
+ delayPerUnit: 0.03,
12901
+ overlap: 0.6,
12902
+ initialTransform: {
12903
+ y: 40,
12904
+ opacity: 0,
12905
+ scale: 0.7,
12906
+ rotateX: 45,
12907
+ blur: 8
12908
+ },
12909
+ easing: "cubic-bezier",
12910
+ bezier: { x1: 0.2, y1: 0.8, x2: 0.2, y2: 1 }
12911
+ },
12912
+ anchor: {
12913
+ anchorPoint: "center",
12914
+ maxWidthPercentage: 90
12915
+ }
12916
+ },
12917
+ {
12918
+ kind: "text",
12919
+ id: "sub-title",
12920
+ content: "{{subtitle}}",
12921
+ fontFamily: "Inter Variable",
12922
+ fontSize: 22,
12923
+ fontWeight: 600,
12924
+ color: "#7c6fff",
12925
+ letterSpacing: 6,
12926
+ align: "center",
12927
+ x: 460,
12928
+ y: 550,
12929
+ width: 1e3,
12930
+ height: 40,
12931
+ role: "secondary",
12932
+ animation: {
12933
+ in: "track-in",
12934
+ out: "fade",
12935
+ inDuration: 0.9,
12936
+ outDuration: 0.4,
12937
+ hold: "full"
12938
+ },
12939
+ anchor: {
12940
+ anchorPoint: "center",
12941
+ maxWidthPercentage: 85
12942
+ }
12943
+ }
12944
+ ]
12945
+ },
12946
+ {
12947
+ id: "responsive-speaker-lower-third",
12948
+ label: "Responsive Speaker Badge",
12949
+ category: "lower-third",
12950
+ duration: 5,
12951
+ canvasWidth: 1920,
12952
+ canvasHeight: 1080,
12953
+ variables: {
12954
+ speakerName: {
12955
+ key: "speakerName",
12956
+ label: "Speaker Name",
12957
+ type: "string",
12958
+ defaultValue: "Sarah Chen"
12959
+ },
12960
+ speakerRole: {
12961
+ key: "speakerRole",
12962
+ label: "Role / Organization",
12963
+ type: "string",
12964
+ defaultValue: "VP of Product @ Clypra"
12965
+ }
12966
+ },
12967
+ layers: [
12968
+ {
12969
+ kind: "text",
12970
+ id: "badge-name",
12971
+ content: "{{speakerName}}",
12972
+ fontFamily: "Poppins",
12973
+ fontSize: 32,
12974
+ fontWeight: 700,
12975
+ color: "#ffffff",
12976
+ backgroundColor: "#1E1E28",
12977
+ backgroundOpacity: 0.95,
12978
+ backgroundRadius: 8,
12979
+ backgroundBorderColor: "#7c6fff",
12980
+ backgroundBorderWidth: 2,
12981
+ paddingTop: 12,
12982
+ paddingBottom: 12,
12983
+ paddingLeft: 20,
12984
+ paddingRight: 20,
12985
+ align: "left",
12986
+ x: 100,
12987
+ y: 860,
12988
+ width: "auto",
12989
+ height: "auto",
12990
+ overflow: "expand-panel",
12991
+ role: "primary",
12992
+ animation: {
12993
+ in: "slide-right",
12994
+ out: "fade",
12995
+ inDuration: 0.5,
12996
+ outDuration: 0.3,
12997
+ hold: "full"
12998
+ },
12999
+ anchor: {
13000
+ anchorPoint: "bottom-left",
13001
+ offsetPercentageX: 5,
13002
+ offsetPercentageY: 10
13003
+ }
13004
+ },
13005
+ {
13006
+ kind: "text",
13007
+ id: "badge-role",
13008
+ content: "{{speakerRole}}",
13009
+ fontFamily: "Inter Variable",
13010
+ fontSize: 18,
13011
+ fontWeight: 500,
13012
+ color: "#9A9AAA",
13013
+ backgroundColor: "#121218",
13014
+ backgroundOpacity: 0.85,
13015
+ backgroundRadius: 6,
13016
+ paddingTop: 8,
13017
+ paddingBottom: 8,
13018
+ paddingLeft: 16,
13019
+ paddingRight: 16,
13020
+ align: "left",
13021
+ x: 100,
13022
+ y: 930,
13023
+ width: "auto",
13024
+ height: "auto",
13025
+ overflow: "expand-panel",
13026
+ role: "secondary",
13027
+ animation: {
13028
+ in: "slide-right",
13029
+ out: "fade",
13030
+ inDuration: 0.6,
13031
+ outDuration: 0.3,
13032
+ hold: "full"
13033
+ },
13034
+ anchor: {
13035
+ anchorPoint: "bottom-left",
13036
+ offsetPercentageX: 5,
13037
+ offsetPercentageY: 4
13038
+ }
13039
+ }
13040
+ ]
13041
+ }
13042
+ ];
13043
+ function getCanvasTemplatePreset(id) {
13044
+ return BUILTIN_CANVAS_TEMPLATES.find((t) => t.id === id);
13045
+ }
13046
+ function getCanvasTemplatesByCategory(category) {
13047
+ return BUILTIN_CANVAS_TEMPLATES.filter((t) => t.category === category);
13048
+ }
13049
+
13050
+ // src/textTemplates/contract.ts
13051
+ var TEXT_TEMPLATE_KIND = "text-template";
13052
+ var TEXT_TEMPLATE_SCHEMA_VERSION = 4;
13053
+ var TEXT_TEMPLATE_RENDERER_VERSION = "1.5.0";
13054
+
13055
+ // src/textTemplates/normalize.ts
13056
+ function clone2(value) {
13057
+ return JSON.parse(JSON.stringify(value));
13058
+ }
13059
+ function stableStringify2(value) {
13060
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
13061
+ if (Array.isArray(value)) return `[${value.map(stableStringify2).join(",")}]`;
13062
+ const object = value;
13063
+ return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableStringify2(object[key])}`).join(",")}}`;
13064
+ }
13065
+ function canonicalTemplateHash(value) {
13066
+ const input = stableStringify2(value);
13067
+ let hash = 2166136261;
13068
+ for (let index = 0; index < input.length; index += 1) {
13069
+ hash ^= input.charCodeAt(index);
13070
+ hash = Math.imul(hash, 16777619);
13071
+ }
13072
+ return `fnv1a-${(hash >>> 0).toString(16).padStart(8, "0")}`;
13073
+ }
13074
+ function now() {
13075
+ return (/* @__PURE__ */ new Date()).toISOString();
13076
+ }
13077
+ function resolveAnimatableValue(raw, fallback) {
13078
+ if (raw == null) return fallback;
13079
+ if (typeof raw === "object" && raw !== null && "keyframes" in raw && Array.isArray(raw.keyframes)) {
13080
+ const kfs = raw.keyframes;
13081
+ if (kfs.length > 0 && kfs[0]?.value !== void 0) {
13082
+ return kfs[0].value;
13083
+ }
13084
+ }
13085
+ return raw;
13086
+ }
13087
+ function resolveNumericProperty(raw, fallback) {
13088
+ const unwrapped = resolveAnimatableValue(raw, fallback);
13089
+ const n = Number(unwrapped);
13090
+ return Number.isFinite(n) ? n : fallback;
13091
+ }
13092
+ function resolveStringProperty(raw, fallback) {
13093
+ const unwrapped = resolveAnimatableValue(raw, fallback);
13094
+ return unwrapped != null ? String(unwrapped) : fallback;
13095
+ }
13096
+ function resolveDimension(raw, fallback) {
13097
+ if (raw === "auto") return "auto";
13098
+ const unwrapped = resolveAnimatableValue(raw, fallback);
13099
+ if (unwrapped === "auto") return "auto";
13100
+ const n = Number(unwrapped);
13101
+ return Number.isFinite(n) ? n : fallback;
13102
+ }
13103
+ function propertyKeyframes(layer2) {
13104
+ const result = {};
13105
+ for (const property of ["x", "y", "width", "height", "opacity", "fontSize", "fontWeight", "letterSpacing"]) {
13106
+ const value = layer2?.[property];
13107
+ if (value && typeof value === "object" && Array.isArray(value.keyframes) && value.keyframes.length > 0) {
13108
+ result[property] = { keyframes: clone2(value.keyframes) };
13109
+ }
13110
+ }
13111
+ return Object.keys(result).length ? result : void 0;
13112
+ }
13113
+ function nodeAnimation(layer2) {
13114
+ const propertyFrames = propertyKeyframes(layer2);
13115
+ if (!propertyFrames) return layer2?.animation;
13116
+ return {
13117
+ ...layer2?.animation || { in: "none", out: "none", inDuration: 0, outDuration: 0, hold: "full" },
13118
+ propertyKeyframes: propertyFrames
13119
+ };
13120
+ }
13121
+ function legacyLayerToNode(layer2, index) {
13122
+ const id = String(layer2?.id || `${layer2?.kind || "node"}-${index + 1}`);
13123
+ const x = resolveNumericProperty(layer2?.x ?? layer2?.relativePosition?.x, 0);
13124
+ const y = resolveNumericProperty(layer2?.y ?? layer2?.relativePosition?.y, 0);
13125
+ const width = resolveDimension(layer2?.width, 400);
13126
+ const height = resolveDimension(layer2?.height, 120);
13127
+ const animation = nodeAnimation(layer2);
13128
+ const anchor = layer2?.anchor;
13129
+ const parentId = layer2?.parentId;
13130
+ const visible = layer2?.visible !== false;
13131
+ if (layer2?.kind === "container" || layer2?.kind === "group") {
13132
+ const container = layer2?.containerProperties || layer2;
13133
+ const layout = container?.layout || {};
13134
+ return {
13135
+ id,
13136
+ name: String(layer2?.name || id),
13137
+ type: "container",
13138
+ layout: {
13139
+ type: layout.type === "absolute" ? "absolute" : "flex",
13140
+ direction: layout.direction === "column" ? "column" : "row",
13141
+ gap: resolveNumericProperty(layout.gap, 0),
13142
+ alignItems: ["start", "center", "end", "stretch"].includes(
13143
+ layout.alignItems
13144
+ ) ? layout.alignItems : "center",
13145
+ justifyContent: [
13146
+ "start",
13147
+ "center",
13148
+ "end",
13149
+ "space-between",
13150
+ "space-around"
13151
+ ].includes(layout.justifyContent) ? layout.justifyContent : "start",
13152
+ paddingTop: resolveNumericProperty(
13153
+ layout.paddingTop ?? container.paddingTop,
13154
+ 0
13155
+ ),
13156
+ paddingRight: resolveNumericProperty(
13157
+ layout.paddingRight ?? container.paddingRight,
13158
+ 0
13159
+ ),
13160
+ paddingBottom: resolveNumericProperty(
13161
+ layout.paddingBottom ?? container.paddingBottom,
13162
+ 0
13163
+ ),
13164
+ paddingLeft: resolveNumericProperty(
13165
+ layout.paddingLeft ?? container.paddingLeft,
13166
+ 0
13167
+ )
13168
+ },
13169
+ x,
13170
+ y,
13171
+ width,
13172
+ height,
13173
+ visible,
13174
+ style: {
13175
+ backgroundColor: container?.backgroundColor ? resolveStringProperty(container.backgroundColor, "") : void 0,
13176
+ backgroundOpacity: resolveNumericProperty(
13177
+ container?.backgroundOpacity,
13178
+ 1
13179
+ ),
13180
+ borderRadius: resolveNumericProperty(
13181
+ container?.backgroundRadius ?? container?.borderRadius,
13182
+ 0
13183
+ ),
13184
+ borderColor: container?.backgroundBorderColor ?? container?.borderColor ? resolveStringProperty(
13185
+ container.backgroundBorderColor ?? container.borderColor,
13186
+ ""
13187
+ ) : void 0,
13188
+ borderWidth: resolveNumericProperty(
13189
+ container?.backgroundBorderWidth ?? container?.borderWidth,
13190
+ 0
13191
+ ),
13192
+ opacity: resolveNumericProperty(container?.opacity, 1)
13193
+ },
13194
+ animation,
13195
+ anchor,
13196
+ parentId
13197
+ };
13198
+ }
13199
+ if (layer2?.kind === "shape" || layer2?.kind === "solid") {
13200
+ const shape = layer2?.solidProperties || layer2;
13201
+ return {
13202
+ id,
13203
+ name: String(layer2?.name || id),
13204
+ type: "shape",
13205
+ shapeType: shape?.shape === "circle" ? "circle" : shape?.shape === "line" ? "line" : "rectangle",
13206
+ x,
13207
+ y,
13208
+ width: typeof width === "number" ? width : 400,
13209
+ height: typeof height === "number" ? height : 200,
13210
+ visible,
13211
+ style: {
13212
+ fillColor: resolveStringProperty(
13213
+ shape?.fill ?? shape?.color,
13214
+ "#000000"
13215
+ ),
13216
+ fillOpacity: resolveNumericProperty(
13217
+ shape?.opacity ?? shape?.fillOpacity,
13218
+ 1
13219
+ ),
13220
+ strokeColor: shape?.stroke?.color ? resolveStringProperty(shape.stroke.color, "#000000") : void 0,
13221
+ strokeWidth: shape?.stroke?.width ? resolveNumericProperty(shape.stroke.width, 0) : void 0
13222
+ },
13223
+ animation,
13224
+ anchor,
13225
+ parentId
13226
+ };
13227
+ }
13228
+ if (layer2?.kind === "image") {
13229
+ const image = layer2?.imageProperties || layer2;
13230
+ return {
13231
+ id,
13232
+ name: String(layer2?.name || id),
13233
+ type: "media",
13234
+ mediaType: "image",
13235
+ x,
13236
+ y,
13237
+ width: typeof width === "number" ? width : 400,
13238
+ height: typeof height === "number" ? height : 300,
13239
+ visible,
13240
+ assetId: image?.assetId,
13241
+ src: image?.url,
13242
+ style: { opacity: resolveNumericProperty(image?.opacity, 1) },
13243
+ animation,
13244
+ anchor,
13245
+ parentId
13246
+ };
13247
+ }
13248
+ const text = layer2?.textProperties || layer2;
13249
+ return {
13250
+ id,
13251
+ name: String(layer2?.name || id),
13252
+ type: "text",
13253
+ text: resolveStringProperty(text?.content ?? text?.text, "Text"),
13254
+ x,
13255
+ y,
13256
+ width,
13257
+ height,
13258
+ visible,
13259
+ animation,
13260
+ anchor,
13261
+ parentId,
13262
+ style: {
13263
+ fontFamily: resolveStringProperty(text?.fontFamily, "Inter Variable"),
13264
+ fontSize: resolveNumericProperty(text?.fontSize, 48),
13265
+ fontWeight: resolveStringProperty(text?.fontWeight, "400"),
13266
+ textColor: resolveStringProperty(
13267
+ text?.color ?? text?.textColor,
13268
+ "#FFFFFF"
13269
+ ),
13270
+ textAlign: text?.align || text?.textAlign || "center",
13271
+ lineHeight: resolveNumericProperty(text?.lineHeight, 1.2),
13272
+ letterSpacing: resolveNumericProperty(text?.letterSpacing, 0),
13273
+ overflow: text?.overflow,
13274
+ verticalAlign: text?.verticalAlign
13275
+ },
13276
+ backgroundPanel: text?.backgroundColor || text?.backgroundPanel ? {
13277
+ color: text?.backgroundPanel?.color ?? text?.backgroundColor ? resolveStringProperty(
13278
+ text?.backgroundPanel?.color ?? text?.backgroundColor,
13279
+ "#000000"
13280
+ ) : void 0,
13281
+ opacity: resolveNumericProperty(
13282
+ text?.backgroundPanel?.opacity ?? text?.backgroundOpacity,
13283
+ 1
13284
+ ),
13285
+ paddingTop: resolveNumericProperty(
13286
+ text?.backgroundPanel?.paddingTop ?? text?.paddingTop,
13287
+ 0
13288
+ ),
13289
+ paddingRight: resolveNumericProperty(
13290
+ text?.backgroundPanel?.paddingRight ?? text?.paddingRight,
13291
+ 0
13292
+ ),
13293
+ paddingBottom: resolveNumericProperty(
13294
+ text?.backgroundPanel?.paddingBottom ?? text?.paddingBottom,
13295
+ 0
13296
+ ),
13297
+ paddingLeft: resolveNumericProperty(
13298
+ text?.backgroundPanel?.paddingLeft ?? text?.paddingLeft,
13299
+ 0
13300
+ ),
13301
+ borderRadius: resolveNumericProperty(
13302
+ text?.backgroundPanel?.borderRadius ?? text?.backgroundRadius,
13303
+ 0
13304
+ ),
13305
+ borderColor: text?.backgroundPanel?.borderColor ?? text?.backgroundBorderColor ? resolveStringProperty(
13306
+ text?.backgroundPanel?.borderColor ?? text?.backgroundBorderColor,
13307
+ "#000000"
13308
+ ) : void 0,
13309
+ borderWidth: resolveNumericProperty(
13310
+ text?.backgroundPanel?.borderWidth ?? text?.backgroundBorderWidth,
13311
+ 0
13312
+ )
13313
+ } : void 0,
13314
+ spans: Array.isArray(text?.spans) ? clone2(text.spans) : void 0,
13315
+ perCharFillEnabled: Boolean(text?.perCharFillEnabled),
13316
+ charFillColors: Array.isArray(text?.charFillColors) ? clone2(text.charFillColors) : void 0,
13317
+ splitAnimator: text?.splitAnimator ? clone2(text.splitAnimator) : void 0,
13318
+ textEffectRef: text?.styleRef ? clone2(text.styleRef) : void 0,
13319
+ // Kept as optional metadata for compatibility with role-based editor
13320
+ // customizations. The canonical renderer does not depend on roles.
13321
+ ...layer2?.role ? { role: String(layer2.role) } : {}
13322
+ };
13323
+ }
13324
+ function inferControls(nodes) {
13325
+ const controls = [];
13326
+ for (const node of nodes) {
13327
+ if (node.type === "text") {
13328
+ controls.push({
13329
+ id: `text-${node.id}`,
13330
+ label: node.name || "Text",
13331
+ type: "text",
13332
+ defaultValue: node.text,
13333
+ constraints: { multiline: true, maxLength: 500 },
13334
+ target: { nodeId: node.id, propertyPath: "text" }
13335
+ });
13336
+ }
13337
+ }
13338
+ return controls;
13339
+ }
13340
+ function collectDependencies(nodes) {
13341
+ const assets = [];
13342
+ const fonts = [];
13343
+ const textEffects = [];
13344
+ const seenAssets = /* @__PURE__ */ new Set();
13345
+ const seenFonts = /* @__PURE__ */ new Set();
13346
+ const seenEffects = /* @__PURE__ */ new Set();
13347
+ for (const node of nodes) {
13348
+ if (node.type === "media" && node.assetId && !seenAssets.has(node.assetId)) {
13349
+ assets.push({
13350
+ id: node.assetId,
13351
+ type: "image",
13352
+ mimeType: "image/png",
13353
+ uri: node.src || "",
13354
+ contentHash: node.assetId
13355
+ });
13356
+ seenAssets.add(node.assetId);
13357
+ }
13358
+ if (node.type === "text" && node.style?.fontFamily) {
13359
+ const key = `${node.style.fontFamily}:${node.style.fontWeight || 400}`;
13360
+ if (!seenFonts.has(key)) {
13361
+ fonts.push({
13362
+ family: node.style.fontFamily,
13363
+ weight: Number(node.style.fontWeight || 400),
13364
+ style: "normal"
13365
+ });
13366
+ seenFonts.add(key);
13367
+ }
13368
+ if (node.textEffectRef) {
13369
+ const effectKey = `${node.textEffectRef.effectId}:${node.textEffectRef.revisionId}`;
13370
+ if (!seenEffects.has(effectKey)) {
13371
+ textEffects.push(clone2(node.textEffectRef));
13372
+ seenEffects.add(effectKey);
13373
+ }
13374
+ }
13375
+ }
13376
+ }
13377
+ return { assets, fonts, textEffects };
13378
+ }
13379
+ function normalizeTextTemplateArtifact(input) {
13380
+ if (!input || typeof input !== "object")
13381
+ throw new Error("Invalid text template artifact");
13382
+ const raw = input;
13383
+ const source = raw.document && typeof raw.document === "object" ? raw.document : raw;
13384
+ const rawLayers = Array.isArray(source.layers) ? source.layers : Array.isArray(source.elements) ? source.elements : [];
13385
+ const nodes = Array.isArray(source.nodes) ? clone2(source.nodes) : rawLayers.map(legacyLayerToNode);
13386
+ const id = String(
13387
+ raw.metadata?.id ?? source.id ?? raw.id ?? "untitled-text-template"
13388
+ );
13389
+ const label = String(
13390
+ raw.metadata?.label ?? source.title ?? raw.label ?? raw.name ?? id
13391
+ );
13392
+ const duration = Number(
13393
+ raw.timing?.duration ?? source.duration ?? raw.duration ?? 4
13394
+ );
13395
+ const fps = Number(raw.timing?.fps ?? source.fps ?? raw.fps ?? 30);
13396
+ const width = Number(
13397
+ source.canvas?.width ?? source.canvasWidth ?? raw.canvasWidth ?? raw.width ?? 1920
13398
+ );
13399
+ const height = Number(
13400
+ source.canvas?.height ?? source.canvasHeight ?? raw.canvasHeight ?? raw.height ?? 1080
13401
+ );
13402
+ const createdAt = String(
13403
+ raw.revision?.createdAt ?? source.createdAt ?? now()
13404
+ );
13405
+ const document2 = {
13406
+ id,
13407
+ kind: TEXT_TEMPLATE_KIND,
13408
+ schemaVersion: TEXT_TEMPLATE_SCHEMA_VERSION,
13409
+ templateVersion: 1,
13410
+ canvas: {
13411
+ width,
13412
+ height,
13413
+ fps,
13414
+ backgroundColor: source.canvas?.backgroundColor ?? raw.backgroundColor
13415
+ },
13416
+ nodes,
13417
+ variables: source.variables && typeof source.variables === "object" ? clone2(source.variables) : void 0
13418
+ };
13419
+ const controls = Array.isArray(raw.controls) ? clone2(raw.controls) : inferControls(nodes);
13420
+ const timing = {
13421
+ duration,
13422
+ fps,
13423
+ durationPolicy: raw.timing?.durationPolicy || "stretch",
13424
+ intro: raw.timing?.intro ? clone2(raw.timing.intro) : void 0,
13425
+ outro: raw.timing?.outro ? clone2(raw.timing.outro) : void 0,
13426
+ loop: raw.timing?.loop ? clone2(raw.timing.loop) : void 0,
13427
+ markers: Array.isArray(raw.timing?.markers) ? clone2(raw.timing.markers) : void 0
13428
+ };
13429
+ const dependencies = raw.dependencies?.assets ? clone2(raw.dependencies) : collectDependencies(nodes);
13430
+ const content = { document: document2, controls, timing, dependencies };
13431
+ const contentHash = String(
13432
+ raw.revision?.contentHash || canonicalTemplateHash(content)
13433
+ );
13434
+ const revision = {
13435
+ revisionId: String(
13436
+ raw.revision?.revisionId ?? raw.revisionId ?? `rev-${contentHash}`
13437
+ ),
13438
+ contentHash,
13439
+ schemaVersion: TEXT_TEMPLATE_SCHEMA_VERSION,
13440
+ rendererVersion: String(
13441
+ raw.revision?.rendererVersion ?? raw.rendererVersion ?? TEXT_TEMPLATE_RENDERER_VERSION
13442
+ ),
13443
+ createdAt,
13444
+ status: raw.revision?.status
13445
+ };
13446
+ const metadata = {
13447
+ id,
13448
+ label,
13449
+ category: String(
13450
+ raw.metadata?.category ?? source.category ?? raw.category ?? "title-card"
13451
+ ),
13452
+ description: String(
13453
+ raw.metadata?.description ?? source.description ?? raw.description ?? ""
13454
+ ),
13455
+ tags: Array.isArray(raw.metadata?.tags) ? clone2(raw.metadata.tags) : Array.isArray(raw.tags) ? raw.tags.map(String) : [],
13456
+ creatorName: raw.metadata?.creatorName ?? raw.creatorName,
13457
+ creatorLink: raw.metadata?.creatorLink ?? raw.creatorLink,
13458
+ thumbnailUrl: raw.previews?.thumbnailUrl ?? raw.thumbnail ?? raw.thumbnailUrl,
13459
+ previewVideoUrl: raw.previews?.previewVideoUrl ?? raw.preview ?? raw.previewVideoUrl
13460
+ };
13461
+ return {
13462
+ kind: TEXT_TEMPLATE_KIND,
13463
+ schemaVersion: TEXT_TEMPLATE_SCHEMA_VERSION,
13464
+ metadata,
13465
+ document: document2,
13466
+ controls,
13467
+ timing,
13468
+ dependencies,
13469
+ revision,
13470
+ previews: raw.previews || metadata.thumbnailUrl || metadata.previewVideoUrl ? {
13471
+ thumbnailUrl: metadata.thumbnailUrl,
13472
+ previewVideoUrl: metadata.previewVideoUrl
13473
+ } : void 0
13474
+ };
13475
+ }
13476
+
13477
+ // src/textTemplates/validator.ts
13478
+ var MAX_NODES = 500;
13479
+ var MAX_CONTROLS = 100;
13480
+ function validateTextTemplateArtifact(artifact) {
13481
+ const diagnostics = [];
13482
+ if (!artifact || artifact.kind !== "text-template") {
13483
+ return [{ severity: "error", code: "TEMPLATE_KIND", message: "Artifact kind must be text-template" }];
13484
+ }
13485
+ const { document: document2, timing, controls } = artifact;
13486
+ if (!document2 || !document2.id) {
13487
+ diagnostics.push({ severity: "error", code: "TEMPLATE_ID", message: "Template ID is required" });
13488
+ }
13489
+ if (!Number.isFinite(document2.canvas.width) || document2.canvas.width <= 0 || !Number.isFinite(document2.canvas.height) || document2.canvas.height <= 0) {
13490
+ diagnostics.push({ severity: "error", code: "CANVAS_SIZE", message: "Canvas dimensions must be positive finite numbers" });
13491
+ }
13492
+ if (!Number.isFinite(timing.duration) || timing.duration <= 0) {
13493
+ diagnostics.push({ severity: "error", code: "DURATION", message: "Duration must be positive" });
13494
+ }
13495
+ if (!Number.isFinite(timing.fps) || timing.fps <= 0 || timing.fps > 240) {
13496
+ diagnostics.push({ severity: "error", code: "FPS", message: "FPS must be between 0 and 240" });
13497
+ }
13498
+ const ids = /* @__PURE__ */ new Set();
13499
+ let nodeCount = 0;
13500
+ const visit = (node) => {
13501
+ nodeCount += 1;
13502
+ if (!node.id) {
13503
+ diagnostics.push({ severity: "error", code: "NODE_ID", message: "Every node needs a stable ID" });
13504
+ } else if (ids.has(node.id)) {
13505
+ diagnostics.push({ severity: "error", code: "DUPLICATE_NODE_ID", message: `Duplicate node ID: ${node.id}`, nodeId: node.id });
13506
+ } else {
13507
+ ids.add(node.id);
13508
+ }
13509
+ for (const value of [node.x, node.y]) {
13510
+ if (!Number.isFinite(value)) {
13511
+ diagnostics.push({ severity: "error", code: "NODE_GEOMETRY", message: `Node ${node.id} has non-finite position`, nodeId: node.id });
13512
+ }
13513
+ }
13514
+ for (const [axis, value] of [["width", node.width], ["height", node.height]]) {
13515
+ if (value === "auto") {
13516
+ if (node.type !== "text" && node.type !== "container") {
13517
+ diagnostics.push({
13518
+ severity: "error",
13519
+ code: "NODE_GEOMETRY_AUTO_NOT_SUPPORTED",
13520
+ message: `Node ${node.id} (${node.type}) does not support auto ${axis} \u2014 only text and container nodes can use content-driven sizing`,
13521
+ nodeId: node.id
13522
+ });
11724
13523
  }
11725
- },
11726
- {
11727
- kind: "text",
11728
- id: "timer-digits",
11729
- content: "5",
11730
- fontFamily: "Poppins",
11731
- fontSize: 120,
11732
- fontWeight: 700,
11733
- color: "#ffffff",
11734
- align: "center",
11735
- x: 810,
11736
- y: 440,
11737
- width: 300,
11738
- height: 200,
11739
- role: "primary",
11740
- animation: {
11741
- in: "fade",
11742
- out: "fade",
11743
- inDuration: 0.3,
11744
- outDuration: 0.3,
11745
- hold: "full"
13524
+ } else if (!Number.isFinite(value)) {
13525
+ diagnostics.push({ severity: "error", code: "NODE_GEOMETRY", message: `Node ${node.id} has non-finite geometry`, nodeId: node.id });
13526
+ }
13527
+ }
13528
+ if (node.type === "text" && !node.text) {
13529
+ diagnostics.push({ severity: "warning", code: "EMPTY_TEXT", message: `Text node ${node.id} is empty`, nodeId: node.id });
13530
+ }
13531
+ };
13532
+ (document2.nodes || []).forEach(visit);
13533
+ if (nodeCount > MAX_NODES) {
13534
+ diagnostics.push({ severity: "error", code: "NODE_LIMIT", message: `Template exceeds the ${MAX_NODES}-node limit` });
13535
+ }
13536
+ if ((controls || []).length > MAX_CONTROLS) {
13537
+ diagnostics.push({ severity: "error", code: "CONTROL_LIMIT", message: `Template exceeds the ${MAX_CONTROLS}-control limit` });
13538
+ }
13539
+ const controlIds = /* @__PURE__ */ new Set();
13540
+ for (const control of controls || []) {
13541
+ if (controlIds.has(control.id)) {
13542
+ diagnostics.push({ severity: "error", code: "DUPLICATE_CONTROL_ID", message: `Duplicate control ID: ${control.id}` });
13543
+ }
13544
+ controlIds.add(control.id);
13545
+ if (!ids.has(control.target.nodeId)) {
13546
+ diagnostics.push({ severity: "error", code: "CONTROL_TARGET", message: `Control ${control.id} targets missing node ${control.target.nodeId}` });
13547
+ }
13548
+ if (control.target.propertyPath.includes("__proto__") || control.target.propertyPath.includes("constructor") || control.target.propertyPath.includes("prototype")) {
13549
+ diagnostics.push({ severity: "error", code: "UNSAFE_TARGET", message: `Control ${control.id} has an unsafe target path` });
13550
+ }
13551
+ }
13552
+ const regions = [timing.intro, timing.outro, timing.loop].filter(Boolean);
13553
+ regions.forEach((region) => {
13554
+ if (!Number.isFinite(region.start) || !Number.isFinite(region.end) || region.start < 0 || region.end <= region.start || region.end > timing.duration) {
13555
+ diagnostics.push({ severity: "error", code: "TIMING_REGION", message: "Timing regions must fit within the template duration" });
13556
+ }
13557
+ });
13558
+ return diagnostics;
13559
+ }
13560
+ function assertValidTextTemplateArtifact(artifact) {
13561
+ const errors = validateTextTemplateArtifact(artifact).filter((diagnostic) => diagnostic.severity === "error");
13562
+ if (errors.length) {
13563
+ throw new Error(errors.map((diagnostic) => diagnostic.message).join("; "));
13564
+ }
13565
+ }
13566
+
13567
+ // src/textTemplates/compiler.ts
13568
+ function clone3(value) {
13569
+ return JSON.parse(JSON.stringify(value));
13570
+ }
13571
+ function findNode(nodes, id) {
13572
+ for (const node of nodes) {
13573
+ if (node.id === id) return node;
13574
+ }
13575
+ return void 0;
13576
+ }
13577
+ function setPath(target, path, value) {
13578
+ const parts = path.split(".").filter(Boolean);
13579
+ if (!parts.length || parts.some((part) => part === "__proto__" || part === "constructor" || part === "prototype")) {
13580
+ return;
13581
+ }
13582
+ let cursor = target;
13583
+ for (let index = 0; index < parts.length - 1; index += 1) {
13584
+ const part = parts[index];
13585
+ if (!cursor[part] || typeof cursor[part] !== "object") cursor[part] = {};
13586
+ cursor = cursor[part];
13587
+ }
13588
+ cursor[parts[parts.length - 1]] = value;
13589
+ }
13590
+ function finite(value, fallback) {
13591
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
13592
+ }
13593
+ function fallbackTextWidth(text, style) {
13594
+ const fontSize = Math.max(1, finite(style.fontSize, 48));
13595
+ const letterSpacing = finite(style.letterSpacing, 0);
13596
+ return Array.from(text).reduce((total) => total + fontSize * 0.55 + letterSpacing, 0);
13597
+ }
13598
+ function measureTextNode(node, runtime) {
13599
+ const style = node.style;
13600
+ const lines = String(node.text ?? "").split("\n");
13601
+ const measure = runtime?.measureText;
13602
+ const widths = lines.map((line) => {
13603
+ const measured = measure?.(line, style)?.width;
13604
+ return Number.isFinite(measured) ? Math.max(0, measured) : fallbackTextWidth(line, style);
13605
+ });
13606
+ const lineHeight = Math.max(1, finite(style.fontSize, 48) * finite(style.lineHeight, 1.2));
13607
+ return {
13608
+ width: Math.max(1, ...widths),
13609
+ height: Math.max(1, lines.length * lineHeight)
13610
+ };
13611
+ }
13612
+ function resolveNodeSize(node, runtime) {
13613
+ if (node.type === "text") {
13614
+ const measured = measureTextNode(node, runtime);
13615
+ return {
13616
+ width: node.width === "auto" ? measured.width : Math.max(1, finite(node.width, measured.width)),
13617
+ height: node.height === "auto" ? measured.height : Math.max(1, finite(node.height, measured.height))
13618
+ };
13619
+ }
13620
+ return {
13621
+ width: node.width === "auto" ? 0 : Math.max(1, finite(node.width, 1)),
13622
+ height: node.height === "auto" ? 0 : Math.max(1, finite(node.height, 1))
13623
+ };
13624
+ }
13625
+ function resolveControls(controls, values) {
13626
+ const resolved = {};
13627
+ for (const control of controls || []) {
13628
+ const value = values && Object.prototype.hasOwnProperty.call(values, control.id) ? values[control.id] : control.defaultValue;
13629
+ if (control.type === "number") {
13630
+ const numeric = Number(value);
13631
+ resolved[control.id] = Number.isFinite(numeric) ? Math.min(
13632
+ control.constraints?.max ?? numeric,
13633
+ Math.max(control.constraints?.min ?? numeric, numeric)
13634
+ ) : control.defaultValue;
13635
+ } else if (control.type === "boolean") {
13636
+ resolved[control.id] = value === true;
13637
+ } else {
13638
+ resolved[control.id] = value;
13639
+ }
13640
+ }
13641
+ return resolved;
13642
+ }
13643
+ function mapTime(time, artifact, clipDuration) {
13644
+ const duration = artifact.timing.duration;
13645
+ const targetDuration = clipDuration && clipDuration > 0 ? clipDuration : duration;
13646
+ const localTime = Math.max(0, Math.min(time, targetDuration));
13647
+ if (artifact.timing.durationPolicy === "stretch" && targetDuration !== duration) {
13648
+ const introEnd = artifact.timing.intro?.end ?? 0;
13649
+ const outroDuration = duration - (artifact.timing.outro?.start ?? duration);
13650
+ const outroStartInTarget = targetDuration - outroDuration;
13651
+ if (localTime <= introEnd) {
13652
+ return localTime;
13653
+ } else if (localTime >= outroStartInTarget) {
13654
+ const outroProgress = outroDuration > 0 ? (localTime - outroStartInTarget) / outroDuration : 1;
13655
+ return (artifact.timing.outro?.start ?? duration) + outroProgress * outroDuration;
13656
+ } else {
13657
+ const flexibleTarget = Math.max(1e-3, outroStartInTarget - introEnd);
13658
+ const flexibleAuthored = Math.max(0, (artifact.timing.outro?.start ?? duration) - introEnd);
13659
+ const progress = (localTime - introEnd) / flexibleTarget;
13660
+ return introEnd + progress * flexibleAuthored;
13661
+ }
13662
+ }
13663
+ if (artifact.timing.durationPolicy === "loop") {
13664
+ const loop = artifact.timing.loop;
13665
+ if (loop && loop.end > loop.start && localTime > loop.start) {
13666
+ return loop.start + (localTime - loop.start) % (loop.end - loop.start);
13667
+ }
13668
+ }
13669
+ return Math.max(0, Math.min(localTime, duration));
13670
+ }
13671
+ function easeBezier(t) {
13672
+ const clamped = Math.max(0, Math.min(1, t));
13673
+ return cubicBezier(0.4, 0, 0.2, 1)(clamped);
13674
+ }
13675
+ function applyAnimationPreset(preset, t, direction) {
13676
+ const ease2 = easeBezier(t);
13677
+ const clamped = Math.max(0, Math.min(1, t));
13678
+ const p = direction === "in" ? ease2 : 1 - ease2;
13679
+ let opacity = 1;
13680
+ let x = 0;
13681
+ let y = 0;
13682
+ let scale = 1;
13683
+ let blur = 0;
13684
+ let typewriterProgress = 1;
13685
+ switch (preset) {
13686
+ case "fade":
13687
+ opacity = p;
13688
+ break;
13689
+ case "typewriter":
13690
+ typewriterProgress = direction === "in" ? clamped : 1 - clamped;
13691
+ break;
13692
+ case "slide-up":
13693
+ opacity = p;
13694
+ y = (1 - p) * 40;
13695
+ break;
13696
+ case "slide-down":
13697
+ opacity = p;
13698
+ y = (p - 1) * 40;
13699
+ break;
13700
+ case "slide-left":
13701
+ opacity = p;
13702
+ x = (1 - p) * 40;
13703
+ break;
13704
+ case "slide-right":
13705
+ opacity = p;
13706
+ x = (p - 1) * 40;
13707
+ break;
13708
+ case "scale-in":
13709
+ opacity = p;
13710
+ scale = 0.8 + p * 0.2;
13711
+ break;
13712
+ case "scale-out":
13713
+ opacity = p;
13714
+ scale = 1.2 - (1 - p) * 0.2;
13715
+ break;
13716
+ case "blur-in":
13717
+ case "blur-out":
13718
+ opacity = p;
13719
+ blur = (1 - p) * 15;
13720
+ break;
13721
+ case "3d-flip":
13722
+ opacity = p;
13723
+ scale = 0.6 + p * 0.4;
13724
+ y = (1 - p) * 25;
13725
+ break;
13726
+ case "scale-pop":
13727
+ opacity = p;
13728
+ scale = p < 0.7 ? p / 0.7 * 1.15 : 1.15 - (p - 0.7) / 0.3 * 0.15;
13729
+ break;
13730
+ case "wave":
13731
+ opacity = p;
13732
+ y = Math.sin(p * Math.PI) * -15;
13733
+ break;
13734
+ case "track-in":
13735
+ opacity = p;
13736
+ blur = (1 - p) * 8;
13737
+ break;
13738
+ case "glitch":
13739
+ opacity = p > 0.05 ? 1 : 0;
13740
+ x = Math.sin(p * 25) * 6 * (1 - p);
13741
+ break;
13742
+ case "none":
13743
+ default:
13744
+ break;
13745
+ }
13746
+ return { opacity, x, y, scale, blur, typewriterProgress };
13747
+ }
13748
+ function computeNodeAnimationState(animation, time, duration) {
13749
+ if (!animation) return { opacity: 1, x: 0, y: 0, scale: 1, blur: 0, typewriterProgress: 1 };
13750
+ const inEnd = Number(animation.inDuration ?? 0);
13751
+ const outStart = duration - Number(animation.outDuration ?? 0);
13752
+ if (time < inEnd && inEnd > 0) {
13753
+ const t = time / inEnd;
13754
+ return applyAnimationPreset(animation.in || "fade", t, "in");
13755
+ } else if (time > outStart && Number(animation.outDuration ?? 0) > 0) {
13756
+ const t = (time - outStart) / Number(animation.outDuration ?? 0);
13757
+ return applyAnimationPreset(animation.out || "fade", t, "out");
13758
+ }
13759
+ return { opacity: 1, x: 0, y: 0, scale: 1, blur: 0, typewriterProgress: 1 };
13760
+ }
13761
+ function evaluateNodeProperty(node, property, fallback, time, duration) {
13762
+ const frames = node.animation?.propertyKeyframes?.[property];
13763
+ if (!frames?.keyframes?.length) return fallback;
13764
+ return evaluateAnimatable(frames, time, duration);
13765
+ }
13766
+ function compileTextTemplate(artifact, context) {
13767
+ assertValidTextTemplateArtifact(artifact);
13768
+ const resolvedControls = resolveControls(artifact.controls, context.controlValues);
13769
+ const document2 = clone3(artifact.document);
13770
+ for (const control of artifact.controls || []) {
13771
+ const node = findNode(document2.nodes, control.target.nodeId);
13772
+ if (node) setPath(node, control.target.propertyPath, resolvedControls[control.id]);
13773
+ }
13774
+ const time = mapTime(context.time, artifact, context.clipDuration);
13775
+ const flexPositions = /* @__PURE__ */ new Map();
13776
+ const containers = (document2.nodes || []).filter((n) => n.type === "container");
13777
+ for (const container of containers) {
13778
+ const children = (document2.nodes || []).filter((n) => n.parentId === container.id && n.visible !== false);
13779
+ const layout = container.layout || { type: "flex", direction: "column", gap: 0, alignItems: "start", justifyContent: "start" };
13780
+ const direction = layout.direction || "column";
13781
+ const gap = layout.gap || 0;
13782
+ const padTop = layout.paddingTop || 0;
13783
+ const padRight = layout.paddingRight || 0;
13784
+ const padBottom = layout.paddingBottom || 0;
13785
+ const padLeft = layout.paddingLeft || 0;
13786
+ const alignItems = layout.alignItems || "center";
13787
+ const containerX = container.x;
13788
+ const containerY = container.y;
13789
+ if (direction === "column") {
13790
+ let totalChildHeight = 0;
13791
+ let maxChildWidth = 0;
13792
+ const childSizes = [];
13793
+ for (const child of children) {
13794
+ const measured = resolveNodeSize(child, context.runtime);
13795
+ const cw = measured.width;
13796
+ const ch = measured.height;
13797
+ childSizes.push({ id: child.id, width: cw, height: ch });
13798
+ totalChildHeight += ch;
13799
+ maxChildWidth = Math.max(maxChildWidth, cw);
13800
+ }
13801
+ if (children.length > 1) {
13802
+ totalChildHeight += (children.length - 1) * gap;
13803
+ }
13804
+ const containerW = container.width === "auto" ? maxChildWidth + padLeft + padRight : Number(container.width);
13805
+ const containerH = container.height === "auto" ? totalChildHeight + padTop + padBottom : Number(container.height);
13806
+ flexPositions.set(container.id, { x: containerX, y: containerY, width: containerW, height: containerH });
13807
+ let currentY = containerY + padTop;
13808
+ const innerW = Math.max(0, containerW - padLeft - padRight);
13809
+ for (const child of childSizes) {
13810
+ let childX = containerX + padLeft;
13811
+ if (alignItems === "center") {
13812
+ childX = containerX + padLeft + (innerW - child.width) / 2;
13813
+ } else if (alignItems === "end") {
13814
+ childX = containerX + padLeft + (innerW - child.width);
13815
+ } else if (alignItems === "stretch") {
13816
+ child.width = innerW;
11746
13817
  }
13818
+ flexPositions.set(child.id, { x: childX, y: currentY, width: child.width, height: child.height });
13819
+ currentY += child.height + gap;
11747
13820
  }
11748
- ]
13821
+ } else {
13822
+ let totalChildWidth = 0;
13823
+ let maxChildHeight = 0;
13824
+ const childSizes = [];
13825
+ for (const child of children) {
13826
+ const measured = resolveNodeSize(child, context.runtime);
13827
+ const cw = measured.width;
13828
+ const ch = measured.height;
13829
+ childSizes.push({ id: child.id, width: cw, height: ch });
13830
+ totalChildWidth += cw;
13831
+ maxChildHeight = Math.max(maxChildHeight, ch);
13832
+ }
13833
+ if (children.length > 1) {
13834
+ totalChildWidth += (children.length - 1) * gap;
13835
+ }
13836
+ const containerW = container.width === "auto" ? totalChildWidth + padLeft + padRight : Number(container.width);
13837
+ const containerH = container.height === "auto" ? maxChildHeight + padTop + padBottom : Number(container.height);
13838
+ flexPositions.set(container.id, { x: containerX, y: containerY, width: containerW, height: containerH });
13839
+ let currentX = containerX + padLeft;
13840
+ const innerH = Math.max(0, containerH - padTop - padBottom);
13841
+ for (const child of childSizes) {
13842
+ let childY = containerY + padTop;
13843
+ if (alignItems === "center") {
13844
+ childY = containerY + padTop + (innerH - child.height) / 2;
13845
+ } else if (alignItems === "end") {
13846
+ childY = containerY + padTop + (innerH - child.height);
13847
+ } else if (alignItems === "stretch") {
13848
+ child.height = innerH;
13849
+ }
13850
+ flexPositions.set(child.id, { x: currentX, y: childY, width: child.width, height: child.height });
13851
+ currentX += child.width + gap;
13852
+ }
13853
+ }
13854
+ }
13855
+ const layers = (document2.nodes || []).map((node) => {
13856
+ const animState = computeNodeAnimationState(node.animation, time, artifact.timing.duration);
13857
+ const fullText = node.type === "text" ? node.text : void 0;
13858
+ const visibleText = fullText === void 0 ? void 0 : Array.from(fullText).slice(0, Math.floor(fullText.length * animState.typewriterProgress)).join("");
13859
+ const flexPos = flexPositions.get(node.id);
13860
+ const baseX = flexPos?.x ?? evaluateNodeProperty(node, "x", Number(node.x), time, artifact.timing.duration);
13861
+ const baseY = flexPos?.y ?? evaluateNodeProperty(node, "y", Number(node.y), time, artifact.timing.duration);
13862
+ const measuredSize = node.type === "text" ? measureTextNode(node, context.runtime) : void 0;
13863
+ const resolvedWidth = flexPos?.width ?? (node.width === "auto" ? measuredSize?.width ?? 1 : evaluateNodeProperty(node, "width", Number(node.width), time, artifact.timing.duration));
13864
+ const resolvedHeight = flexPos?.height ?? (node.height === "auto" ? measuredSize?.height ?? 1 : evaluateNodeProperty(node, "height", Number(node.height), time, artifact.timing.duration));
13865
+ const baseOpacity = node.type === "shape" ? node.style.fillOpacity ?? 1 : node.type === "media" ? node.style?.opacity ?? 1 : node.type === "container" ? node.style?.opacity ?? 1 : 1;
13866
+ return {
13867
+ id: node.id,
13868
+ type: node.type,
13869
+ parentId: node.parentId,
13870
+ x: baseX + animState.x,
13871
+ y: baseY + animState.y,
13872
+ width: resolvedWidth * animState.scale,
13873
+ height: resolvedHeight * animState.scale,
13874
+ rotation: 0,
13875
+ opacity: node.visible === false ? 0 : animState.opacity * baseOpacity,
13876
+ visible: node.visible !== false && animState.opacity > 0,
13877
+ text: visibleText,
13878
+ assetId: node.type === "media" ? node.assetId : void 0,
13879
+ mediaUrl: node.type === "media" ? node.src : void 0,
13880
+ style: node.style,
13881
+ content: node.type === "text" ? {
13882
+ text: node.text,
13883
+ backgroundPanel: node.backgroundPanel,
13884
+ splitAnimator: node.splitAnimator,
13885
+ typewriterProgress: animState.typewriterProgress,
13886
+ splitProgress: Number(node.animation?.inDuration ?? 0) > 0 ? Math.max(0, Math.min(1, time / Number(node.animation?.inDuration))) : 1
13887
+ } : void 0
13888
+ };
13889
+ });
13890
+ const capabilities2 = {
13891
+ studio: { status: "exact", unsupportedFeatures: [], warnings: [] },
13892
+ editor: { status: "exact", unsupportedFeatures: [], warnings: [] },
13893
+ export: { status: "exact", unsupportedFeatures: [], warnings: [] }
13894
+ };
13895
+ return {
13896
+ kind: "text-template",
13897
+ templateId: artifact.metadata.id,
13898
+ revisionId: artifact.revision.revisionId,
13899
+ contentHash: artifact.revision.contentHash || canonicalTemplateHash(artifact),
13900
+ width: artifact.document.canvas.width,
13901
+ height: artifact.document.canvas.height,
13902
+ duration: artifact.timing.duration,
13903
+ fps: artifact.timing.fps,
13904
+ time,
13905
+ evaluatedScene: { nodes: layers, diagnostics: [] },
13906
+ resolvedControls,
13907
+ layers,
13908
+ dependencies: artifact.dependencies,
13909
+ capabilities: capabilities2,
13910
+ diagnostics: []
13911
+ };
13912
+ }
13913
+
13914
+ // src/rendering/textEffectRenderer.ts
13915
+ function isScene(value) {
13916
+ return Boolean(value && typeof value === "object" && Array.isArray(value.effectLayers) && value.canvas);
13917
+ }
13918
+ function isConfig(value) {
13919
+ return Boolean(value && typeof value === "object" && typeof value.text === "string" && typeof value.fontFamily === "string");
13920
+ }
13921
+ function renderTextEffectToCanvas(ctx, input) {
13922
+ const source = input.source;
13923
+ const scene = isScene(source) ? source : isScene(source?.scene) ? source.scene : isConfig(source?.config) ? textEffectConfigToScene(source.config) : isConfig(source) ? textEffectConfigToScene(source) : null;
13924
+ if (!scene) {
13925
+ return {
13926
+ capability: "text-effect",
13927
+ rendererVersion: CANONICAL_RENDERER_VERSION,
13928
+ diagnostics: [{ level: "error", code: "effect-source-invalid", message: "Text effect source is not a scene or supported configuration.", capability: "text-effect" }],
13929
+ usedDependencies: []
13930
+ };
11749
13931
  }
11750
- ];
11751
- function getCanvasTemplatePreset(id) {
11752
- return BUILTIN_CANVAS_TEMPLATES.find((t) => t.id === id);
13932
+ if (isConfig(source)) evaluateConfig(source, input.context.time, ctx);
13933
+ else evaluateScene(scene, input.context.time, ctx);
13934
+ return {
13935
+ capability: "text-effect",
13936
+ revisionId: source?.revisionId,
13937
+ contentHash: source?.contentHash,
13938
+ rendererVersion: source?.rendererVersion ?? CANONICAL_RENDERER_VERSION,
13939
+ diagnostics: [],
13940
+ usedDependencies: []
13941
+ };
11753
13942
  }
11754
- function getCanvasTemplatesByCategory(category) {
11755
- return BUILTIN_CANVAS_TEMPLATES.filter((t) => t.category === category);
13943
+
13944
+ // src/rendering/textTemplateRenderer.ts
13945
+ function isObject(value) {
13946
+ return Boolean(value && typeof value === "object");
13947
+ }
13948
+ function isCanonicalArtifact(value) {
13949
+ return isObject(value) && value.kind === "text-template" && isObject(value.document) && Array.isArray(value.document.nodes);
13950
+ }
13951
+ function hasLegacyLayers(value) {
13952
+ return isObject(value) && (Array.isArray(value.layers) || Array.isArray(value.elements));
13953
+ }
13954
+ function resolveTextTemplateArtifact(input, options = {}) {
13955
+ if (!isObject(input)) return null;
13956
+ if (isCanonicalArtifact(input)) return normalizeTextTemplateArtifact(input);
13957
+ for (const key of ["templateData", "injectedData", "templateDefinition", "lottieData", "artifact", "snapshot"]) {
13958
+ const nested = input[key];
13959
+ if (nested && nested !== input) {
13960
+ const resolved = resolveTextTemplateArtifact(nested, options);
13961
+ if (resolved) return resolved;
13962
+ }
13963
+ }
13964
+ if (options.allowLegacy !== false && hasLegacyLayers(input)) return normalizeTextTemplateArtifact(input);
13965
+ return null;
13966
+ }
13967
+ function getTextTemplateControls(input) {
13968
+ return resolveTextTemplateArtifact(input)?.controls ?? [];
13969
+ }
13970
+ function finite2(value, fallback) {
13971
+ const number = Number(value);
13972
+ return Number.isFinite(number) ? number : fallback;
13973
+ }
13974
+ function cssColor(value, fallback) {
13975
+ return typeof value === "string" && value.trim() ? value : fallback;
13976
+ }
13977
+ function roundedRect(ctx, x, y, width, height, radius) {
13978
+ const r = Math.max(0, Math.min(radius, Math.min(Math.abs(width), Math.abs(height)) / 2));
13979
+ if (r <= 0) {
13980
+ ctx.rect(x, y, width, height);
13981
+ return;
13982
+ }
13983
+ ctx.moveTo(x + r, y);
13984
+ ctx.arcTo(x + width, y, x + width, y + height, r);
13985
+ ctx.arcTo(x + width, y + height, x, y + height, r);
13986
+ ctx.arcTo(x, y + height, x, y, r);
13987
+ ctx.arcTo(x, y, x + width, y, r);
13988
+ ctx.closePath();
13989
+ }
13990
+ function drawPanel(ctx, panel, x, y, width, height) {
13991
+ ctx.save();
13992
+ const left = finite2(panel.paddingLeft, 0);
13993
+ const right = finite2(panel.paddingRight, left);
13994
+ const top = finite2(panel.paddingTop, 0);
13995
+ const bottom = finite2(panel.paddingBottom, top);
13996
+ const px = x - left;
13997
+ const py = y - top;
13998
+ const pw = width + left + right;
13999
+ const ph = height + top + bottom;
14000
+ ctx.beginPath();
14001
+ roundedRect(ctx, px, py, pw, ph, finite2(panel.borderRadius, 0));
14002
+ ctx.fillStyle = cssColor(panel.color, "#000000");
14003
+ ctx.globalAlpha *= Math.max(0, Math.min(1, finite2(panel.opacity, 1)));
14004
+ ctx.fill();
14005
+ if (finite2(panel.borderWidth, 0) > 0 && panel.borderColor) {
14006
+ ctx.lineWidth = finite2(panel.borderWidth, 1);
14007
+ ctx.strokeStyle = cssColor(panel.borderColor, "#000000");
14008
+ ctx.stroke();
14009
+ }
14010
+ ctx.restore();
14011
+ }
14012
+ function letterSpacedText(ctx, text, x, y, maxWidth, letterSpacing) {
14013
+ if (!letterSpacing) {
14014
+ ctx.fillText(text, x, y, maxWidth);
14015
+ return;
14016
+ }
14017
+ const glyphs = Array.from(text);
14018
+ const widths = glyphs.map((glyph) => ctx.measureText(glyph).width);
14019
+ const total = widths.reduce((sum, value) => sum + value, 0) + Math.max(0, glyphs.length - 1) * letterSpacing;
14020
+ const align = ctx.textAlign;
14021
+ let cursor = x;
14022
+ if (align === "center") cursor -= total / 2;
14023
+ if (align === "right") cursor -= total;
14024
+ ctx.textAlign = "left";
14025
+ for (let index = 0; index < glyphs.length; index += 1) {
14026
+ ctx.fillText(glyphs[index], cursor, y);
14027
+ cursor += widths[index] + letterSpacing;
14028
+ }
14029
+ ctx.textAlign = align;
14030
+ }
14031
+ function drawTextLayer(ctx, layer2, style) {
14032
+ const text = layer2.text ?? "";
14033
+ const fontSize = finite2(style.fontSize, 48);
14034
+ const fontWeight = style.fontWeight ?? 400;
14035
+ const fontStyle = "normal";
14036
+ const fontFamily = String(style.fontFamily || "sans-serif").replace(/"/g, "");
14037
+ ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px "${fontFamily}"`;
14038
+ ctx.fillStyle = cssColor(style.textColor, "#FFFFFF");
14039
+ ctx.textAlign = style.textAlign ?? "left";
14040
+ ctx.textBaseline = style.verticalAlign === "top" ? "top" : style.verticalAlign === "bottom" ? "bottom" : "middle";
14041
+ const lineHeight = fontSize * finite2(style.lineHeight, 1.2);
14042
+ const maxWidth = Math.max(1, layer2.width);
14043
+ const lines = style.overflow === "wrap" ? wrapText(ctx, text, maxWidth) : [text];
14044
+ const blockHeight = lines.length * lineHeight;
14045
+ const startY = style.verticalAlign === "top" ? layer2.y : style.verticalAlign === "bottom" ? layer2.y + layer2.height - blockHeight + lineHeight : layer2.y + (layer2.height - blockHeight) / 2 + lineHeight / 2;
14046
+ const anchorX = style.textAlign === "center" ? layer2.x + layer2.width / 2 : style.textAlign === "right" ? layer2.x + layer2.width : layer2.x;
14047
+ for (let index = 0; index < lines.length; index += 1) {
14048
+ letterSpacedText(ctx, lines[index], anchorX, startY + index * lineHeight, maxWidth, finite2(style.letterSpacing, 0));
14049
+ }
14050
+ }
14051
+ function drawSplitTextLayer(ctx, layer2, style, animator, progress) {
14052
+ const text = layer2.text ?? "";
14053
+ const fontSize = finite2(style.fontSize, 48);
14054
+ const fontFamily = String(style.fontFamily || "sans-serif").replace(/"/g, "");
14055
+ ctx.font = `normal ${style.fontWeight ?? 400} ${fontSize}px "${fontFamily}"`;
14056
+ ctx.textBaseline = "middle";
14057
+ ctx.textAlign = "left";
14058
+ ctx.fillStyle = cssColor(style.textColor, "#FFFFFF");
14059
+ const units = splitTextContent(text, animator.splitBy);
14060
+ const transforms = evaluateSplitTextTransforms(units, animator, progress, "in");
14061
+ const lineHeight = fontSize * finite2(style.lineHeight, 1.2);
14062
+ const fullWidth = ctx.measureText(text.split("\n")[0] ?? "").width;
14063
+ let cursorX = style.textAlign === "center" ? layer2.x + (layer2.width - fullWidth) / 2 : style.textAlign === "right" ? layer2.x + layer2.width - fullWidth : layer2.x;
14064
+ let cursorY = layer2.y + layer2.height / 2;
14065
+ for (const item of transforms) {
14066
+ if (item.unit.text.includes("\n")) {
14067
+ cursorX = layer2.x;
14068
+ cursorY += lineHeight;
14069
+ continue;
14070
+ }
14071
+ const advance = ctx.measureText(item.unit.text).width;
14072
+ ctx.save();
14073
+ ctx.globalAlpha *= Math.max(0, Math.min(1, item.opacity));
14074
+ if (item.blur > 0) ctx.filter = `blur(${item.blur}px)`;
14075
+ ctx.translate(cursorX + item.x, cursorY + item.y);
14076
+ ctx.rotate(item.rotation * Math.PI / 180);
14077
+ ctx.scale(item.scaleX, item.scaleY);
14078
+ ctx.fillText(item.unit.text, 0, 0);
14079
+ ctx.restore();
14080
+ cursorX += advance + item.letterSpacingOffset;
14081
+ }
14082
+ }
14083
+ function wrapText(ctx, text, maxWidth) {
14084
+ const words = text.split(/\s+/);
14085
+ const lines = [];
14086
+ let line = "";
14087
+ for (const word of words) {
14088
+ const candidate = line ? `${line} ${word}` : word;
14089
+ if (line && ctx.measureText(candidate).width > maxWidth) {
14090
+ lines.push(line);
14091
+ line = word;
14092
+ } else {
14093
+ line = candidate;
14094
+ }
14095
+ }
14096
+ if (line || !lines.length) lines.push(line);
14097
+ return lines;
14098
+ }
14099
+ function drawLayer(ctx, layer2) {
14100
+ if (!layer2.visible || layer2.opacity <= 0) return;
14101
+ ctx.save();
14102
+ ctx.globalAlpha *= Math.max(0, Math.min(1, layer2.opacity));
14103
+ if (layer2.type === "shape") {
14104
+ const style = layer2.style ?? {};
14105
+ ctx.beginPath();
14106
+ roundedRect(ctx, layer2.x, layer2.y, layer2.width, layer2.height, finite2(style.borderRadius, 0));
14107
+ ctx.fillStyle = cssColor(style.fillColor, "#000000");
14108
+ ctx.globalAlpha *= Math.max(0, Math.min(1, finite2(style.fillOpacity, 1)));
14109
+ ctx.fill();
14110
+ if (finite2(style.strokeWidth, 0) > 0 && style.strokeColor) {
14111
+ ctx.lineWidth = finite2(style.strokeWidth, 1);
14112
+ ctx.strokeStyle = cssColor(style.strokeColor, "#000000");
14113
+ ctx.stroke();
14114
+ }
14115
+ } else if (layer2.type === "container") {
14116
+ const style = layer2.style ?? {};
14117
+ if (style.backgroundColor) {
14118
+ ctx.beginPath();
14119
+ roundedRect(ctx, layer2.x, layer2.y, layer2.width, layer2.height, finite2(style.borderRadius, 0));
14120
+ ctx.fillStyle = cssColor(style.backgroundColor, "#000000");
14121
+ ctx.globalAlpha *= Math.max(0, Math.min(1, finite2(style.backgroundOpacity, 1)));
14122
+ ctx.fill();
14123
+ }
14124
+ } else if (layer2.type === "text" || layer2.type === "rich-text") {
14125
+ const style = layer2.style ?? {};
14126
+ if (style && layer2.content?.backgroundPanel) {
14127
+ drawPanel(ctx, layer2.content.backgroundPanel, layer2.x, layer2.y, layer2.width, layer2.height);
14128
+ }
14129
+ const splitAnimator = layer2.content?.splitAnimator;
14130
+ if (splitAnimator) {
14131
+ drawSplitTextLayer(ctx, layer2, style, splitAnimator, finite2(layer2.content?.splitProgress, 1));
14132
+ } else {
14133
+ drawTextLayer(ctx, layer2, style);
14134
+ }
14135
+ }
14136
+ ctx.restore();
14137
+ }
14138
+ function renderTextTemplateToCanvas(ctx, input) {
14139
+ const artifact = input.artifact;
14140
+ const runtime = {
14141
+ ...input.context.runtime || {},
14142
+ // Measure with the exact Canvas context that will draw the layer. This
14143
+ // makes auto-sized nodes use loaded font metrics instead of a fixed box.
14144
+ measureText: (text, style) => {
14145
+ const family = String(style.fontFamily || "sans-serif").replace(/"/g, "");
14146
+ ctx.save();
14147
+ ctx.font = `${style.fontWeight ?? 400} ${finite2(style.fontSize, 48)}px "${family}"`;
14148
+ const width = ctx.measureText(text).width + Math.max(0, text.length - 1) * finite2(style.letterSpacing, 0);
14149
+ ctx.restore();
14150
+ return { width };
14151
+ }
14152
+ };
14153
+ const compiled = compileTextTemplate(artifact, {
14154
+ time: input.context.time,
14155
+ target: input.context.environment === "preview" || input.context.environment === "thumbnail" ? "editor" : input.context.environment,
14156
+ clipDuration: input.context.clipDuration,
14157
+ controlValues: input.context.controlValues,
14158
+ runtime
14159
+ });
14160
+ const outputWidth = finite2(input.context.width, compiled.width);
14161
+ const outputHeight = finite2(input.context.height, compiled.height);
14162
+ const scaleX = outputWidth / compiled.width;
14163
+ const scaleY = outputHeight / compiled.height;
14164
+ ctx.save();
14165
+ ctx.scale(scaleX, scaleY);
14166
+ if (artifact.document.canvas.backgroundColor) {
14167
+ ctx.fillStyle = artifact.document.canvas.backgroundColor;
14168
+ ctx.fillRect(0, 0, compiled.width, compiled.height);
14169
+ }
14170
+ for (const layer2 of compiled.layers) drawLayer(ctx, layer2);
14171
+ ctx.restore();
14172
+ return {
14173
+ capability: "text-template",
14174
+ revisionId: compiled.revisionId,
14175
+ contentHash: compiled.contentHash,
14176
+ rendererVersion: artifact.revision.rendererVersion || TEXT_TEMPLATE_RENDERER_VERSION,
14177
+ diagnostics: compiled.diagnostics.map((diagnostic) => ({ ...diagnostic, capability: "text-template" })),
14178
+ usedDependencies: [
14179
+ ...artifact.dependencies.fonts.map((font) => `font:${font.family}:${font.weight ?? "normal"}`),
14180
+ ...artifact.dependencies.assets.map((asset) => `asset:${asset.id}:${asset.contentHash}`),
14181
+ ...artifact.dependencies.textEffects.map((effect) => `text-effect:${effect.effectId}:${effect.revisionId}:${effect.contentHash}`)
14182
+ ],
14183
+ compiledTemplate: compiled
14184
+ };
14185
+ }
14186
+
14187
+ // src/rendering/index.ts
14188
+ function renderCanonicalToCanvas(ctx, input) {
14189
+ if (input.capability === "text-template") {
14190
+ const artifact = resolveTextTemplateArtifact(input.artifact);
14191
+ if (!artifact) {
14192
+ return {
14193
+ capability: "text-template",
14194
+ rendererVersion: TEXT_TEMPLATE_RENDERER_VERSION,
14195
+ diagnostics: [{ level: "error", code: "template-artifact-missing", message: "A full text-template artifact is required for rendering.", capability: "text-template" }],
14196
+ usedDependencies: []
14197
+ };
14198
+ }
14199
+ return renderTextTemplateToCanvas(ctx, { artifact, context: input.context });
14200
+ }
14201
+ return renderTextEffectToCanvas(ctx, { source: input.source, context: input.context });
11756
14202
  }
11757
14203
 
11758
14204
  // src/v2/project/types.ts
@@ -11786,7 +14232,7 @@ var ProjectHelper = class {
11786
14232
  };
11787
14233
 
11788
14234
  // src/v2/graph/types.ts
11789
- var import_types = require("@clypra-studio/types");
14235
+ var import_types2 = require("@clypra-studio/types");
11790
14236
 
11791
14237
  // src/v2/graph/NodeRegistry.ts
11792
14238
  var NodeRegistry = class _NodeRegistry {
@@ -12430,7 +14876,7 @@ var ProjectCompiler = class {
12430
14876
  */
12431
14877
  static compile(manifest, registry) {
12432
14878
  const nodeRegistry = registry || NodeRegistry.createDefault();
12433
- let graph = import_types.GraphHelper.create(`compiled-graph-${manifest.id}`);
14879
+ let graph = import_types2.GraphHelper.create(`compiled-graph-${manifest.id}`);
12434
14880
  let trackOutPins = [];
12435
14881
  for (const track of manifest.tracks) {
12436
14882
  if (!track.enabled) continue;
@@ -12461,7 +14907,7 @@ var ProjectCompiler = class {
12461
14907
  },
12462
14908
  lifecycle: "Created"
12463
14909
  };
12464
- graph = import_types.GraphHelper.withNode(graph, trackSourceNode);
14910
+ graph = import_types2.GraphHelper.withNode(graph, trackSourceNode);
12465
14911
  let activeNodeId = trackSourceId;
12466
14912
  let activePinId = "output";
12467
14913
  for (let i = 0; i < track.effectStack.length; i++) {
@@ -12487,8 +14933,8 @@ var ProjectCompiler = class {
12487
14933
  requirements,
12488
14934
  lifecycle: "Created"
12489
14935
  };
12490
- graph = import_types.GraphHelper.withNode(graph, effectNode);
12491
- graph = import_types.GraphHelper.withEdge(graph, activeNodeId, activePinId, effectNodeId, "input");
14936
+ graph = import_types2.GraphHelper.withNode(graph, effectNode);
14937
+ graph = import_types2.GraphHelper.withEdge(graph, activeNodeId, activePinId, effectNodeId, "input");
12492
14938
  activeNodeId = effectNodeId;
12493
14939
  activePinId = "output";
12494
14940
  }
@@ -12510,8 +14956,8 @@ var ProjectCompiler = class {
12510
14956
  requirements: { temporalRadius: 0, preferredPrecision: "fp16", multipass: false, supportsHalfResolution: true },
12511
14957
  lifecycle: "Created"
12512
14958
  };
12513
- graph = import_types.GraphHelper.withNode(graph, finalOut);
12514
- graph = import_types.GraphHelper.withEdge(graph, trackOutPins[0].nodeId, trackOutPins[0].pinId, "composite-output", "input");
14959
+ graph = import_types2.GraphHelper.withNode(graph, finalOut);
14960
+ graph = import_types2.GraphHelper.withEdge(graph, trackOutPins[0].nodeId, trackOutPins[0].pinId, "composite-output", "input");
12515
14961
  } else {
12516
14962
  let currentOutNode = trackOutPins[0].nodeId;
12517
14963
  let currentOutPin = trackOutPins[0].pinId;
@@ -12533,9 +14979,9 @@ var ProjectCompiler = class {
12533
14979
  requirements: { temporalRadius: 0, preferredPrecision: "fp16", multipass: false, supportsHalfResolution: true },
12534
14980
  lifecycle: "Created"
12535
14981
  };
12536
- graph = import_types.GraphHelper.withNode(graph, mixNode);
12537
- graph = import_types.GraphHelper.withEdge(graph, currentOutNode, currentOutPin, mixNodeId, "base");
12538
- graph = import_types.GraphHelper.withEdge(graph, trackOutPins[i].nodeId, trackOutPins[i].pinId, mixNodeId, "over");
14982
+ graph = import_types2.GraphHelper.withNode(graph, mixNode);
14983
+ graph = import_types2.GraphHelper.withEdge(graph, currentOutNode, currentOutPin, mixNodeId, "base");
14984
+ graph = import_types2.GraphHelper.withEdge(graph, trackOutPins[i].nodeId, trackOutPins[i].pinId, mixNodeId, "over");
12539
14985
  currentOutNode = mixNodeId;
12540
14986
  currentOutPin = "output";
12541
14987
  }
@@ -12552,15 +14998,15 @@ var ProjectCompiler = class {
12552
14998
  requirements: { temporalRadius: 0, preferredPrecision: "fp16", multipass: false, supportsHalfResolution: true },
12553
14999
  lifecycle: "Created"
12554
15000
  };
12555
- graph = import_types.GraphHelper.withNode(graph, finalOut);
12556
- graph = import_types.GraphHelper.withEdge(graph, currentOutNode, currentOutPin, "composite-output", "input");
15001
+ graph = import_types2.GraphHelper.withNode(graph, finalOut);
15002
+ graph = import_types2.GraphHelper.withEdge(graph, currentOutNode, currentOutPin, "composite-output", "input");
12557
15003
  }
12558
15004
  return graph;
12559
15005
  }
12560
15006
  };
12561
15007
 
12562
15008
  // src/v2/planner/FrameGraphBuilder.ts
12563
- var import_types3 = require("@clypra-studio/types");
15009
+ var import_types4 = require("@clypra-studio/types");
12564
15010
  var FrameGraphBuilder = class _FrameGraphBuilder {
12565
15011
  /**
12566
15012
  * Builds the FrameGraph for a specific timeline time point.
@@ -12597,7 +15043,7 @@ var FrameGraphBuilder = class _FrameGraphBuilder {
12597
15043
  }
12598
15044
  return false;
12599
15045
  }
12600
- const incomingEdges = import_types3.GraphHelper.getIncomingEdges(compiledGraph, nodeId);
15046
+ const incomingEdges = import_types4.GraphHelper.getIncomingEdges(compiledGraph, nodeId);
12601
15047
  let anyInputActive = incomingEdges.length === 0;
12602
15048
  const activeEdges = [];
12603
15049
  for (const edge of incomingEdges) {
@@ -15241,11 +17687,13 @@ var DataBindingEngine = class {
15241
17687
  }
15242
17688
  }
15243
17689
  if (direction === "horizontal") {
15244
- clonedNode.x = repeater.x + idx * (clonedNode.width + gap);
17690
+ const nodeW = typeof clonedNode.width === "number" ? clonedNode.width : 0;
17691
+ clonedNode.x = repeater.x + idx * (nodeW + gap);
15245
17692
  clonedNode.y = repeater.y;
15246
17693
  } else {
17694
+ const nodeH = typeof clonedNode.height === "number" ? clonedNode.height : 0;
15247
17695
  clonedNode.x = repeater.x;
15248
- clonedNode.y = repeater.y + idx * (clonedNode.height + gap);
17696
+ clonedNode.y = repeater.y + idx * (nodeH + gap);
15249
17697
  }
15250
17698
  if (clonedNode.animation?.entrance) {
15251
17699
  clonedNode.animation.entrance = {
@@ -16234,8 +18682,8 @@ var CommandExecutor = class {
16234
18682
  for (const n of targetNodes) {
16235
18683
  if (n.x < minX) minX = n.x;
16236
18684
  if (n.y < minY) minY = n.y;
16237
- if (n.x + n.width > maxX) maxX = n.x + n.width;
16238
- if (n.y + n.height > maxY) maxY = n.y + n.height;
18685
+ if (typeof n.width === "number" && n.x + n.width > maxX) maxX = n.x + n.width;
18686
+ if (typeof n.height === "number" && n.y + n.height > maxY) maxY = n.y + n.height;
16239
18687
  }
16240
18688
  const frameId = `frame-${Date.now().toString(36)}`;
16241
18689
  const frameNode = {
@@ -16691,17 +19139,19 @@ var DocumentValidator = class {
16691
19139
  });
16692
19140
  }
16693
19141
  }
16694
- const absX = node.x < 100 ? node.x / 100 * doc.canvas.width : node.x;
16695
- const absY = node.y < 100 ? node.y / 100 * doc.canvas.height : node.y;
16696
- const absW = node.width <= 100 ? node.width / 100 * doc.canvas.width : node.width;
16697
- const absH = node.height <= 100 ? node.height / 100 * doc.canvas.height : node.height;
16698
- if (absX + absW > doc.canvas.width || absY + absH > doc.canvas.height) {
16699
- diagnostics.push({
16700
- severity: "warning",
16701
- code: "WARN_OUT_OF_BOUNDS",
16702
- message: `Node "${node.name || node.id}" extends outside canvas bounds.`,
16703
- nodeId: node.id
16704
- });
19142
+ if (typeof node.width === "number" && typeof node.height === "number") {
19143
+ const absX = node.x < 100 ? node.x / 100 * doc.canvas.width : node.x;
19144
+ const absY = node.y < 100 ? node.y / 100 * doc.canvas.height : node.y;
19145
+ const absW = node.width <= 100 ? node.width / 100 * doc.canvas.width : node.width;
19146
+ const absH = node.height <= 100 ? node.height / 100 * doc.canvas.height : node.height;
19147
+ if (absX + absW > doc.canvas.width || absY + absH > doc.canvas.height) {
19148
+ diagnostics.push({
19149
+ severity: "warning",
19150
+ code: "WARN_OUT_OF_BOUNDS",
19151
+ message: `Node "${node.name || node.id}" extends outside canvas bounds.`,
19152
+ nodeId: node.id
19153
+ });
19154
+ }
16705
19155
  }
16706
19156
  if ("children" in node && Array.isArray(node.children)) {
16707
19157
  for (const child of node.children) {
@@ -16917,14 +19367,14 @@ var documentMigrator = new DocumentMigrator();
16917
19367
 
16918
19368
  // src/smartOverlays/migrations/serializeTemplate.ts
16919
19369
  function serializeTemplate(doc, meta) {
16920
- const now = (/* @__PURE__ */ new Date()).toISOString();
19370
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
16921
19371
  return {
16922
19372
  kind: "smart-overlay-template",
16923
19373
  schemaVersion: "1.0",
16924
19374
  metadata: {
16925
19375
  ...meta,
16926
- createdAt: now,
16927
- updatedAt: now
19376
+ createdAt: now2,
19377
+ updatedAt: now2
16928
19378
  },
16929
19379
  document: JSON.parse(JSON.stringify(doc))
16930
19380
  };
@@ -17023,43 +19473,45 @@ var SnapEngine = class {
17023
19473
  let snappedX = movingNode.x;
17024
19474
  let snappedY = movingNode.y;
17025
19475
  const guides = [];
19476
+ const movingW = typeof movingNode.width === "number" ? movingNode.width : 0;
19477
+ const movingH = typeof movingNode.height === "number" ? movingNode.height : 0;
17026
19478
  const nodeLeft = movingNode.x;
17027
- const nodeCenter = movingNode.x + movingNode.width / 2;
17028
- const nodeRight = movingNode.x + movingNode.width;
19479
+ const nodeCenter = movingNode.x + movingW / 2;
19480
+ const nodeRight = movingNode.x + movingW;
17029
19481
  const nodeTop = movingNode.y;
17030
- const nodeMiddle = movingNode.y + movingNode.height / 2;
17031
- const nodeBottom = movingNode.y + movingNode.height;
19482
+ const nodeMiddle = movingNode.y + movingH / 2;
19483
+ const nodeBottom = movingNode.y + movingH;
17032
19484
  const safeMarginX = Math.round(canvasWidth * 0.05);
17033
19485
  const safeMarginY = Math.round(canvasHeight * 0.05);
17034
19486
  const canvasCenterX = canvasWidth / 2;
17035
19487
  const canvasCenterY = canvasHeight / 2;
17036
19488
  if (Math.abs(nodeCenter - canvasCenterX) < threshold) {
17037
- snappedX = canvasCenterX - movingNode.width / 2;
19489
+ snappedX = canvasCenterX - movingW / 2;
17038
19490
  guides.push({ type: "vertical", position: canvasCenterX });
17039
19491
  }
17040
19492
  if (Math.abs(nodeMiddle - canvasCenterY) < threshold) {
17041
- snappedY = canvasCenterY - movingNode.height / 2;
19493
+ snappedY = canvasCenterY - movingH / 2;
17042
19494
  guides.push({ type: "horizontal", position: canvasCenterY });
17043
19495
  }
17044
19496
  if (Math.abs(nodeLeft - safeMarginX) < threshold) {
17045
19497
  snappedX = safeMarginX;
17046
19498
  guides.push({ type: "vertical", position: safeMarginX });
17047
19499
  } else if (Math.abs(nodeRight - (canvasWidth - safeMarginX)) < threshold) {
17048
- snappedX = canvasWidth - safeMarginX - movingNode.width;
19500
+ snappedX = canvasWidth - safeMarginX - movingW;
17049
19501
  guides.push({ type: "vertical", position: canvasWidth - safeMarginX });
17050
19502
  }
17051
19503
  if (Math.abs(nodeTop - safeMarginY) < threshold) {
17052
19504
  snappedY = safeMarginY;
17053
19505
  guides.push({ type: "horizontal", position: safeMarginY });
17054
19506
  } else if (Math.abs(nodeBottom - (canvasHeight - safeMarginY)) < threshold) {
17055
- snappedY = canvasHeight - safeMarginY - movingNode.height;
19507
+ snappedY = canvasHeight - safeMarginY - movingH;
17056
19508
  guides.push({ type: "horizontal", position: canvasHeight - safeMarginY });
17057
19509
  }
17058
19510
  for (const other of otherNodes) {
17059
19511
  const otherX = other.x;
17060
19512
  const otherY = other.y;
17061
- const otherW = other.width;
17062
- const otherH = other.height;
19513
+ const otherW = typeof other.width === "number" ? other.width : 0;
19514
+ const otherH = typeof other.height === "number" ? other.height : 0;
17063
19515
  const otherCenter = otherX + otherW / 2;
17064
19516
  const otherMiddle = otherY + otherH / 2;
17065
19517
  const minXDist = Math.min(
@@ -17079,29 +19531,31 @@ var SnapEngine = class {
17079
19531
  snappedX = otherX;
17080
19532
  guides.push({ type: "vertical", position: otherX });
17081
19533
  } else if (Math.abs(nodeCenter - otherCenter) < threshold) {
17082
- snappedX = otherCenter - movingNode.width / 2;
19534
+ snappedX = otherCenter - movingW / 2;
17083
19535
  guides.push({ type: "vertical", position: otherCenter });
17084
19536
  } else if (Math.abs(nodeRight - (otherX + otherW)) < threshold) {
17085
- snappedX = otherX + otherW - movingNode.width;
19537
+ snappedX = otherX + otherW - movingW;
17086
19538
  guides.push({ type: "vertical", position: otherX + otherW });
17087
19539
  }
17088
19540
  if (Math.abs(nodeTop - otherY) < threshold) {
17089
19541
  snappedY = otherY;
17090
19542
  guides.push({ type: "horizontal", position: otherY });
17091
19543
  } else if (Math.abs(nodeMiddle - otherMiddle) < threshold) {
17092
- snappedY = otherMiddle - movingNode.height / 2;
19544
+ snappedY = otherMiddle - movingH / 2;
17093
19545
  guides.push({ type: "horizontal", position: otherMiddle });
17094
19546
  } else if (Math.abs(nodeBottom - (otherY + otherH)) < threshold) {
17095
- snappedY = otherY + otherH - movingNode.height;
19547
+ snappedY = otherY + otherH - movingH;
17096
19548
  guides.push({ type: "horizontal", position: otherY + otherH });
17097
19549
  }
17098
19550
  }
17099
19551
  if (otherNodes.length >= 2) {
17100
19552
  const sortedX = [...otherNodes].sort((a, b) => a.x - b.x);
17101
19553
  for (let i = 0; i < sortedX.length - 1; i++) {
17102
- const gap = sortedX[i + 1].x - (sortedX[i].x + sortedX[i].width);
19554
+ const itemW = typeof sortedX[i].width === "number" ? sortedX[i].width : 0;
19555
+ const nextItemW = typeof sortedX[i + 1].width === "number" ? sortedX[i + 1].width : 0;
19556
+ const gap = sortedX[i + 1].x - (sortedX[i].x + itemW);
17103
19557
  if (gap > 0) {
17104
- const targetNextX = sortedX[i + 1].x + sortedX[i + 1].width + gap;
19558
+ const targetNextX = sortedX[i + 1].x + nextItemW + gap;
17105
19559
  if (Math.abs(nodeLeft - targetNextX) < threshold) {
17106
19560
  snappedX = targetNextX;
17107
19561
  guides.push({ type: "vertical", position: targetNextX });
@@ -17499,7 +19953,12 @@ var LayoutEngine = class {
17499
19953
  const anchor = node.anchor;
17500
19954
  if (anchor && anchor.targetId && result[anchor.targetId]) {
17501
19955
  const targetBounds = result[anchor.targetId];
17502
- const currentBounds = result[node.id] || { x: node.x, y: node.y, width: node.width, height: node.height };
19956
+ const currentBounds = result[node.id] || {
19957
+ x: node.x,
19958
+ y: node.y,
19959
+ width: typeof node.width === "number" ? node.width : 400,
19960
+ height: typeof node.height === "number" ? node.height : 120
19961
+ };
17503
19962
  let targetPointX = targetBounds.x + targetBounds.width / 2;
17504
19963
  let targetPointY = targetBounds.y + targetBounds.height / 2;
17505
19964
  const targetSide = anchor.targetSide || "right";
@@ -17538,10 +19997,12 @@ var LayoutEngine = class {
17538
19997
  const startTarget = lineNode.startNodeId ? result[lineNode.startNodeId] : void 0;
17539
19998
  const endTarget = lineNode.endNodeId ? result[lineNode.endNodeId] : void 0;
17540
19999
  if (startTarget || endTarget || lineNode.startX !== void 0 || lineNode.endX !== void 0) {
20000
+ const fallbackEndW = typeof node.width === "number" ? node.width : 0;
20001
+ const fallbackEndH = typeof node.height === "number" ? node.height : 0;
17541
20002
  const startX = startTarget ? startTarget.x + startTarget.width / 2 : lineNode.startX ?? node.x;
17542
20003
  const startY = startTarget ? startTarget.y + startTarget.height / 2 : lineNode.startY ?? node.y;
17543
- const endX = endTarget ? endTarget.x + endTarget.width / 2 : lineNode.endX ?? node.x + node.width;
17544
- const endY = endTarget ? endTarget.y + endTarget.height / 2 : lineNode.endY ?? node.y + node.height;
20004
+ const endX = endTarget ? endTarget.x + endTarget.width / 2 : lineNode.endX ?? node.x + fallbackEndW;
20005
+ const endY = endTarget ? endTarget.y + endTarget.height / 2 : lineNode.endY ?? node.y + fallbackEndH;
17545
20006
  const minX = Math.min(startX, endX);
17546
20007
  const minY = Math.min(startY, endY);
17547
20008
  const lineW = Math.max(1, Math.abs(endX - startX));
@@ -17561,7 +20022,9 @@ var LayoutEngine = class {
17561
20022
  const fromTarget = conn.fromNodeId ? result[conn.fromNodeId] : void 0;
17562
20023
  const toTarget = conn.toNodeId ? result[conn.toNodeId] : void 0;
17563
20024
  const fromPt = fromTarget ? this.resolveAnchorPoint(fromTarget, conn.fromAnchor || conn.fromElement) : { x: node.x, y: node.y };
17564
- const toPt = toTarget ? this.resolveAnchorPoint(toTarget, conn.toAnchor || conn.toElement) : { x: node.x + (node.width || 100), y: node.y + (node.height || 100) };
20025
+ const fallbackConnW = typeof node.width === "number" ? node.width : 100;
20026
+ const fallbackConnH = typeof node.height === "number" ? node.height : 100;
20027
+ const toPt = toTarget ? this.resolveAnchorPoint(toTarget, conn.toAnchor || conn.toElement) : { x: node.x + fallbackConnW, y: node.y + fallbackConnH };
17565
20028
  const minX = Math.min(fromPt.x, toPt.x);
17566
20029
  const minY = Math.min(fromPt.y, toPt.y);
17567
20030
  const connW = Math.max(1, Math.abs(toPt.x - fromPt.x));
@@ -17614,8 +20077,22 @@ var LayoutEngine = class {
17614
20077
  computeNodeGeometry(node, doc, context, result, parentX = 0, parentY = 0, isAbsoluteSlot = false) {
17615
20078
  let absX = isAbsoluteSlot ? parentX : parentX + node.x;
17616
20079
  let absY = isAbsoluteSlot ? parentY : parentY + node.y;
17617
- let width = node.width;
17618
- let height = node.height;
20080
+ let width;
20081
+ let height;
20082
+ if (node.type === "text") {
20083
+ const fontSize = node.style?.fontSize ?? 48;
20084
+ const fontWeight = node.style?.fontWeight ?? "normal";
20085
+ const fontFamily = node.style?.fontFamily ?? "Inter, sans-serif";
20086
+ const textContent = node.text ?? "Text";
20087
+ const measuredW = measureTextWidth(textContent, fontSize, fontWeight, fontFamily);
20088
+ width = typeof node.width === "number" && node.width > 0 ? node.width : measuredW;
20089
+ const lineHeight = node.style?.lineHeight ?? 1.2;
20090
+ const measuredH = Math.ceil(fontSize * lineHeight);
20091
+ height = typeof node.height === "number" && node.height > 0 ? node.height : measuredH;
20092
+ } else {
20093
+ width = typeof node.width === "number" ? node.width : 400;
20094
+ height = typeof node.height === "number" ? node.height : 120;
20095
+ }
17619
20096
  if (node.type === "line" || node.shapeKind === "line") {
17620
20097
  const strokeW = node.style?.strokeWidth ?? node.strokeWidth;
17621
20098
  if (typeof strokeW === "number" && strokeW > 0) {
@@ -17648,7 +20125,8 @@ var LayoutEngine = class {
17648
20125
  const scaleX = containerW / (doc.canvas.width || 1280);
17649
20126
  absX = Math.round(parentX + node.x * scaleX);
17650
20127
  if (node.layout?.constraints?.widthMode !== "fixed") {
17651
- width = Math.round(node.width * scaleX);
20128
+ const baseW = typeof node.width === "number" ? node.width : width;
20129
+ width = Math.round(baseW * scaleX);
17652
20130
  }
17653
20131
  }
17654
20132
  if (verticalPin === "center") {
@@ -17659,7 +20137,8 @@ var LayoutEngine = class {
17659
20137
  const scaleY = containerH / (doc.canvas.height || 720);
17660
20138
  absY = Math.round(parentY + node.y * scaleY);
17661
20139
  if (node.layout?.constraints?.heightMode !== "fixed") {
17662
- height = Math.round(node.height * scaleY);
20140
+ const baseH = typeof node.height === "number" ? node.height : height;
20141
+ height = Math.round(baseH * scaleY);
17663
20142
  }
17664
20143
  }
17665
20144
  }
@@ -17832,7 +20311,7 @@ var LayoutEngine = class {
17832
20311
  }
17833
20312
  }
17834
20313
  if (effectiveHeightMode === "hug") {
17835
- height = activeChildren.length > 0 ? hugHeight : node.height || 240;
20314
+ height = activeChildren.length > 0 ? hugHeight : typeof node.height === "number" ? node.height : 240;
17836
20315
  } else if (effectiveHeightMode !== "fill") {
17837
20316
  if (activeChildren.length > 0 && hugHeight > height) {
17838
20317
  height = hugHeight;
@@ -17929,14 +20408,14 @@ var LayoutEngine = class {
17929
20408
  const hugWidth = maxChildW + normPadding.left + normPadding.right;
17930
20409
  const hugHeight = totalContentH + normPadding.top + normPadding.bottom;
17931
20410
  if (effectiveWidthMode === "hug") {
17932
- width = activeColChildren.length > 0 ? hugWidth : node.width || 320;
20411
+ width = activeColChildren.length > 0 ? hugWidth : typeof node.width === "number" ? node.width : 320;
17933
20412
  } else if (effectiveWidthMode !== "fill") {
17934
20413
  if (activeColChildren.length > 0 && hugWidth > width) {
17935
20414
  width = hugWidth;
17936
20415
  }
17937
20416
  }
17938
20417
  if (effectiveHeightMode === "hug") {
17939
- height = activeColChildren.length > 0 ? hugHeight : node.height || 240;
20418
+ height = activeColChildren.length > 0 ? hugHeight : typeof node.height === "number" ? node.height : 240;
17940
20419
  } else if (effectiveHeightMode !== "fill") {
17941
20420
  if (activeColChildren.length > 0 && hugHeight > height) {
17942
20421
  height = hugHeight;
@@ -18261,7 +20740,9 @@ var SelectionEngine = class {
18261
20740
  for (let i = container.children.length - 1; i >= 0; i--) {
18262
20741
  const child = container.children[i];
18263
20742
  if (child.locked) continue;
18264
- if (clickPoint.x >= child.x && clickPoint.x <= child.x + child.width && clickPoint.y >= child.y && clickPoint.y <= child.y + child.height) {
20743
+ const childW = typeof child.width === "number" ? child.width : 0;
20744
+ const childH = typeof child.height === "number" ? child.height : 0;
20745
+ if (clickPoint.x >= child.x && clickPoint.x <= child.x + childW && clickPoint.y >= child.y && clickPoint.y <= child.y + childH) {
18265
20746
  this.select(child.id, doc);
18266
20747
  return true;
18267
20748
  }
@@ -18393,56 +20874,58 @@ var TransformEngine = class {
18393
20874
  */
18394
20875
  static resizeNode(node, handle, dx, dy, options = {}) {
18395
20876
  const { lockAspectRatio = false, minWidth = 10, minHeight = 10 } = options;
20877
+ const initialW = typeof node.width === "number" ? node.width : 200;
20878
+ const initialH = typeof node.height === "number" ? node.height : 50;
18396
20879
  let newX = node.x;
18397
20880
  let newY = node.y;
18398
- let newWidth = node.width;
18399
- let newHeight = node.height;
18400
- const initialAspect = node.width > 0 && node.height > 0 ? node.width / node.height : 1;
20881
+ let newWidth = initialW;
20882
+ let newHeight = initialH;
20883
+ const initialAspect = initialW > 0 && initialH > 0 ? initialW / initialH : 1;
18401
20884
  switch (handle) {
18402
20885
  case "e":
18403
- newWidth = Math.max(minWidth, node.width + dx);
20886
+ newWidth = Math.max(minWidth, initialW + dx);
18404
20887
  if (lockAspectRatio) newHeight = Math.max(minHeight, newWidth / initialAspect);
18405
20888
  break;
18406
20889
  case "w": {
18407
- const potentialW = node.width - dx;
20890
+ const potentialW = initialW - dx;
18408
20891
  if (potentialW >= minWidth) {
18409
20892
  newWidth = potentialW;
18410
20893
  newX = node.x + dx;
18411
20894
  } else {
18412
20895
  newWidth = minWidth;
18413
- newX = node.x + (node.width - minWidth);
20896
+ newX = node.x + (initialW - minWidth);
18414
20897
  }
18415
20898
  if (lockAspectRatio) newHeight = Math.max(minHeight, newWidth / initialAspect);
18416
20899
  break;
18417
20900
  }
18418
20901
  case "s":
18419
- newHeight = Math.max(minHeight, node.height + dy);
20902
+ newHeight = Math.max(minHeight, initialH + dy);
18420
20903
  if (lockAspectRatio) newWidth = Math.max(minWidth, newHeight * initialAspect);
18421
20904
  break;
18422
20905
  case "n": {
18423
- const potentialH = node.height - dy;
20906
+ const potentialH = initialH - dy;
18424
20907
  if (potentialH >= minHeight) {
18425
20908
  newHeight = potentialH;
18426
20909
  newY = node.y + dy;
18427
20910
  } else {
18428
20911
  newHeight = minHeight;
18429
- newY = node.y + (node.height - minHeight);
20912
+ newY = node.y + (initialH - minHeight);
18430
20913
  }
18431
20914
  if (lockAspectRatio) newWidth = Math.max(minWidth, newHeight * initialAspect);
18432
20915
  break;
18433
20916
  }
18434
20917
  case "se":
18435
- newWidth = Math.max(minWidth, node.width + dx);
18436
- newHeight = Math.max(minHeight, node.height + dy);
20918
+ newWidth = Math.max(minWidth, initialW + dx);
20919
+ newHeight = Math.max(minHeight, initialH + dy);
18437
20920
  if (lockAspectRatio) {
18438
- const scale = Math.max(newWidth / node.width, newHeight / node.height);
18439
- newWidth = Math.max(minWidth, node.width * scale);
18440
- newHeight = Math.max(minHeight, node.height * scale);
20921
+ const scale = Math.max(newWidth / initialW, newHeight / initialH);
20922
+ newWidth = Math.max(minWidth, initialW * scale);
20923
+ newHeight = Math.max(minHeight, initialH * scale);
18441
20924
  }
18442
20925
  break;
18443
20926
  case "nw": {
18444
- const potW = node.width - dx;
18445
- const potH = node.height - dy;
20927
+ const potW = initialW - dx;
20928
+ const potH = initialH - dy;
18446
20929
  if (potW >= minWidth) {
18447
20930
  newWidth = potW;
18448
20931
  newX = node.x + dx;
@@ -18452,15 +20935,15 @@ var TransformEngine = class {
18452
20935
  newY = node.y + dy;
18453
20936
  }
18454
20937
  if (lockAspectRatio) {
18455
- const scale = Math.max(newWidth / node.width, newHeight / node.height);
18456
- newWidth = Math.max(minWidth, node.width * scale);
18457
- newHeight = Math.max(minHeight, node.height * scale);
20938
+ const scale = Math.max(newWidth / initialW, newHeight / initialH);
20939
+ newWidth = Math.max(minWidth, initialW * scale);
20940
+ newHeight = Math.max(minHeight, initialH * scale);
18458
20941
  }
18459
20942
  break;
18460
20943
  }
18461
20944
  case "ne": {
18462
- newWidth = Math.max(minWidth, node.width + dx);
18463
- const potH = node.height - dy;
20945
+ newWidth = Math.max(minWidth, initialW + dx);
20946
+ const potH = initialH - dy;
18464
20947
  if (potH >= minHeight) {
18465
20948
  newHeight = potH;
18466
20949
  newY = node.y + dy;
@@ -18471,12 +20954,12 @@ var TransformEngine = class {
18471
20954
  break;
18472
20955
  }
18473
20956
  case "sw": {
18474
- const potW = node.width - dx;
20957
+ const potW = initialW - dx;
18475
20958
  if (potW >= minWidth) {
18476
20959
  newWidth = potW;
18477
20960
  newX = node.x + dx;
18478
20961
  }
18479
- newHeight = Math.max(minHeight, node.height + dy);
20962
+ newHeight = Math.max(minHeight, initialH + dy);
18480
20963
  if (lockAspectRatio) {
18481
20964
  newWidth = Math.max(minWidth, newHeight * initialAspect);
18482
20965
  }
@@ -18520,9 +21003,9 @@ var TransformEngine = class {
18520
21003
  }
18521
21004
  } else {
18522
21005
  const minX = Math.min(...nodes.map((n) => n.x));
18523
- const maxX = Math.max(...nodes.map((n) => n.x + n.width));
21006
+ const maxX = Math.max(...nodes.map((n) => n.x + (typeof n.width === "number" ? n.width : 0)));
18524
21007
  const minY = Math.min(...nodes.map((n) => n.y));
18525
- const maxY = Math.max(...nodes.map((n) => n.y + n.height));
21008
+ const maxY = Math.max(...nodes.map((n) => n.y + (typeof n.height === "number" ? n.height : 0)));
18526
21009
  switch (alignment) {
18527
21010
  case "left":
18528
21011
  targetCoord = minX;
@@ -18547,24 +21030,26 @@ var TransformEngine = class {
18547
21030
  return nodes.map((node) => {
18548
21031
  let updatedX = node.x;
18549
21032
  let updatedY = node.y;
21033
+ const nW = typeof node.width === "number" ? node.width : 0;
21034
+ const nH = typeof node.height === "number" ? node.height : 0;
18550
21035
  switch (alignment) {
18551
21036
  case "left":
18552
21037
  updatedX = targetCoord;
18553
21038
  break;
18554
21039
  case "center":
18555
- updatedX = Math.round(targetCoord - node.width / 2);
21040
+ updatedX = Math.round(targetCoord - nW / 2);
18556
21041
  break;
18557
21042
  case "right":
18558
- updatedX = Math.round(targetCoord - node.width);
21043
+ updatedX = Math.round(targetCoord - nW);
18559
21044
  break;
18560
21045
  case "top":
18561
21046
  updatedY = targetCoord;
18562
21047
  break;
18563
21048
  case "middle":
18564
- updatedY = Math.round(targetCoord - node.height / 2);
21049
+ updatedY = Math.round(targetCoord - nH / 2);
18565
21050
  break;
18566
21051
  case "bottom":
18567
- updatedY = Math.round(targetCoord - node.height);
21052
+ updatedY = Math.round(targetCoord - nH);
18568
21053
  break;
18569
21054
  }
18570
21055
  return { ...node, x: updatedX, y: updatedY };
@@ -18579,33 +21064,37 @@ var TransformEngine = class {
18579
21064
  const first = sorted[0];
18580
21065
  const last = sorted[sorted.length - 1];
18581
21066
  if (axis === "horizontal") {
18582
- const totalSpan = last.x + last.width - first.x;
18583
- const totalNodeWidths = sorted.reduce((sum, n) => sum + n.width, 0);
21067
+ const lastW = typeof last.width === "number" ? last.width : 0;
21068
+ const totalSpan = last.x + lastW - first.x;
21069
+ const totalNodeWidths = sorted.reduce((sum, n) => sum + (typeof n.width === "number" ? n.width : 0), 0);
18584
21070
  const totalGapSpace = totalSpan - totalNodeWidths;
18585
21071
  const gap = totalGapSpace / (sorted.length - 1);
18586
21072
  let currentX = first.x;
18587
21073
  return sorted.map((node, i) => {
21074
+ const nW = typeof node.width === "number" ? node.width : 0;
18588
21075
  if (i === 0) {
18589
- currentX += node.width + gap;
21076
+ currentX += nW + gap;
18590
21077
  return node;
18591
21078
  }
18592
21079
  const updated = { ...node, x: Math.round(currentX) };
18593
- currentX += node.width + gap;
21080
+ currentX += nW + gap;
18594
21081
  return updated;
18595
21082
  });
18596
21083
  } else {
18597
- const totalSpan = last.y + last.height - first.y;
18598
- const totalNodeHeights = sorted.reduce((sum, n) => sum + n.height, 0);
21084
+ const lastH = typeof last.height === "number" ? last.height : 0;
21085
+ const totalSpan = last.y + lastH - first.y;
21086
+ const totalNodeHeights = sorted.reduce((sum, n) => sum + (typeof n.height === "number" ? n.height : 0), 0);
18599
21087
  const totalGapSpace = totalSpan - totalNodeHeights;
18600
21088
  const gap = totalGapSpace / (sorted.length - 1);
18601
21089
  let currentY = first.y;
18602
21090
  return sorted.map((node, i) => {
21091
+ const nH = typeof node.height === "number" ? node.height : 0;
18603
21092
  if (i === 0) {
18604
- currentY += node.height + gap;
21093
+ currentY += nH + gap;
18605
21094
  return node;
18606
21095
  }
18607
21096
  const updated = { ...node, y: Math.round(currentY) };
18608
- currentY += node.height + gap;
21097
+ currentY += nH + gap;
18609
21098
  return updated;
18610
21099
  });
18611
21100
  }
@@ -19086,21 +21575,23 @@ var SmartGuideEngine = class {
19086
21575
  let snappedX = false;
19087
21576
  let snappedY = false;
19088
21577
  const guides = [];
21578
+ const movingW = typeof moving.width === "number" ? moving.width : 0;
21579
+ const movingH = typeof moving.height === "number" ? moving.height : 0;
19089
21580
  const left = moving.x;
19090
- const centerX = moving.x + moving.width / 2;
19091
- const right = moving.x + moving.width;
21581
+ const centerX = moving.x + movingW / 2;
21582
+ const right = moving.x + movingW;
19092
21583
  const top = moving.y;
19093
- const centerY = moving.y + moving.height / 2;
19094
- const bottom = moving.y + moving.height;
21584
+ const centerY = moving.y + movingH / 2;
21585
+ const bottom = moving.y + movingH;
19095
21586
  const canvasCenterX = canvasWidth / 2;
19096
21587
  const canvasCenterY = canvasHeight / 2;
19097
21588
  if (Math.abs(centerX - canvasCenterX) <= threshold) {
19098
- finalX = Math.round(canvasCenterX - moving.width / 2);
21589
+ finalX = Math.round(canvasCenterX - movingW / 2);
19099
21590
  snappedX = true;
19100
21591
  guides.push({ type: "vertical", position: canvasCenterX, label: "Canvas Center X" });
19101
21592
  }
19102
21593
  if (Math.abs(centerY - canvasCenterY) <= threshold) {
19103
- finalY = Math.round(canvasCenterY - moving.height / 2);
21594
+ finalY = Math.round(canvasCenterY - movingH / 2);
19104
21595
  snappedY = true;
19105
21596
  guides.push({ type: "horizontal", position: canvasCenterY, label: "Canvas Center Y" });
19106
21597
  }
@@ -19112,7 +21603,7 @@ var SmartGuideEngine = class {
19112
21603
  snappedX = true;
19113
21604
  guides.push({ type: "vertical", position: safeMarginX, label: "Safe Margin Left" });
19114
21605
  } else if (Math.abs(right - (canvasWidth - safeMarginX)) <= threshold) {
19115
- finalX = canvasWidth - safeMarginX - moving.width;
21606
+ finalX = canvasWidth - safeMarginX - movingW;
19116
21607
  snappedX = true;
19117
21608
  guides.push({ type: "vertical", position: canvasWidth - safeMarginX, label: "Safe Margin Right" });
19118
21609
  }
@@ -19123,29 +21614,31 @@ var SmartGuideEngine = class {
19123
21614
  snappedY = true;
19124
21615
  guides.push({ type: "horizontal", position: safeMarginY, label: "Safe Margin Top" });
19125
21616
  } else if (Math.abs(bottom - (canvasHeight - safeMarginY)) <= threshold) {
19126
- finalY = canvasHeight - safeMarginY - moving.height;
21617
+ finalY = canvasHeight - safeMarginY - movingH;
19127
21618
  snappedY = true;
19128
21619
  guides.push({ type: "horizontal", position: canvasHeight - safeMarginY, label: "Safe Margin Bottom" });
19129
21620
  }
19130
21621
  }
19131
21622
  for (const other of otherNodes) {
21623
+ const otherW = typeof other.width === "number" ? other.width : 0;
21624
+ const otherH = typeof other.height === "number" ? other.height : 0;
19132
21625
  const oLeft = other.x;
19133
- const oCenterX = other.x + other.width / 2;
19134
- const oRight = other.x + other.width;
21626
+ const oCenterX = other.x + otherW / 2;
21627
+ const oRight = other.x + otherW;
19135
21628
  const oTop = other.y;
19136
- const oCenterY = other.y + other.height / 2;
19137
- const oBottom = other.y + other.height;
21629
+ const oCenterY = other.y + otherH / 2;
21630
+ const oBottom = other.y + otherH;
19138
21631
  if (!snappedX) {
19139
21632
  if (Math.abs(left - oLeft) <= threshold) {
19140
21633
  finalX = oLeft;
19141
21634
  snappedX = true;
19142
21635
  guides.push({ type: "vertical", position: oLeft, label: "Align Left" });
19143
21636
  } else if (Math.abs(centerX - oCenterX) <= threshold) {
19144
- finalX = Math.round(oCenterX - moving.width / 2);
21637
+ finalX = Math.round(oCenterX - movingW / 2);
19145
21638
  snappedX = true;
19146
21639
  guides.push({ type: "vertical", position: oCenterX, label: "Align Center X" });
19147
21640
  } else if (Math.abs(right - oRight) <= threshold) {
19148
- finalX = Math.round(oRight - moving.width);
21641
+ finalX = Math.round(oRight - movingW);
19149
21642
  snappedX = true;
19150
21643
  guides.push({ type: "vertical", position: oRight, label: "Align Right" });
19151
21644
  } else if (Math.abs(left - oRight) <= threshold) {
@@ -19153,7 +21646,7 @@ var SmartGuideEngine = class {
19153
21646
  snappedX = true;
19154
21647
  guides.push({ type: "vertical", position: oRight, label: "Edge Flush Right" });
19155
21648
  } else if (Math.abs(right - oLeft) <= threshold) {
19156
- finalX = Math.round(oLeft - moving.width);
21649
+ finalX = Math.round(oLeft - movingW);
19157
21650
  snappedX = true;
19158
21651
  guides.push({ type: "vertical", position: oLeft, label: "Edge Flush Left" });
19159
21652
  }
@@ -19164,11 +21657,11 @@ var SmartGuideEngine = class {
19164
21657
  snappedY = true;
19165
21658
  guides.push({ type: "horizontal", position: oTop, label: "Align Top" });
19166
21659
  } else if (Math.abs(centerY - oCenterY) <= threshold) {
19167
- finalY = Math.round(oCenterY - moving.height / 2);
21660
+ finalY = Math.round(oCenterY - movingH / 2);
19168
21661
  snappedY = true;
19169
21662
  guides.push({ type: "horizontal", position: oCenterY, label: "Align Center Y" });
19170
21663
  } else if (Math.abs(bottom - oBottom) <= threshold) {
19171
- finalY = Math.round(oBottom - moving.height);
21664
+ finalY = Math.round(oBottom - movingH);
19172
21665
  snappedY = true;
19173
21666
  guides.push({ type: "horizontal", position: oBottom, label: "Align Bottom" });
19174
21667
  } else if (Math.abs(top - oBottom) <= threshold) {
@@ -19176,7 +21669,7 @@ var SmartGuideEngine = class {
19176
21669
  snappedY = true;
19177
21670
  guides.push({ type: "horizontal", position: oBottom, label: "Edge Flush Bottom" });
19178
21671
  } else if (Math.abs(bottom - oTop) <= threshold) {
19179
- finalY = Math.round(oTop - moving.height);
21672
+ finalY = Math.round(oTop - movingH);
19180
21673
  snappedY = true;
19181
21674
  guides.push({ type: "horizontal", position: oTop, label: "Edge Flush Top" });
19182
21675
  }
@@ -20268,7 +22761,9 @@ var ExportValidator = class {
20268
22761
  });
20269
22762
  }
20270
22763
  }
20271
- if (isNaN(node.x) || isNaN(node.y) || isNaN(node.width) || isNaN(node.height)) {
22764
+ const widthIsNaN = typeof node.width === "number" ? isNaN(node.width) : false;
22765
+ const heightIsNaN = typeof node.height === "number" ? isNaN(node.height) : false;
22766
+ if (isNaN(node.x) || isNaN(node.y) || widthIsNaN || heightIsNaN) {
20272
22767
  diagnostics.push({
20273
22768
  severity: "error",
20274
22769
  code: "UNRESOLVED_CONSTRAINTS",
@@ -21781,8 +24276,8 @@ function evaluateOverlayDocument(doc, context = {}, time = 0) {
21781
24276
  resolvedText = dataBindingEngine.evaluateExpression(responsiveNode.text, evalVariables);
21782
24277
  }
21783
24278
  const computedBounds = computedLayout.nodes[responsiveNode.id];
21784
- const finalWidth = computedBounds ? computedBounds.width : animState.width;
21785
- const finalHeight = computedBounds ? computedBounds.height : animState.height;
24279
+ const finalWidth = computedBounds ? computedBounds.width : typeof animState.width === "number" ? animState.width : 400;
24280
+ const finalHeight = computedBounds ? computedBounds.height : typeof animState.height === "number" ? animState.height : 120;
21786
24281
  const finalX = computedBounds ? computedBounds.x : animState.x;
21787
24282
  const finalY = computedBounds ? computedBounds.y : animState.y;
21788
24283
  let transform = {
@@ -21893,7 +24388,8 @@ function evaluateOverlayDocument(doc, context = {}, time = 0) {
21893
24388
  style,
21894
24389
  content,
21895
24390
  geometry,
21896
- children: evaluatedChildren
24391
+ children: evaluatedChildren,
24392
+ metadata: "textEffectRef" in responsiveNode ? { textEffectRef: responsiveNode.textEffectRef } : void 0
21897
24393
  };
21898
24394
  nodeMap[evaluatedNode.id] = evaluatedNode;
21899
24395
  return evaluatedNode;
@@ -22236,11 +24732,142 @@ function resolveBehaviorToAnimationSpec(behavior, node) {
22236
24732
  }
22237
24733
  }
22238
24734
 
24735
+ // src/smartOverlays/runtime/canvasRenderer.ts
24736
+ function alpha(value, fallback = 1) {
24737
+ if (value === void 0) return fallback;
24738
+ return value > 1 ? value / 100 : Math.max(0, Math.min(1, value));
24739
+ }
24740
+ function roundedRect2(ctx, x, y, width, height, radius) {
24741
+ const r = Math.max(0, Math.min(radius, Math.min(width, height) / 2));
24742
+ if (typeof ctx.roundRect === "function") {
24743
+ ctx.beginPath();
24744
+ ctx.roundRect(x, y, width, height, r);
24745
+ return;
24746
+ }
24747
+ ctx.beginPath();
24748
+ ctx.rect(x, y, width, height);
24749
+ }
24750
+ function drawText(ctx, node, text) {
24751
+ const style = node.style;
24752
+ const size = Math.max(1, style.fontSize ?? 20);
24753
+ const weight = style.fontWeight ?? "400";
24754
+ const family = style.fontFamily ?? "Inter, sans-serif";
24755
+ const lineHeight = (style.lineHeight ?? 1.2) * size;
24756
+ const maxWidth = Math.max(1, node.transform.width);
24757
+ const lines = [];
24758
+ let line = "";
24759
+ for (const word of text.split(/\s+/)) {
24760
+ const candidate = line ? `${line} ${word}` : word;
24761
+ if (line && ctx.measureText(candidate).width > maxWidth) {
24762
+ lines.push(line);
24763
+ line = word;
24764
+ } else {
24765
+ line = candidate;
24766
+ }
24767
+ }
24768
+ if (line || !lines.length) lines.push(line);
24769
+ const maxLines = style.maxLines;
24770
+ const visibleLines = maxLines ? lines.slice(0, maxLines) : lines;
24771
+ ctx.font = `${weight} ${size}px ${family}`;
24772
+ ctx.fillStyle = style.textColor ?? style.fillColor ?? "#ffffff";
24773
+ ctx.textAlign = style.textAlign ?? "left";
24774
+ ctx.textBaseline = "top";
24775
+ const x = style.textAlign === "center" ? maxWidth / 2 : style.textAlign === "right" ? maxWidth : 0;
24776
+ const progress = node.content?.typewriterProgress;
24777
+ visibleLines.forEach((value, index) => {
24778
+ const lineText = progress === void 0 ? value : value.slice(0, Math.ceil(value.length * progress));
24779
+ ctx.fillText(lineText, x, index * lineHeight, maxWidth);
24780
+ });
24781
+ }
24782
+ function drawPinnedTextEffect(ctx, node, text, time) {
24783
+ const reference = node.metadata?.textEffectRef;
24784
+ const snapshot = reference?.snapshot;
24785
+ if (!snapshot?.effectLayers || !snapshot.text || !snapshot.canvas) return false;
24786
+ const width = Math.max(1, Math.ceil(node.transform.width));
24787
+ const height = Math.max(1, Math.ceil(node.transform.height));
24788
+ const effectCanvas = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(width, height) : typeof document !== "undefined" ? Object.assign(document.createElement("canvas"), { width, height }) : null;
24789
+ const effectCtx = effectCanvas?.getContext("2d");
24790
+ if (!effectCtx) return false;
24791
+ const effectScene = JSON.parse(JSON.stringify(snapshot));
24792
+ effectScene.canvas.width = width;
24793
+ effectScene.canvas.height = height;
24794
+ effectScene.text.content = text;
24795
+ effectScene.text.fontFamily = node.style.fontFamily;
24796
+ effectScene.text.fontSize = node.style.fontSize;
24797
+ effectScene.text.fontWeight = node.style.fontWeight;
24798
+ effectScene.text.textPosX = "center";
24799
+ effectScene.text.textPosY = "middle";
24800
+ evaluateScene(effectScene, time, effectCtx);
24801
+ ctx.drawImage(effectCanvas, 0, 0, node.transform.width, node.transform.height);
24802
+ return true;
24803
+ }
24804
+ function drawNode(ctx, node, time) {
24805
+ if (!node.visible || node.style.opacity <= 1e-3) return;
24806
+ const { x, y, width, height, rotation, scaleX, scaleY, translateX, translateY } = node.transform;
24807
+ const style = node.style;
24808
+ ctx.save();
24809
+ ctx.translate(x + width / 2 + translateX, y + height / 2 + translateY);
24810
+ ctx.rotate(rotation * Math.PI / 180);
24811
+ ctx.scale(scaleX || 1, scaleY || 1);
24812
+ ctx.globalAlpha *= alpha(style.opacity);
24813
+ if (style.shadowColor || style.shadowBlur) {
24814
+ ctx.shadowColor = style.shadowColor ?? "rgba(0,0,0,0.5)";
24815
+ ctx.shadowBlur = style.shadowBlur ?? 0;
24816
+ }
24817
+ ctx.translate(-width / 2, -height / 2);
24818
+ if (style.fillGradient?.colors?.length) {
24819
+ const gradient = style.fillGradient.type === "radial" ? ctx.createRadialGradient(width / 2, height / 2, 0, width / 2, height / 2, Math.max(width, height) / 2) : ctx.createLinearGradient(0, 0, width, height);
24820
+ style.fillGradient.colors.forEach((color, index) => gradient.addColorStop(index / Math.max(1, style.fillGradient.colors.length - 1), color));
24821
+ ctx.fillStyle = gradient;
24822
+ ctx.globalAlpha *= alpha(style.fillOpacity);
24823
+ roundedRect2(ctx, 0, 0, width, height, style.borderRadius ?? 0);
24824
+ ctx.fill();
24825
+ } else if (style.fillColor || node.type === "shape") {
24826
+ ctx.fillStyle = style.fillColor ?? "#334155";
24827
+ ctx.globalAlpha *= alpha(style.fillOpacity);
24828
+ roundedRect2(ctx, 0, 0, width, height, style.borderRadius ?? 0);
24829
+ ctx.fill();
24830
+ }
24831
+ if (style.strokeColor && (style.strokeWidth ?? 0) > 0) {
24832
+ ctx.strokeStyle = style.strokeColor;
24833
+ ctx.lineWidth = style.strokeWidth ?? 1;
24834
+ roundedRect2(ctx, 0, 0, width, height, style.borderRadius ?? 0);
24835
+ ctx.stroke();
24836
+ }
24837
+ if (node.type === "text" || node.type === "rich-text" || node.type === "metric" || node.type === "callout" || node.type === "annotation") {
24838
+ const text = node.content?.text ?? node.content?.formattedValue ?? node.content?.props?.body ?? node.content?.props?.label ?? "";
24839
+ if (text && !drawPinnedTextEffect(ctx, node, text, time)) drawText(ctx, node, text);
24840
+ } else if (node.type === "line" || node.type === "divider" || node.type === "connector") {
24841
+ ctx.strokeStyle = style.strokeColor ?? "#94a3b8";
24842
+ ctx.lineWidth = style.strokeWidth ?? 2;
24843
+ ctx.beginPath();
24844
+ ctx.moveTo(0, height / 2);
24845
+ ctx.lineTo(width, height / 2);
24846
+ ctx.stroke();
24847
+ } else if (node.type === "media" || node.type === "video" || node.type === "lottie") {
24848
+ ctx.fillStyle = "rgba(30,41,59,0.65)";
24849
+ ctx.fillRect(0, 0, width, height);
24850
+ ctx.strokeStyle = "rgba(148,163,184,0.65)";
24851
+ ctx.strokeRect(4, 4, Math.max(0, width - 8), Math.max(0, height - 8));
24852
+ }
24853
+ ctx.restore();
24854
+ node.children?.forEach((child) => drawNode(ctx, child, time));
24855
+ }
24856
+ function renderEvaluatedSceneToCanvas(scene, ctx, options = {}) {
24857
+ if (options.clear !== false) ctx.clearRect(0, 0, scene.canvas.width, scene.canvas.height);
24858
+ if (options.background !== false && scene.canvas.backgroundColor && scene.canvas.backgroundColor !== "transparent") {
24859
+ ctx.fillStyle = scene.canvas.backgroundColor;
24860
+ ctx.fillRect(0, 0, scene.canvas.width, scene.canvas.height);
24861
+ }
24862
+ scene.nodes.forEach((node) => drawNode(ctx, node, scene.time));
24863
+ }
24864
+
22239
24865
  // src/index.ts
22240
- var VERSION = "0.1.0";
24866
+ var VERSION = "1.4.0";
22241
24867
  // Annotate the CommonJS export names for ESM import in node:
22242
24868
  0 && (module.exports = {
22243
24869
  ALL_TRANSITIONS,
24870
+ ASPECT_RATIO_PRESETS,
22244
24871
  AnimationPresetSchema,
22245
24872
  AnimationRuntime,
22246
24873
  AnimationSchema,
@@ -22334,6 +24961,9 @@ var VERSION = "0.1.0";
22334
24961
  SmartOverlayRenderer,
22335
24962
  SnapEngine,
22336
24963
  TEMPLATE_CATEGORIES,
24964
+ TEXT_TEMPLATE_KIND,
24965
+ TEXT_TEMPLATE_RENDERER_VERSION,
24966
+ TEXT_TEMPLATE_SCHEMA_VERSION,
22337
24967
  TRANSITION_CATEGORIES,
22338
24968
  TRANSITION_PRESETS,
22339
24969
  TemplateCategorySchema,
@@ -22366,6 +24996,7 @@ var VERSION = "0.1.0";
22366
24996
  alignToLottieJ,
22367
24997
  animationRuntime,
22368
24998
  animationValidator,
24999
+ applyEasing,
22369
25000
  applyFillColorToAll,
22370
25001
  applyLetterSpacing,
22371
25002
  applyMaskReveal,
@@ -22373,6 +25004,7 @@ var VERSION = "0.1.0";
22373
25004
  applyStyleToLottie,
22374
25005
  applyStyleToLottieLayer,
22375
25006
  applyTimelineAtTime,
25007
+ assertValidTextTemplateArtifact,
22376
25008
  assetRegistry,
22377
25009
  bakeAnimationIntoLayer,
22378
25010
  blendColors,
@@ -22390,6 +25022,7 @@ var VERSION = "0.1.0";
22390
25022
  calculateResizeBounds,
22391
25023
  calculateRotationAngle,
22392
25024
  canonicalContentHash,
25025
+ canonicalTemplateHash,
22393
25026
  canonicalizeSceneDocument,
22394
25027
  captureImageSourceDimensions,
22395
25028
  captureLottieFrames,
@@ -22402,6 +25035,7 @@ var VERSION = "0.1.0";
22402
25035
  cloneSceneWithNewIds,
22403
25036
  commandExecutor,
22404
25037
  compileSemanticOverlay,
25038
+ compileTextTemplate,
22405
25039
  componentRegistry,
22406
25040
  computeAutoFitFontSize,
22407
25041
  computeFitZoom,
@@ -22446,6 +25080,7 @@ var VERSION = "0.1.0";
22446
25080
  evaluateExportFrame,
22447
25081
  evaluateOverlayDocument,
22448
25082
  evaluateScene,
25083
+ evaluateSplitTextTransforms,
22449
25084
  evaluateTextEffect,
22450
25085
  evaluateTextTemplate,
22451
25086
  exportLottieToMp4,
@@ -22478,9 +25113,11 @@ var VERSION = "0.1.0";
22478
25113
  getRenderCapabilities,
22479
25114
  getSceneTime,
22480
25115
  getSourceCropRect,
25116
+ getSpanForCharIndex,
22481
25117
  getSupportedWebMMimeType,
22482
25118
  getTemplatePreset,
22483
25119
  getTemplatesByCategory,
25120
+ getTextTemplateControls,
22484
25121
  getTransitionById,
22485
25122
  getTransitionByRenderer,
22486
25123
  getTransitionCategories,
@@ -22500,6 +25137,8 @@ var VERSION = "0.1.0";
22500
25137
  injectSolidColor,
22501
25138
  injectText,
22502
25139
  injectTextStyle,
25140
+ interpolateColorString,
25141
+ interpolateValue,
22503
25142
  isKeyframed,
22504
25143
  isMp4ExportSupported,
22505
25144
  isWebMExportSupported,
@@ -22518,6 +25157,7 @@ var VERSION = "0.1.0";
22518
25157
  newLayerId,
22519
25158
  normalizeTextEffect,
22520
25159
  normalizeTextTemplate,
25160
+ normalizeTextTemplateArtifact,
22521
25161
  parseHistorySnapshot,
22522
25162
  parseLottieJson,
22523
25163
  preloadGoogleFont,
@@ -22535,12 +25175,17 @@ var VERSION = "0.1.0";
22535
25175
  removeKeyframe,
22536
25176
  removeTemplateKeyframe,
22537
25177
  removeTrack,
25178
+ renderCanonicalToCanvas,
25179
+ renderEvaluatedSceneToCanvas,
22538
25180
  renderPngSequence,
22539
25181
  renderSceneWebM,
22540
25182
  renderTextEffectCore,
25183
+ renderTextEffectToCanvas,
25184
+ renderTextTemplateToCanvas,
22541
25185
  resetFontLoader,
22542
25186
  resetSceneTime,
22543
25187
  resizeCharFillColors,
25188
+ resolveAnchorPosition,
22544
25189
  resolveAnimatedScalar,
22545
25190
  resolveBehaviorToAnimationSpec,
22546
25191
  resolveConform,
@@ -22550,6 +25195,7 @@ var VERSION = "0.1.0";
22550
25195
  resolveMediaLayout,
22551
25196
  resolveNodeForBreakpoint,
22552
25197
  resolveSpatialConstraints,
25198
+ resolveTextTemplateArtifact,
22553
25199
  restoreLetterSpacing,
22554
25200
  rgbaToComponents,
22555
25201
  rotateCrop,
@@ -22570,7 +25216,9 @@ var VERSION = "0.1.0";
22570
25216
  smartOverlayRegistry,
22571
25217
  snapEngine,
22572
25218
  snapshotScene,
25219
+ solveSpring,
22573
25220
  sortKeyframes,
25221
+ splitTextContent,
22574
25222
  streamExportFrames,
22575
25223
  supportsCtxFilter,
22576
25224
  supportsLetterSpacing,
@@ -22599,6 +25247,7 @@ var VERSION = "0.1.0";
22599
25247
  validateTextEffectDefinition,
22600
25248
  validateTextEffectDefinitionStrict,
22601
25249
  validateTextTemplate,
25250
+ validateTextTemplateArtifact,
22602
25251
  validateTextTemplateStrict,
22603
25252
  viewportTransform,
22604
25253
  waitForFontsReady,