@openpresentation/opf-render 0.35.1 → 0.37.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.
@@ -0,0 +1,93 @@
1
+ // FR-08: the live frames of a web presenter. The renderer draws an embed as its static form (a picture or a card) and marks it with
2
+ // `data-opf-embed*` attributes; engines never load the page. A presenter whose host allows a page (its `embeds` option) calls
3
+ // `mountLiveEmbeds` after it draws a slide: a sandboxed iframe goes over the static form of each allowed embed, and the static form
4
+ // stays under it until the frame loads (and stays if the frame never does). The deck holds no sandbox policy: which pages are shown
5
+ // live is the host's list, and nothing is shown live by default.
6
+
7
+ /** What a live frame may do. Same-origin pages are never framed (see `isSameOriginPage`), so `allow-same-origin` keeps the page its own origin, not the host's. */
8
+ export const LIVE_EMBED_SANDBOX = "allow-scripts allow-same-origin allow-popups allow-forms";
9
+
10
+ /**
11
+ * Whether an address is on the origin of the page that presents it. Such a page is never shown live whatever the host's list says:
12
+ * a sandbox that allows scripts and its own origin does not contain a page of the host's own origin.
13
+ */
14
+ export function isSameOriginPage(src, origin) {
15
+ if (!origin || origin === "null") return false;
16
+ try { return new URL(src).origin === new URL(origin).origin; } catch { return false; }
17
+ }
18
+
19
+ /** The embeds an SVG slide draws: `{ path, src, title, area }`, `area` the element whose box is the frame. */
20
+ export function embedsOf(svg) {
21
+ const found = [];
22
+ for (const group of svg?.querySelectorAll?.("[data-opf-embed]") ?? []) {
23
+ const src = group.getAttribute("data-opf-embed-src"), area = group.querySelector("[data-opf-link-area]");
24
+ if (src && area) found.push({ path: group.getAttribute("data-opf-embed"), src, title: group.getAttribute("data-opf-embed-title") ?? "", area });
25
+ }
26
+ return found;
27
+ }
28
+
29
+ /**
30
+ * Put a sandboxed frame over each embed of `svg` that the host allows. `host` is the element that holds the SVG (the frames go in a
31
+ * layer appended to it, which takes no pointer events itself). `embeds(src)` is the host's answer (absent: nothing is live), `origin`
32
+ * the presenting page's origin (default: the document's). Returns `{ frames, destroy }`; `destroy` removes the layer.
33
+ *
34
+ * A click on a live frame never reaches the presenter, so it never changes the slide; the slide keys keep working while the frame
35
+ * does not have focus. Tab enters a frame only after a click on it.
36
+ */
37
+ export function mountLiveEmbeds({ host, svg, embeds, origin, document: doc = host?.ownerDocument }) {
38
+ const none = { frames: [], destroy() {} };
39
+ if (typeof embeds !== "function" || !host || !svg || !doc) return none;
40
+ const win = doc.defaultView ?? globalThis, page = origin ?? win.location?.origin;
41
+ const wanted = embedsOf(svg).filter(({ src }) => {
42
+ if (isSameOriginPage(src, page)) return false;
43
+ try { return embeds(src) === true; } catch { return false; }
44
+ });
45
+ if (!wanted.length) return none;
46
+ const layer = doc.createElement("div");
47
+ layer.setAttribute("data-opf-live-embeds", "");
48
+ layer.style.cssText = "position:absolute;inset:0;pointer-events:none;overflow:hidden";
49
+ const entries = wanted.map(({ path, src, title, area }) => {
50
+ const box = doc.createElement("div");
51
+ box.setAttribute("data-opf-live-embed", path);
52
+ box.style.cssText = "position:absolute;pointer-events:auto;overflow:hidden;visibility:hidden";
53
+ const frame = doc.createElement("iframe");
54
+ frame.setAttribute("sandbox", LIVE_EMBED_SANDBOX);
55
+ frame.setAttribute("referrerpolicy", "no-referrer");
56
+ frame.setAttribute("loading", "lazy");
57
+ frame.setAttribute("title", title);
58
+ // Tab skips the frame (and everything in it) until the viewer has clicked it: a press inside a frame blurs this window with the frame as its active element.
59
+ frame.setAttribute("tabindex", "-1");
60
+ frame.style.cssText = "display:block;width:100%;height:100%;border:0;background:#fff";
61
+ // The static form stays visible under the frame until the page has loaded; a page that never loads leaves the static form.
62
+ frame.addEventListener("load", () => { box.style.visibility = "visible"; });
63
+ box.append(frame);
64
+ // Nothing a press on the frame's box does reaches the presenter's own zones.
65
+ for (const type of ["click", "pointerdown", "pointerup", "touchstart", "touchend"]) box.addEventListener(type, (event) => event.stopPropagation());
66
+ layer.append(box);
67
+ frame.setAttribute("src", src);
68
+ return { box, frame, area };
69
+ });
70
+ const place = () => {
71
+ const base = layer.getBoundingClientRect();
72
+ for (const { box, area } of entries) {
73
+ const at = area.getBoundingClientRect();
74
+ Object.assign(box.style, { left: `${at.left - base.left}px`, top: `${at.top - base.top}px`, width: `${at.width}px`, height: `${at.height}px` });
75
+ }
76
+ };
77
+ const onBlur = () => { for (const { frame } of entries) if (doc.activeElement === frame) frame.setAttribute("tabindex", "0"); };
78
+ host.append(layer);
79
+ place();
80
+ const observer = typeof win.ResizeObserver === "function" ? new win.ResizeObserver(place) : undefined;
81
+ observer?.observe(host);
82
+ win.addEventListener("resize", place);
83
+ win.addEventListener("blur", onBlur);
84
+ return {
85
+ frames: entries.map(({ frame }) => frame),
86
+ destroy() {
87
+ observer?.disconnect();
88
+ win.removeEventListener("resize", place);
89
+ win.removeEventListener("blur", onBlur);
90
+ layer.remove();
91
+ },
92
+ };
93
+ }
@@ -188,6 +188,9 @@ class Converter {
188
188
  };
