@btps/boundview 1.2.0-rc.3.1 → 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.
- package/dist/glyphs/arimo-more.json +1 -0
- package/dist/glyphs/caladea-more.json +1 -0
- package/dist/glyphs/carlito-more.json +1 -0
- package/dist/glyphs/caveat-more.json +1 -0
- package/dist/glyphs/cousine-more.json +1 -0
- package/dist/glyphs/tinos-more.json +1 -0
- package/dist/glyphs.d.ts +7 -2
- package/dist/glyphs.js +41 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/render.js +15 -3
- package/dist/signature.d.ts +35 -0
- package/dist/signature.js +86 -0
- package/dist/snapshot/bind.d.ts +13 -4
- package/dist/snapshot/bind.js +334 -118
- package/dist/snapshot/decor.d.ts +70 -0
- package/dist/snapshot/decor.js +644 -0
- package/dist/snapshot/fonts.d.ts +28 -3
- package/dist/snapshot/fonts.js +23 -4
- package/dist/snapshot/index.d.ts +46 -1
- package/dist/snapshot/index.js +1257 -181
- package/dist/snapshot/layers.d.ts +32 -0
- package/dist/snapshot/layers.js +232 -0
- package/dist/snapshot/woff2.d.ts +10 -0
- package/dist/snapshot/woff2.js +391 -0
- package/dist/svg.d.ts +1 -3
- package/dist/svg.js +39 -26
- package/package.json +7 -2
package/dist/snapshot/index.js
CHANGED
|
@@ -12,21 +12,29 @@
|
|
|
12
12
|
* an SVG logo as its outlines when they draw exactly as the browser did.
|
|
13
13
|
*/
|
|
14
14
|
import * as opentypeModule from 'opentype.js';
|
|
15
|
-
import { zlibSync } from 'fflate';
|
|
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
|
-
|
|
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
|
}
|
|
@@ -40,8 +48,16 @@ const parseFont = (buffer) => {
|
|
|
40
48
|
const umd = Reflect.get(opentypeModule, 'default');
|
|
41
49
|
return (named ?? umd.parse)(buffer);
|
|
42
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;
|
|
43
53
|
const r2 = (value) => Math.round(value * 100) / 100;
|
|
44
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));
|
|
45
61
|
// ---- Colour ----
|
|
46
62
|
let probe;
|
|
47
63
|
/** A CSS colour as `#rrggbb` or `#rrggbbaa`, by the browser's own reading of it; undefined when transparent. */
|
|
@@ -71,11 +87,16 @@ const toBase64 = (bytes) => {
|
|
|
71
87
|
text += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
72
88
|
return btoa(text);
|
|
73
89
|
};
|
|
74
|
-
/**
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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));
|
|
79
100
|
const canvas = document.createElement('canvas');
|
|
80
101
|
canvas.width = width;
|
|
81
102
|
canvas.height = height;
|
|
@@ -83,7 +104,91 @@ const capturePixels = (draw, box) => {
|
|
|
83
104
|
draw(context, width, height);
|
|
84
105
|
// Throws for an image from another site that does not allow it: the caller says so.
|
|
85
106
|
const rgba = context.getImageData(0, 0, width, height).data;
|
|
86
|
-
return {
|
|
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;
|
|
87
192
|
};
|
|
88
193
|
const loaded = (src) => new Promise((resolve, reject) => {
|
|
89
194
|
const image = new Image();
|
|
@@ -103,7 +208,9 @@ const svgPaths = (svg, origin, offset = [0, 0]) => {
|
|
|
103
208
|
if (node.closest('defs, clipPath, mask, symbol, pattern') && tag !== 'defs')
|
|
104
209
|
continue;
|
|
105
210
|
if (IGNORED.has(tag)) {
|
|
106
|
-
if (node.getAttribute('filter') ||
|
|
211
|
+
if (node.getAttribute('filter') ||
|
|
212
|
+
node.getAttribute('mask') ||
|
|
213
|
+
node.getAttribute('clip-path'))
|
|
107
214
|
return undefined;
|
|
108
215
|
continue;
|
|
109
216
|
}
|
|
@@ -113,7 +220,10 @@ const svgPaths = (svg, origin, offset = [0, 0]) => {
|
|
|
113
220
|
const style = getComputedStyle(shape);
|
|
114
221
|
if (style.display === 'none' || style.visibility === 'hidden')
|
|
115
222
|
continue;
|
|
116
|
-
if (style.filter !== 'none' ||
|
|
223
|
+
if (style.filter !== 'none' ||
|
|
224
|
+
style.mask !== 'none' ||
|
|
225
|
+
style.clipPath !== 'none' ||
|
|
226
|
+
style.strokeDasharray !== 'none') {
|
|
117
227
|
return undefined;
|
|
118
228
|
}
|
|
119
229
|
const number = (name) => {
|
|
@@ -124,7 +234,10 @@ const svgPaths = (svg, origin, offset = [0, 0]) => {
|
|
|
124
234
|
if (tag === 'path')
|
|
125
235
|
d = shape.getAttribute('d') ?? undefined;
|
|
126
236
|
else if (tag === 'polyline' || tag === 'polygon') {
|
|
127
|
-
const points = (shape.getAttribute('points') ?? '')
|
|
237
|
+
const points = (shape.getAttribute('points') ?? '')
|
|
238
|
+
.trim()
|
|
239
|
+
.split(/[\s,]+/)
|
|
240
|
+
.map(Number);
|
|
128
241
|
d = points.reduce((path, value, i) => path + (i % 2 === 0 ? `${i === 0 ? 'M' : 'L'}${value}` : ` ${value}`), '');
|
|
129
242
|
if (tag === 'polygon')
|
|
130
243
|
d += 'Z';
|
|
@@ -135,9 +248,17 @@ const svgPaths = (svg, origin, offset = [0, 0]) => {
|
|
|
135
248
|
const ctm = shape.getScreenCTM();
|
|
136
249
|
if (!commands || !ctm)
|
|
137
250
|
return undefined;
|
|
138
|
-
const matrix = [
|
|
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.
|
|
139
260
|
let opacity = 1;
|
|
140
|
-
for (let at = shape; at && at !== svg
|
|
261
|
+
for (let at = shape; at && at !== svg; at = at.parentElement) {
|
|
141
262
|
opacity *= Number(getComputedStyle(at).opacity);
|
|
142
263
|
}
|
|
143
264
|
const paint = (css, alpha) => {
|
|
@@ -171,7 +292,8 @@ const svgPaths = (svg, origin, offset = [0, 0]) => {
|
|
|
171
292
|
return out;
|
|
172
293
|
};
|
|
173
294
|
/** The browser's own picture of an SVG in its box, at `scale`, over white. */
|
|
174
|
-
|
|
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) => {
|
|
175
297
|
const copy = svg.cloneNode(true);
|
|
176
298
|
copy.setAttribute('width', String(box.width));
|
|
177
299
|
copy.setAttribute('height', String(box.height));
|
|
@@ -179,11 +301,14 @@ const browserPixels = async (svg, box, scale) => {
|
|
|
179
301
|
try {
|
|
180
302
|
const image = await loaded(url);
|
|
181
303
|
const canvas = document.createElement('canvas');
|
|
182
|
-
|
|
183
|
-
canvas.
|
|
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));
|
|
184
307
|
const context = canvas.getContext('2d');
|
|
185
|
-
|
|
186
|
-
|
|
308
|
+
if (white) {
|
|
309
|
+
context.fillStyle = '#ffffff';
|
|
310
|
+
context.fillRect(0, 0, canvas.width, canvas.height);
|
|
311
|
+
}
|
|
187
312
|
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
|
188
313
|
return context.getImageData(0, 0, canvas.width, canvas.height).data;
|
|
189
314
|
}
|
|
@@ -198,9 +323,20 @@ const browserPixels = async (svg, box, scale) => {
|
|
|
198
323
|
* (an effect the outlines could not carry) and the logo travels as pixels.
|
|
199
324
|
*/
|
|
200
325
|
const drawsAlike = async (svg, box, paths) => {
|
|
201
|
-
const view = {
|
|
202
|
-
|
|
203
|
-
|
|
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();
|
|
204
340
|
const theirs = await browserPixels(svg, box, 2);
|
|
205
341
|
if (ours.length !== theirs.length)
|
|
206
342
|
return false;
|
|
@@ -219,14 +355,48 @@ const drawsAlike = async (svg, box, paths) => {
|
|
|
219
355
|
const pixels = ours.length / 4;
|
|
220
356
|
return total / (pixels * 3) <= 3 && far / pixels <= 0.01;
|
|
221
357
|
};
|
|
222
|
-
// ---- Fonts ----
|
|
223
358
|
const fontFiles = new Map();
|
|
224
|
-
/**
|
|
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
|
+
*/
|
|
225
395
|
const fontFile = (family, weight, style) => {
|
|
226
396
|
const key = `${family}|${weight}|${style}`;
|
|
227
397
|
if (!fontFiles.has(key)) {
|
|
228
398
|
fontFiles.set(key, (async () => {
|
|
229
|
-
|
|
399
|
+
const candidates = [];
|
|
230
400
|
for (const sheet of document.styleSheets) {
|
|
231
401
|
let rules;
|
|
232
402
|
try {
|
|
@@ -243,64 +413,153 @@ const fontFile = (family, weight, style) => {
|
|
|
243
413
|
continue;
|
|
244
414
|
if ((rule.style.getPropertyValue('font-style').trim() || 'normal') !== style)
|
|
245
415
|
continue;
|
|
246
|
-
const weights = (rule.style.getPropertyValue('font-weight').trim() || '400')
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
const
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
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
|
+
});
|
|
254
435
|
}
|
|
255
436
|
}
|
|
256
|
-
if (
|
|
257
|
-
return undefined;
|
|
258
|
-
try {
|
|
259
|
-
return parseFont(await (await fetch(best.url)).arrayBuffer());
|
|
260
|
-
}
|
|
261
|
-
catch {
|
|
437
|
+
if (candidates.length === 0)
|
|
262
438
|
return undefined;
|
|
263
|
-
}
|
|
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;
|
|
264
448
|
})());
|
|
265
449
|
}
|
|
266
450
|
return fontFiles.get(key);
|
|
267
451
|
};
|
|
268
|
-
|
|
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) => {
|
|
269
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
|
+
}));
|
|
270
502
|
return {
|
|
271
503
|
family: (css.fontFamily.split(',')[0] ?? '').replace(/["']/g, '').trim(),
|
|
272
504
|
weight: Number(css.fontWeight) || 400,
|
|
273
505
|
style: css.fontStyle === 'italic' || css.fontStyle === 'oblique' ? 'italic' : 'normal',
|
|
274
506
|
size: parseFloat(css.fontSize),
|
|
275
|
-
colour: solid(
|
|
507
|
+
colour: solid(ink),
|
|
276
508
|
spacing: css.letterSpacing === 'normal' ? 0 : parseFloat(css.letterSpacing) || 0,
|
|
277
|
-
...(css.textTransform === 'uppercase' || css.textTransform === 'lowercase'
|
|
509
|
+
...(css.textTransform === 'uppercase' || css.textTransform === 'lowercase'
|
|
510
|
+
? { transform: css.textTransform }
|
|
511
|
+
: {}),
|
|
278
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 }),
|
|
279
517
|
};
|
|
280
518
|
};
|
|
281
519
|
/** Each text node as runs, one a line it was laid out on, with each character's box and the line's baseline. */
|
|
282
|
-
const textRuns = (root, origin) => {
|
|
520
|
+
export const textRuns = (root, origin) => {
|
|
283
521
|
const runs = [];
|
|
284
522
|
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
285
523
|
const range = document.createRange();
|
|
286
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;
|
|
287
538
|
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
288
539
|
const parent = node.parentElement;
|
|
289
540
|
if (!parent || parent.closest('svg') || !node.textContent?.trim())
|
|
290
541
|
continue;
|
|
542
|
+
// Text the page does not draw: hidden, or in an element not laid out (display: none, a closed details).
|
|
291
543
|
if (getComputedStyle(parent).visibility === 'hidden')
|
|
292
544
|
continue;
|
|
545
|
+
if (typeof parent.checkVisibility === 'function' && !parent.checkVisibility())
|
|
546
|
+
continue;
|
|
293
547
|
const css = getComputedStyle(parent);
|
|
294
548
|
measure.font = `${css.fontStyle} ${css.fontWeight} ${css.fontSize} ${css.fontFamily}`;
|
|
295
549
|
const ascent = measure.measureText('Hg').fontBoundingBoxAscent;
|
|
296
|
-
const style = styleOf(parent);
|
|
550
|
+
const style = styleOf(parent, root);
|
|
551
|
+
const nodeIndex = index++;
|
|
552
|
+
const block = blockOf(parent);
|
|
297
553
|
let line;
|
|
554
|
+
let lastRight = -Infinity;
|
|
298
555
|
let offset = 0;
|
|
299
556
|
for (const char of node.textContent) {
|
|
300
557
|
range.setStart(node, offset);
|
|
301
558
|
range.setEnd(node, offset + char.length);
|
|
302
559
|
offset += char.length;
|
|
303
560
|
const rect = range.getBoundingClientRect();
|
|
561
|
+
if (rect.width === 0 && rect.height === 0 && !/\s/.test(char))
|
|
562
|
+
continue;
|
|
304
563
|
if (rect.width === 0 && /\s/.test(char)) {
|
|
305
564
|
if (line) {
|
|
306
565
|
line.text += ' ';
|
|
@@ -308,97 +567,504 @@ const textRuns = (root, origin) => {
|
|
|
308
567
|
}
|
|
309
568
|
continue;
|
|
310
569
|
}
|
|
311
|
-
|
|
312
|
-
|
|
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
|
+
};
|
|
313
589
|
runs.push(line);
|
|
314
590
|
}
|
|
315
|
-
|
|
316
|
-
|
|
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;
|
|
317
596
|
}
|
|
318
597
|
}
|
|
319
598
|
return runs;
|
|
320
599
|
};
|
|
321
|
-
|
|
322
|
-
const
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
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;
|
|
332
621
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
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;
|
|
339
654
|
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
const
|
|
350
|
-
const
|
|
351
|
-
const
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
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) } };
|
|
355
784
|
return {
|
|
356
|
-
|
|
357
|
-
from: [r2(cx - dx), r2(cy - dy)],
|
|
358
|
-
to: [r2(cx + dx), r2(cy + dy)],
|
|
359
|
-
stops: stops.map(([offset, colour]) => [r2(Math.min(1, Math.max(0, offset))), colour]),
|
|
360
|
-
},
|
|
785
|
+
radial: { ...p.radial, centre: at(p.radial.centre), radius: r2(p.radial.radius * scaleOf(m)) },
|
|
361
786
|
};
|
|
362
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
|
+
};
|
|
363
968
|
/** Boxes with a fill, a gradient or a border, images and SVG logos, in the order the page paints them. */
|
|
364
|
-
const paint = async (root, origin, images, problems, engine) => {
|
|
969
|
+
const paint = async (root, origin, images, problems, engine, signature = { found: [] }) => {
|
|
365
970
|
const out = [];
|
|
971
|
+
const outlines = [];
|
|
366
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 = [];
|
|
367
975
|
for (const element of all) {
|
|
368
976
|
if (element.closest('svg') && element.tagName.toLowerCase() !== 'svg')
|
|
369
977
|
continue;
|
|
978
|
+
starts.push([out.length, outlines.length, element]);
|
|
370
979
|
const css = getComputedStyle(element);
|
|
371
980
|
if (css.display === 'none' || css.visibility === 'hidden')
|
|
372
981
|
continue;
|
|
373
982
|
const rect = element.getBoundingClientRect();
|
|
374
983
|
if (rect.width === 0 || rect.height === 0)
|
|
375
984
|
continue;
|
|
376
|
-
const box = {
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
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
|
+
};
|
|
381
1002
|
const tag = element.tagName.toLowerCase();
|
|
382
1003
|
if (tag !== 'svg' && tag !== 'img') {
|
|
383
|
-
|
|
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);
|
|
384
1014
|
if (fill)
|
|
385
|
-
out.push(
|
|
386
|
-
const
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
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;
|
|
392
1044
|
try {
|
|
393
1045
|
const image = await loaded(src);
|
|
394
1046
|
const key = `image${Object.keys(images).length}`;
|
|
1047
|
+
const at = (list) => list[i % list.length] ?? '';
|
|
395
1048
|
images[key] = capturePixels((context, width, height) => {
|
|
396
|
-
|
|
397
|
-
const
|
|
398
|
-
const
|
|
399
|
-
const
|
|
400
|
-
const
|
|
401
|
-
|
|
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
|
+
}
|
|
402
1068
|
}, box);
|
|
403
1069
|
out.push({ type: 'image', image: key, ...shape });
|
|
404
1070
|
}
|
|
@@ -407,46 +1073,64 @@ const paint = async (root, origin, images, problems, engine) => {
|
|
|
407
1073
|
}
|
|
408
1074
|
}
|
|
409
1075
|
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
x: r2(box.left + half),
|
|
418
|
-
y: r2(box.top + half),
|
|
419
|
-
width: r2(box.width - 2 * half),
|
|
420
|
-
height: r2(box.height - 2 * half),
|
|
421
|
-
stroke: colours[0],
|
|
422
|
-
strokeWidth: r2(widths[0]),
|
|
423
|
-
});
|
|
424
|
-
}
|
|
425
|
-
else {
|
|
426
|
-
sides.forEach((side, i) => {
|
|
427
|
-
const width = widths[i];
|
|
428
|
-
const colour = colours[i];
|
|
429
|
-
if (!width || !colour)
|
|
430
|
-
return;
|
|
431
|
-
const at = (value) => r2(value);
|
|
432
|
-
const half = width / 2;
|
|
433
|
-
const [from, to] = side === 'Top'
|
|
434
|
-
? [[box.left, box.top + half], [box.left + box.width, box.top + half]]
|
|
435
|
-
: side === 'Bottom'
|
|
436
|
-
? [[box.left, box.top + box.height - half], [box.left + box.width, box.top + box.height - half]]
|
|
437
|
-
: side === 'Left'
|
|
438
|
-
? [[box.left + half, box.top], [box.left + half, box.top + box.height]]
|
|
439
|
-
: [[box.left + box.width - half, box.top], [box.left + box.width - half, box.top + box.height]];
|
|
440
|
-
out.push({ type: 'line', from: from.map(at), to: to.map(at), stroke: colour, strokeWidth: r2(width) });
|
|
441
|
-
});
|
|
442
|
-
}
|
|
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));
|
|
443
1083
|
continue;
|
|
444
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);
|
|
445
1127
|
// An SVG logo, inline or by <img>: its outlines when they draw as the browser drew it, else its pixels.
|
|
446
1128
|
let svg = tag === 'svg' ? element : undefined;
|
|
447
1129
|
let holder;
|
|
448
|
-
const src = tag === 'img'
|
|
449
|
-
|
|
1130
|
+
const src = tag === 'img'
|
|
1131
|
+
? element.currentSrc || element.src
|
|
1132
|
+
: '';
|
|
1133
|
+
if (tag === 'img' && !effects && /\.svg(\?|#|$)|^data:image\/svg\+xml/i.test(src)) {
|
|
450
1134
|
try {
|
|
451
1135
|
const text = await (await fetch(src)).text();
|
|
452
1136
|
const parsed = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement;
|
|
@@ -466,7 +1150,23 @@ const paint = async (root, origin, images, problems, engine) => {
|
|
|
466
1150
|
}
|
|
467
1151
|
}
|
|
468
1152
|
try {
|
|
469
|
-
|
|
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) {
|
|
470
1170
|
const paths = svgPaths(svg, origin);
|
|
471
1171
|
const local = svgPaths(svg, origin, [box.left, box.top]);
|
|
472
1172
|
if (paths && local && paths.length > 0 && (await drawsAlike(svg, box, local))) {
|
|
@@ -476,14 +1176,56 @@ const paint = async (root, origin, images, problems, engine) => {
|
|
|
476
1176
|
}
|
|
477
1177
|
const key = `image${Object.keys(images).length}`;
|
|
478
1178
|
if (svg) {
|
|
479
|
-
|
|
480
|
-
const
|
|
481
|
-
|
|
482
|
-
|
|
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
|
+
}
|
|
483
1205
|
}
|
|
484
1206
|
else {
|
|
485
1207
|
const image = element;
|
|
486
|
-
|
|
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);
|
|
487
1229
|
}
|
|
488
1230
|
out.push({ type: 'image', image: key, ...shape });
|
|
489
1231
|
}
|
|
@@ -494,11 +1236,46 @@ const paint = async (root, origin, images, problems, engine) => {
|
|
|
494
1236
|
holder?.remove();
|
|
495
1237
|
}
|
|
496
1238
|
}
|
|
497
|
-
|
|
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
|
+
];
|
|
498
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('');
|
|
499
1273
|
const FACT_LIKE = [
|
|
500
1274
|
['an amount', /(A\$|NZ\$|US\$|\$|£|€|¥)\s?\d|\d[\d,]*\.\d{2}\b|\b[A-Z]{3}\s?\d/],
|
|
501
|
-
[
|
|
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
|
+
],
|
|
502
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/],
|
|
503
1280
|
['an address', /\S+[$@]\S+\.\S+/],
|
|
504
1281
|
];
|
|
@@ -522,9 +1299,60 @@ export const snapshotBoundView = async (preview, document, { engine, onWarning =
|
|
|
522
1299
|
}
|
|
523
1300
|
}
|
|
524
1301
|
const images = {};
|
|
525
|
-
|
|
526
|
-
const
|
|
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
|
+
}
|
|
527
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 });
|
|
528
1356
|
// A font a style: its own glyphs, read from the page's font file, or the bundled font with its widths.
|
|
529
1357
|
const styles = new Map();
|
|
530
1358
|
for (const segment of segments) {
|
|
@@ -532,13 +1360,15 @@ export const snapshotBoundView = async (preview, document, { engine, onWarning =
|
|
|
532
1360
|
const key = `${style.family}|${style.weight}|${style.style}|${style.tabular}`;
|
|
533
1361
|
styles.set(key, { style, segments: [...(styles.get(key)?.segments ?? []), segment] });
|
|
534
1362
|
}
|
|
535
|
-
if (styles.size > 4)
|
|
536
|
-
problems.push(`the preview uses ${styles.size} fonts; a BoundView carries at most 4`);
|
|
537
1363
|
const fonts = {};
|
|
538
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();
|
|
539
1368
|
let index = 0;
|
|
540
1369
|
for (const [key, { style, segments: used }] of styles) {
|
|
541
1370
|
const characters = new Set();
|
|
1371
|
+
const boundCharacters = new Set();
|
|
542
1372
|
for (const segment of used) {
|
|
543
1373
|
const run = runs[segment.run];
|
|
544
1374
|
const text = segment.bind
|
|
@@ -548,36 +1378,160 @@ export const snapshotBoundView = async (preview, document, { engine, onWarning =
|
|
|
548
1378
|
})()
|
|
549
1379
|
: [...run.text].slice(segment.from, segment.to).join('');
|
|
550
1380
|
// Each text's own case: one font may draw a heading in capitals and a name as written.
|
|
551
|
-
const
|
|
552
|
-
|
|
553
|
-
for (const char of shown)
|
|
1381
|
+
const shown = transformed(text, run.style.transform);
|
|
1382
|
+
for (const char of shown) {
|
|
554
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);
|
|
555
1390
|
}
|
|
556
|
-
const
|
|
1391
|
+
const files = await fontFile(style.family, style.weight, style.style);
|
|
557
1392
|
const fallback = fallbackFor(style.family);
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
const
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
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);
|
|
564
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;
|
|
565
1450
|
}
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
}
|
|
573
|
-
const
|
|
574
|
-
|
|
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);
|
|
575
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}`);
|
|
576
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
|
+
};
|
|
577
1530
|
// The text: each fact bound to its field, each of the sender's words a label, on its own baseline.
|
|
578
1531
|
const texts = [];
|
|
579
1532
|
for (const segment of segments) {
|
|
580
1533
|
const run = runs[segment.run];
|
|
1534
|
+
const source = run.element ?? preview;
|
|
581
1535
|
const { style } = run;
|
|
582
1536
|
const font = fontKey.get(`${style.family}|${style.weight}|${style.style}|${style.tabular}`);
|
|
583
1537
|
const table = fonts[font];
|
|
@@ -597,41 +1551,163 @@ export const snapshotBoundView = async (preview, document, { engine, onWarning =
|
|
|
597
1551
|
// A fact's box is as wide as its value drawn with these glyphs, so every receiver measures the same.
|
|
598
1552
|
const value = boundValue(document, segment.bind.field);
|
|
599
1553
|
const text = value ? writtenValue(value, segment.bind) : '';
|
|
600
|
-
const shown =
|
|
1554
|
+
const shown = transformed(text, style.transform);
|
|
601
1555
|
const chars = [...shown];
|
|
602
1556
|
const width = chars.reduce((sum, char, i) => {
|
|
603
1557
|
const glyph = table.glyphs?.[char];
|
|
604
1558
|
const kerning = table.kerning?.[`${char}${chars[i + 1] ?? ''}`] ?? 0;
|
|
605
|
-
return sum +
|
|
1559
|
+
return (sum +
|
|
1560
|
+
((glyph?.advance ?? 0) + kerning) * (style.size / table.unitsPerEm) +
|
|
1561
|
+
(style.spacing ?? 0));
|
|
606
1562
|
}, 0);
|
|
607
|
-
|
|
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));
|
|
608
1575
|
}
|
|
609
1576
|
else {
|
|
610
1577
|
const text = [...run.text].slice(segment.from, segment.to).join('');
|
|
611
|
-
|
|
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));
|
|
612
1612
|
for (const [what, pattern] of FACT_LIKE) {
|
|
613
1613
|
if (pattern.test(text))
|
|
614
1614
|
onWarning(`"${text}" looks like ${what} but is not bound to the signed data`);
|
|
615
1615
|
}
|
|
616
1616
|
}
|
|
617
1617
|
}
|
|
618
|
-
|
|
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;
|
|
619
1689
|
const view = {
|
|
620
1690
|
format: 1,
|
|
621
|
-
page
|
|
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
|
+
},
|
|
622
1698
|
...(Object.keys(fonts).length > 0 && { fonts }),
|
|
623
1699
|
...(Object.keys(images).length > 0 && { images }),
|
|
624
|
-
elements: [...
|
|
1700
|
+
elements: [...ordered, ...signature.found],
|
|
625
1701
|
};
|
|
626
1702
|
if (problems.length > 0)
|
|
627
1703
|
throw new BoundViewSnapshotError('The preview cannot be sent as a BoundView', problems);
|
|
628
1704
|
const parsed = BtpBoundViewSchema.safeParse(view);
|
|
629
1705
|
if (!parsed.success) {
|
|
630
|
-
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);
|
|
631
1707
|
}
|
|
632
1708
|
const result = checkBoundView(document, parsed.data);
|
|
633
1709
|
if (!result.show) {
|
|
634
|
-
throw new BoundViewSnapshotError('A receiver would not show this BoundView', result.problems.map(({ message, field, element }) =>
|
|
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);
|
|
635
1711
|
}
|
|
636
1712
|
return parsed.data;
|
|
637
1713
|
};
|