@openpresentation/opf-render 0.32.0 → 0.33.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/README.md +1 -1
- package/dist/charts.js +87 -96
- package/dist/effects.js +302 -0
- package/dist/fonts-browser.js +8 -2
- package/dist/shapes.js +308 -0
- package/dist/svg.js +145 -14
- package/package.json +4 -4
package/dist/shapes.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
// SH-02: shape blocks and strokes in the SVG preview.
|
|
2
|
+
//
|
|
3
|
+
// A shape block (core ComposedItem.shape) is drawn from core's evaluated geometry (SH-01 presetGeometry, in slide coordinates):
|
|
4
|
+
// each path filled in its DrawingML mode (norm, or the fill shaded by lighten, lightenLess, darken and darkenLess) and stroked where
|
|
5
|
+
// the path takes the line, in order; then the text, fitted by core in shape.textArea; then the effects (SH-03's effectsSvg through drawEffects) wrap the outline and the text. The
|
|
6
|
+
// whole drawing turns about the frame's center (rotate) and mirrors (flip); the text turns with it but is not mirrored, and a vertical
|
|
7
|
+
// flip turns it upside down, as PowerPoint draws it. The PPTX export writes the same shape natively (opf-pptx src/shape-blocks.js).
|
|
8
|
+
//
|
|
9
|
+
// strokeElements draws every stroke property (color or gradient, width, dash presets and arrays, cap, join, miter limit, compound
|
|
10
|
+
// lines, inside alignment and arrowheads) for a shape's paths and for a picture's outline; sketch is PowerPoint's own randomized line
|
|
11
|
+
// and is drawn plain.
|
|
12
|
+
|
|
13
|
+
import { patternRuns, shapeTextColor } from "@openpresentation/opf/composition";
|
|
14
|
+
import { effectsSvg } from "./effects.js";
|
|
15
|
+
|
|
16
|
+
const HIDDEN = Object.freeze({ "aria-hidden": "true" });
|
|
17
|
+
const number = value => (Number.isInteger(value) ? String(value) : Number(value).toFixed(3).replace(/\.?0+$/, ""));
|
|
18
|
+
const precise = value => String(Math.round(value * 1e6) / 1e6);
|
|
19
|
+
|
|
20
|
+
/** DrawingML preset dashes as dash and gap lengths in line widths (PowerPoint's patterns for a flat cap). */
|
|
21
|
+
export const PRESET_DASHES = Object.freeze({
|
|
22
|
+
solid: null, dot: [1, 3], dash: [4, 3], longDash: [8, 3], dashDot: [4, 3, 1, 3], longDashDot: [8, 3, 1, 3], longDashDotDot: [8, 3, 1, 3, 1, 3],
|
|
23
|
+
sysDot: [1, 1], sysDash: [3, 1], sysDashDot: [3, 1, 1, 1], sysDashDotDot: [3, 1, 1, 1, 1, 1],
|
|
24
|
+
});
|
|
25
|
+
/** Compound lines as bands across the line's width, from its outer edge (0) to its inner edge (1): the parts that are drawn. */
|
|
26
|
+
export const COMPOUND_BANDS = Object.freeze({
|
|
27
|
+
single: [[0, 1]], double: [[0, 1 / 3], [2 / 3, 1]], thickThin: [[0, 0.6], [0.8, 1]], thinThick: [[0, 0.2], [0.4, 1]], triple: [[0, 1 / 6], [1 / 3, 2 / 3], [5 / 6, 1]],
|
|
28
|
+
});
|
|
29
|
+
/** Arrowhead width and length in line widths, for small, medium and large. */
|
|
30
|
+
export const ARROWHEAD_SIZES = Object.freeze({ small: 2, medium: 3, large: 5 });
|
|
31
|
+
|
|
32
|
+
// A ColorRef as an opaque #RRGGBB and the alpha of an eight-digit hex.
|
|
33
|
+
function paintOf(value, helpers, fallback) {
|
|
34
|
+
const hex = helpers.resolveColorRef(value, fallback) ?? fallback;
|
|
35
|
+
const raw = String(hex).replace(/^#/, "");
|
|
36
|
+
const six = /^[0-9a-f]{3}$/i.test(raw) ? [...raw].map(char => char + char).join("") : raw.slice(0, 6);
|
|
37
|
+
return { color: `#${six.toUpperCase()}`, alpha: raw.length === 8 ? parseInt(raw.slice(6), 16) / 255 : 1 };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// DrawingML path fill modes as PowerPoint draws them: lighten mixes 40% white into the fill, lightenLess 20%, darken scales it to 60%,
|
|
41
|
+
// darkenLess to 80%, on the sRGB values (measured in PowerPoint 365's export of can, cube and bevel).
|
|
42
|
+
const SHADE = Object.freeze({ lighten: ["tint", 0.6], lightenLess: ["tint", 0.8], darken: ["shade", 0.6], darkenLess: ["shade", 0.8] });
|
|
43
|
+
export function shadeColor(hex, mode) {
|
|
44
|
+
const entry = SHADE[mode];
|
|
45
|
+
if (!entry) return hex;
|
|
46
|
+
const [kind, amount] = entry;
|
|
47
|
+
const channels = [1, 3, 5].map(at => parseInt(hex.slice(at, at + 2), 16) / 255);
|
|
48
|
+
const mixed = channels.map(value => kind === "shade" ? value * amount : value * amount + (1 - amount));
|
|
49
|
+
return `#${mixed.map(value => Math.round(Math.min(1, Math.max(0, value)) * 255).toString(16).padStart(2, "0")).join("").toUpperCase()}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// A gradient (core ComposedGradient) in the frame `box` drawn as an SVG paint: linear along its angle across the box, radial (and a shape
|
|
53
|
+
// gradient PowerPoint draws as its circle gradient) as a circle. Rectangle and outline-following shape gradients are fans (fanElements).
|
|
54
|
+
function gradientDef(gradient, id, box, helpers, mode, alpha = 1) {
|
|
55
|
+
const stop = (offset, t) => {
|
|
56
|
+
const color = sampleStops(gradient.stops, t, helpers);
|
|
57
|
+
return helpers.tag("stop", { offset: precise(offset), "stop-color": shadeColor(color.color, mode), "stop-opacity": color.alpha * alpha < 1 ? precise(color.alpha * alpha) : undefined });
|
|
58
|
+
};
|
|
59
|
+
const cx = box.x + box.width / 2, cy = box.y + box.height / 2;
|
|
60
|
+
if (gradient.type === "linear") {
|
|
61
|
+
// The preview samples the gradient as PowerPoint mixes it (sampleStops) so SVG's straight sRGB mixing between samples stays within
|
|
62
|
+
// a level or two of it.
|
|
63
|
+
const offsets = [...new Set([...gradient.stops.map(entry => entry.position), ...Array.from({ length: GRADIENT_SAMPLES + 1 }, (_, index) => index / GRADIENT_SAMPLES)])].sort((a, b) => a - b);
|
|
64
|
+
const angle = gradient.angle * Math.PI / 180, cos = Math.cos(angle), sin = Math.sin(angle);
|
|
65
|
+
const half = (Math.abs(box.width * cos) + Math.abs(box.height * sin)) / 2;
|
|
66
|
+
return helpers.tag("linearGradient", { id, gradientUnits: "userSpaceOnUse", x1: number(cx - half * cos), y1: number(cy - half * sin), x2: number(cx + half * cos), y2: number(cy + half * sin) }, offsets.map(offset => stop(offset, offset)).join(""));
|
|
67
|
+
}
|
|
68
|
+
// PowerPoint's circle gradient (a:path circle) is a true circle from the frame's center through its corners (radius half the diagonal,
|
|
69
|
+
// whatever the frame's proportions), eased and mixed as a linear one (measured on PowerPoint 365's export).
|
|
70
|
+
const samples = Array.from({ length: GRADIENT_SAMPLES + 1 }, (_, index) => index / GRADIENT_SAMPLES).map(offset => stop(offset, offset)).join("");
|
|
71
|
+
return helpers.tag("radialGradient", { id, gradientUnits: "userSpaceOnUse", cx: number(cx), cy: number(cy), r: number(Math.hypot(box.width, box.height) / 2) }, samples);
|
|
72
|
+
}
|
|
73
|
+
const GRADIENT_SAMPLES = 24;
|
|
74
|
+
const toLinear = value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
|
|
75
|
+
const toSrgb = value => value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055;
|
|
76
|
+
// The color `t` of the way through gradient stops, as PowerPoint 365 draws it (measured on linear and rectangle gradients): a gradient of
|
|
77
|
+
// exactly two stops at 0 and 1 is eased by smoothstep and mixed in linear light; any other gradient (more stops, or a stop inside) is
|
|
78
|
+
// mixed straight in sRGB between neighboring stops. The alpha is mixed the same way.
|
|
79
|
+
function sampleStops(stops, t, helpers) {
|
|
80
|
+
const paints = stops.map(entry => ({ position: entry.position, ...paintOf(entry.color, helpers, "#000000") }));
|
|
81
|
+
if (t <= paints[0].position) return paints[0];
|
|
82
|
+
const after = paints.findIndex(entry => entry.position >= t);
|
|
83
|
+
if (after < 0) return paints[paints.length - 1];
|
|
84
|
+
const a = paints[after - 1], b = paints[after], linear = b.position > a.position ? (t - a.position) / (b.position - a.position) : 1;
|
|
85
|
+
const eased = paints.length === 2 && paints[0].position === 0 && paints[1].position === 1;
|
|
86
|
+
const k = eased ? linear * linear * (3 - 2 * linear) : linear;
|
|
87
|
+
const space = eased ? [toLinear, toSrgb] : [value => value, value => value];
|
|
88
|
+
const channel = at => {
|
|
89
|
+
const mixed = space[0](parseInt(a.color.slice(at, at + 2), 16) / 255) * (1 - k) + space[0](parseInt(b.color.slice(at, at + 2), 16) / 255) * k;
|
|
90
|
+
return Math.round(Math.min(1, Math.max(0, space[1](mixed))) * 255).toString(16).padStart(2, "0");
|
|
91
|
+
};
|
|
92
|
+
return { color: `#${channel(1)}${channel(3)}${channel(5)}`.toUpperCase(), alpha: a.alpha * (1 - k) + b.alpha * k };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The SVG paint of a fill (core ComposedFill) for one path's fill mode: { fill, opacity, defs }.
|
|
96
|
+
/**
|
|
97
|
+
* A fan of triangles from the frame's center to each edge of `outline` (polygons), each filled with a linear gradient from the center
|
|
98
|
+
* (the first stop) to the edge's line (the last stop): within a triangle the contour lines are parallel to its edge, so together they are
|
|
99
|
+
* the outline scaled about the center. Each triangle is widened a little so neighbors overlap without a seam (they agree where they meet).
|
|
100
|
+
*/
|
|
101
|
+
function fanElements(gradient, outline, id, box, helpers, mode, alpha) {
|
|
102
|
+
const cx = box.x + box.width / 2, cy = box.y + box.height / 2, defs = [], shapes = [];
|
|
103
|
+
let index = 0;
|
|
104
|
+
for (const ring of outline) {
|
|
105
|
+
for (let at = 0; at < ring.length; at++) {
|
|
106
|
+
const [px, py] = ring[at], [qx, qy] = ring[(at + 1) % ring.length];
|
|
107
|
+
const ex = qx - px, ey = qy - py, length = Math.hypot(ex, ey);
|
|
108
|
+
if (length < 1e-6) continue;
|
|
109
|
+
// The foot of the perpendicular from the center to the edge's line: where the last stop is.
|
|
110
|
+
const k = ((cx - px) * ex + (cy - py) * ey) / (length * length), fx = px + ex * k, fy = py + ey * k;
|
|
111
|
+
if (Math.hypot(fx - cx, fy - cy) < 1e-6) continue;
|
|
112
|
+
const gid = `${id}-fan-${index++}`;
|
|
113
|
+
defs.push(helpers.tag("linearGradient", { id: gid, gradientUnits: "userSpaceOnUse", x1: number(cx), y1: number(cy), x2: number(fx), y2: number(fy) }, sampledStops(gradient, helpers, mode, alpha)));
|
|
114
|
+
// The triangle is widened by 0.8 px on every side (its apex split in two), so neighbors overlap all the way to the center and leave
|
|
115
|
+
// no seam however thin they are; past the center the gradient pads with its first stop, the center's own color.
|
|
116
|
+
const mx = (px + qx) / 2 - cx, my = (py + qy) / 2 - cy, md = Math.hypot(mx, my) || 1, ux = mx / md, uy = my / md;
|
|
117
|
+
const side = Math.sign(ex * -uy + ey * ux) || 1, nx = -uy * side * 0.8, ny = ux * side * 0.8;
|
|
118
|
+
const out = (x, y) => { const dx = x - cx, dy = y - cy, d = Math.hypot(dx, dy) || 1; return [x + dx / d * 0.8, y + dy / d * 0.8]; };
|
|
119
|
+
const [ax, ay] = out(px - nx, py - ny), [bx, by] = out(qx + nx, qy + ny);
|
|
120
|
+
const points = [[cx - ux * 0.8 - nx, cy - uy * 0.8 - ny], [ax, ay], [bx, by], [cx - ux * 0.8 + nx, cy - uy * 0.8 + ny]];
|
|
121
|
+
shapes.push(helpers.tag("path", { d: `M${points.map(([x, y]) => `${number(x)} ${number(y)}`).join("L")}Z`, fill: `url(#${gid})` }));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return { defs: defs.join(""), body: shapes.join("") };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// The stops of a gradient sampled as PowerPoint mixes them (sampleStops), from offset 0 to 1.
|
|
128
|
+
function sampledStops(gradient, helpers, mode, alpha) {
|
|
129
|
+
const offsets = [...new Set([...gradient.stops.map(entry => entry.position), ...Array.from({ length: GRADIENT_SAMPLES + 1 }, (_, index) => index / GRADIENT_SAMPLES)])].sort((a, b) => a - b);
|
|
130
|
+
return offsets.map(offset => {
|
|
131
|
+
const color = sampleStops(gradient.stops, offset, helpers);
|
|
132
|
+
return helpers.tag("stop", { offset: precise(offset), "stop-color": shadeColor(color.color, mode), "stop-opacity": color.alpha * alpha < 1 ? precise(color.alpha * alpha) : undefined });
|
|
133
|
+
}).join("");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function fillPaint(fill, mode, id, box, helpers, shape, path) {
|
|
137
|
+
if (!fill || fill.type === "none" || mode === "none") return { fill: "none" };
|
|
138
|
+
const alpha = fill.opacity ?? 1;
|
|
139
|
+
if (fill.type === "solid") {
|
|
140
|
+
const paint = paintOf(fill.color, helpers, helpers.colors.primary);
|
|
141
|
+
return { fill: shadeColor(paint.color, mode), opacity: paint.alpha * alpha };
|
|
142
|
+
}
|
|
143
|
+
if (fill.type === "gradient") {
|
|
144
|
+
// Every gradient spans the bounds of the shape's outline (core gradientBox; the frame for most presets). Rectangle and shape gradients:
|
|
145
|
+
// their contours are those bounds (rectangle) or the outline (shape) scaled about the bounds' center, so they are drawn exactly as a
|
|
146
|
+
// fan of triangles from the center, each a linear gradient across it to its edge.
|
|
147
|
+
const span = shape?.gradientBox ?? box;
|
|
148
|
+
const outline = fill.gradient.type === "rectangle" ? [[[span.x, span.y], [span.x + span.width, span.y], [span.x + span.width, span.y + span.height], [span.x, span.y + span.height]]]
|
|
149
|
+
: fill.gradient.type === "shape" && shape?.shapeGradient === "outline" ? path?.gradientOutline : undefined;
|
|
150
|
+
if (outline) return { fan: fanElements(fill.gradient, outline, id, span, helpers, mode, alpha) };
|
|
151
|
+
// A shape gradient PowerPoint draws as its circle gradient (shape.shapeGradient circle).
|
|
152
|
+
const gradient = fill.gradient.type === "shape" ? { ...fill.gradient, type: "radial" } : fill.gradient;
|
|
153
|
+
return { fill: `url(#${id})`, defs: gradientDef(gradient, id, span, helpers, mode, alpha) };
|
|
154
|
+
}
|
|
155
|
+
// PowerPoint tiles a pattern from the slide's top-left corner, not the shape's (measured on a PowerPoint-drawn rectangle: the tile phase matches to the pixel).
|
|
156
|
+
const runs = patternRuns(fill.preset);
|
|
157
|
+
const foreground = shadeColor(paintOf(fill.foreground ?? "accent1", helpers, helpers.colors.primary).color, mode);
|
|
158
|
+
const background = paintOf(fill.background ?? helpers.colors.background, helpers, helpers.colors.background);
|
|
159
|
+
if (!runs) helpers.report?.({ code: "unsupported-pattern", message: `Pattern ${fill.preset} is not implemented by the SVG preview.` });
|
|
160
|
+
const cell = helpers.tag("rect", { width: 8, height: 8, fill: shadeColor(background.color, mode), "fill-opacity": background.alpha < 1 ? precise(background.alpha) : undefined })
|
|
161
|
+
+ (runs ? helpers.tag("path", { d: runs.map(run => `M${run.x} ${run.y}h${run.width}v1h-${run.width}z`).join(""), fill: foreground, "shape-rendering": "crispEdges" }) : "");
|
|
162
|
+
return { fill: `url(#${id})`, opacity: alpha, defs: helpers.tag("pattern", { id, x: 0, y: 0, width: 8, height: 8, patternUnits: "userSpaceOnUse" }, cell) };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// An arrowhead at one end (core ShapeEnd), as a polygon in the line's color; `cover` is the part of the line the head hides.
|
|
166
|
+
function arrowheadParts(head, end, width, color, helpers) {
|
|
167
|
+
const w = Math.max(width, 1) * ARROWHEAD_SIZES[head.width], l = Math.max(width, 1) * ARROWHEAD_SIZES[head.length];
|
|
168
|
+
const at = `translate(${number(end.x)} ${number(end.y)}) rotate(${number(end.angle)})`;
|
|
169
|
+
const attrs = { ...HIDDEN, transform: at, fill: color.color, "fill-opacity": color.alpha < 1 ? precise(color.alpha) : undefined };
|
|
170
|
+
switch (head.type) {
|
|
171
|
+
case "triangle": return { shape: helpers.tag("path", { ...attrs, d: `M0 0L${number(-l)} ${number(w / 2)}L${number(-l)} ${number(-w / 2)}Z` }), cover: { transform: at, x: -l, width: l, height: Math.max(w, width) } };
|
|
172
|
+
case "stealth": return { shape: helpers.tag("path", { ...attrs, d: `M0 0L${number(-l)} ${number(w / 2)}L${number(-l / 2)} 0L${number(-l)} ${number(-w / 2)}Z` }), cover: { transform: at, x: -l / 2, width: l / 2, height: Math.max(w / 2, width) } };
|
|
173
|
+
case "diamond": return { shape: helpers.tag("path", { ...attrs, d: `M${number(l / 2)} 0L0 ${number(w / 2)}L${number(-l / 2)} 0L0 ${number(-w / 2)}Z` }) };
|
|
174
|
+
case "oval": return { shape: helpers.tag("ellipse", { ...attrs, cx: 0, cy: 0, rx: number(l / 2), ry: number(w / 2) }) };
|
|
175
|
+
default: return { shape: helpers.tag("path", { ...HIDDEN, transform: at, d: `M${number(-l)} ${number(w / 2)}L0 0L${number(-l)} ${number(-w / 2)}`, fill: "none", stroke: color.color, "stroke-opacity": color.alpha < 1 ? precise(color.alpha) : undefined, "stroke-width": number(width), "stroke-linejoin": "miter" }) };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* The SVG of one stroke (core ComposedStroke) along path data `d`: the line, its compound bands and inside alignment as masks, and
|
|
181
|
+
* its arrowheads at `ends` (an open path's ends). `closed` tells inside from outside. Returns { defs, elements }.
|
|
182
|
+
*/
|
|
183
|
+
export function strokeElements(stroke, d, id, { box, closed, ends, helpers, mode = "norm" }) {
|
|
184
|
+
if (!stroke || !(stroke.width > 0)) return { defs: "", elements: "" };
|
|
185
|
+
const defs = [], width = stroke.width;
|
|
186
|
+
let paint;
|
|
187
|
+
if (stroke.gradient) { defs.push(gradientDef(stroke.gradient, `${id}-grad`, box, helpers, mode)); paint = { stroke: `url(#${id}-grad)` }; }
|
|
188
|
+
const color = paintOf(stroke.color ?? helpers.colors.border, helpers, helpers.colors.border);
|
|
189
|
+
if (!paint) paint = { stroke: shadeColor(color.color, mode), "stroke-opacity": color.alpha < 1 ? precise(color.alpha) : undefined };
|
|
190
|
+
const dash = Array.isArray(stroke.dash) ? stroke.dash : PRESET_DASHES[stroke.dash] ?? null;
|
|
191
|
+
// The line's extent across the outline: centered on it, or inside it (closed outlines only).
|
|
192
|
+
const inside = stroke.align === "inside" && closed, bands = COMPOUND_BANDS[stroke.compound] ?? COMPOUND_BANDS.single;
|
|
193
|
+
// Offsets from the outline, positive outside: [outer, inner] edge of each band.
|
|
194
|
+
const offsets = bands.map(([from, to]) => inside ? [-from * width, -to * width] : [width / 2 - from * width, width / 2 - to * width]);
|
|
195
|
+
const reach = Math.max(...offsets.flat().map(Math.abs));
|
|
196
|
+
const plain = !inside && bands.length === 1;
|
|
197
|
+
const region = { x: -1e5, y: -1e5, width: 2e5, height: 2e5 };
|
|
198
|
+
const heads = [stroke.start && ends?.start ? arrowheadParts(stroke.start, ends.start, width, color, helpers) : undefined, stroke.end && ends?.end ? arrowheadParts(stroke.end, ends.end, width, color, helpers) : undefined].filter(Boolean);
|
|
199
|
+
const covers = heads.flatMap(head => head.cover ? [helpers.tag("rect", { transform: head.cover.transform, x: number(head.cover.x), y: number(-head.cover.height / 2 - 1), width: number(head.cover.width + 1), height: number(head.cover.height + 2), fill: "#000" })] : []);
|
|
200
|
+
const base = { ...HIDDEN, d, fill: "none", ...paint, "stroke-linecap": stroke.cap === "flat" ? undefined : stroke.cap === "round" ? "round" : "square", "stroke-linejoin": stroke.join === "miter" ? "miter" : stroke.join, "stroke-miterlimit": stroke.join === "miter" ? number(stroke.miterLimit) : undefined,
|
|
201
|
+
"stroke-dasharray": dash ? dash.map(part => number(part * width)).join(" ") : undefined };
|
|
202
|
+
const elements = [], mask = (name, content) => { defs.push(helpers.tag("mask", { id: name, maskUnits: "userSpaceOnUse", ...region }, content + covers.join(""))); return `url(#${name})`; };
|
|
203
|
+
const ring = (radius, color) => radius > 1e-9 ? helpers.tag("path", { d, fill: "none", stroke: color, "stroke-width": number(2 * radius), "stroke-linejoin": base["stroke-linejoin"], "stroke-miterlimit": base["stroke-miterlimit"], "stroke-linecap": base["stroke-linecap"] }) : "";
|
|
204
|
+
if (plain) {
|
|
205
|
+
elements.push(helpers.tag("path", { ...base, "stroke-width": number(width), mask: covers.length ? mask(`${id}-ends`, helpers.tag("rect", { ...region, fill: "#fff" })) : undefined }));
|
|
206
|
+
} else {
|
|
207
|
+
// Each band is the set of points whose distance from the outline (positive outside) lies between its inner and outer offsets: the
|
|
208
|
+
// outline stroked as wide as the far edge less the stroke as wide as the near edge, on its side of a closed outline.
|
|
209
|
+
let part = 0;
|
|
210
|
+
const draw = content => elements.push(helpers.tag("path", { ...base, "stroke-width": number(2 * reach), mask: mask(`${id}-band-${part++}`, content) }));
|
|
211
|
+
for (const [outer, inner] of offsets) {
|
|
212
|
+
if (!closed) {
|
|
213
|
+
const far = Math.max(Math.abs(outer), Math.abs(inner)), near = Math.sign(outer) === Math.sign(inner) ? Math.min(Math.abs(outer), Math.abs(inner)) : 0;
|
|
214
|
+
draw(ring(far, "#fff") + ring(near, "#000"));
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const outHi = Math.max(0, outer), outLo = Math.max(0, inner);
|
|
218
|
+
if (outHi - outLo > 1e-9) draw(ring(outHi, "#fff") + ring(outLo, "#000") + helpers.tag("path", { d, fill: "#000" }));
|
|
219
|
+
const inFar = -Math.min(0, inner), inNear = -Math.min(0, outer);
|
|
220
|
+
if (inFar - inNear > 1e-9) {
|
|
221
|
+
const clip = `${id}-band-${part}-inside`;
|
|
222
|
+
draw(helpers.tag("clipPath", { id: clip }, helpers.tag("path", { d })) + helpers.tag("g", { "clip-path": `url(#${clip})` }, ring(inFar, "#fff") + ring(inNear, "#000")));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return { defs: defs.join(""), elements: elements.join("") + heads.map(head => head.shape).join("") };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const NO_EFFECTS = Object.freeze({ defs: "", empty: true, wrap: (geometry = "", text = "") => `${geometry}${text}` });
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* A shape's effects (shadow, innerShadow, glow, softEdge, reflection, blur), SH-03's effectsSvg: its outline is the shape's frame turned
|
|
233
|
+
* by its rotation, its colors are the slide's ColorRefs resolved as the fill's are (a lighter or darker color included), and its lengths
|
|
234
|
+
* are reference pixels at the canvas's scale (core effectScale). `defs` goes in the shape's defs; `wrap(geometry, text)` draws the
|
|
235
|
+
* outline (already turned and mirrored) and the text with the effects: the inner shadow, soft edge, blur and glow on the outline, the
|
|
236
|
+
* outer shadow and the reflection from both.
|
|
237
|
+
*/
|
|
238
|
+
export function drawEffects(shape, id, helpers) {
|
|
239
|
+
if (!shape.effects) return NO_EFFECTS;
|
|
240
|
+
return effectsSvg(shape.effects, { ...shape.box, rotate: shape.rotate ?? 0 }, ref => helpers.resolveColorRef(ref, "#000000") ?? "#000000", { id: `${id}-fx`, scale: shape.effectScale ?? 1 });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** The text color of a shape: the style's preferred color where it reads at 4.5:1 on the backdrop, else the slide's text or background color (core shapeTextColor). */
|
|
244
|
+
export function shapeTextFill(shape, helpers) {
|
|
245
|
+
const preferred = paintOf(shape.textColor, helpers, helpers.colors.text).color;
|
|
246
|
+
const backdrop = shape.textBackdrop === undefined ? paintOf(helpers.colors.background, helpers, "#FFFFFF").color : paintOf(shape.textBackdrop, helpers, helpers.colors.background).color;
|
|
247
|
+
return shapeTextColor(backdrop, preferred, paintOf(helpers.colors.text, helpers, "#000000").color, paintOf(helpers.colors.background, helpers, "#FFFFFF").color);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** A shape block (core ComposedItem.shape). `helpers` gives the renderer's tag, colors and text drawing. */
|
|
251
|
+
export function renderShapeBlock(item, helpers) {
|
|
252
|
+
const shape = item.shape;
|
|
253
|
+
if (!shape || shape.hidden) return "";
|
|
254
|
+
const id = `${helpers.idPrefix}-shape-${item.path.replace(/[^A-Za-z0-9]+/g, "-")}`, box = shape.box, defs = [], parts = [];
|
|
255
|
+
const effects = drawEffects(shape, id, helpers);
|
|
256
|
+
if (effects.defs) defs.push(effects.defs);
|
|
257
|
+
shape.paths.forEach((path, index) => {
|
|
258
|
+
const fill = fillPaint(shape.fill, path.fill, `${id}-fill-${index}`, box, helpers, shape, path);
|
|
259
|
+
if (fill.defs) defs.push(fill.defs);
|
|
260
|
+
const closed = !path.open;
|
|
261
|
+
// A sketched line's path is filled within its sketched outline (core stroke.sketched), as PowerPoint fills it.
|
|
262
|
+
const area = shape.stroke?.sketched?.fills[index] ?? path.d;
|
|
263
|
+
if (fill.fan) {
|
|
264
|
+
// The fan is clipped (antialiased) to the path it fills; its triangles overlap and are drawn without antialiasing, so the many thin
|
|
265
|
+
// triangles of a curved outline meet without seams.
|
|
266
|
+
defs.push(fill.fan.defs, helpers.tag("clipPath", { id: `${id}-fill-${index}-clip` }, helpers.tag("path", { d: area })));
|
|
267
|
+
parts.push(helpers.tag("g", { ...HIDDEN, "clip-path": `url(#${id}-fill-${index}-clip)` }, helpers.tag("g", { "shape-rendering": "crispEdges" }, fill.fan.body)));
|
|
268
|
+
}
|
|
269
|
+
if (fill.fill && fill.fill !== "none") parts.push(helpers.tag("path", { ...HIDDEN, d: area, fill: fill.fill, "fill-opacity": fill.opacity !== undefined && fill.opacity < 1 ? precise(fill.opacity) : undefined }));
|
|
270
|
+
if (path.stroke && shape.stroke) {
|
|
271
|
+
// A sketched line (core stroke.sketched) is drawn along its sketched outline, as PowerPoint draws it.
|
|
272
|
+
const stroke = strokeElements(shape.stroke, shape.stroke.sketched?.lines[index] ?? path.d, `${id}-line-${index}`, { box, closed, ends: path.ends, helpers });
|
|
273
|
+
if (stroke.defs) defs.push(stroke.defs);
|
|
274
|
+
parts.push(stroke.elements);
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
const cx = box.x + box.width / 2, cy = box.y + box.height / 2;
|
|
278
|
+
const turn = shape.rotate ? `rotate(${number(shape.rotate)} ${number(cx)} ${number(cy)})` : "";
|
|
279
|
+
const mirror = shape.flipH || shape.flipV ? `translate(${number(cx)} ${number(cy)}) scale(${shape.flipH ? -1 : 1} ${shape.flipV ? -1 : 1}) translate(${number(-cx)} ${number(-cy)})` : "";
|
|
280
|
+
const outline = helpers.tag("g", { transform: [turn, mirror].filter(Boolean).join(" ") || undefined }, parts.join(""));
|
|
281
|
+
let text = "";
|
|
282
|
+
if (item.text && shape.textArea) {
|
|
283
|
+
const area = shape.textArea, tx = area.x + area.width / 2, ty = shape.textBox.y + shape.textBox.height / 2;
|
|
284
|
+
const fill = shapeTextFill(shape, helpers);
|
|
285
|
+
const drawn = helpers.drawText(item, area, fill);
|
|
286
|
+
const textTurn = [turn, shape.flipV ? `rotate(180 ${number(tx)} ${number(shape.textBox.y + shape.textBox.height / 2)})` : "", shape.textDirection === "vertical" ? `rotate(90 ${number(tx)} ${number(ty)})` : shape.textDirection === "vertical270" ? `rotate(-90 ${number(tx)} ${number(ty)})` : ""].filter(Boolean).join(" ");
|
|
287
|
+
text = textTurn ? helpers.tag("g", { transform: textTurn }, drawn) : drawn;
|
|
288
|
+
}
|
|
289
|
+
// A decorative shape is hidden from assistive technology; alt text names the shape; otherwise its text is what is read.
|
|
290
|
+
const accessible = shape.decorative ? HIDDEN : shape.alt !== undefined ? { role: "img", "aria-label": shape.alt } : {};
|
|
291
|
+
const body = (defs.length ? helpers.tag("defs", {}, defs.join("")) : "") + effects.wrap(outline, text);
|
|
292
|
+
const content = shape.link ? helpers.tag("a", { href: shape.link }, body) : body;
|
|
293
|
+
return helpers.tag("g", { ...accessible, ...helpers.trace }, content);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* SH-04: a connector of the slide's overlay (core ComposedConnector): its route (`paths[0]`, core's evaluation of PowerPoint's connector
|
|
298
|
+
* preset in its frame) stroked with the shape stroke drawing, so dash, compound lines, the sketch and the arrowheads (`stroke.start` at
|
|
299
|
+
* `from`, `stroke.end` at `to`) are drawn as on a shape's open path. A hidden connector draws nothing.
|
|
300
|
+
*/
|
|
301
|
+
export function renderConnector(connector, helpers) {
|
|
302
|
+
const path = connector.paths?.[0];
|
|
303
|
+
if (!path || connector.hidden || !connector.stroke) return "";
|
|
304
|
+
const id = `${helpers.idPrefix}-connector-${connector.path.replace(/[^A-Za-z0-9]+/g, "-")}`;
|
|
305
|
+
const stroke = strokeElements(connector.stroke, connector.stroke.sketched?.lines[0] ?? path.d, `${id}-line`, { box: connector.bounds, closed: false, ends: path.ends, helpers });
|
|
306
|
+
const accessible = connector.decorative ? HIDDEN : connector.alt !== undefined ? { role: "img", "aria-label": connector.alt } : HIDDEN;
|
|
307
|
+
return helpers.tag("g", { ...accessible, ...helpers.trace }, (stroke.defs ? helpers.tag("defs", {}, stroke.defs) : "") + stroke.elements);
|
|
308
|
+
}
|
package/dist/svg.js
CHANGED
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
// load instead of switching a feature (script fonts, right-to-left, patterns, code colours, trend arrows) off.
|
|
3
3
|
import {
|
|
4
4
|
layoutTable, fitList, fitRichText, composeSlide, emphasisSurface, resolveTextStyle, textWidthMeasurer, fitText, styledText, LIST_RULE_WIDTH, LIST_ACCENT_RULE_WIDTH, textColorForFill, chartColorForFill,
|
|
5
|
-
resolveColorRef as resolveCoreColorRef, resolveScriptFonts, paragraphDirection, physicalAlignment, patternRuns, isolateNumbers,
|
|
5
|
+
resolveColorRef as resolveCoreColorRef, colorTransform, applyColorTransform, stackedText, resolveScriptFonts, paragraphDirection, physicalAlignment, patternRuns, isolateNumbers,
|
|
6
6
|
metricTrendMark as coreMetricTrendMark, metricPillFill, metricValueColor, tokenizeCode, codeLineRuns, codeSyntaxPaletteForRoles, readableSchemeColor, resolveChartData,
|
|
7
7
|
timelineMarkerShapes, timelineTextColor, layoutWatermark, tableHighlightColor,
|
|
8
|
-
|
|
8
|
+
arrangementPaint, colorContrast,
|
|
9
|
+
codeHighlightLines, codeLineNumbers, codeHighlightBands, codeHighlightColors, fitImage, intrinsicImageAspect, intrinsicImageSize, diagramPalette, paintDiagramGroup, iconPathData,
|
|
9
10
|
ENGINE_DEFAULT_THEME, ENGINE_DEFAULT_COLOR_SCHEME, ENGINE_DEFAULT_FONT_SCHEME, ENGINE_DEFAULT_CHART_TYPES
|
|
10
11
|
} from "@openpresentation/opf/composition";
|
|
11
12
|
// The renderer is a library: it never imports a catalog. Hosts register theirs (`options.catalogs`, core `Catalog[]`, for
|
|
@@ -24,6 +25,7 @@ import { fontPolicyFor } from "@openpresentation/opf/font-policy";
|
|
|
24
25
|
import { disabledFeaturesStyle } from "./font-compatibility.js";
|
|
25
26
|
import { isDatasetChart, isDatasetTable, renderCatalogChart } from "./charts.js";
|
|
26
27
|
import { renderCaption, renderFootnotes } from "./annotations.js";
|
|
28
|
+
import { renderConnector, renderShapeBlock, strokeElements } from "./shapes.js";
|
|
27
29
|
import { drawnFaces } from "./drawn-faces.js";
|
|
28
30
|
import { dataUrlFsType, embeddingAllowed } from "./font-fstype.js";
|
|
29
31
|
import { rejectRenamedOptions, selectSlides } from "./slide-sources.js";
|
|
@@ -264,6 +266,12 @@ function resolveColorRef(value, bound, fallback) {
|
|
|
264
266
|
// partial one for the background, before the text-dependent roles exist.
|
|
265
267
|
function resolveColorRefIn(value, design, fallback) {
|
|
266
268
|
if (value == null || value === "") return fallback;
|
|
269
|
+
// SH-02: { color, lighten } or { color, darken } resolves its base, then applies core's transform (an alpha byte is kept).
|
|
270
|
+
const transform = colorTransform(value);
|
|
271
|
+
if (transform) {
|
|
272
|
+
const base = resolveColorRefIn(transform.color, design, fallback);
|
|
273
|
+
return typeof base === "string" ? applyColorTransform(base, transform) : base;
|
|
274
|
+
}
|
|
267
275
|
if (typeof value !== "string") return fallback;
|
|
268
276
|
const trimmed = value.trim();
|
|
269
277
|
// Core normalizeHexColor uppercases literals and strips #RRGGBBAA alpha.
|
|
@@ -723,13 +731,19 @@ function renderResolvedSlide(resolved, slideIndex, options) {
|
|
|
723
731
|
let content = [
|
|
724
732
|
renderBackground(bound, width, height, options),
|
|
725
733
|
renderBranding(bound, resolved.presentation, width, height, options),
|
|
734
|
+
// SH-04: the back layer of the overlay, above the background and the watermark, below the content and the furniture.
|
|
735
|
+
renderOverlayShapes(bound, options, "back"),
|
|
726
736
|
renderSteps(bound, options),
|
|
737
|
+
renderArrangements(bound, options),
|
|
727
738
|
renderTitleRule(bound, options),
|
|
728
739
|
...renderSlideContent(bound, width, height, options),
|
|
740
|
+
renderIcons(bound, options),
|
|
729
741
|
// RR-34: the footnote area core reserved above the footer band, after the content and before the furniture.
|
|
730
742
|
renderFootnotes(bound, options, drawHelpers),
|
|
731
743
|
renderFurniture(bound, resolved.presentation, width, height, options, "header"),
|
|
732
|
-
renderFurniture(bound, resolved.presentation, width, height, options, "footer")
|
|
744
|
+
renderFurniture(bound, resolved.presentation, width, height, options, "footer"),
|
|
745
|
+
// SH-04: the slide's overlay (geometry.overlayShapes) over everything, in array order.
|
|
746
|
+
renderOverlayShapes(bound, options, "front")
|
|
733
747
|
].filter(Boolean);
|
|
734
748
|
// RR-64: text as glyph outlines. The used-face rule below then embeds only the faces of text that stays text.
|
|
735
749
|
let glyphs = "";
|
|
@@ -875,22 +889,43 @@ function renderImageBlock(item, bound, options) {
|
|
|
875
889
|
const trace = options.trace && image.placement ? { "data-opf-image-placement": image.placement.edge } : {};
|
|
876
890
|
if (isImagePlaceholder(picture)) return Object.keys(trace).length ? tag("g", trace, picture) : picture;
|
|
877
891
|
const id = `opf-s${bound.index + 1}-image-${item.path.replace(/[^A-Za-z0-9]+/g, "-")}`, shape = image.shape, defs = [];
|
|
878
|
-
|
|
879
|
-
|
|
892
|
+
// A sketched stroke (core stroke.sketched) clips the picture to its sketched outline, as PowerPoint draws it.
|
|
893
|
+
const sketched = image.stroke?.sketched?.fills[0];
|
|
894
|
+
const masked = sketched || (shape && shape.preset !== "rect");
|
|
895
|
+
if (masked) defs.push(tag("clipPath", { id: `${id}-clip` }, tag("path", { d: sketched ?? shape.path })));
|
|
880
896
|
const matrix = imageRecolorMatrix(image.recolor, bound);
|
|
881
897
|
if (matrix) defs.push(tag("filter", { id: `${id}-recolor`, "color-interpolation-filters": "sRGB" }, tag("feColorMatrix", { type: "matrix", values: matrix })));
|
|
882
898
|
let pixels = matrix || image.opacity !== undefined ? tag("g", { filter: matrix ? `url(#${id}-recolor)` : undefined, opacity: image.opacity === undefined ? undefined : preciseNumber(image.opacity) }, picture) : picture;
|
|
883
899
|
if (masked) pixels = tag("g", { "clip-path": `url(#${id}-clip)` }, pixels);
|
|
884
900
|
const children = [defs.length ? tag("defs", {}, defs.join("")) : "", pixels];
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
901
|
+
// SH-02: the picture's stroke (renamed from border) takes every stroke property, along the frame's preset outline.
|
|
902
|
+
if (image.stroke) {
|
|
903
|
+
const stroke = strokeElements(image.stroke, image.stroke.sketched?.lines[0] ?? shape?.path ?? rectanglePath(image.box), `${id}-stroke`, { box: image.box, closed: true, helpers: shapeHelpers(item, bound, options) });
|
|
904
|
+
if (stroke.defs) children[0] = (children[0] ? children[0].replace(/<\/defs>$/, "") : "<defs>") + stroke.defs + "</defs>";
|
|
905
|
+
children.push(stroke.elements);
|
|
888
906
|
}
|
|
889
907
|
if (image.overlay) children.push(renderImageOverlay(image.overlay, bound, options));
|
|
890
908
|
if (children.length === 2 && !children[0] && !Object.keys(trace).length) return pixels;
|
|
891
909
|
return tag("g", trace, children.filter(Boolean).join(""));
|
|
892
910
|
}
|
|
893
911
|
|
|
912
|
+
// SH-02: what the shape drawing (src/shapes.js) needs from the renderer: its tag writer, the slide's colors and ColorRef resolution, and
|
|
913
|
+
// the text drawing of a composed item (a shape's text, fitted by core, drawn at the box it was fitted for).
|
|
914
|
+
function shapeHelpers(item, bound, options) {
|
|
915
|
+
const colors = bound.design.colors;
|
|
916
|
+
return {
|
|
917
|
+
tag, idPrefix: `opf-s${bound.index + 1}`, trace: traceAttrs(options, item.path),
|
|
918
|
+
colors: { primary: colors.primary, background: bound.design.backgroundColor ?? colors.background, text: colors.text, border: colors.border },
|
|
919
|
+
resolveColorRef: (value, fallback) => resolveColorRef(value, bound, fallback),
|
|
920
|
+
report: diagnostic => reportDiagnostic({ ...diagnostic, path: item.path }, options),
|
|
921
|
+
drawText: (shapeItem, area, fill) => {
|
|
922
|
+
const value = shapeItem.shape.textDirection === "stacked" ? stackedText(shapeItem.payload.text) : shapeItem.payload.text;
|
|
923
|
+
const config = { path: `${shapeItem.path.replace(/\.(shape|path)$/, "")}.text`, align: "center", fit: shapeItem.text, textStyle: shapeItem.textStyle, fill, fontSize: 25, fontFamily: bound.design.fonts.body, fontWeight: shapeItem.shape.textBold ? 700 : 400, diagnosticsHandled: true, options };
|
|
924
|
+
return Array.isArray(value) ? renderRichTextBox(value, area, bound, config) : renderTextBox(flattenText(value), area, bound, config);
|
|
925
|
+
},
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
|
|
894
929
|
// One overlay (shared by image backgrounds and image blocks): its outline filled with the colour, the colour's alpha times the
|
|
895
930
|
// overlay opacity.
|
|
896
931
|
function renderImageOverlay(overlay, bound, options) {
|
|
@@ -952,6 +987,78 @@ function renderSteps(bound, options) {
|
|
|
952
987
|
return tag('g', options.trace ? {'data-opf-steps': step.form, 'data-opf-region': step.region} : {}, parts.join('\n'));
|
|
953
988
|
}).join('\n');
|
|
954
989
|
}
|
|
990
|
+
// SH-09: core's pyramids and matrices (geometry.arrangements; SH-18: cycles, circles or rounded rectangles with an arrow after each; SH-17: chevrons and flows), under the text of their entries, as the PPTX export draws them (live
|
|
991
|
+
// SmartArt or native shapes): the matrix's diamond in the primary lightened 80%, then every node (an empty quadrant too) in the primary with
|
|
992
|
+
// a centered outline in the background color, core's lineWidth wide. A pyramid level is its trapezoid's polygon (the apex a triangle), a
|
|
993
|
+
// quadrant a rounded square of core's corner radius (DrawingML roundRect's circular corners). With trace each shape names the entry it
|
|
994
|
+
// holds in data-opf-arrangement-path, not data-opf-path: it is the layout's drawing.
|
|
995
|
+
// SH-18: a cycle's circle (DrawingML ellipse) and its arrow (rightArrow, core's outline turned by its rotation), the arrow without an outline.
|
|
996
|
+
function cycleCircle(node, fill, stroke, trace) {
|
|
997
|
+
const {x, y, width, height} = node.box, n = stableNumber;
|
|
998
|
+
return tag('ellipse', {...HIDDEN, cx: n(x + width / 2), cy: n(y + height / 2), rx: n(width / 2), ry: n(height / 2), fill, ...stroke, ...trace});
|
|
999
|
+
}
|
|
1000
|
+
function cycleArrowPath(arrow, fill) {
|
|
1001
|
+
const n = stableNumber;
|
|
1002
|
+
return tag('path', {...HIDDEN, d: `M${arrow.points.map(([px, py]) => `${n(px)} ${n(py)}`).join(' L')} Z`, fill});
|
|
1003
|
+
}
|
|
1004
|
+
function renderArrangements(bound, options) {
|
|
1005
|
+
const arrangements = bound.geometry.arrangements;
|
|
1006
|
+
if (!arrangements?.length) return '';
|
|
1007
|
+
const roles = bound.design.roles, paint = arrangementPaint(bound.design.colors.primary, roles.background, roles.text, colorContrast, applyColorTransform), n = stableNumber;
|
|
1008
|
+
return arrangements.map(arrangement => {
|
|
1009
|
+
// A card grid (a matrix of other than four entries) is drawn in the card neutral with its border, as every OPF card.
|
|
1010
|
+
const card = arrangement.paint === 'card', fill = card ? roles.neutrals.card.hex : paint.fill.hex;
|
|
1011
|
+
const parts = [], stroke = {stroke: card ? roles.neutrals.cardBorder.hex : paint.line.hex, 'stroke-width': n(arrangement.lineWidth), 'stroke-linejoin': 'miter', 'stroke-miterlimit': 8};
|
|
1012
|
+
if (arrangement.background) {
|
|
1013
|
+
const {x, y, width, height} = arrangement.background;
|
|
1014
|
+
parts.push(tag('path', {...HIDDEN, d: `M${n(x + width / 2)} ${n(y)} L${n(x + width)} ${n(y + height / 2)} L${n(x + width / 2)} ${n(y + height)} L${n(x)} ${n(y + height / 2)} Z`, fill: paint.background.hex}));
|
|
1015
|
+
}
|
|
1016
|
+
for (const node of arrangement.nodes) {
|
|
1017
|
+
const trace = options.trace && node.path ? {'data-opf-arrangement-path': node.path} : {};
|
|
1018
|
+
if (node.points) parts.push(tag('path', {...HIDDEN, d: `M${node.points.map(([px, py]) => `${n(px)} ${n(py)}`).join(' L')} Z`, fill, ...stroke, ...trace}));
|
|
1019
|
+
else if (node.preset === 'ellipse') parts.push(cycleCircle(node, fill, stroke, trace));
|
|
1020
|
+
else parts.push(tag('rect', {...HIDDEN, x: n(node.box.x), y: n(node.box.y), width: n(node.box.width), height: n(node.box.height), rx: n(node.radius ?? 0), fill, ...stroke, ...trace}));
|
|
1021
|
+
// SH-18: a cycle's arrow after its node, as PowerPoint stacks them (an arrow of two entries runs under the next circle).
|
|
1022
|
+
for (const arrow of arrangement.arrows?.filter(entry => entry.index === node.index) ?? []) parts.push(cycleArrowPath(arrow, paint.arrow.hex));
|
|
1023
|
+
}
|
|
1024
|
+
return tag('g', options.trace ? {'data-opf-arrangement': arrangement.kind, 'data-opf-arrangement-design': arrangement.design, 'data-opf-region': arrangement.region} : {}, parts.join(''));
|
|
1025
|
+
}).join('\n');
|
|
1026
|
+
}
|
|
1027
|
+
// LH-14: core's icons (geometry.icons) on their chips, over the cards they sit on, as the PPTX export draws them: the chip a circle in
|
|
1028
|
+
// core's chip color; a monochrome glyph core's placed path commands in its glyph color, each part filled (nonzero or even-odd), stroked at
|
|
1029
|
+
// its width with its caps and joins, or both; a multicolor SVG a picture contained in the chip's square, with no chip, in its own colors.
|
|
1030
|
+
// With trace each icon names its path in data-opf-icon (and the entry, metric or group it marks in data-opf-icon-owner), not
|
|
1031
|
+
// data-opf-path: it is decoration, so hit-testing still finds each item by its own text.
|
|
1032
|
+
function renderIcons(bound, options) {
|
|
1033
|
+
const icons = bound.geometry.icons;
|
|
1034
|
+
if (!icons?.length) return "";
|
|
1035
|
+
return icons.map(icon => {
|
|
1036
|
+
const parts = [], glyph = icon.colors.glyph.hex, n = stableNumber;
|
|
1037
|
+
if (icon.picture) parts.push(tag("image", { ...HIDDEN, x: n(icon.box.x), y: n(icon.box.y), width: n(icon.box.width), height: n(icon.box.height), preserveAspectRatio: "xMidYMid meet", href: svgTextDataUri(icon.picture.svg) }));
|
|
1038
|
+
else {
|
|
1039
|
+
parts.push(tag("circle", { ...HIDDEN, cx: n(icon.chip.cx), cy: n(icon.chip.cy), r: n(icon.chip.radius), fill: icon.colors.chip.hex }));
|
|
1040
|
+
for (const part of icon.parts ?? []) parts.push(tag("path", { ...HIDDEN, d: iconPathData(part.commands), fill: part.fill ? glyph : "none", ...(part.fill && part.evenOdd ? { "fill-rule": "evenodd" } : {}),
|
|
1041
|
+
...(part.stroke !== undefined ? { stroke: glyph, "stroke-width": n(part.stroke), "stroke-linecap": part.linecap ?? "butt", "stroke-linejoin": part.linejoin ?? "miter" } : {}) }));
|
|
1042
|
+
}
|
|
1043
|
+
return tag("g", options.trace ? { "data-opf-icon": icon.path, "data-opf-icon-owner": icon.owner } : {}, parts.join(""));
|
|
1044
|
+
}).join("\n");
|
|
1045
|
+
}
|
|
1046
|
+
// An SVG text as a base64 data URI (UTF-8), for an icon drawn as a picture.
|
|
1047
|
+
function svgTextDataUri(text) {
|
|
1048
|
+
const bytes = new TextEncoder().encode(text);
|
|
1049
|
+
let binary = "";
|
|
1050
|
+
for (let index = 0; index < bytes.length; index += 0x8000) binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
|
|
1051
|
+
return `data:image/svg+xml;base64,${btoa(binary)}`;
|
|
1052
|
+
}
|
|
1053
|
+
// SH-04: core's overlay (geometry.overlayShapes) in one of its layers, in array order, as the PPTX export writes it: the front layer (and
|
|
1054
|
+
// every connector) over the content and the furniture, the back layer behind the content, over the background and the watermark;
|
|
1055
|
+
// an overlay shape with the shape block's drawing (it is a shape block item, its text fitted by core), a connector its route stroked with
|
|
1056
|
+
// the shape stroke drawing. With trace each names its entry (slides.N.shapes.I) in data-opf-path, as a block does.
|
|
1057
|
+
function renderOverlayShapes(bound, options, layer) {
|
|
1058
|
+
const overlay = bound.geometry.overlayShapes?.filter(entry => (entry.kind === "shape" && entry.layer === "back" ? "back" : "front") === layer);
|
|
1059
|
+
if (!overlay?.length) return "";
|
|
1060
|
+
return overlay.map(entry => entry.kind === "connector" ? renderConnector(entry, shapeHelpers(entry, bound, options)) : renderShapeBlock(entry, shapeHelpers(entry, bound, options))).join("\n");
|
|
1061
|
+
}
|
|
955
1062
|
// LH-130: the short accent rule core sets above a cover's or section's title (geometry.titleRule), filled in the tag's color (tagFill), as
|
|
956
1063
|
// the PPTX export draws it. With trace it names the title it stands for in data-opf-title-rule, not data-opf-path: it is the layout's
|
|
957
1064
|
// drawing, so hit-testing still finds the title by its own text.
|
|
@@ -977,8 +1084,12 @@ function renderSlideContent(bound, width, height, options) {
|
|
|
977
1084
|
const emphasis=bound.geometry.emphasis;
|
|
978
1085
|
const onSurface=emphasis ? emphasisBound(bound, emphasisSurface(bound.design.colorScheme, bound.design.roles)) : undefined;
|
|
979
1086
|
let surfaceDrawn=false,previousFrame;
|
|
1087
|
+
// SH-09: the entries of a pyramid or matrix (geometry.arrangements) are drawn on its nodes, in the color arrangementPaint reads on the primary.
|
|
1088
|
+
// Only entries drawn on their nodes take the color that reads on the primary; beside a level or on a card they keep the slide's.
|
|
1089
|
+
const arranged=new Set((bound.geometry.arrangements??[]).filter(arrangement=>arrangement.text==='node').map(arrangement=>arrangement.path));
|
|
1090
|
+
const onNodes=arranged.size ? {...bound,design:{...bound.design,colors:{...bound.design.colors,text:arrangementPaint(bound.design.colors.primary,bound.design.roles.background,bound.design.roles.text,colorContrast,applyColorTransform).text.hex}}} : undefined;
|
|
980
1091
|
return bound.geometry.items.map(item => {
|
|
981
|
-
const itemBound=item.emphasis&&onSurface ? onSurface : bound;
|
|
1092
|
+
const itemBound=item.emphasis&&onSurface ? onSurface : arranged.has(item.path) ? onNodes : bound;
|
|
982
1093
|
// LH-131: a featured before and after pair's arrow (emphasis.arrow), a primary block arrow as LH-07's flows draw theirs, with the surface.
|
|
983
1094
|
const under=item.emphasis&&onSurface&&!surfaceDrawn ? (surfaceDrawn=true, tag('rect',{...HIDDEN,x:emphasis.box.x,y:emphasis.box.y,width:emphasis.box.width,height:emphasis.box.height,rx:emphasis.radius,fill:onSurface.design.colors.background,...traceAttrs(options,emphasis.path)})
|
|
984
1095
|
+(emphasis.arrow?tag('path',{...HIDDEN,d:blockArrowPath(emphasis.arrow.box,emphasis.arrow.direction),fill:bound.design.colors.primary,...(options.trace?{'data-opf-emphasis-arrow':emphasis.path}:{})}):'')) : '';
|
|
@@ -1032,6 +1143,8 @@ function renderPayload(item, box, bound, options) {
|
|
|
1032
1143
|
return altText(renderTable(item, box, bound, options), item.value?.alt, "group");
|
|
1033
1144
|
case "image":
|
|
1034
1145
|
return renderImageBlock(item, bound, options);
|
|
1146
|
+
case "shape":
|
|
1147
|
+
return renderShapeBlock(item, shapeHelpers(item, bound, options));
|
|
1035
1148
|
case "video":
|
|
1036
1149
|
return renderMedia(item, box, bound, options);
|
|
1037
1150
|
case "code":
|
|
@@ -1052,7 +1165,9 @@ function renderPayload(item, box, bound, options) {
|
|
|
1052
1165
|
}
|
|
1053
1166
|
|
|
1054
1167
|
function renderTextPayload(item, box, bound, options) {
|
|
1055
|
-
|
|
1168
|
+
// LH-63: a text whose first line is a run-in heading draws core's runs (item.runs: the same characters, the heading bold).
|
|
1169
|
+
const value = item.runs ?? item.value;
|
|
1170
|
+
return (Array.isArray(value) ? renderRichTextBox : renderTextBox)(Array.isArray(value) ? value : flattenText(value), box, bound, {
|
|
1056
1171
|
path: item.path,
|
|
1057
1172
|
// Core resolves one alignment per composed item for every engine, from the slide's design, the deck's design
|
|
1058
1173
|
// and the layout record's design (SlideComposition.design).
|
|
@@ -1097,12 +1212,14 @@ function listEntriesSvg(item, fit, bound, options) {
|
|
|
1097
1212
|
const children=[];
|
|
1098
1213
|
// design.listBullet=image: core attaches the icon logo as item.bulletImage and its box (entry.bulletBox: 0.65 em, as PowerPoint draws a:buBlip). An icon that cannot be drawn keeps the glyph marker.
|
|
1099
1214
|
const bullet=item.bulletImage?resolveBulletImage(item.bulletImage,bound,options):undefined;
|
|
1215
|
+
const arranged=bound.geometry.arrangements?.find(arrangement=>arrangement.path===item.path)?.align==='center';
|
|
1100
1216
|
for(const entry of fit.listEntries){
|
|
1101
1217
|
if(entry.marker.none){/* design.listBullet: none draws no marker */}
|
|
1102
1218
|
else if(bullet){const box=entry.bulletBox??{x:entry.marker.x,y:entry.marker.y-entry.marker.fontSize*.65,width:entry.marker.fontSize*.65,height:entry.marker.fontSize*.65};children.push(tag('image',{x:stableNumber(box.x),y:stableNumber(box.y),width:stableNumber(box.width),height:stableNumber(box.height),href:bullet,preserveAspectRatio:'xMidYMid meet','aria-hidden':'true',...(options.trace?{'data-opf-generated':'true'}:{})}));}
|
|
1103
1219
|
else children.push(tag('text',{x:stableNumber(entry.marker.x),y:stableNumber(entry.marker.y),'font-family':fontStack(entry.marker.style.fontFamily,bound.design.fontScheme.type),'font-size':stableNumber(entry.marker.fontSize),...numberMarkerStyle(entry.marker),fill:bound.design.colors.text,'aria-hidden':'true',...(entry.marker.anchor==='end'?{'text-anchor':'end'}:{})},escapeText(entry.marker.text)));
|
|
1104
1220
|
// LH-133: a glossary's term (entry.accent) draws in the tag's color on its backdrop, as the export writes it.
|
|
1105
|
-
|
|
1221
|
+
// SH-09: an entry of a pyramid or matrix (geometry.arrangements) is centered on its node, as the export writes it.
|
|
1222
|
+
const config={path:entry.textPath,align:arranged?'center':'left',fill:entry.accent?eyebrowFill(bound.design,item):bound.design.colors.text,rich:Array.isArray(entry.value),options};
|
|
1106
1223
|
children.push(renderRichLines(typeof entry.value==='string'?[entry.value]:entry.value,entry.text,entry.textBox,bound,config));
|
|
1107
1224
|
if(entry.description)children.push(renderRichLines(typeof entry.descriptionValue==='string'?[entry.descriptionValue]:entry.descriptionValue,entry.description,entry.descriptionBox,bound,{...config,path:entry.descriptionPath,rich:Array.isArray(entry.descriptionValue),fill:bound.design.colors.mutedText}));
|
|
1108
1225
|
}
|
|
@@ -1559,7 +1676,7 @@ function renderQuote(item, box, bound, options) {
|
|
|
1559
1676
|
if (!part.fit) throw new OPFRenderError('layout-overflow', 'Quote content has no usable internal space; increase its cell size before rendering.', {path:part.path,diagnostics:layout.diagnostics});
|
|
1560
1677
|
const fill=part.role==='footer'?bound.design.colors.mutedText:bound.design.colors.text;
|
|
1561
1678
|
// FA-10: a TextRun[] quote body is laid out by core's rich-text layouter; its runs (quotation marks joined to the first and last) draw like body runs.
|
|
1562
|
-
if(part.runs&&part.fit.richLines)return renderRichLines(part.runs,part.fit,part.box,bound,{path:part.path,fill,fontFamily:part.requestedStyle.fontFamily,diagnosticsHandled:true,textOffset:-1,options});
|
|
1679
|
+
if(part.runs&&part.fit.richLines)return renderRichLines(part.runs,part.fit,part.box,bound,{path:part.path,fill,fontFamily:part.requestedStyle.fontFamily,diagnosticsHandled:true,textOffset:layout.mark?.hidden?0:-1,options});
|
|
1563
1680
|
return renderTextBox(part.text,part.box,bound,{
|
|
1564
1681
|
path:part.path,fit:part.fit,textStyle:part.style,fontFamily:part.requestedStyle.fontFamily,
|
|
1565
1682
|
fill,
|
|
@@ -1568,13 +1685,22 @@ function renderQuote(item, box, bound, options) {
|
|
|
1568
1685
|
});
|
|
1569
1686
|
// FA-12: the attributed person's headshot, cropped to fill the core circle frame (the clip is the outline the native ellipse picture uses).
|
|
1570
1687
|
if (layout.photo) children.push(renderQuotePhoto(layout.photo, item, bound, options));
|
|
1688
|
+
// LH-78: a quote card's decorative mark, in the primary color against the card (as a metric's value is); core places it in the room above the text.
|
|
1689
|
+
if (layout.mark) {
|
|
1690
|
+
const backdrop = item.frameBox ? bound.design.roles.neutrals.card.hex : bound.design.backgroundColor ?? bound.design.colors.background, mark = layout.mark;
|
|
1691
|
+
children.push(tag('g', options.trace ? {'data-opf-quote-mark': 'true'} : {}, renderTextBox(mark.text, mark.box, bound, {
|
|
1692
|
+
path: item.path, fit: mark.fit, textStyle: mark.style, fontFamily: mark.requestedStyle.fontFamily,
|
|
1693
|
+
fill: metricValueColor(bound.design.colors.primary, backdrop, bound.design.colors.text), diagnosticsHandled: true, options,
|
|
1694
|
+
})));
|
|
1695
|
+
}
|
|
1571
1696
|
// LH-114: a pull line's accent rule, in the primary color (core places it; the PPTX export draws the same rectangle).
|
|
1572
1697
|
if (layout.rule) children.unshift(tag('rect', {...HIDDEN, x: stableNumber(layout.rule.x), y: stableNumber(layout.rule.y), width: stableNumber(layout.rule.width), height: stableNumber(layout.rule.height), fill: bound.design.colors.primary, ...(options.trace ? {'data-opf-quote-rule': 'true'} : {})}));
|
|
1573
1698
|
return tag("g", traceAttrs(options, item.path), children.join("\n"));
|
|
1574
1699
|
}
|
|
1575
1700
|
|
|
1576
1701
|
function renderQuotePhoto(photo, item, bound, options) {
|
|
1577
|
-
|
|
1702
|
+
// LH-132: a portrait beside the quote crops around the focus core gave it (the upper third), as the export does.
|
|
1703
|
+
const picture = renderImage({ value: photo.value, path: photo.path }, photo.box, bound, { ...options, imageFit: 'cover', ...(photo.focus ? { imageFocus: photo.focus } : {}) });
|
|
1578
1704
|
// An unresolved source keeps the ordinary placeholder, unmasked, like the export.
|
|
1579
1705
|
if (isImagePlaceholder(picture)) return picture;
|
|
1580
1706
|
const id = `opf-s${bound.index + 1}-quote-photo-${item.path.replace(/[^A-Za-z0-9]+/g, '-')}`;
|
|
@@ -1887,7 +2013,12 @@ function renderBranding(bound,presentation,width,height,options) {
|
|
|
1887
2013
|
}
|
|
1888
2014
|
} else if(design.watermark){
|
|
1889
2015
|
// The group keeps its bare opacity attribute (opf-pptx's watermark parity test reads it); the picture itself is hidden.
|
|
1890
|
-
|
|
2016
|
+
const mark=renderImage({value:design.watermark,path:rootFor('watermark')},{x:width*.3,y:height*.3,width:width*.4,height:height*.4},bound,{...options,imageFit:'contain',imageDecorative:true});
|
|
2017
|
+
// LH-164: on the accent surface of a message-only slide the mark is drawn in the slide's text color (the export's one-color duotone), so a mark made for the plain surface still reads.
|
|
2018
|
+
const matrix=bound.geometry?.surface&&!isImagePlaceholder(mark)?imageRecolorMatrix({type:'duotone',dark:bound.design.colors.text,light:bound.design.colors.text},bound):undefined, filterId=`opf-s${bound.index+1}-watermark-recolor`;
|
|
2019
|
+
// The filter and the opacity sit on one group: the vector PDF rasterizes a filtered group on its own, without its ancestors' opacity.
|
|
2020
|
+
const watermarkOpacity=typeof design.watermark==='object'?design.watermark.opacity??.08:.08;
|
|
2021
|
+
pieces.push(matrix?tag('g',{opacity:watermarkOpacity,filter:`url(#${filterId})`},tag('defs',{},tag('filter',{id:filterId,'color-interpolation-filters':'sRGB'},tag('feColorMatrix',{type:'matrix',values:matrix})))+mark):tag('g',{opacity:watermarkOpacity},mark));
|
|
1891
2022
|
}
|
|
1892
2023
|
// Cover and section slides: the logo core composed (the primary organization's full logo, or the design.logo override, in the
|
|
1893
2024
|
// variant for this slide's background) at the top-left of the free area, anchored left. RR-71: the picture is named by its
|