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

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 (125) 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/PagePreview.d.ts +8 -1
  8. package/dist/components/PagePreview.js +4 -1
  9. package/dist/components/TopBar/DownloadSection.d.ts +24 -3
  10. package/dist/components/TopBar/DownloadSection.js +45 -7
  11. package/dist/components/TopBar/ShareDropdown.d.ts +4 -2
  12. package/dist/components/TopBar/ShareDropdown.js +2 -2
  13. package/dist/entries/export.d.ts +14 -1
  14. package/dist/entries/export.js +14 -1
  15. package/dist/entries/services.d.ts +1 -1
  16. package/dist/export/fonts/fontFiles.d.ts +100 -0
  17. package/dist/export/fonts/fontFiles.js +333 -0
  18. package/dist/export/fonts/glyphs.d.ts +113 -0
  19. package/dist/export/fonts/glyphs.js +120 -0
  20. package/dist/export/fonts/variation.d.ts +23 -0
  21. package/dist/export/fonts/variation.js +43 -0
  22. package/dist/export/pdf/pdfContent.d.ts +108 -0
  23. package/dist/export/pdf/pdfContent.js +566 -0
  24. package/dist/export/pdf/pdfFontkit.d.ts +54 -0
  25. package/dist/export/pdf/pdfFontkit.js +159 -0
  26. package/dist/export/pdf/pdfGeometry.d.ts +54 -0
  27. package/dist/export/pdf/pdfGeometry.js +228 -0
  28. package/dist/export/pdf/pdfResources.d.ts +109 -0
  29. package/dist/export/pdf/pdfResources.js +314 -0
  30. package/dist/export/pdf/writePdf.d.ts +34 -0
  31. package/dist/export/pdf/writePdf.js +165 -0
  32. package/dist/export/pptx/exportPptxDeck.d.ts +10 -2
  33. package/dist/export/pptx/exportPptxDeck.js +5 -2
  34. package/dist/export/pptx/svgPicture.d.ts +19 -0
  35. package/dist/export/pptx/svgPicture.js +64 -0
  36. package/dist/export/pptx/vectorizeElement.d.ts +9 -0
  37. package/dist/export/pptx/vectorizeElement.js +118 -0
  38. package/dist/export/pptx/writePptx.d.ts +13 -0
  39. package/dist/export/pptx/writePptx.js +17 -0
  40. package/dist/export/printPdf.d.ts +1 -0
  41. package/dist/export/printPdf.js +1 -1
  42. package/dist/export/scene/browserDeps.d.ts +32 -0
  43. package/dist/export/scene/browserDeps.js +174 -0
  44. package/dist/export/scene/imageBytes.d.ts +79 -0
  45. package/dist/export/scene/imageBytes.js +330 -0
  46. package/dist/export/scene/itemBounds.d.ts +9 -0
  47. package/dist/export/scene/itemBounds.js +40 -0
  48. package/dist/export/scene/matrix.d.ts +13 -0
  49. package/dist/export/scene/matrix.js +32 -0
  50. package/dist/export/scene/rasterLimit.d.ts +13 -0
  51. package/dist/export/scene/rasterLimit.js +24 -0
  52. package/dist/export/scene/rebaseOps.d.ts +8 -0
  53. package/dist/export/scene/rebaseOps.js +51 -0
  54. package/dist/export/scene/recordPageScene.d.ts +28 -0
  55. package/dist/export/scene/recordPageScene.js +224 -0
  56. package/dist/export/scene/recordingCanvas.d.ts +55 -0
  57. package/dist/export/scene/recordingCanvas.js +71 -0
  58. package/dist/export/scene/recordingContext.d.ts +162 -0
  59. package/dist/export/scene/recordingContext.js +1031 -0
  60. package/dist/export/scene/replayScene.d.ts +31 -0
  61. package/dist/export/scene/replayScene.js +213 -0
  62. package/dist/export/scene/resolveScene.d.ts +48 -0
  63. package/dist/export/scene/resolveScene.js +236 -0
  64. package/dist/export/scene/trustedSvgImages.d.ts +3 -0
  65. package/dist/export/scene/trustedSvgImages.js +21 -0
  66. package/dist/export/scene/types.d.ts +241 -0
  67. package/dist/export/scene/types.js +38 -0
  68. package/dist/export/slidesPdf.d.ts +10 -2
  69. package/dist/export/slidesPdf.js +8 -4
  70. package/dist/export/svg/__fixtures__/barChart.svg +1 -0
  71. package/dist/export/svg/__golden__/fixture-editable.svg +87 -0
  72. package/dist/export/svg/__golden__/fixture-outlines.svg +88 -0
  73. package/dist/export/svg/inlineSvg.d.ts +10 -0
  74. package/dist/export/svg/inlineSvg.js +119 -0
  75. package/dist/export/svg/scopeCss.d.ts +45 -0
  76. package/dist/export/svg/scopeCss.js +214 -0
  77. package/dist/export/svg/svgColor.d.ts +8 -0
  78. package/dist/export/svg/svgColor.js +46 -0
  79. package/dist/export/svg/svgImageScene.d.ts +41 -0
  80. package/dist/export/svg/svgImageScene.js +128 -0
  81. package/dist/export/svg/svgPathData.d.ts +31 -0
  82. package/dist/export/svg/svgPathData.js +466 -0
  83. package/dist/export/svg/svgToScene.d.ts +19 -0
  84. package/dist/export/svg/svgToScene.js +1183 -0
  85. package/dist/export/svg/writeSvg.d.ts +33 -0
  86. package/dist/export/svg/writeSvg.js +594 -0
  87. package/dist/export/svg/xml.d.ts +23 -0
  88. package/dist/export/svg/xml.js +49 -0
  89. package/dist/export/vectorDeps.d.ts +27 -0
  90. package/dist/export/vectorDeps.js +37 -0
  91. package/dist/export/vectorExport.d.ts +85 -0
  92. package/dist/export/vectorExport.js +287 -0
  93. package/dist/hostServices.d.ts +15 -0
  94. package/dist/i18n/de.d.ts +26 -9
  95. package/dist/i18n/de.js +26 -10
  96. package/dist/i18n/en.js +24 -0
  97. package/dist/primitives/AssetPrimitive.js +7 -2
  98. package/dist/primitives/CanvasIcons.js +6 -0
  99. package/dist/primitives/CanvasStage.js +2 -2
  100. package/dist/primitives/ChartPrimitive.d.ts +11 -1
  101. package/dist/primitives/ChartPrimitive.js +73 -19
  102. package/dist/primitives/IconPrimitive.js +3 -0
  103. package/dist/primitives/IllustrationPrimitive.js +14 -1
  104. package/dist/primitives/chartFont.d.ts +30 -0
  105. package/dist/primitives/chartFont.js +127 -0
  106. package/dist/sidebar/sections/ImageAdjustSection.js +5 -4
  107. package/dist/sidebar/sections/assets/ElementsPanel.js +4 -2
  108. package/dist/sidebar/sections/assets/assetAudience.d.ts +12 -0
  109. package/dist/sidebar/sections/assets/assetAudience.js +18 -0
  110. package/dist/sidebar/sections/assets/useElementCatalog.js +3 -2
  111. package/dist/styles/compiled.css +1 -1
  112. package/dist/utils/canvasAssets.d.ts +11 -1
  113. package/dist/utils/canvasAssets.js +8 -0
  114. package/dist/utils/canvasIcons.js +5 -3
  115. package/dist/utils/captureStage.d.ts +19 -0
  116. package/dist/utils/captureStage.js +14 -1
  117. package/dist/utils/externalIcons.d.ts +7 -0
  118. package/dist/utils/externalIcons.js +70 -3
  119. package/dist/utils/illustrations/svgCache.js +6 -1
  120. package/dist/utils/imageFilters.d.ts +13 -0
  121. package/dist/utils/imageFilters.js +11 -0
  122. package/dist/utils/zipPageImages.d.ts +8 -0
  123. package/dist/utils/zipPageImages.js +16 -4
  124. package/package.json +6 -2
  125. package/skills/ggraphic-embed/SKILL.md +33 -1
