@codehz/draw-call 0.2.2 → 0.4.1

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.
package/node/index.cjs ADDED
@@ -0,0 +1,2054 @@
1
+ let _napi_rs_canvas = require("@napi-rs/canvas");
2
+
3
+ //#region src/compat/index.ts
4
+ function createRawCanvas(width, height) {
5
+ return (0, _napi_rs_canvas.createCanvas)(width, height);
6
+ }
7
+
8
+ //#endregion
9
+ //#region src/types/base.ts
10
+ function linearGradient(angle, ...stops) {
11
+ return {
12
+ type: "linear-gradient",
13
+ angle,
14
+ stops: stops.map((stop, index) => {
15
+ if (typeof stop === "string") return {
16
+ offset: stops.length > 1 ? index / (stops.length - 1) : 0,
17
+ color: stop
18
+ };
19
+ return {
20
+ offset: stop[0],
21
+ color: stop[1]
22
+ };
23
+ })
24
+ };
25
+ }
26
+ function radialGradient(options, ...stops) {
27
+ const colorStops = stops.map((stop, index) => {
28
+ if (typeof stop === "string") return {
29
+ offset: stops.length > 1 ? index / (stops.length - 1) : 0,
30
+ color: stop
31
+ };
32
+ return {
33
+ offset: stop[0],
34
+ color: stop[1]
35
+ };
36
+ });
37
+ return {
38
+ type: "radial-gradient",
39
+ ...options,
40
+ stops: colorStops
41
+ };
42
+ }
43
+ function normalizeSpacing(value) {
44
+ if (value === void 0) return {
45
+ top: 0,
46
+ right: 0,
47
+ bottom: 0,
48
+ left: 0
49
+ };
50
+ if (typeof value === "number") return {
51
+ top: value,
52
+ right: value,
53
+ bottom: value,
54
+ left: value
55
+ };
56
+ return {
57
+ top: value.top ?? 0,
58
+ right: value.right ?? 0,
59
+ bottom: value.bottom ?? 0,
60
+ left: value.left ?? 0
61
+ };
62
+ }
63
+ function normalizeBorderRadius(value) {
64
+ if (value === void 0) return [
65
+ 0,
66
+ 0,
67
+ 0,
68
+ 0
69
+ ];
70
+ if (typeof value === "number") return [
71
+ value,
72
+ value,
73
+ value,
74
+ value
75
+ ];
76
+ return value;
77
+ }
78
+
79
+ //#endregion
80
+ //#region src/layout/components/box.ts
81
+ function calcEffectiveSize(element, padding, availableWidth) {
82
+ return {
83
+ width: typeof element.width === "number" ? element.width - padding.left - padding.right : availableWidth > 0 ? availableWidth : 0,
84
+ height: typeof element.height === "number" ? element.height - padding.top - padding.bottom : 0
85
+ };
86
+ }
87
+ function collectChildSizes(children, ctx, availableWidth, padding, measureChild) {
88
+ const childSizes = [];
89
+ for (const child of children) {
90
+ const childMargin = normalizeSpacing(child.margin);
91
+ const childSize = measureChild(child, ctx, availableWidth - padding.left - padding.right - childMargin.left - childMargin.right);
92
+ childSizes.push({
93
+ width: childSize.width,
94
+ height: childSize.height,
95
+ margin: childMargin
96
+ });
97
+ }
98
+ return childSizes;
99
+ }
100
+ function measureWrappedContent(childSizes, gap, availableMain, isRow) {
101
+ let currentMain = 0;
102
+ let currentCross = 0;
103
+ let totalCross = 0;
104
+ let maxMain = 0;
105
+ let lineCount = 0;
106
+ for (let i = 0; i < childSizes.length; i++) {
107
+ const { width, height, margin } = childSizes[i];
108
+ const itemMain = isRow ? width + margin.left + margin.right : height + margin.top + margin.bottom;
109
+ const itemCross = isRow ? height + margin.top + margin.bottom : width + margin.left + margin.right;
110
+ if (lineCount > 0 && currentMain + gap + itemMain > availableMain) {
111
+ totalCross += currentCross;
112
+ maxMain = Math.max(maxMain, currentMain);
113
+ lineCount++;
114
+ currentMain = itemMain;
115
+ currentCross = itemCross;
116
+ } else {
117
+ if (lineCount > 0 || i > 0) currentMain += gap;
118
+ currentMain += itemMain;
119
+ currentCross = Math.max(currentCross, itemCross);
120
+ if (i === 0) lineCount = 1;
121
+ }
122
+ }
123
+ if (childSizes.length > 0) {
124
+ totalCross += currentCross;
125
+ maxMain = Math.max(maxMain, currentMain);
126
+ }
127
+ if (lineCount > 1) totalCross += gap * (lineCount - 1);
128
+ return isRow ? {
129
+ width: maxMain,
130
+ height: totalCross
131
+ } : {
132
+ width: totalCross,
133
+ height: maxMain
134
+ };
135
+ }
136
+ /**
137
+ * 测量 Box 元素的固有尺寸
138
+ */
139
+ function measureBoxSize(element, ctx, availableWidth, measureChild) {
140
+ const padding = normalizeSpacing(element.padding);
141
+ const gap = element.gap ?? 0;
142
+ const direction = element.direction ?? "row";
143
+ const wrap = element.wrap ?? false;
144
+ const isRow = direction === "row" || direction === "row-reverse";
145
+ let contentWidth = 0;
146
+ let contentHeight = 0;
147
+ const children = element.children ?? [];
148
+ const { width: effectiveWidth, height: effectiveHeight } = calcEffectiveSize(element, padding, availableWidth);
149
+ if (wrap && isRow && effectiveWidth > 0) {
150
+ const wrapped = measureWrappedContent(collectChildSizes(children, ctx, availableWidth, padding, measureChild), gap, effectiveWidth, true);
151
+ contentWidth = wrapped.width;
152
+ contentHeight = wrapped.height;
153
+ } else if (wrap && !isRow && effectiveHeight > 0) {
154
+ const wrapped = measureWrappedContent(collectChildSizes(children, ctx, availableWidth, padding, measureChild), gap, effectiveHeight, false);
155
+ contentWidth = wrapped.width;
156
+ contentHeight = wrapped.height;
157
+ } else for (let i = 0; i < children.length; i++) {
158
+ const child = children[i];
159
+ const childMargin = normalizeSpacing(child.margin);
160
+ const childSize = measureChild(child, ctx, availableWidth - padding.left - padding.right - childMargin.left - childMargin.right);
161
+ if (isRow) {
162
+ contentWidth += childSize.width + childMargin.left + childMargin.right;
163
+ contentHeight = Math.max(contentHeight, childSize.height + childMargin.top + childMargin.bottom);
164
+ if (i > 0) contentWidth += gap;
165
+ } else {
166
+ contentHeight += childSize.height + childMargin.top + childMargin.bottom;
167
+ contentWidth = Math.max(contentWidth, childSize.width + childMargin.left + childMargin.right);
168
+ if (i > 0) contentHeight += gap;
169
+ }
170
+ }
171
+ const intrinsicWidth = contentWidth + padding.left + padding.right;
172
+ const intrinsicHeight = contentHeight + padding.top + padding.bottom;
173
+ return {
174
+ width: typeof element.width === "number" ? element.width : intrinsicWidth,
175
+ height: typeof element.height === "number" ? element.height : intrinsicHeight
176
+ };
177
+ }
178
+
179
+ //#endregion
180
+ //#region src/layout/components/customDraw.ts
181
+ /**
182
+ * 测量 CustomDraw 元素的固有尺寸
183
+ */
184
+ function measureCustomDrawSize(element, ctx, availableWidth, measureChild) {
185
+ if (typeof element.width === "number" && typeof element.height === "number") return {
186
+ width: element.width,
187
+ height: element.height
188
+ };
189
+ if (element.children && measureChild) return measureChild(element.children, ctx, availableWidth);
190
+ return {
191
+ width: 0,
192
+ height: 0
193
+ };
194
+ }
195
+
196
+ //#endregion
197
+ //#region src/layout/components/image.ts
198
+ /**
199
+ * 测量 Image 元素的固有尺寸
200
+ */
201
+ function measureImageSize(element, _ctx, _availableWidth) {
202
+ const imageElement = element;
203
+ if (imageElement.width !== void 0 && imageElement.height !== void 0) return {
204
+ width: typeof imageElement.width === "number" ? imageElement.width : 0,
205
+ height: typeof imageElement.height === "number" ? imageElement.height : 0
206
+ };
207
+ const src = imageElement.src;
208
+ if (src) {
209
+ const imgWidth = "naturalWidth" in src ? src.naturalWidth : "width" in src ? +src.width : 0;
210
+ const imgHeight = "naturalHeight" in src ? src.naturalHeight : "height" in src ? +src.height : 0;
211
+ if (imgWidth > 0 && imgHeight > 0) return {
212
+ width: imgWidth,
213
+ height: imgHeight
214
+ };
215
+ }
216
+ return {
217
+ width: 0,
218
+ height: 0
219
+ };
220
+ }
221
+
222
+ //#endregion
223
+ //#region src/layout/components/richtext.ts
224
+ /**
225
+ * 合并 span 样式和元素级别样式
226
+ * 优先级:span 样式 > 元素样式 > 默认值
227
+ * font 属性进行深度合并,允许 span 部分覆盖 element 的 font
228
+ */
229
+ function mergeSpanStyle(span, elementStyle) {
230
+ return {
231
+ font: {
232
+ ...elementStyle.font || {},
233
+ ...span.font || {}
234
+ },
235
+ color: span.color ?? elementStyle.color,
236
+ background: span.background ?? elementStyle.background,
237
+ underline: span.underline ?? elementStyle.underline ?? false,
238
+ strikethrough: span.strikethrough ?? elementStyle.strikethrough ?? false
239
+ };
240
+ }
241
+ /**
242
+ * 测量富文本元素的固有尺寸
243
+ */
244
+ function measureRichTextSize(element, ctx, availableWidth) {
245
+ const lineHeight = element.lineHeight ?? 1.2;
246
+ const elementStyle = {
247
+ font: element.font,
248
+ color: element.color,
249
+ background: element.background,
250
+ underline: element.underline,
251
+ strikethrough: element.strikethrough
252
+ };
253
+ const richLines = wrapRichText(ctx, element.spans, availableWidth, lineHeight, elementStyle);
254
+ let maxWidth = 0;
255
+ let totalHeight = 0;
256
+ for (const line of richLines) {
257
+ maxWidth = Math.max(maxWidth, line.width);
258
+ totalHeight += line.height;
259
+ }
260
+ return {
261
+ width: maxWidth,
262
+ height: totalHeight
263
+ };
264
+ }
265
+ /**
266
+ * 将富文本内容拆分为行
267
+ */
268
+ function wrapRichText(ctx, spans, maxWidth, lineHeightScale = 1.2, elementStyle = {}) {
269
+ const lines = [];
270
+ let currentSegments = [];
271
+ let currentLineWidth = 0;
272
+ const pushLine = () => {
273
+ if (currentSegments.length === 0) return;
274
+ let maxTopDist = 0;
275
+ let maxBottomDist = 0;
276
+ let maxLineHeight = 0;
277
+ for (const seg of currentSegments) {
278
+ const topDist = seg.ascent - seg.offset;
279
+ const bottomDist = seg.descent + seg.offset;
280
+ maxTopDist = Math.max(maxTopDist, topDist);
281
+ maxBottomDist = Math.max(maxBottomDist, bottomDist);
282
+ maxLineHeight = Math.max(maxLineHeight, seg.height);
283
+ }
284
+ const contentHeight = maxTopDist + maxBottomDist;
285
+ const finalHeight = Math.max(contentHeight, maxLineHeight);
286
+ const extra = (finalHeight - contentHeight) / 2;
287
+ lines.push({
288
+ segments: [...currentSegments],
289
+ width: currentLineWidth,
290
+ height: finalHeight,
291
+ baseline: maxTopDist + extra
292
+ });
293
+ currentSegments = [];
294
+ currentLineWidth = 0;
295
+ };
296
+ for (const span of spans) {
297
+ const mergedStyle = mergeSpanStyle(span, elementStyle);
298
+ const font = mergedStyle.font;
299
+ const lh = (font.size ?? 16) * lineHeightScale;
300
+ const words = span.text.split(/(\s+)/);
301
+ for (const word of words) {
302
+ if (word === "") continue;
303
+ if (/^\s+$/.test(word)) {
304
+ const metrics = ctx.measureText(word, font);
305
+ const wordWidth = metrics.width;
306
+ if (maxWidth > 0 && currentLineWidth + wordWidth > maxWidth && currentSegments.length > 0) pushLine();
307
+ currentSegments.push({
308
+ text: word,
309
+ font: mergedStyle.font,
310
+ color: mergedStyle.color,
311
+ background: mergedStyle.background,
312
+ underline: mergedStyle.underline,
313
+ strikethrough: mergedStyle.strikethrough,
314
+ width: wordWidth,
315
+ height: lh,
316
+ ascent: metrics.ascent,
317
+ descent: metrics.descent,
318
+ offset: metrics.offset
319
+ });
320
+ currentLineWidth += wordWidth;
321
+ } else {
322
+ const metrics = ctx.measureText(word, font);
323
+ const wordWidth = metrics.width;
324
+ if (maxWidth <= 0 || currentLineWidth + wordWidth <= maxWidth) {
325
+ currentSegments.push({
326
+ text: word,
327
+ font: mergedStyle.font,
328
+ color: mergedStyle.color,
329
+ background: mergedStyle.background,
330
+ underline: mergedStyle.underline,
331
+ strikethrough: mergedStyle.strikethrough,
332
+ width: wordWidth,
333
+ height: lh,
334
+ ascent: metrics.ascent,
335
+ descent: metrics.descent,
336
+ offset: metrics.offset
337
+ });
338
+ currentLineWidth += wordWidth;
339
+ } else {
340
+ if (currentSegments.length > 0) pushLine();
341
+ const remainingWidth = maxWidth;
342
+ let currentPos = 0;
343
+ while (currentPos < word.length) {
344
+ let bestLen = 0;
345
+ for (let len = word.length - currentPos; len > 0; len--) {
346
+ const substr = word.substring(currentPos, currentPos + len);
347
+ const m = ctx.measureText(substr, font);
348
+ if (currentLineWidth + m.width <= remainingWidth) {
349
+ bestLen = len;
350
+ if (len < word.length - currentPos) break;
351
+ }
352
+ }
353
+ if (bestLen === 0) {
354
+ if (currentSegments.length > 0) pushLine();
355
+ bestLen = 1;
356
+ }
357
+ const substr = word.substring(currentPos, currentPos + bestLen);
358
+ const m = ctx.measureText(substr, font);
359
+ currentSegments.push({
360
+ text: substr,
361
+ font: mergedStyle.font,
362
+ color: mergedStyle.color,
363
+ background: mergedStyle.background,
364
+ underline: mergedStyle.underline,
365
+ strikethrough: mergedStyle.strikethrough,
366
+ width: m.width,
367
+ height: lh,
368
+ ascent: m.ascent,
369
+ descent: m.descent,
370
+ offset: m.offset
371
+ });
372
+ currentLineWidth += m.width;
373
+ currentPos += bestLen;
374
+ if (currentPos < word.length && currentLineWidth >= remainingWidth) pushLine();
375
+ }
376
+ }
377
+ }
378
+ }
379
+ }
380
+ pushLine();
381
+ if (lines.length === 0) return [{
382
+ segments: [],
383
+ width: 0,
384
+ height: 0,
385
+ baseline: 0
386
+ }];
387
+ return lines;
388
+ }
389
+
390
+ //#endregion
391
+ //#region src/layout/components/stack.ts
392
+ /**
393
+ * 测量 Stack 元素的固有尺寸
394
+ */
395
+ function measureStackSize(element, ctx, availableWidth, measureChild) {
396
+ const padding = normalizeSpacing(element.padding);
397
+ let contentWidth = 0;
398
+ let contentHeight = 0;
399
+ const children = element.children ?? [];
400
+ for (const child of children) {
401
+ const childMargin = normalizeSpacing(child.margin);
402
+ const childSize = measureChild(child, ctx, availableWidth - padding.left - padding.right - childMargin.left - childMargin.right);
403
+ contentWidth = Math.max(contentWidth, childSize.width + childMargin.left + childMargin.right);
404
+ contentHeight = Math.max(contentHeight, childSize.height + childMargin.top + childMargin.bottom);
405
+ }
406
+ const intrinsicWidth = contentWidth + padding.left + padding.right;
407
+ const intrinsicHeight = contentHeight + padding.top + padding.bottom;
408
+ return {
409
+ width: typeof element.width === "number" ? element.width : intrinsicWidth,
410
+ height: typeof element.height === "number" ? element.height : intrinsicHeight
411
+ };
412
+ }
413
+
414
+ //#endregion
415
+ //#region src/layout/components/svg.ts
416
+ /**
417
+ * 测量 SVG 元素的固有尺寸
418
+ */
419
+ function measureSvgSize(element, _ctx, _availableWidth) {
420
+ const svgElement = element;
421
+ if (svgElement.width !== void 0 && svgElement.height !== void 0) return {
422
+ width: typeof svgElement.width === "number" ? svgElement.width : 0,
423
+ height: typeof svgElement.height === "number" ? svgElement.height : 0
424
+ };
425
+ if (svgElement.viewBox) {
426
+ const viewBoxWidth = svgElement.viewBox.width;
427
+ const viewBoxHeight = svgElement.viewBox.height;
428
+ const aspectRatio = viewBoxWidth / viewBoxHeight;
429
+ if (svgElement.width !== void 0 && typeof svgElement.width === "number") return {
430
+ width: svgElement.width,
431
+ height: svgElement.width / aspectRatio
432
+ };
433
+ if (svgElement.height !== void 0 && typeof svgElement.height === "number") return {
434
+ width: svgElement.height * aspectRatio,
435
+ height: svgElement.height
436
+ };
437
+ return {
438
+ width: viewBoxWidth,
439
+ height: viewBoxHeight
440
+ };
441
+ }
442
+ return {
443
+ width: 0,
444
+ height: 0
445
+ };
446
+ }
447
+
448
+ //#endregion
449
+ //#region src/render/utils/font.ts
450
+ /**
451
+ * 构建 Canvas 字体字符串
452
+ * @param font 字体属性
453
+ * @returns CSS 字体字符串
454
+ */
455
+ function buildFontString(font) {
456
+ return `${font.style ?? "normal"} ${font.weight ?? "normal"} ${font.size ?? 16}px ${font.family ?? "sans-serif"}`;
457
+ }
458
+
459
+ //#endregion
460
+ //#region src/layout/utils/measure.ts
461
+ function createCanvasMeasureContext(ctx) {
462
+ return { measureText(text, font) {
463
+ ctx.font = buildFontString(font);
464
+ ctx.textBaseline = "middle";
465
+ const metrics = ctx.measureText(text);
466
+ const height = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
467
+ const fontSize = font.size || 16;
468
+ return {
469
+ width: metrics.width,
470
+ height: height || fontSize,
471
+ offset: (metrics.actualBoundingBoxAscent - metrics.actualBoundingBoxDescent) / 2,
472
+ ascent: metrics.actualBoundingBoxAscent,
473
+ descent: metrics.actualBoundingBoxDescent
474
+ };
475
+ } };
476
+ }
477
+ function wrapText(ctx, text, maxWidth, font) {
478
+ if (maxWidth <= 0) {
479
+ const { offset } = ctx.measureText(text, font);
480
+ return {
481
+ lines: [text],
482
+ offsets: [offset]
483
+ };
484
+ }
485
+ const lines = [];
486
+ const offsets = [];
487
+ const paragraphs = text.split("\n");
488
+ for (const paragraph of paragraphs) {
489
+ if (paragraph === "") {
490
+ lines.push("");
491
+ offsets.push(0);
492
+ continue;
493
+ }
494
+ const words = paragraph.split(/(\s+)/);
495
+ let currentLine = "";
496
+ for (const word of words) {
497
+ const testLine = currentLine + word;
498
+ const { width } = ctx.measureText(testLine, font);
499
+ if (width > maxWidth && currentLine !== "") {
500
+ const trimmed = currentLine.trim();
501
+ lines.push(trimmed);
502
+ offsets.push(ctx.measureText(trimmed, font).offset);
503
+ currentLine = word.trimStart();
504
+ } else currentLine = testLine;
505
+ }
506
+ if (currentLine) {
507
+ const trimmed = currentLine.trim();
508
+ lines.push(trimmed);
509
+ offsets.push(ctx.measureText(trimmed, font).offset);
510
+ }
511
+ }
512
+ return lines.length > 0 ? {
513
+ lines,
514
+ offsets
515
+ } : {
516
+ lines: [""],
517
+ offsets: [0]
518
+ };
519
+ }
520
+ function truncateText(ctx, text, maxWidth, font, ellipsis = "...") {
521
+ const measured = ctx.measureText(text, font);
522
+ if (measured.width <= maxWidth) return {
523
+ text,
524
+ offset: measured.offset
525
+ };
526
+ const availableWidth = maxWidth - ctx.measureText(ellipsis, font).width;
527
+ if (availableWidth <= 0) {
528
+ const { offset } = ctx.measureText(ellipsis, font);
529
+ return {
530
+ text: ellipsis,
531
+ offset
532
+ };
533
+ }
534
+ let left = 0;
535
+ let right = text.length;
536
+ while (left < right) {
537
+ const mid = Math.floor((left + right + 1) / 2);
538
+ const truncated = text.slice(0, mid);
539
+ const { width: truncatedWidth } = ctx.measureText(truncated, font);
540
+ if (truncatedWidth <= availableWidth) left = mid;
541
+ else right = mid - 1;
542
+ }
543
+ const result = text.slice(0, left) + ellipsis;
544
+ const { offset } = ctx.measureText(result, font);
545
+ return {
546
+ text: result,
547
+ offset
548
+ };
549
+ }
550
+
551
+ //#endregion
552
+ //#region src/layout/components/text.ts
553
+ /**
554
+ * 测量文本元素的固有尺寸
555
+ */
556
+ function measureTextSize(element, ctx, availableWidth) {
557
+ const font = element.font ?? {};
558
+ const lineHeightPx = (font.size ?? 16) * (element.lineHeight ?? 1.2);
559
+ if (element.wrap && availableWidth > 0 && availableWidth < Infinity) {
560
+ const { lines } = wrapText(ctx, element.content, availableWidth, font);
561
+ const { width: maxLineWidth } = lines.reduce((max, line) => {
562
+ const { width } = ctx.measureText(line, font);
563
+ return width > max.width ? { width } : max;
564
+ }, { width: 0 });
565
+ return {
566
+ width: maxLineWidth,
567
+ height: lines.length * lineHeightPx
568
+ };
569
+ }
570
+ const { width, height } = ctx.measureText(element.content, font);
571
+ return {
572
+ width,
573
+ height: Math.max(height, lineHeightPx)
574
+ };
575
+ }
576
+
577
+ //#endregion
578
+ //#region src/layout/components/transform.ts
579
+ /**
580
+ * 测量 Transform 元素的固有尺寸
581
+ * Transform 不施加任何尺寸约束,直接透传子元素的测量结果
582
+ * 变换(rotate, scale 等)仅在渲染时应用,不影响固有尺寸
583
+ */
584
+ function measureTransformSize(element, ctx, availableWidth, measureIntrinsicSize) {
585
+ return measureIntrinsicSize(element.children, ctx, availableWidth);
586
+ }
587
+
588
+ //#endregion
589
+ //#region src/layout/components/index.ts
590
+ /**
591
+ * 计算元素的固有尺寸(不依赖父容器的尺寸)
592
+ */
593
+ function measureIntrinsicSize(element, ctx, availableWidth) {
594
+ switch (element.type) {
595
+ case "text": return measureTextSize(element, ctx, availableWidth);
596
+ case "richtext": return measureRichTextSize(element, ctx, availableWidth);
597
+ case "box": return measureBoxSize(element, ctx, availableWidth, measureIntrinsicSize);
598
+ case "stack": return measureStackSize(element, ctx, availableWidth, measureIntrinsicSize);
599
+ case "image": return measureImageSize(element, ctx, availableWidth);
600
+ case "svg": return measureSvgSize(element, ctx, availableWidth);
601
+ case "transform": return measureTransformSize(element, ctx, availableWidth, measureIntrinsicSize);
602
+ case "customdraw": return measureCustomDrawSize(element, ctx, availableWidth, measureIntrinsicSize);
603
+ default: return {
604
+ width: 0,
605
+ height: 0
606
+ };
607
+ }
608
+ }
609
+
610
+ //#endregion
611
+ //#region src/layout/utils/offset.ts
612
+ /**
613
+ * 递归地为布局节点及其子节点应用位置偏移
614
+ */
615
+ function applyOffset(node, dx, dy) {
616
+ node.layout.x += dx;
617
+ node.layout.y += dy;
618
+ node.layout.contentX += dx;
619
+ node.layout.contentY += dy;
620
+ for (const child of node.children) applyOffset(child, dx, dy);
621
+ }
622
+
623
+ //#endregion
624
+ //#region src/types/layout.ts
625
+ function resolveSize(size, available, auto) {
626
+ if (size === void 0 || size === "auto") return auto;
627
+ if (size === "fill") return available;
628
+ if (typeof size === "number") return size;
629
+ return available * parseFloat(size) / 100;
630
+ }
631
+ function sizeNeedsParent(size) {
632
+ if (size === void 0 || size === "auto") return false;
633
+ if (size === "fill") return true;
634
+ if (typeof size === "string" && size.endsWith("%")) return true;
635
+ return false;
636
+ }
637
+
638
+ //#endregion
639
+ //#region src/layout/engine.ts
640
+ function computeLayout(element, ctx, constraints, x = 0, y = 0) {
641
+ const margin = normalizeSpacing(element.margin);
642
+ const padding = normalizeSpacing("padding" in element ? element.padding : void 0);
643
+ const availableWidth = constraints.maxWidth - margin.left - margin.right;
644
+ const availableHeight = constraints.maxHeight - margin.top - margin.bottom;
645
+ const intrinsic = measureIntrinsicSize(element, ctx, availableWidth);
646
+ let width = constraints.minWidth === constraints.maxWidth && constraints.minWidth > 0 ? constraints.maxWidth - margin.left - margin.right : resolveSize(element.width, availableWidth, intrinsic.width);
647
+ let height = constraints.minHeight === constraints.maxHeight && constraints.minHeight > 0 ? constraints.maxHeight - margin.top - margin.bottom : resolveSize(element.height, availableHeight, intrinsic.height);
648
+ if (element.minWidth !== void 0) width = Math.max(width, element.minWidth);
649
+ if (element.maxWidth !== void 0) width = Math.min(width, element.maxWidth);
650
+ if (element.minHeight !== void 0) height = Math.max(height, element.minHeight);
651
+ if (element.maxHeight !== void 0) height = Math.min(height, element.maxHeight);
652
+ const actualX = x + margin.left;
653
+ const actualY = y + margin.top;
654
+ const contentX = actualX + padding.left;
655
+ const contentY = actualY + padding.top;
656
+ const contentWidth = width - padding.left - padding.right;
657
+ const contentHeight = height - padding.top - padding.bottom;
658
+ const node = {
659
+ element,
660
+ layout: {
661
+ x: actualX,
662
+ y: actualY,
663
+ width,
664
+ height,
665
+ contentX,
666
+ contentY,
667
+ contentWidth,
668
+ contentHeight
669
+ },
670
+ children: []
671
+ };
672
+ if (element.type === "text") {
673
+ const font = element.font ?? {};
674
+ if (element.wrap && contentWidth > 0) {
675
+ let { lines, offsets } = wrapText(ctx, element.content, contentWidth, font);
676
+ if (element.maxLines && lines.length > element.maxLines) {
677
+ lines = lines.slice(0, element.maxLines);
678
+ offsets = offsets.slice(0, element.maxLines);
679
+ if (element.ellipsis && lines.length > 0) {
680
+ const lastIdx = lines.length - 1;
681
+ const truncated = truncateText(ctx, lines[lastIdx], contentWidth, font);
682
+ lines[lastIdx] = truncated.text;
683
+ offsets[lastIdx] = truncated.offset;
684
+ }
685
+ }
686
+ node.lines = lines;
687
+ node.lineOffsets = offsets;
688
+ } else {
689
+ const { text, offset } = truncateText(ctx, element.content, contentWidth > 0 && element.ellipsis ? contentWidth : Infinity, font);
690
+ node.lines = [text];
691
+ node.lineOffsets = [offset];
692
+ }
693
+ }
694
+ if (element.type === "richtext") {
695
+ const lineHeight = element.lineHeight ?? 1.2;
696
+ let lines = wrapRichText(ctx, element.spans, contentWidth, lineHeight);
697
+ if (element.maxLines && lines.length > element.maxLines) {
698
+ lines = lines.slice(0, element.maxLines);
699
+ if (element.ellipsis && lines.length > 0) {
700
+ const lastLine = lines[lines.length - 1];
701
+ if (lastLine.segments.length > 0) {
702
+ const lastSeg = lastLine.segments[lastLine.segments.length - 1];
703
+ lastSeg.text += "...";
704
+ lastSeg.width = ctx.measureText(lastSeg.text, lastSeg.font ?? {}).width;
705
+ lastLine.width = lastLine.segments.reduce((sum, s) => sum + s.width, 0);
706
+ }
707
+ }
708
+ }
709
+ node.richLines = lines;
710
+ }
711
+ if (element.type === "box" || element.type === "stack") {
712
+ const children = element.children ?? [];
713
+ if (element.type === "stack") {
714
+ const stackAlign = element.align ?? "start";
715
+ const stackJustify = element.justify ?? "start";
716
+ for (const child of children) {
717
+ const childNode = computeLayout(child, ctx, {
718
+ minWidth: 0,
719
+ maxWidth: contentWidth,
720
+ minHeight: 0,
721
+ maxHeight: contentHeight
722
+ }, contentX, contentY);
723
+ const childMargin = normalizeSpacing(child.margin);
724
+ const childOuterWidth = childNode.layout.width + childMargin.left + childMargin.right;
725
+ const childOuterHeight = childNode.layout.height + childMargin.top + childMargin.bottom;
726
+ let offsetX = 0;
727
+ if (stackAlign === "center") offsetX = (contentWidth - childOuterWidth) / 2;
728
+ else if (stackAlign === "end") offsetX = contentWidth - childOuterWidth;
729
+ let offsetY = 0;
730
+ if (stackJustify === "center") offsetY = (contentHeight - childOuterHeight) / 2;
731
+ else if (stackJustify === "end") offsetY = contentHeight - childOuterHeight;
732
+ if (offsetX !== 0 || offsetY !== 0) applyOffset(childNode, offsetX, offsetY);
733
+ node.children.push(childNode);
734
+ }
735
+ } else {
736
+ const direction = element.direction ?? "row";
737
+ const justify = element.justify ?? "start";
738
+ const align = element.align ?? "stretch";
739
+ const gap = element.gap ?? 0;
740
+ const wrap = element.wrap ?? false;
741
+ const isRow = direction === "row" || direction === "row-reverse";
742
+ const isReverse = direction === "row-reverse" || direction === "column-reverse";
743
+ const getContentMainSize = () => isRow ? contentWidth : contentHeight;
744
+ const getContentCrossSize = () => isRow ? contentHeight : contentWidth;
745
+ const childInfos = [];
746
+ for (const child of children) {
747
+ const childMargin = normalizeSpacing(child.margin);
748
+ const childFlex = child.flex ?? 0;
749
+ if (childFlex > 0) childInfos.push({
750
+ element: child,
751
+ width: 0,
752
+ height: 0,
753
+ flex: childFlex,
754
+ margin: childMargin
755
+ });
756
+ else {
757
+ const size = measureIntrinsicSize(child, ctx, contentWidth - childMargin.left - childMargin.right);
758
+ const shouldStretchWidth = !isRow && child.width === void 0 && align === "stretch";
759
+ const shouldStretchHeight = isRow && child.height === void 0 && align === "stretch";
760
+ let w = sizeNeedsParent(child.width) ? resolveSize(child.width, contentWidth - childMargin.left - childMargin.right, size.width) : resolveSize(child.width, 0, size.width);
761
+ let h = sizeNeedsParent(child.height) ? resolveSize(child.height, contentHeight - childMargin.top - childMargin.bottom, size.height) : resolveSize(child.height, 0, size.height);
762
+ if (shouldStretchWidth && !wrap) w = contentWidth - childMargin.left - childMargin.right;
763
+ if (shouldStretchHeight && !wrap) h = contentHeight - childMargin.top - childMargin.bottom;
764
+ childInfos.push({
765
+ element: child,
766
+ width: w,
767
+ height: h,
768
+ flex: 0,
769
+ margin: childMargin
770
+ });
771
+ }
772
+ }
773
+ const lines = [];
774
+ if (wrap) {
775
+ let currentLine = [];
776
+ let currentLineSize = 0;
777
+ const mainAxisSize = getContentMainSize();
778
+ for (const info of childInfos) {
779
+ const itemSize = isRow ? info.width + info.margin.left + info.margin.right : info.height + info.margin.top + info.margin.bottom;
780
+ if (currentLine.length > 0 && currentLineSize + gap + itemSize > mainAxisSize) {
781
+ lines.push(currentLine);
782
+ currentLine = [info];
783
+ currentLineSize = itemSize;
784
+ } else {
785
+ currentLine.push(info);
786
+ currentLineSize += (currentLine.length > 1 ? gap : 0) + itemSize;
787
+ }
788
+ }
789
+ if (currentLine.length > 0) lines.push(currentLine);
790
+ } else lines.push(childInfos);
791
+ for (const lineInfos of lines) {
792
+ let totalFixed = 0;
793
+ let totalFlex = 0;
794
+ const totalGap = lineInfos.length > 1 ? gap * (lineInfos.length - 1) : 0;
795
+ for (const info of lineInfos) if (info.flex > 0) totalFlex += info.flex;
796
+ else if (isRow) totalFixed += info.width + info.margin.left + info.margin.right;
797
+ else totalFixed += info.height + info.margin.top + info.margin.bottom;
798
+ const mainAxisSize = getContentMainSize();
799
+ const availableForFlex = Math.max(0, mainAxisSize - totalFixed - totalGap);
800
+ for (const info of lineInfos) if (info.flex > 0) {
801
+ const flexSize = totalFlex > 0 ? availableForFlex * info.flex / totalFlex : 0;
802
+ if (isRow) {
803
+ info.width = flexSize;
804
+ const size = measureIntrinsicSize(info.element, ctx, flexSize);
805
+ info.height = sizeNeedsParent(info.element.height) ? resolveSize(info.element.height, contentHeight - info.margin.top - info.margin.bottom, size.height) : resolveSize(info.element.height, 0, size.height);
806
+ } else {
807
+ info.height = flexSize;
808
+ const size = measureIntrinsicSize(info.element, ctx, contentWidth - info.margin.left - info.margin.right);
809
+ info.width = sizeNeedsParent(info.element.width) ? resolveSize(info.element.width, contentWidth - info.margin.left - info.margin.right, size.width) : resolveSize(info.element.width, 0, size.width);
810
+ }
811
+ }
812
+ }
813
+ let crossOffset = 0;
814
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
815
+ const lineInfos = lines[lineIndex];
816
+ const totalGap = lineInfos.length > 1 ? gap * (lineInfos.length - 1) : 0;
817
+ const totalSize = lineInfos.reduce((sum, info) => {
818
+ return sum + (isRow ? info.width + info.margin.left + info.margin.right : info.height + info.margin.top + info.margin.bottom);
819
+ }, 0) + totalGap;
820
+ const freeSpace = getContentMainSize() - totalSize;
821
+ let mainStart = 0;
822
+ let mainGap = gap;
823
+ switch (justify) {
824
+ case "start":
825
+ mainStart = 0;
826
+ break;
827
+ case "end":
828
+ mainStart = freeSpace;
829
+ break;
830
+ case "center":
831
+ mainStart = freeSpace / 2;
832
+ break;
833
+ case "space-between":
834
+ mainStart = 0;
835
+ if (lineInfos.length > 1) mainGap = gap + freeSpace / (lineInfos.length - 1);
836
+ break;
837
+ case "space-around":
838
+ if (lineInfos.length > 0) {
839
+ const spacing = freeSpace / lineInfos.length;
840
+ mainStart = spacing / 2;
841
+ mainGap = gap + spacing;
842
+ }
843
+ break;
844
+ case "space-evenly":
845
+ if (lineInfos.length > 0) {
846
+ const spacing = freeSpace / (lineInfos.length + 1);
847
+ mainStart = spacing;
848
+ mainGap = gap + spacing;
849
+ }
850
+ break;
851
+ }
852
+ const lineCrossSize = lineInfos.reduce((max, info) => {
853
+ const itemCrossSize = isRow ? info.height + info.margin.top + info.margin.bottom : info.width + info.margin.left + info.margin.right;
854
+ return Math.max(max, itemCrossSize);
855
+ }, 0);
856
+ let mainOffset = mainStart;
857
+ const orderedInfos = isReverse ? [...lineInfos].reverse() : lineInfos;
858
+ for (let i = 0; i < orderedInfos.length; i++) {
859
+ const info = orderedInfos[i];
860
+ const crossAxisSize = wrap ? lineCrossSize : getContentCrossSize();
861
+ const childCrossSize = isRow ? info.height + info.margin.top + info.margin.bottom : info.width + info.margin.left + info.margin.right;
862
+ let itemCrossOffset = 0;
863
+ const effectiveAlign = info.element.alignSelf ?? align;
864
+ if (effectiveAlign === "start") itemCrossOffset = 0;
865
+ else if (effectiveAlign === "end") itemCrossOffset = crossAxisSize - childCrossSize;
866
+ else if (effectiveAlign === "center") itemCrossOffset = (crossAxisSize - childCrossSize) / 2;
867
+ else if (effectiveAlign === "stretch") {
868
+ itemCrossOffset = 0;
869
+ if (isRow && info.element.height === void 0) info.height = crossAxisSize - info.margin.top - info.margin.bottom;
870
+ else if (!isRow && info.element.width === void 0) info.width = crossAxisSize - info.margin.left - info.margin.right;
871
+ }
872
+ const childX = isRow ? contentX + mainOffset + info.margin.left : contentX + crossOffset + itemCrossOffset + info.margin.left;
873
+ const childY = isRow ? contentY + crossOffset + itemCrossOffset + info.margin.top : contentY + mainOffset + info.margin.top;
874
+ let minWidth = 0;
875
+ let maxWidth = info.width;
876
+ let minHeight = 0;
877
+ let maxHeight = info.height;
878
+ let shouldStretchCross = false;
879
+ if (info.flex > 0) if (isRow) {
880
+ minWidth = maxWidth = info.width;
881
+ if (info.element.height === void 0 && align === "stretch") {
882
+ minHeight = info.height;
883
+ maxHeight = element.height !== void 0 ? info.height : Infinity;
884
+ shouldStretchCross = true;
885
+ }
886
+ } else {
887
+ minHeight = maxHeight = info.height;
888
+ if (info.element.width === void 0 && align === "stretch") {
889
+ minWidth = info.width;
890
+ maxWidth = element.width !== void 0 ? info.width : Infinity;
891
+ shouldStretchCross = true;
892
+ }
893
+ }
894
+ else {
895
+ if (!isRow && info.element.width === void 0 && align === "stretch") minWidth = maxWidth = crossAxisSize - info.margin.left - info.margin.right;
896
+ if (isRow && info.element.height === void 0 && align === "stretch") minHeight = maxHeight = crossAxisSize - info.margin.top - info.margin.bottom;
897
+ }
898
+ const childNode = computeLayout(info.element, ctx, {
899
+ minWidth,
900
+ maxWidth,
901
+ minHeight,
902
+ maxHeight
903
+ }, childX - info.margin.left, childY - info.margin.top);
904
+ if (shouldStretchCross && info.flex > 0) {
905
+ const childPadding = normalizeSpacing("padding" in info.element ? info.element.padding : void 0);
906
+ if (isRow && childNode.layout.height < info.height) {
907
+ childNode.layout.height = info.height;
908
+ childNode.layout.contentHeight = info.height - childPadding.top - childPadding.bottom;
909
+ } else if (!isRow && childNode.layout.width < info.width) {
910
+ childNode.layout.width = info.width;
911
+ childNode.layout.contentWidth = info.width - childPadding.left - childPadding.right;
912
+ }
913
+ }
914
+ node.children.push(childNode);
915
+ mainOffset += isRow ? info.width + info.margin.left + info.margin.right : info.height + info.margin.top + info.margin.bottom;
916
+ if (i < orderedInfos.length - 1) mainOffset += mainGap;
917
+ }
918
+ crossOffset += lineCrossSize;
919
+ if (lineIndex < lines.length - 1) crossOffset += gap;
920
+ }
921
+ if (wrap && element.height === void 0 && isRow) {
922
+ const actualContentHeight = crossOffset;
923
+ const actualHeight = actualContentHeight + padding.top + padding.bottom;
924
+ node.layout.height = actualHeight;
925
+ node.layout.contentHeight = actualContentHeight;
926
+ } else if (wrap && element.width === void 0 && !isRow) {
927
+ const actualContentWidth = crossOffset;
928
+ const actualWidth = actualContentWidth + padding.left + padding.right;
929
+ node.layout.width = actualWidth;
930
+ node.layout.contentWidth = actualContentWidth;
931
+ }
932
+ if (!wrap) {
933
+ let maxChildCrossSize = 0;
934
+ for (const childNode of node.children) {
935
+ const childMargin = normalizeSpacing(childNode.element.margin);
936
+ if (isRow) {
937
+ const childOuterHeight = childNode.layout.height + childMargin.top + childMargin.bottom;
938
+ maxChildCrossSize = Math.max(maxChildCrossSize, childOuterHeight);
939
+ } else {
940
+ const childOuterWidth = childNode.layout.width + childMargin.left + childMargin.right;
941
+ maxChildCrossSize = Math.max(maxChildCrossSize, childOuterWidth);
942
+ }
943
+ }
944
+ if (isRow && element.height === void 0) {
945
+ const actualHeight = maxChildCrossSize + padding.top + padding.bottom;
946
+ if (actualHeight > node.layout.height) {
947
+ node.layout.height = actualHeight;
948
+ node.layout.contentHeight = maxChildCrossSize;
949
+ }
950
+ } else if (!isRow && element.width === void 0) {
951
+ const actualWidth = maxChildCrossSize + padding.left + padding.right;
952
+ if (actualWidth > node.layout.width) {
953
+ node.layout.width = actualWidth;
954
+ node.layout.contentWidth = maxChildCrossSize;
955
+ }
956
+ }
957
+ }
958
+ if (isReverse) node.children.reverse();
959
+ }
960
+ } else if (element.type === "transform") {
961
+ const child = element.children;
962
+ if (child) {
963
+ const childMargin = normalizeSpacing(child.margin);
964
+ const childNode = computeLayout(child, ctx, {
965
+ minWidth: 0,
966
+ maxWidth: contentWidth,
967
+ minHeight: 0,
968
+ maxHeight: contentHeight
969
+ }, contentX, contentY);
970
+ node.children.push(childNode);
971
+ if (element.width === void 0) {
972
+ const childOuterWidth = childNode.layout.width + childMargin.left + childMargin.right;
973
+ const actualWidth = childOuterWidth + padding.left + padding.right;
974
+ node.layout.width = actualWidth;
975
+ node.layout.contentWidth = childOuterWidth;
976
+ }
977
+ if (element.height === void 0) {
978
+ const childOuterHeight = childNode.layout.height + childMargin.top + childMargin.bottom;
979
+ const actualHeight = childOuterHeight + padding.top + padding.bottom;
980
+ node.layout.height = actualHeight;
981
+ node.layout.contentHeight = childOuterHeight;
982
+ }
983
+ }
984
+ } else if (element.type === "customdraw") {
985
+ const child = element.children;
986
+ if (child) {
987
+ const childMargin = normalizeSpacing(child.margin);
988
+ const childNode = computeLayout(child, ctx, {
989
+ minWidth: 0,
990
+ maxWidth: contentWidth,
991
+ minHeight: 0,
992
+ maxHeight: contentHeight
993
+ }, contentX, contentY);
994
+ node.children.push(childNode);
995
+ if (element.width === void 0) {
996
+ const childOuterWidth = childNode.layout.width + childMargin.left + childMargin.right;
997
+ const actualWidth = childOuterWidth + padding.left + padding.right;
998
+ node.layout.width = actualWidth;
999
+ node.layout.contentWidth = childOuterWidth;
1000
+ }
1001
+ if (element.height === void 0) {
1002
+ const childOuterHeight = childNode.layout.height + childMargin.top + childMargin.bottom;
1003
+ const actualHeight = childOuterHeight + padding.top + padding.bottom;
1004
+ node.layout.height = actualHeight;
1005
+ node.layout.contentHeight = childOuterHeight;
1006
+ }
1007
+ }
1008
+ }
1009
+ return node;
1010
+ }
1011
+
1012
+ //#endregion
1013
+ //#region src/render/utils/colors.ts
1014
+ function isGradientDescriptor$1(color) {
1015
+ return typeof color === "object" && color !== null && "type" in color && (color.type === "linear-gradient" || color.type === "radial-gradient");
1016
+ }
1017
+ function resolveGradient$1(ctx, descriptor, x, y, width, height) {
1018
+ if (descriptor.type === "linear-gradient") {
1019
+ const angleRad = (descriptor.angle - 90) * Math.PI / 180;
1020
+ const centerX = x + width / 2;
1021
+ const centerY = y + height / 2;
1022
+ const diagLength = Math.sqrt(width * width + height * height) / 2;
1023
+ const x0 = centerX - Math.cos(angleRad) * diagLength;
1024
+ const y0 = centerY - Math.sin(angleRad) * diagLength;
1025
+ const x1 = centerX + Math.cos(angleRad) * diagLength;
1026
+ const y1 = centerY + Math.sin(angleRad) * diagLength;
1027
+ const gradient = ctx.createLinearGradient(x0, y0, x1, y1);
1028
+ for (const stop of descriptor.stops) gradient.addColorStop(stop.offset, stop.color);
1029
+ return gradient;
1030
+ } else {
1031
+ const diagLength = Math.sqrt(width * width + height * height);
1032
+ const startX = x + (descriptor.startX ?? .5) * width;
1033
+ const startY = y + (descriptor.startY ?? .5) * height;
1034
+ const startRadius = (descriptor.startRadius ?? 0) * diagLength;
1035
+ const endX = x + (descriptor.endX ?? .5) * width;
1036
+ const endY = y + (descriptor.endY ?? .5) * height;
1037
+ const endRadius = (descriptor.endRadius ?? .5) * diagLength;
1038
+ const gradient = ctx.createRadialGradient(startX, startY, startRadius, endX, endY, endRadius);
1039
+ for (const stop of descriptor.stops) gradient.addColorStop(stop.offset, stop.color);
1040
+ return gradient;
1041
+ }
1042
+ }
1043
+ function resolveColor$1(ctx, color, x, y, width, height) {
1044
+ if (isGradientDescriptor$1(color)) return resolveGradient$1(ctx, color, x, y, width, height);
1045
+ return color;
1046
+ }
1047
+
1048
+ //#endregion
1049
+ //#region src/render/utils/shadows.ts
1050
+ function applyShadow$1(ctx, shadow) {
1051
+ if (shadow) {
1052
+ ctx.shadowOffsetX = shadow.offsetX ?? 0;
1053
+ ctx.shadowOffsetY = shadow.offsetY ?? 0;
1054
+ ctx.shadowBlur = shadow.blur ?? 0;
1055
+ ctx.shadowColor = shadow.color ?? "rgba(0,0,0,0.5)";
1056
+ } else {
1057
+ ctx.shadowOffsetX = 0;
1058
+ ctx.shadowOffsetY = 0;
1059
+ ctx.shadowBlur = 0;
1060
+ ctx.shadowColor = "transparent";
1061
+ }
1062
+ }
1063
+ function clearShadow$1(ctx) {
1064
+ ctx.shadowOffsetX = 0;
1065
+ ctx.shadowOffsetY = 0;
1066
+ ctx.shadowBlur = 0;
1067
+ ctx.shadowColor = "transparent";
1068
+ }
1069
+
1070
+ //#endregion
1071
+ //#region src/render/utils/shapes.ts
1072
+ function roundRectPath(ctx, x, y, width, height, radius) {
1073
+ const [tl, tr, br, bl] = radius;
1074
+ ctx.beginPath();
1075
+ ctx.moveTo(x + tl, y);
1076
+ ctx.lineTo(x + width - tr, y);
1077
+ ctx.quadraticCurveTo(x + width, y, x + width, y + tr);
1078
+ ctx.lineTo(x + width, y + height - br);
1079
+ ctx.quadraticCurveTo(x + width, y + height, x + width - br, y + height);
1080
+ ctx.lineTo(x + bl, y + height);
1081
+ ctx.quadraticCurveTo(x, y + height, x, y + height - bl);
1082
+ ctx.lineTo(x, y + tl);
1083
+ ctx.quadraticCurveTo(x, y, x + tl, y);
1084
+ ctx.closePath();
1085
+ }
1086
+
1087
+ //#endregion
1088
+ //#region src/render/components/box.ts
1089
+ function renderBox(ctx, node) {
1090
+ const element = node.element;
1091
+ const { x, y, width, height } = node.layout;
1092
+ const border = element.border;
1093
+ const radius = normalizeBorderRadius(border?.radius);
1094
+ const hasRadius = radius.some((r) => r > 0);
1095
+ if (element.opacity !== void 0 && element.opacity < 1) ctx.globalAlpha = element.opacity;
1096
+ if (element.shadow && element.background) applyShadow$1(ctx, element.shadow);
1097
+ if (element.background) {
1098
+ ctx.fillStyle = resolveColor$1(ctx, element.background, x, y, width, height);
1099
+ if (hasRadius) {
1100
+ roundRectPath(ctx, x, y, width, height, radius);
1101
+ ctx.fill();
1102
+ } else ctx.fillRect(x, y, width, height);
1103
+ clearShadow$1(ctx);
1104
+ }
1105
+ if (border && border.width && border.width > 0) {
1106
+ ctx.strokeStyle = border.color ? resolveColor$1(ctx, border.color, x, y, width, height) : "#000";
1107
+ ctx.lineWidth = border.width;
1108
+ if (hasRadius) {
1109
+ roundRectPath(ctx, x, y, width, height, radius);
1110
+ ctx.stroke();
1111
+ } else ctx.strokeRect(x, y, width, height);
1112
+ }
1113
+ if (element.opacity !== void 0 && element.opacity < 1) ctx.globalAlpha = 1;
1114
+ }
1115
+
1116
+ //#endregion
1117
+ //#region src/render/components/ProxiedCanvasContext.ts
1118
+ /**
1119
+ * ProxiedCanvasContext - Canvas 上下文代理类
1120
+ *
1121
+ * 该类提供对真实 CanvasRenderingContext2D 的代理,有以下功能:
1122
+ * 1. 管理 save/restore 的平衡(计数器)
1123
+ * 2. 追踪相对变换而不是绝对变换
1124
+ * 3. 在析构时自动恢复所有未恢复的状态
1125
+ * 4. 转发所有其他 Canvas API 调用
1126
+ */
1127
+ var ProxiedCanvasContext = class {
1128
+ /**
1129
+ * 真实的 Canvas 上下文
1130
+ */
1131
+ ctx;
1132
+ /**
1133
+ * 基础变换矩阵(初始化时设置,保持不变)
1134
+ */
1135
+ baseTransform;
1136
+ /**
1137
+ * 相对变换矩阵(用户通过 setTransform 设置)
1138
+ */
1139
+ relativeTransform;
1140
+ /**
1141
+ * save/restore 计数器
1142
+ */
1143
+ saveCount = 0;
1144
+ /**
1145
+ * 构造函数
1146
+ * @param ctx 真实的 CanvasRenderingContext2D
1147
+ * @param baseTransform 初始的基础变换矩阵
1148
+ */
1149
+ constructor(ctx, baseTransform) {
1150
+ this.ctx = ctx;
1151
+ this.baseTransform = baseTransform;
1152
+ this.relativeTransform = new _napi_rs_canvas.DOMMatrix();
1153
+ }
1154
+ /**
1155
+ * save() - 保存当前状态并增加计数
1156
+ */
1157
+ save() {
1158
+ this.saveCount++;
1159
+ this.ctx.save();
1160
+ }
1161
+ /**
1162
+ * restore() - 恢复上一个状态并减少计数
1163
+ */
1164
+ restore() {
1165
+ if (this.saveCount > 0) {
1166
+ this.saveCount--;
1167
+ this.ctx.restore();
1168
+ }
1169
+ }
1170
+ /**
1171
+ * setTransform() - 设置相对变换
1172
+ */
1173
+ setTransform(...args) {
1174
+ let matrix;
1175
+ if (args.length === 1 && args[0] instanceof _napi_rs_canvas.DOMMatrix) matrix = args[0];
1176
+ else if (args.length === 6) matrix = new _napi_rs_canvas.DOMMatrix([
1177
+ args[0],
1178
+ args[1],
1179
+ args[2],
1180
+ args[3],
1181
+ args[4],
1182
+ args[5]
1183
+ ]);
1184
+ else return;
1185
+ this.relativeTransform = matrix;
1186
+ const actualTransform = this.baseTransform.multiply(matrix);
1187
+ this.ctx.setTransform(actualTransform);
1188
+ }
1189
+ /**
1190
+ * getTransform() - 返回相对变换(而不是绝对变换)
1191
+ */
1192
+ getTransform() {
1193
+ return this.relativeTransform;
1194
+ }
1195
+ /**
1196
+ * 析构函数级的清理 - 自动恢复所有未恢复的 save
1197
+ */
1198
+ destroy() {
1199
+ while (this.saveCount > 0) {
1200
+ console.log("destroy restore", this.saveCount);
1201
+ this.saveCount--;
1202
+ this.ctx.restore();
1203
+ }
1204
+ }
1205
+ };
1206
+ function createProxiedCanvasContext(ctx, baseTransform) {
1207
+ const proxy = new ProxiedCanvasContext(ctx, baseTransform);
1208
+ return new Proxy(proxy, {
1209
+ get(target, prop, receiver) {
1210
+ if (prop === "save" || prop === "restore" || prop === "setTransform" || prop === "getTransform" || prop === "destroy") return Reflect.get(target, prop, receiver).bind(proxy);
1211
+ const ownValue = Reflect.get(target, prop, receiver);
1212
+ if (ownValue !== void 0) return ownValue;
1213
+ const contextValue = target.ctx[prop];
1214
+ if (typeof contextValue === "function") return contextValue.bind(target.ctx);
1215
+ return contextValue;
1216
+ },
1217
+ set(target, prop, value, _receiver) {
1218
+ target.ctx[prop] = value;
1219
+ return true;
1220
+ },
1221
+ has(target, prop) {
1222
+ if (prop === "save" || prop === "restore" || prop === "setTransform" || prop === "getTransform" || prop === "destroy") return true;
1223
+ return prop in target.ctx;
1224
+ },
1225
+ ownKeys(target) {
1226
+ return Reflect.ownKeys(target.ctx);
1227
+ },
1228
+ getOwnPropertyDescriptor(target, prop) {
1229
+ return Reflect.getOwnPropertyDescriptor(target.ctx, prop);
1230
+ }
1231
+ });
1232
+ }
1233
+
1234
+ //#endregion
1235
+ //#region src/render/components/customDraw.ts
1236
+ /**
1237
+ * 渲染 CustomDraw 组件
1238
+ * 提供自定义绘制回调,用户可以直接访问 Canvas 上下文并绘制自定义内容
1239
+ */
1240
+ function renderCustomDraw(ctx, node) {
1241
+ const element = node.element;
1242
+ ctx.save();
1243
+ ctx.translate(node.layout.x, node.layout.y);
1244
+ const proxyCtx = createProxiedCanvasContext(ctx, ctx.getTransform());
1245
+ const inner = () => {
1246
+ if (node.children && node.children.length > 0) {
1247
+ ctx.save();
1248
+ ctx.translate(-node.layout.x, -node.layout.y);
1249
+ renderNode(ctx, node.children[0]);
1250
+ ctx.restore();
1251
+ }
1252
+ };
1253
+ element.draw(proxyCtx, {
1254
+ inner,
1255
+ width: node.layout.contentWidth,
1256
+ height: node.layout.contentHeight
1257
+ });
1258
+ proxyCtx.destroy();
1259
+ ctx.restore();
1260
+ }
1261
+
1262
+ //#endregion
1263
+ //#region src/render/components/image.ts
1264
+ function renderImage(ctx, node) {
1265
+ const element = node.element;
1266
+ const { x, y, width, height } = node.layout;
1267
+ const src = element.src;
1268
+ if (!src) return;
1269
+ if (element.opacity !== void 0 && element.opacity < 1) ctx.globalAlpha = element.opacity;
1270
+ if (element.shadow) applyShadow$1(ctx, element.shadow);
1271
+ const border = element.border;
1272
+ const radius = normalizeBorderRadius(border?.radius);
1273
+ const hasRadius = radius.some((r) => r > 0);
1274
+ if (hasRadius) {
1275
+ ctx.save();
1276
+ roundRectPath(ctx, x, y, width, height, radius);
1277
+ ctx.clip();
1278
+ }
1279
+ const imgWidth = "naturalWidth" in src ? src.naturalWidth : "width" in src ? +src.width : 0;
1280
+ const imgHeight = "naturalHeight" in src ? src.naturalHeight : "height" in src ? +src.height : 0;
1281
+ const fit = element.fit ?? "fill";
1282
+ let drawX = x;
1283
+ let drawY = y;
1284
+ let drawWidth = width;
1285
+ let drawHeight = height;
1286
+ if (fit !== "fill" && imgWidth > 0 && imgHeight > 0) {
1287
+ const imgAspect = imgWidth / imgHeight;
1288
+ const boxAspect = width / height;
1289
+ let scale = 1;
1290
+ switch (fit) {
1291
+ case "contain":
1292
+ scale = imgAspect > boxAspect ? width / imgWidth : height / imgHeight;
1293
+ break;
1294
+ case "cover":
1295
+ scale = imgAspect > boxAspect ? height / imgHeight : width / imgWidth;
1296
+ break;
1297
+ case "scale-down":
1298
+ scale = Math.min(1, imgAspect > boxAspect ? width / imgWidth : height / imgHeight);
1299
+ break;
1300
+ case "none":
1301
+ scale = 1;
1302
+ break;
1303
+ }
1304
+ drawWidth = imgWidth * scale;
1305
+ drawHeight = imgHeight * scale;
1306
+ const position = element.position ?? {};
1307
+ const posX = position.x ?? "center";
1308
+ const posY = position.y ?? "center";
1309
+ if (typeof posX === "number") drawX = x + posX;
1310
+ else switch (posX) {
1311
+ case "left":
1312
+ drawX = x;
1313
+ break;
1314
+ case "center":
1315
+ drawX = x + (width - drawWidth) / 2;
1316
+ break;
1317
+ case "right":
1318
+ drawX = x + width - drawWidth;
1319
+ break;
1320
+ }
1321
+ if (typeof posY === "number") drawY = y + posY;
1322
+ else switch (posY) {
1323
+ case "top":
1324
+ drawY = y;
1325
+ break;
1326
+ case "center":
1327
+ drawY = y + (height - drawHeight) / 2;
1328
+ break;
1329
+ case "bottom":
1330
+ drawY = y + height - drawHeight;
1331
+ break;
1332
+ }
1333
+ }
1334
+ ctx.drawImage(src, drawX, drawY, drawWidth, drawHeight);
1335
+ if (element.shadow) clearShadow$1(ctx);
1336
+ if (hasRadius) ctx.restore();
1337
+ if (border && border.width && border.width > 0) {
1338
+ ctx.strokeStyle = border.color ? resolveColor$1(ctx, border.color, x, y, width, height) : "#000";
1339
+ ctx.lineWidth = border.width;
1340
+ if (hasRadius) {
1341
+ roundRectPath(ctx, x, y, width, height, radius);
1342
+ ctx.stroke();
1343
+ } else ctx.strokeRect(x, y, width, height);
1344
+ }
1345
+ if (element.opacity !== void 0 && element.opacity < 1) ctx.globalAlpha = 1;
1346
+ }
1347
+
1348
+ //#endregion
1349
+ //#region src/render/components/richtext.ts
1350
+ function renderRichText(ctx, node) {
1351
+ const element = node.element;
1352
+ const { contentX, contentY, contentWidth, contentHeight } = node.layout;
1353
+ const lines = node.richLines ?? [];
1354
+ if (lines.length === 0) return;
1355
+ const totalTextHeight = lines.reduce((sum, line) => sum + line.height, 0);
1356
+ let verticalOffset = 0;
1357
+ if (element.verticalAlign === "middle") verticalOffset = (contentHeight - totalTextHeight) / 2;
1358
+ else if (element.verticalAlign === "bottom") verticalOffset = contentHeight - totalTextHeight;
1359
+ let currentY = contentY + verticalOffset;
1360
+ for (const line of lines) {
1361
+ let lineX = contentX;
1362
+ if (element.align === "center") lineX = contentX + (contentWidth - line.width) / 2;
1363
+ else if (element.align === "right") lineX = contentX + (contentWidth - line.width);
1364
+ const baselineY = currentY + line.baseline;
1365
+ for (const seg of line.segments) {
1366
+ ctx.save();
1367
+ ctx.font = buildFontString(seg.font ?? {});
1368
+ if (seg.background) {
1369
+ ctx.fillStyle = resolveColor$1(ctx, seg.background, lineX, currentY, seg.width, line.height);
1370
+ ctx.fillRect(lineX, currentY, seg.width, line.height);
1371
+ }
1372
+ ctx.fillStyle = seg.color ? resolveColor$1(ctx, seg.color, lineX, currentY, seg.width, line.height) : "#000";
1373
+ ctx.textBaseline = "middle";
1374
+ ctx.fillText(seg.text, lineX, baselineY - seg.offset);
1375
+ if (seg.underline) {
1376
+ ctx.beginPath();
1377
+ ctx.strokeStyle = ctx.fillStyle;
1378
+ ctx.lineWidth = 1;
1379
+ ctx.moveTo(lineX, currentY + seg.height);
1380
+ ctx.lineTo(lineX + seg.width, currentY + seg.height);
1381
+ ctx.stroke();
1382
+ }
1383
+ if (seg.strikethrough) {
1384
+ ctx.beginPath();
1385
+ ctx.strokeStyle = ctx.fillStyle;
1386
+ ctx.lineWidth = 1;
1387
+ const strikeY = currentY + seg.height / 2 + seg.offset;
1388
+ ctx.moveTo(lineX, strikeY);
1389
+ ctx.lineTo(lineX + seg.width, strikeY);
1390
+ ctx.stroke();
1391
+ }
1392
+ ctx.restore();
1393
+ lineX += seg.width;
1394
+ }
1395
+ currentY += line.height;
1396
+ }
1397
+ }
1398
+
1399
+ //#endregion
1400
+ //#region src/render/components/svg.ts
1401
+ function isGradientDescriptor(color) {
1402
+ return typeof color === "object" && color !== null && "type" in color && (color.type === "linear-gradient" || color.type === "radial-gradient");
1403
+ }
1404
+ function resolveGradient(ctx, descriptor, x, y, width, height) {
1405
+ if (descriptor.type === "linear-gradient") {
1406
+ const angleRad = (descriptor.angle - 90) * Math.PI / 180;
1407
+ const centerX = x + width / 2;
1408
+ const centerY = y + height / 2;
1409
+ const diagLength = Math.sqrt(width * width + height * height) / 2;
1410
+ const x0 = centerX - Math.cos(angleRad) * diagLength;
1411
+ const y0 = centerY - Math.sin(angleRad) * diagLength;
1412
+ const x1 = centerX + Math.cos(angleRad) * diagLength;
1413
+ const y1 = centerY + Math.sin(angleRad) * diagLength;
1414
+ const gradient = ctx.createLinearGradient(x0, y0, x1, y1);
1415
+ for (const stop of descriptor.stops) gradient.addColorStop(stop.offset, stop.color);
1416
+ return gradient;
1417
+ } else {
1418
+ const diagLength = Math.sqrt(width * width + height * height);
1419
+ const startX = x + (descriptor.startX ?? .5) * width;
1420
+ const startY = y + (descriptor.startY ?? .5) * height;
1421
+ const startRadius = (descriptor.startRadius ?? 0) * diagLength;
1422
+ const endX = x + (descriptor.endX ?? .5) * width;
1423
+ const endY = y + (descriptor.endY ?? .5) * height;
1424
+ const endRadius = (descriptor.endRadius ?? .5) * diagLength;
1425
+ const gradient = ctx.createRadialGradient(startX, startY, startRadius, endX, endY, endRadius);
1426
+ for (const stop of descriptor.stops) gradient.addColorStop(stop.offset, stop.color);
1427
+ return gradient;
1428
+ }
1429
+ }
1430
+ function resolveColor(ctx, color, x, y, width, height) {
1431
+ if (isGradientDescriptor(color)) return resolveGradient(ctx, color, x, y, width, height);
1432
+ return color;
1433
+ }
1434
+ function applyTransform(base, transform) {
1435
+ if (!transform) return base;
1436
+ let result = new _napi_rs_canvas.DOMMatrix([
1437
+ base.a,
1438
+ base.b,
1439
+ base.c,
1440
+ base.d,
1441
+ base.e,
1442
+ base.f
1443
+ ]);
1444
+ if (transform.matrix) {
1445
+ const [a, b, c, d, e, f] = transform.matrix;
1446
+ result = result.multiply(new _napi_rs_canvas.DOMMatrix([
1447
+ a,
1448
+ b,
1449
+ c,
1450
+ d,
1451
+ e,
1452
+ f
1453
+ ]));
1454
+ }
1455
+ if (transform.translate) result = result.translate(transform.translate[0], transform.translate[1]);
1456
+ if (transform.rotate !== void 0) if (typeof transform.rotate === "number") result = result.rotate(transform.rotate);
1457
+ else {
1458
+ const [angle, cx, cy] = transform.rotate;
1459
+ result = result.translate(cx, cy).rotate(angle).translate(-cx, -cy);
1460
+ }
1461
+ if (transform.scale !== void 0) if (typeof transform.scale === "number") result = result.scale(transform.scale);
1462
+ else result = result.scale(transform.scale[0], transform.scale[1]);
1463
+ if (transform.skewX !== void 0) {
1464
+ const degrees = transform.skewX * 180 / Math.PI;
1465
+ result = result.skewX(degrees);
1466
+ }
1467
+ if (transform.skewY !== void 0) {
1468
+ const degrees = transform.skewY * 180 / Math.PI;
1469
+ result = result.skewY(degrees);
1470
+ }
1471
+ return result;
1472
+ }
1473
+ function applyStroke(ctx, stroke, bounds) {
1474
+ ctx.strokeStyle = resolveColor(ctx, stroke.color, bounds.x, bounds.y, bounds.width, bounds.height);
1475
+ ctx.lineWidth = stroke.width;
1476
+ ctx.setLineDash(stroke.dash ?? []);
1477
+ if (stroke.cap) ctx.lineCap = stroke.cap;
1478
+ if (stroke.join) ctx.lineJoin = stroke.join;
1479
+ }
1480
+ function applyFill(ctx, fill, bounds) {
1481
+ ctx.fillStyle = resolveColor(ctx, fill, bounds.x, bounds.y, bounds.width, bounds.height);
1482
+ ctx.fill();
1483
+ }
1484
+ function applyFillAndStroke(ctx, shape, bounds) {
1485
+ if (shape.fill && shape.fill !== "none") applyFill(ctx, shape.fill, bounds);
1486
+ if (shape.stroke) {
1487
+ applyStroke(ctx, shape.stroke, bounds);
1488
+ ctx.stroke();
1489
+ }
1490
+ }
1491
+ function renderSvgRect(ctx, rect, bounds) {
1492
+ const { x = 0, y = 0, width, height, rx = 0, ry = 0 } = rect;
1493
+ ctx.beginPath();
1494
+ if (rx || ry) ctx.roundRect(x, y, width, height, Math.max(rx, ry));
1495
+ else ctx.rect(x, y, width, height);
1496
+ applyFillAndStroke(ctx, rect, bounds);
1497
+ }
1498
+ function renderSvgCircle(ctx, circle, bounds) {
1499
+ ctx.beginPath();
1500
+ ctx.arc(circle.cx, circle.cy, circle.r, 0, Math.PI * 2);
1501
+ applyFillAndStroke(ctx, circle, bounds);
1502
+ }
1503
+ function renderSvgEllipse(ctx, ellipse, bounds) {
1504
+ ctx.beginPath();
1505
+ ctx.ellipse(ellipse.cx, ellipse.cy, ellipse.rx, ellipse.ry, 0, 0, Math.PI * 2);
1506
+ applyFillAndStroke(ctx, ellipse, bounds);
1507
+ }
1508
+ function renderSvgLine(ctx, line, bounds) {
1509
+ ctx.beginPath();
1510
+ ctx.moveTo(line.x1, line.y1);
1511
+ ctx.lineTo(line.x2, line.y2);
1512
+ if (line.stroke) {
1513
+ applyStroke(ctx, line.stroke, bounds);
1514
+ ctx.stroke();
1515
+ }
1516
+ }
1517
+ function renderSvgPolyline(ctx, polyline, bounds) {
1518
+ const { points } = polyline;
1519
+ if (points.length === 0) return;
1520
+ ctx.beginPath();
1521
+ ctx.moveTo(points[0][0], points[0][1]);
1522
+ for (let i = 1; i < points.length; i++) ctx.lineTo(points[i][0], points[i][1]);
1523
+ applyFillAndStroke(ctx, polyline, bounds);
1524
+ }
1525
+ function renderSvgPolygon(ctx, polygon, bounds) {
1526
+ const { points } = polygon;
1527
+ if (points.length === 0) return;
1528
+ ctx.beginPath();
1529
+ ctx.moveTo(points[0][0], points[0][1]);
1530
+ for (let i = 1; i < points.length; i++) ctx.lineTo(points[i][0], points[i][1]);
1531
+ ctx.closePath();
1532
+ applyFillAndStroke(ctx, polygon, bounds);
1533
+ }
1534
+ function renderSvgPath(ctx, path, bounds) {
1535
+ const path2d = new _napi_rs_canvas.Path2D(path.d);
1536
+ if (path.fill && path.fill !== "none") {
1537
+ ctx.fillStyle = resolveColor(ctx, path.fill, bounds.x, bounds.y, bounds.width, bounds.height);
1538
+ ctx.fill(path2d);
1539
+ }
1540
+ if (path.stroke) {
1541
+ applyStroke(ctx, path.stroke, bounds);
1542
+ ctx.stroke(path2d);
1543
+ }
1544
+ }
1545
+ const TEXT_ANCHOR_MAP = {
1546
+ start: "left",
1547
+ middle: "center",
1548
+ end: "right"
1549
+ };
1550
+ const BASELINE_MAP = {
1551
+ auto: "alphabetic",
1552
+ middle: "middle",
1553
+ hanging: "hanging"
1554
+ };
1555
+ function renderSvgText(ctx, text, bounds) {
1556
+ const { x = 0, y = 0, content, font, textAnchor = "start", dominantBaseline = "auto" } = text;
1557
+ ctx.font = buildFontString(font ?? {});
1558
+ ctx.textAlign = TEXT_ANCHOR_MAP[textAnchor] ?? "left";
1559
+ ctx.textBaseline = BASELINE_MAP[dominantBaseline] ?? "alphabetic";
1560
+ if (text.fill && text.fill !== "none") {
1561
+ ctx.fillStyle = resolveColor(ctx, text.fill, bounds.x, bounds.y, bounds.width, bounds.height);
1562
+ ctx.fillText(content, x, y);
1563
+ }
1564
+ if (text.stroke) {
1565
+ applyStroke(ctx, text.stroke, bounds);
1566
+ ctx.strokeText(content, x, y);
1567
+ }
1568
+ }
1569
+ function renderSvgChild(ctx, child, parentTransform, bounds, baseTransform) {
1570
+ const localTransform = applyTransform(parentTransform, child.transform);
1571
+ ctx.save();
1572
+ ctx.setTransform(baseTransform.multiply(localTransform));
1573
+ if (child.opacity !== void 0) ctx.globalAlpha *= child.opacity;
1574
+ switch (child.type) {
1575
+ case "rect":
1576
+ renderSvgRect(ctx, child, bounds);
1577
+ break;
1578
+ case "circle":
1579
+ renderSvgCircle(ctx, child, bounds);
1580
+ break;
1581
+ case "ellipse":
1582
+ renderSvgEllipse(ctx, child, bounds);
1583
+ break;
1584
+ case "line":
1585
+ renderSvgLine(ctx, child, bounds);
1586
+ break;
1587
+ case "polyline":
1588
+ renderSvgPolyline(ctx, child, bounds);
1589
+ break;
1590
+ case "polygon":
1591
+ renderSvgPolygon(ctx, child, bounds);
1592
+ break;
1593
+ case "path":
1594
+ renderSvgPath(ctx, child, bounds);
1595
+ break;
1596
+ case "text":
1597
+ renderSvgText(ctx, child, bounds);
1598
+ break;
1599
+ case "g":
1600
+ renderSvgGroup(ctx, child, localTransform, bounds, baseTransform);
1601
+ break;
1602
+ }
1603
+ ctx.restore();
1604
+ }
1605
+ function renderSvgGroup(ctx, group, parentTransform, bounds, baseTransform) {
1606
+ for (const child of group.children) renderSvgChild(ctx, child, parentTransform, bounds, baseTransform);
1607
+ }
1608
+ function calculateViewBoxTransform(x, y, width, height, viewBox, preserveAspectRatio) {
1609
+ const vbX = viewBox.x ?? 0;
1610
+ const vbY = viewBox.y ?? 0;
1611
+ const vbWidth = viewBox.width;
1612
+ const vbHeight = viewBox.height;
1613
+ const scaleX = width / vbWidth;
1614
+ const scaleY = height / vbHeight;
1615
+ const align = preserveAspectRatio?.align ?? "xMidYMid";
1616
+ const meetOrSlice = preserveAspectRatio?.meetOrSlice ?? "meet";
1617
+ if (align === "none") return new _napi_rs_canvas.DOMMatrix().translate(x, y).scale(scaleX, scaleY).translate(-vbX, -vbY);
1618
+ const scale = meetOrSlice === "meet" ? Math.min(scaleX, scaleY) : Math.max(scaleX, scaleY);
1619
+ const scaledWidth = vbWidth * scale;
1620
+ const scaledHeight = vbHeight * scale;
1621
+ let translateX = x;
1622
+ let translateY = y;
1623
+ if (align.includes("xMid")) translateX += (width - scaledWidth) / 2;
1624
+ else if (align.includes("xMax")) translateX += width - scaledWidth;
1625
+ if (align.includes("YMid")) translateY += (height - scaledHeight) / 2;
1626
+ else if (align.includes("YMax")) translateY += height - scaledHeight;
1627
+ return new _napi_rs_canvas.DOMMatrix().translate(translateX, translateY).scale(scale, scale).translate(-vbX, -vbY);
1628
+ }
1629
+ function applyShadow(ctx, shadow) {
1630
+ ctx.shadowOffsetX = shadow.offsetX ?? 0;
1631
+ ctx.shadowOffsetY = shadow.offsetY ?? 0;
1632
+ ctx.shadowBlur = shadow.blur ?? 0;
1633
+ ctx.shadowColor = shadow.color ?? "rgba(0,0,0,0.5)";
1634
+ }
1635
+ function clearShadow(ctx) {
1636
+ ctx.shadowOffsetX = 0;
1637
+ ctx.shadowOffsetY = 0;
1638
+ ctx.shadowBlur = 0;
1639
+ ctx.shadowColor = "transparent";
1640
+ }
1641
+ function renderSvg(ctx, node) {
1642
+ const element = node.element;
1643
+ const { x, y, width, height } = node.layout;
1644
+ const bounds = {
1645
+ x,
1646
+ y,
1647
+ width,
1648
+ height
1649
+ };
1650
+ if (element.background) {
1651
+ if (element.shadow) applyShadow(ctx, element.shadow);
1652
+ ctx.fillStyle = resolveColor(ctx, element.background, x, y, width, height);
1653
+ ctx.fillRect(x, y, width, height);
1654
+ if (element.shadow) clearShadow(ctx);
1655
+ }
1656
+ ctx.save();
1657
+ ctx.beginPath();
1658
+ ctx.rect(x, y, width, height);
1659
+ ctx.clip();
1660
+ const baseTransform = ctx.getTransform();
1661
+ const transform = calculateViewBoxTransform(x, y, width, height, element.viewBox ?? {
1662
+ x: 0,
1663
+ y: 0,
1664
+ width,
1665
+ height
1666
+ }, element.preserveAspectRatio);
1667
+ for (const child of element.children) renderSvgChild(ctx, child, transform, bounds, baseTransform);
1668
+ ctx.restore();
1669
+ }
1670
+
1671
+ //#endregion
1672
+ //#region src/render/components/text.ts
1673
+ function renderText(ctx, node) {
1674
+ const element = node.element;
1675
+ const { contentX, contentY, contentWidth, contentHeight } = node.layout;
1676
+ const lines = node.lines ?? [element.content];
1677
+ const font = element.font ?? {};
1678
+ const lineHeightPx = (font.size ?? 16) * (element.lineHeight ?? 1.2);
1679
+ ctx.font = buildFontString(font);
1680
+ ctx.fillStyle = element.color ? resolveColor$1(ctx, element.color, contentX, contentY, contentWidth, contentHeight) : "#000";
1681
+ let textAlign = "left";
1682
+ if (element.align === "center") textAlign = "center";
1683
+ else if (element.align === "right") textAlign = "right";
1684
+ ctx.textAlign = textAlign;
1685
+ ctx.textBaseline = "middle";
1686
+ const totalTextHeight = lines.length * lineHeightPx;
1687
+ let verticalOffset = 0;
1688
+ if (element.verticalAlign === "middle") verticalOffset = (contentHeight - totalTextHeight) / 2;
1689
+ else if (element.verticalAlign === "bottom") verticalOffset = contentHeight - totalTextHeight;
1690
+ let textX = contentX;
1691
+ if (element.align === "center") textX = contentX + contentWidth / 2;
1692
+ else if (element.align === "right") textX = contentX + contentWidth;
1693
+ if (element.shadow) applyShadow$1(ctx, element.shadow);
1694
+ for (let i = 0; i < lines.length; i++) {
1695
+ const correctedLineY = contentY + verticalOffset + i * lineHeightPx + lineHeightPx / 2 + (node.lineOffsets?.[i] ?? 0);
1696
+ if (element.stroke) {
1697
+ ctx.strokeStyle = resolveColor$1(ctx, element.stroke.color, contentX, contentY, contentWidth, contentHeight);
1698
+ ctx.lineWidth = element.stroke.width;
1699
+ ctx.strokeText(lines[i], textX, correctedLineY);
1700
+ }
1701
+ ctx.fillText(lines[i], textX, correctedLineY);
1702
+ }
1703
+ if (element.shadow) clearShadow$1(ctx);
1704
+ }
1705
+
1706
+ //#endregion
1707
+ //#region src/render/components/transform.ts
1708
+ /**
1709
+ * 解析 Transform 值为 DOMMatrix
1710
+ * 支持三种格式:
1711
+ * - 数组: [a, b, c, d, e, f]
1712
+ * - DOMMatrix2DInit 对象: { a, b, c, d, e, f, ... }
1713
+ * - 简易对象: { translate, rotate, scale, skewX, skewY }
1714
+ */
1715
+ function parseTransformValue(transform) {
1716
+ if (transform === void 0) return new _napi_rs_canvas.DOMMatrix();
1717
+ if (Array.isArray(transform)) return new _napi_rs_canvas.DOMMatrix(transform);
1718
+ const hasDOMMatrixInit = "a" in transform || "b" in transform || "c" in transform || "d" in transform || "e" in transform || "f" in transform;
1719
+ const hasSimpleTransform = "translate" in transform || "rotate" in transform || "scale" in transform || "skewX" in transform || "skewY" in transform;
1720
+ if (hasDOMMatrixInit && !hasSimpleTransform) {
1721
+ const init = transform;
1722
+ return new _napi_rs_canvas.DOMMatrix([
1723
+ init.a ?? 1,
1724
+ init.b ?? 0,
1725
+ init.c ?? 0,
1726
+ init.d ?? 1,
1727
+ init.e ?? 0,
1728
+ init.f ?? 0
1729
+ ]);
1730
+ }
1731
+ const simpleObj = transform;
1732
+ let result = new _napi_rs_canvas.DOMMatrix();
1733
+ if (simpleObj.translate) result = result.translate(simpleObj.translate[0], simpleObj.translate[1]);
1734
+ if (simpleObj.rotate !== void 0) if (typeof simpleObj.rotate === "number") result = result.rotate(simpleObj.rotate);
1735
+ else {
1736
+ const [angle, cx, cy] = simpleObj.rotate;
1737
+ result = result.translate(cx, cy).rotate(angle).translate(-cx, -cy);
1738
+ }
1739
+ if (simpleObj.scale !== void 0) if (typeof simpleObj.scale === "number") result = result.scale(simpleObj.scale);
1740
+ else result = result.scale(simpleObj.scale[0], simpleObj.scale[1]);
1741
+ if (simpleObj.skewX !== void 0) result = result.skewX(simpleObj.skewX);
1742
+ if (simpleObj.skewY !== void 0) result = result.skewY(simpleObj.skewY);
1743
+ return result;
1744
+ }
1745
+ /**
1746
+ * 根据 transformOrigin 属性和子元素尺寸计算实际变换原点坐标
1747
+ */
1748
+ function resolveTransformOrigin(origin, childLayout) {
1749
+ if (origin === void 0) return [0, 0];
1750
+ const [xVal, yVal] = origin;
1751
+ const sizes = [childLayout.width, childLayout.height];
1752
+ const values = [xVal, yVal];
1753
+ const result = [0, 0];
1754
+ for (let i = 0; i < 2; i++) {
1755
+ const val = values[i];
1756
+ if (typeof val === "string") if (val.endsWith("%")) result[i] = parseFloat(val) / 100 * sizes[i];
1757
+ else result[i] = parseFloat(val);
1758
+ else result[i] = val;
1759
+ }
1760
+ return result;
1761
+ }
1762
+ /**
1763
+ * 渲染 Transform 组件及其子元素
1764
+ */
1765
+ function renderTransform(ctx, node) {
1766
+ const element = node.element;
1767
+ const { children } = node;
1768
+ if (!children || children.length === 0) return;
1769
+ const childNode = children[0];
1770
+ const [relativeOx, relativeOy] = resolveTransformOrigin(element.transformOrigin, childNode.layout);
1771
+ const ox = childNode.layout.x + relativeOx;
1772
+ const oy = childNode.layout.y + relativeOy;
1773
+ const targetMatrix = parseTransformValue(element.transform);
1774
+ const finalMatrix = new _napi_rs_canvas.DOMMatrix().translate(ox, oy).multiply(targetMatrix).translate(-ox, -oy);
1775
+ ctx.save();
1776
+ const composedTransform = ctx.getTransform().multiply(finalMatrix);
1777
+ ctx.setTransform(composedTransform);
1778
+ renderNode(ctx, childNode);
1779
+ ctx.restore();
1780
+ }
1781
+
1782
+ //#endregion
1783
+ //#region src/render/index.ts
1784
+ function renderNode(ctx, node) {
1785
+ const element = node.element;
1786
+ switch (element.type) {
1787
+ case "box":
1788
+ case "stack": {
1789
+ renderBox(ctx, node);
1790
+ const shouldClip = element.clip === true;
1791
+ if (shouldClip) {
1792
+ ctx.save();
1793
+ const { x, y, width, height } = node.layout;
1794
+ roundRectPath(ctx, x, y, width, height, normalizeBorderRadius(element.border?.radius));
1795
+ ctx.clip();
1796
+ }
1797
+ for (const child of node.children) renderNode(ctx, child);
1798
+ if (shouldClip) ctx.restore();
1799
+ break;
1800
+ }
1801
+ case "text":
1802
+ renderText(ctx, node);
1803
+ break;
1804
+ case "richtext":
1805
+ renderRichText(ctx, node);
1806
+ break;
1807
+ case "image":
1808
+ renderImage(ctx, node);
1809
+ break;
1810
+ case "svg":
1811
+ renderSvg(ctx, node);
1812
+ break;
1813
+ case "transform":
1814
+ renderTransform(ctx, node);
1815
+ break;
1816
+ case "customdraw":
1817
+ renderCustomDraw(ctx, node);
1818
+ break;
1819
+ }
1820
+ }
1821
+
1822
+ //#endregion
1823
+ //#region src/canvas.ts
1824
+ /**
1825
+ * 创建适用于浏览器环境的 Canvas
1826
+ *
1827
+ * 在浏览器环境中使用,支持传入已有的 canvas 实例
1828
+ */
1829
+ function createCanvas(options) {
1830
+ const { width, height, pixelRatio = 1 } = options;
1831
+ const canvas = options.canvas ?? createRawCanvas(width * pixelRatio, height * pixelRatio);
1832
+ const ctx = canvas.getContext("2d");
1833
+ if (!ctx) throw new Error("Failed to get 2d context");
1834
+ if (options.imageSmoothingEnabled !== void 0) ctx.imageSmoothingEnabled = options.imageSmoothingEnabled;
1835
+ if (options.imageSmoothingQuality !== void 0) ctx.imageSmoothingQuality = options.imageSmoothingQuality;
1836
+ if (pixelRatio !== 1) ctx.scale(pixelRatio, pixelRatio);
1837
+ const measureCtx = createCanvasMeasureContext(ctx);
1838
+ return {
1839
+ width,
1840
+ height,
1841
+ pixelRatio,
1842
+ canvas,
1843
+ render(element) {
1844
+ const layoutTree = computeLayout(element, measureCtx, {
1845
+ minWidth: 0,
1846
+ maxWidth: width,
1847
+ minHeight: 0,
1848
+ maxHeight: height
1849
+ });
1850
+ renderNode(ctx, layoutTree);
1851
+ return layoutTree;
1852
+ },
1853
+ clear() {
1854
+ ctx.clearRect(0, 0, width, height);
1855
+ },
1856
+ getContext() {
1857
+ return ctx;
1858
+ },
1859
+ toDataURL(type, quality) {
1860
+ if ("toDataURL" in canvas && typeof canvas.toDataURL === "function") return canvas.toDataURL(type, quality);
1861
+ throw new Error("toDataURL not supported");
1862
+ },
1863
+ toBuffer(type = "image/png") {
1864
+ if ("toBuffer" in canvas && typeof canvas.toBuffer === "function") return canvas.toBuffer(type);
1865
+ throw new Error("toBuffer not supported in this environment");
1866
+ }
1867
+ };
1868
+ }
1869
+
1870
+ //#endregion
1871
+ //#region src/components/Box.ts
1872
+ function Box(props) {
1873
+ return {
1874
+ type: "box",
1875
+ ...props
1876
+ };
1877
+ }
1878
+
1879
+ //#endregion
1880
+ //#region src/components/CustomDraw.ts
1881
+ function CustomDraw(props) {
1882
+ return {
1883
+ type: "customdraw",
1884
+ ...props
1885
+ };
1886
+ }
1887
+
1888
+ //#endregion
1889
+ //#region src/components/Image.ts
1890
+ function Image(props) {
1891
+ return {
1892
+ type: "image",
1893
+ ...props
1894
+ };
1895
+ }
1896
+
1897
+ //#endregion
1898
+ //#region src/components/RichText.ts
1899
+ function RichText(props) {
1900
+ return {
1901
+ type: "richtext",
1902
+ ...props
1903
+ };
1904
+ }
1905
+
1906
+ //#endregion
1907
+ //#region src/components/Stack.ts
1908
+ function Stack(props) {
1909
+ return {
1910
+ type: "stack",
1911
+ ...props
1912
+ };
1913
+ }
1914
+
1915
+ //#endregion
1916
+ //#region src/components/Svg.ts
1917
+ function Svg(props) {
1918
+ return {
1919
+ type: "svg",
1920
+ ...props
1921
+ };
1922
+ }
1923
+ const svg = {
1924
+ rect: (props) => ({
1925
+ type: "rect",
1926
+ ...props
1927
+ }),
1928
+ circle: (props) => ({
1929
+ type: "circle",
1930
+ ...props
1931
+ }),
1932
+ ellipse: (props) => ({
1933
+ type: "ellipse",
1934
+ ...props
1935
+ }),
1936
+ line: (props) => ({
1937
+ type: "line",
1938
+ ...props
1939
+ }),
1940
+ polyline: (props) => ({
1941
+ type: "polyline",
1942
+ ...props
1943
+ }),
1944
+ polygon: (props) => ({
1945
+ type: "polygon",
1946
+ ...props
1947
+ }),
1948
+ path: (props) => ({
1949
+ type: "path",
1950
+ ...props
1951
+ }),
1952
+ text: (props) => ({
1953
+ type: "text",
1954
+ ...props
1955
+ }),
1956
+ g: (props) => ({
1957
+ type: "g",
1958
+ ...props
1959
+ })
1960
+ };
1961
+
1962
+ //#endregion
1963
+ //#region src/components/Text.ts
1964
+ function Text(props) {
1965
+ return {
1966
+ type: "text",
1967
+ ...props
1968
+ };
1969
+ }
1970
+
1971
+ //#endregion
1972
+ //#region src/components/Transform.ts
1973
+ function Transform(props) {
1974
+ return {
1975
+ type: "transform",
1976
+ ...props
1977
+ };
1978
+ }
1979
+
1980
+ //#endregion
1981
+ //#region src/layout/utils/print.ts
1982
+ /**
1983
+ * 获取元素类型的显示名称
1984
+ */
1985
+ function getElementType(element) {
1986
+ switch (element.type) {
1987
+ case "box": return "Box";
1988
+ case "text": return `Text "${element.content.slice(0, 20)}${element.content.length > 20 ? "..." : ""}"`;
1989
+ case "stack": return "Stack";
1990
+ case "image": return "Image";
1991
+ case "svg": return "Svg";
1992
+ default: return element.type;
1993
+ }
1994
+ }
1995
+ /**
1996
+ * 递归打印布局树
1997
+ */
1998
+ function printLayoutToString(node, prefix = "", isLast = true, depth = 0) {
1999
+ const lines = [];
2000
+ const connector = isLast ? "└─ " : "├─ ";
2001
+ const type = getElementType(node.element);
2002
+ const { x, y, width, height } = node.layout;
2003
+ const childCount = node.children.length;
2004
+ lines.push(`${prefix}${connector}${type} @(${Math.round(x)},${Math.round(y)}) size:${Math.round(width)}x${Math.round(height)}`);
2005
+ if (node.element.type === "text" && node.lines) {
2006
+ const contentPrefix = prefix + (isLast ? " " : "│ ");
2007
+ for (let i = 0; i < node.lines.length; i++) {
2008
+ const lineText = node.lines[i];
2009
+ const isLastLine = i === node.lines.length - 1 && childCount === 0;
2010
+ lines.push(`${contentPrefix}${isLastLine ? "└─ " : "├─ "}${JSON.stringify(lineText)}`);
2011
+ }
2012
+ }
2013
+ for (let i = 0; i < node.children.length; i++) {
2014
+ const child = node.children[i];
2015
+ const isChildLast = i === node.children.length - 1;
2016
+ const childPrefix = prefix + (isLast ? " " : "│ ");
2017
+ lines.push(...printLayoutToString(child, childPrefix, isChildLast, depth + 1));
2018
+ }
2019
+ return lines;
2020
+ }
2021
+ /**
2022
+ * 打印 LayoutNode 树结构到控制台
2023
+ */
2024
+ function printLayout(node) {
2025
+ const lines = printLayoutToString(node, "", true);
2026
+ console.log(lines.join("\n"));
2027
+ }
2028
+ /**
2029
+ * 将 LayoutNode 转换为美观的字符串
2030
+ * @param node LayoutNode 根节点
2031
+ * @param indent 缩进字符串,默认为两个空格
2032
+ * @returns 格式化的字符串
2033
+ */
2034
+ function layoutToString(node, _indent = " ") {
2035
+ return printLayoutToString(node, "", true).join("\n");
2036
+ }
2037
+
2038
+ //#endregion
2039
+ exports.Box = Box;
2040
+ exports.CustomDraw = CustomDraw;
2041
+ exports.Image = Image;
2042
+ exports.RichText = RichText;
2043
+ exports.Stack = Stack;
2044
+ exports.Svg = Svg;
2045
+ exports.Text = Text;
2046
+ exports.Transform = Transform;
2047
+ exports.computeLayout = computeLayout;
2048
+ exports.createCanvas = createCanvas;
2049
+ exports.createCanvasMeasureContext = createCanvasMeasureContext;
2050
+ exports.layoutToString = layoutToString;
2051
+ exports.linearGradient = linearGradient;
2052
+ exports.printLayout = printLayout;
2053
+ exports.radialGradient = radialGradient;
2054
+ exports.svg = svg;