@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,49 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /** The few XML helpers the SVG writer and the SVG inliner share. */
3
+ const ESCAPES = {
4
+ '&': '&',
5
+ '<': '&lt;',
6
+ '>': '&gt;',
7
+ '"': '&quot;',
8
+ "'": '&#39;',
9
+ };
10
+ /**
11
+ * What XML 1.0 does not allow in a document, escaped or not: the control characters other than
12
+ * tab, LF and CR, the two non-characters U+FFFE and U+FFFF, and a surrogate that is not half of a
13
+ * pair. A paste from Word or a PDF brings them in; one of them makes the whole file unreadable.
14
+ */
15
+ /* eslint-disable no-control-regex -- the control characters are what it is for */
16
+ const ILLEGAL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
17
+ /* eslint-enable no-control-regex */
18
+ /**
19
+ * For text and attribute values alike: all five characters, so no caller has to know which. The
20
+ * characters XML forbids are dropped.
21
+ */
22
+ export function escapeXml(text) {
23
+ return text.replace(ILLEGAL, '').replace(/[&<>"']/g, (char) => ESCAPES[char]);
24
+ }
25
+ /**
26
+ * A text run as `escapeXml` writes it, with the x of every code point it drops dropped too: a
27
+ * `<text x="…">` takes one x per character, so a list that still counted the dropped ones would
28
+ * move every glyph after it.
29
+ */
30
+ export function withoutIllegalXml(run) {
31
+ const kept = [];
32
+ const xs = [];
33
+ Array.from(run.text).forEach((char, index) => {
34
+ if (char.replace(ILLEGAL, '') === '')
35
+ return;
36
+ kept.push(char);
37
+ const x = run.xs[index];
38
+ if (x !== undefined)
39
+ xs.push(x);
40
+ });
41
+ return { text: kept.join(''), xs };
42
+ }
43
+ /**
44
+ * At most `digits` decimals with the trailing zeros trimmed. Never `-0` (`String(-0)` is `'0'`)
45
+ * and never `NaN`: a non-finite value is a bug upstream, but it must not make the file invalid.
46
+ */
47
+ export function formatNumber(value, digits = 3) {
48
+ return Number.isFinite(value) ? String(Number(value.toFixed(digits))) : '0';
49
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * What the SVG and PDF exports (`VectorExportDeps`) need of an editor that is on screen: the
3
+ * stage of each page to record and draw from, the browser's image reading and rasteriser, the
4
+ * host's font service and the brand's fonts, and the resolution of the raster islands (a print
5
+ * format asks for more than a screen does).
6
+ *
7
+ * One function for every host of the exports: the editor shell, and the render gate, which checks
8
+ * what the shell would export. A copy of this wiring is a place the two can differ.
9
+ */
10
+ import { type CanvasFormat } from '../formats/index.js';
11
+ import type { VectorExportDeps } from './vectorExport.js';
12
+ import type { BrandPack } from '@ggraphic/core';
13
+ import type { GenericCanvasRef } from '../components/GenericCanvas.js';
14
+ import type { CanvasExportFontService } from '../hostServices.js';
15
+ /** The part of a page's mounted stage the exports use. */
16
+ export type VectorExportCanvas = Pick<GenericCanvasRef, 'recordScene' | 'rasterizeElement' | 'rasterizeNode'>;
17
+ export interface CreateVectorDepsOptions {
18
+ /** The mounted stage of page `index` (0-based); none when that page is not mounted. */
19
+ canvasOf: (index: number) => VectorExportCanvas | null | undefined;
20
+ /** The host's font files (`services.exportFonts`), asked before the brand's. */
21
+ exportFonts?: CanvasExportFontService | null;
22
+ /** Its font faces and bold families find the font files. */
23
+ brand: BrandPack;
24
+ /** A print format sets the pixel ratio of the raster islands; any other, 2. */
25
+ format: CanvasFormat;
26
+ }
27
+ export declare function createVectorDeps({ canvasOf, exportFonts, brand, format, }: CreateVectorDepsOptions): VectorExportDeps;
@@ -0,0 +1,37 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * What the SVG and PDF exports (`VectorExportDeps`) need of an editor that is on screen: the
4
+ * stage of each page to record and draw from, the browser's image reading and rasteriser, the
5
+ * host's font service and the brand's fonts, and the resolution of the raster islands (a print
6
+ * format asks for more than a screen does).
7
+ *
8
+ * One function for every host of the exports: the editor shell, and the render gate, which checks
9
+ * what the shell would export. A copy of this wiring is a place the two can differ.
10
+ */
11
+ import { isPrintFormat } from '../formats/index.js';
12
+ import { printPixelRatio } from './printExport.js';
13
+ import { fetchImageBytes, rasterizeOps, reencodeImage } from './scene/browserDeps.js';
14
+ import { pngFromDataUrl } from './scene/imageBytes.js';
15
+ export function createVectorDeps({ canvasOf, exportFonts, brand, format, }) {
16
+ return {
17
+ recordPage: async (index, options) => (await canvasOf(index)?.recordScene({ page: index + 1, ...options })) ?? null,
18
+ resolveDeps: (index) => ({
19
+ page: index + 1,
20
+ fetchBytes: fetchImageBytes,
21
+ reencode: reencodeImage,
22
+ rasterizeElement: async (elementId, pixelRatio) => {
23
+ const drawn = await canvasOf(index)?.rasterizeElement(elementId, pixelRatio);
24
+ const png = drawn ? pngFromDataUrl(drawn.dataUrl) : null;
25
+ return drawn && png ? { png, box: drawn.box } : null;
26
+ },
27
+ rasterizeNode: async (nodeRef, pixelRatio) => (await canvasOf(index)?.rasterizeNode(nodeRef, pixelRatio)) ?? null,
28
+ rasterizeOps,
29
+ rasterPixelRatio: isPrintFormat(format) ? printPixelRatio(format) : 2,
30
+ }),
31
+ fontDeps: {
32
+ ...(exportFonts ? { host: exportFonts } : {}),
33
+ brandFaces: brand.fontFaces,
34
+ ...(brand.fonts.boldFamilies ? { boldFamilies: brand.fonts.boldFamilies } : {}),
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The SVG and PDF downloads: each page is recorded from its mounted stage, resolved (images read,
3
+ * islands drawn), written, and packed. One SVG page is the SVG itself, several are a ZIP with one
4
+ * SVG each; a PDF holds all the pages.
5
+ *
6
+ * Everything that needs a browser comes in through `VectorExportDeps`, so this file runs in node:
7
+ * the editor wires the stage, the canvas and the host's font service in (`CanvasEditorShell`).
8
+ *
9
+ * Pages are one after the other, which keeps one scene in memory at a time (the PDF writer takes
10
+ * all of them at once) and makes the report list things in the order of the pages. Their numbers
11
+ * in the report are 1-based (`index + 1`), the number the editor shows.
12
+ */
13
+ import { type CanvasFormat } from '../formats/index.js';
14
+ import { type FontFileSet, type FontSourceDeps } from './fonts/fontFiles.js';
15
+ import { type ResolveDeps } from './scene/resolveScene.js';
16
+ import { type ExportReport, type RecordedScene } from './scene/types.js';
17
+ import type { BrandPack } from '@ggraphic/core';
18
+ export interface VectorExportDeps {
19
+ /** The page as the stage draws it now, or null when it is not mounted. */
20
+ recordPage: (index: number, options: {
21
+ transparent: boolean;
22
+ }) => Promise<RecordedScene | null>;
23
+ /** What `resolveScene` needs of page `index`; its `page` is replaced by the page's number. */
24
+ resolveDeps: (index: number) => ResolveDeps;
25
+ fontDeps: FontSourceDeps;
26
+ }
27
+ export interface VectorExportOptions {
28
+ /** `outlines`: glyph outlines, no font needed to open the file. `editable`: `<text>`. */
29
+ text: 'outlines' | 'editable';
30
+ /** No page background. */
31
+ transparent: boolean;
32
+ /** The file name without its extension. */
33
+ filenameBase: string;
34
+ }
35
+ export interface VectorExportResult {
36
+ blob: Blob;
37
+ filename: string;
38
+ report: ExportReport;
39
+ }
40
+ export declare function exportPagesSvg(pageIndexes: readonly number[], options: VectorExportOptions, deps: VectorExportDeps): Promise<VectorExportResult>;
41
+ /**
42
+ * The files of every face the page draws text in: its own, and the text inside its SVG pictures
43
+ * (the writer draws those as ops in outline mode, which is when fonts are asked for). The font a
44
+ * picture's text inherits is the one `writeSvg` uses, so the faces match exactly. A face no source
45
+ * has comes out with no files.
46
+ */
47
+ export declare function fontsOf(scene: RecordedScene, deps: FontSourceDeps): Promise<Map<string, FontFileSet>>;
48
+ /**
49
+ * The longest the PDF writer may take. A font that fontkit cannot subset can fail inside a timer
50
+ * callback, where nothing can catch it, and the write then never settles: the export would hang.
51
+ * Past this the raster PDF is made instead.
52
+ */
53
+ export declare const PDF_WRITE_TIMEOUT_MS = 60000;
54
+ /** The most one raster island may take (decode, draw, encode) before the export falls back. */
55
+ export declare const PDF_ISLAND_TIMEOUT_MS = 60000;
56
+ export interface PdfExportOptions {
57
+ /** `print` pages are trim + bleed with crop marks, `slides` fill a slide, `digital` are 1 pt to the px. */
58
+ mode: 'digital' | 'slides' | 'print';
59
+ /** Print mode takes the trim size and the bleed from it. */
60
+ format: CanvasFormat;
61
+ /** Its print values (`brand.print`) make the CMYK colours; its palette is what `report.rgbBrandColors` checks. */
62
+ brand: BrandPack;
63
+ /** The file name without its extension. */
64
+ filenameBase: string;
65
+ /** How many pages the document has: a PDF holds all of them. */
66
+ pageCount: number;
67
+ /** Default `PDF_WRITE_TIMEOUT_MS`. */
68
+ writeTimeoutMs?: number;
69
+ /** Default `PDF_ISLAND_TIMEOUT_MS`. */
70
+ islandTimeoutMs?: number;
71
+ }
72
+ export interface PdfExportDeps extends VectorExportDeps {
73
+ /**
74
+ * The PDF of page pictures this export replaces, for when the vector PDF cannot be made. If it
75
+ * fails too, so does the export.
76
+ */
77
+ rasterFallback: () => Promise<Uint8Array>;
78
+ }
79
+ /**
80
+ * The PDF of the document: vector, in the mode of its format. It falls back to the raster PDF for
81
+ * the whole document when the vector one cannot be made: the writer throws or does not finish in
82
+ * time, or fonts failed for the text of more than one element (a picture of one element is a
83
+ * normal island, of several it is a PDF nobody asked for). `report.fallback` then says why.
84
+ */
85
+ export declare function exportPagesPdf(options: PdfExportOptions, deps: PdfExportDeps): Promise<VectorExportResult>;
@@ -0,0 +1,287 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * The SVG and PDF downloads: each page is recorded from its mounted stage, resolved (images read,
4
+ * islands drawn), written, and packed. One SVG page is the SVG itself, several are a ZIP with one
5
+ * SVG each; a PDF holds all the pages.
6
+ *
7
+ * Everything that needs a browser comes in through `VectorExportDeps`, so this file runs in node:
8
+ * the editor wires the stage, the canvas and the host's font service in (`CanvasEditorShell`).
9
+ *
10
+ * Pages are one after the other, which keeps one scene in memory at a time (the PDF writer takes
11
+ * all of them at once) and makes the report list things in the order of the pages. Their numbers
12
+ * in the report are 1-based (`index + 1`), the number the editor shows.
13
+ */
14
+ import { isPrintFormat } from '../formats/index.js';
15
+ import { messages } from '../i18n/catalogue.js';
16
+ import { zipFiles } from '../utils/zipPageImages.js';
17
+ import { resolveFontFiles } from './fonts/fontFiles.js';
18
+ import { normalHex } from './pdf/pdfGeometry.js';
19
+ import { writePdf } from './pdf/writePdf.js';
20
+ import { IDENTITY } from './scene/matrix.js';
21
+ import { fontFamilies } from './scene/recordingContext.js';
22
+ import { resolveScene } from './scene/resolveScene.js';
23
+ import { emptyReport, mergeReports, } from './scene/types.js';
24
+ import { mostUsedFont, svgHasText } from './svg/svgImageScene.js';
25
+ import { svgToScene } from './svg/svgToScene.js';
26
+ import { writeSvg } from './svg/writeSvg.js';
27
+ export async function exportPagesSvg(pageIndexes, options, deps) {
28
+ // One cache for the export: a face used on several pages is read once.
29
+ const fontDeps = { ...deps.fontDeps, cache: deps.fontDeps.cache ?? new Map() };
30
+ const files = [];
31
+ let report = emptyReport();
32
+ for (const index of pageIndexes) {
33
+ const page = index + 1;
34
+ const recorded = await deps.recordPage(index, { transparent: options.transparent });
35
+ if (!recorded)
36
+ throw new Error(messages().errors.pageExport(page));
37
+ const scene = await resolveScene(recorded, { ...deps.resolveDeps(index), page });
38
+ const fonts = options.text === 'outlines' ? await fontsOf(scene, fontDeps) : new Map();
39
+ // The scene's report is the one the writer adds to (a run no font covers).
40
+ const svg = writeSvg(scene, { text: options.text, fonts, report: scene.report, page });
41
+ report = mergeReports(report, scene.report);
42
+ files.push({ name: `${options.filenameBase}-${page}.svg`, svg });
43
+ }
44
+ const [only] = files;
45
+ if (files.length === 1 && only) {
46
+ return {
47
+ blob: new Blob([only.svg], { type: 'image/svg+xml' }),
48
+ filename: `${options.filenameBase}.svg`,
49
+ report,
50
+ };
51
+ }
52
+ const encoder = new TextEncoder();
53
+ return {
54
+ blob: zipFiles(files.map(({ name, svg }) => ({ name, bytes: encoder.encode(svg) }))),
55
+ filename: `${options.filenameBase}.zip`,
56
+ report,
57
+ };
58
+ }
59
+ // ---------------------------------------------------------------------------------------------
60
+ // Fonts
61
+ /** The key `writeSvg` looks a face up by. */
62
+ const faceKey = (font) => `${font.family}|${font.weight}|${font.style}`;
63
+ function collectFaces(ops, into,
64
+ /** More ops an op stands for, whose text needs a face too. */
65
+ expand) {
66
+ for (const op of ops) {
67
+ if (op.kind === 'text') {
68
+ if (!into.has(faceKey(op.font)))
69
+ into.set(faceKey(op.font), op.font);
70
+ }
71
+ else if (op.kind === 'group') {
72
+ collectFaces(op.ops, into, expand);
73
+ }
74
+ else if (expand) {
75
+ collectFaces(expand(op), into, expand);
76
+ }
77
+ }
78
+ }
79
+ /**
80
+ * The files of every face the page draws text in: its own, and the text inside its SVG pictures
81
+ * (the writer draws those as ops in outline mode, which is when fonts are asked for). The font a
82
+ * picture's text inherits is the one `writeSvg` uses, so the faces match exactly. A face no source
83
+ * has comes out with no files.
84
+ */
85
+ export async function fontsOf(scene, deps) {
86
+ return resolveFaces([scene], mostUsedFont([scene]), deps, false);
87
+ }
88
+ /**
89
+ * The files of every face the scenes' text is drawn in: their own, the text inside their SVG
90
+ * images (found by converting them, which is what the writers do too, so the faces match
91
+ * exactly), and, when `withDefault`, the default font.
92
+ */
93
+ async function resolveFaces(scenes, defaultFont, deps, withDefault) {
94
+ const faces = new Map(withDefault ? [[faceKey(defaultFont), defaultFont]] : []);
95
+ const converted = new Map();
96
+ const textOfSvg = (op) => {
97
+ if (op.kind !== 'image' || op.image.kind !== 'svg' || !svgHasText(op.image.markup))
98
+ return [];
99
+ const { markup, width, height } = op.image;
100
+ let ops = converted.get(markup);
101
+ if (!ops) {
102
+ ops = svgToScene(markup, { matrix: IDENTITY, width, height }, { font: defaultFont }).ops;
103
+ converted.set(markup, ops);
104
+ }
105
+ return ops;
106
+ };
107
+ for (const scene of scenes) {
108
+ for (const item of scene.items)
109
+ collectFaces(item.ops, faces, textOfSvg);
110
+ }
111
+ const fonts = new Map();
112
+ for (const [key, face] of faces)
113
+ fonts.set(key, await resolveFontFiles(face, deps));
114
+ return fonts;
115
+ }
116
+ // ---------------------------------------------------------------------------------------------
117
+ // PDF
118
+ /**
119
+ * The longest the PDF writer may take. A font that fontkit cannot subset can fail inside a timer
120
+ * callback, where nothing can catch it, and the write then never settles: the export would hang.
121
+ * Past this the raster PDF is made instead.
122
+ */
123
+ export const PDF_WRITE_TIMEOUT_MS = 60_000;
124
+ /** The most one raster island may take (decode, draw, encode) before the export falls back. */
125
+ export const PDF_ISLAND_TIMEOUT_MS = 60_000;
126
+ /**
127
+ * Raster reasons that mean a font could not be used, as opposed to the legitimate islands (a
128
+ * photo with a filter, a shadow, a glyph this one font lacks).
129
+ */
130
+ const FONT_FAILURES = new Set(['font-unavailable', 'bitmap-only-font']);
131
+ /** The elements (of all pages) whose text a font failure turned into a picture. */
132
+ function fontFailureCount(report) {
133
+ return new Set(report.rasterIslands
134
+ .filter((island) => FONT_FAILURES.has(island.reason))
135
+ .map((island) => `${island.page}:${island.elementId ?? ''}`)).size;
136
+ }
137
+ /**
138
+ * The PDF of the document: vector, in the mode of its format. It falls back to the raster PDF for
139
+ * the whole document when the vector one cannot be made: the writer throws or does not finish in
140
+ * time, or fonts failed for the text of more than one element (a picture of one element is a
141
+ * normal island, of several it is a PDF nobody asked for). `report.fallback` then says why.
142
+ */
143
+ export async function exportPagesPdf(options, deps) {
144
+ // A mistake of the caller, not something a raster PDF could make up for.
145
+ if (options.mode === 'print' && !isPrintFormat(options.format)) {
146
+ throw new Error('exportPagesPdf: the print mode needs a print format');
147
+ }
148
+ const filename = `${options.filenameBase}.pdf`;
149
+ let reason;
150
+ let kind;
151
+ try {
152
+ const { bytes, report } = await writeVectorPdf(options, deps);
153
+ const failures = fontFailureCount(report);
154
+ if (failures <= 1)
155
+ return { blob: pdfBlob(bytes), filename, report };
156
+ kind = 'fonts';
157
+ reason = `fonts could not be used for the text of ${failures} elements`;
158
+ }
159
+ catch (error) {
160
+ kind = error instanceof WriteTimeoutError ? 'timeout' : 'error';
161
+ reason = error instanceof Error ? error.message : String(error);
162
+ }
163
+ console.warn(`[exportPagesPdf] vector PDF not made, writing the raster PDF instead: ${reason}`);
164
+ const bytes = await deps.rasterFallback();
165
+ return {
166
+ blob: pdfBlob(bytes),
167
+ filename,
168
+ report: { ...emptyReport(), fallback: { kind, reason } },
169
+ };
170
+ }
171
+ const pdfBlob = (bytes) => new Blob([bytes], { type: 'application/pdf' });
172
+ async function writeVectorPdf(options, deps) {
173
+ const { brand, format } = options;
174
+ const fontDeps = { ...deps.fontDeps, cache: deps.fontDeps.cache ?? new Map() };
175
+ const scenes = [];
176
+ for (let index = 0; index < options.pageCount; index++) {
177
+ const page = index + 1;
178
+ const recorded = await deps.recordPage(index, { transparent: false });
179
+ if (!recorded)
180
+ throw new Error(messages().errors.pageExport(page));
181
+ scenes.push(await resolveScene(recorded, { ...deps.resolveDeps(index), page }));
182
+ }
183
+ // What an SVG's text inherits where it names no family (a chart's labels): the body font.
184
+ const defaultFont = bodyFont(brand);
185
+ const fonts = await resolveFaces(scenes, defaultFont, fontDeps, true);
186
+ // Islands do not depend on the page they are on: the first page's rasteriser draws them all.
187
+ const shared = deps.resolveDeps(0);
188
+ const trim = isPrintFormat(format) ? format.print.trimMm : null;
189
+ // The budget is for the writer: the time it waits for a raster island does not count, or a
190
+ // page with several shadows or filtered photos would fall back to the raster PDF by itself.
191
+ const budget = new TimeoutBudget(options.writeTimeoutMs ?? PDF_WRITE_TIMEOUT_MS, options.islandTimeoutMs ?? PDF_ISLAND_TIMEOUT_MS);
192
+ return budget.run(() => writePdf(scenes, {
193
+ mode: options.mode,
194
+ ...(trim && {
195
+ print: { trimMm: { width: trim.w, height: trim.h }, bleedMm: format.print.bleedMm },
196
+ }),
197
+ ...(brand.print?.cmyk && { cmyk: brand.print.cmyk }),
198
+ brandPalette: brandHexes(brand),
199
+ fonts,
200
+ rasterize: (ops, box, pixelRatio) => budget.paused(() => shared.rasterizeOps(ops, box, pixelRatio)),
201
+ rasterPixelRatio: shared.rasterPixelRatio,
202
+ defaultFont,
203
+ }));
204
+ }
205
+ /** The writer did not finish in its time. */
206
+ class WriteTimeoutError extends Error {
207
+ }
208
+ /** A timeout that stands still while `paused` work runs (overlapping pauses count once). */
209
+ class TimeoutBudget {
210
+ ms;
211
+ islandMs;
212
+ left;
213
+ timer;
214
+ since = 0;
215
+ pauses = 0;
216
+ done = false;
217
+ fail = () => { };
218
+ constructor(ms, islandMs) {
219
+ this.ms = ms;
220
+ this.islandMs = islandMs;
221
+ this.left = ms;
222
+ }
223
+ run(work) {
224
+ const expired = new Promise((_resolve, reject) => {
225
+ this.fail = reject;
226
+ });
227
+ this.start();
228
+ return Promise.race([work(), expired]).finally(() => {
229
+ this.done = true;
230
+ clearTimeout(this.timer);
231
+ });
232
+ }
233
+ async paused(work) {
234
+ if (this.pauses++ === 0)
235
+ this.stop();
236
+ // Paused time is not the writer's, but it is not unbounded either: a decode or encode that
237
+ // never settles must still end in the raster PDF.
238
+ let cap;
239
+ const stuck = new Promise((_resolve, reject) => {
240
+ cap = setTimeout(() => {
241
+ const error = new WriteTimeoutError(`a raster island did not finish within ${this.islandMs / 1000} s`);
242
+ this.fail(error);
243
+ reject(error);
244
+ }, this.islandMs);
245
+ });
246
+ try {
247
+ return await Promise.race([work(), stuck]);
248
+ }
249
+ finally {
250
+ clearTimeout(cap);
251
+ if (--this.pauses === 0)
252
+ this.start();
253
+ }
254
+ }
255
+ start() {
256
+ // An abandoned writer may still finish a pause after the race is over.
257
+ if (this.done)
258
+ return;
259
+ this.since = Date.now();
260
+ this.timer = setTimeout(() => this.fail(new WriteTimeoutError(`the PDF writer did not finish within ${this.ms / 1000} s`)), this.left);
261
+ }
262
+ stop() {
263
+ clearTimeout(this.timer);
264
+ this.left = Math.max(0, this.left - (Date.now() - this.since));
265
+ }
266
+ }
267
+ /** The body font of the brand as the default of an SVG's text: regular, upright, 16 px. */
268
+ function bodyFont(brand) {
269
+ const [family, ...fallback] = fontFamilies(brand.fonts.body);
270
+ return {
271
+ family: family ?? 'sans-serif',
272
+ ...(fallback.length > 0 && { fallback }),
273
+ weight: 400,
274
+ style: 'normal',
275
+ size: 16,
276
+ };
277
+ }
278
+ /** Every colour of the brand pack that is a hex colour, as `#rrggbb`: its roles, palettes, grounds and glows. */
279
+ function brandHexes(brand) {
280
+ const colours = [
281
+ ...Object.values(brand.colors),
282
+ ...brand.palette.map((swatch) => swatch.color),
283
+ ...brand.textPalette.map((swatch) => swatch.color),
284
+ ...brand.backgrounds.flatMap((ground) => [ground.color, ...(ground.glow ?? [])]),
285
+ ];
286
+ return [...new Set(colours.flatMap((colour) => normalHex(colour) ?? []))];
287
+ }
@@ -0,0 +1,6 @@
1
+ export declare function setLiveFontSize(next: {
2
+ id: string;
3
+ size: number;
4
+ } | null): void;
5
+ /** The live size of `id` while one of its corners is dragged; null otherwise. */
6
+ export declare function useLiveFontSize(id: string): number | null;
@@ -0,0 +1,26 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ /**
3
+ * The size a text is being scaled to by a corner handle, while the pointer is still down.
4
+ *
5
+ * A channel of its own, not a field of the canvas store: every page has its own store, and the
6
+ * size field sits in the shell's toolbar, outside all of them. Only the field subscribes, so a
7
+ * drag re-renders that one input — once per whole size step — and nothing else. The page itself
8
+ * is written once, on release.
9
+ */
10
+ import { useSyncExternalStore } from 'react';
11
+ let live = null;
12
+ const listeners = new Set();
13
+ export function setLiveFontSize(next) {
14
+ if (next?.id === live?.id && next?.size === live?.size)
15
+ return;
16
+ live = next;
17
+ listeners.forEach((listener) => listener());
18
+ }
19
+ function subscribe(listener) {
20
+ listeners.add(listener);
21
+ return () => listeners.delete(listener);
22
+ }
23
+ /** The live size of `id` while one of its corners is dragged; null otherwise. */
24
+ export function useLiveFontSize(id) {
25
+ return useSyncExternalStore(subscribe, () => (live?.id === id ? live.size : null), () => null);
26
+ }
@@ -295,6 +295,21 @@ export interface CanvasPrintService {
295
295
  /** Shown in the download view next to the print PDF; omitted, there is no notice. */
296
296
  untestedNotice?: string;
297
297
  }
298
+ /**
299
+ * The font files behind the page's text, for the vector export (SVG outlines, PDF embedding).
300
+ *
301
+ * Without it the export reads the brand pack's font faces and the page's `@font-face` rules; a
302
+ * host that serves fonts some other way (a font server with signed URLs, bundled files) hands
303
+ * them over here, and they win over both.
304
+ */
305
+ export interface CanvasExportFontService {
306
+ /** The font file for one face, or null when the host has none. TTF, OTF, WOFF or WOFF2. */
307
+ load: (face: {
308
+ family: string;
309
+ weight: number;
310
+ style: 'normal' | 'italic';
311
+ }) => Promise<Uint8Array | null>;
312
+ }
298
313
  /** @deprecated Use `CanvasImprintLocale`. Removed in the next alpha. */
299
314
  export type CanvasImpressumLocale = CanvasImprintLocale;
300
315
  /** @deprecated Use `CanvasImprintLabels`. Removed in the next alpha. */
package/dist/i18n/de.d.ts CHANGED
@@ -1,12 +1,3 @@
1
- /**
2
- * The German message catalogue — the source of truth for every user-visible
3
- * string of the editor core, and the shape `en.ts` (and any host catalogue)
4
- * must match. Nested by feature. Texts that carry a number or a name are small
5
- * typed functions, so there is no ICU library to pull in.
6
- *
7
- * Deliberately no `as const`: the leaves stay `string` / `(…) => string`, so a
8
- * second language fits the same type.
9
- */
10
1
  export declare const de: {
11
2
  common: {
12
3
  addShape: (name: string) => string;
@@ -774,6 +765,32 @@ export declare const de: {
774
765
  imprintAddressPlaceholder: string;
775
766
  imprintAddressRequired: string;
776
767
  imprintSubmit: string;
768
+ svg: string;
769
+ keepTextEditable: string;
770
+ keepTextEditableHint: string;
771
+ rasterNotice: (items: string) => string;
772
+ missingNotice: (n: number) => string;
773
+ reducedRasterNotice: string;
774
+ variableFontNotice: (fonts: string) => string;
775
+ /** Why the PDF is a picture, by `ExportReport['fallback'].kind`. */
776
+ pdfFallbackNotice: {
777
+ fonts: string;
778
+ timeout: string;
779
+ error: string;
780
+ };
781
+ /** Why a part of the page is a picture in the SVG or PDF, as a short noun phrase. */
782
+ rasterReason: {
783
+ filter: string;
784
+ composite: string;
785
+ 'unsupported-call': string;
786
+ 'unsupported-pattern': string;
787
+ 'missing-glyph': string;
788
+ 'font-unavailable': string;
789
+ 'bitmap-only-font': string;
790
+ shadow: string;
791
+ 'svg-unsupported': string;
792
+ 'image-unreadable': string;
793
+ };
777
794
  };
778
795
  };
779
796
  /** The tabs of a free page (`createPageConfig`). */
@@ -856,6 +873,7 @@ export declare const de: {
856
873
  layerDown: string;
857
874
  fontSmaller: string;
858
875
  fontLarger: string;
876
+ fontSizeInput: string;
859
877
  fontRole: string;
860
878
  fontRoles: {
861
879
  headline: string;
package/dist/i18n/de.js CHANGED
@@ -1,13 +1,3 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- /**
3
- * The German message catalogue — the source of truth for every user-visible
4
- * string of the editor core, and the shape `en.ts` (and any host catalogue)
5
- * must match. Nested by feature. Texts that carry a number or a name are small
6
- * typed functions, so there is no ICU library to pull in.
7
- *
8
- * Deliberately no `as const`: the leaves stay `string` / `(…) => string`, so a
9
- * second language fits the same type.
10
- */
11
1
  export const de = {
12
2
  common: {
13
3
  addShape: (name) => `${name} hinzufügen`,
@@ -824,6 +814,32 @@ export const de = {
824
814
  imprintAddressPlaceholder: 'Straße Nr., PLZ Ort',
825
815
  imprintAddressRequired: 'Bitte Anschrift eintragen.',
826
816
  imprintSubmit: 'Übernehmen',
817
+ svg: 'SVG (Vektor)',
818
+ keepTextEditable: 'Text bearbeitbar lassen',
819
+ keepTextEditableHint: 'Sieht nur richtig aus, wo die Schrift installiert ist.',
820
+ rasterNotice: (items) => `Als Bild eingebettet: ${items}`,
821
+ missingNotice: (n) => `${n} Element(e) fehlen, weil ihr Bild nicht geladen werden konnte.`,
822
+ reducedRasterNotice: 'Ein Bildbereich wurde in geringerer Auflösung eingebettet, weil das Bild sonst zu groß geworden wäre.',
823
+ variableFontNotice: (fonts) => `Schrift in Standardstärke eingebettet, die Stärke kann abweichen: ${fonts}`,
824
+ /** Why the PDF is a picture, by `ExportReport['fallback'].kind`. */
825
+ pdfFallbackNotice: {
826
+ fonts: 'Das PDF wurde als Bild erzeugt, weil nicht alle Schriften geladen werden konnten.',
827
+ timeout: 'Das PDF wurde als Bild erzeugt, weil die Vektor-Erzeugung zu lange gedauert hat.',
828
+ error: 'Das PDF wurde als Bild erzeugt, weil die Vektor-Erzeugung fehlgeschlagen ist.',
829
+ },
830
+ /** Why a part of the page is a picture in the SVG or PDF, as a short noun phrase. */
831
+ rasterReason: {
832
+ filter: 'Foto mit Filter',
833
+ composite: 'Überblendung',
834
+ 'unsupported-call': 'Effekt ohne Vektorform',
835
+ 'unsupported-pattern': 'Muster',
836
+ 'missing-glyph': 'Zeichen ohne Schrift',
837
+ 'font-unavailable': 'Schrift nicht verfügbar',
838
+ 'bitmap-only-font': 'Bitmap-Schrift',
839
+ shadow: 'Schatten',
840
+ 'svg-unsupported': 'SVG-Grafik',
841
+ 'image-unreadable': 'Bild nicht lesbar',
842
+ },
827
843
  },
828
844
  },
829
845
  /** The tabs of a free page (`createPageConfig`). */
@@ -906,6 +922,7 @@ export const de = {
906
922
  layerDown: 'Ebene nach unten',
907
923
  fontSmaller: 'Schrift verkleinern',
908
924
  fontLarger: 'Schrift vergrößern',
925
+ fontSizeInput: 'Schriftgröße',
909
926
  fontRole: 'Schrift',
910
927
  fontRoles: {
911
928
  headline: 'Überschrift',