@formepdf/react 0.9.2 → 0.10.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
@@ -203,6 +203,14 @@ function serializePage(element) {
203
203
  margin = expandEdges(props.margin);
204
204
  }
205
205
  const config = { size, margin, wrap: true };
206
+ if (props.backgroundImage !== undefined)
207
+ config.backgroundImage = props.backgroundImage;
208
+ if (props.backgroundOpacity !== undefined)
209
+ config.backgroundOpacity = props.backgroundOpacity;
210
+ if (props.backgroundSize !== undefined)
211
+ config.backgroundSize = props.backgroundSize;
212
+ if (props.backgroundPosition !== undefined)
213
+ config.backgroundPosition = props.backgroundPosition;
206
214
  const childElements = flattenChildren(props.children);
207
215
  const children = serializeChildren(childElements, 'Page');
208
216
  return {
@@ -1105,6 +1113,13 @@ export function mapStyle(style) {
1105
1113
  result.textAlign = TEXT_ALIGN_MAP[style.textAlign];
1106
1114
  if (style.letterSpacing !== undefined)
1107
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
+ }
1108
1123
  if (style.textDecoration !== undefined)
1109
1124
  result.textDecoration = TEXT_DECORATION_MAP[style.textDecoration];
1110
1125
  if (style.textTransform !== undefined)
@@ -1126,6 +1141,21 @@ export function mapStyle(style) {
1126
1141
  result.color = parseColor(style.color);
1127
1142
  if (style.backgroundColor !== undefined)
1128
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
+ }
1129
1159
  if (style.opacity !== undefined)
1130
1160
  result.opacity = style.opacity;
1131
1161
  // Border — cascade: border < borderTop/Right/Bottom/Left < borderWidth/borderColor < borderTopWidth/borderTopColor
@@ -1347,6 +1377,277 @@ export function parseColor(hex) {
1347
1377
  // Fallback: black
1348
1378
  return { r: 0, g: 0, b: 0, a: 1 };
1349
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
+ }
1350
1651
  /**
1351
1652
  * Parse a CSS-style 1-4 value edge shorthand.
1352
1653
  * Accepts: `"8"`, `"8 16"`, `"8 16 24"`, `"8 16 24 32"` (with optional `px` suffix).
package/dist/types.d.ts CHANGED
@@ -89,6 +89,20 @@ export interface Style {
89
89
  lineHeight?: number;
90
90
  textAlign?: 'left' | 'center' | 'right' | 'justify';
91
91
  letterSpacing?: number;
92
+ /** Extra width (points) added to each ASCII space — PDF Tw operator.
93
+ * Negative values tighten word gaps. When `textAlign: 'justify'` is
94
+ * set, the layout engine adds the computed slack-per-space on top. */
95
+ wordSpacing?: number;
96
+ /** Drop shadow painted behind the element. Object form is preferred;
97
+ * CSS-like string form `"offsetX offsetY blur color"` is also
98
+ * accepted. v1 paints a solid offset shadow only — `blur` is parsed
99
+ * for forward-compat but ignored. */
100
+ boxShadow?: string | {
101
+ offsetX: number;
102
+ offsetY: number;
103
+ blur?: number;
104
+ color: string;
105
+ };
92
106
  textDecoration?: 'none' | 'underline' | 'line-through';
93
107
  textTransform?: 'none' | 'uppercase' | 'lowercase' | 'capitalize';
94
108
  hyphens?: 'none' | 'manual' | 'auto';
@@ -104,6 +118,17 @@ export interface Style {
104
118
  overflow?: 'visible' | 'hidden';
105
119
  color?: string;
106
120
  backgroundColor?: string;
121
+ /**
122
+ * CSS background. Supports:
123
+ * - solid colors (`"#1e293b"`, `"rgba(...)"`) — equivalent to backgroundColor
124
+ * - 2-stop linear gradients: `"linear-gradient(180deg, #fff 0%, #000 100%)"`
125
+ * - 2-stop radial gradients: `"radial-gradient(circle, #fff 0%, #000 100%)"`
126
+ *
127
+ * v1 supports exactly 2 color stops; gradients with 3+ stops fall back to
128
+ * the first and last stop. Multi-stop support is planned via PDF Type 3
129
+ * stitching functions in a follow-up.
130
+ */
131
+ background?: string;
107
132
  opacity?: number;
108
133
  borderWidth?: number | Edges;
109
134
  borderTopWidth?: number;
@@ -192,6 +217,15 @@ export interface PageProps {
192
217
  height: number;
193
218
  };
194
219
  margin?: number | string | number[] | Edges;
220
+ /** Optional background image painted behind the page's content. URL,
221
+ * file path, or `data:image/...;base64,` URI. */
222
+ backgroundImage?: string;
223
+ /** Background image opacity 0–1. Defaults to 1.0. */
224
+ backgroundOpacity?: number;
225
+ /** How the background image is sized within the page. */
226
+ backgroundSize?: 'fill' | 'cover' | 'contain';
227
+ /** Where the background image is positioned within the page. */
228
+ backgroundPosition?: 'center' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
195
229
  children?: ReactNode;
196
230
  }
197
231
  export interface ViewProps {
@@ -613,6 +647,10 @@ export interface FormePageConfig {
613
647
  size: FormePageSize;
614
648
  margin: FormeEdges;
615
649
  wrap: boolean;
650
+ backgroundImage?: string;
651
+ backgroundOpacity?: number;
652
+ backgroundSize?: 'fill' | 'cover' | 'contain';
653
+ backgroundPosition?: 'center' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
616
654
  }
617
655
  export type FormePageSize = 'A4' | 'A3' | 'A5' | 'Letter' | 'Legal' | 'Tabloid' | {
618
656
  Custom: {
@@ -626,6 +664,42 @@ export interface FormeEdges {
626
664
  bottom: number;
627
665
  left: number;
628
666
  }
667
+ export interface FormeBoxShadow {
668
+ offsetX: number;
669
+ offsetY: number;
670
+ blur?: number;
671
+ color: {
672
+ r: number;
673
+ g: number;
674
+ b: number;
675
+ a: number;
676
+ };
677
+ }
678
+ export interface FormeGradientStop {
679
+ position: number;
680
+ color: {
681
+ r: number;
682
+ g: number;
683
+ b: number;
684
+ a: number;
685
+ };
686
+ }
687
+ export type FormeBackground = {
688
+ type: 'color';
689
+ value: {
690
+ r: number;
691
+ g: number;
692
+ b: number;
693
+ a: number;
694
+ };
695
+ } | {
696
+ type: 'linear';
697
+ angleDeg: number;
698
+ stops: FormeGradientStop[];
699
+ } | {
700
+ type: 'radial';
701
+ stops: FormeGradientStop[];
702
+ };
629
703
  /** Margin edges that support auto values (for centering). */
630
704
  export interface FormeMarginEdges {
631
705
  top: number | 'auto';
@@ -870,6 +944,8 @@ export interface FormeStyle {
870
944
  lineHeight?: number;
871
945
  textAlign?: string;
872
946
  letterSpacing?: number;
947
+ wordSpacing?: number;
948
+ boxShadow?: FormeBoxShadow;
873
949
  textDecoration?: string;
874
950
  textTransform?: string;
875
951
  hyphens?: string;
@@ -880,6 +956,7 @@ export interface FormeStyle {
880
956
  overflow?: string;
881
957
  color?: FormeColor;
882
958
  backgroundColor?: FormeColor;
959
+ background?: FormeBackground;
883
960
  opacity?: number;
884
961
  borderWidth?: FormeEdgeValues<number>;
885
962
  borderColor?: FormeEdgeValues<FormeColor>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@formepdf/react",
3
- "version": "0.9.2",
3
+ "version": "0.10.0",
4
4
  "description": "JSX-to-JSON serializer for Forme PDF engine",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",