189
189
  page.section.page = page;
190
190
  this.pages.push(page);
191
+ // FR-03: the slide this page draws, when another slide links to it (the first page of a slide that continues).
192
+ const slideId = attrs["data-opf-slide"];
193
+ if (slideId !== undefined && !(this.slidePages ??= new Map()).has(slideId)) this.slidePages.set(slideId, page);
191
194
  // The page is painted white unless `background` says otherwise (raster mode composites on white too), so the page looks
192
195
  // the same in viewers that show a dark or transparent paper.
193
196
  const background = parseColor(this.options.background ?? "#FFFFFF");
@@ -317,7 +320,8 @@ class Converter {
317
320
  };
318
321
  if (node.name === "a") {
319
322
  const href = attrs.href ?? attrs["xlink:href"];
320
- if (href !== undefined) next.link = { href, node };
323
+ // FR-03: a slide link (`data-opf-slide-link`) is a link to the page of that slide, not to an address.
324
+ if (href !== undefined) next.link = { href, node, slide: attrs["data-opf-slide-link"] };
321
325
  }
322
326
  const opacity = attrs.opacity === undefined ? 1 : Math.min(1, Math.max(0, parseFloat(attrs.opacity)));
323
327
  if (opacity === 0 || Number.isNaN(opacity)) return;
