resvg-napi 0.0.0-probe.1788204851 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 resvg-napi contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,205 @@
1
+ # resvg-napi
2
+
3
+ [![npm](https://img.shields.io/npm/v/resvg-napi)](https://www.npmjs.com/package/resvg-napi)
4
+ [![conformance](https://img.shields.io/badge/resvg%20conformance-1715%2F1715-brightgreen)](#conformance)
5
+ [![licence](https://img.shields.io/npm/l/resvg-napi)](#licence)
6
+
7
+ Node.js bindings for [resvg](https://github.com/linebender/resvg) 0.48: render
8
+ SVG to PNG, and read back what usvg made of the document — the resolved tree,
9
+ text metrics, paint, geometry.
10
+
11
+ Generated from the upstream Rust sources, so the TypeScript surface is usvg's
12
+ own, names and doc comments included.
13
+
14
+ ```bash
15
+ npm install resvg-napi
16
+ ```
17
+
18
+ ```js
19
+ import { Resvg, FontDatabase, renderAsync } from 'resvg-napi'
20
+
21
+ const doc = new Resvg(svg, { dpi: 192, fontFamily: 'DejaVu Sans' })
22
+ doc.renderPng({ width: 1200, background: '#fff' }) // Buffer
23
+ doc.renderRaw({ crop: doc.absLayerBoundingBox() }) // RGBA8, trimmed
24
+ await renderAsync(svg, options, { width: 1200 }) // off the event loop
25
+ ```
26
+
27
+ ## What you can read back
28
+
29
+ `index.d.ts` is the reference — it is generated, so it cannot drift. This is
30
+ the map.
31
+
32
+ **Render.** Parse once with `new Resvg(svg, options?, fonts?, images?)`, then
33
+ render as often as you like.
34
+
35
+ | | |
36
+ |---|---|
37
+ | `renderPng(params?)` | `Buffer` |
38
+ | `renderRaw(params?)` | `RawImage`, un-premultiplied RGBA8 |
39
+ | `toString(opts?)` | the resolved tree, back as SVG |
40
+ | `renderPngAsync` · `renderRawAsync` · `toStringAsync` | the same, off the event loop, `AbortSignal`-aware |
41
+
42
+ `params` carries `width` / `height` / `scale`, a `background` colour and a
43
+ `crop` box. `Resvg.parseAsync` moves the parse off the loop too.
44
+
45
+ **Walk the tree.** `node(id)` and `children()` hand back `SvgNode`s, and each
46
+ one knows what it is:
47
+
48
+ ```js
49
+ const n = doc.node('surname')
50
+ n.kind // 'group' | 'path' | 'image' | 'text'
51
+ n.path() // geometry, fill, stroke — null unless it is a shape
52
+ n.text() // chunks, layouted spans, positioned glyphs, decoration
53
+ n.renderPng() // that element alone, cropped to its own extent
54
+ ```
55
+
56
+ A span carries what it is drawn with, down to the lines through it:
57
+
58
+ ```js
59
+ const span = n.text().chunks[0].spans[0]
60
+ span.decoration.underline?.fill?.paint // …and .overline, .lineThrough
61
+ ```
62
+
63
+ Paint is a discriminated union, so TypeScript narrows it:
64
+
65
+ ```ts
66
+ const paint = n.path()?.fill?.paint
67
+ if (paint?.type === 'color') paint.value // { red, green, blue }
68
+ else paint?.id // the gradient or pattern it names
69
+ ```
70
+
71
+ **Measure.** Every node reports `boundingBox()`, `absBoundingBox()`,
72
+ `strokeBoundingBox()`, `absLayerBoundingBox()` and `extent()` — in the
73
+ document's own units, which is not the canvas. See *Fitting text* below for why
74
+ that distinction bites.
75
+
76
+ **Fonts.** `FontDatabase` is `fontdb` itself: `loadSystemFonts()`,
77
+ `loadFontData(buffer)`, `loadFontFile(path)`, `faces()`, `query()`, and the
78
+ generic-family setters. A face reports its `families`, `weight`, `style`
79
+ (`'normal' | 'italic' | 'oblique'`) and whether it is `monospaced`. `pendingFonts()` on a parsed document names the
80
+ families it wanted and did not get; `pendingImages()` does the same for hrefs.
81
+
82
+ **Definitions.** `linearGradients()`, `radialGradients()`, `patterns()`,
83
+ `clipPaths()`, `masks()`, `filters()` — the paint servers an element's `id`
84
+ refers to.
85
+
86
+ Something missing? The generator keeps a report of every upstream member it
87
+ left alone, with the reason. `RESVG_NAPI_CODEGEN_LOG=1 cargo build` prints it,
88
+ and [CONTRIBUTING.md](CONTRIBUTING.md) explains what the reasons mean.
89
+
90
+ ## Conformance
91
+
92
+ resvg's own test corpus, rendered through these bindings: **1715 of 1715 match**
93
+ the reference PNGs upstream asserts on, within 1/255 per channel — a tolerance
94
+ measured rather than chosen, with the reason recorded in
95
+ [`scripts/conformance.mjs`](scripts/conformance.mjs).
96
+
97
+ ```bash
98
+ npm run conformance:fetch # the corpus, at the tag Cargo.toml pins
99
+ npm run conformance # 15 seconds including the fetch
100
+ ```
101
+
102
+ CI runs it on every pull request, so a resvg bump that changes a render shows up
103
+ as a diff rather than passing unnoticed.
104
+
105
+ ## Platforms
106
+
107
+ Thirteen targets.
108
+
109
+ | | x64 | arm64 | armv7 | ia32 |
110
+ |---|---|---|---|---|
111
+ | Linux (glibc) | ✅ | ✅ | ✅ | — |
112
+ | Linux (musl) | ✅ | ✅ | — | — |
113
+ | macOS | ✅ | ✅ | — | — |
114
+ | Windows (MSVC) | ✅ | ✅ | — | ✅ |
115
+ | Android | — | ✅ | ✅ | — |
116
+ | WASI (`wasm32-wasip1-threads`) | ✅ | — | — | — |
117
+
118
+ The dependency tree is pure Rust — `fontconfig` support comes from
119
+ `fontconfig-parser`, not the C library — so every target cross-compiles without
120
+ a system SDK.
121
+
122
+ The WASI build is the same generated bindings on emnapi instead of node-api, and
123
+ it is complete: rendering, `toString`, bounding boxes, the node walk, `renderAsync`
124
+ (threads via `wasm32-wasip1-threads`) and even filesystem image resolution all
125
+ work. One difference: `loadSystemFonts()` finds 0 faces inside the sandbox, so
126
+ fonts must be supplied with `loadFontData(buffer)` — the demo fetches them from
127
+ google/fonts by name rather than making you find a file.
128
+
129
+ Adding a target is an entry in `scripts/ci-targets.mjs` — which host builds it
130
+ and which cross-compilation flag it needs — and the triple in `package.json`
131
+ under `napi.targets`; then `npm run create-npm-dirs`. The two lists used to be
132
+ independent, so a target could sit in one and not the other; the script now
133
+ fails when they disagree.
134
+
135
+ CI does not build all thirteen on a pull request. It builds the two that can
136
+ tell it something — `x86_64-unknown-linux-gnu`, which the tests, the drift
137
+ checks and the conformance suite run on, and `wasm32-wasip1-threads`, whose
138
+ generated shims and test run are a different code path. The other eleven build
139
+ on the merge, on a `v*` tag, on a manual dispatch, or on a pull request labelled
140
+ `full-matrix` when the proof is wanted before merging rather than after.
141
+
142
+
143
+ ## Fitting text to a width
144
+
145
+ An Illustrator template says how wide a field may be on the element itself
146
+ (`data-maxwidth="85"`), which is not SVG — resvg drops it. `fit.mjs` reads the
147
+ constraint from the source, measures the rendered text with
148
+ `node(id).extent()`, and compresses the element horizontally, composing a
149
+ `scale(k 1)` onto whatever transform it already has (the same device those
150
+ templates use by hand):
151
+
152
+ ```js
153
+ import { fitTextWidths } from 'resvg-napi/fit.mjs'
154
+
155
+ const { svg, adjustments, problems } = fitTextWidths(source,
156
+ (s) => new Resvg(s, { fontFamily }, fonts))
157
+ // adjustments: [{ id: 'surname', from: 200.23, to: 90, factor: 0.4495, measured: 90.0031 }]
158
+ ```
159
+
160
+ The limit is read in **the document's own units**, the ones the attribute is
161
+ written in. That matters: `width="85.6mm"` with a `viewBox` 240.94 wide makes usvg
162
+ normalise the tree to 323.53 units, so `extent()` comes back 1.343× larger than
163
+ anything the file says. Comparing raw canvas widths compresses text that actually
164
+ fits — everything past `limit / 1.343`.
165
+
166
+ No `id` needed: an element that has none gets one generated, numbered in document
167
+ order, so the constraint does not depend on the template carrying ids. The scale
168
+ is anchored at the element's own `x` — a bare `scale()` is anchored at the origin
169
+ and slides the text left as it narrows.
170
+
171
+ A geometric scale is exactly linear in width, so one pass lands on the target;
172
+ the second measurement is a check, and it is reported. Text that already fits is
173
+ left untouched, and a constraint that cannot be honoured says why: no `id` to
174
+ measure by, no visible extent, or an unusable width. It compresses glyphs rather
175
+ than reducing `font-size` — the choice the templates already made.
176
+
177
+ ## Diagnostics
178
+
179
+ usvg and resvg report every recoverable problem through the `log` crate —
180
+ unparsable values, skipped shapes, unmatched font families, images that could not
181
+ be read. Nothing consumes that by default, so those messages used to vanish:
182
+
183
+ ```js
184
+ import { setLogLevel, takeLogs, Resvg } from 'resvg-napi'
185
+
186
+ setLogLevel('warn') // off | error | warn | info | debug | trace
187
+ new Resvg(svg).renderPng()
188
+ takeLogs()
189
+ // [ "WARN usvg::parser::style: Failed to parse fill value: 'notacolour'. Fallback to black.",
190
+ // "WARN usvg::parser::shapes: Rect '' has an invalid 'width' value. Skipped." ]
191
+ ```
192
+
193
+ `takeLogs()` drains the buffer, which is capped at 500 entries so a pathological
194
+ document cannot grow it without end.
195
+
196
+ ## Elsewhere
197
+
198
+ - **[demo/](demo/README.md)** — a browser proof bench: Liquid templating, an
199
+ array editor, per-element export, live diagnostics. `npm run demo`.
200
+ - **[CONTRIBUTING.md](CONTRIBUTING.md)** — how the bindings are generated, and
201
+ what to read before touching `build.rs`.
202
+
203
+ ## Licence
204
+
205
+ Apache-2.0 OR MIT, matching resvg.
package/browser.js ADDED
@@ -0,0 +1 @@
1
+ export * from 'resvg-napi-wasm32-wasi'
package/fit.d.mts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Horizontal text fitting, driven by `data-maxwidth`.
3
+ *
4
+ * Declarations for `fit.mjs`, which is JavaScript with JSDoc: written by hand,
5
+ * unlike `index.d.ts`, so they can drift. `npm run typecheck` reads them.
6
+ */
7
+
8
+ /** A `Resvg` instance, however the caller chose to build one. */
9
+ type Renderer = {
10
+ node(id: string): { extent(): { width: number } | null } | null
11
+ }
12
+
13
+ /** One element carrying a width constraint, and what is needed to rewrite it. */
14
+ export interface WidthConstraint {
15
+ /** The element's opening tag, verbatim. */
16
+ tag: string
17
+ /** The tag name: `text`, `tspan`, ... */
18
+ name: string
19
+ /** The attribute text inside that tag, verbatim. */
20
+ attrs: string
21
+ /** The element's `id`, or null when it had none and one must be generated. */
22
+ id: string | null
23
+ /** The limit, in the document's own units -- not canvas pixels. */
24
+ max: number
25
+ /** Byte offset of the tag in the source string. */
26
+ index: number
27
+ }
28
+
29
+ /** One element that was compressed, and by how much. */
30
+ export interface Adjustment {
31
+ id: string
32
+ /** Measured width before, in the document's units. */
33
+ from: number
34
+ /** The limit it was fitted to. */
35
+ to: number
36
+ /** The horizontal scale applied: `to / from`. */
37
+ factor: number
38
+ /** Measured width after, as a check on the one-pass assumption. */
39
+ measured: number
40
+ }
41
+
42
+ export interface FitResult {
43
+ /** The source, with a `scale(k 1)` composed onto each fitted element. */
44
+ svg: string
45
+ adjustments: Adjustment[]
46
+ /** Constraints that could not be honoured, each saying why. */
47
+ problems: string[]
48
+ }
49
+
50
+ /** Elements carrying a width constraint, with the tag text needed to rewrite it. */
51
+ export function findWidthConstraints(svg: string): WidthConstraint[]
52
+
53
+ /**
54
+ * Fits every `data-maxwidth` element by compressing it horizontally.
55
+ *
56
+ * @param svg source, after any templating
57
+ * @param render `(svg) => Resvg`; supply fonts and options here
58
+ */
59
+ export function fitTextWidths(
60
+ svg: string,
61
+ render: (svg: string) => Renderer,
62
+ ): FitResult
package/fit.mjs ADDED
@@ -0,0 +1,170 @@
1
+ // Horizontal fitting for text that must not exceed a width, the way an
2
+ // Illustrator template expresses it: `data-maxwidth` on the element itself.
3
+ //
4
+ // resvg drops attributes it does not know, so the constraint can only be read
5
+ // from the source. The measurement, on the other hand, comes from the render:
6
+ // `node(id).extent()` is the width the text actually occupies with the fonts in
7
+ // hand -- which is the only number that matters.
8
+ //
9
+ // The correction is a horizontal scale appended to the element's own transform,
10
+ // matching what these templates already do (`scale(1.11 1)`). A pure geometric
11
+ // scale is exactly linear in width, so one pass lands on the target; the second
12
+ // measurement is a check, not an iteration.
13
+
14
+ const ATTR = 'data-maxwidth';
15
+
16
+ /**
17
+ * Ratio between the tree's canvas units and the document's own coordinates.
18
+ *
19
+ * `width="85.6mm" viewBox="0 0 240.94 …"` makes usvg normalise the tree to the
20
+ * physical size (323.53 units at 96 dpi), so `extent()` comes back 1.343× larger
21
+ * than the numbers written in the file. A limit expressed in the document's own
22
+ * units has to be compared in those units, or everything wider than
23
+ * `limit / ratio` gets compressed while it actually fits.
24
+ */
25
+ function unitScale(svg, canvasWidth) {
26
+ const viewBox = svg.match(/\bviewBox\s*=\s*"\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)/);
27
+ const width = viewBox ? Number(viewBox[1]) : NaN;
28
+ if (!Number.isFinite(width) || width <= 0) return 1;
29
+ return canvasWidth / width;
30
+ }
31
+
32
+ /** Elements carrying a width constraint, with the tag text needed to rewrite it. */
33
+ export function findWidthConstraints(svg) {
34
+ const found = [];
35
+ for (const match of svg.matchAll(/<([a-zA-Z][\w:.-]*)\b([^>]*?)(\/?)>/g)) {
36
+ const [tag, name, attrs] = match;
37
+ const max = attrs.match(new RegExp(`${ATTR}\\s*=\\s*"([^"]*)"`))?.[1];
38
+ if (max === undefined) continue;
39
+ const width = Number(max);
40
+ const id = attrs.match(/\bid\s*=\s*"([^"]*)"/)?.[1];
41
+ found.push({ tag, name, attrs, id, max: width, index: match.index });
42
+ }
43
+ return found;
44
+ }
45
+
46
+ /**
47
+ * Appends a horizontal scale to a tag's transform, creating one if absent.
48
+ *
49
+ * Anchored at the element's own `x`: a bare `scale()` is anchored at the origin,
50
+ * which slides the text left as it narrows -- 30.72 to 3.98 on a `x="28"` text.
51
+ * `translate(x) scale(k) translate(-x)` compresses it in place, and collapses to
52
+ * a plain scale when x is 0, which is the case for anything positioned by a
53
+ * transform.
54
+ */
55
+ function withHorizontalScale(tag, attrs, factor) {
56
+ // `x` may be a list for per-glyph positioning; the first value is the anchor.
57
+ const anchor = Number.parseFloat(attrs.match(/\bx\s*=\s*"\s*([-\d.]+)/)?.[1] ?? '0') || 0;
58
+ const scale = anchor
59
+ ? `translate(${round(anchor)} 0) scale(${round(factor)} 1) translate(${round(-anchor)} 0)`
60
+ : `scale(${round(factor)} 1)`;
61
+ const existing = attrs.match(/\btransform\s*=\s*"([^"]*)"/);
62
+ if (existing) {
63
+ // Composed on the right: the element keeps its position, the glyphs
64
+ // compress toward the anchor the transform established.
65
+ return tag.replace(existing[0], `transform="${existing[1].trim()} ${scale}"`);
66
+ }
67
+ return tag.replace(/(\/?)>$/, ` transform="${scale}"$1>`);
68
+ }
69
+
70
+ const round = (n) => Math.round(n * 10000) / 10000;
71
+
72
+ /**
73
+ * Measuring goes through `node(id)`, but a template has no reason to carry ids
74
+ * just to be measurable. Elements that lack one get a generated id, checked
75
+ * against the source so it cannot collide.
76
+ *
77
+ * Insertions run backwards so the offsets still ahead of them stay valid. The
78
+ * caller then re-reads the constraints from the rewritten source: patching the
79
+ * old offsets by hand is how the first version corrupted the document.
80
+ */
81
+ function ensureIds(svg) {
82
+ const missing = findWidthConstraints(svg).filter((c) => !c.id);
83
+ if (!missing.length) return svg;
84
+
85
+ // Numbered in document order, so a diagnostic about `fit-1` refers to the
86
+ // first constrained element, then spliced back to front.
87
+ let n = 0;
88
+ const named = missing.map((c) => {
89
+ let id;
90
+ do {
91
+ id = `fit-${++n}`;
92
+ } while (svg.includes(`"${id}"`));
93
+ return { ...c, id };
94
+ });
95
+
96
+ let out = svg;
97
+ for (const c of named.reverse()) {
98
+ const tagged = c.tag.replace(/^<([a-zA-Z][\w:.-]*)/, `<$1 id="${c.id}"`);
99
+ out = out.slice(0, c.index) + tagged + out.slice(c.index + c.tag.length);
100
+ }
101
+ return out;
102
+ }
103
+
104
+ /**
105
+ * Fits every `data-maxwidth` element by compressing it horizontally.
106
+ *
107
+ * @param svg source, after any templating
108
+ * @param render (svg) => Resvg instance; supply fonts and options here
109
+ * @returns { svg, adjustments, problems }
110
+ */
111
+ export function fitTextWidths(svg, render) {
112
+ const problems = [];
113
+ if (!findWidthConstraints(svg).length) return { svg, adjustments: [], problems };
114
+
115
+ // Every constrained element carries an id from here on, and the offsets are
116
+ // read from this exact string.
117
+ svg = ensureIds(svg);
118
+ const constraints = findWidthConstraints(svg);
119
+
120
+ let doc;
121
+ try {
122
+ doc = render(svg);
123
+ } catch (e) {
124
+ return { svg, adjustments: [], problems: [`could not measure: ${e.message}`] };
125
+ }
126
+
127
+ // Every width below is in the document's own units, like the attribute.
128
+ const scale = unitScale(svg, doc.width);
129
+ let out = svg;
130
+ const adjustments = [];
131
+ const splices = [];
132
+ for (const c of constraints) {
133
+ if (!Number.isFinite(c.max) || c.max <= 0) {
134
+ problems.push(`#${c.id}: ${ATTR}="${c.max}" is not a usable width`);
135
+ continue;
136
+ }
137
+ const extent = doc.node(c.id)?.extent();
138
+ if (!extent) {
139
+ problems.push(`#${c.id} has no visible extent: nothing to fit`);
140
+ continue;
141
+ }
142
+ const width = extent.width / scale;
143
+ if (width <= c.max) continue;
144
+
145
+ const factor = c.max / width;
146
+ splices.push({ index: c.index, length: c.tag.length,
147
+ text: withHorizontalScale(c.tag, c.attrs, factor) });
148
+ adjustments.push({ id: c.id, from: round(width), to: c.max, factor: round(factor) });
149
+ }
150
+
151
+ // Backwards, so each offset still points where it did when it was taken.
152
+ for (const s of splices.sort((a, b) => b.index - a.index)) {
153
+ out = out.slice(0, s.index) + s.text + out.slice(s.index + s.length);
154
+ }
155
+
156
+ if (!adjustments.length) return { svg: out, adjustments, problems };
157
+
158
+ // Verify rather than trust: report what the widths actually became.
159
+ try {
160
+ const after = render(out);
161
+ const afterScale = unitScale(out, after.width);
162
+ for (const a of adjustments) {
163
+ const got = after.node(a.id)?.extent()?.width;
164
+ a.measured = got === undefined ? NaN : round(got / afterScale);
165
+ }
166
+ } catch (e) {
167
+ problems.push(`could not verify: ${e.message}`);
168
+ }
169
+ return { svg: out, adjustments, problems };
170
+ }