@ggraphic/editor 0.1.0-alpha.5 → 0.1.0-alpha.7

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 (141) hide show
  1. package/dist/CanvasEditorProvider.d.ts +6 -1
  2. package/dist/components/CanvasEditor/CanvasEditorShell.js +139 -36
  3. package/dist/components/CanvasEditor/editorShell.d.ts +6 -0
  4. package/dist/components/CanvasEditor/types.d.ts +28 -0
  5. package/dist/components/GenericCanvas.d.ts +19 -2
  6. package/dist/components/GenericCanvas.js +28 -3
  7. package/dist/components/GenericCanvasElement.js +15 -1
  8. package/dist/components/PagePreview.d.ts +8 -1
  9. package/dist/components/PagePreview.js +4 -1
  10. package/dist/components/TopBar/ContextControls.js +1 -1
  11. package/dist/components/TopBar/DownloadSection.d.ts +24 -3
  12. package/dist/components/TopBar/DownloadSection.js +45 -7
  13. package/dist/components/TopBar/ShareDropdown.d.ts +4 -2
  14. package/dist/components/TopBar/ShareDropdown.js +2 -2
  15. package/dist/components/TopBar/modules/FloatingFontSizeControl.d.ts +3 -1
  16. package/dist/components/TopBar/modules/FloatingFontSizeControl.js +46 -4
  17. package/dist/components/kindRenderers.js +10 -1
  18. package/dist/entries/export.d.ts +14 -1
  19. package/dist/entries/export.js +14 -1
  20. package/dist/entries/services.d.ts +1 -1
  21. package/dist/export/fonts/fontFiles.d.ts +100 -0
  22. package/dist/export/fonts/fontFiles.js +333 -0
  23. package/dist/export/fonts/glyphs.d.ts +113 -0
  24. package/dist/export/fonts/glyphs.js +120 -0
  25. package/dist/export/fonts/variation.d.ts +23 -0
  26. package/dist/export/fonts/variation.js +43 -0
  27. package/dist/export/pdf/pdfContent.d.ts +108 -0
  28. package/dist/export/pdf/pdfContent.js +566 -0
  29. package/dist/export/pdf/pdfFontkit.d.ts +54 -0
  30. package/dist/export/pdf/pdfFontkit.js +159 -0
  31. package/dist/export/pdf/pdfGeometry.d.ts +54 -0
  32. package/dist/export/pdf/pdfGeometry.js +228 -0
  33. package/dist/export/pdf/pdfResources.d.ts +109 -0
  34. package/dist/export/pdf/pdfResources.js +314 -0
  35. package/dist/export/pdf/writePdf.d.ts +34 -0
  36. package/dist/export/pdf/writePdf.js +165 -0
  37. package/dist/export/pptx/exportPptxDeck.d.ts +10 -2
  38. package/dist/export/pptx/exportPptxDeck.js +5 -2
  39. package/dist/export/pptx/svgPicture.d.ts +19 -0
  40. package/dist/export/pptx/svgPicture.js +64 -0
  41. package/dist/export/pptx/vectorizeElement.d.ts +9 -0
  42. package/dist/export/pptx/vectorizeElement.js +118 -0
  43. package/dist/export/pptx/writePptx.d.ts +13 -0
  44. package/dist/export/pptx/writePptx.js +17 -0
  45. package/dist/export/printPdf.d.ts +1 -0
  46. package/dist/export/printPdf.js +1 -1
  47. package/dist/export/scene/browserDeps.d.ts +32 -0
  48. package/dist/export/scene/browserDeps.js +174 -0
  49. package/dist/export/scene/imageBytes.d.ts +79 -0
  50. package/dist/export/scene/imageBytes.js +330 -0
  51. package/dist/export/scene/itemBounds.d.ts +9 -0
  52. package/dist/export/scene/itemBounds.js +40 -0
  53. package/dist/export/scene/matrix.d.ts +13 -0
  54. package/dist/export/scene/matrix.js +32 -0
  55. package/dist/export/scene/rasterLimit.d.ts +13 -0
  56. package/dist/export/scene/rasterLimit.js +24 -0
  57. package/dist/export/scene/rebaseOps.d.ts +8 -0
  58. package/dist/export/scene/rebaseOps.js +51 -0
  59. package/dist/export/scene/recordPageScene.d.ts +28 -0
  60. package/dist/export/scene/recordPageScene.js +224 -0
  61. package/dist/export/scene/recordingCanvas.d.ts +55 -0
  62. package/dist/export/scene/recordingCanvas.js +71 -0
  63. package/dist/export/scene/recordingContext.d.ts +162 -0
  64. package/dist/export/scene/recordingContext.js +1031 -0
  65. package/dist/export/scene/replayScene.d.ts +31 -0
  66. package/dist/export/scene/replayScene.js +213 -0
  67. package/dist/export/scene/resolveScene.d.ts +48 -0
  68. package/dist/export/scene/resolveScene.js +236 -0
  69. package/dist/export/scene/trustedSvgImages.d.ts +3 -0
  70. package/dist/export/scene/trustedSvgImages.js +21 -0
  71. package/dist/export/scene/types.d.ts +241 -0
  72. package/dist/export/scene/types.js +38 -0
  73. package/dist/export/slidesPdf.d.ts +10 -2
  74. package/dist/export/slidesPdf.js +8 -4
  75. package/dist/export/svg/__fixtures__/barChart.svg +1 -0
  76. package/dist/export/svg/__golden__/fixture-editable.svg +87 -0
  77. package/dist/export/svg/__golden__/fixture-outlines.svg +88 -0
  78. package/dist/export/svg/inlineSvg.d.ts +10 -0
  79. package/dist/export/svg/inlineSvg.js +119 -0
  80. package/dist/export/svg/scopeCss.d.ts +45 -0
  81. package/dist/export/svg/scopeCss.js +214 -0
  82. package/dist/export/svg/svgColor.d.ts +8 -0
  83. package/dist/export/svg/svgColor.js +46 -0
  84. package/dist/export/svg/svgImageScene.d.ts +41 -0
  85. package/dist/export/svg/svgImageScene.js +128 -0
  86. package/dist/export/svg/svgPathData.d.ts +31 -0
  87. package/dist/export/svg/svgPathData.js +466 -0
  88. package/dist/export/svg/svgToScene.d.ts +19 -0
  89. package/dist/export/svg/svgToScene.js +1183 -0
  90. package/dist/export/svg/writeSvg.d.ts +33 -0
  91. package/dist/export/svg/writeSvg.js +594 -0
  92. package/dist/export/svg/xml.d.ts +23 -0
  93. package/dist/export/svg/xml.js +49 -0
  94. package/dist/export/vectorDeps.d.ts +27 -0
  95. package/dist/export/vectorDeps.js +37 -0
  96. package/dist/export/vectorExport.d.ts +85 -0
  97. package/dist/export/vectorExport.js +287 -0
  98. package/dist/hooks/useLiveFontSize.d.ts +6 -0
  99. package/dist/hooks/useLiveFontSize.js +26 -0
  100. package/dist/hostServices.d.ts +15 -0
  101. package/dist/i18n/de.d.ts +27 -9
  102. package/dist/i18n/de.js +27 -10
  103. package/dist/i18n/en.js +25 -0
  104. package/dist/page/actions.js +8 -2
  105. package/dist/primitives/AssetPrimitive.js +7 -2
  106. package/dist/primitives/CanvasIcons.js +6 -0
  107. package/dist/primitives/CanvasImage.js +86 -12
  108. package/dist/primitives/CanvasRichText.js +10 -5
  109. package/dist/primitives/CanvasStage.js +2 -2
  110. package/dist/primitives/CanvasText.d.ts +8 -1
  111. package/dist/primitives/CanvasText.js +25 -5
  112. package/dist/primitives/ChartPrimitive.d.ts +11 -1
  113. package/dist/primitives/ChartPrimitive.js +73 -19
  114. package/dist/primitives/IconPrimitive.js +3 -0
  115. package/dist/primitives/IllustrationPrimitive.js +14 -1
  116. package/dist/primitives/chartFont.d.ts +30 -0
  117. package/dist/primitives/chartFont.js +127 -0
  118. package/dist/sidebar/sections/ImageAdjustSection.js +5 -4
  119. package/dist/sidebar/sections/assets/ElementsPanel.js +4 -2
  120. package/dist/sidebar/sections/assets/assetAudience.d.ts +12 -0
  121. package/dist/sidebar/sections/assets/assetAudience.js +18 -0
  122. package/dist/sidebar/sections/assets/useElementCatalog.js +3 -2
  123. package/dist/styles/compiled.css +1 -1
  124. package/dist/utils/canvasAssets.d.ts +11 -1
  125. package/dist/utils/canvasAssets.js +8 -0
  126. package/dist/utils/canvasIcons.js +5 -3
  127. package/dist/utils/captureStage.d.ts +19 -0
  128. package/dist/utils/captureStage.js +14 -1
  129. package/dist/utils/cropGhost.d.ts +3 -2
  130. package/dist/utils/cropGhost.js +4 -3
  131. package/dist/utils/externalIcons.d.ts +7 -0
  132. package/dist/utils/externalIcons.js +70 -3
  133. package/dist/utils/filteredPan.d.ts +22 -0
  134. package/dist/utils/filteredPan.js +36 -0
  135. package/dist/utils/illustrations/svgCache.js +6 -1
  136. package/dist/utils/imageFilters.d.ts +13 -0
  137. package/dist/utils/imageFilters.js +11 -0
  138. package/dist/utils/zipPageImages.d.ts +8 -0
  139. package/dist/utils/zipPageImages.js +16 -4
  140. package/package.json +6 -2
  141. package/skills/ggraphic-embed/SKILL.md +33 -1