@@ -0,0 +1,330 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * The bytes behind one drawn image, as a source a writer can embed (`SceneImageSource`).
4
+ *
5
+ * - PNG and JPEG pass through with their metadata removed (`stripJpegMetadata`,
6
+ * `stripPngMetadata`: Exif and its GPS position, XMP, text chunks), the image data untouched. A
7
+ * JPEG with an EXIF orientation other than 1 does not pass through: the browser turns it when
8
+ * it draws, a file does not, so it goes through `reencode`, which drops the metadata with it.
9
+ * - WebP, GIF and AVIF are re-encoded: opaque ones as JPEG, the others as PNG.
10
+ * - An SVG the editor generated itself is inlined as it is (`trusted`: the caller knows from who
11
+ * made the image element, see `trustedSvgImages.ts`; the look of the url proves nothing). Every
12
+ * other SVG is a trust boundary and goes through `sanitizeSvg` before it is inlined anywhere.
13
+ * The sanitiser also strips what an SVG may be drawn with (`<style>`, `class`, `<text>` …), so
14
+ * a foreign SVG that uses any of it is not inlined at all: it is `svg-unsupported`, and the
15
+ * caller draws it from the stage.
16
+ *
17
+ * Every function answers a failure rather than throwing; the caller decides what that costs.
18
+ */
19
+ import { sanitizeSvg } from '@ggraphic/schema';
20
+ const UNREADABLE = { ok: false, reason: 'image-unreadable' };
21
+ const UNSUPPORTED = { ok: false, reason: 'svg-unsupported' };
22
+ const found = (source) => source ? { ok: true, source } : UNREADABLE;
23
+ /** Runs `work`; a throw is "cannot be read", like any other failure to read. */
24
+ export async function attempt(work) {
25
+ try {
26
+ return await work();
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ // ---------------------------------------------------------------------------------------------
33
+ // Formats
34
+ const startsWith = (bytes, at, text) => [...text].every((char, n) => bytes[at + n] === char.charCodeAt(0));
35
+ /** The raster format the bytes are, by their magic number; what a server called it is not trusted. */
36
+ export function sniffRaster(bytes) {
37
+ if (bytes[0] === 0x89 && startsWith(bytes, 1, 'PNG\r\n') && bytes[6] === 0x1a)
38
+ return 'image/png';
39
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff)
40
+ return 'image/jpeg';
41
+ if (startsWith(bytes, 0, 'GIF8'))
42
+ return 'image/gif';
43
+ if (startsWith(bytes, 0, 'RIFF') && startsWith(bytes, 8, 'WEBP'))
44
+ return 'image/webp';
45
+ if (startsWith(bytes, 4, 'ftyp') &&
46
+ (startsWith(bytes, 8, 'avif') || startsWith(bytes, 8, 'avis'))) {
47
+ return 'image/avif';
48
+ }
49
+ return null;
50
+ }
51
+ /**
52
+ * Whether a WebP can have transparent pixels, from its first chunk: `VP8 ` (lossy) never does and
53
+ * `VP8X` says so in its flags. `VP8L` (lossless) is taken to: its `alpha_is_used` bit is only a
54
+ * hint, and a lossless file that ignores it still decodes with transparency.
55
+ */
56
+ function webpHasAlpha(bytes) {
57
+ if (startsWith(bytes, 12, 'VP8X'))
58
+ return ((bytes[20] ?? 0) & 0x10) !== 0;
59
+ return startsWith(bytes, 12, 'VP8L');
60
+ }
61
+ /**
62
+ * The marker segments of a JPEG that have a length, in file order, up to the image data (`SOS`)
63
+ * or the end. A segment cut off by the end of the file ends at the end of the file. The walk stops
64
+ * where the structure stops making sense; what lies beyond is not a segment of ours.
65
+ */
66
+ function* jpegSegments(bytes) {
67
+ const at = (i) => bytes[i] ?? 0;
68
+ if (at(0) !== 0xff || at(1) !== 0xd8)
69
+ return;
70
+ let cursor = 2;
71
+ while (cursor + 4 <= bytes.length) {
72
+ if (at(cursor) !== 0xff)
73
+ return;
74
+ const marker = at(cursor + 1);
75
+ // Fill bytes, and the markers that stand alone and have no length.
76
+ if (marker === 0xff) {
77
+ cursor += 1;
78
+ continue;
79
+ }
80
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) {
81
+ cursor += 2;
82
+ continue;
83
+ }
84
+ // Image data or the end: no segment of this kind comes after it.
85
+ if (marker === 0xda || marker === 0xd9)
86
+ return;
87
+ const length = (at(cursor + 2) << 8) | at(cursor + 3);
88
+ if (length < 2)
89
+ return;
90
+ const end = Math.min(cursor + 2 + length, bytes.length);
91
+ yield { marker, start: cursor, end };
92
+ cursor += 2 + length;
93
+ }
94
+ }
95
+ /**
96
+ * The orientation tag (EXIF 0x0112, 1..8) of a JPEG; 1 when there is none, or when the file is
97
+ * not one we can read it from. Reads the first IFD of the Exif segment's TIFF block in whichever
98
+ * byte order it declares.
99
+ */
100
+ export function jpegOrientation(bytes) {
101
+ for (const { marker, start, end } of jpegSegments(bytes)) {
102
+ if (marker === 0xe1 && startsWith(bytes, start + 4, 'Exif\0\0')) {
103
+ return tiffOrientation(bytes, start + 10, end);
104
+ }
105
+ }
106
+ return 1;
107
+ }
108
+ function tiffOrientation(bytes, tiff, end) {
109
+ const at = (i) => bytes[i] ?? 0;
110
+ const little = startsWith(bytes, tiff, 'II');
111
+ if (!little && !startsWith(bytes, tiff, 'MM'))
112
+ return 1;
113
+ const u16 = (i) => (little ? at(i) | (at(i + 1) << 8) : (at(i) << 8) | at(i + 1));
114
+ const u32 = (i) => (little ? u16(i) + u16(i + 2) * 65536 : u16(i) * 65536 + u16(i + 2));
115
+ if (u16(tiff + 2) !== 42)
116
+ return 1;
117
+ const ifd = tiff + u32(tiff + 4);
118
+ if (ifd + 2 > end)
119
+ return 1;
120
+ const entries = u16(ifd);
121
+ for (let n = 0; n < entries; n += 1) {
122
+ const entry = ifd + 2 + n * 12;
123
+ if (entry + 12 > end)
124
+ return 1;
125
+ // A SHORT sits in the first two bytes of the entry's value field, in either byte order.
126
+ if (u16(entry) === 0x0112) {
127
+ const value = u16(entry + 8);
128
+ return value >= 1 && value <= 8 ? value : 1;
129
+ }
130
+ }
131
+ return 1;
132
+ }
133
+ // ---------------------------------------------------------------------------------------------
134
+ // Metadata
135
+ /** `bytes` without the half-open `ranges` (in order, not overlapping); the same array when none. */
136
+ function withoutRanges(bytes, ranges) {
137
+ if (ranges.length === 0)
138
+ return bytes;
139
+ const removed = ranges.reduce((total, { start, end }) => total + (end - start), 0);
140
+ const kept = new Uint8Array(bytes.length - removed);
141
+ let from = 0;
142
+ let to = 0;
143
+ for (const { start, end } of ranges) {
144
+ kept.set(bytes.subarray(from, start), to);
145
+ to += start - from;
146
+ from = end;
147
+ }
148
+ kept.set(bytes.subarray(from), to);
149
+ return kept;
150
+ }
151
+ /**
152
+ * Whether a JPEG segment is part of the picture rather than about it. APP0 (JFIF) and APP14
153
+ * (Adobe: the colour transform of a CMYK or YCCK file) are read by decoders; APP2 only when it
154
+ * carries the ICC profile. APP1 (Exif, XMP, and with them the GPS position), APP3 to APP13 and
155
+ * APP15 (Photoshop, IPTC …) and comments are not.
156
+ */
157
+ function isJpegPicture(bytes, { marker, start }) {
158
+ if (marker === 0xe0 || marker === 0xee)
159
+ return true;
160
+ if (marker === 0xe2)
161
+ return startsWith(bytes, start + 4, 'ICC_PROFILE\0');
162
+ return !(marker >= 0xe1 && marker <= 0xef) && marker !== 0xfe;
163
+ }
164
+ /**
165
+ * The JPEG without its metadata: the image data and what decodes it stay byte for byte. A photo
166
+ * is placed in a file that is sent on, and its Exif can hold where it was taken. A file whose
167
+ * segments cannot be walked to the image data is returned as it is: a decoder cannot find
168
+ * metadata in what it cannot walk either.
169
+ */
170
+ export function stripJpegMetadata(bytes) {
171
+ return withoutRanges(bytes, [...jpegSegments(bytes)].filter((segment) => !isJpegPicture(bytes, segment)));
172
+ }
173
+ /** PNG chunks that are text, a timestamp or Exif: about the picture, not part of it. */
174
+ const PNG_METADATA = new Set(['tEXt', 'zTXt', 'iTXt', 'eXIf', 'tIME']);
175
+ /**
176
+ * The PNG without its text, time and Exif chunks. The colour chunks (`iCCP`, `sRGB`, `gAMA`,
177
+ * `cHRM`) and `pHYs` stay, and so does every chunk that is the image. A file whose chunks do not
178
+ * add up is returned as far as they did: what was found before the break is dropped.
179
+ */
180
+ export function stripPngMetadata(bytes) {
181
+ const dropped = [];
182
+ let cursor = 8;
183
+ while (cursor + 12 <= bytes.length) {
184
+ const length = (bytes[cursor] ?? 0) * 0x1000000 +
185
+ (((bytes[cursor + 1] ?? 0) << 16) |
186
+ ((bytes[cursor + 2] ?? 0) << 8) |
187
+ (bytes[cursor + 3] ?? 0));
188
+ const end = cursor + 12 + length;
189
+ if (end > bytes.length)
190
+ break;
191
+ const type = String.fromCharCode(...bytes.subarray(cursor + 4, cursor + 8));
192
+ if (PNG_METADATA.has(type))
193
+ dropped.push({ start: cursor, end });
194
+ if (type === 'IEND')
195
+ break;
196
+ cursor = end;
197
+ }
198
+ return withoutRanges(bytes, dropped);
199
+ }
200
+ export function parseDataUrl(url) {
201
+ const match = /^data:([^,]*),([\s\S]*)$/i.exec(url);
202
+ if (!match)
203
+ return null;
204
+ const [mime = '', ...params] = (match[1] ?? '').split(';');
205
+ return {
206
+ mime: mime.trim().toLowerCase(),
207
+ base64: params.some((param) => param.trim().toLowerCase() === 'base64'),
208
+ payload: match[2] ?? '',
209
+ };
210
+ }
211
+ function base64Bytes(payload) {
212
+ try {
213
+ const binary = atob(payload);
214
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
215
+ }
216
+ catch {
217
+ return null;
218
+ }
219
+ }
220
+ const decodeText = (bytes) => new TextDecoder().decode(bytes);
221
+ function dataUrlText(data) {
222
+ if (data.base64) {
223
+ const bytes = base64Bytes(data.payload);
224
+ return bytes ? decodeText(bytes) : null;
225
+ }
226
+ try {
227
+ return decodeURIComponent(data.payload);
228
+ }
229
+ catch {
230
+ // Not percent-encoded after all (`data:image/svg+xml;utf8,<svg …>`).
231
+ return data.payload;
232
+ }
233
+ }
234
+ /** The bytes of a base64 PNG data url, or null for anything else. */
235
+ export function pngFromDataUrl(dataUrl) {
236
+ const data = parseDataUrl(dataUrl);
237
+ return data?.base64 && data.mime === 'image/png' ? base64Bytes(data.payload) : null;
238
+ }
239
+ /** The PNG of a canvas, or null for an empty or tainted one. */
240
+ export function canvasPng(canvas) {
241
+ try {
242
+ return pngFromDataUrl(canvas.toDataURL('image/png'));
243
+ }
244
+ catch {
245
+ return null;
246
+ }
247
+ }
248
+ // ---------------------------------------------------------------------------------------------
249
+ // Sources
250
+ const bitmap = (mime, bytes, size) => ({ kind: 'bitmap', mime, bytes, ...size });
251
+ const svg = (markup, size) => ({
252
+ kind: 'svg',
253
+ markup,
254
+ ...size,
255
+ });
256
+ /**
257
+ * What `sanitizeSvg` throws away that a picture is drawn with: style sheets, `class` and `style`
258
+ * attributes, text, embedded images, filters, patterns, markers, links and `switch`, animation.
259
+ * Looked for in the markup as it was, because the sanitised copy cannot say what is missing from
260
+ * it. A hit may be a false alarm (the word in a text node); the cost is a raster instead of a
261
+ * vector, never a lost picture.
262
+ */
263
+ const LOST_BY_SANITISING = /<(?:[\w-]+:)?(?:style|text|image|filter|foreignObject|pattern|marker|a|switch|animate\w*|set)[\s/>]|\s(?:class|style|filter)\s*=/i;
264
+ /** An SVG that is not ours: sanitised, or `svg-unsupported` when sanitising would change it. */
265
+ function foreignSvg(markup, size) {
266
+ if (LOST_BY_SANITISING.test(markup))
267
+ return UNSUPPORTED;
268
+ const clean = sanitizeSvg(markup);
269
+ return clean === null ? UNSUPPORTED : { ok: true, source: svg(clean, size) };
270
+ }
271
+ /** Whether fetched bytes are SVG text: by what the server said, or by how the text starts. */
272
+ function isSvgText(bytes, mime) {
273
+ if (mime.toLowerCase().includes('svg'))
274
+ return true;
275
+ return /^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg[\s>]/i.test(decodeText(bytes.subarray(0, 512)));
276
+ }
277
+ async function reencoded(bytes, mime, opaque, size, deps) {
278
+ const result = await attempt(() => deps.reencode(bytes, mime, opaque));
279
+ if (!result)
280
+ return UNREADABLE;
281
+ // The size is the one the canvas measured its source rectangle in; the bitmap only supplies it
282
+ // when the element had none.
283
+ return found(bitmap(result.mime, result.bytes, {
284
+ width: size.width || result.width,
285
+ height: size.height || result.height,
286
+ }));
287
+ }
288
+ async function fromBytes(bytes, mime, size, deps, trusted) {
289
+ const raster = sniffRaster(bytes);
290
+ if (raster === 'image/png')
291
+ return found(bitmap(raster, stripPngMetadata(bytes), size));
292
+ if (raster === 'image/jpeg') {
293
+ return jpegOrientation(bytes) === 1
294
+ ? found(bitmap(raster, stripJpegMetadata(bytes), size))
295
+ : reencoded(bytes, raster, true, size, deps);
296
+ }
297
+ if (raster) {
298
+ // Only a WebP says whether it has alpha without being decoded; for the rest, the pixels do.
299
+ const opaque = raster === 'image/webp' ? !webpHasAlpha(bytes) : null;
300
+ return reencoded(bytes, raster, opaque, size, deps);
301
+ }
302
+ if (!isSvgText(bytes, mime))
303
+ return UNREADABLE;
304
+ const markup = decodeText(bytes);
305
+ return trusted ? { ok: true, source: svg(markup, size) } : foreignSvg(markup, size);
306
+ }
307
+ /**
308
+ * The source behind an image url. `trusted`: the image element was made by editor code that
309
+ * generated this SVG itself (`isTrustedSvgImage`); it only matters for SVG.
310
+ */
311
+ export async function sourceFromUrl(url, size, deps, trusted) {
312
+ const data = parseDataUrl(url);
313
+ if (data?.mime === 'image/svg+xml') {
314
+ const markup = dataUrlText(data);
315
+ if (markup === null)
316
+ return UNREADABLE;
317
+ return trusted ? { ok: true, source: svg(markup, size) } : foreignSvg(markup, size);
318
+ }
319
+ const fetched = data?.base64 ? bytesOf(data) : await attempt(() => deps.fetchBytes(url));
320
+ return fetched ? fromBytes(fetched.bytes, fetched.mime, size, deps, trusted) : UNREADABLE;
321
+ }
322
+ function bytesOf(data) {
323
+ const bytes = base64Bytes(data.payload);
324
+ return bytes ? { bytes, mime: data.mime } : null;
325
+ }
326
+ /** A canvas's pixels as a PNG source. */
327
+ export function sourceFromCanvas(canvas, size) {
328
+ const png = canvasPng(canvas);
329
+ return found(png ? bitmap('image/png', png, size) : null);
330
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Where an item draws, in page px: the box a picture of that one element has to cover. The ink of
3
+ * each op is `opBounds` (matrix, stroke, clips); what it does not know is a shadow, which reaches
4
+ * past the shape by its offset and three sigma of blur (the reach `writeSvg` gives its filter).
5
+ */
6
+ import { type Rect } from '../pdf/pdfGeometry.js';
7
+ import type { SceneItem } from './types.js';
8
+ /** The union of everything the item's ops draw, or null when it draws nothing that can be known. */
9
+ export declare function itemBounds(item: SceneItem): Rect | null;
@@ -0,0 +1,40 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * Where an item draws, in page px: the box a picture of that one element has to cover. The ink of
4
+ * each op is `opBounds` (matrix, stroke, clips); what it does not know is a shadow, which reaches
5
+ * past the shape by its offset and three sigma of blur (the reach `writeSvg` gives its filter).
6
+ */
7
+ import { clipped, opBounds, transformRect, unionRect } from '../pdf/pdfGeometry.js';
8
+ /** The ink and the shadow of `op`, in page px; null when it draws nothing. */
9
+ function inkOf(op) {
10
+ let ink;
11
+ if (op.kind === 'group') {
12
+ // The children's matrices are absolute; the group's own matrix then moves what they drew.
13
+ let union = null;
14
+ for (const child of op.ops)
15
+ union = unionRect(union, inkOf(child));
16
+ ink = clipped(union && transformRect(union, op.matrix), op);
17
+ }
18
+ else {
19
+ ink = opBounds(op);
20
+ }
21
+ if (!ink || !op.shadow)
22
+ return ink;
23
+ // Blur is the canvas `shadowBlur`: a Gaussian of sigma blur / 2.
24
+ const reach = 1.5 * op.shadow.blur;
25
+ const { offsetX, offsetY } = op.shadow;
26
+ return unionRect(ink, {
27
+ x0: ink.x0 + offsetX - reach,
28
+ y0: ink.y0 + offsetY - reach,
29
+ x1: ink.x1 + offsetX + reach,
30
+ y1: ink.y1 + offsetY + reach,
31
+ });
32
+ }
33
+ /** The union of everything the item's ops draw, or null when it draws nothing that can be known. */
34
+ export function itemBounds(item) {
35
+ let union = null;
36
+ for (const op of item.ops)
37
+ union = unionRect(union, inkOf(op));
38
+ const finite = union && [union.x0, union.y0, union.x1, union.y1].every(Number.isFinite);
39
+ return finite ? union : null;
40
+ }
@@ -0,0 +1,13 @@
1
+ import type { Matrix } from './types.js';
2
+ export declare const IDENTITY: Matrix;
3
+ /**
4
+ * `a · b`: the matrix that applies `b` first, then `a`. With `a` the current transform,
5
+ * `multiply(a, b)` is what the canvas `transform(...b)` call leaves behind.
6
+ */
7
+ export declare function multiply(a: Matrix, b: Matrix): Matrix;
8
+ /** Throws a `RangeError` for a singular matrix; there is no sensible inverse to hand back. */
9
+ export declare function invert(m: Matrix): Matrix;
10
+ export declare function apply(m: Matrix, x: number, y: number): {
11
+ x: number;
12
+ y: number;
13
+ };
@@ -0,0 +1,32 @@
1
+ export const IDENTITY = [1, 0, 0, 1, 0, 0];
2
+ /**
3
+ * `a · b`: the matrix that applies `b` first, then `a`. With `a` the current transform,
4
+ * `multiply(a, b)` is what the canvas `transform(...b)` call leaves behind.
5
+ */
6
+ export function multiply(a, b) {
7
+ return [
8
+ a[0] * b[0] + a[2] * b[1],
9
+ a[1] * b[0] + a[3] * b[1],
10
+ a[0] * b[2] + a[2] * b[3],
11
+ a[1] * b[2] + a[3] * b[3],
12
+ a[0] * b[4] + a[2] * b[5] + a[4],
13
+ a[1] * b[4] + a[3] * b[5] + a[5],
14
+ ];
15
+ }
16
+ /** Throws a `RangeError` for a singular matrix; there is no sensible inverse to hand back. */
17
+ export function invert(m) {
18
+ const det = m[0] * m[3] - m[1] * m[2];
19
+ if (!Number.isFinite(det) || det === 0)
20
+ throw new RangeError('cannot invert a singular matrix');
21
+ return [
22
+ m[3] / det,
23
+ -m[1] / det,
24
+ -m[2] / det,
25
+ m[0] / det,
26
+ (m[2] * m[5] - m[3] * m[4]) / det,
27
+ (m[1] * m[4] - m[0] * m[5]) / det,
28
+ ];
29
+ }
30
+ export function apply(m, x, y) {
31
+ return { x: m[0] * x + m[2] * y + m[4], y: m[1] * x + m[3] * y + m[5] };
32
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The most pixels one bitmap may have: iOS Safari refuses a canvas of more than 2^24 px, and a
3
+ * print page at 300 dpi (A3: ~17.4 Mpx) is over it.
4
+ */
5
+ export declare const MAX_RASTER_PIXELS = 16777216;
6
+ /**
7
+ * `pixelRatio`, lowered if a box of `width` x `height` page px would be over `MAX_RASTER_PIXELS`
8
+ * at it; the aspect ratio is kept. `reduced` says whether it had to be.
9
+ */
10
+ export declare function fitPixelRatio(width: number, height: number, pixelRatio: number): {
11
+ pixelRatio: number;
12
+ reduced: boolean;
13
+ };
@@ -0,0 +1,24 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * The most pixels one bitmap may have: iOS Safari refuses a canvas of more than 2^24 px, and a
4
+ * print page at 300 dpi (A3: ~17.4 Mpx) is over it.
5
+ */
6
+ export const MAX_RASTER_PIXELS = 16_777_216;
7
+ /**
8
+ * `pixelRatio`, lowered if a box of `width` x `height` page px would be over `MAX_RASTER_PIXELS`
9
+ * at it; the aspect ratio is kept. `reduced` says whether it had to be.
10
+ */
11
+ export function fitPixelRatio(width, height, pixelRatio) {
12
+ // Snapping a box to whole device px and the rasteriser's `ceil` add up to 2 px a side; the margin
13
+ // keeps the result inside.
14
+ const pixels = (Math.ceil(width * pixelRatio) + 2) * (Math.ceil(height * pixelRatio) + 2);
15
+ if (!(pixels > MAX_RASTER_PIXELS) || !(width > 0) || !(height > 0)) {
16
+ return { pixelRatio, reduced: false };
17
+ }
18
+ // `ceil(w*r) + 2` is under `w*r + 3`: solve (w*r + 3) * (h*r + 3) = MAX for r, then take a hair
19
+ // less, so the checked product is guaranteed to be within the limit.
20
+ const a = width * height;
21
+ const b = 3 * (width + height);
22
+ const r = (-b + Math.sqrt(b * b + 4 * a * (MAX_RASTER_PIXELS - 9))) / (2 * a);
23
+ return { pixelRatio: Math.min(pixelRatio, r * 0.9999), reduced: true };
24
+ }
@@ -0,0 +1,8 @@
1
+ import type { SceneOp } from './types.js';
2
+ export interface PageBox {
3
+ x: number;
4
+ y: number;
5
+ width: number;
6
+ height: number;
7
+ }
8
+ export declare function rebaseOps(ops: readonly SceneOp[], box: PageBox, pixelRatio: number): SceneOp[];
@@ -0,0 +1,51 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * Moves ops from page px onto a canvas that shows only a box of the page, at a pixel ratio, so
4
+ * `replayScene` can draw them there. Replay sets every op's matrix absolutely, so the move has to
5
+ * be part of the ops: matrix and clip matrices get the box origin and the ratio on top. Shadow
6
+ * blur and offsets are device px (the CTM does not apply to them), so the ratio scales them too.
7
+ *
8
+ * Used by whoever answers a writer's request to raster ops (`WritePdfOptions.rasterize`).
9
+ */
10
+ import { invert, multiply } from './matrix.js';
11
+ export function rebaseOps(ops, box, pixelRatio) {
12
+ const base = [pixelRatio, 0, 0, pixelRatio, -box.x * pixelRatio, -box.y * pixelRatio];
13
+ // A writer groups neighbours that share a clip by reference: moved clips stay shared.
14
+ const movedClips = new Map();
15
+ const moveClip = (clip) => {
16
+ let moved = movedClips.get(clip);
17
+ if (!moved) {
18
+ moved = { ...clip, matrix: multiply(base, clip.matrix) };
19
+ movedClips.set(clip, moved);
20
+ }
21
+ return moved;
22
+ };
23
+ const rebase = (op) => {
24
+ const moved = {
25
+ matrix: multiply(base, op.matrix),
26
+ clips: op.clips.map(moveClip),
27
+ shadow: op.shadow && {
28
+ ...op.shadow,
29
+ blur: op.shadow.blur * pixelRatio,
30
+ offsetX: op.shadow.offsetX * pixelRatio,
31
+ offsetY: op.shadow.offsetY * pixelRatio,
32
+ },
33
+ };
34
+ switch (op.kind) {
35
+ case 'group':
36
+ // The children are moved by `base` alone, and replay draws them under the group's matrix:
37
+ // that matrix has to act in the moved space, or `base` is applied twice.
38
+ return {
39
+ ...op,
40
+ ...moved,
41
+ matrix: multiply(base, multiply(op.matrix, invert(base))),
42
+ ops: op.ops.map(rebase),
43
+ };
44
+ case 'raster':
45
+ return { ...op, ...moved, source: op.source && op.source.map(rebase) };
46
+ default:
47
+ return { ...op, ...moved };
48
+ }
49
+ };
50
+ return ops.map(rebase);
51
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Records a mounted page stage as a scene (`types.ts`): one item per canvas element, in render
3
+ * order, each a flat list of ops in page px. Konva draws the elements; the recording canvas
4
+ * (`recordingCanvas.ts`) turns what it draws into ops.
5
+ *
6
+ * Page px are the format's px: the stage is shown at a display scale, and a page whose layout is
7
+ * drawn in a smaller logical size sits under a scaled group (`PAGE_ROOT_NAME`). Elements are drawn
8
+ * relative to their layer, which leaves out the display scale of the stage and keeps the group's.
9
+ */
10
+ import Konva from 'konva';
11
+ import { type RecordedScene } from './types.js';
12
+ export interface RecordPageOptions {
13
+ page: number;
14
+ /**
15
+ * The page in px. Without it, the stage's own size at scale 1: exact where the stage was sized in
16
+ * whole px at that scale, but `CanvasStage` rounds its container to whole display px, which puts
17
+ * the height up to half a display px off.
18
+ */
19
+ size?: {
20
+ width: number;
21
+ height: number;
22
+ };
23
+ /** Labels per canvasItemId, from layerLabel(); missing → null. */
24
+ labels?: ReadonlyMap<string, string>;
25
+ /** Draw no page background (SVG transparent export). */
26
+ transparent?: boolean;
27
+ }
28
+ export declare function recordPageScene(stage: Konva.Stage, options: RecordPageOptions): RecordedScene;