@pixldocs/canvas-renderer 0.5.154 → 0.5.156

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.
@@ -1,745 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
25
- const opentype = require("opentype.js");
26
- const pdfFonts = require("./pdfFonts-BTEVnYX8.cjs");
27
- function _interopNamespaceDefault(e) {
28
- const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
29
- if (e) {
30
- for (const k in e) {
31
- if (k !== "default") {
32
- const d = Object.getOwnPropertyDescriptor(e, k);
33
- Object.defineProperty(n, k, d.get ? d : {
34
- enumerable: true,
35
- get: () => e[k]
36
- });
37
- }
38
- }
39
- }
40
- n.default = e;
41
- return Object.freeze(n);
42
- }
43
- const opentype__namespace = /* @__PURE__ */ _interopNamespaceDefault(opentype);
44
- const HB_WASM_URL = "/wasm/hb.wasm";
45
- let hbInstancePromise = null;
46
- async function getHB() {
47
- if (hbInstancePromise) return hbInstancePromise;
48
- hbInstancePromise = (async () => {
49
- const [{ default: createHarfBuzz }, { default: hbjs }] = await Promise.all([
50
- import("harfbuzzjs/hb.js"),
51
- import("harfbuzzjs/hbjs.js")
52
- ]);
53
- const moduleInstance = await createHarfBuzz({
54
- locateFile: (path) => {
55
- if (path.endsWith(".wasm")) return HB_WASM_URL;
56
- return path;
57
- }
58
- });
59
- return hbjs(moduleInstance);
60
- })();
61
- return hbInstancePromise;
62
- }
63
- const hbFontCache = /* @__PURE__ */ new Map();
64
- async function getHBFont(cacheKey, fontDataLoader) {
65
- const cached = hbFontCache.get(cacheKey);
66
- if (cached) return { font: cached.font, upem: cached.upem };
67
- const hb = await getHB();
68
- const fontData = await fontDataLoader();
69
- const blob = hb.createBlob(fontData);
70
- const face = hb.createFace(blob, 0);
71
- const font = hb.createFont(face);
72
- const upem = (face.getUpem ? face.getUpem() : face.upem ?? 1e3) || 1e3;
73
- font.setScale(upem, upem);
74
- blob.destroy();
75
- hbFontCache.set(cacheKey, { face, font, upem });
76
- return { font, upem };
77
- }
78
- async function shapeRunToSvgPath(fontData, cacheKey, text, x, y, fontSize, opts) {
79
- const hb = await getHB();
80
- const loader = typeof fontData === "function" ? fontData : async () => fontData;
81
- const { font, upem } = await getHBFont(cacheKey, loader);
82
- const buffer = hb.createBuffer();
83
- buffer.addText(text);
84
- if (opts == null ? void 0 : opts.direction) buffer.setDirection(opts.direction);
85
- if (opts == null ? void 0 : opts.script) buffer.setScript(opts.script);
86
- if (opts == null ? void 0 : opts.language) buffer.setLanguage(opts.language);
87
- buffer.guessSegmentProperties();
88
- hb.shape(font, buffer);
89
- const glyphs = buffer.json();
90
- const scale = fontSize / upem;
91
- let penX = 0;
92
- let penY = 0;
93
- const pieces = [];
94
- for (const g of glyphs) {
95
- const rawPath = font.glyphToPath(g.g);
96
- if (rawPath) {
97
- const ox = (penX + g.dx) * scale + x;
98
- const oy = (penY + g.dy) * -scale + y;
99
- pieces.push(transformPathData(rawPath, scale, -scale, ox, oy));
100
- }
101
- penX += g.ax;
102
- penY += g.ay;
103
- }
104
- buffer.destroy();
105
- return {
106
- pathData: pieces.join(""),
107
- width: penX * scale
108
- };
109
- }
110
- function transformPathData(d, sx, sy, tx, ty) {
111
- let out = "";
112
- let i = 0;
113
- const n = d.length;
114
- while (i < n) {
115
- const c = d[i];
116
- if (c === "M" || c === "L" || c === "C" || c === "Q") {
117
- out += c;
118
- i++;
119
- let pairsBuf = "";
120
- while (i < n && d[i] !== "M" && d[i] !== "L" && d[i] !== "C" && d[i] !== "Q" && d[i] !== "Z") {
121
- pairsBuf += d[i];
122
- i++;
123
- }
124
- const nums = pairsBuf.trim().split(/[ ,]+/).filter(Boolean).map(Number);
125
- for (let k = 0; k < nums.length; k += 2) {
126
- const px = nums[k] * sx + tx;
127
- const py = nums[k + 1] * sy + ty;
128
- if (k > 0) out += " ";
129
- out += `${round(px)},${round(py)}`;
130
- }
131
- } else if (c === "Z") {
132
- out += "Z";
133
- i++;
134
- } else {
135
- i++;
136
- }
137
- }
138
- return out;
139
- }
140
- function round(n) {
141
- return (Math.round(n * 100) / 100).toString();
142
- }
143
- const fontCache = /* @__PURE__ */ new Map();
144
- const fontBytesCache = /* @__PURE__ */ new Map();
145
- function isDevanagari(char) {
146
- const c = char.codePointAt(0) ?? 0;
147
- return c >= 2304 && c <= 2431 || c >= 43232 && c <= 43263 || c >= 7376 && c <= 7423;
148
- }
149
- function containsDevanagari(text) {
150
- if (!text) return false;
151
- for (const char of text) {
152
- if (isDevanagari(char)) return true;
153
- }
154
- return false;
155
- }
156
- function isBasicLatinOrLatinExtended(char) {
157
- const c = char.codePointAt(0) ?? 0;
158
- return c <= 591;
159
- }
160
- function isMathOperatorChar(char) {
161
- const c = char.codePointAt(0) ?? 0;
162
- if (c >= 8592 && c <= 8703) return true;
163
- if (c >= 8704 && c <= 8959) return true;
164
- if (c >= 8960 && c <= 9215) return true;
165
- if (c >= 10176 && c <= 10223) return true;
166
- if (c >= 10624 && c <= 10751) return true;
167
- if (c >= 10752 && c <= 11007) return true;
168
- if (c >= 11008 && c <= 11097) return true;
169
- return false;
170
- }
171
- function classifyCharForFontRun(char) {
172
- if (isBasicLatinOrLatinExtended(char)) return "main";
173
- if (isDevanagari(char)) return "devanagari";
174
- if (isMathOperatorChar(char)) return "math";
175
- return "symbol";
176
- }
177
- function isIgnorableForCoverage(char) {
178
- return /\s/.test(char) || /[\u0964\u0965\u200c\u200d]/u.test(char);
179
- }
180
- function fontSupportsRun(font, text, runType) {
181
- if (!font) return false;
182
- for (const char of text) {
183
- if (isIgnorableForCoverage(char)) continue;
184
- if (runType === "devanagari" && !isDevanagari(char)) continue;
185
- if (runType === "symbol" && classifyCharForFontRun(char) !== "symbol") continue;
186
- if (runType === "math" && classifyCharForFontRun(char) !== "math") continue;
187
- const glyph = font.charToGlyph(char);
188
- if (!glyph || glyph.index === 0) return false;
189
- }
190
- return true;
191
- }
192
- const browserMeasureCanvas = typeof document !== "undefined" ? document.createElement("canvas") : null;
193
- function measureBrowserWidth(fontFamily, weight, fontSize, text) {
194
- const ctx = browserMeasureCanvas == null ? void 0 : browserMeasureCanvas.getContext("2d");
195
- if (!ctx) return null;
196
- ctx.font = `normal normal ${weight} ${fontSize}px "${fontFamily}"`;
197
- return ctx.measureText(text).width;
198
- }
199
- function uniqueFamilies(families) {
200
- const seen = /* @__PURE__ */ new Set();
201
- const out = [];
202
- for (const family of families) {
203
- const clean = family == null ? void 0 : family.trim();
204
- if (!clean || seen.has(clean)) continue;
205
- seen.add(clean);
206
- out.push(clean);
207
- }
208
- return out;
209
- }
210
- function fontLooksItalic(font) {
211
- var _a, _b, _c, _d;
212
- if (!font) return false;
213
- const names = font.names;
214
- const candidates = [
215
- (_a = names.fontSubfamily) == null ? void 0 : _a.en,
216
- (_b = names.typographicSubfamily) == null ? void 0 : _b.en,
217
- (_c = names.fullName) == null ? void 0 : _c.en,
218
- (_d = names.postScriptName) == null ? void 0 : _d.en
219
- ].filter(Boolean).join(" ");
220
- return /italic|oblique/i.test(candidates);
221
- }
222
- function syntheticItalicTransform(anchorX, baselineY) {
223
- return `translate(${anchorX} ${baselineY}) skewX(-12) translate(${-anchorX} ${-baselineY})`;
224
- }
225
- function getFontPath(fontFiles, weight, isItalic = false) {
226
- const resolved = pdfFonts.resolveFontWeight(weight);
227
- const uprightMap = {
228
- 300: ["light", "regular"],
229
- 400: ["regular"],
230
- 500: ["medium", "regular"],
231
- 600: ["semibold", "bold"],
232
- 700: ["bold", "semibold", "regular"]
233
- };
234
- const italicMap = {
235
- 300: ["lightItalic", "italic", "light", "regular"],
236
- 400: ["italic", "regular"],
237
- 500: ["mediumItalic", "italic", "medium", "regular"],
238
- 600: ["semiboldItalic", "boldItalic", "italic", "semibold", "bold", "regular"],
239
- 700: ["boldItalic", "semiboldItalic", "italic", "bold", "semibold", "regular"]
240
- };
241
- const map = isItalic ? italicMap : uprightMap;
242
- for (const key of map[resolved] || ["regular"]) {
243
- if (fontFiles[key]) return fontFiles[key];
244
- }
245
- return fontFiles.regular || null;
246
- }
247
- function resolveFontUrl(fileName, fontBaseUrl) {
248
- if (/^https?:\/\//i.test(fileName) || fileName.startsWith("data:")) return fileName;
249
- if (fileName.startsWith("/")) {
250
- return typeof window !== "undefined" ? new URL(fileName, window.location.origin).toString() : fileName;
251
- }
252
- const baseUrl = fontBaseUrl.endsWith("/") ? fontBaseUrl : fontBaseUrl + "/";
253
- return new URL(fileName, baseUrl).toString();
254
- }
255
- async function loadFont(fontFamily, weight, fontBaseUrl, isItalic = false) {
256
- const cacheKey = `${fontFamily}__${weight}__${isItalic ? "i" : "n"}`;
257
- if (fontCache.has(cacheKey)) return fontCache.get(cacheKey);
258
- const fontFiles = pdfFonts.FONT_FILES[fontFamily];
259
- if (fontFiles) {
260
- const fileName = getFontPath(fontFiles, weight, isItalic);
261
- if (!fileName) return null;
262
- const url = resolveFontUrl(fileName, fontBaseUrl);
263
- try {
264
- const response = await fetch(url);
265
- if (!response.ok) {
266
- console.warn(`[text-to-path] Failed to fetch font ${url}: ${response.status}`);
267
- return null;
268
- }
269
- const buffer = await response.arrayBuffer();
270
- const bytes = new Uint8Array(buffer);
271
- fontBytesCache.set(cacheKey, bytes);
272
- const font = opentype__namespace.parse(buffer);
273
- fontCache.set(cacheKey, font);
274
- return font;
275
- } catch (err) {
276
- console.warn(`[text-to-path] Failed to load local font ${fontFamily}:`, err);
277
- return null;
278
- }
279
- }
280
- try {
281
- const resolvedWeight = pdfFonts.resolveFontWeight(weight);
282
- let bytes = await pdfFonts.getGoogleFontBytes(fontFamily, resolvedWeight, isItalic);
283
- if (!bytes) {
284
- bytes = await pdfFonts.getFontshareFontBytes(fontFamily, resolvedWeight, isItalic);
285
- }
286
- if (!bytes && isItalic) {
287
- bytes = await pdfFonts.getGoogleFontBytes(fontFamily, resolvedWeight, false);
288
- if (!bytes) bytes = await pdfFonts.getFontshareFontBytes(fontFamily, resolvedWeight, false);
289
- }
290
- if (!bytes) {
291
- console.warn(`[text-to-path] No TTF available for ${fontFamily} (${weight}) on Google Fonts or Fontshare`);
292
- return null;
293
- }
294
- fontBytesCache.set(cacheKey, bytes);
295
- const ab = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
296
- const font = opentype__namespace.parse(ab);
297
- fontCache.set(cacheKey, font);
298
- return font;
299
- } catch (err) {
300
- console.warn(`[text-to-path] Failed to load Google font ${fontFamily}:`, err);
301
- return null;
302
- }
303
- }
304
- async function getFontBytes(fontFamily, weight, fontBaseUrl, isItalic = false) {
305
- const cacheKey = `${fontFamily}__${weight}__${isItalic ? "i" : "n"}`;
306
- if (!fontBytesCache.has(cacheKey)) {
307
- await loadFont(fontFamily, weight, fontBaseUrl, isItalic);
308
- }
309
- const bytes = fontBytesCache.get(cacheKey);
310
- return bytes ? { bytes, cacheKey } : null;
311
- }
312
- function measureRunWidth(font, text, fontSize) {
313
- try {
314
- return font.getAdvanceWidth(text, fontSize, { kerning: true });
315
- } catch {
316
- try {
317
- return font.getAdvanceWidth(text, fontSize);
318
- } catch {
319
- return text.length * fontSize * 0.5;
320
- }
321
- }
322
- }
323
- function splitByFontRun(text) {
324
- if (!text) return [];
325
- const runs = [];
326
- let buf = "";
327
- let bufType = classifyCharForFontRun(text[0]);
328
- for (const ch of text) {
329
- const chType = classifyCharForFontRun(ch);
330
- const isNeutral = /\s/.test(ch);
331
- if (chType === bufType || isNeutral) {
332
- buf += ch;
333
- } else {
334
- if (buf) runs.push({ text: buf, runType: bufType });
335
- buf = ch;
336
- bufType = chType;
337
- }
338
- }
339
- if (buf) runs.push({ text: buf, runType: bufType });
340
- return runs;
341
- }
342
- async function shapeRunToPath(run, isDeva, primaryFont, primaryBytes, devaFont, devaBytes, x, y, fontSize) {
343
- if (isDeva && devaBytes && devaFont) {
344
- try {
345
- const shaped = await shapeRunToSvgPath(
346
- devaBytes.bytes,
347
- devaBytes.cacheKey,
348
- run,
349
- x,
350
- y,
351
- fontSize,
352
- { script: "deva", language: "hin", direction: "ltr" }
353
- );
354
- if (shaped.pathData) {
355
- const advance = measureRunWidth(devaFont, run, fontSize);
356
- return { pathData: shaped.pathData, advance };
357
- }
358
- } catch (err) {
359
- console.warn(`[text-to-path] HarfBuzz failed for "${run}":`, err);
360
- }
361
- try {
362
- const path = devaFont.getPath(run, x, y, fontSize);
363
- const d = path.toPathData(2);
364
- if (d && d !== "M0 0") return { pathData: d, advance: measureRunWidth(devaFont, run, fontSize) };
365
- } catch {
366
- }
367
- return null;
368
- }
369
- try {
370
- const path = primaryFont.getPath(run, x, y, fontSize, { kerning: true });
371
- const d = path.toPathData(2);
372
- if (d && d !== "M0 0") return { pathData: d, advance: measureRunWidth(primaryFont, run, fontSize) };
373
- return { pathData: "", advance: measureRunWidth(primaryFont, run, fontSize) };
374
- } catch (err) {
375
- console.warn(`[text-to-path] opentype getPath failed for "${run}":`, err);
376
- return null;
377
- }
378
- }
379
- function parseTranslate(transform) {
380
- if (!transform) return { tx: 0, ty: 0 };
381
- const m = transform.match(/translate\(\s*([-\d.]+)[ \s,]+([-\d.]+)\s*\)/);
382
- if (m) return { tx: parseFloat(m[1]), ty: parseFloat(m[2]) };
383
- const mm = transform.match(/matrix\(\s*([-\d.]+)[ \s,]+([-\d.]+)[ \s,]+([-\d.]+)[ \s,]+([-\d.]+)[ \s,]+([-\d.]+)[ \s,]+([-\d.]+)\s*\)/);
384
- if (mm) return { tx: parseFloat(mm[5]), ty: parseFloat(mm[6]) };
385
- return { tx: 0, ty: 0 };
386
- }
387
- function needsComplexShaping(text) {
388
- if (!text) return false;
389
- for (const ch of text) {
390
- const c = ch.codePointAt(0) ?? 0;
391
- if (c >= 2304 && c <= 2431 || c >= 43232 && c <= 43263 || c >= 7376 && c <= 7423) return true;
392
- if (c >= 2432 && c <= 3583) return true;
393
- if (c >= 3584 && c <= 4095) return true;
394
- if (c >= 4096 && c <= 4255) return true;
395
- if (c >= 6016 && c <= 6143) return true;
396
- if (c >= 1424 && c <= 1791) return true;
397
- if (c >= 1792 && c <= 1871) return true;
398
- if (c >= 12288 && c <= 40959) return true;
399
- if (c >= 44032 && c <= 55215) return true;
400
- if (c >= 126976) return true;
401
- if (c >= 8592 && c <= 8703) return true;
402
- if (c >= 8704 && c <= 8959) return true;
403
- if (c >= 8960 && c <= 9215) return true;
404
- if (c >= 10176 && c <= 10223) return true;
405
- if (c >= 10624 && c <= 10751) return true;
406
- if (c >= 10752 && c <= 11007) return true;
407
- if (c >= 11008 && c <= 11097) return true;
408
- }
409
- return false;
410
- }
411
- const DECORATIVE_OUTLINE_FAMILIES = /* @__PURE__ */ new Set([
412
- "greatvibes",
413
- "great vibes",
414
- "cinzel",
415
- "cinzeldecorative",
416
- "cinzel decorative",
417
- "pacifico",
418
- "allura",
419
- "alexbrush",
420
- "alex brush",
421
- "abrilfatface",
422
- "abril fatface",
423
- "cormorant",
424
- "cormorantgaramond",
425
- "cormorant garamond",
426
- "dancingscript",
427
- "dancing script",
428
- "sacramento",
429
- "lobster",
430
- "satisfy",
431
- "kaushanscript",
432
- "kaushan script",
433
- "parisienne",
434
- "tangerine",
435
- "yellowtail",
436
- "shadowsintolight",
437
- "shadows into light",
438
- "amaticsc",
439
- "amatic sc",
440
- "caveat",
441
- "playball",
442
- "marckscript",
443
- "marck script",
444
- "courgette"
445
- ]);
446
- function isDecorativeFamily(family) {
447
- if (!family) return false;
448
- const k = family.replace(/['"]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
449
- if (DECORATIVE_OUTLINE_FAMILIES.has(k)) return true;
450
- return DECORATIVE_OUTLINE_FAMILIES.has(k.replace(/\s+/g, ""));
451
- }
452
- function readResolvedFontFamily(textEl) {
453
- var _a, _b, _c;
454
- const readStyleToken = (style, prop) => {
455
- var _a2;
456
- const m = style.match(new RegExp(`${prop}\\s*:\\s*([^;]+)`, "i"));
457
- return ((_a2 = m == null ? void 0 : m[1]) == null ? void 0 : _a2.trim()) || null;
458
- };
459
- let current = textEl;
460
- while (current) {
461
- const a = (_a = current.getAttribute("font-family")) == null ? void 0 : _a.trim();
462
- if (a) return ((_b = a.split(",")[0]) == null ? void 0 : _b.replace(/['"]/g, "").trim()) || null;
463
- const s = readStyleToken(current.getAttribute("style") || "", "font-family");
464
- if (s) return ((_c = s.split(",")[0]) == null ? void 0 : _c.replace(/['"]/g, "").trim()) || null;
465
- current = current.parentElement;
466
- }
467
- return null;
468
- }
469
- async function convertDevanagariTextToPath(svgStr, fontBaseUrl, options = {}) {
470
- var _a, _b, _c;
471
- const baseUrl = fontBaseUrl ?? (typeof window !== "undefined" ? window.location.origin + "/fonts/" : "/fonts/");
472
- const mode = options.mode ?? "all";
473
- const parser = new DOMParser();
474
- const doc = parser.parseFromString(svgStr, "image/svg+xml");
475
- const textEls = doc.querySelectorAll("text");
476
- let convertedCount = 0;
477
- let skippedCount = 0;
478
- for (const textEl of textEls) {
479
- const fullText = textEl.textContent || "";
480
- if (!fullText.trim()) continue;
481
- if (mode === "shadow-bound") {
482
- const inShadowMarker = !!textEl.closest && !!textEl.closest("g.__pdShadowRaster");
483
- let inTaggedTextbox = false;
484
- let cur = textEl.parentElement;
485
- while (cur) {
486
- if (cur.tagName.toLowerCase() === "g" && (cur.hasAttribute("data-pd-shadow-blur") || cur.hasAttribute("data-pd-text-bg"))) {
487
- inTaggedTextbox = true;
488
- break;
489
- }
490
- cur = cur.parentElement;
491
- }
492
- if (!inShadowMarker && !inTaggedTextbox) {
493
- skippedCount++;
494
- continue;
495
- }
496
- }
497
- const hasMixedStyleTspans = () => {
498
- const tspansAll = textEl.querySelectorAll("tspan");
499
- const readProp = (el, prop) => {
500
- const attr = (el.getAttribute(prop) || "").trim();
501
- if (attr) return attr;
502
- const style = el.getAttribute("style") || "";
503
- const m = style.match(new RegExp(`(?:^|;)\\s*${prop}\\s*:\\s*([^;]+)`, "i"));
504
- return m ? m[1].trim() : "";
505
- };
506
- const baseWeight = readProp(textEl, "font-weight");
507
- const baseStyle = readProp(textEl, "font-style");
508
- const baseFill = readProp(textEl, "fill");
509
- const baseDeco = readProp(textEl, "text-decoration");
510
- for (const ts of tspansAll) {
511
- const tw = readProp(ts, "font-weight");
512
- const tst = readProp(ts, "font-style");
513
- const tFill = readProp(ts, "fill");
514
- const tDeco = readProp(ts, "text-decoration");
515
- const tBg = (ts.getAttribute("style") || "").match(/background|text-background/i);
516
- if (tw && tw !== baseWeight || tst && tst !== baseStyle || tFill && tFill !== baseFill || tDeco && tDeco !== baseDeco || tBg) {
517
- return true;
518
- }
519
- }
520
- return false;
521
- };
522
- if (mode === "complex-only") {
523
- const resolvedFamily = readResolvedFontFamily(textEl);
524
- const decorative = isDecorativeFamily(resolvedFamily);
525
- if (!needsComplexShaping(fullText) && !hasMixedStyleTspans() && !decorative) {
526
- skippedCount++;
527
- continue;
528
- }
529
- }
530
- if (mode === "mixed-style-only" && !hasMixedStyleTspans()) {
531
- skippedCount++;
532
- continue;
533
- }
534
- const readStyleToken = (style, prop) => {
535
- var _a2;
536
- const m = style.match(new RegExp(`${prop}\\s*:\\s*([^;]+)`, "i"));
537
- return ((_a2 = m == null ? void 0 : m[1]) == null ? void 0 : _a2.trim()) || null;
538
- };
539
- const getAttrOrStyle = (el, attr) => {
540
- var _a2;
541
- let current = el;
542
- while (current) {
543
- const attrVal = (_a2 = current.getAttribute(attr)) == null ? void 0 : _a2.trim();
544
- if (attrVal) return attrVal;
545
- const styleVal = readStyleToken(current.getAttribute("style") || "", attr);
546
- if (styleVal) return styleVal;
547
- current = current.parentElement;
548
- }
549
- return null;
550
- };
551
- const fontFamily = (_b = (_a = getAttrOrStyle(textEl, "font-family")) == null ? void 0 : _a.split(",")[0]) == null ? void 0 : _b.replace(/['"]/g, "").trim();
552
- const fontSizeStr = getAttrOrStyle(textEl, "font-size") || "16";
553
- const fontSize = parseFloat(fontSizeStr);
554
- const fontWeightStr = getAttrOrStyle(textEl, "font-weight") || "400";
555
- const fontWeight = Number.parseInt(fontWeightStr, 10) || 400;
556
- const fillColor = getAttrOrStyle(textEl, "fill") || "#000000";
557
- const fillOpacity = getAttrOrStyle(textEl, "fill-opacity") || "1";
558
- if (!fontFamily) {
559
- skippedCount++;
560
- continue;
561
- }
562
- const primaryFont = await loadFont(fontFamily, fontWeight, baseUrl);
563
- const primaryBytes = await getFontBytes(fontFamily, fontWeight, baseUrl);
564
- const hasDeva = containsDevanagari(fullText);
565
- const hasSymbol = [...fullText].some((char) => classifyCharForFontRun(char) === "symbol");
566
- const hasMath = [...fullText].some((char) => classifyCharForFontRun(char) === "math");
567
- const devaCandidateFamilies = hasDeva ? uniqueFamilies([fontFamily, pdfFonts.FONT_FALLBACK_DEVANAGARI, pdfFonts.resolveDevanagariSibling(fontFamily)]) : [];
568
- const devaRunFontCache = /* @__PURE__ */ new Map();
569
- const resolveDevaFontForRun = (runText, runFontSize) => {
570
- const cacheKey = `${runText}__${runFontSize}`;
571
- const cached = devaRunFontCache.get(cacheKey);
572
- if (cached) return cached;
573
- const promise = (async () => {
574
- const browserWidth = measureBrowserWidth(fontFamily, fontWeight, runFontSize, runText);
575
- let best = null;
576
- for (const family of devaCandidateFamilies) {
577
- const font = family === fontFamily ? primaryFont : await loadFont(family, fontWeight, baseUrl);
578
- const bytes = family === fontFamily ? primaryBytes : await getFontBytes(family, fontWeight, baseUrl);
579
- if (!font || !bytes || !fontSupportsRun(font, runText, "devanagari")) continue;
580
- const width = measureRunWidth(font, runText, runFontSize);
581
- const diff = browserWidth == null ? 0 : Math.abs(width - browserWidth);
582
- if (!best || diff < best.diff) best = { family, font, bytes, diff };
583
- if (browserWidth != null && diff <= 0.25) break;
584
- }
585
- if (best) {
586
- console.log("[text-to-path] Devanagari font resolved", {
587
- requestedFamily: fontFamily,
588
- resolvedFamily: best.family,
589
- browserWidth,
590
- diff: Math.round(best.diff * 100) / 100
591
- });
592
- }
593
- return best;
594
- })();
595
- devaRunFontCache.set(cacheKey, promise);
596
- return promise;
597
- };
598
- const symbolRunFontPromise = hasSymbol ? (async () => {
599
- const symbolFont = await loadFont(pdfFonts.FONT_FALLBACK_SYMBOLS, 400, baseUrl);
600
- const symbolBytes = await getFontBytes(pdfFonts.FONT_FALLBACK_SYMBOLS, 400, baseUrl);
601
- return symbolFont && symbolBytes ? { family: pdfFonts.FONT_FALLBACK_SYMBOLS, font: symbolFont, bytes: symbolBytes } : null;
602
- })() : null;
603
- const mathRunFontPromise = hasMath ? (async () => {
604
- const mathFont = await loadFont(pdfFonts.FONT_FALLBACK_MATH, 400, baseUrl);
605
- const mathBytes = await getFontBytes(pdfFonts.FONT_FALLBACK_MATH, 400, baseUrl);
606
- return mathFont && mathBytes ? { family: pdfFonts.FONT_FALLBACK_MATH, font: mathFont, bytes: mathBytes } : null;
607
- })() : null;
608
- if (!primaryFont && !hasDeva && !hasSymbol && !hasMath) {
609
- console.warn(`[text-to-path] No font available for "${fontFamily}", leaving as <text>`);
610
- skippedCount++;
611
- continue;
612
- }
613
- const textAnchorRaw = (getAttrOrStyle(textEl, "text-anchor") || "start").toLowerCase();
614
- const baseTextAnchor = textAnchorRaw === "middle" ? "middle" : textAnchorRaw === "end" ? "end" : "start";
615
- const tspans = textEl.querySelectorAll("tspan");
616
- const elementsToProcess = tspans.length > 0 ? Array.from(tspans) : [textEl];
617
- const group = doc.createElementNS("http://www.w3.org/2000/svg", "g");
618
- const textTransform = textEl.getAttribute("transform");
619
- if (textTransform) group.setAttribute("transform", textTransform);
620
- const baseX = parseFloat(textEl.getAttribute("x") || "0");
621
- const baseY = parseFloat(textEl.getAttribute("y") || "0");
622
- for (const elem of elementsToProcess) {
623
- const text = elem.textContent || "";
624
- if (!text.trim()) continue;
625
- const elemX = parseFloat(elem.getAttribute("x") || String(baseX));
626
- const elemY = parseFloat(elem.getAttribute("y") || String(baseY));
627
- const elemAnchorRaw = (getAttrOrStyle(elem, "text-anchor") || baseTextAnchor).toLowerCase();
628
- const elemTextAnchor = elemAnchorRaw === "middle" ? "middle" : elemAnchorRaw === "end" ? "end" : "start";
629
- const elemTransform = elem !== textEl ? parseTranslate(elem.getAttribute("transform")) : { tx: 0, ty: 0 };
630
- let x = elemX + elemTransform.tx;
631
- const y = elemY + elemTransform.ty;
632
- const elemFill = getAttrOrStyle(elem, "fill") || fillColor;
633
- const elemFillOpacity = getAttrOrStyle(elem, "fill-opacity") || fillOpacity;
634
- const elemFontSizeStr = getAttrOrStyle(elem, "font-size") || String(fontSize);
635
- const elemFontSize = parseFloat(elemFontSizeStr);
636
- const elemWeightStr = getAttrOrStyle(elem, "font-weight") || String(fontWeight);
637
- const elemWeight = Number.parseInt(elemWeightStr, 10) || (/bold/i.test(elemWeightStr) ? 700 : fontWeight);
638
- const elemStyleRaw = (getAttrOrStyle(elem, "font-style") || "normal").toLowerCase();
639
- const elemItalic = /italic|oblique/i.test(elemStyleRaw);
640
- const sameAsPrimary = elemWeight === fontWeight && !elemItalic;
641
- const elemFont = sameAsPrimary ? primaryFont : await loadFont(fontFamily, elemWeight, baseUrl, elemItalic);
642
- const elemBytes = sameAsPrimary ? primaryBytes : await getFontBytes(fontFamily, elemWeight, baseUrl, elemItalic);
643
- const fontForElem = elemFont || primaryFont;
644
- const bytesForElem = elemBytes || primaryBytes;
645
- const runs = splitByFontRun(text);
646
- let totalAdvance = 0;
647
- let canMeasureAll = true;
648
- for (const r of runs) {
649
- if (r.runType === "devanagari") {
650
- const resolved = await resolveDevaFontForRun(r.text, elemFontSize);
651
- if (resolved) totalAdvance += measureRunWidth(resolved.font, r.text, elemFontSize);
652
- else canMeasureAll = false;
653
- } else if (r.runType === "symbol") {
654
- const resolved = await symbolRunFontPromise;
655
- if (resolved && fontSupportsRun(resolved.font, r.text, "symbol")) totalAdvance += measureRunWidth(resolved.font, r.text, elemFontSize);
656
- else canMeasureAll = false;
657
- } else if (r.runType === "math") {
658
- const resolved = await mathRunFontPromise;
659
- if (resolved && fontSupportsRun(resolved.font, r.text, "math")) totalAdvance += measureRunWidth(resolved.font, r.text, elemFontSize);
660
- else canMeasureAll = false;
661
- } else {
662
- if (fontForElem) totalAdvance += measureRunWidth(fontForElem, r.text, elemFontSize);
663
- else canMeasureAll = false;
664
- }
665
- }
666
- if (canMeasureAll) {
667
- if (elemTextAnchor === "middle") x -= totalAdvance / 2;
668
- else if (elemTextAnchor === "end") x -= totalAdvance;
669
- }
670
- let cursor = x;
671
- let elemConverted = false;
672
- for (const r of runs) {
673
- const resolvedDeva = r.runType === "devanagari" ? await resolveDevaFontForRun(r.text, elemFontSize) : null;
674
- const resolvedSymbol = r.runType === "symbol" ? await symbolRunFontPromise : null;
675
- const resolvedMath = r.runType === "math" ? await mathRunFontPromise : null;
676
- const useDeva = !!resolvedDeva;
677
- const fontForRun = (resolvedDeva == null ? void 0 : resolvedDeva.font) ?? (resolvedSymbol == null ? void 0 : resolvedSymbol.font) ?? (resolvedMath == null ? void 0 : resolvedMath.font) ?? fontForElem;
678
- const bytesForRun = (resolvedDeva == null ? void 0 : resolvedDeva.bytes) ?? (resolvedSymbol == null ? void 0 : resolvedSymbol.bytes) ?? (resolvedMath == null ? void 0 : resolvedMath.bytes) ?? bytesForElem;
679
- if (!fontForRun) continue;
680
- const result = await shapeRunToPath(
681
- r.text,
682
- !!useDeva,
683
- fontForRun,
684
- bytesForRun,
685
- (resolvedDeva == null ? void 0 : resolvedDeva.font) ?? null,
686
- (resolvedDeva == null ? void 0 : resolvedDeva.bytes) ?? null,
687
- cursor,
688
- y,
689
- elemFontSize
690
- );
691
- if (result && result.pathData) {
692
- const pathEl = doc.createElementNS("http://www.w3.org/2000/svg", "path");
693
- pathEl.setAttribute("d", result.pathData);
694
- pathEl.setAttribute("fill", elemFill);
695
- if (elemItalic && !fontLooksItalic(fontForRun)) {
696
- pathEl.setAttribute("transform", syntheticItalicTransform(cursor, y));
697
- }
698
- if (elemFillOpacity !== "1") {
699
- pathEl.setAttribute("fill-opacity", elemFillOpacity);
700
- }
701
- group.appendChild(pathEl);
702
- elemConverted = true;
703
- }
704
- if (result) cursor += result.advance;
705
- }
706
- if (elemConverted) {
707
- convertedCount++;
708
- } else {
709
- if (elem === textEl) {
710
- const clone = elem.cloneNode(true);
711
- if (textTransform) clone.removeAttribute("transform");
712
- group.appendChild(clone);
713
- } else {
714
- const newText = doc.createElementNS("http://www.w3.org/2000/svg", "text");
715
- newText.setAttribute("x", String(elemX));
716
- newText.setAttribute("y", String(elemY));
717
- if (elem.getAttribute("style")) newText.setAttribute("style", elem.getAttribute("style"));
718
- if (elem.getAttribute("font-family")) newText.setAttribute("font-family", elem.getAttribute("font-family"));
719
- if (elem.getAttribute("font-size")) newText.setAttribute("font-size", elem.getAttribute("font-size"));
720
- if (elem.getAttribute("font-weight")) newText.setAttribute("font-weight", elem.getAttribute("font-weight"));
721
- newText.textContent = text;
722
- group.appendChild(newText);
723
- }
724
- }
725
- }
726
- if (group.childNodes.length > 0) {
727
- (_c = textEl.parentNode) == null ? void 0 : _c.replaceChild(group, textEl);
728
- }
729
- }
730
- console.log(
731
- `[text-to-path] Universal outline complete: converted=${convertedCount} skipped=${skippedCount}`
732
- );
733
- return new XMLSerializer().serializeToString(doc.documentElement);
734
- }
735
- const convertAllTextToPath = convertDevanagariTextToPath;
736
- async function preloadDevanagariFont(fontBaseUrl) {
737
- const baseUrl = fontBaseUrl ?? (typeof window !== "undefined" ? window.location.origin + "/fonts/" : "/fonts/");
738
- for (const weight of [300, 400, 500, 600, 700]) {
739
- await loadFont(pdfFonts.FONT_FALLBACK_DEVANAGARI, weight, baseUrl);
740
- }
741
- }
742
- exports.convertAllTextToPath = convertAllTextToPath;
743
- exports.convertDevanagariTextToPath = convertDevanagariTextToPath;
744
- exports.preloadDevanagariFont = preloadDevanagariFont;
745
- //# sourceMappingURL=svgTextToPath-IM1f6F-f.cjs.map