@formepdf/react 0.10.4 → 0.11.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.
package/dist/serialize.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { isValidElement, Children, Fragment } from 'react';
2
- import { Document, Page, View, Text, Image, Table, Row, Cell, Fixed, Svg, QrCode, Barcode, Canvas, Watermark, PageBreak, BarChart, LineChart, PieChart, AreaChart, DotPlot, TextField, Checkbox, Dropdown, RadioButton } from './components.js';
2
+ import { Document, Page, View, Text, H1, H2, H3, H4, H5, H6, OrderedList, UnorderedList, ListItem, Strong, Em, Code, Link, Image, Table, Row, Cell, Fixed, Svg, QrCode, Barcode, Canvas, Watermark, PageBreak, BarChart, LineChart, PieChart, AreaChart, DotPlot, TextField, Checkbox, Dropdown, RadioButton } from './components.js';
3
3
  import { Font } from './font.js';
4
+ import { mapStyle, parseColor, expandEdges, mapColumnWidth, mergeFonts, recordCanvasOperations, mapListMarker, HEADING_DEFAULTS, STRONG_DEFAULTS, EM_DEFAULTS, CODE_DEFAULTS, LINK_DEFAULTS, buildBarChartKind, buildLineChartKind, buildPieChartKind, buildAreaChartKind, buildDotPlotKind } from '@formepdf/shared';
4
5
  import { isRefMarker, getRefPath, isEachMarker, getEachPath, getEachTemplate, isExprMarker, getExpr, REF_SENTINEL, REF_SENTINEL_END, } from './template-proxy.js';
5
6
  const VALID_PARENTS = {
6
7
  Page: {
@@ -263,6 +264,24 @@ function serializeChild(child, parent = null) {
263
264
  if (element.type === Text) {
264
265
  return serializeText(element);
265
266
  }
267
+ if (element.type === H1)
268
+ return serializeHeading(element, 1);
269
+ if (element.type === H2)
270
+ return serializeHeading(element, 2);
271
+ if (element.type === H3)
272
+ return serializeHeading(element, 3);
273
+ if (element.type === H4)
274
+ return serializeHeading(element, 4);
275
+ if (element.type === H5)
276
+ return serializeHeading(element, 5);
277
+ if (element.type === H6)
278
+ return serializeHeading(element, 6);
279
+ if (element.type === OrderedList)
280
+ return serializeList(element, true);
281
+ if (element.type === UnorderedList)
282
+ return serializeList(element, false);
283
+ if (element.type === ListItem)
284
+ return serializeListItem(element);
266
285
  if (element.type === Image) {
267
286
  return serializeImage(element);
268
287
  }
@@ -375,32 +394,71 @@ function serializeView(element, _parent = null) {
375
394
  node.href = props.href;
376
395
  return node;
377
396
  }
397
+ /** Return the component-default style for a recognized inline component,
398
+ * or `null` if the element isn't a recognized inline component.
399
+ * `Text` returns `{}` because it carries no defaults beyond the user's style. */
400
+ function inlineDefaults(type) {
401
+ switch (type) {
402
+ case Text: return {};
403
+ case Strong: return STRONG_DEFAULTS;
404
+ case Em: return EM_DEFAULTS;
405
+ case Code: return CODE_DEFAULTS;
406
+ case Link: return LINK_DEFAULTS;
407
+ default: return null;
408
+ }
409
+ }
410
+ /**
411
+ * Recursively flatten children of a `<Text>` into TextRuns, accumulating
412
+ * styles and href as we descend. Outer style is overlaid by each inline
413
+ * component's defaults, which are in turn overlaid by the user-supplied
414
+ * `style` on that element — so user style wins at every level while
415
+ * still inheriting whatever wasn't explicitly set.
416
+ *
417
+ * E.g. `<Strong><Em>both</Em></Strong>` produces a single run with
418
+ * `{ fontWeight: 700, fontStyle: 'italic' }`. A `<Link href>` nested in a
419
+ * `<Strong>` produces a bold underlined blue run with the href set.
420
+ */
421
+ function buildTextRuns(children, accStyle = {}, accHref = undefined) {
422
+ const out = [];
423
+ const elements = flattenChildren(children);
424
+ for (const child of elements) {
425
+ if (child === null || child === undefined || typeof child === 'boolean')
426
+ continue;
427
+ if (typeof child === 'string' || typeof child === 'number') {
428
+ const content = String(child);
429
+ if (content === '')
430
+ continue;
431
+ const run = { content };
432
+ if (Object.keys(accStyle).length > 0)
433
+ run.style = mapStyle(accStyle);
434
+ if (accHref)
435
+ run.href = accHref;
436
+ out.push(run);
437
+ continue;
438
+ }
439
+ if (!isValidElement(child))
440
+ continue;
441
+ const defaults = inlineDefaults(child.type);
442
+ if (defaults === null)
443
+ continue; // unknown element inside <Text> — skip
444
+ const childProps = child.props;
445
+ // Cascade: outer accumulated → this component's defaults → user style.
446
+ // Later spreads win, so user style overrides defaults and outer.
447
+ const nextStyle = { ...accStyle, ...defaults, ...(childProps.style || {}) };
448
+ const nextHref = childProps.href ?? accHref;
449
+ out.push(...buildTextRuns(childProps.children, nextStyle, nextHref));
450
+ }
451
+ return out;
452
+ }
378
453
  function serializeText(element) {
379
454
  const props = element.props;
380
455
  const childElements = flattenChildren(props.children);
381
- // Check if any child is a <Text> element (inline runs)
382
- const hasTextChild = childElements.some(c => isValidElement(c) && c.type === Text);
456
+ // Detect mixed content: any inline element child (<Text>, <Strong>, <Em>,
457
+ // <Code>, <Link>) means we need TextRuns rather than a flat content string.
458
+ const hasInlineChild = childElements.some(c => isValidElement(c) && inlineDefaults(c.type) !== null);
383
459
  const kind = { type: 'Text', content: '' };
384
- if (hasTextChild) {
385
- // Build runs from children
386
- const runs = [];
387
- for (const child of childElements) {
388
- if (typeof child === 'string' || typeof child === 'number') {
389
- runs.push({ content: String(child) });
390
- }
391
- else if (isValidElement(child) && child.type === Text) {
392
- const childProps = child.props;
393
- const run = {
394
- content: flattenTextContent(childProps.children),
395
- };
396
- if (childProps.style)
397
- run.style = mapStyle(childProps.style);
398
- if (childProps.href)
399
- run.href = childProps.href;
400
- runs.push(run);
401
- }
402
- }
403
- kind.runs = runs;
460
+ if (hasInlineChild) {
461
+ kind.runs = buildTextRuns(props.children);
404
462
  }
405
463
  else {
406
464
  kind.content = flattenTextContent(props.children);
@@ -417,6 +475,94 @@ function serializeText(element) {
417
475
  node.bookmark = props.bookmark;
418
476
  return node;
419
477
  }
478
+ /**
479
+ * Serialize an H1-H6 element. Mirrors serializeText for the children
480
+ * machinery (mixed strings + inline-formatting components produce runs)
481
+ * but emits the engine's `Heading { level }` node kind so the tagged-PDF
482
+ * builder can pick up the semantic role. Default styles per level are
483
+ * merged BEFORE the user's `style` prop, so user values win.
484
+ */
485
+ function serializeHeading(element, level) {
486
+ const props = element.props;
487
+ const childElements = flattenChildren(props.children);
488
+ const hasInlineChild = childElements.some((c) => isValidElement(c) && inlineDefaults(c.type) !== null);
489
+ const kind = {
490
+ type: 'Heading',
491
+ level,
492
+ content: '',
493
+ };
494
+ if (hasInlineChild) {
495
+ kind.runs = buildTextRuns(props.children);
496
+ }
497
+ else {
498
+ kind.content = flattenTextContent(props.children);
499
+ }
500
+ if (props.href)
501
+ kind.href = props.href;
502
+ // Defaults underlay; user style wins on conflicting keys.
503
+ const mergedStyle = { ...HEADING_DEFAULTS[level], ...(props.style || {}) };
504
+ const node = {
505
+ kind,
506
+ style: mapStyle(mergedStyle),
507
+ children: [],
508
+ sourceLocation: extractSourceLocation(element),
509
+ };
510
+ if (props.bookmark)
511
+ node.bookmark = props.bookmark;
512
+ return node;
513
+ }
514
+ function serializeList(element, ordered) {
515
+ const props = element.props;
516
+ const markerType = ordered
517
+ ? mapListMarker(props.type, 'decimal')
518
+ : mapListMarker(props.marker, 'disc');
519
+ const start = typeof props.start === 'number' && props.start >= 1 ? props.start : 1;
520
+ // Children must be ListItems — anything else is silently dropped to
521
+ // keep the serializer tolerant. (We don't throw on stray content because
522
+ // a Fragment / null child in JSX is too common to be a real error.)
523
+ const childElements = flattenChildren(props.children).filter((c) => isValidElement(c) && c.type === ListItem);
524
+ const children = childElements.map((c) => serializeListItem(c));
525
+ const node = {
526
+ kind: { type: 'List', ordered, marker_type: markerType, start },
527
+ style: mapStyle(props.style),
528
+ children,
529
+ sourceLocation: extractSourceLocation(element),
530
+ };
531
+ if (props.bookmark)
532
+ node.bookmark = props.bookmark;
533
+ return node;
534
+ }
535
+ function serializeListItem(element) {
536
+ const props = element.props;
537
+ // ListItem content is layed out by the engine using layout_children, so
538
+ // we serialize whatever the user put inside as the node's children. This
539
+ // covers plain strings, JSX text, nested lists, formatted runs via
540
+ // <Text>, etc.
541
+ const rawChildren = flattenChildren(props.children);
542
+ const children = [];
543
+ for (const c of rawChildren) {
544
+ if (typeof c === 'string' || typeof c === 'number') {
545
+ // Auto-wrap raw strings in a Text node so the engine has something
546
+ // concrete to render. Matches the convention everywhere else.
547
+ children.push({
548
+ kind: { type: 'Text', content: String(c) },
549
+ style: {},
550
+ children: [],
551
+ });
552
+ }
553
+ else if (isValidElement(c)) {
554
+ const node = serializeChild(c, null);
555
+ if (node)
556
+ children.push(node);
557
+ }
558
+ }
559
+ return {
560
+ kind: { type: 'ListItem' },
561
+ style: mapStyle(props.style),
562
+ children,
563
+ sourceLocation: extractSourceLocation(element),
564
+ };
565
+ }
420
566
  function serializeImage(element) {
421
567
  const props = element.props;
422
568
  const kind = { type: 'Image', src: props.src };
@@ -674,42 +820,7 @@ function serializeRadioButton(element) {
674
820
  }
675
821
  function serializeCanvas(element) {
676
822
  const props = element.props;
677
- const operations = [];
678
- // Create a recording context that captures draw calls as CanvasOp[]
679
- const ctx = {
680
- moveTo(x, y) { operations.push({ op: 'MoveTo', x, y }); },
681
- lineTo(x, y) { operations.push({ op: 'LineTo', x, y }); },
682
- bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
683
- operations.push({ op: 'BezierCurveTo', cp1x, cp1y, cp2x, cp2y, x, y });
684
- },
685
- quadraticCurveTo(cpx, cpy, x, y) {
686
- operations.push({ op: 'QuadraticCurveTo', cpx, cpy, x, y });
687
- },
688
- closePath() { operations.push({ op: 'ClosePath' }); },
689
- rect(x, y, w, h) { operations.push({ op: 'Rect', x, y, width: w, height: h }); },
690
- circle(cx, cy, r) { operations.push({ op: 'Circle', cx, cy, r }); },
691
- ellipse(cx, cy, rx, ry) { operations.push({ op: 'Ellipse', cx, cy, rx, ry }); },
692
- arc(cx, cy, r, startAngle, endAngle, counterclockwise = false) {
693
- operations.push({ op: 'Arc', cx, cy, r, start_angle: startAngle, end_angle: endAngle, counterclockwise });
694
- },
695
- line(x1, y1, x2, y2) {
696
- operations.push({ op: 'MoveTo', x: x1, y: y1 });
697
- operations.push({ op: 'LineTo', x: x2, y: y2 });
698
- operations.push({ op: 'Stroke' });
699
- },
700
- stroke() { operations.push({ op: 'Stroke' }); },
701
- fill() { operations.push({ op: 'Fill' }); },
702
- fillAndStroke() { operations.push({ op: 'FillAndStroke' }); },
703
- setFillColor(r, g, b) { operations.push({ op: 'SetFillColor', r, g, b }); },
704
- setStrokeColor(r, g, b) { operations.push({ op: 'SetStrokeColor', r, g, b }); },
705
- setLineWidth(w) { operations.push({ op: 'SetLineWidth', width: w }); },
706
- setLineCap(cap) { operations.push({ op: 'SetLineCap', cap }); },
707
- setLineJoin(join) { operations.push({ op: 'SetLineJoin', join }); },
708
- save() { operations.push({ op: 'Save' }); },
709
- restore() { operations.push({ op: 'Restore' }); },
710
- };
711
- // Execute the draw callback to record operations
712
- props.draw(ctx);
823
+ const operations = recordCanvasOperations(props.draw);
713
824
  return {
714
825
  kind: { type: 'Canvas', width: props.width, height: props.height, operations },
715
826
  style: mapStyle(props.style),
@@ -740,21 +851,8 @@ function serializeWatermark(element) {
740
851
  }
741
852
  function serializeBarChart(element) {
742
853
  const props = element.props;
743
- const kind = {
744
- type: 'BarChart',
745
- data: props.data.map(d => ({ label: d.label, value: d.value, color: d.color })),
746
- width: props.width,
747
- height: props.height,
748
- show_labels: props.showLabels ?? true,
749
- show_values: props.showValues ?? false,
750
- show_grid: props.showGrid ?? false,
751
- };
752
- if (props.color !== undefined)
753
- kind.color = props.color;
754
- if (props.title !== undefined)
755
- kind.title = props.title;
756
854
  return {
757
- kind,
855
+ kind: buildBarChartKind(props),
758
856
  style: mapStyle(props.style),
759
857
  children: [],
760
858
  sourceLocation: extractSourceLocation(element),
@@ -762,19 +860,8 @@ function serializeBarChart(element) {
762
860
  }
763
861
  function serializeLineChart(element) {
764
862
  const props = element.props;
765
- const kind = {
766
- type: 'LineChart',
767
- series: props.series.map(s => ({ name: s.name, data: s.data, color: s.color })),
768
- labels: props.labels,
769
- width: props.width,
770
- height: props.height,
771
- show_points: props.showPoints ?? false,
772
- show_grid: props.showGrid ?? false,
773
- };
774
- if (props.title !== undefined)
775
- kind.title = props.title;
776
863
  return {
777
- kind,
864
+ kind: buildLineChartKind(props),
778
865
  style: mapStyle(props.style),
779
866
  children: [],
780
867
  sourceLocation: extractSourceLocation(element),
@@ -782,18 +869,8 @@ function serializeLineChart(element) {
782
869
  }
783
870
  function serializePieChart(element) {
784
871
  const props = element.props;
785
- const kind = {
786
- type: 'PieChart',
787
- data: props.data.map(d => ({ label: d.label, value: d.value, color: d.color })),
788
- width: props.width,
789
- height: props.height,
790
- donut: props.donut ?? false,
791
- show_legend: props.showLegend ?? false,
792
- };
793
- if (props.title !== undefined)
794
- kind.title = props.title;
795
872
  return {
796
- kind,
873
+ kind: buildPieChartKind(props),
797
874
  style: mapStyle(props.style),
798
875
  children: [],
799
876
  sourceLocation: extractSourceLocation(element),
@@ -801,18 +878,8 @@ function serializePieChart(element) {
801
878
  }
802
879
  function serializeAreaChart(element) {
803
880
  const props = element.props;
804
- const kind = {
805
- type: 'AreaChart',
806
- series: props.series.map(s => ({ name: s.name, data: s.data, color: s.color })),
807
- labels: props.labels,
808
- width: props.width,
809
- height: props.height,
810
- show_grid: props.showGrid ?? false,
811
- };
812
- if (props.title !== undefined)
813
- kind.title = props.title;
814
881
  return {
815
- kind,
882
+ kind: buildAreaChartKind(props),
816
883
  style: mapStyle(props.style),
817
884
  children: [],
818
885
  sourceLocation: extractSourceLocation(element),
@@ -820,28 +887,8 @@ function serializeAreaChart(element) {
820
887
  }
821
888
  function serializeDotPlot(element) {
822
889
  const props = element.props;
823
- const kind = {
824
- type: 'DotPlot',
825
- groups: props.groups.map(g => ({ name: g.name, color: g.color, data: g.data })),
826
- width: props.width,
827
- height: props.height,
828
- show_legend: props.showLegend ?? false,
829
- dot_size: props.dotSize ?? 4,
830
- };
831
- if (props.xMin !== undefined)
832
- kind.x_min = props.xMin;
833
- if (props.xMax !== undefined)
834
- kind.x_max = props.xMax;
835
- if (props.yMin !== undefined)
836
- kind.y_min = props.yMin;
837
- if (props.yMax !== undefined)
838
- kind.y_max = props.yMax;
839
- if (props.xLabel !== undefined)
840
- kind.x_label = props.xLabel;
841
- if (props.yLabel !== undefined)
842
- kind.y_label = props.yLabel;
843
890
  return {
844
- kind,
891
+ kind: buildDotPlotKind(props),
845
892
  style: mapStyle(props.style),
846
893
  children: [],
847
894
  sourceLocation: extractSourceLocation(element),
@@ -907,869 +954,6 @@ function flattenTextContent(children) {
907
954
  }
908
955
  return String(children);
909
956
  }
910
- // ─── Style mapping ──────────────────────────────────────────────────
911
- const FLEX_DIRECTION_MAP = {
912
- 'row': 'Row',
913
- 'column': 'Column',
914
- 'row-reverse': 'RowReverse',
915
- 'column-reverse': 'ColumnReverse',
916
- };
917
- const JUSTIFY_CONTENT_MAP = {
918
- 'flex-start': 'FlexStart',
919
- 'flex-end': 'FlexEnd',
920
- 'center': 'Center',
921
- 'space-between': 'SpaceBetween',
922
- 'space-around': 'SpaceAround',
923
- 'space-evenly': 'SpaceEvenly',
924
- };
925
- const ALIGN_ITEMS_MAP = {
926
- 'flex-start': 'FlexStart',
927
- 'flex-end': 'FlexEnd',
928
- 'center': 'Center',
929
- 'stretch': 'Stretch',
930
- 'baseline': 'Baseline',
931
- };
932
- const FLEX_WRAP_MAP = {
933
- 'nowrap': 'NoWrap',
934
- 'wrap': 'Wrap',
935
- 'wrap-reverse': 'WrapReverse',
936
- };
937
- const ALIGN_CONTENT_MAP = {
938
- 'flex-start': 'FlexStart',
939
- 'flex-end': 'FlexEnd',
940
- 'center': 'Center',
941
- 'space-between': 'SpaceBetween',
942
- 'space-around': 'SpaceAround',
943
- 'space-evenly': 'SpaceEvenly',
944
- 'stretch': 'Stretch',
945
- };
946
- const FONT_STYLE_MAP = {
947
- 'normal': 'Normal',
948
- 'italic': 'Italic',
949
- 'oblique': 'Oblique',
950
- };
951
- const TEXT_ALIGN_MAP = {
952
- 'left': 'Left',
953
- 'right': 'Right',
954
- 'center': 'Center',
955
- 'justify': 'Justify',
956
- };
957
- const TEXT_DECORATION_MAP = {
958
- 'none': 'None',
959
- 'underline': 'Underline',
960
- 'line-through': 'LineThrough',
961
- };
962
- const TEXT_TRANSFORM_MAP = {
963
- 'none': 'None',
964
- 'uppercase': 'Uppercase',
965
- 'lowercase': 'Lowercase',
966
- 'capitalize': 'Capitalize',
967
- };
968
- const HYPHENS_MAP = {
969
- 'none': 'none',
970
- 'manual': 'manual',
971
- 'auto': 'auto',
972
- };
973
- const TEXT_OVERFLOW_MAP = {
974
- 'wrap': 'Wrap',
975
- 'ellipsis': 'Ellipsis',
976
- 'clip': 'Clip',
977
- };
978
- const LINE_BREAKING_MAP = {
979
- 'optimal': 'optimal',
980
- 'greedy': 'greedy',
981
- };
982
- const OVERFLOW_MAP = {
983
- 'visible': 'Visible',
984
- 'hidden': 'Hidden',
985
- };
986
- export function mapStyle(style) {
987
- if (!style)
988
- return {};
989
- const result = {};
990
- // Dimensions
991
- if (style.width !== undefined)
992
- result.width = mapDimension(style.width);
993
- if (style.height !== undefined)
994
- result.height = mapDimension(style.height);
995
- if (style.minWidth !== undefined)
996
- result.minWidth = mapDimension(style.minWidth);
997
- if (style.minHeight !== undefined)
998
- result.minHeight = mapDimension(style.minHeight);
999
- if (style.maxWidth !== undefined)
1000
- result.maxWidth = mapDimension(style.maxWidth);
1001
- if (style.maxHeight !== undefined)
1002
- result.maxHeight = mapDimension(style.maxHeight);
1003
- // Edges (individual > axis > base)
1004
- if (style.padding !== undefined || style.paddingTop !== undefined || style.paddingRight !== undefined || style.paddingBottom !== undefined || style.paddingLeft !== undefined || style.paddingHorizontal !== undefined || style.paddingVertical !== undefined) {
1005
- const base = style.padding !== undefined ? expandEdges(style.padding) : { top: 0, right: 0, bottom: 0, left: 0 };
1006
- const vt = style.paddingVertical ?? base.top;
1007
- const vb = style.paddingVertical ?? base.bottom;
1008
- const hl = style.paddingHorizontal ?? base.left;
1009
- const hr = style.paddingHorizontal ?? base.right;
1010
- result.padding = {
1011
- top: style.paddingTop ?? vt,
1012
- right: style.paddingRight ?? hr,
1013
- bottom: style.paddingBottom ?? vb,
1014
- left: style.paddingLeft ?? hl,
1015
- };
1016
- }
1017
- if (style.margin !== undefined || style.marginTop !== undefined || style.marginRight !== undefined || style.marginBottom !== undefined || style.marginLeft !== undefined || style.marginHorizontal !== undefined || style.marginVertical !== undefined) {
1018
- const base = style.margin !== undefined ? expandMarginEdges(style.margin) : { top: 0, right: 0, bottom: 0, left: 0 };
1019
- const vt = style.marginVertical ?? base.top;
1020
- const vb = style.marginVertical ?? base.bottom;
1021
- const hl = style.marginHorizontal ?? base.left;
1022
- const hr = style.marginHorizontal ?? base.right;
1023
- result.margin = {
1024
- top: style.marginTop ?? vt,
1025
- right: style.marginRight ?? hr,
1026
- bottom: style.marginBottom ?? vb,
1027
- left: style.marginLeft ?? hl,
1028
- };
1029
- }
1030
- // Flex shorthand: flex: N → flexGrow: N, flexShrink: 1, flexBasis: 0
1031
- if (style.flex !== undefined) {
1032
- if (style.flexGrow === undefined)
1033
- result.flexGrow = style.flex;
1034
- if (style.flexShrink === undefined)
1035
- result.flexShrink = 1;
1036
- if (style.flexBasis === undefined)
1037
- result.flexBasis = { Pt: 0 };
1038
- }
1039
- // Flex
1040
- if (style.flexDirection !== undefined)
1041
- result.flexDirection = FLEX_DIRECTION_MAP[style.flexDirection];
1042
- if (style.justifyContent !== undefined)
1043
- result.justifyContent = JUSTIFY_CONTENT_MAP[style.justifyContent];
1044
- if (style.alignItems !== undefined)
1045
- result.alignItems = ALIGN_ITEMS_MAP[style.alignItems];
1046
- if (style.alignSelf !== undefined)
1047
- result.alignSelf = ALIGN_ITEMS_MAP[style.alignSelf];
1048
- if (style.flexWrap !== undefined)
1049
- result.flexWrap = FLEX_WRAP_MAP[style.flexWrap];
1050
- if (style.alignContent !== undefined)
1051
- result.alignContent = ALIGN_CONTENT_MAP[style.alignContent];
1052
- if (style.flexGrow !== undefined)
1053
- result.flexGrow = style.flexGrow;
1054
- if (style.flexShrink !== undefined)
1055
- result.flexShrink = style.flexShrink;
1056
- if (style.flexBasis !== undefined)
1057
- result.flexBasis = mapDimension(style.flexBasis);
1058
- if (style.gap !== undefined)
1059
- result.gap = style.gap;
1060
- if (style.rowGap !== undefined)
1061
- result.rowGap = style.rowGap;
1062
- if (style.columnGap !== undefined)
1063
- result.columnGap = style.columnGap;
1064
- // Display mode
1065
- if (style.display !== undefined) {
1066
- result.display = style.display === 'grid' ? 'Grid' : 'Flex';
1067
- }
1068
- // CSS Grid
1069
- if (style.gridTemplateColumns !== undefined) {
1070
- result.gridTemplateColumns = parseGridTemplate(style.gridTemplateColumns);
1071
- }
1072
- if (style.gridTemplateRows !== undefined) {
1073
- result.gridTemplateRows = parseGridTemplate(style.gridTemplateRows);
1074
- }
1075
- if (style.gridAutoRows !== undefined) {
1076
- result.gridAutoRows = mapGridTrack(style.gridAutoRows);
1077
- }
1078
- if (style.gridAutoColumns !== undefined) {
1079
- result.gridAutoColumns = mapGridTrack(style.gridAutoColumns);
1080
- }
1081
- // Grid placement (individual props → single gridPlacement object)
1082
- if (style.gridColumnStart !== undefined || style.gridColumnEnd !== undefined ||
1083
- style.gridRowStart !== undefined || style.gridRowEnd !== undefined ||
1084
- style.gridColumnSpan !== undefined || style.gridRowSpan !== undefined) {
1085
- const placement = {};
1086
- if (style.gridColumnStart !== undefined)
1087
- placement.columnStart = style.gridColumnStart;
1088
- if (style.gridColumnEnd !== undefined)
1089
- placement.columnEnd = style.gridColumnEnd;
1090
- if (style.gridRowStart !== undefined)
1091
- placement.rowStart = style.gridRowStart;
1092
- if (style.gridRowEnd !== undefined)
1093
- placement.rowEnd = style.gridRowEnd;
1094
- if (style.gridColumnSpan !== undefined)
1095
- placement.columnSpan = style.gridColumnSpan;
1096
- if (style.gridRowSpan !== undefined)
1097
- placement.rowSpan = style.gridRowSpan;
1098
- result.gridPlacement = placement;
1099
- }
1100
- // Typography
1101
- if (style.fontFamily !== undefined)
1102
- result.fontFamily = style.fontFamily;
1103
- if (style.fontSize !== undefined)
1104
- result.fontSize = style.fontSize;
1105
- if (style.fontWeight !== undefined) {
1106
- result.fontWeight = style.fontWeight === 'bold' ? 700 : style.fontWeight === 'normal' ? 400 : style.fontWeight;
1107
- }
1108
- if (style.fontStyle !== undefined)
1109
- result.fontStyle = FONT_STYLE_MAP[style.fontStyle];
1110
- if (style.lineHeight !== undefined)
1111
- result.lineHeight = style.lineHeight;
1112
- if (style.textAlign !== undefined)
1113
- result.textAlign = TEXT_ALIGN_MAP[style.textAlign];
1114
- if (style.letterSpacing !== undefined)
1115
- result.letterSpacing = style.letterSpacing;
1116
- if (style.wordSpacing !== undefined)
1117
- result.wordSpacing = style.wordSpacing;
1118
- if (style.boxShadow !== undefined) {
1119
- const parsed = parseBoxShadow(style.boxShadow);
1120
- if (parsed)
1121
- result.boxShadow = parsed;
1122
- }
1123
- if (style.textDecoration !== undefined)
1124
- result.textDecoration = TEXT_DECORATION_MAP[style.textDecoration];
1125
- if (style.textTransform !== undefined)
1126
- result.textTransform = TEXT_TRANSFORM_MAP[style.textTransform];
1127
- if (style.hyphens !== undefined)
1128
- result.hyphens = HYPHENS_MAP[style.hyphens];
1129
- if (style.lang !== undefined)
1130
- result.lang = style.lang;
1131
- if (style.direction !== undefined)
1132
- result.direction = style.direction;
1133
- if (style.textOverflow !== undefined)
1134
- result.textOverflow = TEXT_OVERFLOW_MAP[style.textOverflow];
1135
- if (style.lineBreaking !== undefined)
1136
- result.lineBreaking = LINE_BREAKING_MAP[style.lineBreaking];
1137
- if (style.overflow !== undefined)
1138
- result.overflow = OVERFLOW_MAP[style.overflow];
1139
- // Color
1140
- if (style.color !== undefined)
1141
- result.color = parseColor(style.color);
1142
- if (style.backgroundColor !== undefined)
1143
- result.backgroundColor = parseColor(style.backgroundColor);
1144
- if (style.background !== undefined) {
1145
- const parsed = parseBackground(style.background);
1146
- if (parsed) {
1147
- if (parsed.type === 'color') {
1148
- // Solid color string in `background`: route to backgroundColor for
1149
- // engine compatibility (Background::Color also works, but
1150
- // backgroundColor is the canonical solid path).
1151
- if (result.backgroundColor === undefined)
1152
- result.backgroundColor = parsed.value;
1153
- }
1154
- else {
1155
- result.background = parsed;
1156
- }
1157
- }
1158
- }
1159
- if (style.opacity !== undefined)
1160
- result.opacity = style.opacity;
1161
- // Border — cascade: border < borderTop/Right/Bottom/Left < borderWidth/borderColor < borderTopWidth/borderTopColor
1162
- // Step 1: Parse string shorthands into intermediate per-side values
1163
- let shortWidth = { top: undefined, right: undefined, bottom: undefined, left: undefined };
1164
- let shortColor = { top: undefined, right: undefined, bottom: undefined, left: undefined };
1165
- if (style.border !== undefined) {
1166
- const parsed = parseBorderString(style.border);
1167
- if (parsed.width !== undefined)
1168
- shortWidth = { top: parsed.width, right: parsed.width, bottom: parsed.width, left: parsed.width };
1169
- if (parsed.color !== undefined)
1170
- shortColor = { top: parsed.color, right: parsed.color, bottom: parsed.color, left: parsed.color };
1171
- }
1172
- // Per-side string shorthands override all-side shorthand
1173
- for (const [side, prop] of [['top', 'borderTop'], ['right', 'borderRight'], ['bottom', 'borderBottom'], ['left', 'borderLeft']]) {
1174
- const val = style[prop];
1175
- if (val === undefined)
1176
- continue;
1177
- if (typeof val === 'number') {
1178
- shortWidth[side] = val;
1179
- }
1180
- else {
1181
- const parsed = parseBorderString(val);
1182
- if (parsed.width !== undefined)
1183
- shortWidth[side] = parsed.width;
1184
- if (parsed.color !== undefined)
1185
- shortColor[side] = parsed.color;
1186
- }
1187
- }
1188
- // Step 2: Build borderWidth — existing borderWidth/borderTopWidth override shorthands
1189
- const hasBorderWidth = style.borderWidth !== undefined || style.borderTopWidth !== undefined || style.borderRightWidth !== undefined || style.borderBottomWidth !== undefined || style.borderLeftWidth !== undefined;
1190
- const hasShortWidth = shortWidth.top !== undefined || shortWidth.right !== undefined || shortWidth.bottom !== undefined || shortWidth.left !== undefined;
1191
- if (hasBorderWidth || hasShortWidth) {
1192
- const base = style.borderWidth !== undefined
1193
- ? expandEdgeValues(style.borderWidth)
1194
- : { top: shortWidth.top ?? 0, right: shortWidth.right ?? 0, bottom: shortWidth.bottom ?? 0, left: shortWidth.left ?? 0 };
1195
- result.borderWidth = {
1196
- top: style.borderTopWidth ?? base.top,
1197
- right: style.borderRightWidth ?? base.right,
1198
- bottom: style.borderBottomWidth ?? base.bottom,
1199
- left: style.borderLeftWidth ?? base.left,
1200
- };
1201
- }
1202
- // Step 3: Build borderColor — existing borderColor/borderTopColor override shorthands
1203
- const hasBorderColor = style.borderColor !== undefined || style.borderTopColor !== undefined || style.borderRightColor !== undefined || style.borderBottomColor !== undefined || style.borderLeftColor !== undefined;
1204
- const hasShortColor = shortColor.top !== undefined || shortColor.right !== undefined || shortColor.bottom !== undefined || shortColor.left !== undefined;
1205
- if (hasBorderColor || hasShortColor) {
1206
- const defaultColor = parseColor('#000000');
1207
- let base = {
1208
- top: shortColor.top ?? defaultColor,
1209
- right: shortColor.right ?? defaultColor,
1210
- bottom: shortColor.bottom ?? defaultColor,
1211
- left: shortColor.left ?? defaultColor,
1212
- };
1213
- if (typeof style.borderColor === 'string') {
1214
- const c = parseColor(style.borderColor);
1215
- base = { top: c, right: c, bottom: c, left: c };
1216
- }
1217
- else if (style.borderColor && typeof style.borderColor === 'object') {
1218
- base = {
1219
- top: parseColor(style.borderColor.top),
1220
- right: parseColor(style.borderColor.right),
1221
- bottom: parseColor(style.borderColor.bottom),
1222
- left: parseColor(style.borderColor.left),
1223
- };
1224
- }
1225
- result.borderColor = {
1226
- top: style.borderTopColor ? parseColor(style.borderTopColor) : base.top,
1227
- right: style.borderRightColor ? parseColor(style.borderRightColor) : base.right,
1228
- bottom: style.borderBottomColor ? parseColor(style.borderBottomColor) : base.bottom,
1229
- left: style.borderLeftColor ? parseColor(style.borderLeftColor) : base.left,
1230
- };
1231
- }
1232
- if (style.borderRadius !== undefined || style.borderTopLeftRadius !== undefined || style.borderTopRightRadius !== undefined || style.borderBottomRightRadius !== undefined || style.borderBottomLeftRadius !== undefined) {
1233
- const base = style.borderRadius !== undefined ? expandCorners(style.borderRadius) : { top_left: 0, top_right: 0, bottom_right: 0, bottom_left: 0 };
1234
- result.borderRadius = {
1235
- top_left: style.borderTopLeftRadius ?? base.top_left,
1236
- top_right: style.borderTopRightRadius ?? base.top_right,
1237
- bottom_right: style.borderBottomRightRadius ?? base.bottom_right,
1238
- bottom_left: style.borderBottomLeftRadius ?? base.bottom_left,
1239
- };
1240
- }
1241
- // Positioning
1242
- if (style.position !== undefined) {
1243
- result.position = style.position === 'absolute' ? 'Absolute' : 'Relative';
1244
- }
1245
- if (style.top !== undefined)
1246
- result.top = style.top;
1247
- if (style.right !== undefined)
1248
- result.right = style.right;
1249
- if (style.bottom !== undefined)
1250
- result.bottom = style.bottom;
1251
- if (style.left !== undefined)
1252
- result.left = style.left;
1253
- // Page behavior
1254
- if (style.wrap !== undefined)
1255
- result.wrap = style.wrap;
1256
- if (style.breakBefore !== undefined)
1257
- result.breakBefore = style.breakBefore;
1258
- if (style.minWidowLines !== undefined)
1259
- result.minWidowLines = style.minWidowLines;
1260
- if (style.minOrphanLines !== undefined)
1261
- result.minOrphanLines = style.minOrphanLines;
1262
- return result;
1263
- }
1264
- // ─── Grid helpers ───────────────────────────────────────────────────
1265
- /** Convert a single GridTrackSize to the Forme JSON format. */
1266
- function mapGridTrack(track) {
1267
- if (typeof track === 'number')
1268
- return { Pt: track };
1269
- if (track === 'auto')
1270
- return 'Auto';
1271
- if (typeof track === 'string') {
1272
- const frMatch = track.match(/^([0-9.]+)fr$/);
1273
- if (frMatch)
1274
- return { Fr: parseFloat(frMatch[1]) };
1275
- // Try numeric string
1276
- const num = parseFloat(track);
1277
- if (!isNaN(num))
1278
- return { Pt: num };
1279
- return 'Auto';
1280
- }
1281
- if (typeof track === 'object' && 'min' in track && 'max' in track) {
1282
- return { MinMax: [mapGridTrack(track.min), mapGridTrack(track.max)] };
1283
- }
1284
- return 'Auto';
1285
- }
1286
- /**
1287
- * Expand `repeat(N, tracks)` in a grid template string.
1288
- * E.g. `"repeat(3, 1fr)"` → `"1fr 1fr 1fr"`
1289
- * `"200 repeat(2, 1fr) 200"` → `"200 1fr 1fr 200"`
1290
- */
1291
- function expandRepeat(input) {
1292
- return input.replace(/repeat\(\s*(\d+)\s*,\s*([^)]+)\)/g, (_match, count, tracks) => {
1293
- return (tracks.trim() + ' ').repeat(parseInt(count, 10)).trim();
1294
- });
1295
- }
1296
- /**
1297
- * Parse a grid template string shorthand into an array of FormeGridTrackSize.
1298
- * E.g. `"1fr 2fr 200"` → `[{Fr:1}, {Fr:2}, {Pt:200}]`
1299
- * Supports `repeat(N, tracks)` syntax.
1300
- */
1301
- function parseGridTemplate(value) {
1302
- if (Array.isArray(value)) {
1303
- return value.map(mapGridTrack);
1304
- }
1305
- const expanded = expandRepeat(value);
1306
- return expanded.split(/\s+/).filter(Boolean).map((token) => {
1307
- if (token === 'auto')
1308
- return 'Auto';
1309
- const frMatch = token.match(/^([0-9.]+)fr$/);
1310
- if (frMatch)
1311
- return { Fr: parseFloat(frMatch[1]) };
1312
- const num = parseFloat(token);
1313
- if (!isNaN(num))
1314
- return { Pt: num };
1315
- return 'Auto';
1316
- });
1317
- }
1318
- export function mapDimension(val) {
1319
- if (typeof val === 'number') {
1320
- return { Pt: val };
1321
- }
1322
- if (val === 'auto')
1323
- return 'Auto';
1324
- const match = val.match(/^([0-9.]+)%$/);
1325
- if (match) {
1326
- return { Percent: parseFloat(match[1]) };
1327
- }
1328
- // Try to parse as a number (e.g. "100" without units)
1329
- const num = parseFloat(val);
1330
- if (!isNaN(num)) {
1331
- return { Pt: num };
1332
- }
1333
- return 'Auto';
1334
- }
1335
- export function parseColor(hex) {
1336
- const s = hex.trim();
1337
- // rgba(r, g, b, a)
1338
- const rgbaMatch = s.match(/^rgba\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/);
1339
- if (rgbaMatch) {
1340
- return {
1341
- r: parseFloat(rgbaMatch[1]) / 255,
1342
- g: parseFloat(rgbaMatch[2]) / 255,
1343
- b: parseFloat(rgbaMatch[3]) / 255,
1344
- a: parseFloat(rgbaMatch[4]),
1345
- };
1346
- }
1347
- // rgb(r, g, b)
1348
- const rgbMatch = s.match(/^rgb\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/);
1349
- if (rgbMatch) {
1350
- return {
1351
- r: parseFloat(rgbMatch[1]) / 255,
1352
- g: parseFloat(rgbMatch[2]) / 255,
1353
- b: parseFloat(rgbMatch[3]) / 255,
1354
- a: 1,
1355
- };
1356
- }
1357
- const h = s.replace(/^#/, '');
1358
- if (h.length === 3) {
1359
- const r = parseInt(h[0] + h[0], 16) / 255;
1360
- const g = parseInt(h[1] + h[1], 16) / 255;
1361
- const b = parseInt(h[2] + h[2], 16) / 255;
1362
- return { r, g, b, a: 1 };
1363
- }
1364
- if (h.length === 6) {
1365
- const r = parseInt(h.slice(0, 2), 16) / 255;
1366
- const g = parseInt(h.slice(2, 4), 16) / 255;
1367
- const b = parseInt(h.slice(4, 6), 16) / 255;
1368
- return { r, g, b, a: 1 };
1369
- }
1370
- if (h.length === 8) {
1371
- const r = parseInt(h.slice(0, 2), 16) / 255;
1372
- const g = parseInt(h.slice(2, 4), 16) / 255;
1373
- const b = parseInt(h.slice(4, 6), 16) / 255;
1374
- const a = parseInt(h.slice(6, 8), 16) / 255;
1375
- return { r, g, b, a };
1376
- }
1377
- // Fallback: black
1378
- return { r: 0, g: 0, b: 0, a: 1 };
1379
- }
1380
- /**
1381
- * Parse a `boxShadow` value (object form or CSS-like string
1382
- * `"offsetX offsetY blur color"`) into the engine's FormeBoxShadow shape.
1383
- * Returns null on malformed input. v1 ignores blur but parses it.
1384
- */
1385
- function parseBoxShadow(val) {
1386
- if (typeof val === 'object') {
1387
- const c = parseColor(val.color);
1388
- return {
1389
- offsetX: val.offsetX,
1390
- offsetY: val.offsetY,
1391
- blur: val.blur ?? 0,
1392
- color: c,
1393
- };
1394
- }
1395
- // String form: "offsetX offsetY blur color".
1396
- // Split on whitespace, but preserve any rgba(...)/rgb(...) parens.
1397
- const tokens = [];
1398
- let depth = 0;
1399
- let buf = '';
1400
- for (const ch of val.trim()) {
1401
- if (ch === '(')
1402
- depth += 1;
1403
- if (ch === ')')
1404
- depth = Math.max(0, depth - 1);
1405
- if (/\s/.test(ch) && depth === 0) {
1406
- if (buf) {
1407
- tokens.push(buf);
1408
- buf = '';
1409
- }
1410
- }
1411
- else {
1412
- buf += ch;
1413
- }
1414
- }
1415
- if (buf)
1416
- tokens.push(buf);
1417
- if (tokens.length < 4)
1418
- return null;
1419
- const offsetX = parseFloat(tokens[0]);
1420
- const offsetY = parseFloat(tokens[1]);
1421
- const blur = parseFloat(tokens[2]);
1422
- if (Number.isNaN(offsetX) || Number.isNaN(offsetY) || Number.isNaN(blur))
1423
- return null;
1424
- const color = parseColor(tokens[3]);
1425
- return { offsetX, offsetY, blur, color };
1426
- }
1427
- /**
1428
- * Parse a CSS `background` value. Supports three forms:
1429
- * - `linear-gradient(<angle>, <stop>, <stop>, ...)` — CSS angle conventions
1430
- * (`0deg` = bottom→top, `90deg` = left→right, `180deg` = top→bottom).
1431
- * Angle is optional; defaults to `180deg` (top→bottom). Side keywords
1432
- * (`to bottom`, `to right`, etc.) also supported.
1433
- * - `radial-gradient(circle, <stop>, <stop>, ...)` — `circle` is the only
1434
- * shape in v1. The `circle` keyword is optional.
1435
- * - solid color (`#abc`, `rgb(...)`, `rgba(...)`) — falls through to a
1436
- * `Color`-typed background, which the caller routes to `backgroundColor`.
1437
- *
1438
- * v1 supports exactly 2 stops; gradients with 3+ stops are flattened to
1439
- * the first and last stop (the engine's v1 ShadingType 2 only renders 2
1440
- * colors). Multi-stop support is planned via PDF Type 3 stitching.
1441
- *
1442
- * Returns null on parse failure (e.g. malformed gradient string with no
1443
- * usable color tokens) so the caller can omit the property.
1444
- */
1445
- function parseBackground(val) {
1446
- const s = val.trim();
1447
- // linear-gradient(...)
1448
- const linearMatch = s.match(/^linear-gradient\s*\(\s*([\s\S]*)\s*\)$/i);
1449
- if (linearMatch) {
1450
- const inner = linearMatch[1];
1451
- const parts = splitGradientArgs(inner);
1452
- if (parts.length === 0)
1453
- return null;
1454
- let angleDeg = 180;
1455
- let stopParts = parts;
1456
- const first = parts[0].trim();
1457
- const angleParsed = parseGradientAngle(first);
1458
- if (angleParsed !== null) {
1459
- angleDeg = angleParsed;
1460
- stopParts = parts.slice(1);
1461
- }
1462
- const stops = parseGradientStops(stopParts);
1463
- if (stops.length < 2)
1464
- return null;
1465
- return { type: 'linear', angleDeg, stops };
1466
- }
1467
- // radial-gradient(...)
1468
- const radialMatch = s.match(/^radial-gradient\s*\(\s*([\s\S]*)\s*\)$/i);
1469
- if (radialMatch) {
1470
- const inner = radialMatch[1];
1471
- const parts = splitGradientArgs(inner);
1472
- if (parts.length === 0)
1473
- return null;
1474
- let stopParts = parts;
1475
- // Optional shape keyword (`circle`, `ellipse`) — only `circle` honored
1476
- // here; `ellipse` strings parse but render as a circle.
1477
- const first = parts[0].trim().toLowerCase();
1478
- if (first === 'circle' || first === 'ellipse' || first.startsWith('circle ') || first.startsWith('ellipse ')) {
1479
- stopParts = parts.slice(1);
1480
- }
1481
- const stops = parseGradientStops(stopParts);
1482
- if (stops.length < 2)
1483
- return null;
1484
- return { type: 'radial', stops };
1485
- }
1486
- // Solid color fallback. parseColor never throws; on garbage input it
1487
- // returns black, so check that the input looks color-shaped first to
1488
- // avoid silently turning a typo'd gradient into a black background.
1489
- if (/^(#|rgb\(|rgba\()/i.test(s)) {
1490
- return { type: 'color', value: parseColor(s) };
1491
- }
1492
- return null;
1493
- }
1494
- /**
1495
- * Split a gradient's interior comma-separated arguments, respecting parens
1496
- * so `rgba(0, 0, 0, 0.5)` doesn't get split mid-color.
1497
- */
1498
- function splitGradientArgs(inner) {
1499
- const parts = [];
1500
- let depth = 0;
1501
- let buf = '';
1502
- for (const ch of inner) {
1503
- if (ch === '(')
1504
- depth += 1;
1505
- else if (ch === ')')
1506
- depth = Math.max(0, depth - 1);
1507
- if (ch === ',' && depth === 0) {
1508
- parts.push(buf);
1509
- buf = '';
1510
- }
1511
- else {
1512
- buf += ch;
1513
- }
1514
- }
1515
- if (buf.trim())
1516
- parts.push(buf);
1517
- return parts.map((p) => p.trim()).filter((p) => p.length > 0);
1518
- }
1519
- /**
1520
- * Parse a CSS gradient angle token. Returns degrees, or null if the token
1521
- * isn't an angle.
1522
- *
1523
- * Forms supported:
1524
- * - `<n>deg` (e.g. `135deg`)
1525
- * - `<n>turn` (e.g. `0.5turn`)
1526
- * - `<n>rad` / `<n>grad`
1527
- * - `to <side>` keywords: `to top` (0), `to right` (90), `to bottom` (180), `to left` (270),
1528
- * and the four diagonal forms (`to top right`, etc.).
1529
- */
1530
- function parseGradientAngle(token) {
1531
- const t = token.trim().toLowerCase();
1532
- const degMatch = t.match(/^(-?\d+(?:\.\d+)?)deg$/);
1533
- if (degMatch)
1534
- return parseFloat(degMatch[1]);
1535
- const turnMatch = t.match(/^(-?\d+(?:\.\d+)?)turn$/);
1536
- if (turnMatch)
1537
- return parseFloat(turnMatch[1]) * 360;
1538
- const radMatch = t.match(/^(-?\d+(?:\.\d+)?)rad$/);
1539
- if (radMatch)
1540
- return (parseFloat(radMatch[1]) * 180) / Math.PI;
1541
- const gradMatch = t.match(/^(-?\d+(?:\.\d+)?)grad$/);
1542
- if (gradMatch)
1543
- return parseFloat(gradMatch[1]) * 0.9;
1544
- if (t === 'to top')
1545
- return 0;
1546
- if (t === 'to right')
1547
- return 90;
1548
- if (t === 'to bottom')
1549
- return 180;
1550
- if (t === 'to left')
1551
- return 270;
1552
- if (t === 'to top right' || t === 'to right top')
1553
- return 45;
1554
- if (t === 'to bottom right' || t === 'to right bottom')
1555
- return 135;
1556
- if (t === 'to bottom left' || t === 'to left bottom')
1557
- return 225;
1558
- if (t === 'to top left' || t === 'to left top')
1559
- return 315;
1560
- return null;
1561
- }
1562
- /**
1563
- * Parse a list of gradient color stops. Each stop is `<color>` or
1564
- * `<color> <position>`. Position can be `<n>%` (CSS) or `<n>` (treated as
1565
- * a 0..1 fraction). Stops without explicit positions get evenly distributed
1566
- * positions matching CSS defaults: first at 0, last at 1, intermediate
1567
- * stops linearly interpolated.
1568
- */
1569
- function parseGradientStops(parts) {
1570
- if (parts.length === 0)
1571
- return [];
1572
- const positions = [];
1573
- const colors = [];
1574
- for (const p of parts) {
1575
- // Find the last whitespace-separated token; if it's a position
1576
- // (`50%` or `0.5`), treat it as such, else everything is the color.
1577
- const trimmed = p.trim();
1578
- const tokens = splitColorAndPosition(trimmed);
1579
- if (!tokens)
1580
- continue;
1581
- colors.push(parseColor(tokens.color));
1582
- positions.push(tokens.position);
1583
- }
1584
- if (colors.length === 0)
1585
- return [];
1586
- // Fill in missing positions with CSS defaults.
1587
- if (positions[0] === null)
1588
- positions[0] = 0;
1589
- if (positions[positions.length - 1] === null)
1590
- positions[positions.length - 1] = 1;
1591
- for (let i = 1; i < positions.length - 1; i += 1) {
1592
- if (positions[i] === null) {
1593
- // Linear interpolate between previous known and next known.
1594
- let prev = i - 1;
1595
- while (prev >= 0 && positions[prev] === null)
1596
- prev -= 1;
1597
- let next = i + 1;
1598
- while (next < positions.length && positions[next] === null)
1599
- next += 1;
1600
- const p0 = positions[prev] ?? 0;
1601
- const p1 = positions[next] ?? 1;
1602
- positions[i] = p0 + ((p1 - p0) * (i - prev)) / (next - prev);
1603
- }
1604
- }
1605
- return colors.map((color, i) => ({
1606
- position: Math.max(0, Math.min(1, positions[i])),
1607
- color,
1608
- }));
1609
- }
1610
- /**
1611
- * Split a stop string like `"#fff 50%"` into color + position.
1612
- * Position can be percentage or fraction; null if not specified.
1613
- */
1614
- function splitColorAndPosition(s) {
1615
- // The position token, if present, is the last whitespace-separated piece
1616
- // and matches `<number>%` or a bare number. Splitting on whitespace
1617
- // respects parens so `rgba(...)` is not chopped up.
1618
- const tokens = [];
1619
- let depth = 0;
1620
- let buf = '';
1621
- for (const ch of s) {
1622
- if (ch === '(')
1623
- depth += 1;
1624
- else if (ch === ')')
1625
- depth = Math.max(0, depth - 1);
1626
- if (/\s/.test(ch) && depth === 0) {
1627
- if (buf) {
1628
- tokens.push(buf);
1629
- buf = '';
1630
- }
1631
- }
1632
- else {
1633
- buf += ch;
1634
- }
1635
- }
1636
- if (buf)
1637
- tokens.push(buf);
1638
- if (tokens.length === 0)
1639
- return null;
1640
- const last = tokens[tokens.length - 1];
1641
- const pctMatch = last.match(/^(-?\d+(?:\.\d+)?)%$/);
1642
- if (pctMatch) {
1643
- return { color: tokens.slice(0, -1).join(' '), position: parseFloat(pctMatch[1]) / 100 };
1644
- }
1645
- const fracMatch = last.match(/^(-?\d+(?:\.\d+)?)$/);
1646
- if (fracMatch && tokens.length > 1) {
1647
- return { color: tokens.slice(0, -1).join(' '), position: parseFloat(fracMatch[1]) };
1648
- }
1649
- return { color: tokens.join(' '), position: null };
1650
- }
1651
- /**
1652
- * Parse a CSS-style 1-4 value edge shorthand.
1653
- * Accepts: `"8"`, `"8 16"`, `"8 16 24"`, `"8 16 24 32"` (with optional `px` suffix).
1654
- * Also accepts number arrays: `[8]`, `[8, 16]`, `[8, 16, 24]`, `[8, 16, 24, 32]`.
1655
- */
1656
- function parseCSSEdges(val) {
1657
- const values = Array.isArray(val)
1658
- ? val
1659
- : val.trim().split(/\s+/).map(s => parseFloat(s.replace(/px$/i, '')));
1660
- switch (values.length) {
1661
- case 1: return { top: values[0], right: values[0], bottom: values[0], left: values[0] };
1662
- case 2: return { top: values[0], right: values[1], bottom: values[0], left: values[1] };
1663
- case 3: return { top: values[0], right: values[1], bottom: values[2], left: values[1] };
1664
- default: return { top: values[0], right: values[1], bottom: values[2], left: values[3] };
1665
- }
1666
- }
1667
- const BORDER_STYLE_KEYWORDS = new Set([
1668
- 'solid', 'dashed', 'dotted', 'double', 'groove', 'ridge', 'inset', 'outset', 'none', 'hidden',
1669
- ]);
1670
- /**
1671
- * Parse a CSS border shorthand string like `"1px solid #000"`.
1672
- * Returns extracted width and/or color. Style keywords are recognized but ignored.
1673
- */
1674
- function parseBorderString(val) {
1675
- const tokens = val.trim().split(/\s+/);
1676
- let width;
1677
- let color;
1678
- for (const token of tokens) {
1679
- const lower = token.toLowerCase();
1680
- if (BORDER_STYLE_KEYWORDS.has(lower))
1681
- continue;
1682
- const num = parseFloat(lower.replace(/px$/i, ''));
1683
- if (!isNaN(num) && /^[\d.]/.test(lower)) {
1684
- width = num;
1685
- }
1686
- else {
1687
- color = parseColor(token);
1688
- }
1689
- }
1690
- return { width, color };
1691
- }
1692
- export function expandEdges(val) {
1693
- if (typeof val === 'number') {
1694
- return { top: val, right: val, bottom: val, left: val };
1695
- }
1696
- if (typeof val === 'string' || Array.isArray(val)) {
1697
- return parseCSSEdges(val);
1698
- }
1699
- return { top: val.top, right: val.right, bottom: val.bottom, left: val.left };
1700
- }
1701
- /** Expand margin edges, preserving 'auto' string values. */
1702
- function expandMarginEdges(val) {
1703
- if (typeof val === 'number') {
1704
- return { top: val, right: val, bottom: val, left: val };
1705
- }
1706
- if (typeof val === 'string') {
1707
- if (val === 'auto') {
1708
- return { top: 'auto', right: 'auto', bottom: 'auto', left: 'auto' };
1709
- }
1710
- const edges = parseCSSEdges(val);
1711
- return edges;
1712
- }
1713
- if (Array.isArray(val)) {
1714
- return parseCSSEdges(val);
1715
- }
1716
- return { top: val.top, right: val.right, bottom: val.bottom, left: val.left };
1717
- }
1718
- function expandEdgeValues(val) {
1719
- if (typeof val === 'number') {
1720
- return { top: val, right: val, bottom: val, left: val };
1721
- }
1722
- return { top: val.top, right: val.right, bottom: val.bottom, left: val.left };
1723
- }
1724
- export function expandCorners(val) {
1725
- if (typeof val === 'number') {
1726
- return { top_left: val, top_right: val, bottom_right: val, bottom_left: val };
1727
- }
1728
- return {
1729
- top_left: val.topLeft,
1730
- top_right: val.topRight,
1731
- bottom_right: val.bottomRight,
1732
- bottom_left: val.bottomLeft,
1733
- };
1734
- }
1735
- function mapColumnWidth(w) {
1736
- if (w === 'auto')
1737
- return 'Auto';
1738
- if ('fraction' in w)
1739
- return { Fraction: w.fraction };
1740
- if ('fixed' in w)
1741
- return { Fixed: w.fixed };
1742
- return 'Auto';
1743
- }
1744
- // ─── Font merging ─────────────────────────────────────────────────
1745
- function normalizeFontWeight(w) {
1746
- if (w === undefined || w === 'normal')
1747
- return 400;
1748
- if (w === 'bold')
1749
- return 700;
1750
- return typeof w === 'number' ? w : (parseInt(w, 10) || 400);
1751
- }
1752
- function fontKey(family, weight, italic) {
1753
- return `${family}:${weight}:${italic}`;
1754
- }
1755
- function mergeFonts(globalFonts, docFonts) {
1756
- const map = new Map();
1757
- for (const f of globalFonts) {
1758
- const weight = normalizeFontWeight(f.fontWeight);
1759
- const italic = f.fontStyle === 'italic' || f.fontStyle === 'oblique';
1760
- const key = fontKey(f.family, weight, italic);
1761
- map.set(key, { family: f.family, src: f.src, weight, italic });
1762
- }
1763
- if (docFonts) {
1764
- for (const f of docFonts) {
1765
- const weight = normalizeFontWeight(f.fontWeight);
1766
- const italic = f.fontStyle === 'italic' || f.fontStyle === 'oblique';
1767
- const key = fontKey(f.family, weight, italic);
1768
- map.set(key, { family: f.family, src: f.src, weight, italic });
1769
- }
1770
- }
1771
- return Array.from(map.values());
1772
- }
1773
957
  // ─── Template serialization ─────────────────────────────────────────
1774
958
  //
1775
959
  // Parallel to `serialize()` but detects proxy markers and expr markers,