@formepdf/react 0.10.5 → 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
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: {
@@ -393,18 +394,6 @@ function serializeView(element, _parent = null) {
393
394
  node.href = props.href;
394
395
  return node;
395
396
  }
396
- // Inline formatting components produce TextRuns with these default styles
397
- // (merged under any user-supplied style, so user style wins).
398
- const STRONG_DEFAULTS = { fontWeight: 700 };
399
- const EM_DEFAULTS = { fontStyle: 'italic' };
400
- const CODE_DEFAULTS = {
401
- fontFamily: 'Courier',
402
- backgroundColor: '#F4F4F5',
403
- };
404
- const LINK_DEFAULTS = {
405
- color: '#2563EB',
406
- textDecoration: 'underline',
407
- };
408
397
  /** Return the component-default style for a recognized inline component,
409
398
  * or `null` if the element isn't a recognized inline component.
410
399
  * `Text` returns `{}` because it carries no defaults beyond the user's style. */
@@ -486,17 +475,6 @@ function serializeText(element) {
486
475
  node.bookmark = props.bookmark;
487
476
  return node;
488
477
  }
489
- // Default style per heading level. Tuned for typical document layout —
490
- // users override individual properties via `style` on the heading element.
491
- // margin top/bottom are in points; font sizes are points.
492
- const HEADING_DEFAULTS = {
493
- 1: { fontSize: 32, fontWeight: 700, marginTop: 24, marginBottom: 16 },
494
- 2: { fontSize: 24, fontWeight: 700, marginTop: 20, marginBottom: 14 },
495
- 3: { fontSize: 20, fontWeight: 600, marginTop: 16, marginBottom: 12 },
496
- 4: { fontSize: 18, fontWeight: 600, marginTop: 14, marginBottom: 10 },
497
- 5: { fontSize: 16, fontWeight: 600, marginTop: 12, marginBottom: 8 },
498
- 6: { fontSize: 14, fontWeight: 600, marginTop: 10, marginBottom: 6 },
499
- };
500
478
  /**
501
479
  * Serialize an H1-H6 element. Mirrors serializeText for the children
502
480
  * machinery (mixed strings + inline-formatting components produce runs)
@@ -533,21 +511,6 @@ function serializeHeading(element, level) {
533
511
  node.bookmark = props.bookmark;
534
512
  return node;
535
513
  }
536
- // React `list-style-type`-shaped string → engine wire enum value.
537
- function mapListMarker(marker, defaultValue) {
538
- switch (marker) {
539
- case 'disc': return 'disc';
540
- case 'circle': return 'circle';
541
- case 'square': return 'square';
542
- case 'none': return 'none';
543
- case 'decimal': return 'decimal';
544
- case 'lower-alpha': return 'lowerAlpha';
545
- case 'upper-alpha': return 'upperAlpha';
546
- case 'lower-roman': return 'lowerRoman';
547
- case 'upper-roman': return 'upperRoman';
548
- default: return defaultValue;
549
- }
550
- }
551
514
  function serializeList(element, ordered) {
552
515
  const props = element.props;
553
516
  const markerType = ordered
@@ -857,42 +820,7 @@ function serializeRadioButton(element) {
857
820
  }
858
821
  function serializeCanvas(element) {
859
822
  const props = element.props;
860
- const operations = [];
861
- // Create a recording context that captures draw calls as CanvasOp[]
862
- const ctx = {
863
- moveTo(x, y) { operations.push({ op: 'MoveTo', x, y }); },
864
- lineTo(x, y) { operations.push({ op: 'LineTo', x, y }); },
865
- bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
866
- operations.push({ op: 'BezierCurveTo', cp1x, cp1y, cp2x, cp2y, x, y });
867
- },
868
- quadraticCurveTo(cpx, cpy, x, y) {
869
- operations.push({ op: 'QuadraticCurveTo', cpx, cpy, x, y });
870
- },
871
- closePath() { operations.push({ op: 'ClosePath' }); },
872
- rect(x, y, w, h) { operations.push({ op: 'Rect', x, y, width: w, height: h }); },
873
- circle(cx, cy, r) { operations.push({ op: 'Circle', cx, cy, r }); },
874
- ellipse(cx, cy, rx, ry) { operations.push({ op: 'Ellipse', cx, cy, rx, ry }); },
875
- arc(cx, cy, r, startAngle, endAngle, counterclockwise = false) {
876
- operations.push({ op: 'Arc', cx, cy, r, start_angle: startAngle, end_angle: endAngle, counterclockwise });
877
- },
878
- line(x1, y1, x2, y2) {
879
- operations.push({ op: 'MoveTo', x: x1, y: y1 });
880
- operations.push({ op: 'LineTo', x: x2, y: y2 });
881
- operations.push({ op: 'Stroke' });
882
- },
883
- stroke() { operations.push({ op: 'Stroke' }); },
884
- fill() { operations.push({ op: 'Fill' }); },
885
- fillAndStroke() { operations.push({ op: 'FillAndStroke' }); },
886
- setFillColor(r, g, b) { operations.push({ op: 'SetFillColor', r, g, b }); },
887
- setStrokeColor(r, g, b) { operations.push({ op: 'SetStrokeColor', r, g, b }); },
888
- setLineWidth(w) { operations.push({ op: 'SetLineWidth', width: w }); },
889
- setLineCap(cap) { operations.push({ op: 'SetLineCap', cap }); },
890
- setLineJoin(join) { operations.push({ op: 'SetLineJoin', join }); },
891
- save() { operations.push({ op: 'Save' }); },
892
- restore() { operations.push({ op: 'Restore' }); },
893
- };
894
- // Execute the draw callback to record operations
895
- props.draw(ctx);
823
+ const operations = recordCanvasOperations(props.draw);
896
824
  return {
897
825
  kind: { type: 'Canvas', width: props.width, height: props.height, operations },
898
826
  style: mapStyle(props.style),
@@ -923,21 +851,8 @@ function serializeWatermark(element) {
923
851
  }
924
852
  function serializeBarChart(element) {
925
853
  const props = element.props;
926
- const kind = {
927
- type: 'BarChart',
928
- data: props.data.map(d => ({ label: d.label, value: d.value, color: d.color })),
929
- width: props.width,
930
- height: props.height,
931
- show_labels: props.showLabels ?? true,
932
- show_values: props.showValues ?? false,
933
- show_grid: props.showGrid ?? false,
934
- };
935
- if (props.color !== undefined)
936
- kind.color = props.color;
937
- if (props.title !== undefined)
938
- kind.title = props.title;
939
854
  return {
940
- kind,
855
+ kind: buildBarChartKind(props),
941
856
  style: mapStyle(props.style),
942
857
  children: [],
943
858
  sourceLocation: extractSourceLocation(element),
@@ -945,19 +860,8 @@ function serializeBarChart(element) {
945
860
  }
946
861
  function serializeLineChart(element) {
947
862
  const props = element.props;
948
- const kind = {
949
- type: 'LineChart',
950
- series: props.series.map(s => ({ name: s.name, data: s.data, color: s.color })),
951
- labels: props.labels,
952
- width: props.width,
953
- height: props.height,
954
- show_points: props.showPoints ?? false,
955
- show_grid: props.showGrid ?? false,
956
- };
957
- if (props.title !== undefined)
958
- kind.title = props.title;
959
863
  return {
960
- kind,
864
+ kind: buildLineChartKind(props),
961
865
  style: mapStyle(props.style),
962
866
  children: [],
963
867
  sourceLocation: extractSourceLocation(element),
@@ -965,18 +869,8 @@ function serializeLineChart(element) {
965
869
  }
966
870
  function serializePieChart(element) {
967
871
  const props = element.props;
968
- const kind = {
969
- type: 'PieChart',
970
- data: props.data.map(d => ({ label: d.label, value: d.value, color: d.color })),
971
- width: props.width,
972
- height: props.height,
973
- donut: props.donut ?? false,
974
- show_legend: props.showLegend ?? false,
975
- };
976
- if (props.title !== undefined)
977
- kind.title = props.title;
978
872
  return {
979
- kind,
873
+ kind: buildPieChartKind(props),
980
874
  style: mapStyle(props.style),
981
875
  children: [],
982
876
  sourceLocation: extractSourceLocation(element),
@@ -984,18 +878,8 @@ function serializePieChart(element) {
984
878
  }
985
879
  function serializeAreaChart(element) {
986
880
  const props = element.props;
987
- const kind = {
988
- type: 'AreaChart',
989
- series: props.series.map(s => ({ name: s.name, data: s.data, color: s.color })),
990
- labels: props.labels,
991
- width: props.width,
992
- height: props.height,
993
- show_grid: props.showGrid ?? false,
994
- };
995
- if (props.title !== undefined)
996
- kind.title = props.title;
997
881
  return {
998
- kind,
882
+ kind: buildAreaChartKind(props),
999
883
  style: mapStyle(props.style),
1000
884
  children: [],
1001
885
  sourceLocation: extractSourceLocation(element),
@@ -1003,28 +887,8 @@ function serializeAreaChart(element) {
1003
887
  }
1004
888
  function serializeDotPlot(element) {
1005
889
  const props = element.props;
1006
- const kind = {
1007
- type: 'DotPlot',
1008
- groups: props.groups.map(g => ({ name: g.name, color: g.color, data: g.data })),
1009
- width: props.width,
1010
- height: props.height,
1011
- show_legend: props.showLegend ?? false,
1012
- dot_size: props.dotSize ?? 4,
1013
- };
1014
- if (props.xMin !== undefined)
1015
- kind.x_min = props.xMin;
1016
- if (props.xMax !== undefined)
1017
- kind.x_max = props.xMax;
1018
- if (props.yMin !== undefined)
1019
- kind.y_min = props.yMin;
1020
- if (props.yMax !== undefined)
1021
- kind.y_max = props.yMax;
1022
- if (props.xLabel !== undefined)
1023
- kind.x_label = props.xLabel;
1024
- if (props.yLabel !== undefined)
1025
- kind.y_label = props.yLabel;
1026
890
  return {
1027
- kind,
891
+ kind: buildDotPlotKind(props),
1028
892
  style: mapStyle(props.style),
1029
893
  children: [],
1030
894
  sourceLocation: extractSourceLocation(element),
@@ -1090,1059 +954,6 @@ function flattenTextContent(children) {
1090
954
  }
1091
955
  return String(children);
1092
956
  }
1093
- // ─── Style mapping ──────────────────────────────────────────────────
1094
- const FLEX_DIRECTION_MAP = {
1095
- 'row': 'Row',
1096
- 'column': 'Column',
1097
- 'row-reverse': 'RowReverse',
1098
- 'column-reverse': 'ColumnReverse',
1099
- };
1100
- const JUSTIFY_CONTENT_MAP = {
1101
- 'flex-start': 'FlexStart',
1102
- 'flex-end': 'FlexEnd',
1103
- 'center': 'Center',
1104
- 'space-between': 'SpaceBetween',
1105
- 'space-around': 'SpaceAround',
1106
- 'space-evenly': 'SpaceEvenly',
1107
- };
1108
- const ALIGN_ITEMS_MAP = {
1109
- 'flex-start': 'FlexStart',
1110
- 'flex-end': 'FlexEnd',
1111
- 'center': 'Center',
1112
- 'stretch': 'Stretch',
1113
- 'baseline': 'Baseline',
1114
- };
1115
- const FLEX_WRAP_MAP = {
1116
- 'nowrap': 'NoWrap',
1117
- 'wrap': 'Wrap',
1118
- 'wrap-reverse': 'WrapReverse',
1119
- };
1120
- const ALIGN_CONTENT_MAP = {
1121
- 'flex-start': 'FlexStart',
1122
- 'flex-end': 'FlexEnd',
1123
- 'center': 'Center',
1124
- 'space-between': 'SpaceBetween',
1125
- 'space-around': 'SpaceAround',
1126
- 'space-evenly': 'SpaceEvenly',
1127
- 'stretch': 'Stretch',
1128
- };
1129
- const FONT_STYLE_MAP = {
1130
- 'normal': 'Normal',
1131
- 'italic': 'Italic',
1132
- 'oblique': 'Oblique',
1133
- };
1134
- const TEXT_ALIGN_MAP = {
1135
- 'left': 'Left',
1136
- 'right': 'Right',
1137
- 'center': 'Center',
1138
- 'justify': 'Justify',
1139
- };
1140
- const TEXT_DECORATION_MAP = {
1141
- 'none': 'None',
1142
- 'underline': 'Underline',
1143
- 'line-through': 'LineThrough',
1144
- };
1145
- const TEXT_TRANSFORM_MAP = {
1146
- 'none': 'None',
1147
- 'uppercase': 'Uppercase',
1148
- 'lowercase': 'Lowercase',
1149
- 'capitalize': 'Capitalize',
1150
- };
1151
- const HYPHENS_MAP = {
1152
- 'none': 'none',
1153
- 'manual': 'manual',
1154
- 'auto': 'auto',
1155
- };
1156
- const TEXT_OVERFLOW_MAP = {
1157
- 'wrap': 'Wrap',
1158
- 'ellipsis': 'Ellipsis',
1159
- 'clip': 'Clip',
1160
- };
1161
- const LINE_BREAKING_MAP = {
1162
- 'optimal': 'optimal',
1163
- 'greedy': 'greedy',
1164
- };
1165
- const OVERFLOW_MAP = {
1166
- 'visible': 'Visible',
1167
- 'hidden': 'Hidden',
1168
- };
1169
- export function mapStyle(style) {
1170
- if (!style)
1171
- return {};
1172
- const result = {};
1173
- // Dimensions
1174
- if (style.width !== undefined)
1175
- result.width = mapDimension(style.width);
1176
- if (style.height !== undefined)
1177
- result.height = mapDimension(style.height);
1178
- if (style.minWidth !== undefined)
1179
- result.minWidth = mapDimension(style.minWidth);
1180
- if (style.minHeight !== undefined)
1181
- result.minHeight = mapDimension(style.minHeight);
1182
- if (style.maxWidth !== undefined)
1183
- result.maxWidth = mapDimension(style.maxWidth);
1184
- if (style.maxHeight !== undefined)
1185
- result.maxHeight = mapDimension(style.maxHeight);
1186
- // Edges (individual > axis > base)
1187
- if (style.padding !== undefined || style.paddingTop !== undefined || style.paddingRight !== undefined || style.paddingBottom !== undefined || style.paddingLeft !== undefined || style.paddingHorizontal !== undefined || style.paddingVertical !== undefined) {
1188
- const base = style.padding !== undefined ? expandEdges(style.padding) : { top: 0, right: 0, bottom: 0, left: 0 };
1189
- const vt = style.paddingVertical ?? base.top;
1190
- const vb = style.paddingVertical ?? base.bottom;
1191
- const hl = style.paddingHorizontal ?? base.left;
1192
- const hr = style.paddingHorizontal ?? base.right;
1193
- result.padding = {
1194
- top: style.paddingTop ?? vt,
1195
- right: style.paddingRight ?? hr,
1196
- bottom: style.paddingBottom ?? vb,
1197
- left: style.paddingLeft ?? hl,
1198
- };
1199
- }
1200
- if (style.margin !== undefined || style.marginTop !== undefined || style.marginRight !== undefined || style.marginBottom !== undefined || style.marginLeft !== undefined || style.marginHorizontal !== undefined || style.marginVertical !== undefined) {
1201
- const base = style.margin !== undefined ? expandMarginEdges(style.margin) : { top: 0, right: 0, bottom: 0, left: 0 };
1202
- const vt = style.marginVertical ?? base.top;
1203
- const vb = style.marginVertical ?? base.bottom;
1204
- const hl = style.marginHorizontal ?? base.left;
1205
- const hr = style.marginHorizontal ?? base.right;
1206
- result.margin = {
1207
- top: style.marginTop ?? vt,
1208
- right: style.marginRight ?? hr,
1209
- bottom: style.marginBottom ?? vb,
1210
- left: style.marginLeft ?? hl,
1211
- };
1212
- }
1213
- // Flex shorthand: flex: N → flexGrow: N, flexShrink: 1, flexBasis: 0
1214
- if (style.flex !== undefined) {
1215
- if (style.flexGrow === undefined)
1216
- result.flexGrow = style.flex;
1217
- if (style.flexShrink === undefined)
1218
- result.flexShrink = 1;
1219
- if (style.flexBasis === undefined)
1220
- result.flexBasis = { Pt: 0 };
1221
- }
1222
- // Flex
1223
- if (style.flexDirection !== undefined)
1224
- result.flexDirection = FLEX_DIRECTION_MAP[style.flexDirection];
1225
- if (style.justifyContent !== undefined)
1226
- result.justifyContent = JUSTIFY_CONTENT_MAP[style.justifyContent];
1227
- if (style.alignItems !== undefined)
1228
- result.alignItems = ALIGN_ITEMS_MAP[style.alignItems];
1229
- if (style.alignSelf !== undefined)
1230
- result.alignSelf = ALIGN_ITEMS_MAP[style.alignSelf];
1231
- if (style.flexWrap !== undefined)
1232
- result.flexWrap = FLEX_WRAP_MAP[style.flexWrap];
1233
- if (style.alignContent !== undefined)
1234
- result.alignContent = ALIGN_CONTENT_MAP[style.alignContent];
1235
- if (style.flexGrow !== undefined)
1236
- result.flexGrow = style.flexGrow;
1237
- if (style.flexShrink !== undefined)
1238
- result.flexShrink = style.flexShrink;
1239
- if (style.flexBasis !== undefined)
1240
- result.flexBasis = mapDimension(style.flexBasis);
1241
- if (style.gap !== undefined)
1242
- result.gap = style.gap;
1243
- if (style.rowGap !== undefined)
1244
- result.rowGap = style.rowGap;
1245
- if (style.columnGap !== undefined)
1246
- result.columnGap = style.columnGap;
1247
- // Display mode
1248
- if (style.display !== undefined) {
1249
- result.display = style.display === 'grid' ? 'Grid' : 'Flex';
1250
- }
1251
- // CSS Grid
1252
- if (style.gridTemplateColumns !== undefined) {
1253
- result.gridTemplateColumns = parseGridTemplate(style.gridTemplateColumns);
1254
- }
1255
- if (style.gridTemplateRows !== undefined) {
1256
- result.gridTemplateRows = parseGridTemplate(style.gridTemplateRows);
1257
- }
1258
- if (style.gridAutoRows !== undefined) {
1259
- result.gridAutoRows = mapGridTrack(style.gridAutoRows);
1260
- }
1261
- if (style.gridAutoColumns !== undefined) {
1262
- result.gridAutoColumns = mapGridTrack(style.gridAutoColumns);
1263
- }
1264
- // Grid placement (individual props → single gridPlacement object)
1265
- if (style.gridColumnStart !== undefined || style.gridColumnEnd !== undefined ||
1266
- style.gridRowStart !== undefined || style.gridRowEnd !== undefined ||
1267
- style.gridColumnSpan !== undefined || style.gridRowSpan !== undefined) {
1268
- const placement = {};
1269
- if (style.gridColumnStart !== undefined)
1270
- placement.columnStart = style.gridColumnStart;
1271
- if (style.gridColumnEnd !== undefined)
1272
- placement.columnEnd = style.gridColumnEnd;
1273
- if (style.gridRowStart !== undefined)
1274
- placement.rowStart = style.gridRowStart;
1275
- if (style.gridRowEnd !== undefined)
1276
- placement.rowEnd = style.gridRowEnd;
1277
- if (style.gridColumnSpan !== undefined)
1278
- placement.columnSpan = style.gridColumnSpan;
1279
- if (style.gridRowSpan !== undefined)
1280
- placement.rowSpan = style.gridRowSpan;
1281
- result.gridPlacement = placement;
1282
- }
1283
- // Typography
1284
- if (style.fontFamily !== undefined)
1285
- result.fontFamily = style.fontFamily;
1286
- if (style.fontSize !== undefined)
1287
- result.fontSize = style.fontSize;
1288
- if (style.fontWeight !== undefined) {
1289
- result.fontWeight = style.fontWeight === 'bold' ? 700 : style.fontWeight === 'normal' ? 400 : style.fontWeight;
1290
- }
1291
- if (style.fontStyle !== undefined)
1292
- result.fontStyle = FONT_STYLE_MAP[style.fontStyle];
1293
- if (style.lineHeight !== undefined)
1294
- result.lineHeight = style.lineHeight;
1295
- if (style.textAlign !== undefined)
1296
- result.textAlign = TEXT_ALIGN_MAP[style.textAlign];
1297
- if (style.letterSpacing !== undefined)
1298
- result.letterSpacing = style.letterSpacing;
1299
- if (style.wordSpacing !== undefined)
1300
- result.wordSpacing = style.wordSpacing;
1301
- if (style.boxShadow !== undefined) {
1302
- const parsed = parseBoxShadow(style.boxShadow);
1303
- if (parsed)
1304
- result.boxShadow = parsed;
1305
- }
1306
- if (style.transform !== undefined) {
1307
- const parsed = parseTransform(style.transform);
1308
- if (parsed && parsed.length > 0)
1309
- result.transform = parsed;
1310
- }
1311
- if (style.transformOrigin !== undefined) {
1312
- const parsed = parseTransformOrigin(style.transformOrigin);
1313
- if (parsed)
1314
- result.transformOrigin = parsed;
1315
- }
1316
- if (style.textDecoration !== undefined)
1317
- result.textDecoration = TEXT_DECORATION_MAP[style.textDecoration];
1318
- if (style.textTransform !== undefined)
1319
- result.textTransform = TEXT_TRANSFORM_MAP[style.textTransform];
1320
- if (style.hyphens !== undefined)
1321
- result.hyphens = HYPHENS_MAP[style.hyphens];
1322
- if (style.lang !== undefined)
1323
- result.lang = style.lang;
1324
- if (style.direction !== undefined)
1325
- result.direction = style.direction;
1326
- if (style.textOverflow !== undefined)
1327
- result.textOverflow = TEXT_OVERFLOW_MAP[style.textOverflow];
1328
- if (style.lineBreaking !== undefined)
1329
- result.lineBreaking = LINE_BREAKING_MAP[style.lineBreaking];
1330
- if (style.overflow !== undefined)
1331
- result.overflow = OVERFLOW_MAP[style.overflow];
1332
- // Color
1333
- if (style.color !== undefined)
1334
- result.color = parseColor(style.color);
1335
- if (style.backgroundColor !== undefined)
1336
- result.backgroundColor = parseColor(style.backgroundColor);
1337
- if (style.background !== undefined) {
1338
- const parsed = parseBackground(style.background);
1339
- if (parsed) {
1340
- if (parsed.type === 'color') {
1341
- // Solid color string in `background`: route to backgroundColor for
1342
- // engine compatibility (Background::Color also works, but
1343
- // backgroundColor is the canonical solid path).
1344
- if (result.backgroundColor === undefined)
1345
- result.backgroundColor = parsed.value;
1346
- }
1347
- else {
1348
- result.background = parsed;
1349
- }
1350
- }
1351
- }
1352
- if (style.opacity !== undefined)
1353
- result.opacity = style.opacity;
1354
- // Border — cascade: border < borderTop/Right/Bottom/Left < borderWidth/borderColor < borderTopWidth/borderTopColor
1355
- // Step 1: Parse string shorthands into intermediate per-side values
1356
- let shortWidth = { top: undefined, right: undefined, bottom: undefined, left: undefined };
1357
- let shortColor = { top: undefined, right: undefined, bottom: undefined, left: undefined };
1358
- if (style.border !== undefined) {
1359
- const parsed = parseBorderString(style.border);
1360
- if (parsed.width !== undefined)
1361
- shortWidth = { top: parsed.width, right: parsed.width, bottom: parsed.width, left: parsed.width };
1362
- if (parsed.color !== undefined)
1363
- shortColor = { top: parsed.color, right: parsed.color, bottom: parsed.color, left: parsed.color };
1364
- }
1365
- // Per-side string shorthands override all-side shorthand
1366
- for (const [side, prop] of [['top', 'borderTop'], ['right', 'borderRight'], ['bottom', 'borderBottom'], ['left', 'borderLeft']]) {
1367
- const val = style[prop];
1368
- if (val === undefined)
1369
- continue;
1370
- if (typeof val === 'number') {
1371
- shortWidth[side] = val;
1372
- }
1373
- else {
1374
- const parsed = parseBorderString(val);
1375
- if (parsed.width !== undefined)
1376
- shortWidth[side] = parsed.width;
1377
- if (parsed.color !== undefined)
1378
- shortColor[side] = parsed.color;
1379
- }
1380
- }
1381
- // Step 2: Build borderWidth — existing borderWidth/borderTopWidth override shorthands
1382
- const hasBorderWidth = style.borderWidth !== undefined || style.borderTopWidth !== undefined || style.borderRightWidth !== undefined || style.borderBottomWidth !== undefined || style.borderLeftWidth !== undefined;
1383
- const hasShortWidth = shortWidth.top !== undefined || shortWidth.right !== undefined || shortWidth.bottom !== undefined || shortWidth.left !== undefined;
1384
- if (hasBorderWidth || hasShortWidth) {
1385
- const base = style.borderWidth !== undefined
1386
- ? expandEdgeValues(style.borderWidth)
1387
- : { top: shortWidth.top ?? 0, right: shortWidth.right ?? 0, bottom: shortWidth.bottom ?? 0, left: shortWidth.left ?? 0 };
1388
- result.borderWidth = {
1389
- top: style.borderTopWidth ?? base.top,
1390
- right: style.borderRightWidth ?? base.right,
1391
- bottom: style.borderBottomWidth ?? base.bottom,
1392
- left: style.borderLeftWidth ?? base.left,
1393
- };
1394
- }
1395
- // Step 3: Build borderColor — existing borderColor/borderTopColor override shorthands
1396
- const hasBorderColor = style.borderColor !== undefined || style.borderTopColor !== undefined || style.borderRightColor !== undefined || style.borderBottomColor !== undefined || style.borderLeftColor !== undefined;
1397
- const hasShortColor = shortColor.top !== undefined || shortColor.right !== undefined || shortColor.bottom !== undefined || shortColor.left !== undefined;
1398
- if (hasBorderColor || hasShortColor) {
1399
- const defaultColor = parseColor('#000000');
1400
- let base = {
1401
- top: shortColor.top ?? defaultColor,
1402
- right: shortColor.right ?? defaultColor,
1403
- bottom: shortColor.bottom ?? defaultColor,
1404
- left: shortColor.left ?? defaultColor,
1405
- };
1406
- if (typeof style.borderColor === 'string') {
1407
- const c = parseColor(style.borderColor);
1408
- base = { top: c, right: c, bottom: c, left: c };
1409
- }
1410
- else if (style.borderColor && typeof style.borderColor === 'object') {
1411
- base = {
1412
- top: parseColor(style.borderColor.top),
1413
- right: parseColor(style.borderColor.right),
1414
- bottom: parseColor(style.borderColor.bottom),
1415
- left: parseColor(style.borderColor.left),
1416
- };
1417
- }
1418
- result.borderColor = {
1419
- top: style.borderTopColor ? parseColor(style.borderTopColor) : base.top,
1420
- right: style.borderRightColor ? parseColor(style.borderRightColor) : base.right,
1421
- bottom: style.borderBottomColor ? parseColor(style.borderBottomColor) : base.bottom,
1422
- left: style.borderLeftColor ? parseColor(style.borderLeftColor) : base.left,
1423
- };
1424
- }
1425
- if (style.borderRadius !== undefined || style.borderTopLeftRadius !== undefined || style.borderTopRightRadius !== undefined || style.borderBottomRightRadius !== undefined || style.borderBottomLeftRadius !== undefined) {
1426
- const base = style.borderRadius !== undefined ? expandCorners(style.borderRadius) : { top_left: 0, top_right: 0, bottom_right: 0, bottom_left: 0 };
1427
- result.borderRadius = {
1428
- top_left: style.borderTopLeftRadius ?? base.top_left,
1429
- top_right: style.borderTopRightRadius ?? base.top_right,
1430
- bottom_right: style.borderBottomRightRadius ?? base.bottom_right,
1431
- bottom_left: style.borderBottomLeftRadius ?? base.bottom_left,
1432
- };
1433
- }
1434
- // Positioning
1435
- if (style.position !== undefined) {
1436
- result.position = style.position === 'absolute' ? 'Absolute' : 'Relative';
1437
- }
1438
- if (style.top !== undefined)
1439
- result.top = style.top;
1440
- if (style.right !== undefined)
1441
- result.right = style.right;
1442
- if (style.bottom !== undefined)
1443
- result.bottom = style.bottom;
1444
- if (style.left !== undefined)
1445
- result.left = style.left;
1446
- // Page behavior
1447
- if (style.wrap !== undefined)
1448
- result.wrap = style.wrap;
1449
- if (style.breakBefore !== undefined)
1450
- result.breakBefore = style.breakBefore;
1451
- if (style.minWidowLines !== undefined)
1452
- result.minWidowLines = style.minWidowLines;
1453
- if (style.minOrphanLines !== undefined)
1454
- result.minOrphanLines = style.minOrphanLines;
1455
- return result;
1456
- }
1457
- // ─── Grid helpers ───────────────────────────────────────────────────
1458
- /** Convert a single GridTrackSize to the Forme JSON format. */
1459
- function mapGridTrack(track) {
1460
- if (typeof track === 'number')
1461
- return { Pt: track };
1462
- if (track === 'auto')
1463
- return 'Auto';
1464
- if (typeof track === 'string') {
1465
- const frMatch = track.match(/^([0-9.]+)fr$/);
1466
- if (frMatch)
1467
- return { Fr: parseFloat(frMatch[1]) };
1468
- // Try numeric string
1469
- const num = parseFloat(track);
1470
- if (!isNaN(num))
1471
- return { Pt: num };
1472
- return 'Auto';
1473
- }
1474
- if (typeof track === 'object' && 'min' in track && 'max' in track) {
1475
- return { MinMax: [mapGridTrack(track.min), mapGridTrack(track.max)] };
1476
- }
1477
- return 'Auto';
1478
- }
1479
- /**
1480
- * Expand `repeat(N, tracks)` in a grid template string.
1481
- * E.g. `"repeat(3, 1fr)"` → `"1fr 1fr 1fr"`
1482
- * `"200 repeat(2, 1fr) 200"` → `"200 1fr 1fr 200"`
1483
- */
1484
- function expandRepeat(input) {
1485
- return input.replace(/repeat\(\s*(\d+)\s*,\s*([^)]+)\)/g, (_match, count, tracks) => {
1486
- return (tracks.trim() + ' ').repeat(parseInt(count, 10)).trim();
1487
- });
1488
- }
1489
- /**
1490
- * Parse a grid template string shorthand into an array of FormeGridTrackSize.
1491
- * E.g. `"1fr 2fr 200"` → `[{Fr:1}, {Fr:2}, {Pt:200}]`
1492
- * Supports `repeat(N, tracks)` syntax.
1493
- */
1494
- function parseGridTemplate(value) {
1495
- if (Array.isArray(value)) {
1496
- return value.map(mapGridTrack);
1497
- }
1498
- const expanded = expandRepeat(value);
1499
- return expanded.split(/\s+/).filter(Boolean).map((token) => {
1500
- if (token === 'auto')
1501
- return 'Auto';
1502
- const frMatch = token.match(/^([0-9.]+)fr$/);
1503
- if (frMatch)
1504
- return { Fr: parseFloat(frMatch[1]) };
1505
- const num = parseFloat(token);
1506
- if (!isNaN(num))
1507
- return { Pt: num };
1508
- return 'Auto';
1509
- });
1510
- }
1511
- export function mapDimension(val) {
1512
- if (typeof val === 'number') {
1513
- return { Pt: val };
1514
- }
1515
- if (val === 'auto')
1516
- return 'Auto';
1517
- const match = val.match(/^([0-9.]+)%$/);
1518
- if (match) {
1519
- return { Percent: parseFloat(match[1]) };
1520
- }
1521
- // Try to parse as a number (e.g. "100" without units)
1522
- const num = parseFloat(val);
1523
- if (!isNaN(num)) {
1524
- return { Pt: num };
1525
- }
1526
- return 'Auto';
1527
- }
1528
- export function parseColor(hex) {
1529
- const s = hex.trim();
1530
- // rgba(r, g, b, a)
1531
- const rgbaMatch = s.match(/^rgba\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/);
1532
- if (rgbaMatch) {
1533
- return {
1534
- r: parseFloat(rgbaMatch[1]) / 255,
1535
- g: parseFloat(rgbaMatch[2]) / 255,
1536
- b: parseFloat(rgbaMatch[3]) / 255,
1537
- a: parseFloat(rgbaMatch[4]),
1538
- };
1539
- }
1540
- // rgb(r, g, b)
1541
- const rgbMatch = s.match(/^rgb\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/);
1542
- if (rgbMatch) {
1543
- return {
1544
- r: parseFloat(rgbMatch[1]) / 255,
1545
- g: parseFloat(rgbMatch[2]) / 255,
1546
- b: parseFloat(rgbMatch[3]) / 255,
1547
- a: 1,
1548
- };
1549
- }
1550
- const h = s.replace(/^#/, '');
1551
- if (h.length === 3) {
1552
- const r = parseInt(h[0] + h[0], 16) / 255;
1553
- const g = parseInt(h[1] + h[1], 16) / 255;
1554
- const b = parseInt(h[2] + h[2], 16) / 255;
1555
- return { r, g, b, a: 1 };
1556
- }
1557
- if (h.length === 6) {
1558
- const r = parseInt(h.slice(0, 2), 16) / 255;
1559
- const g = parseInt(h.slice(2, 4), 16) / 255;
1560
- const b = parseInt(h.slice(4, 6), 16) / 255;
1561
- return { r, g, b, a: 1 };
1562
- }
1563
- if (h.length === 8) {
1564
- const r = parseInt(h.slice(0, 2), 16) / 255;
1565
- const g = parseInt(h.slice(2, 4), 16) / 255;
1566
- const b = parseInt(h.slice(4, 6), 16) / 255;
1567
- const a = parseInt(h.slice(6, 8), 16) / 255;
1568
- return { r, g, b, a };
1569
- }
1570
- // Fallback: black
1571
- return { r: 0, g: 0, b: 0, a: 1 };
1572
- }
1573
- /**
1574
- * Parse a CSS-like `transform` string into the engine's TransformOp[].
1575
- *
1576
- * Accepted syntax (space- or comma-separated ops, in any order):
1577
- * `rotate(45deg)`, `rotate(-15deg)`, `rotate(0.5turn)`, `rotate(1.2rad)`
1578
- * `scale(1.5)`, `scale(2, 0.5)`
1579
- * `translate(10, -4)`, `translate(10px, -4pt)`
1580
- *
1581
- * Lengths are interpreted as points (px/pt suffix accepted and ignored;
1582
- * Forme is a print-first engine — 1 point = 1 point). Returns `null` on
1583
- * unparseable input (the property is silently dropped, matching the
1584
- * boxShadow precedent).
1585
- */
1586
- function parseTransform(val) {
1587
- const ops = [];
1588
- // Match `name(args)` pairs. Names: ASCII letters. Args: anything between
1589
- // parentheses (no nesting in this grammar).
1590
- const re = /([a-zA-Z]+)\s*\(([^)]*)\)/g;
1591
- let m;
1592
- let matched = false;
1593
- while ((m = re.exec(val)) !== null) {
1594
- matched = true;
1595
- const name = m[1].toLowerCase();
1596
- const args = m[2]
1597
- .split(/[,\s]+/)
1598
- .map((s) => s.trim())
1599
- .filter((s) => s.length > 0);
1600
- if (name === 'rotate' || name === 'rotatez') {
1601
- if (args.length !== 1)
1602
- return null;
1603
- const deg = parseAngle(args[0]);
1604
- if (deg === null)
1605
- return null;
1606
- ops.push({ type: 'rotate', deg });
1607
- }
1608
- else if (name === 'scale') {
1609
- if (args.length === 0 || args.length > 2)
1610
- return null;
1611
- const x = parseFloat(args[0]);
1612
- if (Number.isNaN(x))
1613
- return null;
1614
- const y = args.length === 2 ? parseFloat(args[1]) : x;
1615
- if (Number.isNaN(y))
1616
- return null;
1617
- ops.push({ type: 'scale', x, y });
1618
- }
1619
- else if (name === 'scalex') {
1620
- if (args.length !== 1)
1621
- return null;
1622
- const x = parseFloat(args[0]);
1623
- if (Number.isNaN(x))
1624
- return null;
1625
- ops.push({ type: 'scale', x, y: 1 });
1626
- }
1627
- else if (name === 'scaley') {
1628
- if (args.length !== 1)
1629
- return null;
1630
- const y = parseFloat(args[0]);
1631
- if (Number.isNaN(y))
1632
- return null;
1633
- ops.push({ type: 'scale', x: 1, y });
1634
- }
1635
- else if (name === 'translate') {
1636
- if (args.length === 0 || args.length > 2)
1637
- return null;
1638
- const x = parseLengthPt(args[0]);
1639
- if (x === null)
1640
- return null;
1641
- const y = args.length === 2 ? parseLengthPt(args[1]) : 0;
1642
- if (y === null)
1643
- return null;
1644
- ops.push({ type: 'translate', x, y });
1645
- }
1646
- else if (name === 'translatex') {
1647
- if (args.length !== 1)
1648
- return null;
1649
- const x = parseLengthPt(args[0]);
1650
- if (x === null)
1651
- return null;
1652
- ops.push({ type: 'translate', x, y: 0 });
1653
- }
1654
- else if (name === 'translatey') {
1655
- if (args.length !== 1)
1656
- return null;
1657
- const y = parseLengthPt(args[0]);
1658
- if (y === null)
1659
- return null;
1660
- ops.push({ type: 'translate', x: 0, y });
1661
- }
1662
- else {
1663
- // Unknown op (e.g. skew, matrix) — reject the whole transform so
1664
- // users notice rather than getting silently-half-applied transforms.
1665
- return null;
1666
- }
1667
- }
1668
- if (!matched)
1669
- return null;
1670
- return ops;
1671
- }
1672
- /**
1673
- * Parse an angle in `deg` / `rad` / `turn` (no unit defaults to deg).
1674
- * Returns the angle in DEGREES, or null on parse failure.
1675
- */
1676
- function parseAngle(s) {
1677
- const t = s.trim().toLowerCase();
1678
- let mult = 1;
1679
- let body = t;
1680
- if (t.endsWith('deg')) {
1681
- body = t.slice(0, -3);
1682
- }
1683
- else if (t.endsWith('rad')) {
1684
- body = t.slice(0, -3);
1685
- mult = 180 / Math.PI;
1686
- }
1687
- else if (t.endsWith('turn')) {
1688
- body = t.slice(0, -4);
1689
- mult = 360;
1690
- }
1691
- const n = parseFloat(body);
1692
- if (Number.isNaN(n))
1693
- return null;
1694
- return n * mult;
1695
- }
1696
- /**
1697
- * Parse a length value — accepts a bare number or `<n>px`/`<n>pt` and
1698
- * returns the value in points. Forme is print-first; px/pt are treated
1699
- * as the same unit at the React layer.
1700
- */
1701
- function parseLengthPt(s) {
1702
- const t = s.trim().toLowerCase();
1703
- const body = t.endsWith('px') || t.endsWith('pt') ? t.slice(0, -2) : t;
1704
- const n = parseFloat(body);
1705
- return Number.isNaN(n) ? null : n;
1706
- }
1707
- /**
1708
- * Parse a `transformOrigin` value into a `[x, y]` tuple of fractions
1709
- * (0.0–1.0). Accepts the user-side tuple shape directly, or a CSS-like
1710
- * string with two tokens (`"50% 50%"`, `"0% 100%"`, `"center top"`,
1711
- * `"left bottom"`, etc.). Returns null on unparseable input.
1712
- */
1713
- function parseTransformOrigin(val) {
1714
- if (Array.isArray(val)) {
1715
- const [x, y] = val;
1716
- if (typeof x !== 'number' || typeof y !== 'number')
1717
- return null;
1718
- return [x, y];
1719
- }
1720
- const tokens = val.trim().split(/\s+/).filter((t) => t.length > 0);
1721
- if (tokens.length === 0 || tokens.length > 2)
1722
- return null;
1723
- const x = parseOriginToken(tokens[0], 'x');
1724
- if (x === null)
1725
- return null;
1726
- const y = tokens.length === 2 ? parseOriginToken(tokens[1], 'y') : 0.5;
1727
- if (y === null)
1728
- return null;
1729
- return [x, y];
1730
- }
1731
- function parseOriginToken(token, axis) {
1732
- const t = token.toLowerCase();
1733
- if (t === 'center')
1734
- return 0.5;
1735
- if (axis === 'x') {
1736
- if (t === 'left')
1737
- return 0;
1738
- if (t === 'right')
1739
- return 1;
1740
- }
1741
- else {
1742
- if (t === 'top')
1743
- return 0;
1744
- if (t === 'bottom')
1745
- return 1;
1746
- }
1747
- if (t.endsWith('%')) {
1748
- const n = parseFloat(t.slice(0, -1));
1749
- return Number.isNaN(n) ? null : n / 100;
1750
- }
1751
- return null;
1752
- }
1753
- /**
1754
- * Parse a `boxShadow` value (object form or CSS-like string
1755
- * `"offsetX offsetY blur color"`) into the engine's FormeBoxShadow shape.
1756
- * Returns null on malformed input. v1 ignores blur but parses it.
1757
- */
1758
- function parseBoxShadow(val) {
1759
- if (typeof val === 'object') {
1760
- const c = parseColor(val.color);
1761
- return {
1762
- offsetX: val.offsetX,
1763
- offsetY: val.offsetY,
1764
- blur: val.blur ?? 0,
1765
- color: c,
1766
- };
1767
- }
1768
- // String form: "offsetX offsetY blur color".
1769
- // Split on whitespace, but preserve any rgba(...)/rgb(...) parens.
1770
- const tokens = [];
1771
- let depth = 0;
1772
- let buf = '';
1773
- for (const ch of val.trim()) {
1774
- if (ch === '(')
1775
- depth += 1;
1776
- if (ch === ')')
1777
- depth = Math.max(0, depth - 1);
1778
- if (/\s/.test(ch) && depth === 0) {
1779
- if (buf) {
1780
- tokens.push(buf);
1781
- buf = '';
1782
- }
1783
- }
1784
- else {
1785
- buf += ch;
1786
- }
1787
- }
1788
- if (buf)
1789
- tokens.push(buf);
1790
- if (tokens.length < 4)
1791
- return null;
1792
- const offsetX = parseFloat(tokens[0]);
1793
- const offsetY = parseFloat(tokens[1]);
1794
- const blur = parseFloat(tokens[2]);
1795
- if (Number.isNaN(offsetX) || Number.isNaN(offsetY) || Number.isNaN(blur))
1796
- return null;
1797
- const color = parseColor(tokens[3]);
1798
- return { offsetX, offsetY, blur, color };
1799
- }
1800
- /**
1801
- * Parse a CSS `background` value. Supports three forms:
1802
- * - `linear-gradient(<angle>, <stop>, <stop>, ...)` — CSS angle conventions
1803
- * (`0deg` = bottom→top, `90deg` = left→right, `180deg` = top→bottom).
1804
- * Angle is optional; defaults to `180deg` (top→bottom). Side keywords
1805
- * (`to bottom`, `to right`, etc.) also supported.
1806
- * - `radial-gradient(circle, <stop>, <stop>, ...)` — `circle` is the only
1807
- * shape in v1. The `circle` keyword is optional.
1808
- * - solid color (`#abc`, `rgb(...)`, `rgba(...)`) — falls through to a
1809
- * `Color`-typed background, which the caller routes to `backgroundColor`.
1810
- *
1811
- * v1 supports exactly 2 stops; gradients with 3+ stops are flattened to
1812
- * the first and last stop (the engine's v1 ShadingType 2 only renders 2
1813
- * colors). Multi-stop support is planned via PDF Type 3 stitching.
1814
- *
1815
- * Returns null on parse failure (e.g. malformed gradient string with no
1816
- * usable color tokens) so the caller can omit the property.
1817
- */
1818
- function parseBackground(val) {
1819
- const s = val.trim();
1820
- // linear-gradient(...)
1821
- const linearMatch = s.match(/^linear-gradient\s*\(\s*([\s\S]*)\s*\)$/i);
1822
- if (linearMatch) {
1823
- const inner = linearMatch[1];
1824
- const parts = splitGradientArgs(inner);
1825
- if (parts.length === 0)
1826
- return null;
1827
- let angleDeg = 180;
1828
- let stopParts = parts;
1829
- const first = parts[0].trim();
1830
- const angleParsed = parseGradientAngle(first);
1831
- if (angleParsed !== null) {
1832
- angleDeg = angleParsed;
1833
- stopParts = parts.slice(1);
1834
- }
1835
- const stops = parseGradientStops(stopParts);
1836
- if (stops.length < 2)
1837
- return null;
1838
- return { type: 'linear', angleDeg, stops };
1839
- }
1840
- // radial-gradient(...)
1841
- const radialMatch = s.match(/^radial-gradient\s*\(\s*([\s\S]*)\s*\)$/i);
1842
- if (radialMatch) {
1843
- const inner = radialMatch[1];
1844
- const parts = splitGradientArgs(inner);
1845
- if (parts.length === 0)
1846
- return null;
1847
- let stopParts = parts;
1848
- // Optional shape keyword (`circle`, `ellipse`) — only `circle` honored
1849
- // here; `ellipse` strings parse but render as a circle.
1850
- const first = parts[0].trim().toLowerCase();
1851
- if (first === 'circle' || first === 'ellipse' || first.startsWith('circle ') || first.startsWith('ellipse ')) {
1852
- stopParts = parts.slice(1);
1853
- }
1854
- const stops = parseGradientStops(stopParts);
1855
- if (stops.length < 2)
1856
- return null;
1857
- return { type: 'radial', stops };
1858
- }
1859
- // Solid color fallback. parseColor never throws; on garbage input it
1860
- // returns black, so check that the input looks color-shaped first to
1861
- // avoid silently turning a typo'd gradient into a black background.
1862
- if (/^(#|rgb\(|rgba\()/i.test(s)) {
1863
- return { type: 'color', value: parseColor(s) };
1864
- }
1865
- return null;
1866
- }
1867
- /**
1868
- * Split a gradient's interior comma-separated arguments, respecting parens
1869
- * so `rgba(0, 0, 0, 0.5)` doesn't get split mid-color.
1870
- */
1871
- function splitGradientArgs(inner) {
1872
- const parts = [];
1873
- let depth = 0;
1874
- let buf = '';
1875
- for (const ch of inner) {
1876
- if (ch === '(')
1877
- depth += 1;
1878
- else if (ch === ')')
1879
- depth = Math.max(0, depth - 1);
1880
- if (ch === ',' && depth === 0) {
1881
- parts.push(buf);
1882
- buf = '';
1883
- }
1884
- else {
1885
- buf += ch;
1886
- }
1887
- }
1888
- if (buf.trim())
1889
- parts.push(buf);
1890
- return parts.map((p) => p.trim()).filter((p) => p.length > 0);
1891
- }
1892
- /**
1893
- * Parse a CSS gradient angle token. Returns degrees, or null if the token
1894
- * isn't an angle.
1895
- *
1896
- * Forms supported:
1897
- * - `<n>deg` (e.g. `135deg`)
1898
- * - `<n>turn` (e.g. `0.5turn`)
1899
- * - `<n>rad` / `<n>grad`
1900
- * - `to <side>` keywords: `to top` (0), `to right` (90), `to bottom` (180), `to left` (270),
1901
- * and the four diagonal forms (`to top right`, etc.).
1902
- */
1903
- function parseGradientAngle(token) {
1904
- const t = token.trim().toLowerCase();
1905
- const degMatch = t.match(/^(-?\d+(?:\.\d+)?)deg$/);
1906
- if (degMatch)
1907
- return parseFloat(degMatch[1]);
1908
- const turnMatch = t.match(/^(-?\d+(?:\.\d+)?)turn$/);
1909
- if (turnMatch)
1910
- return parseFloat(turnMatch[1]) * 360;
1911
- const radMatch = t.match(/^(-?\d+(?:\.\d+)?)rad$/);
1912
- if (radMatch)
1913
- return (parseFloat(radMatch[1]) * 180) / Math.PI;
1914
- const gradMatch = t.match(/^(-?\d+(?:\.\d+)?)grad$/);
1915
- if (gradMatch)
1916
- return parseFloat(gradMatch[1]) * 0.9;
1917
- if (t === 'to top')
1918
- return 0;
1919
- if (t === 'to right')
1920
- return 90;
1921
- if (t === 'to bottom')
1922
- return 180;
1923
- if (t === 'to left')
1924
- return 270;
1925
- if (t === 'to top right' || t === 'to right top')
1926
- return 45;
1927
- if (t === 'to bottom right' || t === 'to right bottom')
1928
- return 135;
1929
- if (t === 'to bottom left' || t === 'to left bottom')
1930
- return 225;
1931
- if (t === 'to top left' || t === 'to left top')
1932
- return 315;
1933
- return null;
1934
- }
1935
- /**
1936
- * Parse a list of gradient color stops. Each stop is `<color>` or
1937
- * `<color> <position>`. Position can be `<n>%` (CSS) or `<n>` (treated as
1938
- * a 0..1 fraction). Stops without explicit positions get evenly distributed
1939
- * positions matching CSS defaults: first at 0, last at 1, intermediate
1940
- * stops linearly interpolated.
1941
- */
1942
- function parseGradientStops(parts) {
1943
- if (parts.length === 0)
1944
- return [];
1945
- const positions = [];
1946
- const colors = [];
1947
- for (const p of parts) {
1948
- // Find the last whitespace-separated token; if it's a position
1949
- // (`50%` or `0.5`), treat it as such, else everything is the color.
1950
- const trimmed = p.trim();
1951
- const tokens = splitColorAndPosition(trimmed);
1952
- if (!tokens)
1953
- continue;
1954
- colors.push(parseColor(tokens.color));
1955
- positions.push(tokens.position);
1956
- }
1957
- if (colors.length === 0)
1958
- return [];
1959
- // Fill in missing positions with CSS defaults.
1960
- if (positions[0] === null)
1961
- positions[0] = 0;
1962
- if (positions[positions.length - 1] === null)
1963
- positions[positions.length - 1] = 1;
1964
- for (let i = 1; i < positions.length - 1; i += 1) {
1965
- if (positions[i] === null) {
1966
- // Linear interpolate between previous known and next known.
1967
- let prev = i - 1;
1968
- while (prev >= 0 && positions[prev] === null)
1969
- prev -= 1;
1970
- let next = i + 1;
1971
- while (next < positions.length && positions[next] === null)
1972
- next += 1;
1973
- const p0 = positions[prev] ?? 0;
1974
- const p1 = positions[next] ?? 1;
1975
- positions[i] = p0 + ((p1 - p0) * (i - prev)) / (next - prev);
1976
- }
1977
- }
1978
- return colors.map((color, i) => ({
1979
- position: Math.max(0, Math.min(1, positions[i])),
1980
- color,
1981
- }));
1982
- }
1983
- /**
1984
- * Split a stop string like `"#fff 50%"` into color + position.
1985
- * Position can be percentage or fraction; null if not specified.
1986
- */
1987
- function splitColorAndPosition(s) {
1988
- // The position token, if present, is the last whitespace-separated piece
1989
- // and matches `<number>%` or a bare number. Splitting on whitespace
1990
- // respects parens so `rgba(...)` is not chopped up.
1991
- const tokens = [];
1992
- let depth = 0;
1993
- let buf = '';
1994
- for (const ch of s) {
1995
- if (ch === '(')
1996
- depth += 1;
1997
- else if (ch === ')')
1998
- depth = Math.max(0, depth - 1);
1999
- if (/\s/.test(ch) && depth === 0) {
2000
- if (buf) {
2001
- tokens.push(buf);
2002
- buf = '';
2003
- }
2004
- }
2005
- else {
2006
- buf += ch;
2007
- }
2008
- }
2009
- if (buf)
2010
- tokens.push(buf);
2011
- if (tokens.length === 0)
2012
- return null;
2013
- const last = tokens[tokens.length - 1];
2014
- const pctMatch = last.match(/^(-?\d+(?:\.\d+)?)%$/);
2015
- if (pctMatch) {
2016
- return { color: tokens.slice(0, -1).join(' '), position: parseFloat(pctMatch[1]) / 100 };
2017
- }
2018
- const fracMatch = last.match(/^(-?\d+(?:\.\d+)?)$/);
2019
- if (fracMatch && tokens.length > 1) {
2020
- return { color: tokens.slice(0, -1).join(' '), position: parseFloat(fracMatch[1]) };
2021
- }
2022
- return { color: tokens.join(' '), position: null };
2023
- }
2024
- /**
2025
- * Parse a CSS-style 1-4 value edge shorthand.
2026
- * Accepts: `"8"`, `"8 16"`, `"8 16 24"`, `"8 16 24 32"` (with optional `px` suffix).
2027
- * Also accepts number arrays: `[8]`, `[8, 16]`, `[8, 16, 24]`, `[8, 16, 24, 32]`.
2028
- */
2029
- function parseCSSEdges(val) {
2030
- const values = Array.isArray(val)
2031
- ? val
2032
- : val.trim().split(/\s+/).map(s => parseFloat(s.replace(/px$/i, '')));
2033
- switch (values.length) {
2034
- case 1: return { top: values[0], right: values[0], bottom: values[0], left: values[0] };
2035
- case 2: return { top: values[0], right: values[1], bottom: values[0], left: values[1] };
2036
- case 3: return { top: values[0], right: values[1], bottom: values[2], left: values[1] };
2037
- default: return { top: values[0], right: values[1], bottom: values[2], left: values[3] };
2038
- }
2039
- }
2040
- const BORDER_STYLE_KEYWORDS = new Set([
2041
- 'solid', 'dashed', 'dotted', 'double', 'groove', 'ridge', 'inset', 'outset', 'none', 'hidden',
2042
- ]);
2043
- /**
2044
- * Parse a CSS border shorthand string like `"1px solid #000"`.
2045
- * Returns extracted width and/or color. Style keywords are recognized but ignored.
2046
- */
2047
- function parseBorderString(val) {
2048
- const tokens = val.trim().split(/\s+/);
2049
- let width;
2050
- let color;
2051
- for (const token of tokens) {
2052
- const lower = token.toLowerCase();
2053
- if (BORDER_STYLE_KEYWORDS.has(lower))
2054
- continue;
2055
- const num = parseFloat(lower.replace(/px$/i, ''));
2056
- if (!isNaN(num) && /^[\d.]/.test(lower)) {
2057
- width = num;
2058
- }
2059
- else {
2060
- color = parseColor(token);
2061
- }
2062
- }
2063
- return { width, color };
2064
- }
2065
- export function expandEdges(val) {
2066
- if (typeof val === 'number') {
2067
- return { top: val, right: val, bottom: val, left: val };
2068
- }
2069
- if (typeof val === 'string' || Array.isArray(val)) {
2070
- return parseCSSEdges(val);
2071
- }
2072
- return { top: val.top, right: val.right, bottom: val.bottom, left: val.left };
2073
- }
2074
- /** Expand margin edges, preserving 'auto' string values. */
2075
- function expandMarginEdges(val) {
2076
- if (typeof val === 'number') {
2077
- return { top: val, right: val, bottom: val, left: val };
2078
- }
2079
- if (typeof val === 'string') {
2080
- if (val === 'auto') {
2081
- return { top: 'auto', right: 'auto', bottom: 'auto', left: 'auto' };
2082
- }
2083
- const edges = parseCSSEdges(val);
2084
- return edges;
2085
- }
2086
- if (Array.isArray(val)) {
2087
- return parseCSSEdges(val);
2088
- }
2089
- return { top: val.top, right: val.right, bottom: val.bottom, left: val.left };
2090
- }
2091
- function expandEdgeValues(val) {
2092
- if (typeof val === 'number') {
2093
- return { top: val, right: val, bottom: val, left: val };
2094
- }
2095
- return { top: val.top, right: val.right, bottom: val.bottom, left: val.left };
2096
- }
2097
- export function expandCorners(val) {
2098
- if (typeof val === 'number') {
2099
- return { top_left: val, top_right: val, bottom_right: val, bottom_left: val };
2100
- }
2101
- return {
2102
- top_left: val.topLeft,
2103
- top_right: val.topRight,
2104
- bottom_right: val.bottomRight,
2105
- bottom_left: val.bottomLeft,
2106
- };
2107
- }
2108
- function mapColumnWidth(w) {
2109
- if (w === 'auto')
2110
- return 'Auto';
2111
- if ('fraction' in w)
2112
- return { Fraction: w.fraction };
2113
- if ('fixed' in w)
2114
- return { Fixed: w.fixed };
2115
- return 'Auto';
2116
- }
2117
- // ─── Font merging ─────────────────────────────────────────────────
2118
- function normalizeFontWeight(w) {
2119
- if (w === undefined || w === 'normal')
2120
- return 400;
2121
- if (w === 'bold')
2122
- return 700;
2123
- return typeof w === 'number' ? w : (parseInt(w, 10) || 400);
2124
- }
2125
- function fontKey(family, weight, italic) {
2126
- return `${family}:${weight}:${italic}`;
2127
- }
2128
- function mergeFonts(globalFonts, docFonts) {
2129
- const map = new Map();
2130
- for (const f of globalFonts) {
2131
- const weight = normalizeFontWeight(f.fontWeight);
2132
- const italic = f.fontStyle === 'italic' || f.fontStyle === 'oblique';
2133
- const key = fontKey(f.family, weight, italic);
2134
- map.set(key, { family: f.family, src: f.src, weight, italic });
2135
- }
2136
- if (docFonts) {
2137
- for (const f of docFonts) {
2138
- const weight = normalizeFontWeight(f.fontWeight);
2139
- const italic = f.fontStyle === 'italic' || f.fontStyle === 'oblique';
2140
- const key = fontKey(f.family, weight, italic);
2141
- map.set(key, { family: f.family, src: f.src, weight, italic });
2142
- }
2143
- }
2144
- return Array.from(map.values());
2145
- }
2146
957
  // ─── Template serialization ─────────────────────────────────────────
2147
958
  //
2148
959
  // Parallel to `serialize()` but detects proxy markers and expr markers,