@openpresentation/opf-render 0.32.1 → 0.34.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 +28 -15
- package/dist/chart-options.js +4 -2
- package/dist/charts.js +162 -163
- package/dist/effects.js +302 -0
- package/dist/export-browser.d.ts +7 -0
- package/dist/export-browser.js +18 -6
- package/dist/font-demand.js +673 -0
- package/dist/font-files.js +43 -0
- package/dist/font-registry.js +57 -20
- package/dist/font-selection-metadata.js +21 -0
- package/dist/font-selection.js +6 -0
- package/dist/fonts-browser.d.ts +4 -3
- package/dist/fonts-browser.js +27 -10
- package/dist/fonts-node.d.ts +6 -5
- package/dist/fonts-node.js +27 -7
- package/dist/fonts.d.ts +13 -3
- package/dist/hb-shape.js +4 -4
- package/dist/index.d.ts +6 -0
- package/dist/lazy-fonts.js +209 -44
- package/dist/pdf-fonts.js +1 -1
- package/dist/pdf-text.js +10 -2
- package/dist/pdf-vector.js +2 -31
- package/dist/preview-fonts-cli.js +14 -4
- package/dist/preview-fonts-node.d.ts +18 -0
- package/dist/preview-fonts-node.js +37 -0
- package/dist/raster-markers.js +46 -0
- package/dist/raster.js +7 -4
- package/dist/script-font-pack.js +65 -4
- package/dist/script-fonts.js +6 -90
- package/dist/shapes.js +308 -0
- package/dist/svg.d.ts +6 -0
- package/dist/svg.js +319 -83
- package/dist/text-paths.js +48 -16
- package/package.json +6 -6
package/dist/effects.js
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
// SH-03: the six shape effects (shadow, innerShadow, glow, softEdge, reflection, blur) drawn as SVG filters, the preview's twin of
|
|
2
|
+
// opf-pptx src/effects.js (a:effectLst). Both read the same presets and defaults; a parity test keeps the two tables equal.
|
|
3
|
+
//
|
|
4
|
+
// How PowerPoint draws them (measured on PowerPoint for Windows renders through COM, docs/shape-effects.md):
|
|
5
|
+
// - every blur radius r is a Gaussian with a standard deviation of r / 3 (outer and inner shadow, blur, reflection);
|
|
6
|
+
// - a glow is the outline grown by 0.45 r and blurred by r / 6, drawn behind the shape;
|
|
7
|
+
// - a soft edge shrinks the outline by 0.91 r and blurs it by r / 3, and the shape is drawn through that mask;
|
|
8
|
+
// - the inner shadow is the outside of the shape moved by the distance toward the angle, blurred and clipped to the shape, so it
|
|
9
|
+
// lies along the edges the angle points at;
|
|
10
|
+
// - the order: inner shadow, soft edge, blur on the shape's own fill and outline (never on its text); the glow from that result;
|
|
11
|
+
// the text on top; the outer shadow from all of it (glow and text included, so a shape without fill casts its text's shadow);
|
|
12
|
+
// the reflection is the whole of it (shadow and glow included) mirrored about the shape's bottom edge and faded linearly from
|
|
13
|
+
// `opacity` to transparent over `size` of the shape's height.
|
|
14
|
+
// The shadow follows the drawn alpha (the outline, not the bounding box) and keeps its direction when the shape rotates
|
|
15
|
+
// (rotWithShape="0" in the export).
|
|
16
|
+
|
|
17
|
+
/** PowerPoint blur radius to Gaussian standard deviation. */
|
|
18
|
+
const SIGMA = 1 / 3;
|
|
19
|
+
const SOFT_EDGE_SHRINK = 0.91;
|
|
20
|
+
const SOFT_EDGE_SIGMA = 1 / 3;
|
|
21
|
+
const GLOW_SPREAD = 0.45;
|
|
22
|
+
const GLOW_SIGMA = 0.165;
|
|
23
|
+
|
|
24
|
+
/** The `shadow` presets (see opf-pptx src/effects.js and docs/shape-effects.md); lengths in reference pixels. */
|
|
25
|
+
export const SHADOW_PRESETS = Object.freeze({
|
|
26
|
+
soft: Object.freeze({ color: "#000000", opacity: 0.4, blur: 16 / 3, distance: 4, angle: 90, size: 1 }),
|
|
27
|
+
hard: Object.freeze({ color: "#000000", opacity: 0.25, blur: 0, distance: 8, angle: 45, size: 1 }),
|
|
28
|
+
perspective: Object.freeze({ color: "#000000", opacity: 0.15, blur: 16, distance: 100 / 3, angle: 90, scaleX: 0.9, scaleY: -0.19, align: "b" }),
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
/** Defaults for the object forms (a key left out takes these). */
|
|
32
|
+
export const EFFECT_DEFAULTS = Object.freeze({
|
|
33
|
+
shadow: SHADOW_PRESETS.soft,
|
|
34
|
+
innerShadow: Object.freeze({ color: "#000000", opacity: 0.5, blur: 20 / 3, distance: 16 / 3, angle: 45 }),
|
|
35
|
+
glow: Object.freeze({ color: "accent", opacity: 0.4, radius: 20 / 3 }),
|
|
36
|
+
reflection: Object.freeze({ opacity: 0.5, size: 0.35, distance: 0, blur: 2 / 3 }),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
40
|
+
const finite = (value, fallback) => (typeof value === "number" && Number.isFinite(value) ? value : fallback);
|
|
41
|
+
const clamp01 = (value) => Math.min(1, Math.max(0, value));
|
|
42
|
+
|
|
43
|
+
/** The block's effects resolved to numbers in reference pixels; an effect that is absent or off is left out. */
|
|
44
|
+
export function normalizeEffects(effects = {}) {
|
|
45
|
+
if (!isObject(effects)) return {};
|
|
46
|
+
const out = {};
|
|
47
|
+
const shadow = effects.shadow;
|
|
48
|
+
if (typeof shadow === "string" && Object.hasOwn(SHADOW_PRESETS, shadow)) out.shadow = { preset: shadow, ...SHADOW_PRESETS[shadow] };
|
|
49
|
+
else if (isObject(shadow)) {
|
|
50
|
+
const base = EFFECT_DEFAULTS.shadow;
|
|
51
|
+
const size = Math.max(0, finite(shadow.size, 1));
|
|
52
|
+
out.shadow = {
|
|
53
|
+
color: shadow.color ?? base.color,
|
|
54
|
+
opacity: clamp01(finite(shadow.opacity, base.opacity)),
|
|
55
|
+
blur: Math.max(0, finite(shadow.blur, base.blur)),
|
|
56
|
+
distance: Math.max(0, finite(shadow.distance, base.distance)),
|
|
57
|
+
angle: finite(shadow.angle, base.angle),
|
|
58
|
+
size,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
if (isObject(effects.innerShadow)) {
|
|
62
|
+
const value = effects.innerShadow, base = EFFECT_DEFAULTS.innerShadow;
|
|
63
|
+
out.innerShadow = {
|
|
64
|
+
color: value.color ?? base.color,
|
|
65
|
+
opacity: clamp01(finite(value.opacity, base.opacity)),
|
|
66
|
+
blur: Math.max(0, finite(value.blur, base.blur)),
|
|
67
|
+
distance: Math.max(0, finite(value.distance, base.distance)),
|
|
68
|
+
angle: finite(value.angle, base.angle),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
if (isObject(effects.glow)) {
|
|
72
|
+
const value = effects.glow, base = EFFECT_DEFAULTS.glow;
|
|
73
|
+
const radius = Math.max(0, finite(value.radius, base.radius));
|
|
74
|
+
if (radius > 0) out.glow = { color: value.color ?? base.color, opacity: clamp01(finite(value.opacity, base.opacity)), radius };
|
|
75
|
+
}
|
|
76
|
+
const softEdge = Math.max(0, finite(effects.softEdge, 0));
|
|
77
|
+
if (softEdge > 0) out.softEdge = softEdge;
|
|
78
|
+
if (isObject(effects.reflection)) {
|
|
79
|
+
const value = effects.reflection, base = EFFECT_DEFAULTS.reflection;
|
|
80
|
+
out.reflection = {
|
|
81
|
+
opacity: clamp01(finite(value.opacity, base.opacity)),
|
|
82
|
+
size: clamp01(finite(value.size, base.size)),
|
|
83
|
+
distance: Math.max(0, finite(value.distance, base.distance)),
|
|
84
|
+
blur: Math.max(0, finite(value.blur, base.blur)),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
const blur = Math.max(0, finite(effects.blur, 0));
|
|
88
|
+
if (blur > 0) out.blur = blur;
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const round = (value) => {
|
|
93
|
+
const rounded = Math.round(value * 1000) / 1000;
|
|
94
|
+
return Object.is(rounded, -0) ? 0 : rounded;
|
|
95
|
+
};
|
|
96
|
+
const escapeAttr = (value) => String(value).replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
97
|
+
|
|
98
|
+
function tag(name, attrs = {}, children = "") {
|
|
99
|
+
const serialized = Object.keys(attrs)
|
|
100
|
+
.filter((key) => attrs[key] !== undefined && attrs[key] !== null && attrs[key] !== false)
|
|
101
|
+
.map((key) => ` ${key}="${escapeAttr(typeof attrs[key] === "number" ? round(attrs[key]) : attrs[key])}"`)
|
|
102
|
+
.join("");
|
|
103
|
+
return children === "" ? `<${name}${serialized}/>` : `<${name}${serialized}>${children}</${name}>`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A CSS color and its alpha: #RGB, #RRGGBB, #RRGGBBAA, rgb() and rgba() are split; anything else keeps alpha 1. */
|
|
107
|
+
function paint(value) {
|
|
108
|
+
const text = String(value ?? "").trim();
|
|
109
|
+
const hex = text.replace(/^#/, "");
|
|
110
|
+
if (/^[\da-f]{3}$/i.test(hex)) return { color: `#${[...hex].map((char) => char + char).join("")}`.toUpperCase(), alpha: 1 };
|
|
111
|
+
if (/^[\da-f]{6}$/i.test(hex)) return { color: `#${hex}`.toUpperCase(), alpha: 1 };
|
|
112
|
+
if (/^[\da-f]{8}$/i.test(hex)) return { color: `#${hex.slice(0, 6)}`.toUpperCase(), alpha: parseInt(hex.slice(6), 16) / 255 };
|
|
113
|
+
const rgba = text.match(/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+%?))?\s*\)$/i);
|
|
114
|
+
if (rgba) {
|
|
115
|
+
const alpha = rgba[4] === undefined ? 1 : rgba[4].endsWith("%") ? parseFloat(rgba[4]) / 100 : parseFloat(rgba[4]);
|
|
116
|
+
return { color: `rgb(${rgba[1]}, ${rgba[2]}, ${rgba[3]})`, alpha: clamp01(alpha) };
|
|
117
|
+
}
|
|
118
|
+
return { color: text || "#000000", alpha: 1 };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function flood(ref, opacity, resolveColor, result) {
|
|
122
|
+
const { color, alpha } = paint(typeof resolveColor === "function" ? resolveColor(ref) : ref);
|
|
123
|
+
return tag("feFlood", { "flood-color": color, "flood-opacity": round(clamp01(opacity * alpha)), result });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const radians = (degrees) => (degrees * Math.PI) / 180;
|
|
127
|
+
const expand = (box, by) => ({ x: box.x - by, y: box.y - by, width: box.width + 2 * by, height: box.height + 2 * by });
|
|
128
|
+
const union = (a, b) => {
|
|
129
|
+
const x = Math.min(a.x, b.x), y = Math.min(a.y, b.y);
|
|
130
|
+
return { x, y, width: Math.max(a.x + a.width, b.x + b.width) - x, height: Math.max(a.y + a.height, b.y + b.height) - y };
|
|
131
|
+
};
|
|
132
|
+
const shift = (box, dx, dy) => ({ ...box, x: box.x + dx, y: box.y + dy });
|
|
133
|
+
function transformBox(box, [a, b, c, d, e, f]) {
|
|
134
|
+
const xs = [], ys = [];
|
|
135
|
+
for (const [x, y] of [[box.x, box.y], [box.x + box.width, box.y], [box.x, box.y + box.height], [box.x + box.width, box.y + box.height]]) {
|
|
136
|
+
xs.push(a * x + c * y + e);
|
|
137
|
+
ys.push(b * x + d * y + f);
|
|
138
|
+
}
|
|
139
|
+
return { x: Math.min(...xs), y: Math.min(...ys), width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys) };
|
|
140
|
+
}
|
|
141
|
+
const region = (box) => ({ filterUnits: "userSpaceOnUse", x: round(box.x), y: round(box.y), width: round(box.width), height: round(box.height) });
|
|
142
|
+
|
|
143
|
+
/** The axis-aligned bounds of the outline box turned by `rotate` degrees about its center. */
|
|
144
|
+
function bounds(outline) {
|
|
145
|
+
const box = { x: finite(outline?.x, 0), y: finite(outline?.y, 0), width: Math.max(0, finite(outline?.width, 0)), height: Math.max(0, finite(outline?.height, 0)) };
|
|
146
|
+
const turn = finite(outline?.rotate, 0) % 360;
|
|
147
|
+
if (!turn) return box;
|
|
148
|
+
const cos = Math.abs(Math.cos(radians(turn))), sin = Math.abs(Math.sin(radians(turn)));
|
|
149
|
+
const width = box.width * cos + box.height * sin, height = box.width * sin + box.height * cos;
|
|
150
|
+
return { x: box.x + (box.width - width) / 2, y: box.y + (box.height - height) / 2, width, height };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// The point a scaled shadow grows from (DrawingML ST_RectAlignment on the shape's bounds).
|
|
154
|
+
function anchor(box, align = "ctr") {
|
|
155
|
+
const horizontal = align === "ctr" ? "" : align.replace(/^[tb]/, ""), vertical = align === "ctr" ? "" : align.replace(/[lr]$/, "");
|
|
156
|
+
const x = horizontal === "l" ? box.x : horizontal === "r" ? box.x + box.width : box.x + box.width / 2;
|
|
157
|
+
const y = vertical === "t" ? box.y : vertical === "b" ? box.y + box.height : box.y + box.height / 2;
|
|
158
|
+
return [x, y];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const DIAGONAL = 0.8, RAMP = 0.35;
|
|
162
|
+
// Grow (distance > 0) or shrink (distance < 0) an alpha with a round pen, as PowerPoint does. SVG's feMorphology pen is a square:
|
|
163
|
+
// alone it squares a glow's corners and pinches an ellipse's soft edge. A blur cut at the level a straight edge reaches at that
|
|
164
|
+
// distance (0.16 outside, 0.84 inside) is round but cuts convex corners too deep. The union of the two is close to the round pen:
|
|
165
|
+
// growing, the cut gives the distance along edges and a square of 0.8 of it fills the corners (tuned against PowerPoint); shrinking, a
|
|
166
|
+
// square of the full distance keeps a rectangle's corners sharp and the cut keeps an ellipse's ends from pinching.
|
|
167
|
+
// `soften` is the blur that follows, which hides the cut's ramp.
|
|
168
|
+
function morph(input, distance, soften, result) {
|
|
169
|
+
const reach = Math.abs(distance), grow = distance > 0;
|
|
170
|
+
const level = grow ? 0.1587 : 0.8413, slope = reach / (0.242 * Math.max(soften * RAMP, 0.1));
|
|
171
|
+
return [
|
|
172
|
+
tag("feMorphology", { in: input, operator: grow ? "dilate" : "erode", radius: round(grow ? reach * DIAGONAL : reach), result: `${result}-square` }),
|
|
173
|
+
tag("feGaussianBlur", { in: input, stdDeviation: round(reach), result: `${result}-spread` }),
|
|
174
|
+
tag("feComponentTransfer", { in: `${result}-spread`, result: `${result}-cut` }, tag("feFuncA", { type: "linear", slope: round(slope), intercept: round(0.5 - slope * level) })),
|
|
175
|
+
tag("feComposite", { in: `${result}-square`, in2: `${result}-cut`, operator: "arithmetic", k1: -1, k2: 1, k3: 1, k4: 0, result }),
|
|
176
|
+
];
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const NONE = Object.freeze({ defs: "", attributes: Object.freeze({}), empty: true, wrap: (geometry = "", text = "") => `${geometry}${text}` });
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The SVG for a shape's effects.
|
|
183
|
+
* - `effects`: the block's keys `{ shadow, innerShadow, glow, softEdge, reflection, blur }` in OPF units.
|
|
184
|
+
* - `outline`: `{ x, y, width, height, rotate? }`, the shape's box in the SVG's user units before its rotation (degrees about its
|
|
185
|
+
* center); the reflection mirrors about the bottom of its rotated bounds and the filter regions are sized from it.
|
|
186
|
+
* - `resolveColor(ref)`: a ColorRef to a CSS color (#RRGGBB, #RRGGBBAA, rgb(), rgba()).
|
|
187
|
+
* - `options.id`: a document-unique id prefix; `options.scale`: user units per reference pixel (min(width, height) / 720).
|
|
188
|
+
* Returns `{ defs, attributes, wrap(geometry, text), empty }`: put `defs` in the document and draw `wrap(geometry, text)`, where
|
|
189
|
+
* `geometry` is the shape's fill and outline markup and `text` its text, both already transformed (rotated or flipped).
|
|
190
|
+
* `attributes` is the filter on the geometry alone, for a caller that draws its own wrapper (no outer shadow or reflection).
|
|
191
|
+
*/
|
|
192
|
+
export function effectsSvg(effects, outline, resolveColor, { id = "opf-effects", scale = 1 } = {}) {
|
|
193
|
+
const fx = normalizeEffects(effects);
|
|
194
|
+
if (!Object.keys(fx).length) return NONE;
|
|
195
|
+
const box = bounds(outline);
|
|
196
|
+
const px = (value) => value * scale;
|
|
197
|
+
const slack = Math.max(px(8), 0.1 * Math.max(box.width, box.height));
|
|
198
|
+
const defs = [];
|
|
199
|
+
|
|
200
|
+
// The geometry: inner shadow, soft edge and blur on its fill and outline, then the glow behind it.
|
|
201
|
+
const body = [];
|
|
202
|
+
let last = "SourceGraphic", bodyMargin = slack;
|
|
203
|
+
if (fx.innerShadow) {
|
|
204
|
+
const value = fx.innerShadow, distance = px(value.distance), angle = radians(value.angle);
|
|
205
|
+
body.push(
|
|
206
|
+
tag("feOffset", { in: "SourceAlpha", dx: round(-distance * Math.cos(angle)), dy: round(-distance * Math.sin(angle)), result: "inner-offset" }),
|
|
207
|
+
tag("feGaussianBlur", { in: "inner-offset", stdDeviation: round(px(value.blur) * SIGMA), result: "inner-blur" }),
|
|
208
|
+
tag("feComposite", { in: "SourceAlpha", in2: "inner-blur", operator: "out", result: "inner-mask" }),
|
|
209
|
+
flood(value.color, value.opacity, resolveColor, "inner-color"),
|
|
210
|
+
tag("feComposite", { in: "inner-color", in2: "inner-mask", operator: "in", result: "inner" }),
|
|
211
|
+
tag("feMerge", { result: "inner-shape" }, tag("feMergeNode", { in: last }) + tag("feMergeNode", { in: "inner" })),
|
|
212
|
+
);
|
|
213
|
+
last = "inner-shape";
|
|
214
|
+
}
|
|
215
|
+
if (fx.softEdge) {
|
|
216
|
+
const radius = px(fx.softEdge);
|
|
217
|
+
body.push(
|
|
218
|
+
...morph("SourceAlpha", -radius * SOFT_EDGE_SHRINK, radius * SOFT_EDGE_SIGMA, "soft-shrink"),
|
|
219
|
+
tag("feGaussianBlur", { in: "soft-shrink", stdDeviation: round(radius * SOFT_EDGE_SIGMA), result: "soft-mask" }),
|
|
220
|
+
tag("feComposite", { in: last, in2: "soft-mask", operator: "in", result: "soft" }),
|
|
221
|
+
);
|
|
222
|
+
last = "soft";
|
|
223
|
+
}
|
|
224
|
+
if (fx.blur) {
|
|
225
|
+
const radius = px(fx.blur);
|
|
226
|
+
body.push(tag("feGaussianBlur", { in: last, stdDeviation: round(radius * SIGMA), result: "blurred" }));
|
|
227
|
+
last = "blurred";
|
|
228
|
+
bodyMargin += radius;
|
|
229
|
+
}
|
|
230
|
+
if (fx.glow) {
|
|
231
|
+
const value = fx.glow, radius = px(value.radius);
|
|
232
|
+
body.push(
|
|
233
|
+
...morph(last, radius * GLOW_SPREAD, radius * GLOW_SIGMA, "glow-grow"),
|
|
234
|
+
tag("feGaussianBlur", { in: "glow-grow", stdDeviation: round(radius * GLOW_SIGMA), result: "glow-mask" }),
|
|
235
|
+
flood(value.color, value.opacity, resolveColor, "glow-color"),
|
|
236
|
+
tag("feComposite", { in: "glow-color", in2: "glow-mask", operator: "in", result: "glow" }),
|
|
237
|
+
tag("feMerge", { result: "glowing" }, tag("feMergeNode", { in: "glow" }) + tag("feMergeNode", { in: last })),
|
|
238
|
+
);
|
|
239
|
+
last = "glowing";
|
|
240
|
+
bodyMargin += radius * (GLOW_SPREAD + 3 * GLOW_SIGMA);
|
|
241
|
+
}
|
|
242
|
+
const core = expand(box, bodyMargin);
|
|
243
|
+
const attributes = {};
|
|
244
|
+
if (body.length) {
|
|
245
|
+
defs.push(tag("filter", { id: `${id}-body`, ...region(core), "color-interpolation-filters": "sRGB" }, body.join("")));
|
|
246
|
+
attributes.filter = `url(#${id}-body)`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// The outer shadow: the whole shape (glow and text included), scaled about its anchor, moved and blurred, drawn behind it.
|
|
250
|
+
let all = core, shadowMarkup = "";
|
|
251
|
+
if (fx.shadow) {
|
|
252
|
+
const value = fx.shadow, distance = px(value.distance), angle = radians(value.angle);
|
|
253
|
+
const dx = distance * Math.cos(angle), dy = distance * Math.sin(angle), sigma = px(value.blur) * SIGMA;
|
|
254
|
+
const sx = value.scaleX ?? value.size ?? 1, sy = value.scaleY ?? value.size ?? 1;
|
|
255
|
+
const scaled = sx !== 1 || sy !== 1;
|
|
256
|
+
const [ax, ay] = anchor(box, value.align ?? "ctr");
|
|
257
|
+
const matrix = [sx, 0, 0, sy, ax - sx * ax, ay - sy * ay];
|
|
258
|
+
const cast = scaled ? transformBox(core, matrix) : core;
|
|
259
|
+
const area = expand(union(cast, shift(cast, dx, dy)), 3 * sigma + px(1));
|
|
260
|
+
defs.push(tag("filter", { id: `${id}-shadow`, ...region(area), "color-interpolation-filters": "sRGB" }, [
|
|
261
|
+
flood(value.color, value.opacity, resolveColor, "shadow-color"),
|
|
262
|
+
tag("feComposite", { in: "shadow-color", in2: "SourceAlpha", operator: "in", result: "shadow-shape" }),
|
|
263
|
+
tag("feOffset", { in: "shadow-shape", dx: round(dx), dy: round(dy), result: "shadow-offset" }),
|
|
264
|
+
sigma > 0 ? tag("feGaussianBlur", { in: "shadow-offset", stdDeviation: round(sigma) }) : "",
|
|
265
|
+
].join("")));
|
|
266
|
+
const use = tag("use", { href: `#${id}-core`, ...(scaled ? { transform: `matrix(${matrix.map(round).join(" ")})` } : {}) });
|
|
267
|
+
shadowMarkup = tag("g", { "aria-hidden": "true", filter: `url(#${id}-shadow)` }, use);
|
|
268
|
+
all = union(core, shift(cast, dx, dy));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// The reflection: everything above mirrored about the bottom of the shape, moved down by the distance, faded and blurred.
|
|
272
|
+
let reflectionMarkup = "";
|
|
273
|
+
if (fx.reflection && fx.reflection.opacity > 0 && fx.reflection.size > 0) {
|
|
274
|
+
const value = fx.reflection, bottom = box.y + box.height, top = bottom + px(value.distance), sigma = px(value.blur) * SIGMA;
|
|
275
|
+
const mirror = [1, 0, 0, -1, 0, 2 * bottom + px(value.distance)];
|
|
276
|
+
const mirrored = expand(transformBox(all, mirror), 3 * sigma + px(1));
|
|
277
|
+
const fadeEnd = top + value.size * box.height;
|
|
278
|
+
defs.push(
|
|
279
|
+
tag("linearGradient", { id: `${id}-reflection-fade`, gradientUnits: "userSpaceOnUse", x1: 0, y1: round(top), x2: 0, y2: round(fadeEnd) },
|
|
280
|
+
tag("stop", { offset: 0, "stop-color": "#FFFFFF", "stop-opacity": round(value.opacity) }) + tag("stop", { offset: 1, "stop-color": "#FFFFFF", "stop-opacity": 0 })),
|
|
281
|
+
tag("mask", { id: `${id}-reflection-mask`, maskUnits: "userSpaceOnUse", x: round(mirrored.x), y: round(top), width: round(mirrored.width), height: round(Math.max(0, fadeEnd - top)) },
|
|
282
|
+
tag("rect", { x: round(mirrored.x), y: round(top), width: round(mirrored.width), height: round(Math.max(0, fadeEnd - top)), fill: `url(#${id}-reflection-fade)` })),
|
|
283
|
+
);
|
|
284
|
+
if (sigma > 0) defs.push(tag("filter", { id: `${id}-reflection-blur`, ...region(mirrored), "color-interpolation-filters": "sRGB" }, tag("feGaussianBlur", { in: "SourceGraphic", stdDeviation: round(sigma) })));
|
|
285
|
+
const use = tag("use", { href: `#${id}-all`, transform: `matrix(${mirror.map(round).join(" ")})` });
|
|
286
|
+
reflectionMarkup = tag("g", { "aria-hidden": "true", mask: `url(#${id}-reflection-mask)` }, sigma > 0 ? tag("g", { filter: `url(#${id}-reflection-blur)` }, use) : use);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const needsCore = Boolean(shadowMarkup);
|
|
290
|
+
const needsAll = Boolean(reflectionMarkup);
|
|
291
|
+
return {
|
|
292
|
+
defs: defs.join(""),
|
|
293
|
+
attributes,
|
|
294
|
+
empty: false,
|
|
295
|
+
wrap(geometry = "", text = "") {
|
|
296
|
+
const shape = body.length ? tag("g", { filter: attributes.filter }, geometry) : geometry;
|
|
297
|
+
const coreMarkup = needsCore ? tag("g", { id: `${id}-core` }, `${shape}${text}`) : `${shape}${text}`;
|
|
298
|
+
const whole = `${shadowMarkup}${coreMarkup}`;
|
|
299
|
+
return needsAll ? `${reflectionMarkup}${tag("g", { id: `${id}-all` }, whole)}` : whole;
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
}
|
package/dist/export-browser.d.ts
CHANGED
|
@@ -8,6 +8,11 @@ export interface BrowserToPngOptions extends ToSvgOptions {
|
|
|
8
8
|
scale?: number;
|
|
9
9
|
/** A CSS colour painted first (default white); `"transparent"` keeps the alpha channel. */
|
|
10
10
|
background?: string;
|
|
11
|
+
/**
|
|
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
|
|
13
|
+
* allows `data:` images but not `blob:` ones (the sandbox of an MCP App). A `blob:` URL that does not load is tried again as `data:`.
|
|
14
|
+
*/
|
|
15
|
+
svgSource?: "blob" | "data";
|
|
11
16
|
signal?: AbortSignal;
|
|
12
17
|
}
|
|
13
18
|
|
|
@@ -15,6 +20,8 @@ export interface BrowserToPngOptions extends ToSvgOptions {
|
|
|
15
20
|
export interface BrowserToPdfOptions extends Omit<ToSvgOptions, "fonts" | "onDiagnostic">, Pick<ToPdfOptions, "raster" | "background" | "serifFamily" | "metadata" | "tagged" | "compress" | "strict" | "rasterFallbackScale" | "defaultFontFamily" | "sansSerifFamily" | "monospaceFamily" | "onDiagnostic"> {
|
|
16
21
|
/** `raster: true`: pixel density of each page image (default 2). */
|
|
17
22
|
scale?: number;
|
|
23
|
+
/** As for `toPng`: how a slide drawn as an image (a raster PDF, or a part the vector PDF cannot draw) reaches the image decoder. */
|
|
24
|
+
svgSource?: "blob" | "data";
|
|
18
25
|
/**
|
|
19
26
|
* `raster: true` only: the pdf-lib module (`import * as pdfLib from "pdf-lib"`), an optional peer of the renderer that this entry never imports itself, so a
|
|
20
27
|
* bundle of it holds no PDF library. Without it a raster PDF tries to import "pdf-lib" by name and rejects with `OPFRenderError` `converter-missing`
|
package/dist/export-browser.js
CHANGED
|
@@ -36,7 +36,7 @@ async function svgPng(svg, options = {}) {
|
|
|
36
36
|
const width = Math.max(1, Math.round(size.width * scale)), height = Math.max(1, Math.round(size.height * scale));
|
|
37
37
|
if (width * height > MAX_PIXELS) throw new OPFRenderError("png-render-failed", `The PNG would be ${width} by ${height} pixels; the limit is ${MAX_PIXELS / 1e6} megapixels.`, { width, height });
|
|
38
38
|
options.signal?.throwIfAborted?.();
|
|
39
|
-
const image = await loadSvgImage(text, options.signal);
|
|
39
|
+
const image = await loadSvgImage(text, options.signal, options.svgSource);
|
|
40
40
|
const { canvas, context } = createCanvas(width, height);
|
|
41
41
|
const background = options.background ?? "#FFFFFF";
|
|
42
42
|
if (background && background !== "transparent" && background !== "none") { context.fillStyle = background; context.fillRect(0, 0, width, height); }
|
|
@@ -83,7 +83,7 @@ export async function toPdf(source, slides, options) {
|
|
|
83
83
|
producer: packageName,
|
|
84
84
|
ErrorClass: OPFRenderError,
|
|
85
85
|
// The element's own text has no fonts in a standalone SVG image: give it the faces the slides embed.
|
|
86
|
-
rasterize: async (svg, factor) => ({ png: await svgPng(fontCss && /<text[\s>]/.test(svg) ? svg.replace(/(<svg\b[^>]*>)/, `$1<style>${fontCss}</style>`) : svg, { scale: factor, background: "transparent", signal: options.signal }) }),
|
|
86
|
+
rasterize: async (svg, factor) => ({ png: await svgPng(fontCss && /<text[\s>]/.test(svg) ? svg.replace(/(<svg\b[^>]*>)/, `$1<style>${fontCss}</style>`) : svg, { scale: factor, background: "transparent", signal: options.signal, svgSource: options.svgSource }) }),
|
|
87
87
|
});
|
|
88
88
|
}
|
|
89
89
|
|
|
@@ -96,7 +96,7 @@ async function rasterPdf(inputs, options) {
|
|
|
96
96
|
for (const [index, svg] of inputs.entries()) {
|
|
97
97
|
options.signal?.throwIfAborted?.();
|
|
98
98
|
const size = pageSize(svg);
|
|
99
|
-
const png = await svgPng(svg, { scale, background: options.background ?? "#FFFFFF", signal: options.signal });
|
|
99
|
+
const png = await svgPng(svg, { scale, background: options.background ?? "#FFFFFF", signal: options.signal, svgSource: options.svgSource });
|
|
100
100
|
const image = await pdf.embedPng(png);
|
|
101
101
|
pdf.addPage([size.width, size.height]).drawImage(image, { x: 0, y: 0, width: size.width, height: size.height });
|
|
102
102
|
options.onProgress?.({ page: index + 1, pages: inputs.length });
|
|
@@ -132,9 +132,12 @@ async function canvasPng(canvas) {
|
|
|
132
132
|
return new Uint8Array(await blob.arrayBuffer());
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
135
|
+
// The SVG reaches the browser's image decoder by URL: a blob: URL by default, or a data: URL (`svgSource: "data"`) for a page whose
|
|
136
|
+
// Content-Security-Policy allows data: images but not blob: ones (the sandbox of an MCP App). A blob: URL that does not load is tried
|
|
137
|
+
// again as data:, so a page that did not say still gets its picture.
|
|
138
|
+
async function loadSvgImage(text, signal, source = "blob") {
|
|
139
|
+
if (source !== "blob" && source !== "data") throw new OPFRenderError("invalid-conversion-option", 'svgSource must be "blob" or "data".', { option: "svgSource", value: source });
|
|
140
|
+
const load = async (url) => {
|
|
138
141
|
const image = new Image();
|
|
139
142
|
image.decoding = "sync";
|
|
140
143
|
const loaded = new Promise((resolve, reject) => {
|
|
@@ -147,6 +150,15 @@ async function loadSvgImage(text, signal) {
|
|
|
147
150
|
// Fonts the SVG embeds as data: faces load with the image; decode() settles the picture before the first draw.
|
|
148
151
|
try { await image.decode(); } catch { /* drawn below as the browser has it */ }
|
|
149
152
|
return image;
|
|
153
|
+
};
|
|
154
|
+
const asData = () => load(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(text)}`);
|
|
155
|
+
if (source === "data") return asData();
|
|
156
|
+
const url = URL.createObjectURL(new Blob([text], { type: "image/svg+xml;charset=utf-8" }));
|
|
157
|
+
try {
|
|
158
|
+
return await load(url);
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (signal?.aborted) throw error;
|
|
161
|
+
return asData();
|
|
150
162
|
} finally {
|
|
151
163
|
// The decoded image keeps its own copy; the URL is no longer needed once loaded.
|
|
152
164
|
setTimeout(() => URL.revokeObjectURL(url), 0);
|