@@ -0,0 +1,333 @@
1
+ import { resolveFontFamily } from '../../utils/fontAliases.js';
2
+ import { loadFontkit } from './glyphs.js';
3
+ import { variationInstance } from './variation.js';
4
+ /**
5
+ * How far a browser shears the upright cut it draws for an italic nobody ships: Skia's fake italic
6
+ * is `skewX(-1/4)`, a quarter of the height above the baseline to the right.
7
+ */
8
+ export const SYNTHETIC_ITALIC_SLANT = 0.25;
9
+ export async function resolveFontFiles(face, deps) {
10
+ const key = `${face.family}|${face.weight}|${face.style}`;
11
+ let files = deps.cache?.get(key);
12
+ if (!files) {
13
+ files = loadFiles(face, deps);
14
+ deps.cache?.set(key, files);
15
+ }
16
+ return fileSet(face, await files);
17
+ }
18
+ function fileSet(face, files) {
19
+ return {
20
+ face,
21
+ files,
22
+ fileFor(codePoint) {
23
+ for (let i = files.length - 1; i >= 0; i--) {
24
+ const file = files[i];
25
+ if (covers(file, codePoint))
26
+ return file;
27
+ }
28
+ return null;
29
+ },
30
+ };
31
+ }
32
+ function covers(file, codePoint) {
33
+ const inRange = file.ranges === null || file.ranges.some(([from, to]) => codePoint >= from && codePoint <= to);
34
+ return inRange && file.font.hasGlyphForCodePoint(codePoint);
35
+ }
36
+ // ── Embedding permission ────────────────────────────────────────────────────
37
+ const FS_NO_EMBEDDING = 0x0002;
38
+ const FS_BITMAP_ONLY = 0x0200;
39
+ /**
40
+ * What the licence flags of a font (`OS/2.fsType`) allow: 0x0002 (restricted licence) = its
41
+ * outlines may be drawn but the font must not travel in the file; 0x0200 = only bitmaps may be
42
+ * embedded. Preview/print, editable and no-subsetting (0x0004, 0x0008, 0x0100) allow embedding.
43
+ * Takes the flag object fontkit decodes the field into as well as the raw number.
44
+ */
45
+ export function embeddingOf(fsType) {
46
+ const bits = typeof fsType === 'number'
47
+ ? fsType
48
+ : (fsType.noEmbedding ? FS_NO_EMBEDDING : 0) | (fsType.bitmapOnly ? FS_BITMAP_ONLY : 0);
49
+ if (bits & FS_BITMAP_ONLY)
50
+ return 'bitmap-only';
51
+ if (bits & FS_NO_EMBEDDING)
52
+ return 'outlines-only';
53
+ return 'yes';
54
+ }
55
+ // ── unicode-range ───────────────────────────────────────────────────────────
56
+ const MAX_CODE_POINT = 0x10ffff;
57
+ /**
58
+ * The code point ranges of a CSS `unicode-range` value: `U+26`, `U+0-7F` and `U+4??`. Tokens
59
+ * that are not a valid range are dropped.
60
+ */
61
+ export function parseUnicodeRange(value) {
62
+ const ranges = [];
63
+ for (const token of value.split(',')) {
64
+ const match = /^\s*u\+([0-9a-f?]{1,6})(?:-([0-9a-f]{1,6}))?\s*$/i.exec(token);
65
+ if (!match)
66
+ continue;
67
+ const start = match[1];
68
+ const end = match[2];
69
+ let range;
70
+ if (start.includes('?')) {
71
+ if (end !== undefined)
72
+ continue;
73
+ range = [parseInt(start.replace(/\?/g, '0'), 16), parseInt(start.replace(/\?/g, 'f'), 16)];
74
+ }
75
+ else {
76
+ const from = parseInt(start, 16);
77
+ range = [from, end === undefined ? from : parseInt(end, 16)];
78
+ }
79
+ if (range[0] <= range[1] && range[1] <= MAX_CODE_POINT)
80
+ ranges.push(range);
81
+ }
82
+ return ranges;
83
+ }
84
+ // ── Subset tag ──────────────────────────────────────────────────────────────
85
+ /**
86
+ * The six capital letters a PDF font name carries before the `+` for a subset (`ABCDEF+Name`),
87
+ * derived from the face and the index of the file in its set, so the same export names its
88
+ * subsets the same way every time. pdf-lib's own default name has no such prefix.
89
+ */
90
+ export function subsetTag(face, fileIndex) {
91
+ // FNV-1a, 32 bit, over the UTF-16 units of the key.
92
+ const key = `${face.family}|${face.weight}|${face.style}|${fileIndex}`;
93
+ let hash = 0x811c9dc5;
94
+ for (let i = 0; i < key.length; i++) {
95
+ hash = Math.imul(hash ^ key.charCodeAt(i), 0x01000193) >>> 0;
96
+ }
97
+ let tag = '';
98
+ for (let i = 0; i < 6; i++) {
99
+ tag += String.fromCharCode(65 + (hash % 26));
100
+ hash = Math.floor(hash / 26);
101
+ }
102
+ return tag;
103
+ }
104
+ async function loadFiles(face, deps) {
105
+ const family = bareFamily(resolveFontFamily(face.family));
106
+ const boldFamily = face.weight >= 600 ? deps.boldFamilies?.[family] : undefined;
107
+ const attempts = boldFamily
108
+ ? [
109
+ { family: boldFamily, weight: 400 },
110
+ { family, weight: face.weight },
111
+ ]
112
+ : [{ family, weight: face.weight }];
113
+ const find = async (style) => {
114
+ for (const attempt of attempts) {
115
+ const { files, served } = await filesFor(attempt.family, attempt.weight, style, deps);
116
+ if (files.length === 0)
117
+ continue;
118
+ // A bold asked for and a lighter cut served (the bold family's own regular is not that).
119
+ const fakeBold = attempt.weight >= 600 && served !== null && served < 600;
120
+ // A variable font covers the weights of its axis whatever its @font-face says.
121
+ return fakeBold
122
+ ? files.map((file) => (file.font.variationAxes?.['wght'] ? file : { ...file, fakeBold }))
123
+ : files;
124
+ }
125
+ return [];
126
+ };
127
+ const files = await find(face.style);
128
+ if (files.length > 0 || face.style === 'normal')
129
+ return files;
130
+ // An italic the family does not ship. A style is never traded for a weight above (a real italic
131
+ // of another weight beats the upright), but with no italic at all a browser slants the upright
132
+ // cut, so the export does: the file is the upright one, flagged for the writers to shear.
133
+ return (await find('normal')).map((file) => ({ ...file, slant: SYNTHETIC_ITALIC_SLANT }));
134
+ }
135
+ /** The files for one family and weight, and the weight they serve (null: unknown). */
136
+ async function filesFor(family, weight, style, deps) {
137
+ // The host's service is code we do not control: a throw is a font it does not have, the same
138
+ // as a download that fails, and the next source is asked.
139
+ let hosted = null;
140
+ try {
141
+ hosted = await deps.host?.load({ family, weight, style });
142
+ }
143
+ catch {
144
+ hosted = null;
145
+ }
146
+ if (hosted) {
147
+ const file = await toFontFile(hosted, null, weight);
148
+ // The host does not say which weight it served; the font's own class does (a host that
149
+ // answers a bold request with its regular is the case fake bold exists for).
150
+ const declared = file?.font['OS/2']?.usWeightClass;
151
+ if (file)
152
+ return { files: [file], served: declared && declared > 0 ? declared : null };
153
+ }
154
+ const fetchBytes = deps.fetchBytes ?? fetchOverHttp;
155
+ // The brand's faces first; the page's `@font-face` rules only if the brand has none.
156
+ const sources = [
157
+ () => brandCandidates(deps.brandFaces ?? [], family),
158
+ () => cssCandidates((deps.cssRules ?? documentFontFaces)(), family),
159
+ ];
160
+ for (const candidatesOf of sources) {
161
+ const picked = pickCandidates(candidatesOf(), weight, style);
162
+ const files = await loadCandidates(picked, fetchBytes, weight);
163
+ if (files.length > 0) {
164
+ const [first] = picked;
165
+ return { files, served: first ? Math.min(Math.max(weight, first.low), first.high) : null };
166
+ }
167
+ }
168
+ return { files: [], served: null };
169
+ }
170
+ function brandCandidates(faces, family) {
171
+ const wanted = family.toLowerCase();
172
+ return faces
173
+ .filter((face) => face.family.toLowerCase() === wanted)
174
+ .map((face) => ({
175
+ low: face.weight ?? 400,
176
+ high: face.weight ?? 400,
177
+ style: face.style ?? 'normal',
178
+ urls: [face.src],
179
+ ranges: null,
180
+ }));
181
+ }
182
+ function cssCandidates(rules, family) {
183
+ const wanted = family.toLowerCase();
184
+ const candidates = [];
185
+ for (const rule of rules) {
186
+ const declared = rule.style.getPropertyValue.bind(rule.style);
187
+ if (bareFamily(declared('font-family')).toLowerCase() !== wanted)
188
+ continue;
189
+ const urls = readableUrls(declared('src'));
190
+ if (urls.length === 0)
191
+ continue;
192
+ const [low, high] = parseWeights(declared('font-weight'));
193
+ const ranges = parseUnicodeRange(declared('unicode-range'));
194
+ candidates.push({
195
+ low,
196
+ high,
197
+ style: /^\s*(italic|oblique)/i.test(declared('font-style')) ? 'italic' : 'normal',
198
+ urls,
199
+ ranges: ranges.length > 0 ? ranges : null,
200
+ });
201
+ }
202
+ return candidates;
203
+ }
204
+ /**
205
+ * The candidates serving the style and the weight closest to `weight`. A style is never traded
206
+ * for a weight: an italic of another weight is closer to what was asked than the upright cut of
207
+ * the right one. An empty answer is for `loadFiles` to turn into a slanted upright cut.
208
+ */
209
+ function pickCandidates(candidates, weight, style) {
210
+ const styled = candidates.filter((c) => c.style === style);
211
+ const served = (c) => Math.min(Math.max(weight, c.low), c.high);
212
+ const best = nearestWeight(styled.map(served), weight);
213
+ return styled.filter((c) => served(c) === best);
214
+ }
215
+ /**
216
+ * CSS Fonts 4, "font matching": the exact weight; else for 400 to 500 the heavier weights up to
217
+ * 500 (ascending), then the lighter ones (descending), then those above 500; below 400 the
218
+ * lighter ones first, above 500 the heavier ones first, each followed by the other side.
219
+ */
220
+ function nearestWeight(available, target) {
221
+ if (available.length === 0 || available.includes(target))
222
+ return target;
223
+ const lighter = available.filter((w) => w < target).sort((a, b) => b - a);
224
+ const heavier = available.filter((w) => w > target).sort((a, b) => a - b);
225
+ if (target > 500)
226
+ return heavier[0] ?? lighter[0];
227
+ if (target >= 400)
228
+ return heavier.find((w) => w <= 500) ?? lighter[0] ?? heavier[0];
229
+ return lighter[0] ?? heavier[0];
230
+ }
231
+ /** `normal`, `bold`, `700` or a variable-font range `100 900`. */
232
+ function parseWeights(value) {
233
+ const weights = value
234
+ .trim()
235
+ .split(/\s+/)
236
+ .map((token) => (token === 'normal' ? 400 : token === 'bold' ? 700 : Number(token)))
237
+ .filter((weight) => Number.isFinite(weight) && weight > 0);
238
+ if (weights.length === 0)
239
+ return [400, 400];
240
+ return [Math.min(...weights), Math.max(...weights)];
241
+ }
242
+ async function loadCandidates(candidates, fetchBytes, weight) {
243
+ const files = await Promise.all(candidates.map(async (candidate) => {
244
+ for (const url of candidate.urls) {
245
+ const bytes = await fetchBytes(url).catch(() => null);
246
+ const file = bytes && (await toFontFile(bytes, candidate.ranges, weight));
247
+ if (file)
248
+ return file;
249
+ }
250
+ return null;
251
+ }));
252
+ return files.filter((file) => file !== null);
253
+ }
254
+ async function toFontFile(bytes, ranges, weight) {
255
+ const parsed = await parseFont(bytes);
256
+ if (!parsed)
257
+ return null;
258
+ const { font, variation } = variationInstance(parsed, weight);
259
+ return {
260
+ bytes,
261
+ font,
262
+ embeddable: embeddingOf(parsed['OS/2']?.fsType ?? 0),
263
+ ranges,
264
+ slant: 0,
265
+ fakeBold: false,
266
+ variation,
267
+ };
268
+ }
269
+ async function parseFont(bytes) {
270
+ const fontkit = await loadFontkit();
271
+ try {
272
+ // Boundary cast: fontkit's shipped declarations lack what `FontkitFont` adds (see glyphs.ts).
273
+ const font = fontkit.create(bytes);
274
+ // A collection (TTC) answers `create` with its list of fonts rather than a font.
275
+ return typeof font.glyphForCodePoint === 'function' ? font : null;
276
+ }
277
+ catch {
278
+ return null;
279
+ }
280
+ }
281
+ // ── CSS sources and the network ─────────────────────────────────────────────
282
+ /** `url(...)` entries of a `src` descriptor in a format fontkit reads, in order; `local()` is skipped. */
283
+ function readableUrls(src) {
284
+ const entry = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\)(?:\s*format\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\))?/gi;
285
+ const urls = [];
286
+ for (const match of src.matchAll(entry)) {
287
+ const url = match[1] ?? match[2] ?? match[3] ?? '';
288
+ const format = (match[4] ?? match[5] ?? match[6])?.toLowerCase().replace(/-variations$/, '');
289
+ const readable = format
290
+ ? ['woff2', 'woff', 'truetype', 'opentype'].includes(format)
291
+ : !/\.(eot|svg)(?:[?#]|$)/i.test(url);
292
+ if (url && readable)
293
+ urls.push(url);
294
+ }
295
+ return urls;
296
+ }
297
+ /** The family without the quotes CSS allows around it. */
298
+ function bareFamily(family) {
299
+ return family.trim().replace(/^(['"])(.*)\1$/, '$2');
300
+ }
301
+ async function fetchOverHttp(url) {
302
+ const response = await fetch(url);
303
+ return response.ok ? new Uint8Array(await response.arrayBuffer()) : null;
304
+ }
305
+ /**
306
+ * The `@font-face` rules of every style sheet of the document, imports and grouping rules
307
+ * included. The default of `FontSourceDeps.cssRules`; exported for its own test.
308
+ */
309
+ export function* documentFontFaces() {
310
+ if (typeof document === 'undefined')
311
+ return;
312
+ for (const sheet of Array.from(document.styleSheets))
313
+ yield* fontFacesIn(sheet);
314
+ }
315
+ function* fontFacesIn(container) {
316
+ let rules;
317
+ try {
318
+ rules = container.cssRules;
319
+ }
320
+ catch {
321
+ return; // a cross-origin sheet without CORS hides its rules
322
+ }
323
+ for (const rule of Array.from(rules)) {
324
+ if (rule instanceof CSSFontFaceRule)
325
+ yield rule;
326
+ else if (rule instanceof CSSImportRule) {
327
+ if (rule.styleSheet)
328
+ yield* fontFacesIn(rule.styleSheet);
329
+ }
330
+ else if (rule instanceof CSSGroupingRule)
331
+ yield* fontFacesIn(rule);
332
+ }
333
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Glyphs for the vector export: the fontkit boundary, the split of a text op into runs by the
3
+ * font file that covers each code point, and glyph outlines as scene paths.
4
+ */
5
+ import type * as FontkitModule from '@pdf-lib/fontkit';
6
+ import type { PathCommand } from '../scene/types.js';
7
+ import type { FontFile, FontFileSet } from './fontFiles.js';
8
+ /**
9
+ * The part of a fontkit font the export reads. This is the boundary to an untyped module:
10
+ * `@pdf-lib/fontkit` ships declarations, but they leave out `OS/2.fsType` (decoded into the flag
11
+ * object below, not the number the spec names) and `path.commands`, and type `OS/2` as something
12
+ * else. `parseFont` in `fontFiles.ts` is the one place that casts into this.
13
+ */
14
+ export interface FontkitFont {
15
+ postscriptName: string | null;
16
+ unitsPerEm: number;
17
+ /** Every code point the font's cmap maps to a glyph. */
18
+ characterSet: readonly number[];
19
+ /** The table is absent in fonts that never declare a licence flag. */
20
+ 'OS/2'?: {
21
+ fsType?: FontkitFsType;
22
+ usWeightClass?: number;
23
+ };
24
+ hasGlyphForCodePoint(codePoint: number): boolean;
25
+ /** One glyph for one code point, no shaping; code points outside the font give `.notdef`. */
26
+ glyphForCodePoint(codePoint: number): FontkitGlyph;
27
+ /** The shaped glyphs of a string, with the default features (what `pdf-lib` embeds). */
28
+ layout(text: string): {
29
+ glyphs: readonly FontkitGlyph[];
30
+ };
31
+ /** The axes of a variable font, by tag; `{}` for any other. */
32
+ variationAxes?: Readonly<Record<string, {
33
+ min: number;
34
+ default: number;
35
+ max: number;
36
+ }>>;
37
+ /** The font with the axes set, for a variable font with `glyf` outlines (not for WOFF2: see `variation.ts`). */
38
+ getVariation?(settings: Record<string, number>): FontkitFont;
39
+ /** Which tables the file holds; `glyf.transformed` is WOFF2's. */
40
+ directory?: {
41
+ tables?: {
42
+ glyf?: {
43
+ transformed?: boolean;
44
+ };
45
+ CFF2?: unknown;
46
+ };
47
+ };
48
+ }
49
+ /** What fontkit makes of `OS/2.fsType`: the bits it names (a number if a future version stops decoding them). */
50
+ export type FontkitFsType = number | {
51
+ noEmbedding?: boolean;
52
+ viewOnly?: boolean;
53
+ editable?: boolean;
54
+ noSubsetting?: boolean;
55
+ bitmapOnly?: boolean;
56
+ };
57
+ export interface FontkitGlyph {
58
+ advanceWidth: number;
59
+ /** y up, in font units. */
60
+ path: {
61
+ commands: readonly FontkitPathSegment[];
62
+ };
63
+ }
64
+ export interface FontkitPathSegment {
65
+ command: 'moveTo' | 'lineTo' | 'quadraticCurveTo' | 'bezierCurveTo' | 'closePath';
66
+ args: readonly number[];
67
+ }
68
+ /**
69
+ * fontkit is large; it loads when an export needs a font, never with the editor. The result is the
70
+ * object `pdf-lib`'s `registerFontkit` takes.
71
+ */
72
+ export declare function loadFontkit(): Promise<typeof FontkitModule>;
73
+ /**
74
+ * The glyphs a font draws for one code point on its own: what the browser shapes it to and what
75
+ * `pdf-lib` embeds (it encodes text through `layout`), not the glyph the cmap names. They differ
76
+ * in a font with required variation alternates: Fraunces Italic draws its 'w' with a glyph of 1491
77
+ * units where the cmap one has 1644, and the x positions the browser measured are those of the
78
+ * shaped glyph. Never empty.
79
+ */
80
+ export declare function glyphsFor(font: FontkitFont, codePoint: number): readonly FontkitGlyph[];
81
+ /** The advance of `codePoint` in font units: that of the glyphs `glyphsFor` gives, and so of the glyphs a PDF holds. */
82
+ export declare function advanceOf(font: FontkitFont, codePoint: number): number;
83
+ /**
84
+ * The width of the outline a browser adds to a regular cut it draws for a bold nobody ships
85
+ * (Skia's fake bold): `size / 24` at 9 px and below, `size / 32` at 36 px and above, in between
86
+ * the factor falls linearly.
87
+ */
88
+ export declare function fakeBoldWidth(size: number): number;
89
+ /** A stretch of a text op that one font file draws; `file` is null where no file has the glyphs. */
90
+ export interface GlyphRun {
91
+ file: FontFile | null;
92
+ text: string;
93
+ /** One x per code point of `text`, the slice of the op's `xs`. */
94
+ xs: number[];
95
+ }
96
+ /**
97
+ * Cuts `text` into maximal runs of code points the same file covers, so a writer draws each run
98
+ * with its own font and can report the runs nobody covers. `xs` has one entry per code point, as
99
+ * in the scene's text ops.
100
+ */
101
+ export declare function splitRuns(set: FontFileSet, text: string, xs: number[]): GlyphRun[];
102
+ /**
103
+ * The outline of every code point of `text` in `file`, scaled to `size` px, y down, baseline at 0
104
+ * and the pen at x = 0 (the writer moves each glyph to its own x). One entry per code point, in
105
+ * the order of the op's `xs`, so a ligature is not formed and kerning is left to the positions
106
+ * the browser measured. A glyph is the one the font shapes the code point to on its own (see
107
+ * `glyphsFor`). A combining mark gets no base to attach to: precomposed text is exact.
108
+ * A file with a `slant` (an upright cut standing in for an italic) is sheared about the baseline.
109
+ */
110
+ export declare function glyphOutline(file: FontFile, text: string, size: number): {
111
+ advance: number;
112
+ path: PathCommand[];
113
+ }[];
@@ -0,0 +1,120 @@
1
+ /**
2
+ * fontkit is large; it loads when an export needs a font, never with the editor. The result is the
3
+ * object `pdf-lib`'s `registerFontkit` takes.
4
+ */
5
+ export async function loadFontkit() {
6
+ // Boundary cast: the module's default export is the object the shipped declarations describe
7
+ // as the module namespace (`create`, ...), and the declarations do not list `default`.
8
+ const module = (await import('@pdf-lib/fontkit'));
9
+ return module.default;
10
+ }
11
+ const shaped = new WeakMap();
12
+ /**
13
+ * The glyphs a font draws for one code point on its own: what the browser shapes it to and what
14
+ * `pdf-lib` embeds (it encodes text through `layout`), not the glyph the cmap names. They differ
15
+ * in a font with required variation alternates: Fraunces Italic draws its 'w' with a glyph of 1491
16
+ * units where the cmap one has 1644, and the x positions the browser measured are those of the
17
+ * shaped glyph. Never empty.
18
+ */
19
+ export function glyphsFor(font, codePoint) {
20
+ let known = shaped.get(font);
21
+ if (!known)
22
+ shaped.set(font, (known = new Map()));
23
+ let glyphs = known.get(codePoint);
24
+ if (!glyphs) {
25
+ const laidOut = font.layout(String.fromCodePoint(codePoint)).glyphs;
26
+ glyphs = laidOut.length > 0 ? laidOut : [font.glyphForCodePoint(codePoint)];
27
+ known.set(codePoint, glyphs);
28
+ }
29
+ return glyphs;
30
+ }
31
+ /** The advance of `codePoint` in font units: that of the glyphs `glyphsFor` gives, and so of the glyphs a PDF holds. */
32
+ export function advanceOf(font, codePoint) {
33
+ return glyphsFor(font, codePoint).reduce((sum, glyph) => sum + glyph.advanceWidth, 0);
34
+ }
35
+ /**
36
+ * The width of the outline a browser adds to a regular cut it draws for a bold nobody ships
37
+ * (Skia's fake bold): `size / 24` at 9 px and below, `size / 32` at 36 px and above, in between
38
+ * the factor falls linearly.
39
+ */
40
+ export function fakeBoldWidth(size) {
41
+ const t = Math.min(Math.max((size - 9) / (36 - 9), 0), 1);
42
+ return size * (1 / 24 + t * (1 / 32 - 1 / 24));
43
+ }
44
+ /**
45
+ * Cuts `text` into maximal runs of code points the same file covers, so a writer draws each run
46
+ * with its own font and can report the runs nobody covers. `xs` has one entry per code point, as
47
+ * in the scene's text ops.
48
+ */
49
+ export function splitRuns(set, text, xs) {
50
+ const runs = [];
51
+ let index = 0;
52
+ for (const char of text) {
53
+ const file = set.fileFor(char.codePointAt(0) ?? 0);
54
+ const x = xs[index++];
55
+ const last = runs.at(-1);
56
+ if (last && last.file === file) {
57
+ last.text += char;
58
+ last.xs.push(x);
59
+ }
60
+ else {
61
+ runs.push({ file, text: char, xs: [x] });
62
+ }
63
+ }
64
+ return runs;
65
+ }
66
+ /**
67
+ * The outline of every code point of `text` in `file`, scaled to `size` px, y down, baseline at 0
68
+ * and the pen at x = 0 (the writer moves each glyph to its own x). One entry per code point, in
69
+ * the order of the op's `xs`, so a ligature is not formed and kerning is left to the positions
70
+ * the browser measured. A glyph is the one the font shapes the code point to on its own (see
71
+ * `glyphsFor`). A combining mark gets no base to attach to: precomposed text is exact.
72
+ * A file with a `slant` (an upright cut standing in for an italic) is sheared about the baseline.
73
+ */
74
+ export function glyphOutline(file, text, size) {
75
+ const { font, slant } = file;
76
+ const scale = size / font.unitsPerEm;
77
+ // `0 - y` rather than `-y`: a flipped 0 must stay +0, or the output differs by a "-0".
78
+ const x = (fx, fy) => (slant === 0 ? fx * scale : (fx + slant * fy) * scale);
79
+ const y = (fy) => 0 - fy * scale;
80
+ return Array.from(text, (char) => {
81
+ const codePoint = char.codePointAt(0) ?? 0;
82
+ // A soft hyphen is not drawn by a canvas (it only shows at a line break) and is 0 wide.
83
+ if (codePoint === 0xad)
84
+ return { advance: 0, path: [] };
85
+ // The shaped glyph, as the browser draws it; one that shapes into several (a decomposition)
86
+ // keeps the glyph of the cmap, which has the whole character in one outline.
87
+ const shapedGlyphs = glyphsFor(font, codePoint);
88
+ const glyph = shapedGlyphs.length === 1 ? shapedGlyphs[0] : font.glyphForCodePoint(codePoint);
89
+ const path = glyph.path.commands.map((segment) => {
90
+ const a = segment.args;
91
+ switch (segment.command) {
92
+ case 'moveTo':
93
+ return { op: 'M', x: x(a[0], a[1]), y: y(a[1]) };
94
+ case 'lineTo':
95
+ return { op: 'L', x: x(a[0], a[1]), y: y(a[1]) };
96
+ case 'quadraticCurveTo':
97
+ return {
98
+ op: 'Q',
99
+ x1: x(a[0], a[1]),
100
+ y1: y(a[1]),
101
+ x: x(a[2], a[3]),
102
+ y: y(a[3]),
103
+ };
104
+ case 'bezierCurveTo':
105
+ return {
106
+ op: 'C',
107
+ x1: x(a[0], a[1]),
108
+ y1: y(a[1]),
109
+ x2: x(a[2], a[3]),
110
+ y2: y(a[3]),
111
+ x: x(a[4], a[5]),
112
+ y: y(a[5]),
113
+ };
114
+ case 'closePath':
115
+ return { op: 'Z' };
116
+ }
117
+ });
118
+ return { advance: glyph.advanceWidth * scale, path };
119
+ });
120
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The instance of a variable font for the weight a text asks for. A font file with a `wght` axis
3
+ * draws its default instance when fontkit is not told otherwise (Bricolage Grotesque: ExtraBold),
4
+ * so a regular text would come out bold, with the advances of a bold.
5
+ *
6
+ * `font.getVariation` makes the instance for a font file that is plain TrueType (TTF). It cannot
7
+ * for a webfont: it re-reads the file as plain TrueType, which a WOFF is not and fails at the
8
+ * first glyph (the probe in `makeInstance` catches that), and fontkit decodes the glyphs of a
9
+ * WOFF2, which is what most webfonts are, in advance, with no variations applied. (Measured on 1.1.1: instancing it by hand gets the advances of the weight, from
10
+ * `HVAR`, but the outlines of the default; that is worse than the default for both.) Such a font
11
+ * stays at its default instance and is reported (`ExportReport.defaultInstanceFonts`).
12
+ */
13
+ import type { FontkitFont } from './glyphs.js';
14
+ /**
15
+ * `none`: the font as parsed is the one asked for (not variable, or the weight is the default).
16
+ * `instance`: `font` is the instance for the weight. `default-only`: the font is variable and the
17
+ * weight differs from its default, but no instance could be made; `font` is the default instance.
18
+ */
19
+ export type Variation = 'none' | 'instance' | 'default-only';
20
+ export declare function variationInstance(font: FontkitFont, weight: number): {
21
+ font: FontkitFont;
22
+ variation: Variation;
23
+ };
@@ -0,0 +1,43 @@
1
+ const instances = new WeakMap();
2
+ export function variationInstance(font, weight) {
3
+ const axes = font.variationAxes;
4
+ const wght = axes?.['wght'];
5
+ if (!axes || !wght)
6
+ return { font, variation: 'none' };
7
+ const asked = Math.min(Math.max(weight, wght.min), wght.max);
8
+ if (asked === wght.default)
9
+ return { font, variation: 'none' };
10
+ let known = instances.get(font);
11
+ if (!known)
12
+ instances.set(font, (known = new Map()));
13
+ let made = known.get(asked);
14
+ if (!made) {
15
+ const instance = makeInstance(font, axes, asked);
16
+ made = instance
17
+ ? { font: instance, variation: 'instance' }
18
+ : { font, variation: 'default-only' };
19
+ known.set(asked, made);
20
+ }
21
+ return made;
22
+ }
23
+ function makeInstance(font, axes, weight) {
24
+ const tables = font.directory?.tables;
25
+ // Cubic outlines cannot be written into a PDF font program, see `pdfFontkit.ts`. A WOFF2
26
+ // font's glyphs are decoded in advance, without the variations, so fontkit cannot instance it.
27
+ if (!tables || tables.CFF2 || !tables.glyf || tables.glyf.transformed)
28
+ return null;
29
+ const settings = Object.fromEntries(Object.entries(axes).map(([tag, axis]) => [tag, tag === 'wght' ? weight : axis.default]));
30
+ try {
31
+ const instance = font.getVariation?.(settings);
32
+ if (!instance)
33
+ return null;
34
+ // Draw one glyph: an instance that fontkit cannot decode fails here, not later in a writer.
35
+ const [first] = instance.characterSet;
36
+ if (first !== undefined)
37
+ void instance.glyphForCodePoint(first).path.commands;
38
+ return instance;
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }