@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/raster.js
CHANGED
|
@@ -4,6 +4,7 @@ import {slideArguments,slideSources} from './slide-sources.js';
|
|
|
4
4
|
import {separateLigatures} from './font-compatibility.js';
|
|
5
5
|
import {monochromeColorFonts,rasterFontFiles} from './color-fonts.js';
|
|
6
6
|
import {pinScriptClusters} from './raster-text.js';
|
|
7
|
+
import {outlineRasterMarkers} from './raster-markers.js';
|
|
7
8
|
import {loadConverter} from './converters.js';
|
|
8
9
|
const DEFAULT_DIMENSIONS = { width: 1280, height: 720 };
|
|
9
10
|
const DEFAULT_RASTER_SCALE = 1;
|
|
@@ -58,7 +59,7 @@ export async function toPdf(source, slides, options) {
|
|
|
58
59
|
for (const input of pdfInputs) {
|
|
59
60
|
const svg = normalizeSvgInput(input);
|
|
60
61
|
const pageSize = svgPageSize(svg);
|
|
61
|
-
const rendered = await rasterizeSvg(svg, options);
|
|
62
|
+
const rendered = await rasterizeSvg(svg, options, {strictMarker:options.strict===true});
|
|
62
63
|
const image = await pdf.embedPng(rendered.png);
|
|
63
64
|
const page = pdf.addPage([pageSize.width, pageSize.height]);
|
|
64
65
|
page.drawImage(image, {
|
|
@@ -108,7 +109,7 @@ async function vectorPdf(inputs, options) {
|
|
|
108
109
|
onProgress: typeof options.onProgress === "function" ? options.onProgress : undefined,
|
|
109
110
|
producer: packageName,
|
|
110
111
|
ErrorClass: OPFRenderError,
|
|
111
|
-
rasterize: (svg, factor) => rasterizeSvg(svg, { ...options, scale: factor, background: "rgba(0, 0, 0, 0)" })
|
|
112
|
+
rasterize: (svg, factor) => rasterizeSvg(svg, { ...options, scale: factor, background: "rgba(0, 0, 0, 0)" }, {strictMarker:options.strict===true})
|
|
112
113
|
});
|
|
113
114
|
}
|
|
114
115
|
|
|
@@ -125,7 +126,7 @@ function sharpImageCodec() {
|
|
|
125
126
|
};
|
|
126
127
|
}
|
|
127
128
|
|
|
128
|
-
async function rasterizeSvg(svgInput, options) {
|
|
129
|
+
async function rasterizeSvg(svgInput, options, {strictMarker=false}={}) {
|
|
129
130
|
const { Resvg } = await loadResvg();
|
|
130
131
|
const scale = positiveNumber(options.scale, "scale", DEFAULT_RASTER_SCALE);
|
|
131
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).
|
|
@@ -165,7 +166,9 @@ async function rasterizeSvg(svgInput, options) {
|
|
|
165
166
|
// FF-31: resvg ignores the SVG's ligature properties, so separate the letters a Gelasio ligature would join.
|
|
166
167
|
// FF-45: colour families (Noto Color Emoji) are drawn with their monochrome stand-in, which resvg can draw.
|
|
167
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).
|
|
168
|
-
const
|
|
169
|
+
const prepared=separateLigatures(monochromeColorFonts(await prepareRasterImages(normalizeSvgInput(svgInput), { nestedSvg })));
|
|
170
|
+
const markers=await outlineRasterMarkers(prepared,{font,shape,report:options.onDiagnostic,strict:strictMarker,fail:(code,message)=>new OPFRenderError(code,message)});
|
|
171
|
+
const svg = await pinScriptClusters(markers, pinning);
|
|
169
172
|
|
|
170
173
|
try {
|
|
171
174
|
const image = new Resvg(svg, renderOptions).render();
|
package/dist/script-font-pack.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { BUNDLED_FONT_MANIFEST } from "./font-manifest.js";
|
|
5
5
|
import { OPFFontError } from "./font-registry.js";
|
|
6
6
|
import { SCRIPT_FONT_REPLACEMENTS, glyphFallbackFamilies, scriptOfCharacter, scriptsOfText } from "./script-fonts.js";
|
|
7
|
-
import { resolveScriptFonts } from "@openpresentation/opf/composition";
|
|
7
|
+
import { MAX_COMPOSITION_DEPTH, languageInEffect, numeralScripts, quoteLanguage, resolveScriptFonts, timelineStatusWordsFor } from "@openpresentation/opf/composition";
|
|
8
8
|
import { createFontAnalysis } from "./lazy-fonts.js";
|
|
9
9
|
import { SYMBOL_SCRIPT, isSymbolEncodedFamily } from "./symbol-fonts.js";
|
|
10
10
|
|
|
@@ -96,13 +96,36 @@ export function* drawnStrings(presentation) {
|
|
|
96
96
|
yield* walkStrings(presentation, undrawn, undrawnRoot, undrawnSlide);
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
+
// Generated words are measured before the guarded status rule decides whether they draw. Source enum values alone do not cover them.
|
|
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
|
+
function* generatedTimelineWords(presentation) {
|
|
103
|
+
if (!Array.isArray(presentation?.slides)) return;
|
|
104
|
+
for (const [slideIndex, slide] of presentation.slides.entries()) {
|
|
105
|
+
if (!slide || typeof slide !== "object" || Array.isArray(slide)) continue;
|
|
106
|
+
const statuses = new Set();
|
|
107
|
+
const visit = (payload, depth = -1, ancestors = []) => {
|
|
108
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload) || depth > MAX_COMPOSITION_DEPTH || ancestors.includes(payload)) return;
|
|
109
|
+
const timeline = payload.timeline, events = Array.isArray(timeline) ? timeline : timeline?.events;
|
|
110
|
+
if (Array.isArray(events)) for (const event of events) if (typeof event?.status === "string") statuses.add(event.status);
|
|
111
|
+
if (Array.isArray(payload.blocks)) for (const block of payload.blocks) visit(block, depth + 1, [...ancestors, payload]);
|
|
112
|
+
};
|
|
113
|
+
visit(slide);
|
|
114
|
+
for (const [key, payload] of Object.entries(slide)) if (PROMOTED_REGION.test(key)) visit(payload);
|
|
115
|
+
if (!statuses.size) continue;
|
|
116
|
+
const words = timelineStatusWordsFor(quoteLanguage(presentation, slideIndex));
|
|
117
|
+
if (!words) continue;
|
|
118
|
+
for (const status of statuses) if (typeof words[status] === "string") yield {text: words[status], slideIndex};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
99
122
|
/**
|
|
100
123
|
* The script profile of a presentation: core `resolveScriptFonts` output, exactly what the renderer plans
|
|
101
124
|
* with. When it throws, the renderer ignores the document language, so the profile is empty and Han text is
|
|
102
125
|
* Simplified Chinese, as drawn. `renderOptions.catalogs` (the host's registered catalogs) resolve as they do for the renderer.
|
|
103
126
|
*/
|
|
104
|
-
export function presentationScriptProfile(presentation, renderOptions) {
|
|
105
|
-
try { return resolveScriptFonts(presentation, renderOptions?.catalogs !== undefined ? { catalogs: renderOptions.catalogs } : {}); } catch { /* the renderer falls back the same way */ }
|
|
127
|
+
export function presentationScriptProfile(presentation, renderOptions, slideIndex) {
|
|
128
|
+
try { return resolveScriptFonts(presentation, { ...(renderOptions?.catalogs !== undefined ? { catalogs: renderOptions.catalogs } : {}), ...(slideIndex !== undefined ? {slideIndex} : {}) }); } catch { /* the renderer falls back the same way */ }
|
|
106
129
|
return {};
|
|
107
130
|
}
|
|
108
131
|
|
|
@@ -191,7 +214,45 @@ export function analyzePresentationScripts(presentation, profile, renderOptions,
|
|
|
191
214
|
for (const script of found.scripts) scripts.add(script);
|
|
192
215
|
for (const character of found.cjk) cjk.add(character);
|
|
193
216
|
}
|
|
194
|
-
|
|
217
|
+
const generatedProfiles = new Map();
|
|
218
|
+
for (const {text, slideIndex} of generatedTimelineWords(presentation)) {
|
|
219
|
+
// A generated Han label follows its own slide locale (for example zh-TW on an English deck), not the deck's default script.
|
|
220
|
+
if (!generatedProfiles.has(slideIndex)) generatedProfiles.set(slideIndex, presentationScriptProfile(presentation, renderOptions, slideIndex));
|
|
221
|
+
const found = memory.scanner(generatedProfiles.get(slideIndex))(text);
|
|
222
|
+
for (const script of found.scripts) scripts.add(script);
|
|
223
|
+
for (const character of found.cjk) cjk.add(character);
|
|
224
|
+
}
|
|
225
|
+
return { profile, detected: [...scripts].sort(), design: [...new Set([...design.scripts, ...generatedNumeralScripts(presentation)])].sort(), cjk };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* LH-106: the scripts of the digits the engines generate (metric values, chart labels and ticks, table numbers, list numerals,
|
|
230
|
+
* step badges, slide numbers) on each slide whose language (its own, else the deck's) has digits of its own: Arab for `ar-SA` and
|
|
231
|
+
* `fa-IR`, Beng for `bn`, none for `ar-AE` or `ar-SA-u-nu-latn`. Like a font scheme's scripts they are faces the deck may draw
|
|
232
|
+
* without one authored character in the script (an `ar-SA` deck titled "T" with the metric 1000 draws ١٬٠٠٠), so their packages
|
|
233
|
+
* are offered to the drawn-face analysis, which loads only the faces the composed slides actually draw. A slide counts when it may
|
|
234
|
+
* generate a number (`generatesNumbers`); a slide of words alone (a timeline of "Week 1" labels) offers nothing.
|
|
235
|
+
*/
|
|
236
|
+
function generatedNumeralScripts(presentation) {
|
|
237
|
+
const slides = Array.isArray(presentation?.slides) ? presentation.slides : [];
|
|
238
|
+
const furniture = generatesNumbers(presentation?.design?.header) || generatesNumbers(presentation?.design?.footer);
|
|
239
|
+
return numeralScripts(slides.map((slide, index) => furniture || generatesNumbers(slide) || generatesNumbers(slide?.design?.header) || generatesNumbers(slide?.design?.footer) ? languageInEffect(presentation, index) : undefined));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Payload keys whose content the engines number: a chart's labels and ticks, a table's cells, a metric, list numerals and step badges
|
|
243
|
+
// (a list or a layout's sequence), and a slide that names a layout (whose regions may badge its blocks).
|
|
244
|
+
const NUMBERED_KEYS = new Set(["chart", "table", "metric", "numbering", "items", "bullets", "blocks", "layout"]);
|
|
245
|
+
/** True when a slide (or a header or footer) may draw a number the engines generate: a JSON number, a numbered payload or a `{{token}}`. */
|
|
246
|
+
function generatesNumbers(value, depth = 0) {
|
|
247
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
248
|
+
if (typeof value === "string") return value.includes("{{");
|
|
249
|
+
if (!value || typeof value !== "object" || depth > MAX_COMPOSITION_DEPTH + 8) return false;
|
|
250
|
+
if (Array.isArray(value)) return value.some(entry => generatesNumbers(entry, depth + 1));
|
|
251
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
252
|
+
if (UNDRAWN_KEYS.includes(key) || key === "language" || key === "design" || key === "composition") continue;
|
|
253
|
+
if (NUMBERED_KEYS.has(key) || generatesNumbers(entry, depth + 1)) return true;
|
|
254
|
+
}
|
|
255
|
+
return false;
|
|
195
256
|
}
|
|
196
257
|
|
|
197
258
|
/** One string's scripts (`scriptsOfText`) and the Han, kana and Hangul characters it draws, in order. One pass over the characters. */
|
package/dist/script-fonts.js
CHANGED
|
@@ -17,9 +17,9 @@
|
|
|
17
17
|
// faces and lets a missing glyph raise `missing-glyph`.
|
|
18
18
|
|
|
19
19
|
import { fontPolicyFor } from "@openpresentation/opf/font-policy";
|
|
20
|
-
import { scriptFontRole } from "@openpresentation/opf/composition";
|
|
20
|
+
import { scriptFontRole, scriptOfCharacter, itemizeScripts } from "@openpresentation/opf/composition";
|
|
21
21
|
import { SYMBOL_PLACEHOLDER, SYMBOL_SCRIPT, mapSymbolAdvances, symbolEncodingFamily, symbolPreviewFaces } from "./symbol-fonts.js";
|
|
22
|
-
export { scriptFontRole };
|
|
22
|
+
export { scriptFontRole, scriptOfCharacter, itemizeScripts };
|
|
23
23
|
|
|
24
24
|
const freeze = value => { if (value && typeof value === "object") { for (const child of Object.values(value)) freeze(child); Object.freeze(value); } return value; };
|
|
25
25
|
|
|
@@ -179,34 +179,6 @@ const rtlScripts = new Set(["Arab", "Hebr", "Syrc", "Thaa", "Nkoo", "Adlm", "Roh
|
|
|
179
179
|
/** Scripts the latin slot covers directly; never split from the surrounding Latin run. */
|
|
180
180
|
const latinGroup = new Set(["Latn", "Cyrl", "Grek", "Zyyy", "Zinh", "Zzzz"]);
|
|
181
181
|
|
|
182
|
-
const detected = ["Latn", "Cyrl", "Grek", "Hani", "Hira", "Kana", "Hang", "Bopo", "Yiii", "Arab", "Hebr", "Syrc", "Thaa", "Nkoo", "Adlm", "Rohg", "Mand", "Samr",
|
|
183
|
-
"Deva", "Beng", "Guru", "Gujr", "Orya", "Taml", "Telu", "Knda", "Mlym", "Sinh", "Thai", "Laoo", "Tibt", "Mymr", "Khmr", "Mong", "Bali", "Java", "Lana",
|
|
184
|
-
"Tale", "Talu", "Cakm", "Olck", "Armn", "Geor", "Ethi", "Cher", "Tfng", "Vaii", "Zinh", "Zyyy"];
|
|
185
|
-
// One precompiled pattern for every script, a capture group each, tried in the list's order (the first match wins, as with one
|
|
186
|
-
// pattern per script): a character is classified by one match instead of up to 48 tests.
|
|
187
|
-
const detectedPattern = new RegExp(`^(?:${detected.map(code => String.raw`(\p{Script=${code}})`).join("|")})$`, "u");
|
|
188
|
-
const ignorable = /^\p{Default_Ignorable_Code_Point}$/u;
|
|
189
|
-
const scriptCache = new Map();
|
|
190
|
-
function classify(character) {
|
|
191
|
-
const match = detectedPattern.exec(character);
|
|
192
|
-
if (!match) return "Zzzz";
|
|
193
|
-
for (let group = 1; group < match.length; group++) if (match[group] !== undefined) return detected[group - 1];
|
|
194
|
-
return "Zzzz";
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/** ISO 15924 script of one character: `Zyyy` common, `Zinh` inherited, `Zzzz` otherwise unknown. */
|
|
198
|
-
export function scriptOfCharacter(character) {
|
|
199
|
-
let script = scriptCache.get(character);
|
|
200
|
-
if (script === undefined) {
|
|
201
|
-
const code = character.codePointAt(0);
|
|
202
|
-
script = code < 0x80 ? (/[A-Za-z]/.test(character) ? "Latn" : "Zyyy")
|
|
203
|
-
: ignorable.test(character) ? "Zinh"
|
|
204
|
-
: classify(character);
|
|
205
|
-
if (scriptCache.size < 65536) scriptCache.set(character, script);
|
|
206
|
-
}
|
|
207
|
-
return script;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
182
|
/** Latin, Greek, Cyrillic, general punctuation and letterlike text: no script split is possible. */
|
|
211
183
|
const latinOnly = /^[\u0000-\u036F\u0370-\u052F\u1E00-\u1FFF\u2000-\u2065\u206A-\u20CF\u2100-\u218F]*$/;
|
|
212
184
|
|
|
@@ -230,70 +202,12 @@ function fontKey(script, text, profile, han = () => hanScript(text, profile)) {
|
|
|
230
202
|
return latinGroup.has(script) ? "Latn" : script;
|
|
231
203
|
}
|
|
232
204
|
|
|
233
|
-
// East Asian common characters that PowerPoint always draws with the East Asian
|
|
234
|
-
// (a:ea) font: CJK symbols and punctuation, kana marks, enclosed CJK, CJK
|
|
235
|
-
// compatibility, vertical and small forms, and halfwidth/fullwidth forms.
|
|
236
|
-
const eastAsianCommon = /[\u3000-\u303F\u3040-\u30FF\u31F0-\u31FF\u3200-\u33FF\uFE30-\uFE4F\uFF00-\uFFEF]/u;
|
|
237
205
|
// Characters whose font PowerPoint picks from the run language: with an East
|
|
238
206
|
// Asian language they use the a:ea font (curly quotes, dashes, ellipsis,
|
|
239
207
|
// daggers, per-mille, primes, reference mark).
|
|
240
208
|
const eastAsianAmbiguous = /[\u2010-\u2016\u2018-\u2022\u2025\u2026\u2030\u2032\u2033\u203B]/u;
|
|
241
209
|
const eastAsianLanguage = profile => profile?.scriptRole === "eastAsian" || /^(ja|zh|ko)\b/i.test(String(profile?.bcp47 ?? ""));
|
|
242
210
|
|
|
243
|
-
/**
|
|
244
|
-
* Split text into font runs by Unicode script, following PowerPoint's
|
|
245
|
-
* character-to-slot rules where they are known:
|
|
246
|
-
* - Letters take their script's slot. Latin, Greek and Cyrillic share one run.
|
|
247
|
-
* - East Asian common characters (CJK punctuation U+3000-303F, fullwidth forms
|
|
248
|
-
* U+FF00-FFEF and similar) are East Asian, also at the start of a text; with
|
|
249
|
-
* an East Asian language, curly quotes, dashes and the ellipsis are too.
|
|
250
|
-
* - ASCII spaces, digits and punctuation use the latin slot next to East Asian
|
|
251
|
-
* text, and stay in a complex-script run (as PowerPoint draws them with the
|
|
252
|
-
* complex-script font inside Arabic, Hebrew, Indic or Thai text).
|
|
253
|
-
* - Other common and inherited characters (combining marks, other punctuation)
|
|
254
|
-
* join the preceding run, or the following run at the start of the text.
|
|
255
|
-
* `profile` (for example core `resolveScriptFonts` output) supplies the
|
|
256
|
-
* language, which disambiguates Han and the language-dependent characters.
|
|
257
|
-
*/
|
|
258
|
-
export function itemizeScripts(text, profile) {
|
|
259
|
-
const source = String(text);
|
|
260
|
-
const runs = [];
|
|
261
|
-
let pending = "";
|
|
262
|
-
const eastAsian = eastAsianLanguage(profile);
|
|
263
|
-
// The Han key depends on the whole text and the profile only: work it out once per text, not once per Han character.
|
|
264
|
-
let han;
|
|
265
|
-
const hanOfText = () => han ??= hanScript(source, profile);
|
|
266
|
-
const push = (character, key) => {
|
|
267
|
-
const last = runs.at(-1);
|
|
268
|
-
if (last && last.script === key) last.text += character;
|
|
269
|
-
else runs.push({text: character, script: key, role: scriptFontRole(key)});
|
|
270
|
-
};
|
|
271
|
-
const strong = (character, key) => {
|
|
272
|
-
// Leading neutrals join a complex-script run; otherwise they are Latin.
|
|
273
|
-
if (!runs.length && pending) {
|
|
274
|
-
if (scriptFontRole(key) === "complexScript") { runs.push({text: pending, script: key, role: "complexScript"}); }
|
|
275
|
-
else push(pending, "Latn");
|
|
276
|
-
pending = "";
|
|
277
|
-
}
|
|
278
|
-
push(character, key);
|
|
279
|
-
};
|
|
280
|
-
for (const character of source) {
|
|
281
|
-
const script = scriptOfCharacter(character);
|
|
282
|
-
if (eastAsianCommon.test(character) || (eastAsian && eastAsianAmbiguous.test(character))) {
|
|
283
|
-
strong(character, script === "Hira" || script === "Kana" ? "Jpan" : hanOfText());
|
|
284
|
-
} else if (script === "Zinh") {
|
|
285
|
-
if (runs.length) runs.at(-1).text += character; else pending += character;
|
|
286
|
-
} else if (script === "Zyyy") {
|
|
287
|
-
const last = runs.at(-1);
|
|
288
|
-
if (!last) pending += character;
|
|
289
|
-
else if (character.codePointAt(0) < 0x80 && last.role === "eastAsian") push(character, "Latn");
|
|
290
|
-
else last.text += character;
|
|
291
|
-
} else strong(character, fontKey(script, source, profile, hanOfText));
|
|
292
|
-
}
|
|
293
|
-
if (!runs.length) return [{text: pending, script: "Latn", role: "latin"}];
|
|
294
|
-
return runs;
|
|
295
|
-
}
|
|
296
|
-
|
|
297
211
|
/**
|
|
298
212
|
* Non-Latin script keys the renderer would plan runs for in `text`. It applies the same shortcut as drawing
|
|
299
213
|
* (`createScriptFonts().plan`): Latin, Greek and Cyrillic text is one run in the design font, except that
|
|
@@ -438,6 +352,8 @@ const scriptMeasurement = Symbol.for("@openpresentation/opf-render/script-measur
|
|
|
438
352
|
* receives each new substitution note `{fontFamily, fallbackFamily, scripts,
|
|
439
353
|
* characters, path?}` once; `fallbacks` lists them all.
|
|
440
354
|
*/
|
|
355
|
+
// Internal recording planners need strict coverage probes but may finish recording unsupported text before optional fonts arrive.
|
|
356
|
+
export const fontCoverageProbe = Symbol('opf.font-analysis-coverage');
|
|
441
357
|
export function createScriptFonts(profile = {}, measurement, options = {}) {
|
|
442
358
|
const wrapped = measurement?.[scriptMeasurement];
|
|
443
359
|
const inner = wrapped?.inner ?? measurement;
|
|
@@ -474,7 +390,7 @@ export function createScriptFonts(profile = {}, measurement, options = {}) {
|
|
|
474
390
|
const key = `${family}\u0000${style.fontWeight ?? 400}\u0000${!!style.italic}\u0000${text}`;
|
|
475
391
|
if (coverage.has(key)) return coverage.get(key);
|
|
476
392
|
let result = true;
|
|
477
|
-
try { inner.measure(text, 1, {...style, fontFamily: family}); }
|
|
393
|
+
try { if (inner[fontCoverageProbe]) inner[fontCoverageProbe](text, 1, {...style, fontFamily: family}); else inner.measure(text, 1, {...style, fontFamily: family}); }
|
|
478
394
|
catch (error) { if (error?.code !== "missing-glyph" && !softErrors.has(error?.code)) throw error; result = false; }
|
|
479
395
|
if (coverage.size >= 8192) coverage.delete(coverage.keys().next().value);
|
|
480
396
|
coverage.set(key, result);
|
|
@@ -613,7 +529,7 @@ export function createScriptFonts(profile = {}, measurement, options = {}) {
|
|
|
613
529
|
// (Cyrillic or Greek beyond a Latin replacement): then it is planned per character below.
|
|
614
530
|
if (!fallbackEnabled || !nonAscii.test(text)) return [{text, family: style.fontFamily, own: true}];
|
|
615
531
|
if (!measured) return cyrillicOrGreek.test(text) ? [{text, family: style.fontFamily, own: false, stack: [style.fontFamily, ...designatedFamilies("Latn", serif)]}] : [{text, family: style.fontFamily, own: true}];
|
|
616
|
-
if (ownFace === null || covers(
|
|
532
|
+
if (ownFace === null || covers(style.fontFamily, text, style)) return [{text, family: style.fontFamily, own: true}];
|
|
617
533
|
}
|
|
618
534
|
const cacheKey = `${style.fontFamily}\u0000${style.fontWeight ?? 400}\u0000${!!style.italic}\u0000${textRole(style) ?? ""}\u0000${style.path ?? ""}\u0000${text}`;
|
|
619
535
|
const cached = plans.get(cacheKey);
|
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.d.ts
CHANGED
|
@@ -28,6 +28,12 @@ export declare const engineDefaults: Readonly<{
|
|
|
28
28
|
}>;
|
|
29
29
|
|
|
30
30
|
export type RenderDiagnostic = LayoutDiagnostic | {
|
|
31
|
+
/** A generated RTL numbered marker stayed text; this PNG/raster-PDF marker is not direction-qualified. */
|
|
32
|
+
code: "raster-marker-unavailable";
|
|
33
|
+
reason: "unresolved" | "restricted" | "colour-font" | "shaping" | "system-fonts";
|
|
34
|
+
fontFamily?: string;
|
|
35
|
+
message: string;
|
|
36
|
+
} | {
|
|
31
37
|
/** LH-145: a picture background could not be read or decoded by `measurePictures`; its scrim is sized for any picture. */
|
|
32
38
|
code: "picture-not-measured";
|
|
33
39
|
path: string;
|