@openpresentation/opf-render 0.34.2 → 0.35.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/charts.js CHANGED
@@ -7,20 +7,20 @@
7
7
  import { chartAxisFraction as axisFraction, chartAxisScale as composedScale, chartBarGeometry, chartBarSeriesOffset, chartDrawPlan, chartSlicePlan, CHART_SLICE_SEPARATOR_PX, histogramBins, paretoPlan, scottBinCount, chartWaterfallColors, waterfallLabelText, markLabelColor, chartEmphasisColors, chartSeriesLabelColor, chartContextColors, chartFocusContextColors, chartSeriesStrokes, chartHighlightColors, chartHighlightMarks, chartLayerDataLabels, chartNumber, chartValueAxisHidden, chartPaletteForFill, chartSchemeSeries, chartSeriesPalette as coreChartSeriesPalette, chartTextSize, CHART_MAX_INTERVALS, chartIntervalsFor, formatDataNumber, groupNumber, groupsAxisTicks, groupsDataRange, groupsThousands, maxIntervalsFor, niceScale, stackCategoryValues, waterfallSteps, numberFormatError, resolveChartData, resolveTextStyle, textColorForFill, textWidthMeasurer, formatNumber, formatPercentNumber, chartNumberLanguage } from "@openpresentation/opf/composition";
8
8
  import { drawAxisTitles, drawBarLabel, drawCenteredLabel, drawPointLabel, drawSliceLabel, labelFill, labelString, outsideLabelReserve, reportOptionDiagnostics, reserveAxisTitles, resolveOptions } from "./chart-options.js";
9
9
 
10
- // The series colours for a chart panel: core's `chartSeriesPalette` (the deck colour scheme's accents, RR-89, with the chart's own
10
+ // The series colors for a chart panel: core's `chartSeriesPalette` (the deck color scheme's accents, RR-89, with the chart's own
11
11
  // `colors` entries replacing their positions) adjusted by core's `chartPaletteForFill` (contrast against the panel without letting
12
- // two series merge). The PPTX export and the validator use the same pair, so the preview draws the colours they write.
12
+ // two series merge). The PPTX export and the validator use the same pair, so the preview draws the colors they write.
13
13
  // WI-5 (P18, D3) and LH-55: every series from the scheme reaches 4.5:1 on a dark panel, series 2 a lightness step from series 1 (an authored
14
14
  // `colors` entry keeps the 3:1 floor).
15
15
  // LH-105: `soften` mixes each scheme series a quarter of the way towards the backdrop (core softenChartPalette), keeping its contrast and its
16
- // lightness step from its neighbours: ordinary data in soft colours, the full-strength colour left for emphasis.
16
+ // lightness step from its neighbors: ordinary data in soft colors, the full-strength color left for emphasis.
17
17
  export function chartSeriesPalette(surface, colorScheme, colors, context, { soften = false } = {}) {
18
18
  return chartPaletteForFill(surface, coreChartSeriesPalette(colorScheme, colors, context), { legible: chartSchemeSeries(colors, colorScheme, context), soften });
19
19
  }
20
20
 
21
- // FA-14: chart.highlight. Core resolves which series and categories are named (chartHighlightMarks) and the two colours
21
+ // FA-14: chart.highlight. Core resolves which series and categories are named (chartHighlightMarks) and the two colors
22
22
  // (chartHighlightColors); a highlighted mark takes the accent, every other mark the muted neutral. A chart without a
