@btps/boundview 0.0.0 → 1.2.0-rc.3
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/NOTICE +10 -0
- package/README.md +58 -1
- package/dist/engine.wasm +0 -0
- package/dist/glyphs/arimo.json +1 -0
- package/dist/glyphs/caladea.json +1 -0
- package/dist/glyphs/carlito.json +1 -0
- package/dist/glyphs/caveat.json +1 -0
- package/dist/glyphs/cousine.json +1 -0
- package/dist/glyphs/tinos.json +1 -0
- package/dist/glyphs.d.ts +19 -0
- package/dist/glyphs.js +55 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +10 -0
- package/dist/png.d.ts +17 -0
- package/dist/png.js +78 -0
- package/dist/render.d.ts +23 -0
- package/dist/render.js +50 -0
- package/dist/snapshot/bind.d.ts +63 -0
- package/dist/snapshot/bind.js +286 -0
- package/dist/snapshot/fonts.d.ts +68 -0
- package/dist/snapshot/fonts.js +119 -0
- package/dist/snapshot/index.d.ts +32 -0
- package/dist/snapshot/index.js +627 -0
- package/dist/snapshot/svgPath.d.ts +31 -0
- package/dist/snapshot/svgPath.js +232 -0
- package/dist/svg.d.ts +19 -0
- package/dist/svg.js +249 -0
- package/package.json +33 -3
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright (c) 2025 Bhupendra Tamang
|
|
4
|
+
* Licensed under the Apache License, Version 2.0
|
|
5
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
*/
|
|
7
|
+
/*
|
|
8
|
+
* snapshotBoundView: a platform's own HTML preview, as the browser laid it out,
|
|
9
|
+
* captured as a BoundView. Runs in the browser where the preview is shown. No
|
|
10
|
+
* marks in the preview: every fact is found by its value (bind.ts), fonts are
|
|
11
|
+
* read from the page's own font files (fonts.ts), images as their pixels, and
|
|
12
|
+
* an SVG logo as its outlines when they draw exactly as the browser did.
|
|
13
|
+
*/
|
|
14
|
+
import opentype from 'opentype.js';
|
|
15
|
+
import { zlibSync } from 'fflate';
|
|
16
|
+
import { Resvg } from '@resvg/resvg-wasm';
|
|
17
|
+
import { BtpBoundViewSchema, checkBoundView, boundValue, writtenValue, } from '@btps/sdk/boundview';
|
|
18
|
+
import { initBoundViewEngine } from '../render.js';
|
|
19
|
+
import { boundViewToSvg } from '../svg.js';
|
|
20
|
+
import { loadBundledFonts } from '../glyphs.js';
|
|
21
|
+
import { bindRuns } from './bind.js';
|
|
22
|
+
import { fallbackFor, glyphTable } from './fonts.js';
|
|
23
|
+
import { normalizePath, pathData, shapeOutline } from './svgPath.js';
|
|
24
|
+
/** A BoundView that cannot be sent as it is, and why. */
|
|
25
|
+
export class BoundViewSnapshotError extends Error {
|
|
26
|
+
problems;
|
|
27
|
+
constructor(message, problems) {
|
|
28
|
+
super(`${message}: ${problems.join('; ')}`);
|
|
29
|
+
this.problems = problems;
|
|
30
|
+
this.name = 'BoundViewSnapshotError';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const r2 = (value) => Math.round(value * 100) / 100;
|
|
34
|
+
const ceil2 = (value) => Math.ceil(value * 100 - 1e-6) / 100;
|
|
35
|
+
// ---- Colour ----
|
|
36
|
+
let probe;
|
|
37
|
+
/** A CSS colour as `#rrggbb` or `#rrggbbaa`, by the browser's own reading of it; undefined when transparent. */
|
|
38
|
+
const hex = (css) => {
|
|
39
|
+
probe ??= document.createElement('canvas').getContext('2d') ?? undefined;
|
|
40
|
+
if (!probe)
|
|
41
|
+
return undefined;
|
|
42
|
+
probe.fillStyle = '#000000';
|
|
43
|
+
probe.fillStyle = css;
|
|
44
|
+
const read = String(probe.fillStyle);
|
|
45
|
+
if (read.startsWith('#'))
|
|
46
|
+
return read.toLowerCase();
|
|
47
|
+
const match = /rgba?\(\s*(\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\s*\)/.exec(read);
|
|
48
|
+
if (!match)
|
|
49
|
+
return undefined;
|
|
50
|
+
const alpha = match[4] === undefined ? 1 : Number(match[4]);
|
|
51
|
+
if (alpha === 0)
|
|
52
|
+
return undefined;
|
|
53
|
+
const two = (n) => n.toString(16).padStart(2, '0');
|
|
54
|
+
return `#${two(Number(match[1]))}${two(Number(match[2]))}${two(Number(match[3]))}${alpha < 1 ? two(Math.round(alpha * 255)) : ''}`;
|
|
55
|
+
};
|
|
56
|
+
const solid = (colour) => colour.slice(0, 7);
|
|
57
|
+
// ---- Pixels ----
|
|
58
|
+
const toBase64 = (bytes) => {
|
|
59
|
+
let text = '';
|
|
60
|
+
for (let i = 0; i < bytes.length; i += 0x8000)
|
|
61
|
+
text += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
62
|
+
return btoa(text);
|
|
63
|
+
};
|
|
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));
|
|
69
|
+
const canvas = document.createElement('canvas');
|
|
70
|
+
canvas.width = width;
|
|
71
|
+
canvas.height = height;
|
|
72
|
+
const context = canvas.getContext('2d');
|
|
73
|
+
draw(context, width, height);
|
|
74
|
+
// Throws for an image from another site that does not allow it: the caller says so.
|
|
75
|
+
const rgba = context.getImageData(0, 0, width, height).data;
|
|
76
|
+
return { width, height, encoding: 'rgba8-deflate', data: toBase64(zlibSync(new Uint8Array(rgba.buffer))) };
|
|
77
|
+
};
|
|
78
|
+
const loaded = (src) => new Promise((resolve, reject) => {
|
|
79
|
+
const image = new Image();
|
|
80
|
+
image.crossOrigin = 'anonymous';
|
|
81
|
+
image.onload = () => resolve(image);
|
|
82
|
+
image.onerror = () => reject(new Error(`could not load ${src}`));
|
|
83
|
+
image.src = src;
|
|
84
|
+
});
|
|
85
|
+
// ---- SVG logos as outlines ----
|
|
86
|
+
const IGNORED = new Set(['defs', 'title', 'desc', 'metadata', 'style', 'g', 'svg']);
|
|
87
|
+
const SHAPES = new Set(['path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon']);
|
|
88
|
+
/** An SVG's shapes as BoundView paths on the page, or undefined when it holds anything a path cannot carry. */
|
|
89
|
+
const svgPaths = (svg, origin, offset = [0, 0]) => {
|
|
90
|
+
const out = [];
|
|
91
|
+
for (const node of svg.querySelectorAll('*')) {
|
|
92
|
+
const tag = node.tagName.toLowerCase();
|
|
93
|
+
if (node.closest('defs, clipPath, mask, symbol, pattern') && tag !== 'defs')
|
|
94
|
+
continue;
|
|
95
|
+
if (IGNORED.has(tag)) {
|
|
96
|
+
if (node.getAttribute('filter') || node.getAttribute('mask') || node.getAttribute('clip-path'))
|
|
97
|
+
return undefined;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (!SHAPES.has(tag))
|
|
101
|
+
return undefined;
|
|
102
|
+
const shape = node;
|
|
103
|
+
const style = getComputedStyle(shape);
|
|
104
|
+
if (style.display === 'none' || style.visibility === 'hidden')
|
|
105
|
+
continue;
|
|
106
|
+
if (style.filter !== 'none' || style.mask !== 'none' || style.clipPath !== 'none' || style.strokeDasharray !== 'none') {
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
const number = (name) => {
|
|
110
|
+
const value = shape.getAttribute(name);
|
|
111
|
+
return value === null ? 0 : parseFloat(value);
|
|
112
|
+
};
|
|
113
|
+
let d;
|
|
114
|
+
if (tag === 'path')
|
|
115
|
+
d = shape.getAttribute('d') ?? undefined;
|
|
116
|
+
else if (tag === 'polyline' || tag === 'polygon') {
|
|
117
|
+
const points = (shape.getAttribute('points') ?? '').trim().split(/[\s,]+/).map(Number);
|
|
118
|
+
d = points.reduce((path, value, i) => path + (i % 2 === 0 ? `${i === 0 ? 'M' : 'L'}${value}` : ` ${value}`), '');
|
|
119
|
+
if (tag === 'polygon')
|
|
120
|
+
d += 'Z';
|
|
121
|
+
}
|
|
122
|
+
else
|
|
123
|
+
d = shapeOutline(tag, number);
|
|
124
|
+
const commands = d ? normalizePath(d) : undefined;
|
|
125
|
+
const ctm = shape.getScreenCTM();
|
|
126
|
+
if (!commands || !ctm)
|
|
127
|
+
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]];
|
|
129
|
+
let opacity = 1;
|
|
130
|
+
for (let at = shape; at && at !== svg.parentElement; at = at.parentElement) {
|
|
131
|
+
opacity *= Number(getComputedStyle(at).opacity);
|
|
132
|
+
}
|
|
133
|
+
const paint = (css, alpha) => {
|
|
134
|
+
if (css === 'none')
|
|
135
|
+
return undefined;
|
|
136
|
+
if (css.startsWith('url('))
|
|
137
|
+
return null;
|
|
138
|
+
const colour = hex(css);
|
|
139
|
+
if (colour === undefined)
|
|
140
|
+
return undefined;
|
|
141
|
+
const a = Math.round((colour.length === 9 ? parseInt(colour.slice(7), 16) / 255 : 1) * Number(alpha) * 255);
|
|
142
|
+
return a >= 255 ? solid(colour) : `${solid(colour)}${a.toString(16).padStart(2, '0')}`;
|
|
143
|
+
};
|
|
144
|
+
const fill = paint(style.fill, style.fillOpacity);
|
|
145
|
+
const stroke = paint(style.stroke, style.strokeOpacity);
|
|
146
|
+
if (fill === null || stroke === null)
|
|
147
|
+
return undefined;
|
|
148
|
+
const scale = Math.sqrt(Math.abs(ctm.a * ctm.d - ctm.b * ctm.c));
|
|
149
|
+
const strokeWidth = r2(parseFloat(style.strokeWidth) * scale);
|
|
150
|
+
if (strokeWidth > 100)
|
|
151
|
+
return undefined;
|
|
152
|
+
out.push({
|
|
153
|
+
type: 'path',
|
|
154
|
+
d: pathData(commands, matrix),
|
|
155
|
+
...(fill && { fill }),
|
|
156
|
+
...(stroke && strokeWidth > 0 && { stroke, strokeWidth }),
|
|
157
|
+
...(style.fillRule === 'evenodd' && { fillRule: 'evenodd' }),
|
|
158
|
+
...(opacity < 1 && { opacity: r2(opacity) }),
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
};
|
|
163
|
+
/** The browser's own picture of an SVG in its box, at `scale`, over white. */
|
|
164
|
+
const browserPixels = async (svg, box, scale) => {
|
|
165
|
+
const copy = svg.cloneNode(true);
|
|
166
|
+
copy.setAttribute('width', String(box.width));
|
|
167
|
+
copy.setAttribute('height', String(box.height));
|
|
168
|
+
const url = URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(copy)], { type: 'image/svg+xml' }));
|
|
169
|
+
try {
|
|
170
|
+
const image = await loaded(url);
|
|
171
|
+
const canvas = document.createElement('canvas');
|
|
172
|
+
canvas.width = Math.round(box.width * scale);
|
|
173
|
+
canvas.height = Math.round(box.height * scale);
|
|
174
|
+
const context = canvas.getContext('2d');
|
|
175
|
+
context.fillStyle = '#ffffff';
|
|
176
|
+
context.fillRect(0, 0, canvas.width, canvas.height);
|
|
177
|
+
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
|
178
|
+
return context.getImageData(0, 0, canvas.width, canvas.height).data;
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
URL.revokeObjectURL(url);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
/**
|
|
185
|
+
* Whether outlines draw as the browser drew the SVG: the engine's picture and
|
|
186
|
+
* the browser's, over white at twice the box, differ by at most 3 a channel
|
|
187
|
+
* on average, and by more than 64 at no more than 1% of pixels. Anything else
|
|
188
|
+
* (an effect the outlines could not carry) and the logo travels as pixels.
|
|
189
|
+
*/
|
|
190
|
+
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;
|
|
194
|
+
const theirs = await browserPixels(svg, box, 2);
|
|
195
|
+
if (ours.length !== theirs.length)
|
|
196
|
+
return false;
|
|
197
|
+
let total = 0;
|
|
198
|
+
let far = 0;
|
|
199
|
+
for (let i = 0; i < ours.length; i += 4) {
|
|
200
|
+
let worst = 0;
|
|
201
|
+
for (let k = 0; k < 3; k++) {
|
|
202
|
+
const diff = Math.abs((ours[i + k] ?? 0) - (theirs[i + k] ?? 0));
|
|
203
|
+
total += diff;
|
|
204
|
+
worst = Math.max(worst, diff);
|
|
205
|
+
}
|
|
206
|
+
if (worst > 64)
|
|
207
|
+
far++;
|
|
208
|
+
}
|
|
209
|
+
const pixels = ours.length / 4;
|
|
210
|
+
return total / (pixels * 3) <= 3 && far / pixels <= 0.01;
|
|
211
|
+
};
|
|
212
|
+
// ---- Fonts ----
|
|
213
|
+
const fontFiles = new Map();
|
|
214
|
+
/** The font file the page uses for a family, weight and style, from its own @font-face rules. */
|
|
215
|
+
const fontFile = (family, weight, style) => {
|
|
216
|
+
const key = `${family}|${weight}|${style}`;
|
|
217
|
+
if (!fontFiles.has(key)) {
|
|
218
|
+
fontFiles.set(key, (async () => {
|
|
219
|
+
let best;
|
|
220
|
+
for (const sheet of document.styleSheets) {
|
|
221
|
+
let rules;
|
|
222
|
+
try {
|
|
223
|
+
rules = sheet.cssRules;
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
for (const rule of rules) {
|
|
229
|
+
if (!(rule instanceof CSSFontFaceRule))
|
|
230
|
+
continue;
|
|
231
|
+
const name = rule.style.getPropertyValue('font-family').replace(/["']/g, '').trim();
|
|
232
|
+
if (name.toLowerCase() !== family.toLowerCase())
|
|
233
|
+
continue;
|
|
234
|
+
if ((rule.style.getPropertyValue('font-style').trim() || 'normal') !== style)
|
|
235
|
+
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
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (!best)
|
|
247
|
+
return undefined;
|
|
248
|
+
try {
|
|
249
|
+
return opentype.parse(await (await fetch(best.url)).arrayBuffer());
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
return undefined;
|
|
253
|
+
}
|
|
254
|
+
})());
|
|
255
|
+
}
|
|
256
|
+
return fontFiles.get(key);
|
|
257
|
+
};
|
|
258
|
+
const styleOf = (element) => {
|
|
259
|
+
const css = getComputedStyle(element);
|
|
260
|
+
return {
|
|
261
|
+
family: (css.fontFamily.split(',')[0] ?? '').replace(/["']/g, '').trim(),
|
|
262
|
+
weight: Number(css.fontWeight) || 400,
|
|
263
|
+
style: css.fontStyle === 'italic' || css.fontStyle === 'oblique' ? 'italic' : 'normal',
|
|
264
|
+
size: parseFloat(css.fontSize),
|
|
265
|
+
colour: solid(hex(css.color) ?? '#000000'),
|
|
266
|
+
spacing: css.letterSpacing === 'normal' ? 0 : parseFloat(css.letterSpacing) || 0,
|
|
267
|
+
...(css.textTransform === 'uppercase' || css.textTransform === 'lowercase' ? { transform: css.textTransform } : {}),
|
|
268
|
+
tabular: css.fontVariantNumeric.includes('tabular'),
|
|
269
|
+
};
|
|
270
|
+
};
|
|
271
|
+
/** 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) => {
|
|
273
|
+
const runs = [];
|
|
274
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
275
|
+
const range = document.createRange();
|
|
276
|
+
const measure = document.createElement('canvas').getContext('2d');
|
|
277
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
278
|
+
const parent = node.parentElement;
|
|
279
|
+
if (!parent || parent.closest('svg') || !node.textContent?.trim())
|
|
280
|
+
continue;
|
|
281
|
+
if (getComputedStyle(parent).visibility === 'hidden')
|
|
282
|
+
continue;
|
|
283
|
+
const css = getComputedStyle(parent);
|
|
284
|
+
measure.font = `${css.fontStyle} ${css.fontWeight} ${css.fontSize} ${css.fontFamily}`;
|
|
285
|
+
const ascent = measure.measureText('Hg').fontBoundingBoxAscent;
|
|
286
|
+
const style = styleOf(parent);
|
|
287
|
+
let line;
|
|
288
|
+
let offset = 0;
|
|
289
|
+
for (const char of node.textContent) {
|
|
290
|
+
range.setStart(node, offset);
|
|
291
|
+
range.setEnd(node, offset + char.length);
|
|
292
|
+
offset += char.length;
|
|
293
|
+
const rect = range.getBoundingClientRect();
|
|
294
|
+
if (rect.width === 0 && /\s/.test(char)) {
|
|
295
|
+
if (line) {
|
|
296
|
+
line.text += ' ';
|
|
297
|
+
line.chars.push({ left: rect.left - origin.left, right: rect.left - origin.left });
|
|
298
|
+
}
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
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 };
|
|
303
|
+
runs.push(line);
|
|
304
|
+
}
|
|
305
|
+
line.text += /\s/.test(char) ? ' ' : char;
|
|
306
|
+
line.chars.push({ left: rect.left - origin.left, right: rect.right - origin.left });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return runs;
|
|
310
|
+
};
|
|
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();
|
|
322
|
+
}
|
|
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();
|
|
329
|
+
}
|
|
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;
|
|
345
|
+
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
|
+
},
|
|
351
|
+
};
|
|
352
|
+
};
|
|
353
|
+
/** 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) => {
|
|
355
|
+
const out = [];
|
|
356
|
+
const all = [root, ...root.querySelectorAll('*')];
|
|
357
|
+
for (const element of all) {
|
|
358
|
+
if (element.closest('svg') && element.tagName.toLowerCase() !== 'svg')
|
|
359
|
+
continue;
|
|
360
|
+
const css = getComputedStyle(element);
|
|
361
|
+
if (css.display === 'none' || css.visibility === 'hidden')
|
|
362
|
+
continue;
|
|
363
|
+
const rect = element.getBoundingClientRect();
|
|
364
|
+
if (rect.width === 0 || rect.height === 0)
|
|
365
|
+
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 } : {}) };
|
|
371
|
+
const tag = element.tagName.toLowerCase();
|
|
372
|
+
if (tag !== 'svg' && tag !== 'img') {
|
|
373
|
+
const fill = element === root ? undefined : hex(css.backgroundColor);
|
|
374
|
+
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) {
|
|
382
|
+
try {
|
|
383
|
+
const image = await loaded(src);
|
|
384
|
+
const key = `image${Object.keys(images).length}`;
|
|
385
|
+
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);
|
|
392
|
+
}, box);
|
|
393
|
+
out.push({ type: 'image', image: key, ...shape });
|
|
394
|
+
}
|
|
395
|
+
catch {
|
|
396
|
+
problems.push(`a background image (${src}) could not be read: it must be served from this site, or allow it (CORS)`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
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
|
+
}
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
// An SVG logo, inline or by <img>: its outlines when they draw as the browser drew it, else its pixels.
|
|
436
|
+
let svg = tag === 'svg' ? element : undefined;
|
|
437
|
+
let holder;
|
|
438
|
+
const src = tag === 'img' ? element.currentSrc || element.src : '';
|
|
439
|
+
if (tag === 'img' && /\.svg(\?|#|$)|^data:image\/svg\+xml/i.test(src)) {
|
|
440
|
+
try {
|
|
441
|
+
const text = await (await fetch(src)).text();
|
|
442
|
+
const parsed = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement;
|
|
443
|
+
if (parsed.tagName.toLowerCase() === 'svg') {
|
|
444
|
+
holder = document.createElement('div');
|
|
445
|
+
holder.style.cssText = `position:fixed;left:${rect.left}px;top:${rect.top}px;width:${rect.width}px;height:${rect.height}px;visibility:hidden;pointer-events:none`;
|
|
446
|
+
const inline = document.importNode(parsed, true);
|
|
447
|
+
inline.setAttribute('width', String(rect.width));
|
|
448
|
+
inline.setAttribute('height', String(rect.height));
|
|
449
|
+
holder.appendChild(inline);
|
|
450
|
+
document.body.appendChild(holder);
|
|
451
|
+
svg = inline;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
catch {
|
|
455
|
+
// Read as pixels below.
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
try {
|
|
459
|
+
if (svg && engine) {
|
|
460
|
+
const paths = svgPaths(svg, origin);
|
|
461
|
+
const local = svgPaths(svg, origin, [box.left, box.top]);
|
|
462
|
+
if (paths && local && paths.length > 0 && (await drawsAlike(svg, box, local))) {
|
|
463
|
+
out.push(...paths);
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
const key = `image${Object.keys(images).length}`;
|
|
468
|
+
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))) };
|
|
473
|
+
}
|
|
474
|
+
else {
|
|
475
|
+
const image = element;
|
|
476
|
+
images[key] = capturePixels((context, width, height) => context.drawImage(image, 0, 0, width, height), box);
|
|
477
|
+
}
|
|
478
|
+
out.push({ type: 'image', image: key, ...shape });
|
|
479
|
+
}
|
|
480
|
+
catch {
|
|
481
|
+
problems.push(`an image (${src || 'inline'}) could not be read: it must be served from this site, or allow it (CORS)`);
|
|
482
|
+
}
|
|
483
|
+
finally {
|
|
484
|
+
holder?.remove();
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return out;
|
|
488
|
+
};
|
|
489
|
+
const FACT_LIKE = [
|
|
490
|
+
['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],
|
|
492
|
+
['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
|
+
['an address', /\S+[$@]\S+\.\S+/],
|
|
494
|
+
];
|
|
495
|
+
/**
|
|
496
|
+
* Captures a preview as a BoundView: the preview's own element, laid out as
|
|
497
|
+
* the sender sees it, and the unsigned document it shows. Every fact found in
|
|
498
|
+
* the preview is bound to its field; the result passes every check a
|
|
499
|
+
* receiver runs, or this throws with what is wrong.
|
|
500
|
+
*/
|
|
501
|
+
export const snapshotBoundView = async (preview, document, { engine, onWarning = (warning) => console.warn(`[BoundView] ${warning}`) } = {}) => {
|
|
502
|
+
const origin = preview.getBoundingClientRect();
|
|
503
|
+
const problems = [];
|
|
504
|
+
let canVerify = false;
|
|
505
|
+
if (engine !== undefined) {
|
|
506
|
+
try {
|
|
507
|
+
await initBoundViewEngine(engine);
|
|
508
|
+
canVerify = true;
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
onWarning('the drawing engine could not be loaded: SVG logos travel as pixels');
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
const images = {};
|
|
515
|
+
const shapes = await paint(preview, origin, images, problems, canVerify);
|
|
516
|
+
const runs = textRuns(preview, origin);
|
|
517
|
+
const segments = bindRuns(document, runs);
|
|
518
|
+
// A font a style: its own glyphs, read from the page's font file, or the bundled font with its widths.
|
|
519
|
+
const styles = new Map();
|
|
520
|
+
for (const segment of segments) {
|
|
521
|
+
const { style } = runs[segment.run];
|
|
522
|
+
const key = `${style.family}|${style.weight}|${style.style}|${style.tabular}`;
|
|
523
|
+
styles.set(key, { style, segments: [...(styles.get(key)?.segments ?? []), segment] });
|
|
524
|
+
}
|
|
525
|
+
if (styles.size > 4)
|
|
526
|
+
problems.push(`the preview uses ${styles.size} fonts; a BoundView carries at most 4`);
|
|
527
|
+
const fonts = {};
|
|
528
|
+
const fontKey = new Map();
|
|
529
|
+
let index = 0;
|
|
530
|
+
for (const [key, { style, segments: used }] of styles) {
|
|
531
|
+
const characters = new Set();
|
|
532
|
+
for (const segment of used) {
|
|
533
|
+
const run = runs[segment.run];
|
|
534
|
+
const text = segment.bind
|
|
535
|
+
? (() => {
|
|
536
|
+
const value = boundValue(document, segment.bind.field);
|
|
537
|
+
return value ? writtenValue(value, segment.bind) : '';
|
|
538
|
+
})()
|
|
539
|
+
: [...run.text].slice(segment.from, segment.to).join('');
|
|
540
|
+
// 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)
|
|
544
|
+
characters.add(char);
|
|
545
|
+
}
|
|
546
|
+
const file = await fontFile(style.family, style.weight, style.style);
|
|
547
|
+
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(', ')}`);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
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;
|
|
565
|
+
fontKey.set(key, name);
|
|
566
|
+
}
|
|
567
|
+
// The text: each fact bound to its field, each of the sender's words a label, on its own baseline.
|
|
568
|
+
const texts = [];
|
|
569
|
+
for (const segment of segments) {
|
|
570
|
+
const run = runs[segment.run];
|
|
571
|
+
const { style } = run;
|
|
572
|
+
const font = fontKey.get(`${style.family}|${style.weight}|${style.style}|${style.tabular}`);
|
|
573
|
+
const table = fonts[font];
|
|
574
|
+
const first = run.chars[segment.from];
|
|
575
|
+
const last = run.chars[segment.to - 1];
|
|
576
|
+
const base = {
|
|
577
|
+
x: r2(first.left),
|
|
578
|
+
y: run.baseline,
|
|
579
|
+
align: 'start',
|
|
580
|
+
font,
|
|
581
|
+
size: r2(style.size),
|
|
582
|
+
colour: style.colour,
|
|
583
|
+
...(style.spacing && { letterSpacing: r2(Math.max(-10, Math.min(50, style.spacing))) }),
|
|
584
|
+
...(style.transform && { transform: style.transform }),
|
|
585
|
+
};
|
|
586
|
+
if (segment.bind) {
|
|
587
|
+
// A fact's box is as wide as its value drawn with these glyphs, so every receiver measures the same.
|
|
588
|
+
const value = boundValue(document, segment.bind.field);
|
|
589
|
+
const text = value ? writtenValue(value, segment.bind) : '';
|
|
590
|
+
const shown = style.transform === 'uppercase' ? text.toUpperCase() : style.transform === 'lowercase' ? text.toLowerCase() : text;
|
|
591
|
+
const chars = [...shown];
|
|
592
|
+
const width = chars.reduce((sum, char, i) => {
|
|
593
|
+
const glyph = table.glyphs?.[char];
|
|
594
|
+
const kerning = table.kerning?.[`${char}${chars[i + 1] ?? ''}`] ?? 0;
|
|
595
|
+
return sum + ((glyph?.advance ?? 0) + kerning) * (style.size / table.unitsPerEm) + (style.spacing ?? 0);
|
|
596
|
+
}, 0);
|
|
597
|
+
texts.push({ type: 'text', bind: segment.bind, ...base, width: ceil2(width) });
|
|
598
|
+
}
|
|
599
|
+
else {
|
|
600
|
+
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)) });
|
|
602
|
+
for (const [what, pattern] of FACT_LIKE) {
|
|
603
|
+
if (pattern.test(text))
|
|
604
|
+
onWarning(`"${text}" looks like ${what} but is not bound to the signed data`);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
const background = hex(getComputedStyle(preview).backgroundColor);
|
|
609
|
+
const view = {
|
|
610
|
+
format: 1,
|
|
611
|
+
page: { width: ceil2(origin.width), height: ceil2(origin.height), ...(background && { background: solid(background) }) },
|
|
612
|
+
...(Object.keys(fonts).length > 0 && { fonts }),
|
|
613
|
+
...(Object.keys(images).length > 0 && { images }),
|
|
614
|
+
elements: [...shapes, ...texts],
|
|
615
|
+
};
|
|
616
|
+
if (problems.length > 0)
|
|
617
|
+
throw new BoundViewSnapshotError('The preview cannot be sent as a BoundView', problems);
|
|
618
|
+
const parsed = BtpBoundViewSchema.safeParse(view);
|
|
619
|
+
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}`));
|
|
621
|
+
}
|
|
622
|
+
const result = checkBoundView(document, parsed.data);
|
|
623
|
+
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}`)));
|
|
625
|
+
}
|
|
626
|
+
return parsed.data;
|
|
627
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright (c) 2025 Bhupendra Tamang
|
|
4
|
+
* Licensed under the Apache License, Version 2.0
|
|
5
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
*/
|
|
7
|
+
type Point = [number, number];
|
|
8
|
+
/** An affine transform, as SVG's matrix(a b c d e f). */
|
|
9
|
+
export type Matrix = [number, number, number, number, number, number];
|
|
10
|
+
export type Command = {
|
|
11
|
+
type: 'M' | 'L';
|
|
12
|
+
to: Point;
|
|
13
|
+
} | {
|
|
14
|
+
type: 'Q';
|
|
15
|
+
c1: Point;
|
|
16
|
+
to: Point;
|
|
17
|
+
} | {
|
|
18
|
+
type: 'C';
|
|
19
|
+
c1: Point;
|
|
20
|
+
c2: Point;
|
|
21
|
+
to: Point;
|
|
22
|
+
} | {
|
|
23
|
+
type: 'Z';
|
|
24
|
+
};
|
|
25
|
+
/** SVG path data as absolute M, L, Q, C and Z, or undefined when it cannot be read. */
|
|
26
|
+
export declare const normalizePath: (d: string) => Command[] | undefined;
|
|
27
|
+
/** Commands placed on the page by `matrix`, written as BoundView path data. */
|
|
28
|
+
export declare const pathData: (commands: Command[], matrix: Matrix) => string;
|
|
29
|
+
/** A basic shape's outline, as path data in its own coordinates. */
|
|
30
|
+
export declare const shapeOutline: (tag: string, attr: (name: string) => number) => string | undefined;
|
|
31
|
+
export {};
|