@btps/boundview 1.2.0-rc.3 → 1.2.0-rc.3.2

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.
@@ -11,27 +11,53 @@
11
11
  * read from the page's own font files (fonts.ts), images as their pixels, and
12
12
  * an SVG logo as its outlines when they draw exactly as the browser did.
13
13
  */
14
- import opentype from 'opentype.js';
15
- import { zlibSync } from 'fflate';
14
+ import * as opentypeModule from 'opentype.js';
15
+ import { unzlibSync, zlibSync } from 'fflate';
16
16
  import { Resvg } from '@resvg/resvg-wasm';
17
17
  import { BtpBoundViewSchema, checkBoundView, boundValue, writtenValue, } from '@btps/sdk/boundview';
18
18
  import { initBoundViewEngine } from '../render.js';
19
19
  import { boundViewToSvg } from '../svg.js';
20
+ import { signatureSvg } from '../signature.js';
20
21
  import { loadBundledFonts } from '../glyphs.js';
21
22
  import { bindRuns } from './bind.js';
22
- import { fallbackFor, glyphTable } from './fonts.js';
23
+ import { fallbackFor, glyphTable, variationFor } from './fonts.js';
23
24
  import { normalizePath, pathData, shapeOutline } from './svgPath.js';
25
+ import { isWoff2, woff2ToSfnt } from './woff2.js';
26
+ import { backgroundSize, borders, cornersOf, decorationLine, grown, insetShadows, isRound, linearPaint, outerShadows, outline, positionAlong, radialBackground, repeatingLinear, roundedRect, shadowsOf, splitTop, } from './decor.js';
27
+ import { apply, flatten, isIdentity, isUpright, materialize, scaleOf, transformPath, } from './layers.js';
24
28
  /** A BoundView that cannot be sent as it is, and why. */
