qrdx 0.0.45 → 0.0.47

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.
Files changed (206) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -300
  3. package/dist/index.js +27 -7
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +27 -7
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/qr-code-canvas.js +12 -0
  8. package/dist/qr-code-canvas.js.map +1 -0
  9. package/dist/qr-code-canvas.mjs +12 -0
  10. package/dist/qr-code-canvas.mjs.map +1 -0
  11. package/dist/src/api.d.ts.map +1 -1
  12. package/dist/src/art-trace.d.ts +46 -0
  13. package/dist/src/art-trace.d.ts.map +1 -0
  14. package/dist/src/art.d.ts +138 -0
  15. package/dist/src/art.d.ts.map +1 -0
  16. package/dist/src/body-patterns.d.ts +34 -0
  17. package/dist/src/body-patterns.d.ts.map +1 -0
  18. package/dist/src/codegen.d.ts +5 -5
  19. package/dist/src/codegen.d.ts.map +1 -1
  20. package/dist/src/codeword-map.d.ts +40 -0
  21. package/dist/src/codeword-map.d.ts.map +1 -0
  22. package/dist/src/constants.d.ts +4 -7
  23. package/dist/src/constants.d.ts.map +1 -1
  24. package/dist/src/corner-dot.d.ts +3 -1
  25. package/dist/src/corner-dot.d.ts.map +1 -1
  26. package/dist/src/corner-eye.d.ts +5 -2
  27. package/dist/src/corner-eye.d.ts.map +1 -1
  28. package/dist/src/detection.d.ts.map +1 -1
  29. package/dist/src/download.d.ts +22 -5
  30. package/dist/src/download.d.ts.map +1 -1
  31. package/dist/src/eps.d.ts +62 -0
  32. package/dist/src/eps.d.ts.map +1 -0
  33. package/dist/src/frame-icons.d.ts +11 -0
  34. package/dist/src/frame-icons.d.ts.map +1 -0
  35. package/dist/src/frame-import.d.ts +61 -0
  36. package/dist/src/frame-import.d.ts.map +1 -0
  37. package/dist/src/frame-spec.d.ts +24 -0
  38. package/dist/src/frame-spec.d.ts.map +1 -0
  39. package/dist/src/frame-styles.d.ts +50 -0
  40. package/dist/src/frame-styles.d.ts.map +1 -0
  41. package/dist/src/frame.d.ts +126 -0
  42. package/dist/src/frame.d.ts.map +1 -0
  43. package/dist/src/frames/builtin.d.ts +8 -0
  44. package/dist/src/frames/builtin.d.ts.map +1 -0
  45. package/dist/src/frames/official.d.ts +18 -0
  46. package/dist/src/frames/official.d.ts.map +1 -0
  47. package/dist/src/helpers.d.ts +15 -2
  48. package/dist/src/helpers.d.ts.map +1 -1
  49. package/dist/src/index.d.ts +24 -13
  50. package/dist/src/index.d.ts.map +1 -1
  51. package/dist/src/logo-budget.d.ts +54 -0
  52. package/dist/src/logo-budget.d.ts.map +1 -0
  53. package/dist/src/logo-cleanup.d.ts +25 -0
  54. package/dist/src/logo-cleanup.d.ts.map +1 -0
  55. package/dist/src/logo.d.ts +28 -0
  56. package/dist/src/logo.d.ts.map +1 -0
  57. package/dist/src/print.d.ts +73 -0
  58. package/dist/src/print.d.ts.map +1 -0
  59. package/dist/src/qr-code-canvas.d.ts +13 -0
  60. package/dist/src/qr-code-canvas.d.ts.map +1 -0
  61. package/dist/src/qr-code.d.ts +4 -2
  62. package/dist/src/qr-code.d.ts.map +1 -1
  63. package/dist/src/qr-outline.d.ts +41 -0
  64. package/dist/src/qr-outline.d.ts.map +1 -0
  65. package/dist/src/qr-shape.d.ts +72 -0
  66. package/dist/src/qr-shape.d.ts.map +1 -0
  67. package/dist/src/scan-risk.d.ts +40 -0
  68. package/dist/src/scan-risk.d.ts.map +1 -0
  69. package/dist/src/scan-score.d.ts +154 -0
  70. package/dist/src/scan-score.d.ts.map +1 -0
  71. package/dist/src/shapes.d.ts +36 -0
  72. package/dist/src/shapes.d.ts.map +1 -0
  73. package/dist/src/silhouette.d.ts +28 -0
  74. package/dist/src/silhouette.d.ts.map +1 -0
  75. package/dist/src/utils/color.d.ts.map +1 -1
  76. package/dist/src/utils/fmt.d.ts +24 -0
  77. package/dist/src/utils/fmt.d.ts.map +1 -0
  78. package/dist/src/utils/paint.d.ts +80 -0
  79. package/dist/src/utils/paint.d.ts.map +1 -0
  80. package/dist/src/utils/parse-color.d.ts +21 -0
  81. package/dist/src/utils/parse-color.d.ts.map +1 -0
  82. package/dist/src/utils/path-data.d.ts +24 -0
  83. package/dist/src/utils/path-data.d.ts.map +1 -0
  84. package/dist/src/utils/png.d.ts +16 -0
  85. package/dist/src/utils/png.d.ts.map +1 -0
  86. package/dist/src/utils/polygon-clip.d.ts +26 -0
  87. package/dist/src/utils/polygon-clip.d.ts.map +1 -0
  88. package/dist/src/utils/print-shared.d.ts +20 -0
  89. package/dist/src/utils/print-shared.d.ts.map +1 -0
  90. package/dist/src/utils/svg-geometry.d.ts +49 -0
  91. package/dist/src/utils/svg-geometry.d.ts.map +1 -0
  92. package/dist/src/utils/svg-gradient.d.ts +59 -0
  93. package/dist/src/utils/svg-gradient.d.ts.map +1 -0
  94. package/dist/src/utils/svg-painter.d.ts +152 -0
  95. package/dist/src/utils/svg-painter.d.ts.map +1 -0
  96. package/dist/src/utils.d.ts +18 -2
  97. package/dist/src/utils.d.ts.map +1 -1
  98. package/dist/types/art.d.ts +64 -0
  99. package/dist/types/art.d.ts.map +1 -0
  100. package/dist/types/color.d.ts +125 -7
  101. package/dist/types/color.d.ts.map +1 -1
  102. package/dist/types/corner-dot.d.ts +52 -2
  103. package/dist/types/corner-dot.d.ts.map +1 -1
  104. package/dist/types/corner-eye.d.ts +43 -2
  105. package/dist/types/corner-eye.d.ts.map +1 -1
  106. package/dist/types/frame-spec.d.ts +3509 -0
  107. package/dist/types/frame-spec.d.ts.map +1 -0
  108. package/dist/types/frame.d.ts +68 -0
  109. package/dist/types/frame.d.ts.map +1 -0
  110. package/dist/types/image-pattern.d.ts +15 -1
  111. package/dist/types/image-pattern.d.ts.map +1 -1
  112. package/dist/types/index.d.ts +15 -9
  113. package/dist/types/index.d.ts.map +1 -1
  114. package/dist/types/index.js +6 -0
  115. package/dist/types/index.js.map +1 -0
  116. package/dist/types/index.mjs +6 -0
  117. package/dist/types/index.mjs.map +1 -0
  118. package/dist/types/qr.d.ts +1684 -4
  119. package/dist/types/qr.d.ts.map +1 -1
  120. package/dist/types/template.d.ts +2 -2
  121. package/dist/types/template.d.ts.map +1 -1
  122. package/package.json +63 -20
  123. package/src/api.tsx +67 -17
  124. package/src/art-trace.ts +554 -0
  125. package/src/art.tsx +2226 -0
  126. package/src/body-patterns.tsx +389 -0
  127. package/src/codegen.ts +10 -5
  128. package/src/codeword-map.ts +265 -0
  129. package/src/constants.ts +4 -8
  130. package/src/corner-dot.tsx +209 -33
  131. package/src/corner-eye.ts +328 -60
  132. package/src/detection.ts +5 -11
  133. package/src/download.tsx +123 -52
  134. package/src/eps.ts +701 -0
  135. package/src/frame-icons.ts +325 -0
  136. package/src/frame-import.ts +1198 -0
  137. package/src/frame-spec.ts +518 -0
  138. package/src/frame-styles.ts +1095 -0
  139. package/src/frame.tsx +630 -0
  140. package/src/frames/builtin/banner-bottom.json +58 -0
  141. package/src/frames/builtin/circle.json +81 -0
  142. package/src/frames/builtin/rounded-border.json +60 -0
  143. package/src/frames/builtin/ticket.json +51 -0
  144. package/src/frames/builtin.ts +20 -0
  145. package/src/frames/official/attendance.json +110 -0
  146. package/src/frames/official/audio-guide.json +95 -0
  147. package/src/frames/official/book-now.json +103 -0
  148. package/src/frames/official/check-in.json +110 -0
  149. package/src/frames/official/christmas.json +131 -0
  150. package/src/frames/official/donate.json +77 -0
  151. package/src/frames/official/event-ticket.json +77 -0
  152. package/src/frames/official/feedback-bubble.json +73 -0
  153. package/src/frames/official/follow-us.json +83 -0
  154. package/src/frames/official/get-the-app.json +107 -0
  155. package/src/frames/official/halloween.json +80 -0
  156. package/src/frames/official/new-year.json +94 -0
  157. package/src/frames/official/order-at-table.json +86 -0
  158. package/src/frames/official/product-info.json +119 -0
  159. package/src/frames/official/register-product.json +77 -0
  160. package/src/frames/official/review-us.json +127 -0
  161. package/src/frames/official/rsvp-card.json +112 -0
  162. package/src/frames/official/save-contact.json +117 -0
  163. package/src/frames/official/scan-to-pay.json +94 -0
  164. package/src/frames/official/shop-window.json +81 -0
  165. package/src/frames/official/sign-rider.json +81 -0
  166. package/src/frames/official/table-tent.json +75 -0
  167. package/src/frames/official/wifi-card.json +89 -0
  168. package/src/frames/official/winter.json +142 -0
  169. package/src/frames/official.ts +77 -0
  170. package/src/helpers.ts +168 -11
  171. package/src/index.tsx +141 -172
  172. package/src/logo-budget.ts +226 -0
  173. package/src/logo-cleanup.ts +146 -0
  174. package/src/logo.tsx +137 -0
  175. package/src/print.ts +794 -0
  176. package/src/qr-code-canvas.tsx +241 -0
  177. package/src/qr-code.tsx +51 -16
  178. package/src/qr-outline.ts +511 -0
  179. package/src/qr-shape.ts +255 -0
  180. package/src/scan-risk.ts +197 -0
  181. package/src/scan-score.ts +1629 -0
  182. package/src/shapes.ts +169 -0
  183. package/src/silhouette.ts +334 -0
  184. package/src/utils/color.ts +10 -1
  185. package/src/utils/fmt.ts +59 -0
  186. package/src/utils/paint.ts +317 -0
  187. package/src/utils/parse-color.ts +135 -0
  188. package/src/utils/path-data.ts +182 -0
  189. package/src/utils/png.ts +175 -0
  190. package/src/utils/polygon-clip.ts +163 -0
  191. package/src/utils/print-shared.ts +74 -0
  192. package/src/utils/svg-geometry.ts +838 -0
  193. package/src/utils/svg-gradient.ts +407 -0
  194. package/src/utils/svg-painter.ts +946 -0
  195. package/src/utils.tsx +794 -385
  196. package/types/art.ts +74 -0
  197. package/types/color.ts +132 -12
  198. package/types/corner-dot.ts +41 -4
  199. package/types/corner-eye.ts +31 -4
  200. package/types/frame-spec.ts +748 -0
  201. package/types/frame.ts +67 -0
  202. package/types/image-pattern.ts +15 -0
  203. package/types/index.ts +106 -4
  204. package/types/qr.ts +180 -2
  205. package/types/template.ts +2 -2
  206. package/dist/cli.js +0 -4231
