@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.d.ts CHANGED
@@ -9,8 +9,13 @@ export type BundledFontName = 'arimo' | 'tinos' | 'cousine' | 'carlito' | 'calad
9
9
  export type BundledFonts = Partial<Record<BundledFontName, BTPBoundViewFont>>;
10
10
  /** What each fallback name is drawn with: the bundled font of that name, or the bundled one of that kind. */
11
11
  export declare const FALLBACK_FONT: Record<string, BundledFontName>;
12
- /** The bundled fonts named, each loaded once. */
13
- export declare const loadBundledFonts: (names: Iterable<BundledFontName>) => Promise<BundledFonts>;
12
+ /**
13
+ * The bundled fonts named, each loaded once: its Latin and Latin-1, and its other characters as well only where
14
+ * `characters` has one Latin-1 does not.
15
+ */
16
+ export declare const loadBundledFonts: (names: Iterable<BundledFontName>, characters?: Iterable<string>) => Promise<BundledFonts>;
17
+ /** The characters a BoundView's bundled fonts may be asked for: its labels', and a typed signature's. */
18
+ export declare const bundledCharactersFor: (document: Record<string, unknown>, view: BTPBoundView) => string[];
14
19
  /**
15
20
  * The bundled fonts a BoundView needs to be drawn: a label's fallbacks, when
16
21
  * a character of it has no glyph in its own font, and Caveat for a typed
package/dist/glyphs.js CHANGED
@@ -23,9 +23,44 @@ export const FALLBACK_FONT = {
23
23
  serif: 'tinos',
24
24
  monospace: 'cousine',
25
25
  };
26
- /** The bundled fonts named, each loaded once. */
27
- export const loadBundledFonts = async (names) => Object.fromEntries(await Promise.all([...new Set(names)].map(async (name) => [name, (await LOADERS[name]()).default])));
26
+ /** Each font's characters beyond Latin-1 (Latin extended, Greek, Cyrillic, currency signs…), its own module too. */
27
+ const MORE = {
28
+ arimo: () => import('./glyphs/arimo-more.json', { with: { type: 'json' } }),
29
+ tinos: () => import('./glyphs/tinos-more.json', { with: { type: 'json' } }),
30
+ cousine: () => import('./glyphs/cousine-more.json', { with: { type: 'json' } }),
31
+ carlito: () => import('./glyphs/carlito-more.json', { with: { type: 'json' } }),
32
+ caladea: () => import('./glyphs/caladea-more.json', { with: { type: 'json' } }),
33
+ caveat: () => import('./glyphs/caveat-more.json', { with: { type: 'json' } }),
34
+ };
35
+ /**
36
+ * The bundled fonts named, each loaded once: its Latin and Latin-1, and its other characters as well only where
37
+ * `characters` has one Latin-1 does not.
38
+ */
39
+ export const loadBundledFonts = async (names, characters = []) => {
40
+ const wanted = [...characters];
41
+ return Object.fromEntries(await Promise.all([...new Set(names)].map(async (name) => {
42
+ const core = (await LOADERS[name]()).default;
43
+ if (!wanted.some((char) => core.glyphs?.[char] === undefined))
44
+ return [name, core];
45
+ const more = (await MORE[name]()).default;
46
+ return [name, { ...core, glyphs: { ...core.glyphs, ...more.glyphs } }];
47
+ })));
48
+ };
28
49
  const transformed = (text, transform) => transform === 'uppercase' ? text.toUpperCase() : transform === 'lowercase' ? text.toLowerCase() : text;