25
29
  export class BoundViewSnapshotError extends Error {
26
30
  problems;
27
- constructor(message, problems) {
31
+ view;
32
+ constructor(message, problems,
33
+ /** The BoundView a receiver would refuse, when one was made: to see which element and why. */
34
+ view) {
28
35
  super(`${message}: ${problems.join('; ')}`);
29
36
  this.problems = problems;
37
+ this.view = view;
30
38
  this.name = 'BoundViewSnapshotError';
31
39
  }
32
40
  }
41
+ /**
42
+ * opentype.js's `parse`, from whichever build the app's bundler or Node chose: its ES module build names it and has no
43
+ * default export (a strict bundler refuses a default import of it); its UMD build is a default export holding it.
44
+ */
45
+ const parseFont = (buffer) => {
46
+ const named = opentypeModule.parse;
47
+ // Read by reflection: a bundler that sees `.default` on a module without one warns about it.
48
+ const umd = Reflect.get(opentypeModule, 'default');
49
+ return (named ?? umd.parse)(buffer);
50
+ };
51
+ /** The most fonts a BoundView carries (the specification's Limits page; the SDK's BTPS_FIELD_LIMITS.boundView.fonts). */
52
+ const MAX_FONTS = 8;
33
53
  const r2 = (value) => Math.round(value * 100) / 100;
34
54
  const ceil2 = (value) => Math.ceil(value * 100 - 1e-6) / 100;
55
+ const floor2 = (value) => Math.floor(value * 100 + 1e-6) / 100;
56
+ /**
57
+ * A text's box width from its (rounded) left edge to where the browser drew its right edge, rounded down: text that
58
+ * touches what follows it (a value split across elements, a comma) must not reach into it.
59
+ */
60
+ const boxWidth = (x, right) => Math.max(0, floor2(floor2(right) - x));
35
61
  // ---- Colour ----
36
62
  let probe;
37
63
  /** A CSS colour as `#rrggbb` or `#rrggbbaa`, by the browser's own reading of it; undefined when transparent. */
@@ -61,11 +87,16 @@ const toBase64 = (bytes) => {
61
87
  text += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
62
88
  return btoa(text);
63
89
  };
64
- /** An image as the browser shows it, at twice its box where the limits allow: every pixel, compressed losslessly. */
65
- const capturePixels = (draw, box) => {
66
- const scale = Math.min(2, 1024 / box.width, 1024 / box.height, Math.sqrt(262144 / (box.width * box.height)));
67
- const width = Math.max(1, Math.round(box.width * scale));
68
- const height = Math.max(1, Math.round(box.height * scale));
90
+ /**
91
+ * An image as the browser shows it, at twice its box or at its own resolution if that is more (a logo drawn small from a
92
+ * larger file stays sharp when the view is enlarged), where the limits allow: every pixel, compressed losslessly.
93
+ */
94
+ const capturePixels = (draw, box, own) => {
95
+ const wanted = Math.max(2, own ? Math.min(own.width / box.width, own.height / box.height) : 0);
96
+ const scale = Math.min(wanted, 1024 / box.width, 1024 / box.height, Math.sqrt(262144 / (box.width * box.height)));
97
+ // Rounded down, so never past the limits.
98
+ const width = Math.max(1, Math.floor(box.width * scale));
99
+ const height = Math.max(1, Math.floor(box.height * scale));
69
100
  const canvas = document.createElement('canvas');
70
101
  canvas.width = width;
71
102
  canvas.height = height;
@@ -73,7 +104,91 @@ const capturePixels = (draw, box) => {
73
104
  draw(context, width, height);
74
105
  // Throws for an image from another site that does not allow it: the caller says so.
75
106
  const rgba = context.getImageData(0, 0, width, height).data;
76
- return { width, height, encoding: 'rgba8-deflate', data: toBase64(zlibSync(new Uint8Array(rgba.buffer))) };
107
+ return {
108
+ width,
109
+ height,
110
+ encoding: 'rgba8-deflate',
111
+ data: toBase64(zlibSync(new Uint8Array(rgba.buffer))),
112
+ };
113
+ };
114
+ /**
115
+ * Where an <img> draws in its box of `width` by `height` (at `scale` to the page), as its object-fit and object-position
116
+ * place it: a logo kept in proportion in a box of another shape is never stretched to the box.
117
+ */
118
+ const fitted = (natural, css, width, height, scale) => {
119
+ const own = { width: natural.width * scale, height: natural.height * scale };
120
+ if (!own.width || !own.height || css.objectFit === 'fill' || !css.objectFit)
121
+ return [0, 0, width, height];
122
+ const fit = Math.min(width / own.width, height / own.height);
123
+ const ratio = css.objectFit === 'contain'
124
+ ? fit
125
+ : css.objectFit === 'cover'
126
+ ? Math.max(width / own.width, height / own.height)
127
+ : css.objectFit === 'scale-down'
128
+ ? Math.min(1, fit)
129
+ : 1;
130
+ const w = own.width * ratio;
131
+ const h = own.height * ratio;
132
+ // Each of object-position's two values: a percentage of the room left, a length from the edge, or a keyword.
133
+ const at = (value, room) => {
134
+ const keyword = { left: 0, top: 0, center: 50, right: 100, bottom: 100 }[value ?? 'center'];
135
+ if (keyword !== undefined)
136
+ return (room * keyword) / 100;
137
+ if (value?.endsWith('%'))
138
+ return (room * parseFloat(value)) / 100;
139
+ return (parseFloat(value ?? '') || 0) * scale;
140
+ };
141
+ const [x, y] = (css.objectPosition || '50% 50%').split(/\s+/);
142
+ return [at(x, width - w), at(y ?? x, height - h), w, h];
143
+ };
144
+ /**
145
+ * A clip-path's basic shape (circle, ellipse, inset with its rounding, polygon) in a box of `width` by `height` pixels,
146
+ * `scale` of them to a page pixel; undefined for none, or a shape this does not read.
147
+ */
148
+ const clipPathOf = (value, width, height, scale) => {
149
+ const match = /^(circle|ellipse|inset|polygon)\((.*)\)/.exec(value.trim());
150
+ if (!match)
151
+ return undefined;
152
+ const [, shape, args = ''] = match;
153
+ const len = (v, of) => v.endsWith('%') ? (parseFloat(v) / 100) * of : parseFloat(v) * scale;
154
+ const path = new Path2D();
155
+ if (shape === 'polygon') {
156
+ const points = args
157
+ .replace(/^(nonzero|evenodd),/, '')
158
+ .split(',')
159
+ .map((pair) => pair.trim().split(/\s+/));
160
+ points.forEach(([x = '0', y = '0'], i) => i === 0
161
+ ? path.moveTo(len(x, width), len(y, height))
162
+ : path.lineTo(len(x, width), len(y, height)));
163
+ path.closePath();
164
+ return path;
165
+ }
166
+ const [size = '', at = '50% 50%'] = args.split(/\s+at\s+/);
167
+ const [cx = '50%', cy = '50%'] = at.trim().split(/\s+/);
168
+ if (shape === 'circle') {
169
+ const r = size.endsWith('%')
170
+ ? ((parseFloat(size) / 100) * Math.hypot(width, height)) / Math.SQRT2
171
+ : size && size !== 'closest-side'
172
+ ? len(size, width)
173
+ : Math.min(width, height) / 2;
174
+ path.arc(len(cx, width), len(cy, height), r, 0, Math.PI * 2);
175
+ return path;
176
+ }
177
+ if (shape === 'ellipse') {
178
+ const [rx = '50%', ry = rx] = size.trim().split(/\s+/).filter(Boolean);
179
+ path.ellipse(len(cx, width), len(cy, height), len(rx, width), len(ry, height), 0, 0, Math.PI * 2);
180
+ return path;
181
+ }
182
+ // inset(t r b l round radius)
183
+ const [edges = '', round] = args.split(/\s+round\s+/);
184
+ const [t = '0', r = t, b = t, l = r] = edges.trim().split(/\s+/);
185
+ const x = len(l, width);
186
+ const y = len(t, height);
187
+ const w = width - x - len(r, width);
188
+ const h = height - y - len(b, height);
189
+ const radius = round ? len(round.trim().split(/\s+/)[0], width) : 0;
190
+ path.roundRect(x, y, w, h, radius);
191
+ return path;
77
192
  };
78
193
  const loaded = (src) => new Promise((resolve, reject) => {
79
194
  const image = new Image();
@@ -93,7 +208,9 @@ const svgPaths = (svg, origin, offset = [0, 0]) => {
93
208
  if (node.closest('defs, clipPath, mask, symbol, pattern') && tag !== 'defs')
94
209
  continue;
95
210
  if (IGNORED.has(tag)) {
96
- if (node.getAttribute('filter') || node.getAttribute('mask') || node.getAttribute('clip-path'))
211
+ if (node.getAttribute('filter') ||
212
+ node.getAttribute('mask') ||
213
+ node.getAttribute('clip-path'))
97
214
  return undefined;
98
215
  continue;
99
216
  }
@@ -103,7 +220,10 @@ const svgPaths = (svg, origin, offset = [0, 0]) => {
103
220
  const style = getComputedStyle(shape);
104
221
  if (style.display === 'none' || style.visibility === 'hidden')
105
222
  continue;
106
- if (style.filter !== 'none' || style.mask !== 'none' || style.clipPath !== 'none' || style.strokeDasharray !== 'none') {
223
+ if (style.filter !== 'none' ||
224
+ style.mask !== 'none' ||
225
+ style.clipPath !== 'none' ||
226
+ style.strokeDasharray !== 'none') {
107
227
  return undefined;
108
228
  }
109
229
  const number = (name) => {
@@ -114,7 +234,10 @@ const svgPaths = (svg, origin, offset = [0, 0]) => {
114
234
  if (tag === 'path')
115
235
  d = shape.getAttribute('d') ?? undefined;
116
236
  else if (tag === 'polyline' || tag === 'polygon') {
117
- const points = (shape.getAttribute('points') ?? '').trim().split(/[\s,]+/).map(Number);
237
+ const points = (shape.getAttribute('points') ?? '')
238
+ .trim()
239
+ .split(/[\s,]+/)
240
+ .map(Number);
118
241
  d = points.reduce((path, value, i) => path + (i % 2 === 0 ? `${i === 0 ? 'M' : 'L'}${value}` : ` ${value}`), '');
119
242
  if (tag === 'polygon')
120
243
  d += 'Z';
@@ -125,9 +248,17 @@ const svgPaths = (svg, origin, offset = [0, 0]) => {
125
248
  const ctm = shape.getScreenCTM();
126
249
  if (!commands || !ctm)
127
250
  return undefined;
128
- const matrix = [ctm.a, ctm.b, ctm.c, ctm.d, ctm.e - origin.left - offset[0], ctm.f - origin.top - offset[1]];
251
+ const matrix = [
252
+ ctm.a,
253
+ ctm.b,
254
+ ctm.c,
255
+ ctm.d,
256
+ ctm.e - origin.left - offset[0],
257
+ ctm.f - origin.top - offset[1],
258
+ ];
259
+ // The opacity inside the SVG; its box's own (and its page ancestors') is applied to every drawn element alike.
129
260
  let opacity = 1;
130
- for (let at = shape; at && at !== svg.parentElement; at = at.parentElement) {
261
+ for (let at = shape; at && at !== svg; at = at.parentElement) {
131
262
  opacity *= Number(getComputedStyle(at).opacity);
132
263
  }
133
264
  const paint = (css, alpha) => {
@@ -161,7 +292,8 @@ const svgPaths = (svg, origin, offset = [0, 0]) => {
161
292
  return out;
162
293
  };
163
294
  /** The browser's own picture of an SVG in its box, at `scale`, over white. */
164
- const browserPixels = async (svg, box, scale) => {
295
+ /** `white`: over white, to compare with the engine's picture; else as it is, its transparency kept, to travel as an image. */
296
+ const browserPixels = async (svg, box, scale, floor = false, white = true) => {
165
297
  const copy = svg.cloneNode(true);
166
298
  copy.setAttribute('width', String(box.width));
167
299
  copy.setAttribute('height', String(box.height));
@@ -169,11 +301,14 @@ const browserPixels = async (svg, box, scale) => {
169
301
  try {
170
302
  const image = await loaded(url);
171
303
  const canvas = document.createElement('canvas');
172
- canvas.width = Math.round(box.width * scale);
173
- canvas.height = Math.round(box.height * scale);
304
+ const round = floor ? Math.floor : Math.round;
305
+ canvas.width = Math.max(1, round(box.width * scale));
306
+ canvas.height = Math.max(1, round(box.height * scale));
174
307
  const context = canvas.getContext('2d');
175
- context.fillStyle = '#ffffff';
176
- context.fillRect(0, 0, canvas.width, canvas.height);
308
+ if (white) {
309
+ context.fillStyle = '#ffffff';
310
+ context.fillRect(0, 0, canvas.width, canvas.height);
311
+ }
177
312
  context.drawImage(image, 0, 0, canvas.width, canvas.height);
178
313
  return context.getImageData(0, 0, canvas.width, canvas.height).data;
179
314
  }
@@ -188,9 +323,20 @@ const browserPixels = async (svg, box, scale) => {
188
323
  * (an effect the outlines could not carry) and the logo travels as pixels.
189
324
  */
190
325
  const drawsAlike = async (svg, box, paths) => {
191
- const view = { format: 1, page: { width: box.width, height: box.height }, elements: paths };
192
- const engine = new Resvg(boundViewToSvg({}, view), { fitTo: { mode: 'zoom', value: 2 }, font: { loadSystemFonts: false } });
193
- const ours = engine.render().pixels;
326
+ const view = {
327
+ format: 1,
328
+ page: { width: box.width, height: box.height },
329
+ elements: paths,
330
+ };
331
+ const engine = new Resvg(boundViewToSvg({}, view), {
332
+ fitTo: { mode: 'zoom', value: 2 },
333
+ font: { loadSystemFonts: false },
334
+ });
335
+ // The engine's memory freed by hand, as the renderer frees it.
336
+ const rendered = engine.render();
337
+ const ours = rendered.pixels.slice();
338
+ rendered.free();
339
+ engine.free();
194
340
  const theirs = await browserPixels(svg, box, 2);
195
341
  if (ours.length !== theirs.length)
196
342
  return false;
@@ -209,14 +355,48 @@ const drawsAlike = async (svg, box, paths) => {
209
355
  const pixels = ours.length / 4;
210
356
  return total / (pixels * 3) <= 3 && far / pixels <= 0.01;
211
357
  };
212
- // ---- Fonts ----
213
358
  const fontFiles = new Map();
214
- /** The font file the page uses for a family, weight and style, from its own @font-face rules. */
359
+ /** A `unicode-range` as code point ranges. */
360
+ const unicodeRanges = (css) => {
361
+ const ranges = css
362
+ .split(',')
363
+ .map((part) => part.trim().replace(/^U\+/i, ''))
364
+ .filter(Boolean)
365
+ .map((part) => {
366
+ if (part.includes('?'))
367
+ return [parseInt(part.replace(/\?/g, '0'), 16), parseInt(part.replace(/\?/g, 'F'), 16)];
368
+ const [from, to = from] = part.split('-');
369
+ return [parseInt(from, 16), parseInt(to, 16)];
370
+ });
371
+ return ranges.length > 0 &&
372
+ ranges.every(([from, to]) => Number.isFinite(from) && Number.isFinite(to))
373
+ ? ranges
374
+ : undefined;
375
+ };
376
+ /** Reads a font file: a woff or ttf as it is, a woff2 decompressed first (woff2.ts, with Brotli loaded only then). */
377
+ const readFont = async (url) => {
378
+ try {
379
+ let bytes = await (await fetch(url)).arrayBuffer();
380
+ if (isWoff2(bytes)) {
381
+ const { decompress } = await import('brotli/decompress');
382
+ bytes = woff2ToSfnt(bytes, decompress);
383
+ }
384
+ return parseFont(bytes);
385
+ }
386
+ catch {
387
+ return undefined;
388
+ }
389
+ };
390
+ /**
391
+ * The font files the page uses for a family, weight and style, from its own @font-face rules: the nearest weight, and
392
+ * every file of it a `unicode-range` splits it into (latin, latin-ext, cyrillic…). The browser drew each character
393
+ * with the file whose range holds it, and so do we.
394
+ */
215
395
  const fontFile = (family, weight, style) => {
216
396
  const key = `${family}|${weight}|${style}`;
217
397
  if (!fontFiles.has(key)) {
218
398
  fontFiles.set(key, (async () => {
219
- let best;
399
+ const candidates = [];
220
400
  for (const sheet of document.styleSheets) {
221
401
  let rules;
222
402
  try {
@@ -233,64 +413,153 @@ const fontFile = (family, weight, style) => {
233
413
  continue;
234
414
  if ((rule.style.getPropertyValue('font-style').trim() || 'normal') !== style)
235
415
  continue;
236
- const weights = (rule.style.getPropertyValue('font-weight').trim() || '400').split(/\s+/).map(Number);
237
- const distance = weights.length === 2 && weight >= (weights[0] ?? 0) && weight <= (weights[1] ?? 0) ? 0 : Math.abs((weights[0] ?? 400) - weight);
238
- // A woff or ttf source: opentype.js reads those, not woff2.
239
- const sources = [...rule.style.getPropertyValue('src').matchAll(/url\(["']?([^"')]+)["']?\)/g)].map((m) => m[1]);
240
- const readable = sources.find((src) => !/\.woff2(\?|#|$)/i.test(src));
241
- if (readable && (!best || distance < best.distance)) {
242
- best = { url: new URL(readable, sheet.href ?? location.href).href, distance };
243
- }
416
+ const weights = (rule.style.getPropertyValue('font-weight').trim() || '400')
417
+ .split(/\s+/)
418
+ .map((value) => (value === 'bold' ? 700 : value === 'normal' ? 400 : Number(value)));
419
+ const distance = weights.length === 2 && weight >= (weights[0] ?? 0) && weight <= (weights[1] ?? 0)
420
+ ? 0
421
+ : Math.abs((weights[0] ?? 400) - weight);
422
+ // A woff or ttf where the rule offers one (read as it is), else its woff2.
423
+ const sources = [
424
+ ...rule.style.getPropertyValue('src').matchAll(/url\(["']?([^"')]+)["']?\)/g),
425
+ ].map((m) => m[1]);
426
+ const source = sources.find((src) => !/\.woff2(\?|#|$)/i.test(src)) ?? sources[0];
427
+ if (!source)
428
+ continue;
429
+ const ranges = unicodeRanges(rule.style.getPropertyValue('unicode-range'));
430
+ candidates.push({
431
+ url: new URL(source, sheet.href ?? location.href).href,
432
+ distance,
433
+ ...(ranges && { ranges }),
434
+ });
244
435
  }
245
436
  }
246
- if (!best)
247
- return undefined;
248
- try {
249
- return opentype.parse(await (await fetch(best.url)).arrayBuffer());
250
- }
251
- catch {
437
+ if (candidates.length === 0)
252
438
  return undefined;
253
- }
439
+ const nearest = Math.min(...candidates.map(({ distance }) => distance));
440
+ const read = await Promise.all(candidates
441
+ .filter(({ distance }) => distance === nearest)
442
+ .map(async ({ url, ranges }) => {
443
+ const font = await readFont(url);
444
+ return font ? { font, ...(ranges && { ranges }) } : undefined;
445
+ }));
446
+ const files = read.filter((file) => file !== undefined);
447
+ return files.length > 0 ? files : undefined;
254
448
  })());
255
449
  }
256
450
  return fontFiles.get(key);
257
451
  };
258
- const styleOf = (element) => {
452
+ /**
453
+ * Which of a family's files draws `char`, as the browser chooses (CSS Fonts, unicode-range): of the files whose range
454
+ * holds it, the last defined first, and the next where one has no glyph for it.
455
+ */
456
+ const fileFor = (files, char) => {
457
+ const code = char.codePointAt(0) ?? 0;
458
+ const holding = files
459
+ .filter(({ ranges }) => ranges === undefined || ranges.some(([from, to]) => code >= from && code <= to))
460
+ .reverse();
461
+ return holding.find(({ font }) => font.charToGlyph(char).index !== 0) ?? holding[0];
462
+ };
463
+ /** The text decorations a text is drawn with: its element's, and its ancestors' down to it (not into an inline block). */
464
+ const decorationsOf = (element, root) => {
465
+ const out = [];
466
+ for (let at = element; at; at = at.parentElement) {
467
+ const css = getComputedStyle(at);
468
+ for (const line of css.textDecorationLine.split(/\s+/)) {
469
+ if (line !== 'underline' && line !== 'overline' && line !== 'line-through')
470
+ continue;
471
+ const thickness = css.textDecorationThickness;
472
+ out.push({
473
+ line,
474
+ style: css.textDecorationStyle,
475
+ colour: solid(hex(css.textDecorationColor) ?? hex(css.color) ?? '#000000'),
476
+ ...(thickness.endsWith('px') && { thickness: parseFloat(thickness) }),
477
+ offset: css.textUnderlineOffset.endsWith('px') ? parseFloat(css.textUnderlineOffset) : 0,
478
+ });
479
+ }
480
+ // A decoration is not carried into an inline block, or out of one positioned or floated.
481
+ if (at === root ||
482
+ /^inline-/.test(css.display) ||
483
+ css.position === 'absolute' ||
484
+ css.position === 'fixed' ||
485
+ css.float !== 'none')
486
+ break;
487
+ }
488
+ return out;
489
+ };
490
+ const styleOf = (element, root) => {
259
491
  const css = getComputedStyle(element);
492
+ const ink = hex(css.color) ?? '#000000';
493
+ const alpha = ink.length === 9 ? parseInt(ink.slice(7), 16) / 255 : 1;
494
+ const decorations = root ? decorationsOf(element, root) : [];
495
+ const shadows = shadowsOf(css.textShadow, hex).map(({ x, y, blur, colour, alpha: a }) => ({
496
+ x,
497
+ y,
498
+ blur,
499
+ colour,
500
+ alpha: a,
501
+ }));
260
502
  return {
261
503
  family: (css.fontFamily.split(',')[0] ?? '').replace(/["']/g, '').trim(),
262
504
  weight: Number(css.fontWeight) || 400,
263
505
  style: css.fontStyle === 'italic' || css.fontStyle === 'oblique' ? 'italic' : 'normal',
264
506
  size: parseFloat(css.fontSize),
265
- colour: solid(hex(css.color) ?? '#000000'),
507
+ colour: solid(ink),
266
508
  spacing: css.letterSpacing === 'normal' ? 0 : parseFloat(css.letterSpacing) || 0,
267
- ...(css.textTransform === 'uppercase' || css.textTransform === 'lowercase' ? { transform: css.textTransform } : {}),
509
+ ...(css.textTransform === 'uppercase' || css.textTransform === 'lowercase'
510
+ ? { transform: css.textTransform }
511
+ : {}),
268
512
  tabular: css.fontVariantNumeric.includes('tabular'),
513
+ ...(alpha < 1 && { alpha }),
514
+ ...(/small-caps/.test(css.fontVariantCaps) && { smallCaps: true }),
515
+ ...(decorations.length > 0 && { decorations }),
516
+ ...(shadows.length > 0 && { shadows }),
269
517
  };
270
518
  };
271
519
  /** Each text node as runs, one a line it was laid out on, with each character's box and the line's baseline. */
272
- const textRuns = (root, origin) => {
520
+ export const textRuns = (root, origin) => {
273
521
  const runs = [];
274
522
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
275
523
  const range = document.createRange();
276
524
  const measure = document.createElement('canvas').getContext('2d');
525
+ // The block each text flows in: its nearest ancestor that is not inline.
526
+ const blocks = new Map();
527
+ const blockOf = (element) => {
528
+ let at = element;
529
+ while (at !== root &&
530
+ at.parentElement &&
531
+ ['inline', 'contents'].includes(getComputedStyle(at).display))
532
+ at = at.parentElement;
533
+ if (!blocks.has(at))
534
+ blocks.set(at, blocks.size);
535
+ return blocks.get(at);
536
+ };
537
+ let index = 0;
277
538
  for (let node = walker.nextNode(); node; node = walker.nextNode()) {
278
539
  const parent = node.parentElement;
279
540
  if (!parent || parent.closest('svg') || !node.textContent?.trim())
280
541
  continue;
542
+ // Text the page does not draw: hidden, or in an element not laid out (display: none, a closed details).
281
543
  if (getComputedStyle(parent).visibility === 'hidden')
282
544
  continue;
545
+ if (typeof parent.checkVisibility === 'function' && !parent.checkVisibility())
546
+ continue;
283
547
  const css = getComputedStyle(parent);
284
548
  measure.font = `${css.fontStyle} ${css.fontWeight} ${css.fontSize} ${css.fontFamily}`;
285
549
  const ascent = measure.measureText('Hg').fontBoundingBoxAscent;
286
- const style = styleOf(parent);
550
+ const style = styleOf(parent, root);
551
+ const nodeIndex = index++;
552
+ const block = blockOf(parent);
287
553
  let line;
554
+ let lastRight = -Infinity;
288
555
  let offset = 0;
289
556
  for (const char of node.textContent) {
290
557
  range.setStart(node, offset);
291
558
  range.setEnd(node, offset + char.length);
292
559
  offset += char.length;
293
560
  const rect = range.getBoundingClientRect();
561
+ if (rect.width === 0 && rect.height === 0 && !/\s/.test(char))
562
+ continue;
294
563
  if (rect.width === 0 && /\s/.test(char)) {
295
564
  if (line) {
296
565
  line.text += ' ';
@@ -298,97 +567,504 @@ const textRuns = (root, origin) => {
298
567
  }
299
568
  continue;
300
569
  }
301
- if (!line || Math.abs(rect.top - origin.top - line.top) > 2) {
302
- line = { text: '', chars: [], baseline: r2(rect.top - origin.top + ascent), top: rect.top - origin.top, style };
570
+ // A new line where the text goes back to the left lower down; a character from another font file (another
571
+ // script) may sit a little higher or lower on the same line.
572
+ const top = rect.top - origin.top;
573
+ const newLine = !line ||
574
+ (Math.abs(top - line.top) > 2 &&
575
+ (rect.left - origin.left < lastRight - 1 || top >= (line.bottom ?? line.top) - 2));
576
+ if (newLine) {
577
+ line = {
578
+ text: '',
579
+ chars: [],
580
+ baseline: r2(top + ascent),
581
+ top,
582
+ bottom: rect.bottom - origin.top,
583
+ node: nodeIndex,
584
+ block,
585
+ size: style.size,
586
+ style,
587
+ element: parent,
588
+ };
303
589
  runs.push(line);
304
590
  }
305
- line.text += /\s/.test(char) ? ' ' : char;
306
- line.chars.push({ left: rect.left - origin.left, right: rect.right - origin.left });
591
+ const current = line;
592
+ current.bottom = Math.max(current.bottom ?? 0, rect.bottom - origin.top);
593
+ current.text += /\s/.test(char) ? ' ' : char;
594
+ current.chars.push({ left: rect.left - origin.left, right: rect.right - origin.left });
595
+ lastRight = rect.right - origin.left;
307
596
  }
308
597
  }
309
598
  return runs;
310
599
  };
311
- /** A CSS linear gradient as a BoundView paint across a box, or undefined when it is not one this reads. */
312
- const linearGradient = (css, box) => {
313
- const match = /^linear-gradient\((.*)\)$/.exec(css.trim());
314
- if (!match)
315
- return undefined;
316
- const parts = match[1].split(/,(?![^(]*\))/).map((part) => part.trim());
317
- let angle = 180;
318
- const first = parts[0] ?? '';
319
- if (/deg$/.test(first)) {
320
- angle = parseFloat(first);
321
- parts.shift();
600
+ // ---- List markers: drawn by the browser, not in the page's text ----
601
+ const ROMAN = [
602
+ [1000, 'm'],
603
+ [900, 'cm'],
604
+ [500, 'd'],
605
+ [400, 'cd'],
606
+ [100, 'c'],
607
+ [90, 'xc'],
608
+ [50, 'l'],
609
+ [40, 'xl'],
610
+ [10, 'x'],
611
+ [9, 'ix'],
612
+ [5, 'v'],
613
+ [4, 'iv'],
614
+ [1, 'i'],
615
+ ];
616
+ const roman = (n) => ROMAN.reduce((out, [value, letters]) => {
617
+ let text = out;
618
+ while (n >= value) {
619
+ text += letters;
620
+ n -= value;
322
621
  }
323
- else if (first.startsWith('to ')) {
324
- const sides = { 'to top': 0, 'to right': 90, 'to bottom': 180, 'to left': 270 };
325
- if (sides[first] === undefined)
326
- return undefined;
327
- angle = sides[first];
328
- parts.shift();
622
+ return text;
623
+ }, '');
624
+ const alpha = (n) => n <= 0 ? '' : alpha(Math.floor((n - 1) / 26)) + String.fromCharCode(97 + ((n - 1) % 26));
625
+ /** A counter as a list-style-type writes it, or undefined for a type this does not write (then nothing is drawn). */
626
+ const counterText = (type, n) => {
627
+ if (type === 'decimal')
628
+ return String(n);
629
+ if (type === 'decimal-leading-zero')
630
+ return String(n).padStart(2, '0');
631
+ if (type === 'lower-alpha' || type === 'lower-latin')
632
+ return alpha(n);
633
+ if (type === 'upper-alpha' || type === 'upper-latin')
634
+ return alpha(n).toUpperCase();
635
+ if (type === 'lower-roman')
636
+ return roman(n);
637
+ if (type === 'upper-roman')
638
+ return roman(n).toUpperCase();
639
+ return undefined;
640
+ };
641
+ /** The item's number in its list: its value, or counted from the list's start (down, in a reversed list). */
642
+ const ordinal = (item) => {
643
+ if (item.hasAttribute('value'))
644
+ return item.value;
645
+ const list = item.parentElement;
646
+ const items = list
647
+ ? [...list.children].filter((child) => getComputedStyle(child).display === 'list-item')
648
+ : [item];
649
+ const position = items.indexOf(item);
650
+ if (list instanceof HTMLOListElement) {
651
+ const reversed = list.reversed;
652
+ const start = list.hasAttribute('start') ? list.start : reversed ? items.length : 1;
653
+ return reversed ? start - position : start + position;
329
654
  }
330
- const stops = [];
331
- parts.forEach((part, i) => {
332
- const position = /\s([\d.]+)%$/.exec(part);
333
- const colour = hex(position ? part.slice(0, position.index) : part);
334
- if (colour)
335
- stops.push([position ? Number(position[1]) / 100 : i / Math.max(1, parts.length - 1), colour]);
336
- });
337
- if (stops.length < 2 || stops.length > 8)
338
- return undefined;
339
- const radians = (angle * Math.PI) / 180;
340
- const half = (Math.abs(box.width * Math.sin(radians)) + Math.abs(box.height * Math.cos(radians))) / 2;
341
- const cx = box.left + box.width / 2;
342
- const cy = box.top + box.height / 2;
343
- const dx = Math.sin(radians) * half;
344
- const dy = -Math.cos(radians) * half;
655
+ return position + 1;
656
+ };
657
+ /**
658
+ * Each list item's marker, where the browser draws it: a number or letter as text, ending at the item's content edge
659
+ * (outside) or starting it (inside), in the marker's own font with tabular figures; a disc, circle or square as the shape
660
+ * Chrome paints, sized and placed from the font's ascent (its list marker code, measured against it).
661
+ */
662
+ const listMarkers = (root, origin) => {
663
+ const runs = [];
664
+ const shapes = [];
665
+ const measure = document.createElement('canvas').getContext('2d');
666
+ for (const item of root.querySelectorAll('li, [style*="list-item"]')) {
667
+ const css = getComputedStyle(item);
668
+ if (css.display !== 'list-item' ||
669
+ css.listStyleType === 'none' ||
670
+ css.visibility === 'hidden' ||
671
+ css.listStyleImage !== 'none')
672
+ continue;
673
+ // The first line's baseline, as the item's text is laid out.
674
+ const walker = document.createTreeWalker(item, NodeFilter.SHOW_TEXT);
675
+ let first;
676
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
677
+ if (node.textContent?.trim()) {
678
+ first = node;
679
+ break;
680
+ }
681
+ }
682
+ if (!first?.parentElement)
683
+ continue;
684
+ const at = first.textContent?.search(/\S/) ?? 0;
685
+ const range = document.createRange();
686
+ range.setStart(first, at);
687
+ range.setEnd(first, at + 1);
688
+ const line = range.getBoundingClientRect();
689
+ const textCss = getComputedStyle(first.parentElement);
690
+ measure.font = `${textCss.fontStyle} ${textCss.fontWeight} ${textCss.fontSize} ${textCss.fontFamily}`;
691
+ const baseline = r2(line.top - origin.top + measure.measureText('Hg').fontBoundingBoxAscent);
692
+ const box = item.getBoundingClientRect();
693
+ const contentLeft = box.left - origin.left + parseFloat(css.borderLeftWidth) + parseFloat(css.paddingLeft);
694
+ const inside = css.listStylePosition === 'inside';
695
+ const marker = getComputedStyle(item, '::marker');
696
+ measure.font = `${marker.fontStyle} ${marker.fontWeight} ${marker.fontSize} ${marker.fontFamily}`;
697
+ const colour = solid(hex(marker.color) ?? hex(css.color) ?? '#000000');
698
+ const type = css.listStyleType;
699
+ if (type === 'disc' || type === 'circle' || type === 'square') {
700
+ const ascent = Math.round(measure.measureText('Hg').fontBoundingBoxAscent);
701
+ const offset = Math.floor((ascent * 2) / 3);
702
+ const size = Math.floor((offset + 1) / 2);
703
+ const x = r2((inside ? contentLeft : contentLeft - offset - 8) + 1);
704
+ const y = r2(baseline - ascent + Math.floor((3 * (ascent - offset)) / 2));
705
+ shapes.push({
706
+ element: type === 'circle'
707
+ ? {
708
+ type: 'rect',
709
+ x: r2(x + 0.5),
710
+ y: r2(y + 0.5),
711
+ width: size - 1,
712
+ height: size - 1,
713
+ radius: r2((size - 1) / 2),
714
+ stroke: colour,
715
+ strokeWidth: 1,
716
+ }
717
+ : {
718
+ type: 'rect',
719
+ x,
720
+ y,
721
+ width: size,
722
+ height: size,
723
+ ...(type === 'disc' && { radius: r2(size / 2) }),
724
+ fill: colour,
725
+ },
726
+ source: item,
727
+ });
728
+ continue;
729
+ }
730
+ // A string marker (list-style-type: "→ ") as written; a counter as its type writes it, then ". ".
731
+ const quoted = /^"(.*)"$/.exec(type)?.[1];
732
+ const counter = quoted === undefined ? counterText(type, ordinal(item)) : undefined;
733
+ const text = quoted ?? (counter === undefined ? undefined : `${counter}. `);
734
+ if (!text)
735
+ continue;
736
+ const style = {
737
+ family: (marker.fontFamily.split(',')[0] ?? '').replace(/["']/g, '').trim(),
738
+ weight: Number(marker.fontWeight) || 400,
739
+ style: marker.fontStyle === 'italic' || marker.fontStyle === 'oblique' ? 'italic' : 'normal',
740
+ size: parseFloat(marker.fontSize),
741
+ colour,
742
+ spacing: 0,
743
+ tabular: marker.fontVariantNumeric.includes('tabular'),
744
+ };
745
+ const width = measure.measureText(text).width;
746
+ let left = inside ? contentLeft : contentLeft - width;
747
+ const chars = [...text].map((char) => {
748
+ const right = left + measure.measureText(char).width;
749
+ const box = { left, right };
750
+ left = right;
751
+ return box;
752
+ });
753
+ runs.push({
754
+ text,
755
+ chars,
756
+ baseline,
757
+ top: line.top - origin.top,
758
+ bottom: line.bottom - origin.top,
759
+ node: -1,
760
+ block: -1,
761
+ size: style.size,
762
+ style,
763
+ element: item,
764
+ });
765
+ }
766
+ return { runs, shapes };
767
+ };
768
+ /** `over` with `ink` laid on it at `alpha`: two #rrggbb colours mixed. */
769
+ const mixed = (over, ink, alpha) => {
770
+ const channel = (c, i) => parseInt(c.slice(1 + i * 2, 3 + i * 2), 16);
771
+ return `#${[0, 1, 2]
772
+ .map((i) => Math.round(channel(ink, i) * alpha + channel(over, i) * (1 - alpha))
773
+ .toString(16)
774
+ .padStart(2, '0'))
775
+ .join('')}`;
776
+ };
777
+ const paintThrough = (paint, m) => {
778
+ if (typeof paint !== 'object' || paint === null)
779
+ return paint;
780
+ const p = paint;
781
+ const at = ([x, y]) => apply(m, x, y).map(r2);
782
+ if ('linear' in p)
783
+ return { linear: { ...p.linear, from: at(p.linear.from), to: at(p.linear.to) } };
345
784
  return {
346
- linear: {
347
- from: [r2(cx - dx), r2(cy - dy)],
348
- to: [r2(cx + dx), r2(cy + dy)],
349
- stops: stops.map(([offset, colour]) => [r2(Math.min(1, Math.max(0, offset))), colour]),
350
- },
785
+ radial: { ...p.radial, centre: at(p.radial.centre), radius: r2(p.radial.radius * scaleOf(m)) },
351
786
  };
352
787
  };
788
+ /**
789
+ * A drawn element through its page element's transform, as the browser draws it: a box or path as its outline moved,
790
+ * an image drawn turned into the box it now takes, a label as its glyphs' outlines, a fact moved and scaled (a fact is
791
+ * drawn upright: one turned or slanted is a problem, said).
792
+ */
793
+ const throughMatrix = (element, m, { images, fonts, problems, }) => {
794
+ const fills = (e) => ({
795
+ ...(e.fill !== undefined && { fill: paintThrough(e.fill, m) }),
796
+ ...(e.stroke !== undefined && {
797
+ stroke: paintThrough(e.stroke, m),
798
+ strokeWidth: r2((e.strokeWidth ?? 0) * scaleOf(m)),
799
+ }),
800
+ ...(e.opacity !== undefined && { opacity: e.opacity }),
801
+ });
802
+ switch (element.type) {
803
+ case 'rect': {
804
+ const radius = element.radius ?? 0;
805
+ const radii = Array.isArray(radius) ? radius : [radius, radius, radius, radius];
806
+ const d = transformPath(roundedRect(element, radii.map((r) => [r, r])), m);
807
+ return d ? [{ type: 'path', d, ...fills(element) }] : [];
808
+ }
809
+ case 'path': {
810
+ const d = transformPath(element.d, m);
811
+ return d
812
+ ? [
813
+ {
814
+ type: 'path',
815
+ d,
816
+ ...(element.fillRule && { fillRule: element.fillRule }),
817
+ ...fills(element),
818
+ },
819
+ ]
820
+ : [];
821
+ }
822
+ case 'line': {
823
+ const from = apply(m, element.from[0], element.from[1]).map(r2);
824
+ const to = apply(m, element.to[0], element.to[1]).map(r2);
825
+ return [
826
+ {
827
+ ...element,
828
+ from,
829
+ to,
830
+ strokeWidth: r2(element.strokeWidth * scaleOf(m)),
831
+ ...(element.stroke && { stroke: paintThrough(element.stroke, m) }),
832
+ },
833
+ ];
834
+ }
835
+ case 'image': {
836
+ const data = images[element.image];
837
+ if (!data)
838
+ return [element];
839
+ const rgba = unzlibSync(Uint8Array.from(atob(data.data), (c) => c.charCodeAt(0)));
840
+ const source = document.createElement('canvas');
841
+ source.width = data.width;
842
+ source.height = data.height;
843
+ source.getContext('2d').putImageData(new ImageData(new Uint8ClampedArray(rgba.buffer, rgba.byteOffset, rgba.length), data.width, data.height), 0, 0);
844
+ const points = [
845
+ [element.x, element.y],
846
+ [element.x + element.width, element.y],
847
+ [element.x + element.width, element.y + element.height],
848
+ [element.x, element.y + element.height],
849
+ ].map(([x, y]) => apply(m, x, y));
850
+ const xs = points.map(([x]) => x);
851
+ const ys = points.map(([, y]) => y);
852
+ const box = {
853
+ left: r2(Math.min(...xs)),
854
+ top: r2(Math.min(...ys)),
855
+ width: r2(Math.max(...xs) - Math.min(...xs)),
856
+ height: r2(Math.max(...ys) - Math.min(...ys)),
857
+ };
858
+ const radius = element.radius ?? 0;
859
+ const radii = Array.isArray(radius) ? radius : [radius, radius, radius, radius];
860
+ images[element.image] = capturePixels((context, width) => {
861
+ const s = width / box.width;
862
+ context.setTransform(s, 0, 0, s, -box.left * s, -box.top * s);
863
+ context.transform(m.a, m.b, m.c, m.d, m.e, m.f);
864
+ if (radii.some((r) => r > 0))
865
+ context.clip(new Path2D(roundedRect(element, radii.map((r) => [r, r]))));
866
+ context.drawImage(source, element.x, element.y, element.width, element.height);
867
+ }, box, {
868
+ width: (data.width * box.width) / element.width,
869
+ height: (data.height * box.height) / element.height,
870
+ });
871
+ return [
872
+ {
873
+ type: 'image',
874
+ image: element.image,
875
+ x: box.left,
876
+ y: box.top,
877
+ width: box.width,
878
+ height: box.height,
879
+ ...(element.opacity !== undefined && { opacity: element.opacity }),
880
+ },
881
+ ];
882
+ }
883
+ case 'label': {
884
+ // Its glyphs' outlines, placed as the label places them, through the matrix.
885
+ const font = fonts[element.font];
886
+ if (!font)
887
+ return [];
888
+ const scale = element.size / font.unitsPerEm;
889
+ const chars = [...transformed(element.text, element.transform)];
890
+ let x = element.x;
891
+ let d = '';
892
+ const out = [];
893
+ chars.forEach((char, i) => {
894
+ const glyph = font.glyphs?.[char];
895
+ if (glyph?.path) {
896
+ const piece = transformPath(glyph.path, m.multiply(new DOMMatrix([scale, 0, 0, scale, x, element.y])));
897
+ if (piece) {
898
+ if (d.length + piece.length > 19000) {
899
+ out.push({ type: 'path', d, fill: element.colour });
900
+ d = '';
901
+ }
902
+ d += piece;
903
+ }
904
+ }
905
+ x +=
906
+ ((glyph?.advance ?? 0) + (font.kerning?.[`${char}${chars[i + 1] ?? ''}`] ?? 0)) * scale +
907
+ (element.letterSpacing ?? 0);
908
+ });
909
+ if (d)
910
+ out.push({ type: 'path', d, fill: element.colour });
911
+ return out;
912
+ }
913
+ case 'text':
914
+ case 'signature': {
915
+ if (!isUpright(m)) {
916
+ problems.push(`${element.type === 'text' ? element.bind.field : 'the signature'} is turned or slanted by a CSS transform; a BoundView draws it upright`);
917
+ return [element];
918
+ }
919
+ const [x, y] = apply(m, element.x, element.y);
920
+ if (element.type === 'signature')
921
+ return [
922
+ {
923
+ ...element,
924
+ x: r2(x),
925
+ y: r2(y),
926
+ width: r2(element.width * m.a),
927
+ height: r2(element.height * m.a),
928
+ },
929
+ ];
930
+ return [
931
+ {
932
+ ...element,
933
+ x: r2(x),
934
+ y: r2(y),
935
+ width: r2(element.width * m.a),
936
+ size: r2(element.size * m.a),
937
+ ...(element.letterSpacing !== undefined && {
938
+ letterSpacing: r2(element.letterSpacing * m.a),
939
+ }),
940
+ },
941
+ ];
942
+ }
943
+ default:
944
+ return [element];
945
+ }
946
+ };
947
+ /** A drawn signature's shapes as their geometry, in order: what a page shows of it, and what signatureSvg draws. */
948
+ const geometryOf = (root) => [...root.querySelectorAll('circle, path')].map((shape) => [
949
+ shape.tagName.toLowerCase(),
950
+ ...['d', 'cx', 'cy', 'r', 'stroke-width'].map((name) => shape.getAttribute(name) ?? ''),
951
+ ].join('|'));
952
+ /**
953
+ * Whether an SVG is the signed signature: the one signatureSvg draws for its strokes, on the 1,000 by 300 canvas, shape
954
+ * for shape. A platform shows that; the engine draws it by the same rule, so the two cannot differ whatever the strokes.
955
+ */
956
+ const drawsSignature = (svg, strokes) => {
957
+ const box = (svg.getAttribute('viewBox') ?? '')
958
+ .trim()
959
+ .split(/[\s,]+/)
960
+ .map(Number);
961
+ if (box.join(' ') !== '0 0 1000 300')
962
+ return false;
963
+ const signed = new DOMParser().parseFromString(signatureSvg(strokes), 'image/svg+xml').documentElement;
964
+ const shown = geometryOf(svg);
965
+ const drawn = geometryOf(signed);
966
+ return shown.length === drawn.length && shown.every((shape, i) => shape === drawn[i]);
967
+ };
353
968
  /** Boxes with a fill, a gradient or a border, images and SVG logos, in the order the page paints them. */
354
- const paint = async (root, origin, images, problems, engine) => {
969
+ const paint = async (root, origin, images, problems, engine, signature = { found: [] }) => {
355
970
  const out = [];
971
+ const outlines = [];
356
972
  const all = [root, ...root.querySelectorAll('*')];
973
+ // Where each element's shapes start, in both lists: so each shape knows the element it is drawn for.
974
+ const starts = [];
357
975
  for (const element of all) {
358
976
  if (element.closest('svg') && element.tagName.toLowerCase() !== 'svg')
359
977
  continue;
978
+ starts.push([out.length, outlines.length, element]);
360
979
  const css = getComputedStyle(element);
361
980
  if (css.display === 'none' || css.visibility === 'hidden')
362
981
  continue;
363
982
  const rect = element.getBoundingClientRect();
364
983
  if (rect.width === 0 || rect.height === 0)
365
984
  continue;
366
- const box = { left: r2(rect.left - origin.left), top: r2(rect.top - origin.top), width: r2(rect.width), height: r2(rect.height) };
367
- const radius = parseFloat(css.borderTopLeftRadius) || 0;
368
- const radii = ['borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius'].map((key) => r2(parseFloat(css[key]) || 0));
369
- const corners = radii.every((value) => value === radii[0]) ? r2(radius) : radii;
370
- const shape = { x: box.left, y: box.top, width: box.width, height: box.height, ...(radius || radii.some(Boolean) ? { radius: corners } : {}) };
985
+ const box = {
986
+ left: r2(rect.left - origin.left),
987
+ top: r2(rect.top - origin.top),
988
+ width: r2(rect.width),
989
+ height: r2(rect.height),
990
+ };
991
+ // Its corners as CSS computes them (elliptical, percentages); an image's as circles, which is what it carries.
992
+ const corners = cornersOf(css, box.width, box.height);
993
+ const round = isRound(corners);
994
+ const radii = corners.map(([h, v]) => r2(Math.min(h, v)));
995
+ const shape = {
996
+ x: box.left,
997
+ y: box.top,
998
+ width: box.width,
999
+ height: box.height,
1000
+ ...(round ? { radius: radii.every((r) => r === radii[0]) ? radii[0] : radii } : {}),
1001
+ };
371
1002
  const tag = element.tagName.toLowerCase();
372
1003
  if (tag !== 'svg' && tag !== 'img') {
373
- const fill = element === root ? undefined : hex(css.backgroundColor);
1004
+ // In the order the browser paints a box: outer shadows, background colour, background layers from the bottom,
1005
+ // inset shadows, border; its outline over everything, after the page.
1006
+ const area = { x: box.left, y: box.top, width: box.width, height: box.height };
1007
+ const filled = (fill) => round
1008
+ ? { type: 'path', d: roundedRect(area, corners), fill }
1009
+ : { type: 'rect', ...area, fill };
1010
+ const shadows = shadowsOf(css.boxShadow, hex);
1011
+ out.push(...outerShadows(area, corners, shadows));
1012
+ // The page's own colour is the page's background, unless its corners are rounded: then the browser shows what is behind them.
1013
+ const fill = element === root && !round ? undefined : hex(css.backgroundColor);
374
1014
  if (fill)
375
- out.push({ type: 'rect', ...shape, fill });
376
- const gradient = css.backgroundImage.startsWith('linear-gradient') ? linearGradient(css.backgroundImage, box) : undefined;
377
- if (gradient)
378
- out.push({ type: 'rect', ...shape, fill: gradient });
379
- else if (css.backgroundImage.startsWith('url(')) {
380
- const src = /url\(["']?([^"')]+)["']?\)/.exec(css.backgroundImage)?.[1];
381
- if (src) {
1015
+ out.push(filled(fill));
1016
+ const layers = css.backgroundImage === 'none' ? [] : splitTop(css.backgroundImage);
1017
+ const sizes = splitTop(css.backgroundSize);
1018
+ const xs = splitTop(css.backgroundPositionX);
1019
+ const ys = splitTop(css.backgroundPositionY);
1020
+ const repeats = splitTop(css.backgroundRepeat);
1021
+ const sides = ['Top', 'Right', 'Bottom', 'Left'];
1022
+ const widths = sides.map((side) => parseFloat(css[`border${side}Width`]) || 0);
1023
+ const padding = {
1024
+ x: area.x + widths[3],
1025
+ y: area.y + widths[0],
1026
+ width: area.width - widths[1] - widths[3],
1027
+ height: area.height - widths[0] - widths[2],
1028
+ };
1029
+ for (let i = layers.length - 1; i >= 0; i--) {
1030
+ const layer = layers[i];
1031
+ if (layer.startsWith('linear-gradient')) {
1032
+ const paint = linearPaint(area, layer, hex);
1033
+ if (paint)
1034
+ out.push(filled(paint));
1035
+ }
1036
+ else if (layer.startsWith('radial-gradient'))
1037
+ out.push(...(radialBackground(area, corners, layer, hex) ?? []));
1038
+ else if (layer.startsWith('repeating-linear-gradient'))
1039
+ out.push(...(repeatingLinear(area, corners, layer, hex) ?? []));
1040
+ else if (layer.startsWith('url(')) {
1041
+ const src = /url\(["']?([^"')]+)["']?\)/.exec(layer)?.[1];
1042
+ if (!src)
1043
+ continue;
382
1044
  try {
383
1045
  const image = await loaded(src);
384
1046
  const key = `image${Object.keys(images).length}`;
1047
+ const at = (list) => list[i % list.length] ?? '';
385
1048
  images[key] = capturePixels((context, width, height) => {
386
- const cover = css.backgroundSize === 'cover';
387
- const contain = css.backgroundSize === 'contain';
388
- const ratio = cover || contain ? (cover ? Math.max : Math.min)(width / image.width, height / image.height) : width / box.width;
389
- const w = image.width * ratio;
390
- const h = image.height * ratio;
391
- context.drawImage(image, (width - w) / 2, (height - h) / 2, w, h);
1049
+ // Placed in the padding box (background-origin), painted over the whole box, as size, position and repeat say.
1050
+ const s = width / box.width;
1051
+ const [w, h] = backgroundSize(at(sizes), padding.width, padding.height, image.width, image.height);
1052
+ const x0 = padding.x - area.x + positionAlong(at(xs), padding.width - w);
1053
+ const y0 = padding.y - area.y + positionAlong(at(ys), padding.height - h);
1054
+ const repeat = at(repeats);
1055
+ const [across = 'repeat', down = across] = repeat === 'repeat-x'
1056
+ ? ['repeat', 'no-repeat']
1057
+ : repeat === 'repeat-y'
1058
+ ? ['no-repeat', 'repeat']
1059
+ : repeat.split(/\s+/);
1060
+ const rx = across !== 'no-repeat';
1061
+ const ry = down !== 'no-repeat';
1062
+ const startX = rx ? x0 - Math.ceil(x0 / w) * w : x0;
1063
+ const startY = ry ? y0 - Math.ceil(y0 / h) * h : y0;
1064
+ for (let y = startY; y < (ry ? box.height : startY + 1); y += h) {
1065
+ for (let x = startX; x < (rx ? box.width : startX + 1); x += w)
1066
+ context.drawImage(image, x * s, y * s, w * s, h * s);
1067
+ }
392
1068
  }, box);
393
1069
  out.push({ type: 'image', image: key, ...shape });
394
1070
  }
@@ -397,46 +1073,64 @@ const paint = async (root, origin, images, problems, engine) => {
397
1073
  }
398
1074
  }
399
1075
  }
400
- const sides = ['Top', 'Right', 'Bottom', 'Left'];
401
- const widths = sides.map((side) => parseFloat(css[`border${side}Width`]) || 0);
402
- const colours = sides.map((side) => (css[`border${side}Style`] === 'none' ? undefined : hex(css[`border${side}Color`])));
403
- if (widths.every((w) => w > 0 && w === widths[0]) && colours.every((c) => c && c === colours[0])) {
404
- const half = widths[0] / 2;
405
- out.push({
406
- type: 'rect',
407
- x: r2(box.left + half),
408
- y: r2(box.top + half),
409
- width: r2(box.width - 2 * half),
410
- height: r2(box.height - 2 * half),
411
- stroke: colours[0],
412
- strokeWidth: r2(widths[0]),
413
- });
414
- }
415
- else {
416
- sides.forEach((side, i) => {
417
- const width = widths[i];
418
- const colour = colours[i];
419
- if (!width || !colour)
420
- return;
421
- const at = (value) => r2(value);
422
- const half = width / 2;
423
- const [from, to] = side === 'Top'
424
- ? [[box.left, box.top + half], [box.left + box.width, box.top + half]]
425
- : side === 'Bottom'
426
- ? [[box.left, box.top + box.height - half], [box.left + box.width, box.top + box.height - half]]
427
- : side === 'Left'
428
- ? [[box.left + half, box.top], [box.left + half, box.top + box.height]]
429
- : [[box.left + box.width - half, box.top], [box.left + box.width - half, box.top + box.height]];
430
- out.push({ type: 'line', from: from.map(at), to: to.map(at), stroke: colour, strokeWidth: r2(width) });
431
- });
432
- }
1076
+ out.push(...insetShadows(padding, grown(corners, -widths[0], -widths[1], -widths[2], -widths[3]), shadows));
1077
+ out.push(...borders(area, corners, sides.map((side) => ({
1078
+ width: parseFloat(css[`border${side}Width`]) || 0,
1079
+ style: css[`border${side}Style`],
1080
+ colour: hex(css[`border${side}Color`]),
1081
+ }))));
1082
+ outlines.push(...outline(area, corners, css, hex));
433
1083
  continue;
434
1084
  }
1085
+ // What outlines cannot carry: a clip, a filter, a blend, a fit that crops or moves it. A logo with any of these is
1086
+ // drawn by the canvas, which applies each as the browser does.
1087
+ const effects = (css.clipPath !== '' && css.clipPath !== 'none') ||
1088
+ (css.filter !== '' && css.filter !== 'none') ||
1089
+ (css.mixBlendMode !== '' && css.mixBlendMode !== 'normal') ||
1090
+ (tag === 'img' &&
1091
+ ((css.objectFit !== '' && css.objectFit !== 'fill') ||
1092
+ (css.objectPosition !== '' && css.objectPosition !== '50% 50%')));
1093
+ // Where a blend is, it is with the colour behind: the nearest box behind that has one.
1094
+ const backdrop = () => {
1095
+ for (let at = element.parentElement; at; at = at === root ? null : at.parentElement) {
1096
+ const fill = hex(getComputedStyle(at).backgroundColor);
1097
+ if (fill && fill.length === 7)
1098
+ return fill;
1099
+ }
1100
+ return '#ffffff';
1101
+ };
1102
+ const drawWithEffects = (source, natural) => capturePixels((context, width, height) => {
1103
+ const s = width / box.width;
1104
+ const layer = document.createElement('canvas');
1105
+ layer.width = width;
1106
+ layer.height = height;
1107
+ const drawn = layer.getContext('2d');
1108
+ const clip = clipPathOf(css.clipPath, width, height, s);
1109
+ if (clip)
1110
+ drawn.clip(clip);
1111
+ if (css.filter && css.filter !== 'none')
1112
+ drawn.filter = css.filter.replace(/(-?[\d.]+)px/g, (_, n) => `${Number(n) * s}px`);
1113
+ drawn.drawImage(source, ...fitted(natural, css, width, height, s));
1114
+ if (css.mixBlendMode && css.mixBlendMode !== 'normal') {
1115
+ // The blend over the backdrop, kept only where the image is.
1116
+ context.fillStyle = backdrop();
1117
+ context.fillRect(0, 0, width, height);
1118
+ context.globalCompositeOperation = css.mixBlendMode;
1119
+ context.drawImage(layer, 0, 0);
1120
+ context.globalCompositeOperation = 'destination-in';
1121
+ context.drawImage(layer, 0, 0);
1122
+ context.globalCompositeOperation = 'source-over';
1123
+ }
1124
+ else
1125
+ context.drawImage(layer, 0, 0);
1126
+ }, box, natural);
435
1127
  // An SVG logo, inline or by <img>: its outlines when they draw as the browser drew it, else its pixels.
436
1128
  let svg = tag === 'svg' ? element : undefined;
437
1129
  let holder;
438
- const src = tag === 'img' ? element.currentSrc || element.src : '';
439
- if (tag === 'img' && /\.svg(\?|#|$)|^data:image\/svg\+xml/i.test(src)) {
1130
+ const src = tag === 'img'
1131
+ ? element.currentSrc || element.src
1132
+ : '';
1133
+ if (tag === 'img' && !effects && /\.svg(\?|#|$)|^data:image\/svg\+xml/i.test(src)) {
440
1134
  try {
441
1135
  const text = await (await fetch(src)).text();
442
1136
  const parsed = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement;
@@ -456,7 +1150,23 @@ const paint = async (root, origin, images, problems, engine) => {
456
1150
  }
457
1151
  }
458
1152
  try {
459
- if (svg && engine) {
1153
+ // The sender's drawn signature: the receiver draws it from the signed strokes, in this box.
1154
+ if (svg && signature.strokes && drawsSignature(svg, signature.strokes)) {
1155
+ // Its ink: the first shape's stroke, or its fill where it has none (a dot).
1156
+ const ink = svg.querySelector('path, circle');
1157
+ const style = ink ? getComputedStyle(ink) : undefined;
1158
+ const colour = style ? hex(style.stroke === 'none' ? style.fill : style.stroke) : undefined;
1159
+ signature.found.push({
1160
+ type: 'signature',
1161
+ x: box.left,
1162
+ y: box.top,
1163
+ width: box.width,
1164
+ height: box.height,
1165
+ colour: solid(colour ?? '#000000'),
1166
+ });
1167
+ continue;
1168
+ }
1169
+ if (svg && engine && !effects) {
460
1170
  const paths = svgPaths(svg, origin);
461
1171
  const local = svgPaths(svg, origin, [box.left, box.top]);
462
1172
  if (paths && local && paths.length > 0 && (await drawsAlike(svg, box, local))) {
@@ -466,14 +1176,56 @@ const paint = async (root, origin, images, problems, engine) => {
466
1176
  }
467
1177
  const key = `image${Object.keys(images).length}`;
468
1178
  if (svg) {
469
- const pixels = await browserPixels(svg, box, Math.min(2, 1024 / box.width, 1024 / box.height));
470
- const width = Math.round(box.width * Math.min(2, 1024 / box.width, 1024 / box.height));
471
- const height = pixels.length / 4 / width;
472
- images[key] = { width, height, encoding: 'rgba8-deflate', data: toBase64(zlibSync(new Uint8Array(pixels.buffer))) };
1179
+ // An inline SVG's pixels: the browser draws it, at its box, with its effects.
1180
+ const copy = svg.cloneNode(true);
1181
+ copy.setAttribute('width', String(box.width));
1182
+ copy.setAttribute('height', String(box.height));
1183
+ // Its box's own effects are applied to its pixels apart (and its opacity to the image): not twice.
1184
+ for (const property of [
1185
+ 'opacity',
1186
+ 'filter',
1187
+ 'transform',
1188
+ 'clip-path',
1189
+ 'mix-blend-mode',
1190
+ 'translate',
1191
+ 'rotate',
1192
+ 'scale',
1193
+ ])
1194
+ copy.style.removeProperty(property);
1195
+ const url = URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(copy)], { type: 'image/svg+xml' }));
1196
+ try {
1197
+ images[key] = drawWithEffects(await loaded(url), {
1198
+ width: box.width * 2,
1199
+ height: box.height * 2,
1200
+ });
1201
+ }
1202
+ finally {
1203
+ URL.revokeObjectURL(url);
1204
+ }
473
1205
  }
474
1206
  else {
475
1207
  const image = element;
476
- images[key] = capturePixels((context, width, height) => context.drawImage(image, 0, 0, width, height), box);
1208
+ let natural = { width: image.naturalWidth, height: image.naturalHeight };
1209
+ if (/\.svg(\?|#|$)|^data:image\/svg\+xml/i.test(src)) {
1210
+ // An SVG's own size, as CSS sizes it: its width and height where it gives them, else its viewBox's shape fitted
1211
+ // into the box (not the browser's 300 by 150 stand-in).
1212
+ const parsed = new DOMParser().parseFromString(await (await fetch(src)).text(), 'image/svg+xml').documentElement;
1213
+ const w = parseFloat(parsed.getAttribute('width') ?? '');
1214
+ const h = parseFloat(parsed.getAttribute('height') ?? '');
1215
+ const viewBox = (parsed.getAttribute('viewBox') ?? '').split(/[\s,]+/).map(Number);
1216
+ const ratio = w > 0 && h > 0
1217
+ ? w / h
1218
+ : (viewBox[2] ?? 0) > 0 && (viewBox[3] ?? 0) > 0
1219
+ ? viewBox[2] / viewBox[3]
1220
+ : box.width / box.height;
1221
+ natural =
1222
+ w > 0 && h > 0 && !/%/.test(parsed.getAttribute('width') ?? '')
1223
+ ? { width: w, height: h }
1224
+ : box.width / box.height > ratio
1225
+ ? { width: box.height * ratio, height: box.height }
1226
+ : { width: box.width, height: box.width / ratio };
1227
+ }
1228
+ images[key] = drawWithEffects(image, natural);
477
1229
  }
478
1230
  out.push({ type: 'image', image: key, ...shape });
479
1231
  }
@@ -484,11 +1236,46 @@ const paint = async (root, origin, images, problems, engine) => {
484
1236
  holder?.remove();
485
1237
  }
486
1238
  }
487
- return out;
1239
+ // Outlines last: the browser paints them over the boxes and images of the page.
1240
+ const sourceOf = (index, which) => {
1241
+ let found = root;
1242
+ for (const start of starts) {
1243
+ if (start[which] > index)
1244
+ break;
1245
+ found = start[2];
1246
+ }
1247
+ return found;
1248
+ };
1249
+ return [
1250
+ ...out.map((element, i) => ({ element, source: sourceOf(i, 0) })),
1251
+ ...outlines.map((element, i) => ({ element, source: sourceOf(i, 1) })),
1252
+ ];
488
1253
  };
1254
+ /** A glyph scaled to another font's units: its advance and every coordinate of its outline. */
1255
+ const scaledGlyph = (glyph, scale) => ({
1256
+ advance: r2(glyph.advance * scale),
1257
+ ...(glyph.path !== undefined && {
1258
+ path: glyph.path.replace(/-?\d+(?:\.\d+)?/g, (n) => String(r2(Number(n) * scale))),
1259
+ }),
1260
+ });
1261
+ /**
1262
+ * A text in the case CSS draws it, by simple case mapping as a receiver draws it: a character that would become
1263
+ * several (ß in capitals) stays as it is, so every receiver measures and draws the same characters.
1264
+ */
1265
+ const transformed = (text, transform) => transform === undefined
1266
+ ? text
1267
+ : [...text]
1268
+ .map((char) => {
1269
+ const changed = transform === 'uppercase' ? char.toUpperCase() : char.toLowerCase();
1270
+ return [...changed].length === 1 ? changed : char;
1271
+ })
1272
+ .join('');
489
1273
  const FACT_LIKE = [
490
1274
  ['an amount', /(A\$|NZ\$|US\$|\$|£|€|¥)\s?\d|\d[\d,]*\.\d{2}\b|\b[A-Z]{3}\s?\d/],
491
- ['a date', /\b\d{1,2}[/.-]\d{1,2}[/.-]\d{2,4}\b|\b\d{4}-\d{2}-\d{2}\b|\b\d{1,2}\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s\d{4}\b/i],
1275
+ [
1276
+ 'a date',
1277
+ /\b\d{1,2}[/.-]\d{1,2}[/.-]\d{2,4}\b|\b\d{4}-\d{2}-\d{2}\b|\b\d{1,2}\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s\d{4}\b/i,
1278
+ ],
492
1279
  ['an account number', /\b\d{3}-\d{3}\b|\b\d{4}\s?\d{4}\b|\b\d{2}\s\d{3}\s\d{3}\s\d{3}\b/],
493
1280
  ['an address', /\S+[$@]\S+\.\S+/],
494
1281
  ];
@@ -512,9 +1299,60 @@ export const snapshotBoundView = async (preview, document, { engine, onWarning =
512
1299
  }
513
1300
  }
514
1301
  const images = {};
515
- const shapes = await paint(preview, origin, images, problems, canVerify);
516
- const runs = textRuns(preview, origin);
1302
+ // The sender's visual signature, drawn by the receiver from the signed data where the page shows it.
1303
+ const visual = (document.signatory ?? {}).visualSignature;
1304
+ const signature = {
1305
+ found: [],
1306
+ ...(visual?.type === 'drawn' && visual.strokes && { strokes: visual.strokes }),
1307
+ ...(visual?.type === 'typed' && visual.text && { text: visual.text }),
1308
+ };
1309
+ // Measured with the page's transforms set aside, each kept as a matrix; put back however the measuring ends.
1310
+ // ::before and ::after made real spans first, so their boxes and text are read like the rest.
1311
+ const unmake = materialize(preview);
1312
+ let flat;
1313
+ let shapes;
1314
+ let runs;
1315
+ let markers;
1316
+ try {
1317
+ flat = flatten(preview);
1318
+ shapes = await paint(preview, origin, images, problems, canVerify, signature);
1319
+ runs = textRuns(preview, origin);
1320
+ markers = listMarkers(preview, origin);
1321
+ }
1322
+ finally {
1323
+ flat?.restore();
1324
+ unmake();
1325
+ }
1326
+ // A typed signature: of the lines that are exactly its text, the one in the page's rarest typeface (a hand of its
1327
+ // own), the last where they tie, is drawn by the receiver as the signature. It is set aside before anything is
1328
+ // bound: the same words may also be a fact (the sender's or the signatory's name).
1329
+ if (signature.text !== undefined) {
1330
+ const families = new Map();
1331
+ for (const run of runs)
1332
+ families.set(run.style.family, (families.get(run.style.family) ?? 0) + [...run.text].length);
1333
+ const lines = runs.filter((run) => run.text.trim() === signature.text);
1334
+ const rarity = (line) => families.get(line.style.family) ?? 0;
1335
+ const run = lines.reduce((best, line) => (best === undefined || rarity(line) <= rarity(best) ? line : best), undefined);
1336
+ if (run) {
1337
+ const lead = [...run.text].findIndex((char) => !/\s/.test(char));
1338
+ const left = run.chars[lead].left;
1339
+ const right = run.chars[lead + [...signature.text].length - 1].right;
1340
+ signature.found.push({
1341
+ type: 'signature',
1342
+ x: r2(left),
1343
+ y: r2(run.top),
1344
+ width: r2(right - left),
1345
+ height: r2((run.bottom ?? run.top + run.style.size) - run.top),
1346
+ colour: run.style.colour,
1347
+ });
1348
+ runs.splice(runs.indexOf(run), 1);
1349
+ }
1350
+ }
517
1351
  const segments = bindRuns(document, runs);
1352
+ // List markers after the binding: the browser draws them, they are never the document's facts ("1." is no quantity).
1353
+ shapes.push(...markers.shapes);
1354
+ for (const run of markers.runs)
1355
+ segments.push({ run: runs.push(run) - 1, from: 0, to: [...run.text.trimEnd()].length });
518
1356
  // A font a style: its own glyphs, read from the page's font file, or the bundled font with its widths.
519
1357
  const styles = new Map();
520
1358
  for (const segment of segments) {
@@ -522,13 +1360,15 @@ export const snapshotBoundView = async (preview, document, { engine, onWarning =
522
1360
  const key = `${style.family}|${style.weight}|${style.style}|${style.tabular}`;
523
1361
  styles.set(key, { style, segments: [...(styles.get(key)?.segments ?? []), segment] });
524
1362
  }
525
- if (styles.size > 4)
526
- problems.push(`the preview uses ${styles.size} fonts; a BoundView carries at most 4`);
527
1363
  const fonts = {};
528
1364
  const fontKey = new Map();
1365
+ // Styles whose page font cannot be read are drawn with the bundled font they fall back to: they share it, one font
1366
+ // with every glyph they draw, rather than each carrying a copy of it.
1367
+ const shared = new Map();
529
1368
  let index = 0;
530
1369
  for (const [key, { style, segments: used }] of styles) {
531
1370
  const characters = new Set();
1371
+ const boundCharacters = new Set();
532
1372
  for (const segment of used) {
533
1373
  const run = runs[segment.run];
534
1374
  const text = segment.bind
@@ -538,36 +1378,160 @@ export const snapshotBoundView = async (preview, document, { engine, onWarning =
538
1378
  })()
539
1379
  : [...run.text].slice(segment.from, segment.to).join('');
540
1380
  // Each text's own case: one font may draw a heading in capitals and a name as written.
541
- const { transform } = run.style;
542
- const shown = transform === 'uppercase' ? text.toUpperCase() : transform === 'lowercase' ? text.toLowerCase() : text;
543
- for (const char of shown)
1381
+ const shown = transformed(text, run.style.transform);
1382
+ for (const char of shown) {
544
1383
  characters.add(char);
1384
+ if (segment.bind)
1385
+ boundCharacters.add(char);
1386
+ }
1387
+ if (run.style.smallCaps)
1388
+ for (const char of shown.toUpperCase())
1389
+ characters.add(char);
545
1390
  }
546
- const file = await fontFile(style.family, style.weight, style.style);
1391
+ const files = await fontFile(style.family, style.weight, style.style);
547
1392
  const fallback = fallbackFor(style.family);
548
- let font;
549
- if (file) {
550
- const { font: table, missing } = glyphTable(file, characters, { tabular: style.tabular });
551
- font = { ...table, fallback: [fallback] };
552
- if (missing.length > 0 && used.some((segment) => segment.bind)) {
553
- problems.push(`${style.family} has no glyph for ${missing.map((c) => JSON.stringify(c)).join(', ')}`);
1393
+ if (files) {
1394
+ // Each character from the file the browser drew it with, at the page's weight (and size, for optical sizes).
1395
+ const first = files[0].font;
1396
+ const table = {
1397
+ unitsPerEm: first.unitsPerEm,
1398
+ ascent: 0,
1399
+ descent: 0,
1400
+ glyphs: {},
1401
+ };
1402
+ const kerning = {};
1403
+ const byFile = new Map();
1404
+ const unread = [];
1405
+ for (const char of characters) {
1406
+ const file = fileFor(files, char);
1407
+ if (file && file.font.unitsPerEm === first.unitsPerEm)
1408
+ byFile.set(file, [...(byFile.get(file) ?? []), char]);
1409
+ else
1410
+ unread.push(char);
1411
+ }
1412
+ if (byFile.size === 0)
1413
+ byFile.set(files[0], []);
1414
+ for (const [file, chars] of byFile) {
1415
+ const variation = variationFor(file.font, {
1416
+ weight: style.weight,
1417
+ italic: style.style === 'italic',
1418
+ size: style.size,
1419
+ });
1420
+ const { font: part, missing } = glyphTable(file.font, chars, {
1421
+ tabular: style.tabular,
1422
+ ...(variation && { variation }),
1423
+ });
1424
+ Object.assign(table.glyphs, part.glyphs);
1425
+ Object.assign(kerning, part.kerning);
1426
+ table.ascent = Math.max(table.ascent, part.ascent);
1427
+ table.descent = Math.max(table.descent, part.descent);
1428
+ unread.push(...missing);
554
1429
  }
1430
+ // A character the page's font has no glyph for: the browser drew it with a fallback, and so do we.
1431
+ if (unread.length > 0) {
1432
+ const bundledFont = (await loadBundledFonts([fallback], unread))[fallback];
1433
+ const scale = table.unitsPerEm / bundledFont.unitsPerEm;
1434
+ for (const char of unread) {
1435
+ const glyph = bundledFont.glyphs?.[char];
1436
+ if (glyph)
1437
+ table.glyphs[char] = scaledGlyph(glyph, scale);
1438
+ else if (boundCharacters.has(char))
1439
+ problems.push(`no font has a glyph for ${JSON.stringify(char)}, which ${style.family} shows`);
1440
+ }
1441
+ }
1442
+ const name = `font${index++}`;
1443
+ fonts[name] = {
1444
+ ...table,
1445
+ ...(Object.keys(kerning).length > 0 && { kerning }),
1446
+ fallback: [fallback],
1447
+ };
1448
+ fontKey.set(key, name);
1449
+ continue;
555
1450
  }
556
- else {
557
- // No font file the page lets us read: its text is drawn with the bundled font of the same widths.
558
- const bundledFont = (await loadBundledFonts([fallback]))[fallback];
559
- const glyphs = Object.fromEntries([...characters, ...'0123456789.,-+%$€£¥/: '].flatMap((char) => (bundledFont.glyphs?.[char] ? [[char, bundledFont.glyphs[char]]] : [])));
560
- font = { unitsPerEm: bundledFont.unitsPerEm, ascent: bundledFont.ascent, descent: bundledFont.descent, glyphs, fallback: [fallback] };
561
- onWarning(`${style.family} ${style.weight} has no font file this page can read; its text is drawn with ${fallback}`);
562
- }
563
- const name = `font${index++}`;
564
- fonts[name] = font;
1451
+ // No font file the page lets us read: its text is drawn with the bundled font of the same widths.
1452
+ const bundledFont = (await loadBundledFonts([fallback], characters))[fallback];
1453
+ const name = shared.get(fallback) ?? `font${index++}`;
1454
+ const glyphs = {
1455
+ ...fonts[name]?.glyphs,
1456
+ ...Object.fromEntries([...characters, ...'0123456789.,-+%$€£¥/: '].flatMap((char) => bundledFont.glyphs?.[char] ? [[char, bundledFont.glyphs[char]]] : [])),
1457
+ };
1458
+ for (const char of boundCharacters) {
1459
+ if (!bundledFont.glyphs?.[char])
1460
+ problems.push(`no font has a glyph for ${JSON.stringify(char)}, which ${style.family} shows`);
1461
+ }
1462
+ fonts[name] = {
1463
+ unitsPerEm: bundledFont.unitsPerEm,
1464
+ ascent: bundledFont.ascent,
1465
+ descent: bundledFont.descent,
1466
+ glyphs,
1467
+ fallback: [fallback],
1468
+ };
1469
+ shared.set(fallback, name);
565
1470
  fontKey.set(key, name);
1471
+ onWarning(`${style.family} ${style.weight} has no font file this page can read; its text is drawn with ${fallback}`);
566
1472
  }
1473
+ const fontCount = Object.keys(fonts).length;
1474
+ if (fontCount > MAX_FONTS)
1475
+ problems.push(`the preview uses ${fontCount} fonts; a BoundView carries at most ${MAX_FONTS}`);
1476
+ /**
1477
+ * A text with what the browser draws with it: its shadows first, its underline and overline under it, its
1478
+ * line-through over it. A fact's lines are not drawn: in its box, a receiver could not tell one from a shape that
1479
+ * hides it (the format has no decoration for a fact yet).
1480
+ */
1481
+ const decorated = (element, shown, run, segment, source, fact) => {
1482
+ const { style } = run;
1483
+ const text = element;
1484
+ const before = [];
1485
+ const after = [];
1486
+ for (const shadow of style.shadows ?? []) {
1487
+ const outline = {
1488
+ type: 'label',
1489
+ text: shown,
1490
+ x: text.x,
1491
+ y: text.y,
1492
+ width: text.width,
1493
+ align: 'start',
1494
+ font: text.font,
1495
+ size: text.size,
1496
+ colour: shadow.colour,
1497
+ ...(text.letterSpacing && { letterSpacing: text.letterSpacing }),
1498
+ };
1499
+ for (const path of throughMatrix(outline, new DOMMatrix().translate(shadow.x, shadow.y), {
1500
+ images,
1501
+ fonts,
1502
+ problems,
1503
+ })) {
1504
+ const alpha = shadow.blur > 0 ? shadow.alpha * 0.6 : shadow.alpha;
1505
+ before.push({ ...path, ...(alpha < 1 && { opacity: r2(alpha) }) });
1506
+ }
1507
+ }
1508
+ // The decoration's extent: the segment's characters, its trailing spaces aside.
1509
+ const chars = [...run.text];
1510
+ let end = segment.to - 1;
1511
+ while (end > segment.from && /\s/.test(chars[end] ?? ''))
1512
+ end--;
1513
+ const from = run.chars[segment.from].left;
1514
+ const to = run.chars[end].right;
1515
+ for (const decoration of fact ? [] : (style.decorations ?? [])) {
1516
+ const thickness = decoration.thickness ?? Math.max(1, Math.round(style.size / 14));
1517
+ if (decoration.line === 'underline')
1518
+ before.push(...decorationLine(from, to, run.baseline + style.size * 0.1 + decoration.offset + thickness / 2, thickness, decoration.style, decoration.colour));
1519
+ else if (decoration.line === 'overline')
1520
+ before.push(...decorationLine(from, to, run.baseline - style.size * 0.93 + thickness / 2, thickness, decoration.style, decoration.colour));
1521
+ else
1522
+ after.push(...decorationLine(from, to, run.baseline - style.size * 0.29, thickness, decoration.style, decoration.colour));
1523
+ }
1524
+ return [...before, element, ...after].map((e) => ({
1525
+ element: e,
1526
+ source,
1527
+ ...(style.alpha !== undefined && e === element && { alpha: style.alpha }),
1528
+ }));
1529
+ };
567
1530
  // The text: each fact bound to its field, each of the sender's words a label, on its own baseline.
568
1531
  const texts = [];
569
1532
  for (const segment of segments) {
570
1533
  const run = runs[segment.run];
1534
+ const source = run.element ?? preview;
571
1535
  const { style } = run;
572
1536
  const font = fontKey.get(`${style.family}|${style.weight}|${style.style}|${style.tabular}`);
573
1537
  const table = fonts[font];
@@ -587,41 +1551,163 @@ export const snapshotBoundView = async (preview, document, { engine, onWarning =
587
1551
  // A fact's box is as wide as its value drawn with these glyphs, so every receiver measures the same.
588
1552
  const value = boundValue(document, segment.bind.field);
589
1553
  const text = value ? writtenValue(value, segment.bind) : '';
590
- const shown = style.transform === 'uppercase' ? text.toUpperCase() : style.transform === 'lowercase' ? text.toLowerCase() : text;
1554
+ const shown = transformed(text, style.transform);
591
1555
  const chars = [...shown];
592
1556
  const width = chars.reduce((sum, char, i) => {
593
1557
  const glyph = table.glyphs?.[char];
594
1558
  const kerning = table.kerning?.[`${char}${chars[i + 1] ?? ''}`] ?? 0;
595
- return sum + ((glyph?.advance ?? 0) + kerning) * (style.size / table.unitsPerEm) + (style.spacing ?? 0);
1559
+ return (sum +
1560
+ ((glyph?.advance ?? 0) + kerning) * (style.size / table.unitsPerEm) +
1561
+ (style.spacing ?? 0));
596
1562
  }, 0);
597
- texts.push({ type: 'text', bind: segment.bind, ...base, width: ceil2(width) });
1563
+ // No wider than the browser drew it: what follows on the line (a comma, the next word) starts where the page put
1564
+ // it, and a box reaching past that would be covered by it. A receiver fits the value to its box.
1565
+ const drawn = last.right - first.left;
1566
+ const element = {
1567
+ type: 'text',
1568
+ bind: segment.bind,
1569
+ ...base,
1570
+ width: drawn > 0 ? boxWidth(base.x, Math.min(first.left + width, last.right)) : ceil2(width),
1571
+ };
1572
+ if (style.smallCaps && shown !== shown.toUpperCase())
1573
+ onWarning(`${segment.bind.field} is in small capitals on the page; a BoundView draws a fact as written`);
1574
+ texts.push(...decorated(element, shown, run, segment, source, true));
598
1575
  }
599
1576
  else {
600
1577
  const text = [...run.text].slice(segment.from, segment.to).join('');
601
- texts.push({ type: 'label', text, ...base, width: ceil2(Math.max(0, last.right - first.left)) });
1578
+ // Small capitals: each run of lower case drawn in capitals at 70%, as the browser makes them.
1579
+ const pieces = [];
1580
+ if (style.smallCaps) {
1581
+ const chars = [...run.text];
1582
+ let start = segment.from;
1583
+ for (let i = segment.from; i <= segment.to; i++) {
1584
+ const lower = (c) => c !== undefined && c !== c.toUpperCase();
1585
+ if (i < segment.to && lower(chars[i]) === lower(chars[start]))
1586
+ continue;
1587
+ const piece = chars.slice(start, i).join('');
1588
+ const small = lower(chars[start]);
1589
+ const left = run.chars[start].left;
1590
+ const right = run.chars[i - 1].right;
1591
+ if (piece.trim())
1592
+ pieces.push({
1593
+ type: 'label',
1594
+ ...base,
1595
+ text: small ? piece.toUpperCase() : piece,
1596
+ x: r2(left),
1597
+ size: r2(style.size * (small ? 0.7 : 1)),
1598
+ width: boxWidth(left, right),
1599
+ });
1600
+ start = i;
1601
+ }
1602
+ }
1603
+ else
1604
+ pieces.push({
1605
+ type: 'label',
1606
+ text,
1607
+ ...base,
1608
+ width: boxWidth(base.x, last.right),
1609
+ });
1610
+ for (const piece of pieces)
1611
+ texts.push(...decorated(piece, piece.text, run, segment, source, false));
602
1612
  for (const [what, pattern] of FACT_LIKE) {
603
1613
  if (pattern.test(text))
604
1614
  onWarning(`"${text}" looks like ${what} but is not bound to the signed data`);
605
1615
  }
606
1616
  }
607
1617
  }
608
- const background = hex(getComputedStyle(preview).backgroundColor);
1618
+ // Each through its element's transform; then in the order the browser paints: the page's own shapes and text, then
1619
+ // each positioned part of it, its shapes then its text.
1620
+ const through = (placed) => {
1621
+ const m = flat.matrixOf(placed.source);
1622
+ if (!m || isIdentity(m))
1623
+ return [placed];
1624
+ return throughMatrix(placed.element, m, { images, fonts, problems }).map((element) => ({
1625
+ element,
1626
+ source: placed.source,
1627
+ }));
1628
+ };
1629
+ // Opacity: an element's, times its ancestors'. A shape or image carries it; a text's colour is solid, so its ink is
1630
+ // mixed with what is behind it, as the eye sees it.
1631
+ const opacities = new Map();
1632
+ const opacityOf = (element) => {
1633
+ if (opacities.has(element))
1634
+ return opacities.get(element);
1635
+ const own = parseFloat(getComputedStyle(element).opacity);
1636
+ const o = (Number.isFinite(own) ? own : 1) *
1637
+ (element === preview || !element.parentElement ? 1 : opacityOf(element.parentElement));
1638
+ opacities.set(element, o);
1639
+ return o;
1640
+ };
1641
+ const behind = (element) => {
1642
+ for (let at = element; at; at = at === preview ? null : at.parentElement) {
1643
+ const fill = hex(getComputedStyle(at).backgroundColor);
1644
+ if (fill && fill.length === 7)
1645
+ return fill;
1646
+ }
1647
+ return '#ffffff';
1648
+ };
1649
+ const faded = (placed) => {
1650
+ const o = opacityOf(placed.source) * (placed.alpha ?? 1);
1651
+ if (o >= 0.999)
1652
+ return [placed];
1653
+ const e = placed.element;
1654
+ if (e.type === 'text' || e.type === 'label' || e.type === 'signature')
1655
+ return [{ ...placed, element: { ...e, colour: mixed(behind(placed.source), e.colour, o) } }];
1656
+ const prior = 'opacity' in e && typeof e.opacity === 'number' ? e.opacity : 1;
1657
+ return [{ ...placed, element: { ...e, opacity: r2(prior * o) } }];
1658
+ };
1659
+ const drawnShapes = shapes.flatMap(through).flatMap(faded);
1660
+ const drawnTexts = texts.flatMap(through).flatMap(faded);
1661
+ const groupOf = (placed) => flat.groupOf(placed.source);
1662
+ const groups = [
1663
+ ...new Set([...drawnShapes, ...drawnTexts]
1664
+ .map(groupOf)
1665
+ .filter((group) => group !== undefined)),
1666
+ ].sort((a, b) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1));
1667
+ const ordered = [
1668
+ ...drawnShapes.filter((placed) => !groupOf(placed)),
1669
+ ...drawnTexts.filter((placed) => !groupOf(placed)),
1670
+ ...groups.flatMap((group) => [
1671
+ ...drawnShapes.filter((placed) => groupOf(placed) === group),
1672
+ ...drawnTexts.filter((placed) => groupOf(placed) === group),
1673
+ ]),
1674
+ ].map(({ element }) => element);
1675
+ const css = getComputedStyle(preview);
1676
+ const background = hex(css.backgroundColor);
1677
+ // The page as the browser draws it: the preview's box, and what overflows it where its overflow is not clipped, to
1678
+ // the furthest edge of anything drawn (scrollWidth is rounded down to whole pixels).
1679
+ const edges = ordered.map((element) => {
1680
+ const e = element;
1681
+ return { right: (e.x ?? 0) + (e.width ?? 0), bottom: (e.y ?? 0) + (e.height ?? e.size ?? 0) };
1682
+ });
1683
+ const width = css.overflowX === 'visible'
1684
+ ? Math.max(origin.width, preview.scrollWidth, ...edges.map(({ right }) => right))
1685
+ : origin.width;
1686
+ const height = css.overflowY === 'visible'
1687
+ ? Math.max(origin.height, preview.scrollHeight, ...edges.map(({ bottom }) => bottom))
1688
+ : origin.height;
609
1689
  const view = {
610
1690
  format: 1,
611
- page: { width: ceil2(origin.width), height: ceil2(origin.height), ...(background && { background: solid(background) }) },
1691
+ // A page with rounded corners draws its colour as a shape (in paint): outside its corners is no colour of its own.
1692
+ page: {
1693
+ width: ceil2(width),
1694
+ height: ceil2(height),
1695
+ ...(background &&
1696
+ !isRound(cornersOf(css, origin.width, origin.height)) && { background: solid(background) }),
1697
+ },
612
1698
  ...(Object.keys(fonts).length > 0 && { fonts }),
613
1699
  ...(Object.keys(images).length > 0 && { images }),
614
- elements: [...shapes, ...texts],
1700
+ elements: [...ordered, ...signature.found],
615
1701
  };
616
1702
  if (problems.length > 0)
617
1703
  throw new BoundViewSnapshotError('The preview cannot be sent as a BoundView', problems);
618
1704
  const parsed = BtpBoundViewSchema.safeParse(view);
619
1705
  if (!parsed.success) {
620
- throw new BoundViewSnapshotError('The preview made a BoundView a receiver would refuse', parsed.error.issues.slice(0, 10).map((issue) => `${issue.path.join('.')}: ${issue.message}`));
1706
+ throw new BoundViewSnapshotError('The preview made a BoundView a receiver would refuse', parsed.error.issues.slice(0, 10).map((issue) => `${issue.path.join('.')}: ${issue.message}`), view);
621
1707
  }
622
1708
  const result = checkBoundView(document, parsed.data);
623
1709
  if (!result.show) {
624
- throw new BoundViewSnapshotError('A receiver would not show this BoundView', result.problems.map(({ message, field, element }) => (field ? `${field}: ${message}` : `element ${element}: ${message}`)));
1710
+ throw new BoundViewSnapshotError('A receiver would not show this BoundView', result.problems.map(({ message, field, element }) => field ? `${field}: ${message}` : `element ${element}: ${message}`), parsed.data);
625
1711
  }
626
1712
  return parsed.data;
627
1713
  };