@@ -0,0 +1,838 @@
1
+ /** biome-ignore-all lint/style/noMagicNumbers: geometry */
2
+ // Minimal SVG reader for the markup this library renders: parses the element
3
+ // tree, transforms and path data into absolute move/line/cubic segments.
4
+
5
+ export interface SvgNode {
6
+ name: string;
7
+ attrs: Record<string, string>;
8
+ children: SvgNode[];
9
+ text: string;
10
+ }
11
+
12
+ const ENTITIES: Record<string, string> = {
13
+ amp: "&",
14
+ lt: "<",
15
+ gt: ">",
16
+ quot: '"',
17
+ apos: "'",
18
+ };
19
+
20
+ function decodeEntities(value: string): string {
21
+ return value.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (match, entity) => {
22
+ if (entity[0] === "#") {
23
+ const code =
24
+ entity[1].toLowerCase() === "x"
25
+ ? Number.parseInt(entity.slice(2), 16)
26
+ : Number.parseInt(entity.slice(1), 10);
27
+ // Out-of-range code points and lone surrogates stay as written
28
+ // (String.fromCodePoint would throw on the first).
29
+ return Number.isInteger(code) &&
30
+ code > 0 &&
31
+ code <= 0x10_ff_ff &&
32
+ !(code >= 0xd8_00 && code <= 0xdf_ff)
33
+ ? String.fromCodePoint(code)
34
+ : match;
35
+ }
36
+ return ENTITIES[entity.toLowerCase()] ?? match;
37
+ });
38
+ }
39
+
40
+ // The reader below tokenizes markup exactly as matchAll did with this regex,
41
+ // but in linear time; the regex backtracked polynomially on hostile input
42
+ // (8 KB of "<!--" took over 30 seconds):
43
+ //
44
+ // <!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[([\s\S]*?)\]\]>|<![^>]*>|
45
+ // <\/([^\s>]+)\s*>|<([^\s/>]+)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>|([^<]+)
46
+ //
47
+ // tests/svg-geometry.test.ts keeps the regex reader and compares the two.
48
+
49
+ const LT = 60;
50
+ const GT = 62;
51
+ const SLASH = 47;
52
+ const EQUALS = 61;
53
+ const DOUBLE_QUOTE = 34;
54
+ const SINGLE_QUOTE = 39;
55
+
56
+ // Runs of one character class: one greedy pass each, nothing to backtrack.
57
+ const SPACE_RUN = /\s*/y;
58
+ const OPEN_NAME_RUN = /[^\s/>]*/y;
59
+ const CLOSE_NAME_RUN = /[^\s>]*/y;
60
+ const ATTR_NAME_RUN = /[^\s=]*/y;
61
+
62
+ /** Where the run of `run`'s characters starting at `from` ends. */
63
+ function runEnd(run: RegExp, text: string, from: number): number {
64
+ run.lastIndex = from;
65
+ return run.test(text) ? run.lastIndex : from;
66
+ }
67
+
68
+ interface MarkupHandler {
69
+ open(name: string, rawAttrs: string, selfClosing: boolean): void;
70
+ close(): void;
71
+ text(text: string): void;
72
+ cdata(text: string): void;
73
+ }
74
+
75
+ /**
76
+ * Splits markup into the regex's tokens, in order. Comments, processing
77
+ * instructions and declarations produce no call. A "<" that starts no token
78
+ * is skipped, and the text after it becomes a text token.
79
+ */
80
+ function tokenizeMarkup(markup: string, on: MarkupHandler): void {
81
+ const n = markup.length;
82
+
83
+ // indexOf for searches whose start only moves forward: a hit at or after
84
+ // the new start, or no hit at all, still answers the next search.
85
+ const finder = (needle: string) => {
86
+ let from = Number.POSITIVE_INFINITY;
87
+ let found = -1;
88
+ return (start: number): number => {
89
+ if (start < from || (found >= 0 && found < start)) {
90
+ from = start;
91
+ found = markup.indexOf(needle, start);
92
+ }
93
+ return found;
94
+ };
95
+ };
96
+ const commentEnd = finder("-->");
97
+ const instructionEnd = finder("?>");
98
+ const cdataEnd = finder("]]>");
99
+ const declarationEnd = finder(">");
100
+
101
+ // An open tag's attributes are a walk over boundaries: a quote jumps past
102
+ // its closing quote, any other character steps one on, and the walk stops
103
+ // at "/>" or ">" (returning its index) or fails at the end of the markup
104
+ // or at a quote that never closes. Where a walk goes depends only on where
105
+ // it is, so every boundary a failed walk crossed fails for later walks
106
+ // too. Marking them keeps all walks together linear.
107
+ let failed: Uint8Array | undefined;
108
+ const nextBoundary = (at: number): number => {
109
+ const code = markup.charCodeAt(at);
110
+ if (code !== DOUBLE_QUOTE && code !== SINGLE_QUOTE) {
111
+ return at + 1;
112
+ }
113
+ const close = markup.indexOf(markup[at] as string, at + 1);
114
+ return close < 0 ? n : close + 1;
115
+ };
116
+ const walk = (start: number): number => {
117
+ for (let at = start; at < n && !failed?.[at]; at = nextBoundary(at)) {
118
+ const code = markup.charCodeAt(at);
119
+ if (code === GT || (code === SLASH && markup.charCodeAt(at + 1) === GT)) {
120
+ return at;
121
+ }
122
+ }
123
+ failed ??= new Uint8Array(n);
124
+ for (let at = start; at < n && !failed[at]; at = nextBoundary(at)) {
125
+ failed[at] = 1;
126
+ }
127
+ return -1;
128
+ };
129
+
130
+ // The name is the run of [^\s/>] after "<", but the regex gave characters
131
+ // back from its end when the attributes could not be read from there. So
132
+ // it ends at the last place a walk succeeds from: the run's end, or a
133
+ // quote inside the run (from anywhere else the walk steps forward to the
134
+ // next quote or the run's end anyway). That depends only on the run, so a
135
+ // "<" later in the same run reuses the answer.
136
+ let nameFrom = -1;
137
+ let nameRunEnd = -1;
138
+ let nameEnd = -1;
139
+ let openEnd = -1;
140
+ const openTag = (lt: number): number => {
141
+ const from = lt + 1;
142
+ if (from < nameFrom || from >= nameRunEnd) {
143
+ nameFrom = from;
144
+ nameRunEnd = runEnd(OPEN_NAME_RUN, markup, from);
145
+ nameEnd = -1;
146
+ for (let at = nameRunEnd; at > from; at--) {
147
+ const code = markup.charCodeAt(at);
148
+ if (
149
+ at === nameRunEnd ||
150
+ code === DOUBLE_QUOTE ||
151
+ code === SINGLE_QUOTE
152
+ ) {
153
+ openEnd = walk(at);
154
+ if (openEnd >= 0) {
155
+ nameEnd = at;
156
+ break;
157
+ }
158
+ }
159
+ }
160
+ }
161
+ // The name needs at least one character.
162
+ if (nameEnd <= from) {
163
+ return -1;
164
+ }
165
+ const selfClosing = markup.charCodeAt(openEnd) === SLASH;
166
+ on.open(
167
+ markup.slice(from, nameEnd),
168
+ markup.slice(nameEnd, openEnd),
169
+ selfClosing
170
+ );
171
+ return openEnd + (selfClosing ? 2 : 1);
172
+ };
173
+
174
+ // "</name>": the run of [^\s>] after "</", optional space, then ">". A "<"
175
+ // later in the same run reuses the answer.
176
+ let closeFrom = -1;
177
+ let closeRunEnd = -1;
178
+ let closeEnd = -1;
179
+ const closeTag = (lt: number): number => {
180
+ const from = lt + 2;
181
+ if (from < closeFrom || from >= closeRunEnd) {
182
+ closeFrom = from;
183
+ closeRunEnd = runEnd(CLOSE_NAME_RUN, markup, from);
184
+ const gt = runEnd(SPACE_RUN, markup, closeRunEnd);
185
+ closeEnd = closeRunEnd > from && markup.charCodeAt(gt) === GT ? gt : -1;
186
+ }
187
+ return closeEnd;
188
+ };
189
+
190
+ /** The end of the token starting at the "<" at `lt`, or -1 for none. */
191
+ const tagAt = (lt: number): number => {
192
+ if (markup.startsWith("<!--", lt)) {
193
+ const end = commentEnd(lt + 4);
194
+ if (end >= 0) {
195
+ return end + 3;
196
+ }
197
+ }
198
+ if (markup.startsWith("<?", lt)) {
199
+ const end = instructionEnd(lt + 2);
200
+ if (end >= 0) {
201
+ return end + 2;
202
+ }
203
+ }
204
+ if (markup.startsWith("<![CDATA[", lt)) {
205
+ const end = cdataEnd(lt + 9);
206
+ if (end >= 0) {
207
+ on.cdata(markup.slice(lt + 9, end));
208
+ return end + 3;
209
+ }
210
+ }
211
+ if (markup.startsWith("<!", lt)) {
212
+ const end = declarationEnd(lt + 2);
213
+ if (end >= 0) {
214
+ return end + 1;
215
+ }
216
+ }
217
+ if (markup.charCodeAt(lt + 1) === SLASH) {
218
+ // "/" can't start an open tag's name either.
219
+ const end = closeTag(lt);
220
+ if (end < 0) {
221
+ return -1;
222
+ }
223
+ on.close();
224
+ return end + 1;
225
+ }
226
+ return openTag(lt);
227
+ };
228
+
229
+ let at = 0;
230
+ while (at < n) {
231
+ if (markup.charCodeAt(at) === LT) {
232
+ const end = tagAt(at);
233
+ at = end < 0 ? at + 1 : end;
234
+ } else {
235
+ const lt = markup.indexOf("<", at);
236
+ const end = lt < 0 ? n : lt;
237
+ on.text(markup.slice(at, end));
238
+ at = end;
239
+ }
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Reads `name="value"` pairs as /([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
245
+ * did with matchAll, in linear time (the regex retried from every character
246
+ * of a long name that no "=" followed).
247
+ */
248
+ function parseAttributes(raw: string): Record<string, string> {
249
+ const attrs: Record<string, string> = {};
250
+ let at = 0;
251
+ while (at < raw.length) {
252
+ const nameEnd = runEnd(ATTR_NAME_RUN, raw, at);
253
+ if (nameEnd === at) {
254
+ at++;
255
+ continue;
256
+ }
257
+ const equals = runEnd(SPACE_RUN, raw, nameEnd);
258
+ if (raw.charCodeAt(equals) === EQUALS) {
259
+ const open = runEnd(SPACE_RUN, raw, equals + 1);
260
+ const quote = raw[open];
261
+ const close =
262
+ quote === '"' || quote === "'" ? raw.indexOf(quote, open + 1) : -1;
263
+ if (close >= 0) {
264
+ attrs[raw.slice(at, nameEnd)] = decodeEntities(
265
+ raw.slice(open + 1, close)
266
+ );
267
+ at = close + 1;
268
+ continue;
269
+ }
270
+ }
271
+ // A pair starting later in this name would fail the same way.
272
+ at = nameEnd;
273
+ }
274
+ return attrs;
275
+ }
276
+
277
+ /** Parses SVG/XML markup into a tree and returns the first `<svg>` element. */
278
+ export function parseSvgMarkup(markup: string): SvgNode | null {
279
+ const root: SvgNode = { name: "#root", attrs: {}, children: [], text: "" };
280
+ const stack: SvgNode[] = [root];
281
+ const current = () => stack.at(-1) as SvgNode;
282
+
283
+ tokenizeMarkup(markup, {
284
+ open(name, rawAttrs, selfClosing) {
285
+ const attrs = parseAttributes(rawAttrs);
286
+ const node: SvgNode = { name, attrs, children: [], text: "" };
287
+ current().children.push(node);
288
+ if (!selfClosing) {
289
+ stack.push(node);
290
+ }
291
+ },
292
+ close() {
293
+ if (stack.length > 1) {
294
+ stack.pop();
295
+ }
296
+ },
297
+ text(text) {
298
+ current().text += decodeEntities(text);
299
+ },
300
+ cdata(text) {
301
+ current().text += text;
302
+ },
303
+ });
304
+
305
+ const findSvg = (node: SvgNode): SvgNode | null => {
306
+ for (const child of node.children) {
307
+ if (child.name === "svg") {
308
+ return child;
309
+ }
310
+ const found = findSvg(child);
311
+ if (found) {
312
+ return found;
313
+ }
314
+ }
315
+ return null;
316
+ };
317
+ return findSvg(root);
318
+ }
319
+
320
+ // ── Matrices ───────────────────────────────────────────────────────────────
321
+
322
+ /** Affine matrix [a, b, c, d, e, f] as in SVG `matrix()` */
323
+ export type Matrix = [number, number, number, number, number, number];
324
+
325
+ export const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0];
326
+
327
+ /** Returns `m1 × m2` (m2 is applied first). */
328
+ export function multiply(m1: Matrix, m2: Matrix): Matrix {
329
+ const [a1, b1, c1, d1, e1, f1] = m1;
330
+ const [a2, b2, c2, d2, e2, f2] = m2;
331
+ return [
332
+ a1 * a2 + c1 * b2,
333
+ b1 * a2 + d1 * b2,
334
+ a1 * c2 + c1 * d2,
335
+ b1 * c2 + d1 * d2,
336
+ a1 * e2 + c1 * f2 + e1,
337
+ b1 * e2 + d1 * f2 + f1,
338
+ ];
339
+ }
340
+
341
+ export function applyMatrix(m: Matrix, x: number, y: number): [number, number] {
342
+ return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
343
+ }
344
+
345
+ /** Average linear scale of a matrix (for stroke widths and font sizes). */
346
+ export function matrixScale(m: Matrix): number {
347
+ return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
348
+ }
349
+
350
+ export function parseNumbers(value: string | undefined): number[] {
351
+ if (!value) {
352
+ return [];
353
+ }
354
+ return (value.match(/[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/gi) ?? []).map(
355
+ Number
356
+ );
357
+ }
358
+
359
+ /** Parses an SVG `transform` attribute into a single matrix. */
360
+ export function parseTransform(value: string | undefined): Matrix {
361
+ let result: Matrix = IDENTITY;
362
+ if (!value) {
363
+ return result;
364
+ }
365
+ for (const [, name, args] of value.matchAll(
366
+ /(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g
367
+ )) {
368
+ const n = parseNumbers(args);
369
+ let t: Matrix = IDENTITY;
370
+ switch (name) {
371
+ case "matrix":
372
+ if (n.length === 6) {
373
+ t = n as Matrix;
374
+ }
375
+ break;
376
+ case "translate":
377
+ t = [1, 0, 0, 1, n[0] ?? 0, n[1] ?? 0];
378
+ break;
379
+ case "scale":
380
+ t = [n[0] ?? 1, 0, 0, n[1] ?? n[0] ?? 1, 0, 0];
381
+ break;
382
+ case "rotate": {
383
+ const angle = ((n[0] ?? 0) * Math.PI) / 180;
384
+ const cos = Math.cos(angle);
385
+ const sin = Math.sin(angle);
386
+ const [cx, cy] = [n[1] ?? 0, n[2] ?? 0];
387
+ t = multiply(
388
+ multiply([1, 0, 0, 1, cx, cy], [cos, sin, -sin, cos, 0, 0]),
389
+ [1, 0, 0, 1, -cx, -cy]
390
+ );
391
+ break;
392
+ }
393
+ case "skewX":
394
+ t = [1, 0, Math.tan(((n[0] ?? 0) * Math.PI) / 180), 1, 0, 0];
395
+ break;
396
+ case "skewY":
397
+ t = [1, Math.tan(((n[0] ?? 0) * Math.PI) / 180), 0, 1, 0, 0];
398
+ break;
399
+ default:
400
+ break;
401
+ }
402
+ result = multiply(result, t);
403
+ }
404
+ return result;
405
+ }
406
+
407
+ // ── Paths ──────────────────────────────────────────────────────────────────
408
+
409
+ export type Segment =
410
+ | { op: "M"; x: number; y: number }
411
+ | { op: "L"; x: number; y: number }
412
+ | {
413
+ op: "C";
414
+ x1: number;
415
+ y1: number;
416
+ x2: number;
417
+ y2: number;
418
+ x: number;
419
+ y: number;
420
+ }
421
+ | { op: "Z" };
422
+
423
+ const NUMBER_RE = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y;
424
+
425
+ function arcToCubics(
426
+ x1: number,
427
+ y1: number,
428
+ rxIn: number,
429
+ ryIn: number,
430
+ rotation: number,
431
+ largeArc: boolean,
432
+ sweep: boolean,
433
+ x2: number,
434
+ y2: number
435
+ ): Segment[] {
436
+ if (x1 === x2 && y1 === y2) {
437
+ return [];
438
+ }
439
+ let rx = Math.abs(rxIn);
440
+ let ry = Math.abs(ryIn);
441
+ if (rx === 0 || ry === 0) {
442
+ return [{ op: "L", x: x2, y: y2 }];
443
+ }
444
+ const phi = (rotation * Math.PI) / 180;
445
+ const cosPhi = Math.cos(phi);
446
+ const sinPhi = Math.sin(phi);
447
+ const dx = (x1 - x2) / 2;
448
+ const dy = (y1 - y2) / 2;
449
+ const x1p = cosPhi * dx + sinPhi * dy;
450
+ const y1p = -sinPhi * dx + cosPhi * dy;
451
+ const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
452
+ if (lambda > 1) {
453
+ rx *= Math.sqrt(lambda);
454
+ ry *= Math.sqrt(lambda);
455
+ }
456
+ const numerator =
457
+ rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
458
+ const denominator = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
459
+ const coef =
460
+ (largeArc === sweep ? -1 : 1) *
461
+ Math.sqrt(Math.max(0, numerator / denominator));
462
+ const cxp = (coef * rx * y1p) / ry;
463
+ const cyp = (-coef * ry * x1p) / rx;
464
+ const cx = cosPhi * cxp - sinPhi * cyp + (x1 + x2) / 2;
465
+ const cy = sinPhi * cxp + cosPhi * cyp + (y1 + y2) / 2;
466
+
467
+ const angle = (ux: number, uy: number, vx: number, vy: number) =>
468
+ Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
469
+ const theta1 = angle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);
470
+ let delta = angle(
471
+ (x1p - cxp) / rx,
472
+ (y1p - cyp) / ry,
473
+ (-x1p - cxp) / rx,
474
+ (-y1p - cyp) / ry
475
+ );
476
+ if (!sweep && delta > 0) {
477
+ delta -= 2 * Math.PI;
478
+ } else if (sweep && delta < 0) {
479
+ delta += 2 * Math.PI;
480
+ }
481
+
482
+ const count = Math.max(1, Math.ceil(Math.abs(delta) / (Math.PI / 2) - 1e-9));
483
+ const step = delta / count;
484
+ const t = (4 / 3) * Math.tan(step / 4);
485
+ const map = (px: number, py: number): [number, number] => [
486
+ cx + rx * cosPhi * px - ry * sinPhi * py,
487
+ cy + rx * sinPhi * px + ry * cosPhi * py,
488
+ ];
489
+
490
+ const segments: Segment[] = [];
491
+ for (let i = 0; i < count; i++) {
492
+ const a = theta1 + i * step;
493
+ const b = a + step;
494
+ const [c1x, c1y] = map(
495
+ Math.cos(a) - t * Math.sin(a),
496
+ Math.sin(a) + t * Math.cos(a)
497
+ );
498
+ const [c2x, c2y] = map(
499
+ Math.cos(b) + t * Math.sin(b),
500
+ Math.sin(b) - t * Math.cos(b)
501
+ );
502
+ const [ex, ey] = i === count - 1 ? [x2, y2] : map(Math.cos(b), Math.sin(b));
503
+ segments.push({
504
+ op: "C",
505
+ x1: c1x,
506
+ y1: c1y,
507
+ x2: c2x,
508
+ y2: c2y,
509
+ x: ex,
510
+ y: ey,
511
+ });
512
+ }
513
+ return segments;
514
+ }
515
+
516
+ /**
517
+ * Parses SVG path data into absolute M/L/C/Z segments (H/V/S/Q/T/A are
518
+ * converted). Stops at the first malformed command, like browsers do.
519
+ */
520
+ export function parsePathData(d: string): Segment[] {
521
+ const segments: Segment[] = [];
522
+ let index = 0;
523
+ let x = 0;
524
+ let y = 0;
525
+ let startX = 0;
526
+ let startY = 0;
527
+ let command = "";
528
+ // Last control point, for S/T reflection
529
+ let lastCubic: [number, number] | null = null;
530
+ let lastQuad: [number, number] | null = null;
531
+
532
+ const skip = () => {
533
+ while (index < d.length && /[\s,]/.test(d[index] as string)) {
534
+ index++;
535
+ }
536
+ };
537
+ const readNumber = (): number | null => {
538
+ skip();
539
+ NUMBER_RE.lastIndex = index;
540
+ const match = NUMBER_RE.exec(d);
541
+ if (!match) {
542
+ return null;
543
+ }
544
+ index = NUMBER_RE.lastIndex;
545
+ return Number(match[0]);
546
+ };
547
+ const readFlag = (): boolean | null => {
548
+ skip();
549
+ const char = d[index];
550
+ if (char === "0" || char === "1") {
551
+ index++;
552
+ return char === "1";
553
+ }
554
+ return null;
555
+ };
556
+ const read = (count: number): number[] | null => {
557
+ const values: number[] = [];
558
+ for (let i = 0; i < count; i++) {
559
+ const value = readNumber();
560
+ if (value === null) {
561
+ return null;
562
+ }
563
+ values.push(value);
564
+ }
565
+ return values;
566
+ };
567
+
568
+ while (true) {
569
+ skip();
570
+ if (index >= d.length) {
571
+ break;
572
+ }
573
+ const char = d[index] as string;
574
+ if (/[MmLlHhVvCcSsQqTtAaZz]/.test(char)) {
575
+ command = char;
576
+ index++;
577
+ } else if (!command || command === "Z" || command === "z") {
578
+ break;
579
+ }
580
+
581
+ const relative = command === command.toLowerCase();
582
+ const ox = relative ? x : 0;
583
+ const oy = relative ? y : 0;
584
+ const upper = command.toUpperCase();
585
+
586
+ if (upper === "Z") {
587
+ segments.push({ op: "Z" });
588
+ x = startX;
589
+ y = startY;
590
+ lastCubic = null;
591
+ lastQuad = null;
592
+ continue;
593
+ }
594
+
595
+ if (upper === "A") {
596
+ const radii = read(3);
597
+ const large = readFlag();
598
+ const sweepFlag = readFlag();
599
+ const end = read(2);
600
+ if (!(radii && end) || large === null || sweepFlag === null) {
601
+ break;
602
+ }
603
+ const [rx, ry, rotation] = radii as [number, number, number];
604
+ const ex = (end[0] as number) + ox;
605
+ const ey = (end[1] as number) + oy;
606
+ segments.push(
607
+ ...arcToCubics(x, y, rx, ry, rotation, large, sweepFlag, ex, ey)
608
+ );
609
+ x = ex;
610
+ y = ey;
611
+ lastCubic = null;
612
+ lastQuad = null;
613
+ continue;
614
+ }
615
+
616
+ const arity =
617
+ { M: 2, L: 2, H: 1, V: 1, C: 6, S: 4, Q: 4, T: 2 }[upper] ?? 0;
618
+ const values = read(arity);
619
+ if (!values) {
620
+ break;
621
+ }
622
+ const v = values as number[];
623
+
624
+ switch (upper) {
625
+ case "M":
626
+ x = (v[0] as number) + ox;
627
+ y = (v[1] as number) + oy;
628
+ startX = x;
629
+ startY = y;
630
+ segments.push({ op: "M", x, y });
631
+ // Extra coordinate pairs after a move are implicit line-tos.
632
+ command = relative ? "l" : "L";
633
+ lastCubic = null;
634
+ lastQuad = null;
635
+ break;
636
+ case "L":
637
+ case "H":
638
+ case "V":
639
+ if (upper !== "V") {
640
+ x = (v[0] as number) + ox;
641
+ }
642
+ if (upper === "V") {
643
+ y = (v[0] as number) + oy;
644
+ } else if (upper === "L") {
645
+ y = (v[1] as number) + oy;
646
+ }
647
+ segments.push({ op: "L", x, y });
648
+ lastCubic = null;
649
+ lastQuad = null;
650
+ break;
651
+ case "C":
652
+ case "S": {
653
+ let c1: [number, number];
654
+ let rest: number[];
655
+ if (upper === "C") {
656
+ c1 = [(v[0] as number) + ox, (v[1] as number) + oy];
657
+ rest = v.slice(2);
658
+ } else {
659
+ c1 = lastCubic
660
+ ? [2 * x - lastCubic[0], 2 * y - lastCubic[1]]
661
+ : [x, y];
662
+ rest = v;
663
+ }
664
+ const c2: [number, number] = [
665
+ (rest[0] as number) + ox,
666
+ (rest[1] as number) + oy,
667
+ ];
668
+ const end: [number, number] = [
669
+ (rest[2] as number) + ox,
670
+ (rest[3] as number) + oy,
671
+ ];
672
+ segments.push({
673
+ op: "C",
674
+ x1: c1[0],
675
+ y1: c1[1],
676
+ x2: c2[0],
677
+ y2: c2[1],
678
+ x: end[0],
679
+ y: end[1],
680
+ });
681
+ [x, y] = end;
682
+ lastCubic = c2;
683
+ lastQuad = null;
684
+ break;
685
+ }
686
+ case "Q":
687
+ case "T": {
688
+ let q: [number, number];
689
+ let end: [number, number];
690
+ if (upper === "Q") {
691
+ q = [(v[0] as number) + ox, (v[1] as number) + oy];
692
+ end = [(v[2] as number) + ox, (v[3] as number) + oy];
693
+ } else {
694
+ q = lastQuad ? [2 * x - lastQuad[0], 2 * y - lastQuad[1]] : [x, y];
695
+ end = [(v[0] as number) + ox, (v[1] as number) + oy];
696
+ }
697
+ segments.push({
698
+ op: "C",
699
+ x1: x + (2 / 3) * (q[0] - x),
700
+ y1: y + (2 / 3) * (q[1] - y),
701
+ x2: end[0] + (2 / 3) * (q[0] - end[0]),
702
+ y2: end[1] + (2 / 3) * (q[1] - end[1]),
703
+ x: end[0],
704
+ y: end[1],
705
+ });
706
+ [x, y] = end;
707
+ lastQuad = q;
708
+ lastCubic = null;
709
+ break;
710
+ }
711
+ default:
712
+ break;
713
+ }
714
+ }
715
+
716
+ return segments;
717
+ }
718
+
719
+ const KAPPA = 0.552_284_749_8;
720
+
721
+ /** Ellipse as four cubic segments. */
722
+ export function ellipseSegments(
723
+ cx: number,
724
+ cy: number,
725
+ rx: number,
726
+ ry: number
727
+ ): Segment[] {
728
+ if (rx <= 0 || ry <= 0) {
729
+ return [];
730
+ }
731
+ const kx = rx * KAPPA;
732
+ const ky = ry * KAPPA;
733
+ return [
734
+ { op: "M", x: cx + rx, y: cy },
735
+ {
736
+ op: "C",
737
+ x1: cx + rx,
738
+ y1: cy + ky,
739
+ x2: cx + kx,
740
+ y2: cy + ry,
741
+ x: cx,
742
+ y: cy + ry,
743
+ },
744
+ {
745
+ op: "C",
746
+ x1: cx - kx,
747
+ y1: cy + ry,
748
+ x2: cx - rx,
749
+ y2: cy + ky,
750
+ x: cx - rx,
751
+ y: cy,
752
+ },
753
+ {
754
+ op: "C",
755
+ x1: cx - rx,
756
+ y1: cy - ky,
757
+ x2: cx - kx,
758
+ y2: cy - ry,
759
+ x: cx,
760
+ y: cy - ry,
761
+ },
762
+ {
763
+ op: "C",
764
+ x1: cx + kx,
765
+ y1: cy - ry,
766
+ x2: cx + rx,
767
+ y2: cy - ky,
768
+ x: cx + rx,
769
+ y: cy,
770
+ },
771
+ { op: "Z" },
772
+ ];
773
+ }
774
+
775
+ /** Rectangle (optionally rounded) as segments. */
776
+ export function rectSegments(
777
+ x: number,
778
+ y: number,
779
+ width: number,
780
+ height: number,
781
+ rxIn = 0,
782
+ ryIn = 0
783
+ ): Segment[] {
784
+ if (width <= 0 || height <= 0) {
785
+ return [];
786
+ }
787
+ const rx = Math.min(Math.max(rxIn, 0), width / 2);
788
+ const ry = Math.min(Math.max(ryIn, 0), height / 2);
789
+ if (rx === 0 || ry === 0) {
790
+ return [
791
+ { op: "M", x, y },
792
+ { op: "L", x: x + width, y },
793
+ { op: "L", x: x + width, y: y + height },
794
+ { op: "L", x, y: y + height },
795
+ { op: "Z" },
796
+ ];
797
+ }
798
+ const kx = rx * KAPPA;
799
+ const ky = ry * KAPPA;
800
+ const right = x + width;
801
+ const bottom = y + height;
802
+ return [
803
+ { op: "M", x: x + rx, y },
804
+ { op: "L", x: right - rx, y },
805
+ {
806
+ op: "C",
807
+ x1: right - rx + kx,
808
+ y1: y,
809
+ x2: right,
810
+ y2: y + ry - ky,
811
+ x: right,
812
+ y: y + ry,
813
+ },
814
+ { op: "L", x: right, y: bottom - ry },
815
+ {
816
+ op: "C",
817
+ x1: right,
818
+ y1: bottom - ry + ky,
819
+ x2: right - rx + kx,
820
+ y2: bottom,
821
+ x: right - rx,
822
+ y: bottom,
823
+ },
824
+ { op: "L", x: x + rx, y: bottom },
825
+ {
826
+ op: "C",
827
+ x1: x + rx - kx,
828
+ y1: bottom,
829
+ x2: x,
830
+ y2: bottom - ry + ky,
831
+ x,
832
+ y: bottom - ry,
833
+ },
834
+ { op: "L", x, y: y + ry },
835
+ { op: "C", x1: x, y1: y + ry - ky, x2: x + rx - kx, y2: y, x: x + rx, y },
836
+ { op: "Z" },
837
+ ];
838
+ }