50
+ /** The characters a BoundView's bundled fonts may be asked for: its labels', and a typed signature's. */
51
+ export const bundledCharactersFor = (document, view) => {
52
+ const characters = new Set();
53
+ for (const element of view.elements) {
54
+ if (element.type === 'label')
55
+ for (const char of transformed(element.text, element.transform))
56
+ characters.add(char);
57
+ }
58
+ const signatory = document.signatory;
59
+ if (signatory?.visualSignature?.type === 'typed')
60
+ for (const char of signatory.visualSignature.text ?? '')
61
+ characters.add(char);
62
+ return [...characters];
63
+ };
29
64
  /**
30
65
  * The bundled fonts a BoundView needs to be drawn: a label's fallbacks, when
31
66
  * a character of it has no glyph in its own font, and Caveat for a typed
@@ -47,8 +82,11 @@ export const bundledFontsFor = (document, view) => {
47
82
  }
48
83
  if (element.type === 'signature') {
49
84
  const signatory = document.signatory;
50
- if (signatory?.visualSignature?.type === 'typed')
85
+ // In Caveat, and what Caveat has no glyph for (another script) in Arimo.
86
+ if (signatory?.visualSignature?.type === 'typed') {
51
87
  names.add('caveat');
88
+ names.add('arimo');
89
+ }
52
90
  }
53
91
  }
54
92
  return [...names];
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
  export { renderBoundView, initBoundViewEngine, type BoundViewEngineSource } from './render.js';
8
- export { boundViewToSvg, SIGNATURE_STROKE } from './svg.js';
9
- export { bundledFontsFor, loadBundledFonts, type BundledFontName, type BundledFonts } from './glyphs.js';
10
- export { snapshotBoundView, BoundViewSnapshotError, type SnapshotOptions } from './snapshot/index.js';
8
+ export { boundViewToSvg } from './svg.js';
9
+ export { SIGNATURE_STROKE, signatureDrawing, signatureSvg, type SignatureDrawing, } from './signature.js';
10
+ export { bundledCharactersFor, bundledFontsFor, loadBundledFonts, type BundledFontName, type BundledFonts, } from './glyphs.js';
11
+ export { snapshotBoundView, BoundViewSnapshotError, type SnapshotOptions, } from './snapshot/index.js';
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
  export { renderBoundView, initBoundViewEngine } from './render.js';
8
- export { boundViewToSvg, SIGNATURE_STROKE } from './svg.js';
9
- export { bundledFontsFor, loadBundledFonts } from './glyphs.js';
10
- export { snapshotBoundView, BoundViewSnapshotError } from './snapshot/index.js';
8
+ export { boundViewToSvg } from './svg.js';
9
+ export { SIGNATURE_STROKE, signatureDrawing, signatureSvg, } from './signature.js';
10
+ export { bundledCharactersFor, bundledFontsFor, loadBundledFonts, } from './glyphs.js';
11
+ export { snapshotBoundView, BoundViewSnapshotError, } from './snapshot/index.js';
package/dist/render.js CHANGED
@@ -13,7 +13,7 @@
13
13
  import { initWasm, Resvg } from '@resvg/resvg-wasm';
14
14
  import { boundViewResultOf } from '@btps/sdk/boundview';
15
15
  import { boundViewToSvg } from './svg.js';
16
- import { bundledFontsFor, loadBundledFonts } from './glyphs.js';
16
+ import { bundledCharactersFor, bundledFontsFor, loadBundledFonts } from './glyphs.js';
17
17
  let engine;
18
18
  /**
19
19
  * Loads the drawing engine once. In Node it is read from the package by
@@ -28,6 +28,10 @@ export const initBoundViewEngine = (source) => {
28
28
  const wasm = createRequire(import.meta.url).resolve('@resvg/resvg-wasm/index_bg.wasm');
29
29
  return initWasm(await readFile(wasm));
30
30
  })();
31
+ // A load that failed (a wrong URL, a network error) is not kept: the next call tries again.
32
+ engine.catch(() => {
33
+ engine = undefined;
34
+ });
31
35
  return engine;
32
36
  };
33
37
  /**
@@ -41,10 +45,18 @@ export const renderBoundView = async (document, { scale = 2 } = {}) => {
41
45
  return null;
42
46
  await initBoundViewEngine();
43
47
  const doc = document;
44
- const bundled = await loadBundledFonts(bundledFontsFor(doc, doc.boundView));
48
+ const bundled = await loadBundledFonts(bundledFontsFor(doc, doc.boundView), bundledCharactersFor(doc, doc.boundView));
45
49
  const resvg = new Resvg(boundViewToSvg(doc, doc.boundView, bundled), {
46
50
  fitTo: { mode: 'zoom', value: scale },
47
51
  font: { loadSystemFonts: false },
48
52
  });
49
- return resvg.render().asPng();
53
+ // The engine's memory is its own (WebAssembly), freed by hand: an app that draws many documents never runs out.
54
+ const image = resvg.render();
55
+ try {
56
+ return image.asPng();
57
+ }
58
+ finally {
59
+ image.free();
60
+ resvg.free();
61
+ }
50
62
  };
@@ -0,0 +1,35 @@
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
+ /** The pen's width, in units of the 1,000 by 300 canvas; a dot is this wide. */
8
+ export declare const SIGNATURE_STROKE = 8;
9
+ /** A number as a drawing writes it: finite, at most four decimals. */
10
+ export declare const n: (value: number) => string;
11
+ /** A drawn signature's shapes, each attribute as the drawing writes it: a disc for each dot, one path through the rest. */
12
+ export interface SignatureDrawing {
13
+ dots: {
14
+ cx: string;
15
+ cy: string;
16
+ r: string;
17
+ }[];
18
+ line: {
19
+ d: string;
20
+ strokeWidth: string;
21
+ } | null;
22
+ }
23
+ /**
24
+ * A drawn signature as a platform shows it on its page, on the 1,000 by 300 canvas (viewBox "0 0 1000 300"): a circle for
25
+ * each of `dots`, then `line` as a path with no fill, round caps and joins, all in the ink of the page. Drawn so, a
26
+ * snapshot finds it as the signature, and the engine draws it the same.
27
+ */
28
+ export declare const signatureDrawing: (strokes: readonly (readonly number[])[]) => SignatureDrawing;
29
+ /**
30
+ * The same as SVG markup, fitted as `at` and `scale` place it, in `colour`: what the engine draws. A colour that is not
31
+ * one (COLOUR) is refused, never written into the markup.
32
+ */
33
+ export declare const signatureShapes: (strokes: readonly (readonly number[])[], at: (x: number, y: number) => [number, number], scale: number, given: string) => string[];
34
+ /** The same as a whole SVG on its canvas, `colour` its ink (the page's text colour by default). */
35
+ export declare const signatureSvg: (strokes: readonly (readonly number[])[], colour?: string) => string;
@@ -0,0 +1,86 @@
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
+ * A drawn signature, by one rule: the engine draws it in a BoundView by it,
9
+ * and a platform shows `signatureSvg` on its page, so the two cannot differ
10
+ * whatever the strokes are. On its 1,000 by 300 canvas, each stroke's points
11
+ * in order, a point repeated at once counted once; a stroke of one point is a
12
+ * disc as wide as the pen, any other a line through its points, the pen
13
+ * SIGNATURE_STROKE wide with round ends and joins. Nothing else is read from
14
+ * a stroke, and nothing of a page's markup is taken in.
15
+ */
16
+ /** The pen's width, in units of the 1,000 by 300 canvas; a dot is this wide. */
17
+ export const SIGNATURE_STROKE = 8;
18
+ /** A number as a drawing writes it: finite, at most four decimals. */
19
+ export const n = (value) => Number.isFinite(value) ? String(Math.round(value * 10000) / 10000) : '0';
20
+ /** A stroke's points as pairs, in order, a point repeated at once counted once. */
21
+ const pointsOf = (stroke) => {
22
+ const points = [];
23
+ for (let i = 0; i + 1 < stroke.length; i += 2) {
24
+ const point = [stroke[i], stroke[i + 1]];
25
+ const last = points.at(-1);
26
+ if (last === undefined || last[0] !== point[0] || last[1] !== point[1])
27
+ points.push(point);
28
+ }
29
+ return points;
30
+ };
31
+ /**
32
+ * The shapes of `strokes`, each canvas point placed by `at`, the pen `scale` times its canvas width: a disc for each
33
+ * stroke of one point, then one path through every other. Everything that draws a signature is made from it.
34
+ */
35
+ const drawingOf = (strokes, at, scale) => {
36
+ const dots = [];
37
+ const lines = [];
38
+ for (const stroke of strokes) {
39
+ const points = pointsOf(stroke).map(([x, y]) => at(x, y));
40
+ const [first] = points;
41
+ if (first === undefined)
42
+ continue;
43
+ if (points.length === 1)
44
+ dots.push({ cx: n(first[0]), cy: n(first[1]), r: n((SIGNATURE_STROKE * scale) / 2) });
45
+ else
46
+ lines.push(points.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${n(x)} ${n(y)}`).join(''));
47
+ }
48
+ return {
49
+ dots,
50
+ line: lines.length > 0 ? { d: lines.join(''), strokeWidth: n(SIGNATURE_STROKE * scale) } : null,
51
+ };
52
+ };
53
+ /**
54
+ * A drawn signature as a platform shows it on its page, on the 1,000 by 300 canvas (viewBox "0 0 1000 300"): a circle for
55
+ * each of `dots`, then `line` as a path with no fill, round caps and joins, all in the ink of the page. Drawn so, a
56
+ * snapshot finds it as the signature, and the engine draws it the same.
57
+ */
58
+ export const signatureDrawing = (strokes) => drawingOf(strokes, (x, y) => [x, y], 1);
59
+ /** A colour a signature is drawn in: `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`, or the page's own, `currentColor`. */
60
+ const COLOUR = /^(?:#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})|currentColor)$/;
61
+ /**
62
+ * `colour` as it is written into markup: never the string given, but `currentColor`, or its hex digits read as numbers
63
+ * and written again. One that is not a colour (COLOUR) is refused.
64
+ */
65
+ const inkOf = (colour) => {
66
+ if (!COLOUR.test(colour))
67
+ throw new TypeError(`a signature's colour is a hex colour or currentColor, not ${JSON.stringify(colour)}`);
68
+ if (colour === 'currentColor')
69
+ return 'currentColor';
70
+ return `#${[...colour.slice(1)].map((digit) => parseInt(digit, 16).toString(16)).join('')}`;
71
+ };
72
+ /**
73
+ * The same as SVG markup, fitted as `at` and `scale` place it, in `colour`: what the engine draws. A colour that is not
74
+ * one (COLOUR) is refused, never written into the markup.
75
+ */
76
+ export const signatureShapes = (strokes, at, scale, given) => {
77
+ const colour = inkOf(given);
78
+ const { dots, line } = drawingOf(strokes, at, scale);
79
+ const shapes = dots.map(({ cx, cy, r }) => `<circle cx="${cx}" cy="${cy}" r="${r}" fill="${colour}"/>`);
80
+ if (line) {
81
+ shapes.push(`<path d="${line.d}" fill="none" stroke="${colour}" stroke-width="${line.strokeWidth}" stroke-linecap="round" stroke-linejoin="round"/>`);
82
+ }
83
+ return shapes;
84
+ };
85
+ /** The same as a whole SVG on its canvas, `colour` its ink (the page's text colour by default). */
86
+ export const signatureSvg = (strokes, colour = 'currentColor') => `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 300">${signatureShapes(strokes, (x, y) => [x, y], 1, colour).join('')}</svg>`;
@@ -13,8 +13,17 @@ export type Run = {
13
13
  left: number;
14
14
  right: number;
15
15
  }[];
16
- /** The line's baseline, used to tell rows of a table apart. */
16
+ /** The line's baseline. */
17
17
  baseline: number;
18
+ /** The line's top and bottom; a pixel either side of its baseline when not given. */
19
+ top?: number;
20
+ bottom?: number;
21
+ /** Which text node it is a line of: the lines of one node are one text, wrapped. */
22
+ node?: number;
23
+ /** Which block it flows in: text in inline elements of one block wraps from one element into the next. */
24
+ block?: number;
25
+ /** Its font size in pixels. */
26
+ size?: number;
18
27
  };
19
28
  type Bind = {
20
29
  field: string;
@@ -55,9 +64,9 @@ export declare const bindableFields: (document: Doc) => {
55
64
  }[];
56
65
  /**
57
66
  * Binds the preview's runs to `document`'s fields. Line items first, a row at
58
- * a time on its own band, so a line's amount is never taken for a total;
59
- * then every other field, the longest writing first, every place it appears.
60
- * Whatever is left is the sender's own words.
67
+ * a time where its cells stand together, so a line's amount is never taken for
68
+ * a total; then every other field, the longest writing first. Fields written
69
+ * alike share their places. Whatever is left is the sender's own words.
61
70
  */
62
71
  export declare const bindRuns: (document: Doc, runs: Run[]) => Segment[];
63
72
  export {};