@@ -447,6 +451,8 @@ class Converter {
447
451
  const resolve = (value, reference) => parseLength(value, { reference: reference ?? viewport.w, fontSize });
448
452
  const commands = shapeToPath(node, attrs, (value, reference) => resolve(value, reference), ctx.page.viewport);
449
453
  if (!commands) return;
454
+ // FR-08: a transparent rect marked as a link area (an embed's frame) is the rectangle of a link annotation, not a drawing.
455
+ if (attrs["data-opf-link-area"] === "true" && ctx.link) this.areaLinkAnnotation(attrs, ctx);
450
456
  const isLine = node.name === "line";
451
457
  const fill = isLine ? null : await this.paint(style.fill, style, ctx, commands, "fill");
452
458
  const strokeWidth = resolve(style["stroke-width"]) ?? 1;
@@ -905,8 +911,23 @@ class Converter {
905
911
  if (run.link) this.linkAnnotation(run, ctx);
906
912
  }
907
913
 
914
+ /** FR-08: a link annotation over the rect an `a` element holds (its `data-opf-link-area`), for a link that wraps a picture and no text. */
915
+ areaLinkAnnotation(attrs, ctx) {
916
+ const link = ctx.link, uri = link.slide === undefined ? safeUri(link.href) : "";
917
+ if (uri === null) {
918
+ this.unsupported("pdf-link-skipped", `The link target ${JSON.stringify(link.href).slice(0, 80)} is not an http, https, mailto or tel address; no PDF link is created.`, {});
919
+ return;
920
+ }
921
+ const x = Number(attrs.x) || 0, y = Number(attrs.y) || 0, width = Number(attrs.width) || 0, height = Number(attrs.height) || 0;
922
+ if (!(width > 0 && height > 0)) return;
923
+ const box = boundsOf([[x, y], [x + width, y], [x + width, y + height], [x, y + height]].map(([px, py]) => applyPoint(ctx.matrix, px, py)));
924
+ const page = ctx.page;
925
+ page.annotations.push({ rect: [box.x, page.height - box.y - box.height, box.x + box.width, page.height - box.y], uri, ...(link.slide === undefined ? {} : { slide: link.slide }), object: link.slide === undefined ? this.file.reserve() : undefined, parent: null });
926
+ }
927
+
908
928
  linkAnnotation(run, ctx) {
909
- const uri = safeUri(run.link.href);
929
+ const slide = run.link.slide;
930
+ const uri = slide === undefined ? safeUri(run.link.href) : "";
910
931
  if (uri === null) {
911
932
  this.unsupported("pdf-link-skipped", `The link target ${JSON.stringify(run.link.href).slice(0, 80)} is not an http, https, mailto or tel address; no PDF link is created.`, {});
912
933
  return;
@@ -916,7 +937,7 @@ class Converter {
916
937
  const corners = [[run.x, top], [run.x + run.width, top], [run.x + run.width, bottom], [run.x, bottom]].map(([x, y]) => applyPoint(ctx.matrix, x, y));
917
938
  const box = boundsOf(corners);
918
939
  const page = ctx.page;
919
- const annotation = { rect: [box.x, page.height - box.y - box.height, box.x + box.width, page.height - box.y], uri, object: this.file.reserve(), parent: null };
940
+ const annotation = { rect: [box.x, page.height - box.y - box.height, box.x + box.width, page.height - box.y], uri, ...(slide === undefined ? {} : { slide }), object: slide === undefined ? this.file.reserve() : undefined, parent: null };
920
941
  page.annotations.push(annotation);
921
942
  const last = page.mcids.at(-1);
922
943
  annotation.parent = last?.role === "Link" ? last : null;
@@ -994,6 +1015,18 @@ class Converter {
994
1015
  }
995
1016
  for (const report of reports) this.diagnostic(report);
996
1017
  const file = this.file;
1018
+ // FR-03: a link to a slide becomes a go-to-page link once every page is known. A slide that is not in this PDF (left out of the
1019
+ // selection, a hidden slide the export skips) has no page: its text stays, without a link.
1020
+ for (const page of this.pages) {
1021
+ page.annotations = page.annotations.filter((annotation) => {
1022
+ if (annotation.slide === undefined) return true;
1023
+ annotation.target = this.slidePages?.get(annotation.slide);
1024
+ if (annotation.target) { annotation.object = file.reserve(); return true; }
1025
+ if (annotation.parent?.annots) annotation.parent.annots = annotation.parent.annots.filter((other) => other !== annotation);
1026
+ this.diagnostic({ code: "pdf-link-skipped", message: `The link to slide ${JSON.stringify(annotation.slide).slice(0, 80)} has no page in this PDF (the slide is not part of the output); no PDF link is created.` });
1027
+ return false;
1028
+ });
1029
+ }
997
1030
  const pagesObject = file.reserve();
998
1031
  const pageObjects = [];
999
1032
  const tagged = this.tagged;
@@ -1003,7 +1036,7 @@ class Converter {
1003
1036
  const contents = file.addStream("", page.content.text());
1004
1037
  const annotations = page.annotations.map((annotation) => {
1005
1038
  const struct = tagged && annotation.parent ? ` /StructParent ${structure.annotationKey(annotation)}` : "";
1006
- file.set(annotation.object, `/Type/Annot/Subtype/Link/Rect[${annotation.rect.map((value) => num(value, 3)).join(" ")}]/Border[0 0 0]/F 4/A<</S/URI/URI${asciiString(annotation.uri)}>>/P ${ref(page.object)}${struct}`);
1039
+ file.set(annotation.object, `/Type/Annot/Subtype/Link/Rect[${annotation.rect.map((value) => num(value, 3)).join(" ")}]/Border[0 0 0]/F 4/A${annotation.target ? `<</S/GoTo/D[${ref(annotation.target.object)} /XYZ 0 ${num(annotation.target.height)} null]>>` : `<</S/URI/URI${asciiString(annotation.uri)}>>`}/P ${ref(page.object)}${struct}`);
1007
1040
  return ref(annotation.object);
1008
1041
  });
1009
1042
  const structParents = tagged && page.mcids.length ? `/StructParents ${structure.pageKey(page)}` : "";
package/dist/player.d.ts CHANGED
@@ -34,6 +34,12 @@ export interface PresentOptions {
34
34
  * Default true; `false` draws every slide as written.
35
35
  */
36
36
  continuation?: boolean;
37
+ /**
38
+ * FR-08: which embedded pages are shown live, by address. A page for which it returns true is shown in a sandboxed frame over the
39
+ * embed's picture or card (the static form stays under it until the frame loads); every other embed stays its static form, linked
40
+ * to its address. Default: none is live. A page on the presenting page's own origin is never shown live, whatever this returns.
41
+ */
42
+ embeds?: (src: string) => boolean;
37
43
  /** Play hidden slides too. Default false. */
38
44
  includeHidden?: boolean;
39
45
  /** Ask for full screen (needs a user gesture). Default true. */
package/dist/player.js CHANGED
@@ -4,9 +4,10 @@
4
4
  // slides are skipped. No transitions or builds (deferred, opf#250) and no rich notes (opf#251): notes are plain text.
5
5
  import {
6
6
  DeckError, counterText, createCursor, createDeckStore, createSync, createTimer, deckChannelName, formatDuration, localIsoDate, newSurfaceId,
7
- parseDeckDocument, plainText, presentableIndexes, prepareSlideSvg, sanitizeSvgTree, slideLabel, stateWins, svgDimensions,
7
+ linkAt, parseDeckDocument, plainText, presentableIndexes, prepareSlideSvg, sanitizeSvgTree, slideIndexById, slideLabel, stateWins, svgDimensions,
8
8
  } from "./deck-runtime.js";
9
9
  import { loadPreviewFonts } from "./preview-fonts.js";
10
+ import { mountLiveEmbeds } from "./live-embeds.js";
10
11
 
11
12
  export { DeckError } from "./deck-runtime.js";
12
13
 
@@ -205,6 +206,14 @@ class Surface {
205
206
  last() { const position = this.cursor.total - 1; return this.navigate(position, this.store.pages(this.cursor.sequence[position]) - 1); }
206
207
  goto(number) { return this.navigate(number - 1); }
207
208
  setBlank(mode) { return this.apply({ blank: this.blank === mode ? "none" : mode }); }
209
+ /**
210
+ * FR-03: the slide a `slide:<id>` link names, on its first page. A hidden slide is not in the sequence the show plays (`includeHidden`
211
+ * puts it there), so a link to one goes nowhere; an unknown id goes nowhere too. Returns whether the show moved.
212
+ */
213
+ gotoSlideId(id) {
214
+ const position = this.cursor.sequence.indexOf(slideIndexById(this.store.document, id));
215
+ return position < 0 ? false : this.navigate(position);
216
+ }
208
217
 
209
218
  setDigits(value) {
210
219
  this.digits = value;
@@ -220,8 +229,9 @@ class Surface {
220
229
  if (target?.closest?.("input, textarea, select")) return;
221
230
  const action = keyAction(event, this.digits);
222
231
  if (!action) return;
223
- // A focused button handles its own Enter and Space.
232
+ // A focused button handles its own Enter and Space, and a focused link its own Enter (a slide link then jumps, in the click handler).
224
233
  if (action.type === "next" && (event.key === "Enter" || event.key === " ") && target?.localName === "button") return;
234
+ if (action.type === "next" && event.key === "Enter" && linkAt(target)) return;
225
235
  event.preventDefault();
226
236
  switch (action.type) {
227
237
  case "digit": this.setDigits((this.digits + action.digit).slice(0, 4)); break;
@@ -251,7 +261,7 @@ class Surface {
251
261
 
252
262
  // --- the audience view: the full-screen overlay ---------------------------------------------------------------------------
253
263
 
254
- function mountAudience({ doc, win, container, session }) {
264
+ function mountAudience({ doc, win, container, session, embeds }) {
255
265
  const el = makeElement(doc);
256
266
  const host = doc.createElement("div");
257
267
  host.setAttribute("data-opf-player", "");
@@ -289,7 +299,10 @@ function mountAudience({ doc, win, container, session }) {
289
299
  let svg;
290
300
  try { svg = store.svg(cursor.index, cursor.page); } catch (error) { view.failed(error.message); return; }
291
301
  parts.message.hidden = true;
302
+ view.live?.destroy();
292
303
  const { width, height } = drawInto(parts.slide, svg, doc);
304
+ // FR-08: the pages the host allows (the `embeds` option) are shown live over their static form; none by default.
305
+ view.live = mountLiveEmbeds({ host: parts.slide, svg: parts.slide.firstElementChild, embeds, document: doc });
293
306
  parts.frame.style.setProperty("--ratio", `${width} / ${height}`);
294
307
  parts.frame.style.setProperty("--ratio-n", String(width / height));
295
308
  const label = slideLabel(info, cursor.number, cursor.total, cursor.page + 1, cursor.pages);
@@ -331,6 +344,7 @@ function mountAudience({ doc, win, container, session }) {
331
344
  },
332
345
  dispose() {
333
346
  win.clearTimeout(view.idleTimer);
347
+ view.live?.destroy();
334
348
  for (const node of view.previouslyInert) node.inert = false;
335
349
  view.previouslyInert = [];
336
350
  host.remove();
@@ -354,6 +368,9 @@ function mountAudience({ doc, win, container, session }) {
354
368
  parts.root.addEventListener("click", (event) => {
355
369
  if (view.swiped) { view.swiped = false; return; }
356
370
  if (!view.surface || event.composedPath().includes(parts.hud)) return;
371
+ // FR-03: a slide link jumps to its slide; any other link is the browser's and does not move the show.
372
+ const hit = linkAt(event.composedPath?.()[0] ?? event.target);
373
+ if (hit && view.surface.blank === "none") { if (hit.slide) { event.preventDefault(); view.surface.gotoSlideId(hit.slide); } return; }
357
374
  if (view.surface.blank !== "none") { view.surface.apply({ blank: "none" }); return; }
358
375
  const box = parts.root.getBoundingClientRect();
359
376
  if (event.clientX - box.left < box.width / 3) view.surface.previous(); else view.surface.next();
@@ -654,7 +671,8 @@ async function readSource(source, signal) {
654
671
  * Options: `fonts` (the self-hosted font root URL, or a browser fonts handle from `loadFonts`), `renderOptions` (extra `toSvg` options),
655
672
  * `startSlide` (1-based), `includeHidden`, `fullscreen` (default true), `presenterView` (open the speaker view too),
656
673
  * `role: "presenter"` (this window is the speaker view: for a second tab or window of your page), `channel` (name, or `false`
657
- * for no sync), `container`, `signal` and `now` (an injectable clock).
674
+ * for no sync), `container`, `signal`, `now` (an injectable clock) and `embeds` (FR-08: `(src) => boolean`, which embedded pages
675
+ * are shown live; none by default).
658
676
  */
659
677
  export async function present(source, options = {}) {
660
678
  const container = options.container ?? globalThis.document?.body;
@@ -671,7 +689,7 @@ export async function present(source, options = {}) {
671
689
  // Cover the page and ask for full screen before awaiting anything: the click that called us must still count.
672
690
  let view;
673
691
  if (role === "audience") {
674
- view = mountAudience({ doc, win, container, session });
692
+ view = mountAudience({ doc, win, container, session, embeds: options.embeds });
675
693
  session.audienceHost = view.host;
676
694
  view.attach(options.returnFocus ?? doc.activeElement);
677
695
  if (options.fullscreen !== false) session.requestFullscreen();
@@ -108,7 +108,7 @@ const escapeXml = (value) => String(value).replace(/[&<>"']/g, (char) => ({ "&":
108
108
  * system's, and `cacheDir` names its cache. An alias replaces the family even where the original is installed.
109
109
  */
110
110
  export function fontconfigConf({ fontDir, aliases = fontconfigAliases(), includeSystem = false, cacheDir } = {}) {
111
- const lines = ['<?xml version="1.0"?>', '<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">', "<!-- OPF preview fonts and font-policy aliases (opf-preview-fonts --fontconfig). -->", "<fontconfig>"];
111
+ const lines = ['<?xml version="1.0"?>', '<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">', "<!-- OPF preview fonts and font-policy aliases, written by opf-preview-fonts with its fontconfig option. -->", "<fontconfig>"];
112
112
  if (includeSystem) lines.push(' <include ignore_missing="yes">/etc/fonts/fonts.conf</include>');
113
113
  if (fontDir) lines.push(` <dir>${escapeXml(fontDir)}</dir>`);
114
114
  if (cacheDir) lines.push(` <cachedir>${escapeXml(cacheDir)}</cachedir>`);
@@ -1,3 +1,4 @@
1
+ import {svgHslStopsToSrgb} from '@openpresentation/opf/composition';
1
2
  import {OPFRenderError} from './svg.js';
2
3
  import {isConverterMissing,loadConverter} from './converters.js';
3
4
 
@@ -37,16 +38,29 @@ export async function prepareRasterImages(svg, {nestedSvg} = {}) {
37
38
  return output + svg.slice(end);
38
39
  }
39
40
 
41
+ // The HSL stop forms resvg reads as a browser does (measured with resvg 2.6.2): an integer hue without a unit, integer
42
+ // percentages, commas or spaces between them and an optional alpha number after a fourth comma. resvg draws every other valid
43
+ // form black or not at all (the slash alpha, number-only, a hue unit, decimals, a percentage alpha), so only those are converted:
44
+ // a form resvg draws keeps its bytes and its pixels (resvg truncates where the conversion rounds, a one-level difference).
45
+ const RESVG_HSL = /^hsla?\(\s*[+-]?\d+\s*(?:,\s*|\s+)\d+%\s*(?:,\s*|\s+)\d+%\s*(?:,\s*(?:\d+(?:\.\d*)?|\.\d+)\s*)?\)$/i;
46
+
40
47
  // An SVG picture that draws text is rendered to PNG here (transparent, up to 4x its size) so its text uses the render's fonts;
41
- // one without text stays vector for resvg.
48
+ // one without text stays vector for resvg. Either way the HSL gradient stops resvg cannot read are first converted to sRGB
49
+ // (opf#1438, the conversion the PPTX export applies), so the PNG draws what a browser draws. A picture with nothing to convert
50
+ // keeps its bytes.
42
51
  async function prepareSvgImage(uri, nestedSvg) {
43
- if (!nestedSvg) return null;
44
52
  const comma = uri.indexOf(',');
45
53
  const header = uri.slice(0, comma), data = uri.slice(comma + 1);
46
- const text = /;base64$/i.test(header) ? Buffer.from(decodeURIComponent(data).replace(/\s/g, ''), 'base64').toString('utf8') : decodeURIComponent(data);
47
- if (!/<(?:[A-Za-z_][\w.-]*:)?text[\s>/]/.test(text)) return null;
48
- // A document resvg cannot read stays as it is: resvg then draws nothing for it, as for any broken picture.
49
- try { return 'data:image/png;base64,' + Buffer.from(await nestedSvg(text)).toString('base64'); } catch { return null; }
54
+ let source;
55
+ try {
56
+ source = /;base64$/i.test(header) ? Buffer.from(decodeURIComponent(data).replace(/\s/g, ''), 'base64').toString('utf8') : decodeURIComponent(data);
57
+ } catch { return null; }
58
+ const text = svgHslStopsToSrgb(source, {keep: value => RESVG_HSL.test(value)});
59
+ if (nestedSvg && /<(?:[A-Za-z_][\w.-]*:)?text[\s>/]/.test(text)) {
60
+ // A document resvg cannot read stays as it is: resvg then draws nothing for it, as for any broken picture.
61
+ try { return 'data:image/png;base64,' + Buffer.from(await nestedSvg(text)).toString('base64'); } catch { return null; }
62
+ }
63
+ return text === source ? null : 'data:image/svg+xml;base64,' + Buffer.from(text, 'utf8').toString('base64');
50
64
  }
51
65
 
52
66
  async function prepareRasterImage(uri) {
@@ -17,6 +17,7 @@
17
17
  // faces and lets a missing glyph raise `missing-glyph`.
18
18
 
19
19
  import { fontPolicyFor } from "@openpresentation/opf/font-policy";
20
+ import { GLYPH_DEFECTS, glyphDefectsFor } from "./font-compatibility.js";
20
21
  import { scriptFontRole, scriptOfCharacter, itemizeScripts } from "@openpresentation/opf/composition";
21
22
  import { SYMBOL_PLACEHOLDER, SYMBOL_SCRIPT, mapSymbolAdvances, symbolEncodingFamily, symbolPreviewFaces } from "./symbol-fonts.js";
22
23
  export { scriptFontRole, scriptOfCharacter, itemizeScripts };
@@ -542,9 +543,73 @@ export function createScriptFonts(profile = {}, measurement, options = {}) {
542
543
  return out;
543
544
  };
544
545
 
546
+ /**
547
+ * opf#1472: a character a bundled face draws wrongly (GLYPH_DEFECTS: U+0111 in the Intos sans faces) is its own run, drawn by the
548
+ * first loaded family of the row's `replacement` that has it. Every run of such a line carries its share of the unsplit line's advance
549
+ * (`run.advance`, em, kerning included), so the line measures, wraps and is placed exactly as before: the SVG draws the replacement at the font size (`run.fontScale`) whose own advance is
550
+ * that advance, in a line that flows (no positioned runs), so every rasterizer, letter-spacing included, places it as it placed the old glyph. Text without such a
551
+ * character, and a face with no loaded replacement, plan as before. Undefined when nothing is replaced.
552
+ */
553
+ const defectCodes = new Set(GLYPH_DEFECTS.flatMap(row => row.codePoints));
554
+ const defectPlans = new Map();
555
+ const planDefects = (text, style) => {
556
+ if (!measured || !fallbackEnabled || ![...text].some(character => defectCodes.has(character.codePointAt(0)))) return undefined;
557
+ const cacheKey = `${style.fontFamily}${style.fontWeight ?? 400}${!!style.italic}${style.path ?? ""}${text}`;
558
+ if (defectPlans.has(cacheKey)) return defectPlans.get(cacheKey);
559
+ let result;
560
+ try {
561
+ const own = inner.resolveStyle({...style}), defect = glyphDefectsFor(own?.fontFamily, own?.fontWeight ?? 400, own?.italic === true);
562
+ if (defect) {
563
+ const bad = new Set(defect.codePoints), replacements = new Map();
564
+ const replacementFor = character => {
565
+ if (!replacements.has(character)) {
566
+ const family = defect.replacement.map(name => resolveName(name, {...style, fontWeight: own.fontWeight, italic: false})).find(name => name && name !== own.fontFamily && covers(name, character, style));
567
+ if (family === undefined) replacements.set(character, null);
568
+ else {
569
+ const advance = inner.measure(character, 1, styled({...style, fontFamily: own.fontFamily, fontWeight: own.fontWeight, italic: own.italic})), natural = inner.measure(character, 1, styled({...style, fontFamily: family, fontWeight: own.fontWeight, italic: false}));
570
+ replacements.set(character, {family, scale: natural > 0 && Math.abs(advance / natural - 1) > 1e-9 ? advance / natural : undefined});
571
+ }
572
+ }
573
+ return replacements.get(character);
574
+ };
575
+ // The line's advance up to each boundary, measured on the whole prefix as the unsplit line was (the shaper kerns a letter with the
576
+ // glyph after it), so the runs' advances add up to exactly the width the unsplit line had.
577
+ const lineStyle = styled(style), upTo = new Map([[0, 0]]);
578
+ const at = index => { if (!upTo.has(index)) upTo.set(index, inner.measure(text.slice(0, index), 1, lineStyle)); return upTo.get(index); };
579
+ const out = [];
580
+ let piece = "", pieceStart = 0, offset = 0;
581
+ const flush = () => {
582
+ if (!piece) return;
583
+ const runs = plan(piece, style, true);
584
+ // A piece that is one run of the line's own face takes its share of the line (a run drawn in another face keeps its own width).
585
+ if (runs.length === 1 && runs[0].own) runs[0] = {...runs[0], advance: at(pieceStart + piece.length) - at(pieceStart)};
586
+ out.push(...runs);
587
+ piece = "";
588
+ };
589
+ for (const character of text) {
590
+ const replacement = bad.has(character.codePointAt(0)) ? replacementFor(character) : null;
591
+ if (replacement) {
592
+ flush();
593
+ out.push({text: character, family: replacement.family, own: false, advance: at(offset + character.length) - at(offset), ...(replacement.scale ? {fontScale: replacement.scale} : {})});
594
+ } else {
595
+ if (!piece) pieceStart = offset;
596
+ piece += character;
597
+ }
598
+ offset += character.length;
599
+ }
600
+ flush();
601
+ if (out.some(run => run.advance !== undefined)) result = out;
602
+ }
603
+ } catch (error) { if (!softErrors.has(error?.code)) throw error; }
604
+ if (defectPlans.size >= 4096) defectPlans.delete(defectPlans.keys().next().value);
605
+ defectPlans.set(cacheKey, result);
606
+ return result;
607
+ };
608
+
545
609
  /** Font runs for text drawn in `style` (the resolved latin style). `own` runs use the style's family. */
546
- const plan = (text, style) => {
610
+ const plan = (text, style, plain = false) => {
547
611
  text = String(text ?? "");
612
+ if (!plain) { const replaced = planDefects(text, style); if (replaced) return replaced; }
548
613
  // A symbol-encoded family (resolved styles carry `symbolEncoding`; an unresolved style names the family itself) is mapped code by
549
614
  // code; `symbolEncoding: null` is the planner's own request for ordinary runs (characters that are not codes).
550
615
  const encoding = style.symbolEncoding === null ? undefined : style.symbolEncoding ?? symbolEncodingFamily(style.fontFamily);
@@ -663,7 +728,7 @@ export function createScriptFonts(profile = {}, measurement, options = {}) {
663
728
  * verified symbol font's advance for its code, so lines break and bullets sit where PowerPoint puts them; `natural`
664
729
  * asks for the open face's advance of that run instead (the SVG compresses a wider glyph to fit, never stretches one).
665
730
  */
666
- const runWidth = (run, size, style, natural = false) => run.symbol && !natural && run.symbol.advance !== null ? run.symbol.advance * size : inner.measure(run.text, adjustedFontSize(size, run.sizeAdjust), styleFor(run, style));
731
+ const runWidth = (run, size, style, natural = false) => run.advance !== undefined ? run.advance * size : run.symbol && !natural && run.symbol.advance !== null ? run.symbol.advance * size : inner.measure(run.text, adjustedFontSize(size, run.sizeAdjust), styleFor(run, style));
667
732
  /** Advance of each planned run, in order (see `runWidth`); undefined without a measurement provider. */
668
733
  const runWidths = (runs, size, style, {natural = false} = {}) => measured ? runs.map(run => runWidth(run, size, style, natural)) : undefined;
669
734
  let textMeasurement;
package/dist/shapes.js CHANGED
@@ -2,7 +2,7 @@
2
2
  //
3
3
  // A shape block (core ComposedItem.shape) is drawn from core's evaluated geometry (SH-01 presetGeometry, in slide coordinates):
4
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
5
+ // the path takes the line, all fills before all lines (renderShapeBlock says why); 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
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
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
8
  //
@@ -18,6 +18,16 @@ const number = value => (Number.isInteger(value) ? String(value) : Number(value)
18
18
  const precise = value => String(Math.round(value * 1e6) / 1e6);
19
19
 
20
20
  /** DrawingML preset dashes as dash and gap lengths in line widths (PowerPoint's patterns for a flat cap). */
21
+ /**
22
+ * FR-03: the attributes of the `a` a link draws. A web, mail or phone link opens in a new tab; a `slide:<id>` link is a fragment link that
23
+ * carries the slide's id in `data-opf-slide-link`: the player and the presenter jump to that slide, the PDF export writes a link to its
24
+ * page, and the PowerPoint export writes a slide jump. Nothing here opens a tab.
25
+ */
26
+ export function linkAnchorAttrs(link, { newTab = false } = {}) {
27
+ if (typeof link === "string" && link.startsWith("slide:") && link.length > 6) return { href: `#slide:${link.slice(6)}`, "data-opf-slide-link": link.slice(6) };
28
+ return newTab ? { href: link, target: "_blank", rel: "noopener noreferrer" } : { href: link };
29
+ }
30
+
21
31
  export const PRESET_DASHES = Object.freeze({
22
32
  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
33
  sysDot: [1, 1], sysDash: [3, 1], sysDashDot: [3, 1, 1, 1], sysDashDotDot: [3, 1, 1, 1, 1, 1],
@@ -254,6 +264,13 @@ export function renderShapeBlock(item, helpers) {
254
264
  const id = `${helpers.idPrefix}-shape-${item.path.replace(/[^A-Za-z0-9]+/g, "-")}`, box = shape.box, defs = [], parts = [];
255
265
  const effects = drawEffects(shape, id, helpers);
256
266
  if (effects.defs) defs.push(effects.defs);
267
+ // Paint order of a preset's paths: every path's fill first, in path order, then every path's line, in path order. A later path's
268
+ // fill never covers an earlier path's line. ECMA-376 (Part 1, 20.1.9.15 path) gives each path its own fill and stroke but no paint
269
+ // order across paths; this is the order PowerPoint 365 draws (qualification deck coverage-shape-presets): chartX, chartStar and
270
+ // chartPlus list their lines first (fill="none") and the square after them (stroke="false"), and PowerPoint and Keynote draw the lines
271
+ // over the square (slide 16); cloudCallout's overlapping bubbles each show their whole outline through the next one's fill (slide 10).
272
+ // Of the 187 presets drawn with their defaults only these four change; in every other one the lines are already the last paths.
273
+ const lines = [];
257
274
  shape.paths.forEach((path, index) => {
258
275
  const fill = fillPaint(shape.fill, path.fill, `${id}-fill-${index}`, box, helpers, shape, path);
259
276
  if (fill.defs) defs.push(fill.defs);
@@ -271,9 +288,10 @@ export function renderShapeBlock(item, helpers) {
271
288
  // A sketched line (core stroke.sketched) is drawn along its sketched outline, as PowerPoint draws it.
272
289
  const stroke = strokeElements(shape.stroke, shape.stroke.sketched?.lines[index] ?? path.d, `${id}-line-${index}`, { box, closed, ends: path.ends, helpers });
273
290
  if (stroke.defs) defs.push(stroke.defs);
274
- parts.push(stroke.elements);
291
+ lines.push(stroke.elements);
275
292
  }
276
293
  });
294
+ parts.push(...lines);
277
295
  const cx = box.x + box.width / 2, cy = box.y + box.height / 2;
278
296
  const turn = shape.rotate ? `rotate(${number(shape.rotate)} ${number(cx)} ${number(cy)})` : "";
279
297
  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)})` : "";
@@ -289,7 +307,7 @@ export function renderShapeBlock(item, helpers) {
289
307
  // A decorative shape is hidden from assistive technology; alt text names the shape; otherwise its text is what is read.
290
308
  const accessible = shape.decorative ? HIDDEN : shape.alt !== undefined ? { role: "img", "aria-label": shape.alt } : {};
291
309
  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;
310
+ const content = shape.link ? helpers.tag("a", linkAnchorAttrs(shape.link), body) : body;
293
311
  return helpers.tag("g", { ...accessible, ...helpers.trace }, content);
294
312
  }
295
313
 
package/dist/svg.d.ts CHANGED
@@ -238,6 +238,8 @@ export interface MeasurePicturesOptions {
238
238
  /** Called with `picture-not-measured` for a picture that could not be read or decoded; its scrim keeps the worst case. */
239
239
  onDiagnostic?: (diagnostic: RenderDiagnostic) => void;
240
240
  }
241
+ /** FR-03: true for an http, https, mailto or tel link, the links a viewer opens outside the deck (never `slide:<id>`, `javascript:` or `data:`). */
242
+ export declare function isOpenableLink(href: unknown): href is string;
241
243
  /**
242
244
  * LH-145: the luminance sampler of a deck's picture backgrounds, each decoded once. Pass the result as `pictureLuminance` to `toSvg` and to the
243
245
  * PPTX export, so the automatic scrim is sized for the picture under the text in both. Never rejects for a picture it cannot read.