@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,118 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * Answers a PPTX raster request with the element as SVG instead of a PNG: the page is recorded
4
+ * and resolved once per slide (the way the SVG export does it), the request's element is picked
5
+ * out of it, and a scene of that one element, moved so its bounds start at the origin, is written
6
+ * as an SVG whose size is those bounds. PowerPoint draws the SVG and keeps a PNG preview for
7
+ * viewers that do not.
8
+ *
9
+ * Only an element that is vector all the way is answered: a raster op in it (a filtered photo, a
10
+ * glyph run no font covers) means the SVG would hold a picture of it, and the PNG of the element
11
+ * does that better. Text is outlines, so no viewer needs a font the file does not carry; an
12
+ * element whose text cannot be outlined, or whose SVG picture sets its own text, is left to the
13
+ * PNG too. So is an element with a shadow (the PNG has it baked in; whether PowerPoint draws a
14
+ * filter shadow is not known) and one the resolver lost a picture of (an SVG with a part missing).
15
+ *
16
+ * The SVG is checked before it is answered (`svgPicture.ts`): pptxgenjs makes its PNG preview
17
+ * together with the rest of the media, and one SVG that fails there loses the whole deck. Anything
18
+ * that goes wrong answers null, which is the PNG path.
19
+ */
20
+ import { itemBounds } from '../scene/itemBounds.js';
21
+ import { rebaseOps } from '../scene/rebaseOps.js';
22
+ import { resolveScene } from '../scene/resolveScene.js';
23
+ import { emptyReport } from '../scene/types.js';
24
+ import { formatNumber } from '../svg/xml.js';
25
+ import { writeSvg } from '../svg/writeSvg.js';
26
+ import { fontsOf } from '../vectorExport.js';
27
+ import { canPreviewSvg, isWellFormedSvg } from './svgPicture.js';
28
+ /**
29
+ * The SVG is sized at this many px to the page px. pptxgenjs makes the PNG preview of an SVG at
30
+ * the SVG's own size, and the raster this replaces was drawn at twice the page px.
31
+ */
32
+ const PREVIEW_SCALE = 2;
33
+ /** What a canvas holds in one go (the preview is drawn on one): per side, and in all. */
34
+ const MAX_PREVIEW_SIDE = 8192;
35
+ const MAX_PREVIEW_AREA = 16_000_000;
36
+ /** Whether `test` holds for an op, or for any op inside a group. */
37
+ function someOp(ops, test) {
38
+ return ops.some((op) => test(op) || (op.kind === 'group' && someOp(op.ops, test)));
39
+ }
40
+ const isRaster = (op) => op.kind === 'raster';
41
+ const hasShadow = (op) => op.shadow !== null;
42
+ /** An SVG picture with text of its own: a viewer sets it in whatever font it has. */
43
+ const hasPictureText = (op) => op.kind === 'image' && op.image.kind === 'svg' && /<text[\s>]/i.test(op.image.markup);
44
+ /** The root's `width` and `height` (not its `viewBox`) at the preview scale, within what a canvas holds. */
45
+ function sizeForPreview(svg, width, height) {
46
+ const scale = Math.min(PREVIEW_SCALE, MAX_PREVIEW_SIDE / Math.max(width, height), Math.sqrt(MAX_PREVIEW_AREA / (width * height)));
47
+ return svg.replace(/^(<svg [^>]*? width=")[^"]*(" height=")[^"]*"/, (_whole, before, between) => `${before}${formatNumber(width * scale)}${between}${formatNumber(height * scale)}"`);
48
+ }
49
+ export function createVectorizer(deps, { canPreview = canPreviewSvg } = {}) {
50
+ // One cache for the export: a face used by several elements is read once.
51
+ const fontDeps = { ...deps.fontDeps, cache: deps.fontDeps.cache ?? new Map() };
52
+ const slides = new Map();
53
+ const sceneOf = (slideIndex) => {
54
+ // Slides are asked for in order: a scene no later request needs is not kept.
55
+ for (const earlier of slides.keys())
56
+ if (earlier < slideIndex)
57
+ slides.delete(earlier);
58
+ let scene = slides.get(slideIndex);
59
+ if (!scene) {
60
+ scene = (async () => {
61
+ const recorded = await deps.recordPage(slideIndex, { transparent: false });
62
+ if (!recorded)
63
+ return null;
64
+ return resolveScene(recorded, {
65
+ ...deps.resolveDeps(slideIndex),
66
+ page: slideIndex + 1,
67
+ });
68
+ })().catch(() => null);
69
+ slides.set(slideIndex, scene);
70
+ }
71
+ return scene;
72
+ };
73
+ const write = async (item, page) => {
74
+ const bounds = itemBounds(item);
75
+ if (!bounds)
76
+ return null;
77
+ const box = {
78
+ x: bounds.x0,
79
+ y: bounds.y0,
80
+ width: bounds.x1 - bounds.x0,
81
+ height: bounds.y1 - bounds.y0,
82
+ };
83
+ if (box.width <= 0 || box.height <= 0)
84
+ return null;
85
+ const report = emptyReport();
86
+ const moved = { ...item, ops: rebaseOps(item.ops, box, 1) };
87
+ const alone = { width: box.width, height: box.height, items: [moved], report };
88
+ const fonts = await fontsOf(alone, fontDeps);
89
+ const written = writeSvg(alone, { text: 'outlines', fonts, report, page });
90
+ // A run without a font file came out as `<text>`: the PNG shows what the canvas showed.
91
+ if (report.missingGlyphs.length > 0)
92
+ return null;
93
+ const svg = sizeForPreview(written, box.width, box.height);
94
+ // pptxgenjs would fail the whole deck on an SVG it cannot make a preview of.
95
+ if (!isWellFormedSvg(svg) || !(await canPreview(svg)))
96
+ return null;
97
+ return { svg, box };
98
+ };
99
+ return async (request, slideIndex) => {
100
+ try {
101
+ const scene = await sceneOf(slideIndex);
102
+ const item = scene?.items.find((candidate) => candidate.elementId === request.elementId);
103
+ if (!scene || !item)
104
+ return null;
105
+ // The resolver drops a picture it cannot read: what is left is not the element.
106
+ if (scene.report.missingElements.some((m) => m.elementId === request.elementId))
107
+ return null;
108
+ const ops = item.ops;
109
+ if (someOp(ops, isRaster) || someOp(ops, hasShadow) || someOp(ops, hasPictureText)) {
110
+ return null;
111
+ }
112
+ return await write(item, slideIndex + 1);
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ };
118
+ }
@@ -15,6 +15,14 @@ export interface PptxRasterImage {
15
15
  dataUrl: string;
16
16
  box: PptxBox;
17
17
  }
18
+ /**
19
+ * Ein Element als SVG-Bild: das Markup plus seine achsparallele Box in Seiten-px (Drehung im Bild).
20
+ * pptxgenjs legt dazu das PNG-Vorschaubild an, das ältere Programme statt des SVG zeigen.
21
+ */
22
+ export interface PptxVectorImage {
23
+ svg: string;
24
+ box: PptxBox;
25
+ }
18
26
  /** Ein geladenes Bild: PNG/JPEG als Data-URL plus Eigenmaße (für den Zuschnitt). */
19
27
  export interface PptxLoadedImage {
20
28
  dataUrl: string;
@@ -24,6 +32,11 @@ export interface PptxLoadedImage {
24
32
  export interface WritePptxDeps {
25
33
  /** `null` oder Fehler: Knoten nicht gefunden oder nicht lesbar — das Element fehlt dann. */
26
34
  rasterize: (request: PptxRasterRequest, slideIndex: number) => Promise<PptxRasterImage | null>;
35
+ /**
36
+ * Das Element als SVG statt als PNG, oder `null` (oder Fehler): dann kommt `rasterize` dran.
37
+ * Gefragt wird zuerst; ohne diese Abhängigkeit bleibt es bei PNG.
38
+ */
39
+ vectorize?: (request: PptxRasterRequest, slideIndex: number) => Promise<PptxVectorImage | null>;
27
40
  /** `null`: Quelle nicht ladbar — das Bild wird dann gerastert. */
28
41
  loadImage: (src: string) => Promise<PptxLoadedImage | null>;
29
42
  onProgress?: (done: number, total: number) => void;
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate';
13
13
  import { parseColor, pptxRotation, pptxUnits, transparencyOf, } from './pptxUnits.js';
14
+ import { svgDataUrl } from './svgPicture.js';
14
15
  import { shadowProps, textBoxOptions, textRuns } from './writeText.js';
15
16
  export const PPTX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
16
17
  function addShape(slide, item, units) {
@@ -157,7 +158,23 @@ export async function writePptx(model, deps) {
157
158
  pres.title = deps.title;
158
159
  const units = pptxUnits(model.page.width);
159
160
  const skipped = [];
161
+ const vectorOf = async (request, slideIndex) => {
162
+ if (!deps.vectorize)
163
+ return null;
164
+ try {
165
+ return await deps.vectorize(request, slideIndex);
166
+ }
167
+ catch {
168
+ return null;
169
+ }
170
+ };
160
171
  const rasterInto = async (slide, request, slideIndex) => {
172
+ // Erst als SVG: dieselbe Box wie beim PNG, nur das Bildformat ist ein anderes.
173
+ const vector = await vectorOf(request, slideIndex);
174
+ if (vector) {
175
+ addRaster(slide, { dataUrl: svgDataUrl(vector.svg), box: vector.box }, request.elementId, units);
176
+ return;
177
+ }
161
178
  // Ein Raster, das wirft, kostet nur dieses Element, nicht den ganzen Export.
162
179
  const image = await deps.rasterize(request, slideIndex).catch(() => null);
163
180
  if (image)
@@ -8,6 +8,7 @@
8
8
  * oben links, y nach unten (wie die Stage). PDF rechnet von unten links.
9
9
  */
10
10
  export declare const PT_PER_MM: number;
11
+ export declare const MARK_STROKE_PT = 0.25;
11
12
  export interface SizeMm {
12
13
  width: number;
13
14
  height: number;
@@ -13,7 +13,7 @@ const MM_PER_INCH = 25.4;
13
13
  const DEFAULT_MARK_MM = 5;
14
14
  /** Abstand der Schnittmarken zur Beschnittkante, damit sie nie hineinragen. */
15
15
  const MARK_GAP_MM = 1;
16
- const MARK_STROKE_PT = 0.25;
16
+ export const MARK_STROKE_PT = 0.25;
17
17
  function splitEvenly(total, maxPart) {
18
18
  const parts = Math.max(1, Math.ceil(total / maxPart));
19
19
  const edges = [];
@@ -0,0 +1,32 @@
1
+ import { type ReplayCanvas } from './replayScene.js';
2
+ import { type SceneImageSource, type SceneOp } from './types.js';
3
+ import type { ImageByteDeps } from './imageBytes.js';
4
+ /** A canvas to draw on, and how to read what was drawn. */
5
+ export interface RasterSurface {
6
+ canvas: CanvasImageSource & ReplayCanvas;
7
+ context: CanvasRenderingContext2D;
8
+ encode: (type: 'image/png' | 'image/jpeg', quality?: number) => Promise<Uint8Array | null>;
9
+ }
10
+ export type CreateSurface = (width: number, height: number) => RasterSurface | null;
11
+ export declare const browserSurface: CreateSurface;
12
+ export declare const fetchImageBytes: ImageByteDeps['fetchBytes'];
13
+ /** The browser decodes (and turns a JPEG by its EXIF orientation), the canvas encodes again. */
14
+ export declare const reencodeImage: ImageByteDeps['reencode'];
15
+ /** The picture behind a source, as `replayScene` draws it; null if it cannot be read. */
16
+ export type DecodeImage = (source: SceneImageSource | Uint8Array) => Promise<CanvasImageSource | null>;
17
+ /** The browser reads the file: a bitmap by `createImageBitmap`, an SVG as an `Image`. */
18
+ export declare const browserDecode: DecodeImage;
19
+ /**
20
+ * `ops` as a PNG of `box` (page px) at `pixelRatio`: they are replayed onto a canvas, each moved
21
+ * by the same transform. An op's matrix and clips are absolute, so the transform is multiplied
22
+ * into every one of them rather than set on the context; a group is composited in a buffer of
23
+ * output px, so its children take the group's matrix too and the group itself keeps none. The
24
+ * pictures the ops draw (a photo that casts a shadow, an SVG the PDF writer cannot convert) are
25
+ * decoded first, once each.
26
+ */
27
+ export declare function rasterizeOps(ops: SceneOp[], box: {
28
+ x: number;
29
+ y: number;
30
+ width: number;
31
+ height: number;
32
+ }, pixelRatio: number, createSurface?: CreateSurface, decode?: DecodeImage): Promise<Uint8Array | null>;
@@ -0,0 +1,174 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * The browser's half of `ResolveDeps`: reading the bytes behind an image url, re-encoding an image
4
+ * through a canvas, and drawing the ops of a raster island. `resolveScene` runs without a page and
5
+ * is handed these (`CanvasEditorShell`); a test hands it its own.
6
+ *
7
+ * Every function answers a failure with null: the caller decides what a missing picture costs.
8
+ */
9
+ import { multiply } from './matrix.js';
10
+ import { replayScene } from './replayScene.js';
11
+ import { emptyReport } from './types.js';
12
+ export const browserSurface = (width, height) => {
13
+ const canvas = document.createElement('canvas');
14
+ canvas.width = width;
15
+ canvas.height = height;
16
+ const context = canvas.getContext('2d');
17
+ if (!context)
18
+ return null;
19
+ return {
20
+ canvas,
21
+ context,
22
+ encode: async (type, quality) => {
23
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, type, quality));
24
+ return blob ? new Uint8Array(await blob.arrayBuffer()) : null;
25
+ },
26
+ };
27
+ };
28
+ export const fetchImageBytes = async (url) => {
29
+ const response = await fetch(url);
30
+ if (!response.ok)
31
+ return null;
32
+ return {
33
+ bytes: new Uint8Array(await response.arrayBuffer()),
34
+ mime: response.headers.get('content-type') ?? '',
35
+ };
36
+ };
37
+ const JPEG_QUALITY = 0.92;
38
+ function hasTransparentPixel(context, width, height) {
39
+ const { data } = context.getImageData(0, 0, width, height);
40
+ for (let i = 3; i < data.length; i += 4)
41
+ if (data[i] < 255)
42
+ return true;
43
+ return false;
44
+ }
45
+ /** The browser decodes (and turns a JPEG by its EXIF orientation), the canvas encodes again. */
46
+ export const reencodeImage = async (bytes, mime, opaque) => {
47
+ const bitmap = await createImageBitmap(new Blob([bytes], { type: mime }));
48
+ try {
49
+ const { width, height } = bitmap;
50
+ const surface = browserSurface(width, height);
51
+ if (!surface)
52
+ return null;
53
+ surface.context.drawImage(bitmap, 0, 0);
54
+ const jpeg = opaque ?? !hasTransparentPixel(surface.context, width, height);
55
+ const type = jpeg ? 'image/jpeg' : 'image/png';
56
+ const encoded = await surface.encode(type, jpeg ? JPEG_QUALITY : undefined);
57
+ return encoded && { bytes: encoded, mime: type, width, height };
58
+ }
59
+ finally {
60
+ bitmap.close();
61
+ }
62
+ };
63
+ /** The browser reads the file: a bitmap by `createImageBitmap`, an SVG as an `Image`. */
64
+ export const browserDecode = async (source) => {
65
+ try {
66
+ if (source instanceof Uint8Array) {
67
+ return await createImageBitmap(new Blob([source], { type: 'image/png' }));
68
+ }
69
+ if (source.kind === 'bitmap') {
70
+ return await createImageBitmap(new Blob([source.bytes], { type: source.mime }));
71
+ }
72
+ const image = new Image();
73
+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(source.markup)}`;
74
+ await image.decode();
75
+ return image;
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ };
81
+ /** What `ops` draw from beyond themselves: image sources, tiles of patterns, pixels of rasters. */
82
+ function* sourcesOf(ops) {
83
+ for (const op of ops) {
84
+ if (op.kind === 'image' && op.image.kind !== 'element')
85
+ yield op.image;
86
+ else if (op.kind === 'raster') {
87
+ if (op.png)
88
+ yield op.png;
89
+ if (op.source)
90
+ yield* sourcesOf(op.source);
91
+ }
92
+ else if (op.kind === 'group')
93
+ yield* sourcesOf(op.ops);
94
+ else if ((op.kind === 'path' || op.kind === 'text') && op.paint.type === 'pattern') {
95
+ if (op.paint.image.kind !== 'element')
96
+ yield op.paint.image;
97
+ }
98
+ }
99
+ }
100
+ /**
101
+ * `ops` as a PNG of `box` (page px) at `pixelRatio`: they are replayed onto a canvas, each moved
102
+ * by the same transform. An op's matrix and clips are absolute, so the transform is multiplied
103
+ * into every one of them rather than set on the context; a group is composited in a buffer of
104
+ * output px, so its children take the group's matrix too and the group itself keeps none. The
105
+ * pictures the ops draw (a photo that casts a shadow, an SVG the PDF writer cannot convert) are
106
+ * decoded first, once each.
107
+ */
108
+ export async function rasterizeOps(ops, box, pixelRatio, createSurface = browserSurface, decode = browserDecode) {
109
+ const width = Math.ceil(box.width * pixelRatio);
110
+ const height = Math.ceil(box.height * pixelRatio);
111
+ if (width <= 0 || height <= 0)
112
+ return null;
113
+ const surface = createSurface(width, height);
114
+ if (!surface)
115
+ return null;
116
+ const images = new Map();
117
+ // The canvas is a whole number of px, so the scale is the one that puts the box on all of it.
118
+ const sx = width / box.width;
119
+ const sy = height / box.height;
120
+ const place = [sx, 0, 0, sy, -box.x * sx, -box.y * sy];
121
+ try {
122
+ for (const source of sourcesOf(ops)) {
123
+ if (images.has(source))
124
+ continue;
125
+ const image = await decode(source);
126
+ if (image)
127
+ images.set(source, image);
128
+ }
129
+ replayScene(surface.context, {
130
+ width,
131
+ height,
132
+ items: [{ elementId: null, label: null, ops: ops.map((op) => placed(op, place, sx, sy)) }],
133
+ report: emptyReport(),
134
+ }, { images, createCanvas: (w, h) => (createSurface(w, h) ?? surface).canvas });
135
+ return await surface.encode('image/png');
136
+ }
137
+ finally {
138
+ for (const image of images.values())
139
+ if ('close' in image)
140
+ image.close();
141
+ }
142
+ }
143
+ /** `op` under `parent`, the matrix that takes its parent's space to the output. */
144
+ function placed(op, parent, sx, sy) {
145
+ const common = {
146
+ clips: op.clips.map((clip) => ({ ...clip, matrix: multiply(parent, clip.matrix) })),
147
+ // Device px: the transform does not reach a shadow's blur and offsets.
148
+ shadow: op.shadow && {
149
+ ...op.shadow,
150
+ blur: op.shadow.blur * Math.max(sx, sy),
151
+ offsetX: op.shadow.offsetX * sx,
152
+ offsetY: op.shadow.offsetY * sy,
153
+ },
154
+ };
155
+ if (op.kind === 'group') {
156
+ const inner = multiply(parent, op.matrix);
157
+ return {
158
+ ...op,
159
+ ...common,
160
+ matrix: [1, 0, 0, 1, 0, 0],
161
+ ops: op.ops.map((child) => placed(child, inner, sx, sy)),
162
+ };
163
+ }
164
+ const matrix = multiply(parent, op.matrix);
165
+ if (op.kind === 'raster') {
166
+ return {
167
+ ...op,
168
+ ...common,
169
+ matrix,
170
+ source: op.source && op.source.map((inner) => placed(inner, parent, sx, sy)),
171
+ };
172
+ }
173
+ return { ...op, ...common, matrix };
174
+ }
@@ -0,0 +1,79 @@
1
+ import type { SceneImageSource } from './types.js';
2
+ export interface ImageByteDeps {
3
+ fetchBytes: (url: string) => Promise<{
4
+ bytes: Uint8Array;
5
+ mime: string;
6
+ } | null>;
7
+ /** Re-encodes any decodable image; browser: canvas, tests: napi. */
8
+ reencode: (bytes: Uint8Array, mime: string,
9
+ /**
10
+ * true: JPEG at 0.92, the source has no alpha. false: PNG, it may have. null: unknown, so look
11
+ * at the decoded pixels: JPEG when none is transparent, else PNG.
12
+ */
13
+ opaque: boolean | null) => Promise<{
14
+ bytes: Uint8Array;
15
+ mime: 'image/png' | 'image/jpeg';
16
+ width: number;
17
+ height: number;
18
+ } | null>;
19
+ }
20
+ /** A source, or why there is none: unreadable, or an SVG that cannot be inlined faithfully. */
21
+ export type SourceOutcome = {
22
+ ok: true;
23
+ source: SceneImageSource;
24
+ } | {
25
+ ok: false;
26
+ reason: 'image-unreadable' | 'svg-unsupported';
27
+ };
28
+ /** The size the image was drawn from: what the canvas's source rectangle is measured in. */
29
+ export interface ImageSize {
30
+ width: number;
31
+ height: number;
32
+ }
33
+ export type RasterMime = 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif' | 'image/avif';
34
+ /** Runs `work`; a throw is "cannot be read", like any other failure to read. */
35
+ export declare function attempt<T>(work: () => Promise<T | null>): Promise<T | null>;
36
+ /** The raster format the bytes are, by their magic number; what a server called it is not trusted. */
37
+ export declare function sniffRaster(bytes: Uint8Array): RasterMime | null;
38
+ /**
39
+ * The orientation tag (EXIF 0x0112, 1..8) of a JPEG; 1 when there is none, or when the file is
40
+ * not one we can read it from. Reads the first IFD of the Exif segment's TIFF block in whichever
41
+ * byte order it declares.
42
+ */
43
+ export declare function jpegOrientation(bytes: Uint8Array): number;
44
+ /**
45
+ * The JPEG without its metadata: the image data and what decodes it stay byte for byte. A photo
46
+ * is placed in a file that is sent on, and its Exif can hold where it was taken. A file whose
47
+ * segments cannot be walked to the image data is returned as it is: a decoder cannot find
48
+ * metadata in what it cannot walk either.
49
+ */
50
+ export declare function stripJpegMetadata(bytes: Uint8Array): Uint8Array;
51
+ /**
52
+ * The PNG without its text, time and Exif chunks. The colour chunks (`iCCP`, `sRGB`, `gAMA`,
53
+ * `cHRM`) and `pHYs` stay, and so does every chunk that is the image. A file whose chunks do not
54
+ * add up is returned as far as they did: what was found before the break is dropped.
55
+ */
56
+ export declare function stripPngMetadata(bytes: Uint8Array): Uint8Array;
57
+ interface DataUrl {
58
+ /** Lower case, without parameters. */
59
+ mime: string;
60
+ base64: boolean;
61
+ payload: string;
62
+ }
63
+ export declare function parseDataUrl(url: string): DataUrl | null;
64
+ /** The bytes of a base64 PNG data url, or null for anything else. */
65
+ export declare function pngFromDataUrl(dataUrl: string): Uint8Array | null;
66
+ /** The PNG of a canvas, or null for an empty or tainted one. */
67
+ export declare function canvasPng(canvas: {
68
+ toDataURL(type?: string): string;
69
+ }): Uint8Array | null;
70
+ /**
71
+ * The source behind an image url. `trusted`: the image element was made by editor code that
72
+ * generated this SVG itself (`isTrustedSvgImage`); it only matters for SVG.
73
+ */
74
+ export declare function sourceFromUrl(url: string, size: ImageSize, deps: ImageByteDeps, trusted: boolean): Promise<SourceOutcome>;
75
+ /** A canvas's pixels as a PNG source. */
76
+ export declare function sourceFromCanvas(canvas: {
77
+ toDataURL(type?: string): string;
78
+ }, size: ImageSize): SourceOutcome;
79
+ export {};