23
- // highlight has no `c.highlight`, and every colour below is the palette colour it always was.
23
+ // highlight has no `c.highlight`, and every color below is the palette color it always was.
24
24
  function highlightFor(c, resolved, spec, data) {
25
25
  if (!resolved.highlight) return undefined;
26
26
  const marks = chartHighlightMarks(resolved.highlight, { columns: data.columns, hasX: spec.kind === "scatter" && data.hasX, rows: data.rows });
@@ -28,19 +28,19 @@ function highlightFor(c, resolved, spec, data) {
28
28
  return { ...marks, ...chartHighlightColors(c.surface, c.bound.design.colors.primary, c.labelColor) };
29
29
  }
30
30
 
31
- // LH-03, LH-95: a one-series small column or bar chart draws its emphasised point (core: the last one with a value) in a stronger shade of
32
- // the series colour and every other point in the series colour (core chartEmphasisColors); it is drawn as a category highlight of that point.
31
+ // LH-03, LH-95: a one-series small column or bar chart draws its emphasized point (core: the last one with a value) in a stronger shade of
32
+ // the series color and every other point in the series color (core chartEmphasisColors); it is drawn as a category highlight of that point.
33
33
  function emphasisFor(c, layer) {
34
34
  const row = layer?.small?.emphasis;
35
- // LH-105: the emphasised point takes the series colour at full strength (or a shade of it); the others keep the soft colour.
35
+ // LH-105: the emphasized point takes the series color at full strength (or a shade of it); the others keep the soft color.
36
36
  const colors = row === undefined ? undefined : chartEmphasisColors(c.surface, c.colors[0], c.strongColors[0]);
37
37
  return colors ? { series: [false], categories: c.rows.map((_, i) => i === row), ...colors } : undefined;
38
38
  }
39
39
 
40
- // LH-105: the series or categories the slide title names (core chart-focus.ts) take their full-strength colour, the other marks the
40
+ // LH-105: the series or categories the slide title names (core chart-focus.ts) take their full-strength color, the other marks the
41
41
  // context neutrals (core chartContextColors: one gray per context series or slice, 11 L* apart, the first the strongest; 3:1 against the
42
- // backdrop, or 1.6:1 when every context mark carries its text). It is drawn as a highlight whose accent is each series' own colour (and
43
- // each slice's, on a pie) and whose muted colour is each context series' (or slice's) own gray.
42
+ // backdrop, or 1.6:1 when every context mark carries its text). It is drawn as a highlight whose accent is each series' own color (and
43
+ // each slice's, on a pie) and whose muted color is each context series' (or slice's) own gray.
44
44
  function focusFor(c, layer, spec) {
45
45
  const focus = layer?.focus;
46
46
  if (!focus) return undefined;
@@ -63,7 +63,7 @@ function focusFor(c, layer, spec) {
63
63
  return { series, categories, accent: strong(0), muted: grays[0], accents: series.map((_, j) => strong(j)), mutedSeries };
64
64
  }
65
65
 
66
- // LH-81: the header row. The caption (bold, the full text colour) and the legend entries sit where core placed them; the band they take
66
+ // LH-81: the header row. The caption (bold, the full text color) and the legend entries sit where core placed them; the band they take
67
67
  // is carved from the top of the chart box, and a header legend replaces the side legend (c.legendManaged).
68
68
  function drawHeader(c, spec, header) {
69
69
  const rtl = c.bound.geometry?.direction === "rtl";
@@ -89,12 +89,12 @@ function drawHeader(c, spec, header) {
89
89
  c.box = { x: outer.x, y: outer.y + header.height, width: outer.width, height: Math.max(1, outer.height - header.height) };
90
90
  }
91
91
 
92
- /** The colour of series `j` as a whole (a line, an area, a legend key): the accent when highlighted, else muted. */
92
+ /** The color of series `j` as a whole (a line, an area, a legend key): the accent when highlighted, else muted. */
93
93
  function seriesColor(c, j) {
94
94
  return c.highlight ? (c.highlight.series[j] ? c.highlight.accents?.[j] ?? c.highlight.accent : c.highlight.mutedSeries?.[j] ?? c.highlight.muted) : c.colors[j % c.colors.length];
95
95
  }
96
96
 
97
- /** The colour of the mark of series `j` at row `i`: highlighted when its series or its category is named. */
97
+ /** The color of the mark of series `j` at row `i`: highlighted when its series or its category is named. */
98
98
  function markColor(c, j, i) {
99
99
  return c.highlight ? (c.highlight.series[j] || c.highlight.categories[i] ? c.highlight.accents?.[j] ?? c.highlight.accent : c.highlight.mutedSeries?.[j] ?? c.highlight.muted) : c.colors[j % c.colors.length];
100
100
  }
@@ -195,7 +195,7 @@ export function renderCatalogChart(item, box, bound, options, svg) {
195
195
  const doughnutFit = layer?.doughnut?.labels;
196
196
  const fitReport = doughnutFit && { code: "chart-option-adapted", option: "dataLabels.content", reason: "unsupported-content", message: `The labels of a doughnut sit inside their slices, and '${doughnutFit.from.join(', ')}' does not fit the ring, so ${doughnutFit.content ? `they show '${doughnutFit.content.join(', ')}' instead (the legend names the slices)` : 'no labels are drawn (the legend names the slices)'}.` };
197
197
  if (fitReport && authoredSpec) resolved.diagnostics = [...resolved.diagnostics, fitReport];
198
- // FA-14: a highlight changes colours only (no space is reserved), so it is resolved whether or not an option is active.
198
+ // FA-14: a highlight changes colors only (no space is reserved), so it is resolved whether or not an option is active.
199
199
  c.highlight = highlightFor(c, resolved, spec, data) ?? focusFor(c, layer, spec) ?? emphasisFor(c, layer);
200
200
  // LH-03, LH-142: no value axis (a small chart's labels or a horizontal stacked bar chart's segment values carry the values): core decides it.
201
201
  c.valueAxisHidden = chartValueAxisHidden(layer);
@@ -312,12 +312,12 @@ function chartContext(item, box, bound, options, svg, { rows, columns, formats,
312
312
  const composition = bound.composition ?? bound.geometry.composition ?? {};
313
313
  // RR-90: core's chart text size (20 px, shrunk only for a small box, never below minFontSize), the size core's value-axis density assumes.
314
314
  const requested = chartTextSize({ width: box.width, height: box.height, scale: u, minFontSize: composition.minFontSize }), fontPx = requested * u;
315
- // LH-03, LH-105: a chart has no panel, so its colours are judged against what it stands on: the card, or the slide background.
315
+ // LH-03, LH-105: a chart has no panel, so its colors are judged against what it stands on: the card, or the slide background.
316
316
  const surface = item.frameBox ? bound.design.roles.neutrals.card.hex : bound.design.backgroundColor ?? bound.design.colors.background;
317
- // RR-96: every neutral comes from the slide's variant (core `roles.neutrals`: tx1 mixed into bg1, the colours the PPTX export writes as
318
- // scheme colours): chart text, gridlines, axis lines and the outline between marks (bg1).
317
+ // RR-96: every neutral comes from the slide's variant (core `roles.neutrals`: tx1 mixed into bg1, the colors the PPTX export writes as
318
+ // scheme colors): chart text, gridlines, axis lines and the outline between marks (bg1).
319
319
  const neutrals = bound.design.roles.neutrals;
320
- // The quiet colour of axis, legend and category text; `labelColor` stays the full text colour (highlight mutes toward it and labels inside
320
+ // The quiet color of axis, legend and category text; `labelColor` stays the full text color (highlight mutes toward it and labels inside
321
321
  // marks contrast against it, as the PPTX export draws them).
322
322
  const chartTextColor = textColorForFill(surface, neutrals.chartText.hex);
323
323
  const labelColor = textColorForFill(surface, bound.design.colors.text);
@@ -340,7 +340,7 @@ const neutrals = bound.design.roles.neutrals;
340
340
  pad: 10 * u,
341
341
  lineHeight: fontPx * 1.5,
342
342
  // One text line as renderTextBox lays it out (fitText line height), and the
343
- // clear space kept between neighbouring category labels.
343
+ // clear space kept between neighboring category labels.
344
344
  textHeight: fontPx * 1.22,
345
345
  labelGap: fontPx * 0.1,
346
346
  colors: chartSeriesPalette(surface, bound.design.colorScheme, item.value?.colors, { accents: bound.design.roles.map.accents, roles: bound.design.colors, variables: bound.design.variables }, { soften: true }),
@@ -444,7 +444,7 @@ function dataGroup(c, format, values, options) {
444
444
 
445
445
  // RR-54: a formatted horizontal axis (horizontal bars, the scatter X axis) can have end tick labels far wider than the margin the layout
446
446
  // leaves beside the plot (a General label is a few characters, a long format code is not). Pull the plot in until the first and
447
- // last labels, centred on their ticks, stay inside the chart, and lay the ticks out again for the new width. Only formatted axes call it,
447
+ // last labels, centered on their ticks, stay inside the chart, and lay the ticks out again for the new width. Only formatted axes call it,
448
448
  // so a General axis keeps its placement.
449
449
  function insetForEndLabels(c, x, width, format, scaleFor) {
450
450
  const left = c.box.x + c.pad, right = c.box.x + c.box.width - c.pad;
@@ -530,7 +530,7 @@ function placeLegend(c, spec, position) {
530
530
  c.box = { x: position === "left" ? outer.x + reserve : outer.x, y: outer.y, width: Math.max(1, outer.width - reserve), height: outer.height };
531
531
  return;
532
532
  }
533
- // Top and bottom: entries flow left to right in rows, each row centred, wrapping when the row would pass the chart width.
533
+ // Top and bottom: entries flow left to right in rows, each row centered, wrapping when the row would pass the chart width.
534
534
  const available = Math.max(1, outer.width - 2 * c.pad), spacing = c.fontPx * 0.8;
535
535
  const sized = entries.map((entry) => ({ entry, width: Math.min(available, metrics.keyWidth + metrics.gap + c.width(entry.name) + spacing) }));
536
536
  const rows = [];
@@ -721,8 +721,8 @@ function drawBottomLabels(c, plan, plot, entries, drop = 0) {
721
721
  if (text) c.children.push(c.svg.tag("g", { transform: `rotate(${-plan.angle} ${c.num(px)} ${c.num(py)})` }, text));
722
722
  continue;
723
723
  }
724
- const centred = Math.abs(label.left - (label.cx - label.width / 2)) < 1e-6;
725
- const rect = plan.n === 1 && centred && label.width <= band
724
+ const centered = Math.abs(label.left - (label.cx - label.width / 2)) < 1e-6;
725
+ const rect = plan.n === 1 && centered && label.width <= band
726
726
  ? { x: plot.x + label.i * band, y, width: band, height: plan.reserve }
727
727
  : { x: label.left - 1, y, width: label.width + 2, height: plan.reserve };
728
728
  c.text(label.text, rect, path);
@@ -732,7 +732,7 @@ function drawBottomLabels(c, plan, plot, entries, drop = 0) {
732
732
 
733
733
  // A vertical category axis (labels to the left of horizontal bars and funnels).
734
734
  // Labels stay on one line inside the gutter, wrap at spaces onto two lines when
735
- // their rows are tall enough, else are ellipsized; every n-th row is labelled
735
+ // their rows are tall enough, else are ellipsized; every n-th row is labeled
736
736
  // when the rows are shorter than a line of text. LH-120: a row is tall enough for
737
737
  // two lines when it holds one line and the glyphs of a second (a line plus one
738
738
  // text size): the label then reaches into the gap between bars, and only a label
@@ -937,7 +937,7 @@ function drawLines(c, spec, series, stacks, { plot, band, at, categorySlot = (i)
937
937
  run.push([plot.x + (categorySlot(i) + 0.5) * band, at(point.to)]);
938
938
  });
939
939
  flush();
940
- // FA-14: with a highlight each point takes its own colour, and a line without markers marks the highlighted categories' points.
940
+ // FA-14: with a highlight each point takes its own color, and a line without markers marks the highlighted categories' points.
941
941
  if (spec.markers || c.highlight?.categories.some(Boolean)) stacks[j].forEach((point, i) => {
942
942
  if (!point || (!spec.markers && !c.highlight.categories[i])) return;
943
943
  const fill = markColor(c, j, i);
@@ -949,7 +949,7 @@ function drawLines(c, spec, series, stacks, { plot, band, at, categorySlot = (i)
949
949
  if (point) drawPointLabel(c, labelString(c, { category: c.rows[i][0] === null || c.rows[i][0] === undefined ? "" : String(c.rows[i][0]), value: s.values[i], format: s.format, group: s.group }), [plot.x + (categorySlot(i) + 0.5) * band, at(point.to)], `${c.path}.data.rows.${i}.${s.column}`);
950
950
  }));
951
951
  // LH-105: each series' last value and name at the end of its line ("61 Enterprise NPS"), in the box core placed it
952
- // (chart-direct-labels.ts), in its colour made legible as text; bold for a series the title names.
952
+ // (chart-direct-labels.ts), in its color made legible as text; bold for a series the title names.
953
953
  for (const entry of c.endLabels?.entries ?? []) {
954
954
  const s = series[entry.series];
955
955
  if (!s) continue;
@@ -1179,7 +1179,7 @@ function renderComboChart(c, spec) {
1179
1179
  }
1180
1180
 
1181
1181
  // ---------------------------------------------------------------------------
1182
- // Pie and doughnut: clockwise from 12 o'clock, one colour per category; a doughnut of several series draws one ring per series (LH-60).
1182
+ // Pie and doughnut: clockwise from 12 o'clock, one color per category; a doughnut of several series draws one ring per series (LH-60).
1183
1183
 
1184
1184
  function renderCircularChart(c, spec) {
1185
1185
  const { box, pad } = c;
@@ -1257,8 +1257,8 @@ function renderCircularChart(c, spec) {
1257
1257
  if (list) drawValueList(c, list);
1258
1258
  }
1259
1259
 
1260
- // LH-92: a ring's name, centred in its band at the slice's middle and turned along the ring by core's rotation (the PPTX label's
1261
- // custom angle), in the colour that contrasts with the slice.
1260
+ // LH-92: a ring's name, centered in its band at the slice's middle and turned along the ring by core's rotation (the PPTX label's
1261
+ // custom angle), in the color that contrasts with the slice.
1262
1262
  function drawRingName(c, text, { cx, cy, r, inner, mid }, path, fill, rotation = 0) {
1263
1263
  const radius = (r + inner) / 2, x = cx + radius * Math.cos(mid), y = cy + radius * Math.sin(mid);
1264
1264
  const width = c.width(text) + c.fontPx * 0.5, height = c.lineHeight;
@@ -1443,7 +1443,7 @@ function renderRadarChart(c, spec) {
1443
1443
  // Chartex constructs (FF-22b). opf-pptx writes these as native Office 2016
1444
1444
  // chartex parts (cx:series layoutId treemap, clusteredColumn with binning or
1445
1445
  // aggregation, paretoLine, boxWhisker, waterfall, funnel, regionMap); the
1446
- // previews below draw the same data with the same colours and defaults.
1446
+ // previews below draw the same data with the same colors and defaults.
1447
1447
 
1448
1448
  /**
1449
1449
  * The plotted column of a chartex chart: [Category, Value, ...] plots the first
@@ -1533,7 +1533,7 @@ function renderHistogramChart(c, spec) {
1533
1533
  drawBarLabel(c, labelString(c, { category: bar.name, value: bar.value, format, group: labelGroup }), { x: plot.x + i * band + offset, y: Math.min(y, crossing), width, height: Math.abs(crossing - y) }, bar.value >= 0 ? "up" : "down", bar.path, c.colors[0]);
1534
1534
  });
1535
1535
  if (pareto && bars.length) {
1536
- // Percentage axis on the right, 0-100%, and the cumulative line through the bar centres.
1536
+ // Percentage axis on the right, 0-100%, and the cumulative line through the bar centers.
1537
1537
  // RR-105: the percentage step core composed (layer.histogram.percentUnit), which the PPTX export writes on the secondary axis.
1538
1538
  const percent = (c.histogram?.percentUnit > 0 ? composedScale({ min: 0, max: 1, majorUnit: c.histogram.percentUnit }) : undefined) ?? niceScale(0, 1, chartIntervalsFor(plot.height, c.lineHeight * 1.2, c.u), { percent: true });
1539
1539
  const right = plot.x + plot.width;
@@ -1550,9 +1550,9 @@ function renderHistogramChart(c, spec) {
1550
1550
  }
1551
1551
  }
1552
1552
 
1553
- // Waterfall: floating bars from the running total, increases and decreases in the first two palette colours, connector lines between bars.
1553
+ // Waterfall: floating bars from the running total, increases and decreases in the first two palette colors, connector lines between bars.
1554
1554
  // LH-59: a last value equal to the running sum of the steps before it is a total (core's waterfallSteps): it stands on zero in the third
1555
- // palette colour, as PowerPoint draws the cx:subtotals point the export writes.
1555
+ // palette color, as PowerPoint draws the cx:subtotals point the export writes.
1556
1556
  // LH-107: core's roles (layer.waterfall): totals in the strong color, gains in the accent, losses in the context gray (core
1557
1557
  // chartWaterfallColors), signed default labels (a total's bold and unsigned), dashed connectors and, with default labels, no value axis.
1558
1558
  const waterfallColor = (bar, palette) => palette[(bar.total ? 2 : bar.value < 0 ? 1 : 0) % palette.length];
@@ -1594,7 +1594,7 @@ function renderWaterfallChart(c) {
1594
1594
  });
1595
1595
  }
1596
1596
 
1597
- // Funnel: centred bars from the top, widths proportional to the value, value labels inside and category labels on the left.
1597
+ // Funnel: centered bars from the top, widths proportional to the value, value labels inside and category labels on the left.
1598
1598
  function renderFunnelChart(c) {
1599
1599
  const { box, pad, fontPx } = c;
1600
1600
  const { column, values, categories } = chartexValues(c.rows, c.columns);
@@ -1668,7 +1668,7 @@ export function squarify(items, x, y, width, height) {
1668
1668
  return rects;
1669
1669
  }
1670
1670
 
1671
- // Treemap: one tile per category from the first value column (positive values only), one palette colour per tile, category labels inside.
1671
+ // Treemap: one tile per category from the first value column (positive values only), one palette color per tile, category labels inside.
1672
1672
  function renderTreemapChart(c) {
1673
1673
  const { box, pad, fontPx } = c;
1674
1674
  const { column, values, categories } = chartexValues(c.rows, c.columns);
@@ -1765,14 +1765,14 @@ function renderBoxWhiskerChart(c) {
1765
1765
  });
1766
1766
  }
1767
1767
 
1768
- // LH-56: a label inside a mark (a treemap tile, a funnel bar, a map tile) takes core's markLabelColor for that fill: the full text colour
1768
+ // LH-56: a label inside a mark (a treemap tile, a funnel bar, a map tile) takes core's markLabelColor for that fill: the full text color
1769
1769
  // when it reaches 4.5:1 on the fill, else the slide background, else black or white, as the PPTX export writes the same labels.
1770
1770
  function insideText(c, value, rect, path, fill, align = "center") {
1771
1771
  const element = c.textElement(value, rect, path, align, markLabelColor(fill, c.labelColor, c.bound.design.colors.background));
1772
1772
  if (element) c.children.push(element);
1773
1773
  }
1774
1774
 
1775
- /** Mix two hex colours (#RRGGBB) by `t` in [0, 1], rounded per channel. */
1775
+ /** Mix two hex colors (#RRGGBB) by `t` in [0, 1], rounded per channel. */
1776
1776
  export function mixHex(from, to, t) {
1777
1777
  const channel = (hex, i) => parseInt(hex.slice(1 + 2 * i, 3 + 2 * i), 16);
1778
1778
  const clamp = Math.min(1, Math.max(0, t));
@@ -1781,8 +1781,8 @@ export function mixHex(from, to, t) {
1781
1781
 
1782
1782
  // Region map: an honest non-geographic preview. PowerPoint draws the map from
1783
1783
  // Bing geodata it fetches itself; the preview shows one tile per region, shaded
1784
- // from a light tint to the series colour by value, with the region name and
1785
- // its value, so labels and colours are traceable without shipping geography.
1784
+ // from a light tint to the series color by value, with the region name and
1785
+ // its value, so labels and colors are traceable without shipping geography.
1786
1786
  function renderRegionMapChart(c) {
1787
1787
  const { box, pad, fontPx } = c;
1788
1788
  const { column, values, categories } = chartexValues(c.rows, c.columns);
@@ -1,25 +1,25 @@
1
- // Colour fonts (FF-45). Noto Color Emoji ships COLRv1 and OT-SVG colour glyphs with empty outlines in `glyf`. Browsers
2
- // draw them in colour (Chromium and Firefox from COLRv1, Safari from the SVG table), and fontkit shapes and measures the
1
+ // Color fonts (FF-45). Noto Color Emoji ships COLRv1 and OT-SVG color glyphs with empty outlines in `glyf`. Browsers
2
+ // draw them in color (Chromium and Firefox from COLRv1, Safari from the SVG table), and fontkit shapes and measures the
3
3
  // face, so the SVG names it. resvg (the raster path) draws neither COLRv1 nor OT-SVG glyphs and would paint nothing, so
4
4
  // the raster path draws the package's monochrome stand-in (Noto Emoji) instead: measured advances are pinned by
5
5
  // textLength where runs are positioned, and the raster shows a black-and-white silhouette, which is a documented limit.
6
6
  import { BUNDLED_FONT_MANIFEST } from "./font-manifest.js";
7
7
 
8
- /** Every colour face of the manifest: its family, package-relative file, colour format and the monochrome family the raster path draws. */
8
+ /** Every color face of the manifest: its family, package-relative file, color format and the monochrome family the raster path draws. */
9
9
  export const COLOR_FONT_FACES = Object.freeze(BUNDLED_FONT_MANIFEST.packages.filter(pkg => pkg.color).flatMap(pkg => pkg.faces.map(face => Object.freeze({
10
10
  family: face.family, file: face.file, package: pkg.name, format: pkg.color.format, rasterFamily: pkg.color.rasterFamily,
11
11
  }))));
12
12
  const rasterFamilyOf = new Map(COLOR_FONT_FACES.map(face => [face.family.toLowerCase(), face.rasterFamily]));
13
13
  const colorFiles = COLOR_FONT_FACES.map(face => face.file.replace(/\\/g, "/"));
14
14
 
15
- /** `files` without the colour faces, which resvg cannot draw (they would also catch its glyph fallback and paint nothing). */
15
+ /** `files` without the color faces, which resvg cannot draw (they would also catch its glyph fallback and paint nothing). */
16
16
  export function rasterFontFiles(files) {
17
17
  return files.filter(file => { const normalized = String(file).replace(/\\/g, "/"); return !colorFiles.some(suffix => normalized.endsWith(`/${suffix}`)); });
18
18
  }
19
19
 
20
20
  const fontFamilyAttribute = /(\sfont-family\s*=\s*)(?:"([^"]*)"|'([^']*)')/g;
21
21
  const unquote = name => name.trim().replace(/^(["'])(.*)\1$/, "$2");
22
- /** SVG about to be rasterized only (never the emitted SVG): text in a colour family is drawn with its monochrome stand-in. */
22
+ /** SVG about to be rasterized only (never the emitted SVG): text in a color family is drawn with its monochrome stand-in. */
23
23
  export function monochromeColorFonts(svg) {
24
24
  if (!rasterFamilyOf.size || !/<(?:text|tspan)[\s>]/.test(svg)) return svg;
25
25
  return svg.replace(fontFamilyAttribute, (match, prefix, doubleQuoted, singleQuoted) => {
@@ -165,7 +165,7 @@ export function svgDimensions(svg) {
165
165
 
166
166
  /**
167
167
  * The renderer's SVG made responsive and readable: the fixed `width` and `height` go (the viewBox scales it), and the root's
168
- * labelled-container attributes (`role="group"`, `aria-roledescription="slide"`, `aria-label`) go too, because the slide section or figure around it
168
+ * labeled-container attributes (`role="group"`, `aria-roledescription="slide"`, `aria-label`) go too, because the slide section or figure around it
169
169
  * carries the one accessible name, so a slide is announced once. The slide's own text nodes reach a screen reader in document order,
170
170
  * which is the reading order (tag, title, content, footnotes, then header and footer) the renderer paints; purely decorative drawing
171
171
  * keeps its `aria-hidden`.
@@ -187,7 +187,7 @@ export function prepareSlideSvg(svg, { idPrefix } = {}) {
187
187
  const UNSAFE_ELEMENTS = new Set(["script", "foreignobject", "iframe", "object", "embed", "animate", "set", "animatetransform", "animatemotion"]);
188
188
 
189
189
  /**
190
- * Defence in depth for a parsed slide: the renderer escapes everything it writes, but a player may be pointed at a deck
190
+ * Defense in depth for a parsed slide: the renderer escapes everything it writes, but a player may be pointed at a deck
191
191
  * nobody reviewed, so scripts, event handlers, foreign content and SMIL animation never reach the page.
192
192
  */
193
193
  export function sanitizeSvgTree(root) {
@@ -6,7 +6,7 @@ export type { PdfDiagnostic, PdfMetadata } from "./index.js";
6
6
  export interface BrowserToPngOptions extends ToSvgOptions {
7
7
  /** Multiplies the SVG's own size (default 1). The result is limited to 40 megapixels. */
8
8
  scale?: number;
9
- /** A CSS colour painted first (default white); `"transparent"` keeps the alpha channel. */
9
+ /** A CSS color painted first (default white); `"transparent"` keeps the alpha channel. */
10
10
  background?: string;
11
11
  /**
12
12
  * How the SVG is handed to the browser's image decoder: a `blob:` URL (default) or a `data:` URL, for a page whose Content-Security-Policy
@@ -19,7 +19,7 @@ const MAX_PIXELS = 40_000_000;
19
19
  /**
20
20
  * PNG with a canvas (RR-73): a deck drawn with `toSvg` (all slides, a slide number or a selection, as for the Node `toPng`) or SVG
21
21
  * the renderer drew; one PNG for a slide number or one SVG, a list otherwise. `scale` multiplies the SVG's own size; `background`
22
- * is a CSS colour (default white, `"transparent"` for none).
22
+ * is a CSS color (default white, `"transparent"` for none).
23
23
  */
24
24
  export async function toPng(source, slides, options) {
25
25
  ({ slides, options } = slideArguments(slides, options));
@@ -352,7 +352,7 @@ export async function createNodeDemand(
352
352
  return {request, selected};
353
353
  });
354
354
  const wanted = new Set([...drawn, ...measured.map(({selected}) => selected)].map(key)), rasterRequired = new Set();
355
- // A selected manifest colour face also needs its effective monochrome raster face.
355
+ // A selected manifest color face also needs its effective monochrome raster face.
356
356
  // This is a dependency of the drawn face, not another script/pack or a caller-face substitution.
357
357
  for (const face of universe) {
358
358
  if (!wanted.has(key(face)) || callerFaceKeys.has(key(face)) || !face.pkg.color?.rasterFamily) continue;
@@ -315,7 +315,7 @@ export function createFontRegistry(entries, options = {}, {allowEmpty = false, c
315
315
  let pen = 0, bounds = null;
316
316
  for (const glyph of glyphs) {
317
317
  if (includeOutline) {
318
- // Colour/bitmap glyphs may have no fontkit outline (the em-box fallback below still applies).
318
+ // Color/bitmap glyphs may have no fontkit outline (the em-box fallback below still applies).
319
319
  let box;
320
320
  try { box = face.font.getGlyph(glyph.gid).bbox; } catch { box = null; }
321
321
  if (box && [box.minX, box.minY, box.maxX, box.maxY].every(Number.isFinite) && box.width > 0 && box.height > 0) {
@@ -335,8 +335,8 @@ export function createFontRegistry(entries, options = {}, {allowEmpty = false, c
335
335
  if(includeOutline) {
336
336
  const unit=face.font.unitsPerEm;
337
337
  let bounds=null;
338
- // FF-45: fontkit reads COLR v0 layers only; a COLRv1 colour face (Noto Color Emoji) has no outlines it can bound (its
339
- // glyf outlines are empty), so its ink box is the face's em box over the run: the colour image fills the em square.
338
+ // FF-45: fontkit reads COLR v0 layers only; a COLRv1 color face (Noto Color Emoji) has no outlines it can bound (its
339
+ // glyf outlines are empty), so its ink box is the face's em box over the run: the color image fills the em square.
340
340
  try { bounds=run.bbox; } catch { bounds=null; }
341
341
  if(bounds&&[bounds.minX,bounds.minY,bounds.maxX,bounds.maxY].every(Number.isFinite)) value.outline={x:bounds.minX/unit,y:-bounds.maxY/unit,width:bounds.width/unit,height:bounds.height/unit};
342
342
  else if(face.font.directory?.tables?.COLR&&value.width>0) { const ascent=face.font.ascent/unit,descent=face.font.descent/unit; value.outline={x:0,y:-ascent,width:value.width,height:ascent-descent}; }
package/dist/fonts.d.ts CHANGED
@@ -179,5 +179,5 @@ export declare const EMOJI_FONT_FAMILIES: readonly string[];
179
179
  export declare function hasEmojiPresentation(text: string): boolean;
180
180
  /** True when the text holds mathematical notation that text faces lack (math alphanumerics, letterlike math sets, rarer operator blocks). */
181
181
  export declare function hasMathNotation(text: string): boolean;
182
- /** Colour faces of the manifest: resvg draws their monochrome stand-in (`rasterFamily`); browsers draw them in colour. */
182
+ /** Color faces of the manifest: resvg draws their monochrome stand-in (`rasterFamily`); browsers draw them in color. */
183
183
  export declare const COLOR_FONT_FACES: readonly { family: string; file: string; package: string; format: string; rasterFamily: string }[];
package/dist/index.d.ts CHANGED
@@ -30,7 +30,7 @@ export declare const engineDefaults: Readonly<{
30
30
  export type RenderDiagnostic = LayoutDiagnostic | {
31
31
  /** A generated RTL numbered marker stayed text; this PNG/raster-PDF marker is not direction-qualified. */
32
32
  code: "raster-marker-unavailable";
33
- reason: "unresolved" | "restricted" | "colour-font" | "system-fonts";
33
+ reason: "unresolved" | "restricted" | "color-font" | "system-fonts";
34
34
  fontFamily?: string;
35
35
  message: string;
36
36
  } | {
@@ -41,7 +41,7 @@ export type RenderDiagnostic = LayoutDiagnostic | {
41
41
  } | {
42
42
  /** A run stays text because its face cannot safely be written as outlines. */
43
43
  code: "text-as-paths-fallback";
44
- reason: "colour-font" | "restricted";
44
+ reason: "color-font" | "restricted";
45
45
  fontFamily: string;
46
46
  message: string;
47
47
  } | {
@@ -93,8 +93,8 @@ export interface ToSvgOptions {
93
93
  * cannot be edited in place. The glyphs are shaped by HarfBuzz (the browser's shaper; the Node handle always, a browser handle
94
94
  * given `shapeWasm`), are hidden from assistive technology, and each outlined line is also invisible real text pinned to the
95
95
  * drawn width, so screen readers, selection, copy and find-in-page get the words. Each element keeps its `data-opf-*` trace.
96
- * A run stays text, reported as `text-as-paths-fallback` with a `reason`, when its font is a colour or bitmap font
97
- * (`"colour-font"`) or its face's fsType restricts embedding (`"restricted"`). Use it for thumbnails, previews and portable SVG files, not for an editing
96
+ * A run stays text, reported as `text-as-paths-fallback` with a `reason`, when its font is a color or bitmap font
97
+ * (`"color-font"`) or its face's fsType restricts embedding (`"restricted"`). Use it for thumbnails, previews and portable SVG files, not for an editing
98
98
  * surface or the vector PDF (which keeps real text from `<text>` SVG).
99
99
  */
100
100
  text?: "fonts" | "system" | "paths";
@@ -175,6 +175,8 @@ export interface ToPngOptions extends Omit<ToSvgOptions, "fonts"> {
175
175
  export type PdfDiagnostic = {
176
176
  /** One per embedded font face: what was embedded, how, and under which embedding permissions. */
177
177
  code: "pdf-font-embedded";
178
+ /** The face, how it was embedded (a subset or the whole font), its size, and the restriction its fsType sets, in a sentence. */
179
+ message: string;
178
180
  family: string; postscriptName: string; weight: number; italic: boolean;
179
181
  /** Distinct glyphs kept, and the size of the embedded font program in bytes. */
180
182
  glyphs: number; bytes: number;
@@ -241,7 +243,7 @@ export interface ToPdfOptions extends Omit<ToPngOptions, "onDiagnostic"> {
241
243
  * the bundled files, the `fonts` handle's `fontFiles` and the font folders you supply, never system fonts.
242
244
  */
243
245
  raster?: boolean;
244
- /** A vector PDF paints the page this colour first (default white, as a raster PDF composites on white); `"none"` leaves it unpainted. */
246
+ /** A vector PDF paints the page this color first (default white, as a raster PDF composites on white); `"none"` leaves it unpainted. */
245
247
  background?: string;
246
248
  /** Vector only. Family drawn for the generic `serif`; default `defaultFontFamily`. */
247
249
  serifFamily?: string;
@@ -299,7 +301,6 @@ export interface RenderBinding {
299
301
  field?: string;
300
302
  value: unknown;
301
303
  path: string;
302
- regionKey?: string;
303
304
  }
304
305
 
305
306
  export declare class OPFRenderError extends Error {
package/dist/pdf-fonts.js CHANGED
@@ -289,8 +289,12 @@ export class FontEmbedder {
289
289
  );
290
290
  const toUnicode = file.addStream("", toUnicodeCMap(cids));
291
291
  file.set(entry.object, "/Type/Font/Subtype/Type0/BaseFont" + name(base) + "/Encoding/Identity-H/DescendantFonts[" + cidFont + " 0 R]/ToUnicode " + toUnicode + " 0 R");
292
+ const label = `${face.postscriptName} (${[...face.names][0]} ${face.weight}${face.italic ? " italic" : ""})`;
293
+ const how = embedding === "subset" ? `as a subset of the ${used.length} glyphs the PDF draws` : `whole, because its fsType forbids subsetting (the PDF draws ${used.length} of its glyphs)`;
294
+ const restricted = face.restriction ? "; its fsType allows the PDF to be viewed and printed only, not edited" : "";
292
295
  return {
293
- code: "pdf-font-embedded", family: [...face.names][0], postscriptName: face.postscriptName, weight: face.weight, italic: face.italic,
296
+ code: "pdf-font-embedded", message: `The font ${label} is embedded in the PDF ${how}, ${fontBytes.length} bytes${restricted}.`,
297
+ family: [...face.names][0], postscriptName: face.postscriptName, weight: face.weight, italic: face.italic,
294
298
  glyphs: used.length, bytes: fontBytes.length, embedding, fsType: face.fsType, ...(face.restriction ? { embeddingRestriction: face.restriction } : {}),
295
299
  ...(face.license ? { license: face.license } : {}), origin: face.origin,
296
300
  };
@@ -312,7 +316,7 @@ export function nominalAdvance(face, gid, cache) {
312
316
  }
313
317
 
314
318
  // A glyph that stands for no character of its own (a diacritic or dot the font split off a letter) maps to a zero width
315
- // space: extractors drop it, and viewers that honour /ActualText never see it.
319
+ // space: extractors drop it, and viewers that honor /ActualText never see it.
316
320
  function toUnicodeCMap(cids) {
317
321
  const pairs = cids.map((item) => [item.cid, item.codePoints]).sort((a, b) => a[0] - b[0]);
318
322
  let body = "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo<</Registry(Adobe)/Ordering(UCS)/Supplement 0>> def\n/CMapName/Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n";
@@ -506,7 +506,7 @@ class Converter {
506
506
  }
507
507
  const color = parseColor(text, parseColor(style.color));
508
508
  if (!color) {
509
- if (!/^(none|inherit|context-(fill|stroke))$/i.test(text)) this.unsupported("pdf-unsupported-paint", `The colour "${text.slice(0, 40)}" is not understood; nothing is drawn for it.`, { kind });
509
+ if (!/^(none|inherit|context-(fill|stroke))$/i.test(text)) this.unsupported("pdf-unsupported-paint", `The color "${text.slice(0, 40)}" is not understood; nothing is drawn for it.`, { kind });
510
510
  return null;
511
511
  }
512
512
  return color.a === 0 ? null : { color };
@@ -889,7 +889,7 @@ class Converter {
889
889
  const commands = glyphOutline(run.face.font, glyph.gid, (x, y) => [run.x + (origin + (glyph.xOffset + x) * scale) * run.scaleX, run.y - (glyph.yOffset + y) * scale]);
890
890
  if (commands.length) content.op(`${pathOps(commands)} f`);
891
891
  }
892
- // Underline / strike-through / overline in the text colour, from the font's own metrics.
892
+ // Underline / strike-through / overline in the text color, from the font's own metrics.
893
893
  if (run.decoration.size && solidFill) {
894
894
  const font = run.face.font, scale = size / upem;
895
895
  for (const kind of run.decoration) {
@@ -941,6 +941,20 @@ class Converter {
941
941
  const defs = [];
942
942
  const collect = (element) => { for (const child of element.children ?? []) if (isElement(child)) { if (child.name === "defs") defs.push(serialize(child, onlyLocalReferences)); collect(child); } };
943
943
  collect(page.svg);
944
+ // A <use> may point at drawn content outside <defs> (a shape effect draws its shadow from a <use> of the shape it
945
+ // follows): that element, and what it references in turn, goes into the standalone SVG too, or the copy draws nothing.
946
+ const referenced = [], seen = new Set();
947
+ const insideDefs = (element) => { for (let at = element.parent; at; at = at.parent) if (at.name === "defs") return true; return false; };
948
+ const follow = (element) => {
949
+ if (element.name === "use") {
950
+ const id = String(element.attrs.href ?? element.attrs["xlink:href"] ?? "").trim().replace(/^#/, "");
951
+ const target = id ? page.defs.get(id) : undefined;
952
+ if (target && !seen.has(target) && !insideDefs(target)) { seen.add(target); referenced.push(target); follow(target); }
953
+ }
954
+ for (const child of element.children ?? []) if (isElement(child)) follow(child);
955
+ };
956
+ follow(node);
957
+ if (referenced.length) defs.push(`<defs>${referenced.map((element) => serialize(element, onlyLocalReferences)).join("")}</defs>`);
944
958
  const rootAttrs = page.svg.attrs;
945
959
  const standalone = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${page.width}" height="${page.height}" viewBox="${escapeAttribute(rootAttrs.viewBox ?? `0 0 ${page.width} ${page.height}`)}">${defs.join("")}${open}${serialize(node, onlyLocalReferences)}${"</g>".repeat(chain.length)}</svg>`;
946
960
  const scale = this.options.rasterFallbackScale;
@@ -326,7 +326,9 @@ function rewriteText(text, db, generics, shape) {
326
326
  for (const line of decorationLines(run.face, decoration, scale)) parts.push(`<rect${paint} x="${stable(piece.x)}" y="${stable(y + line.offset)}" width="${stable(piece.advance)}" height="${stable(line.thickness)}"/>`);
327
327
  continue;
328
328
  }
329
- const attrs = [...spanAttrs].map(([key, value]) => ` ${key}="${escapeAttr(value)}"`).join("");
329
+ // The piece states its own xml:space (its white space is already resolved), so a span's copy is not repeated: an attribute
330
+ // written twice is not XML, and resvg refuses the whole slide.
331
+ const attrs = [...spanAttrs].filter(([key]) => key !== "xml:space").map(([key, value]) => ` ${key}="${escapeAttr(value)}"`).join("");
330
332
  parts.push(`<text x="${stable(piece.x)}" y="${stable(y)}"${attrs} text-anchor="start" xml:space="preserve">${escapeText(value)}</text>`);
331
333
  }
332
334
  }
package/dist/raster.js CHANGED
@@ -129,7 +129,7 @@ function sharpImageCodec() {
129
129
  async function rasterizeSvg(svgInput, options, {strictMarker=false}={}) {
130
130
  const { Resvg } = await loadResvg();
131
131
  const scale = positiveNumber(options.scale, "scale", DEFAULT_RASTER_SCALE);
132
- // FF-45: resvg draws no COLRv1 or OT-SVG colour glyphs; the colour faces stay out of its font list (see color-fonts.js).
132
+ // FF-45: resvg draws no COLRv1 or OT-SVG color glyphs; the color faces stay out of its font list (see color-fonts.js).
133
133
  const settings = fontSettings(options);
134
134
  const fontFiles = rasterFontFiles([
135
135
  ...(settings.useBundledFonts ? await bundledFontFiles() : []),
@@ -164,7 +164,7 @@ async function rasterizeSvg(svgInput, options, {strictMarker=false}={}) {
164
164
  return new Resvg(pinned, { ...renderOptions, fitTo: { mode: "zoom", value: zoom }, background: "rgba(0, 0, 0, 0)" }).render().asPng();
165
165
  };
166
166
  // FF-31: resvg ignores the SVG's ligature properties, so separate the letters a Gelasio ligature would join.
167
- // FF-45: colour families (Noto Color Emoji) are drawn with their monochrome stand-in, which resvg can draw.
167
+ // FF-45: color families (Noto Color Emoji) are drawn with their monochrome stand-in, which resvg can draw.
168
168
  // FF-44: resvg loses the advance of a vowel sign or space inside a complex-script cluster, so pin each cluster (raster-text.js).
169
169
  const prepared=separateLigatures(monochromeColorFonts(await prepareRasterImages(normalizeSvgInput(svgInput), { nestedSvg })));
170
170
  const markers=await outlineRasterMarkers(prepared,{font,shape,report:options.onDiagnostic,strict:strictMarker,fail:(code,message)=>new OPFRenderError(code,message)});
@@ -98,7 +98,6 @@ export function* drawnStrings(presentation) {
98
98
 
99
99
  // Generated words are measured before the guarded status rule decides whether they draw. Source enum values alone do not cover them.
100
100
  // Only content payloads count: arbitrary variables, metadata, notes, catalogs and extensions never synthesize timeline labels.
101
- const PROMOTED_REGION = /^(?:(?:top|middle|bottom)(?:\+(?:top|middle|bottom))*(?::(?:start|center|end)(?:\+(?:start|center|end))*)?|(?:start|center|end)(?:\+(?:start|center|end))*)$/;
102
101
  function* generatedTimelineWords(presentation) {
103
102
  if (!Array.isArray(presentation?.slides)) return;
104
103
  for (const [slideIndex, slide] of presentation.slides.entries()) {
@@ -111,7 +110,6 @@ function* generatedTimelineWords(presentation) {
111
110
  if (Array.isArray(payload.blocks)) for (const block of payload.blocks) visit(block, depth + 1, [...ancestors, payload]);
112
111
  };
113
112
  visit(slide);
114
- for (const [key, payload] of Object.entries(slide)) if (PROMOTED_REGION.test(key)) visit(payload);
115
113
  if (!statuses.size) continue;
116
114
  const words = timelineStatusWordsFor(quoteLanguage(presentation, slideIndex));
117
115
  if (!words) continue;