@ggraphic/editor 0.1.0-alpha.4 → 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 (131) hide show
  1. package/dist/CanvasEditorProvider.d.ts +6 -1
  2. package/dist/collab/useYjsPageStateSync.d.ts +1 -1
  3. package/dist/collab/useYjsPageStateSync.js +5 -2
  4. package/dist/components/CanvasEditor/CanvasEditorShell.js +139 -36
  5. package/dist/components/CanvasEditor/editorShell.d.ts +6 -0
  6. package/dist/components/CanvasEditor/types.d.ts +28 -0
  7. package/dist/components/GenericCanvas.d.ts +19 -2
  8. package/dist/components/GenericCanvas.js +30 -5
  9. package/dist/components/PagePreview.d.ts +8 -1
  10. package/dist/components/PagePreview.js +4 -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/entries/export.d.ts +14 -1
  16. package/dist/entries/export.js +14 -1
  17. package/dist/entries/services.d.ts +1 -1
  18. package/dist/export/fonts/fontFiles.d.ts +100 -0
  19. package/dist/export/fonts/fontFiles.js +333 -0
  20. package/dist/export/fonts/glyphs.d.ts +113 -0
  21. package/dist/export/fonts/glyphs.js +120 -0
  22. package/dist/export/fonts/variation.d.ts +23 -0
  23. package/dist/export/fonts/variation.js +43 -0
  24. package/dist/export/pdf/pdfContent.d.ts +108 -0
  25. package/dist/export/pdf/pdfContent.js +566 -0
  26. package/dist/export/pdf/pdfFontkit.d.ts +54 -0
  27. package/dist/export/pdf/pdfFontkit.js +159 -0
  28. package/dist/export/pdf/pdfGeometry.d.ts +54 -0
  29. package/dist/export/pdf/pdfGeometry.js +228 -0
  30. package/dist/export/pdf/pdfResources.d.ts +109 -0
  31. package/dist/export/pdf/pdfResources.js +314 -0
  32. package/dist/export/pdf/writePdf.d.ts +34 -0
  33. package/dist/export/pdf/writePdf.js +165 -0
  34. package/dist/export/pptx/exportPptxDeck.d.ts +10 -2
  35. package/dist/export/pptx/exportPptxDeck.js +5 -2
  36. package/dist/export/pptx/svgPicture.d.ts +19 -0
  37. package/dist/export/pptx/svgPicture.js +64 -0
  38. package/dist/export/pptx/vectorizeElement.d.ts +9 -0
  39. package/dist/export/pptx/vectorizeElement.js +118 -0
  40. package/dist/export/pptx/writePptx.d.ts +13 -0
  41. package/dist/export/pptx/writePptx.js +17 -0
  42. package/dist/export/printPdf.d.ts +1 -0
  43. package/dist/export/printPdf.js +1 -1
  44. package/dist/export/scene/browserDeps.d.ts +32 -0
  45. package/dist/export/scene/browserDeps.js +174 -0
  46. package/dist/export/scene/imageBytes.d.ts +79 -0
  47. package/dist/export/scene/imageBytes.js +330 -0
  48. package/dist/export/scene/itemBounds.d.ts +9 -0
  49. package/dist/export/scene/itemBounds.js +40 -0
  50. package/dist/export/scene/matrix.d.ts +13 -0
  51. package/dist/export/scene/matrix.js +32 -0
  52. package/dist/export/scene/rasterLimit.d.ts +13 -0
  53. package/dist/export/scene/rasterLimit.js +24 -0
  54. package/dist/export/scene/rebaseOps.d.ts +8 -0
  55. package/dist/export/scene/rebaseOps.js +51 -0
  56. package/dist/export/scene/recordPageScene.d.ts +28 -0
  57. package/dist/export/scene/recordPageScene.js +224 -0
  58. package/dist/export/scene/recordingCanvas.d.ts +55 -0
  59. package/dist/export/scene/recordingCanvas.js +71 -0
  60. package/dist/export/scene/recordingContext.d.ts +162 -0
  61. package/dist/export/scene/recordingContext.js +1031 -0
  62. package/dist/export/scene/replayScene.d.ts +31 -0
  63. package/dist/export/scene/replayScene.js +213 -0
  64. package/dist/export/scene/resolveScene.d.ts +48 -0
  65. package/dist/export/scene/resolveScene.js +236 -0
  66. package/dist/export/scene/trustedSvgImages.d.ts +3 -0
  67. package/dist/export/scene/trustedSvgImages.js +21 -0
  68. package/dist/export/scene/types.d.ts +241 -0
  69. package/dist/export/scene/types.js +38 -0
  70. package/dist/export/slidesPdf.d.ts +10 -2
  71. package/dist/export/slidesPdf.js +8 -4
  72. package/dist/export/svg/__fixtures__/barChart.svg +1 -0
  73. package/dist/export/svg/__golden__/fixture-editable.svg +87 -0
  74. package/dist/export/svg/__golden__/fixture-outlines.svg +88 -0
  75. package/dist/export/svg/inlineSvg.d.ts +10 -0
  76. package/dist/export/svg/inlineSvg.js +119 -0
  77. package/dist/export/svg/scopeCss.d.ts +45 -0
  78. package/dist/export/svg/scopeCss.js +214 -0
  79. package/dist/export/svg/svgColor.d.ts +8 -0
  80. package/dist/export/svg/svgColor.js +46 -0
  81. package/dist/export/svg/svgImageScene.d.ts +41 -0
  82. package/dist/export/svg/svgImageScene.js +128 -0
  83. package/dist/export/svg/svgPathData.d.ts +31 -0
  84. package/dist/export/svg/svgPathData.js +466 -0
  85. package/dist/export/svg/svgToScene.d.ts +19 -0
  86. package/dist/export/svg/svgToScene.js +1183 -0
  87. package/dist/export/svg/writeSvg.d.ts +33 -0
  88. package/dist/export/svg/writeSvg.js +594 -0
  89. package/dist/export/svg/xml.d.ts +23 -0
  90. package/dist/export/svg/xml.js +49 -0
  91. package/dist/export/vectorDeps.d.ts +27 -0
  92. package/dist/export/vectorDeps.js +37 -0
  93. package/dist/export/vectorExport.d.ts +85 -0
  94. package/dist/export/vectorExport.js +287 -0
  95. package/dist/hostServices.d.ts +15 -0
  96. package/dist/i18n/de.d.ts +26 -9
  97. package/dist/i18n/de.js +26 -10
  98. package/dist/i18n/en.js +24 -0
  99. package/dist/primitives/AssetPrimitive.js +7 -2
  100. package/dist/primitives/CanvasIcons.js +6 -0
  101. package/dist/primitives/CanvasStage.js +2 -2
  102. package/dist/primitives/ChartPrimitive.d.ts +11 -1
  103. package/dist/primitives/ChartPrimitive.js +73 -19
  104. package/dist/primitives/IconPrimitive.js +3 -0
  105. package/dist/primitives/IllustrationPrimitive.js +14 -1
  106. package/dist/primitives/chartFont.d.ts +30 -0
  107. package/dist/primitives/chartFont.js +127 -0
  108. package/dist/sidebar/sections/ImageAdjustSection.js +5 -4
  109. package/dist/sidebar/sections/assets/ElementsPanel.js +4 -2
  110. package/dist/sidebar/sections/assets/assetAudience.d.ts +12 -0
  111. package/dist/sidebar/sections/assets/assetAudience.js +18 -0
  112. package/dist/sidebar/sections/assets/useElementCatalog.js +3 -2
  113. package/dist/stores/createCanvasEditorStore.d.ts +5 -2
  114. package/dist/stores/createCanvasEditorStore.js +9 -5
  115. package/dist/styles/compiled.css +1 -1
  116. package/dist/utils/canvasAssets.d.ts +11 -1
  117. package/dist/utils/canvasAssets.js +8 -0
  118. package/dist/utils/canvasIcons.js +5 -3
  119. package/dist/utils/captureStage.d.ts +19 -0
  120. package/dist/utils/captureStage.js +14 -1
  121. package/dist/utils/externalIcons.d.ts +7 -0
  122. package/dist/utils/externalIcons.js +70 -3
  123. package/dist/utils/illustrations/svgCache.js +6 -1
  124. package/dist/utils/imageFilters.d.ts +13 -0
  125. package/dist/utils/imageFilters.js +11 -0
  126. package/dist/utils/rebaseHistoryState.d.ts +9 -0
  127. package/dist/utils/rebaseHistoryState.js +26 -0
  128. package/dist/utils/zipPageImages.d.ts +8 -0
  129. package/dist/utils/zipPageImages.js +16 -4
  130. package/package.json +6 -2
  131. package/skills/ggraphic-embed/SKILL.md +33 -1
@@ -39,13 +39,15 @@ function ProgressBar({ progress }) {
39
39
  }
40
40
  const DEFAULT_RASTER_PIXEL_RATIO = 1;
41
41
  const SCALE_OPTIONS = [1, 2];
42
- export function DownloadSection({ onDownload, onDownloadAllZip, pageCount, isMultiExporting = false, exportProgress, exportError, exportNotice, printExport = null, slideDeck = null, }) {
42
+ export function DownloadSection({ onDownload, onDownloadAllZip, pageCount, isMultiExporting = false, exportProgress, exportError, exportNotice, printExport = null, slideDeck = null, vectorExport = null, }) {
43
43
  const t = useMessages();
44
44
  const [choice, setChoice] = useState(printExport ? 'pdf' : slideDeck ? 'pptx' : 'png');
45
45
  const [pptxProgress, setPptxProgress] = useState(null);
46
46
  const [printWarnings] = useState(() => printExport?.getWarnings() ?? []);
47
47
  const [scale, setScale] = useState(DEFAULT_RASTER_PIXEL_RATIO);
48
48
  const [transparent, setTransparent] = useState(false);
49
+ const [keepTextEditable, setKeepTextEditable] = useState(false);
50
+ const [report, setReport] = useState(null);
49
51
  const [pageSelection, setPageSelection] = useState('current');
50
52
  const [isDownloading, setIsDownloading] = useState(false);
51
53
  const [downloadError, setDownloadError] = useState(null);
@@ -59,22 +61,49 @@ export function DownloadSection({ onDownload, onDownloadAllZip, pageCount, isMul
59
61
  impressumGate?.ready === true &&
60
62
  !impressum.isComplete(impressum.parse(impressumGate.locale, impressumGate.text ?? ''));
61
63
  const isSlidesPdf = choice === 'pdf' && slideDeck !== null;
64
+ // A digital format has no print or slide service: its PDF comes with the vector export.
65
+ const isDigitalPdf = choice === 'pdf' && !printExport && !slideDeck && vectorExport !== null;
62
66
  const isPptx = choice === 'pptx' && slideDeck !== null;
63
- const isMultiPage = pageCount > 1 && onDownloadAllZip && !isPdf && !isSlidesPdf && !isPptx;
67
+ const isSvg = choice === 'svg' && vectorExport !== null;
68
+ // A PDF always holds every page, so it asks nothing.
69
+ const isMultiPage = pageCount > 1 &&
70
+ (isSvg || (onDownloadAllZip && !isPdf && !isSlidesPdf && !isDigitalPdf && !isPptx));
71
+ // What the person is told after a vector download: SVG, and every PDF but the old raster one.
72
+ const reportsExport = isSvg || choice === 'pdf';
64
73
  // JPEG has no alpha channel — the transparency toggle is only meaningful for
65
74
  // PNG/WebP.
66
75
  const supportsTransparency = choice !== 'jpeg';
67
- const rasterFormat = choice === 'pdf' || choice === 'pptx' ? 'png' : choice;
76
+ // A print page or a slide always has its background; only a digital format can leave it out.
77
+ const svgTransparency = vectorExport?.category === 'digital';
78
+ const rasterFormat = choice === 'pdf' || choice === 'pptx' || choice === 'svg' ? 'png' : choice;
79
+ const downloadPanel = t.shell.downloadPanel;
80
+ // Once each, in the order they happened: the same reason on three photos is one phrase.
81
+ const rasterReasons = [
82
+ ...new Set(report?.rasterIslands.map((island) => downloadPanel.rasterReason[island.reason])),
83
+ ];
68
84
  const handleDownload = async () => {
69
85
  setIsDownloading(true);
70
86
  setDownloadError(null);
87
+ setReport(null);
71
88
  try {
89
+ if (isSvg && vectorExport) {
90
+ setReport(await vectorExport.onDownloadSvg({
91
+ pages: pageCount > 1 ? pageSelection : 'current',
92
+ text: keepTextEditable ? 'editable' : 'outlines',
93
+ transparent: svgTransparency && transparent,
94
+ }));
95
+ return;
96
+ }
72
97
  if (choice === 'pdf' && printExport) {
73
- await printExport.onDownloadPdf();
98
+ setReport((await printExport.onDownloadPdf()) ?? null);
74
99
  return;
75
100
  }
76
101
  if (isSlidesPdf && slideDeck) {
77
- await slideDeck.onDownloadPdf();
102
+ setReport((await slideDeck.onDownloadPdf()) ?? null);
103
+ return;
104
+ }
105
+ if (isDigitalPdf && vectorExport) {
106
+ setReport(await vectorExport.onDownloadPdf());
78
107
  return;
79
108
  }
80
109
  if (isPptx && slideDeck) {
@@ -97,6 +126,15 @@ export function DownloadSection({ onDownload, onDownloadAllZip, pageCount, isMul
97
126
  setPptxProgress(null);
98
127
  }
99
128
  };
100
- return (_jsxs("div", { className: "flex flex-col gap-3", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx(Label, { htmlFor: `${fieldId}-format`, className: "text-xs font-medium text-foreground-muted", children: t.shell.downloadPanel.format }), _jsxs(Select, { value: choice, onValueChange: (v) => setChoice(v), children: [_jsx(SelectTrigger, { id: `${fieldId}-format`, size: "sm", className: "w-full", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { position: "popper", className: "z-[10001]", children: [printExport && _jsx(SelectItem, { value: "pdf", children: t.shell.downloadPanel.pdfPrint }), slideDeck && _jsx(SelectItem, { value: "pptx", children: "PowerPoint (.pptx)" }), slideDeck && _jsx(SelectItem, { value: "pdf", children: "PDF" }), _jsx(SelectItem, { value: "png", children: "PNG" }), !printExport && _jsx(SelectItem, { value: "jpeg", children: "JPG" }), !printExport && _jsx(SelectItem, { value: "webp", children: "WebP" })] })] })] }), !isPdf && !isSlidesPdf && !isPptx && pageSelection === 'current' && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx(Label, { htmlFor: `${fieldId}-scale`, className: "text-xs font-medium text-foreground-muted", children: t.shell.downloadPanel.resolution }), _jsxs(Select, { value: String(scale), onValueChange: (v) => setScale(Number(v)), children: [_jsx(SelectTrigger, { id: `${fieldId}-scale`, size: "sm", className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { position: "popper", className: "z-[10001]", children: SCALE_OPTIONS.map((s) => (_jsxs(SelectItem, { value: String(s), children: [s, "\u00D7 ", s === DEFAULT_RASTER_PIXEL_RATIO ? t.shell.downloadPanel.defaultMark : ''] }, s))) })] })] }), supportsTransparency && (_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx(Label, { htmlFor: `${fieldId}-transparent`, className: "text-xs font-medium text-foreground-muted", children: t.shell.downloadPanel.transparentBackground }), _jsx(Switch, { id: `${fieldId}-transparent`, checked: transparent, onCheckedChange: setTransparent })] }))] })), isMultiPage && (_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx(Label, { htmlFor: `${fieldId}-pages`, className: "text-xs font-medium text-foreground-muted", children: t.shell.downloadPanel.selectPages }), _jsxs(Select, { value: pageSelection, onValueChange: (v) => setPageSelection(v), children: [_jsx(SelectTrigger, { id: `${fieldId}-pages`, size: "sm", className: "w-full", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { position: "popper", className: "z-[10001]", children: [_jsx(SelectItem, { value: "current", children: t.shell.downloadPanel.currentPage }), _jsx(SelectItem, { value: "all", children: t.shell.allPagesZip(pageCount) })] })] })] })), isMultiExporting && exportProgress && exportProgress.total > 0 && (_jsx(ProgressBar, { progress: exportProgress })), pptxProgress && pptxProgress.total > 0 && _jsx(ProgressBar, { progress: pptxProgress }), impressumMissing && impressumGate && impressum && (_jsxs(_Fragment, { children: [_jsx(DownloadNotice, { tone: "info", children: t.shell.downloadPanel.imprintMissingNotice }), _jsx(ImpressumForm, { gate: impressumGate, impressum: impressum })] })), isPdf && print?.untestedNotice && (_jsx(DownloadNotice, { tone: "info", children: print.untestedNotice })), isPptx && slideDeck && carousel?.pptxFontHint && (_jsx(DownloadNotice, { tone: "info", children: carousel.pptxFontHint[slideDeck.locale] })), isPdf &&
101
- printWarnings.map((warning) => (_jsx(DownloadNotice, { tone: "info", children: warning }, warning))), downloadError && _jsx(DownloadNotice, { children: downloadError }), exportError && !isMultiExporting && _jsx(DownloadNotice, { children: exportError }), exportNotice && _jsx(DownloadNotice, { tone: "info", children: exportNotice }), _jsxs(Button, { variant: "brand", className: "w-full rounded-lg", onClick: handleDownload, disabled: isDownloading || isMultiExporting, children: [isDownloading || isMultiExporting ? (_jsx(Skeleton, { className: "size-3.5 rounded-full" })) : (_jsx(PiDownloadSimple, { className: "size-3.5" })), isDownloading ? t.shell.downloading : t.shell.download] })] }));
129
+ return (_jsxs("div", { className: "flex flex-col gap-3", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx(Label, { htmlFor: `${fieldId}-format`, className: "text-xs font-medium text-foreground-muted", children: t.shell.downloadPanel.format }), _jsxs(Select, { value: choice, onValueChange: (v) => {
130
+ setChoice(v);
131
+ // What the last download reported is about that format only.
132
+ setReport(null);
133
+ }, children: [_jsx(SelectTrigger, { id: `${fieldId}-format`, size: "sm", className: "w-full", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { position: "popper", className: "z-[10001]", children: [printExport && _jsx(SelectItem, { value: "pdf", children: t.shell.downloadPanel.pdfPrint }), slideDeck && _jsx(SelectItem, { value: "pptx", children: "PowerPoint (.pptx)" }), slideDeck && _jsx(SelectItem, { value: "pdf", children: "PDF" }), vectorExport && (printExport || slideDeck) && (_jsx(SelectItem, { value: "svg", children: downloadPanel.svg })), _jsx(SelectItem, { value: "png", children: "PNG" }), !printExport && _jsx(SelectItem, { value: "jpeg", children: "JPG" }), !printExport && _jsx(SelectItem, { value: "webp", children: "WebP" }), vectorExport && !printExport && !slideDeck && (_jsxs(_Fragment, { children: [_jsx(SelectItem, { value: "pdf", children: "PDF" }), _jsx(SelectItem, { value: "svg", children: downloadPanel.svg })] }))] })] })] }), !isPdf &&
134
+ !isSlidesPdf &&
135
+ !isDigitalPdf &&
136
+ !isPptx &&
137
+ !isSvg &&
138
+ pageSelection === 'current' && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx(Label, { htmlFor: `${fieldId}-scale`, className: "text-xs font-medium text-foreground-muted", children: t.shell.downloadPanel.resolution }), _jsxs(Select, { value: String(scale), onValueChange: (v) => setScale(Number(v)), children: [_jsx(SelectTrigger, { id: `${fieldId}-scale`, size: "sm", className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { position: "popper", className: "z-[10001]", children: SCALE_OPTIONS.map((s) => (_jsxs(SelectItem, { value: String(s), children: [s, "\u00D7", ' ', s === DEFAULT_RASTER_PIXEL_RATIO ? t.shell.downloadPanel.defaultMark : ''] }, s))) })] })] }), supportsTransparency && (_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx(Label, { htmlFor: `${fieldId}-transparent`, className: "text-xs font-medium text-foreground-muted", children: t.shell.downloadPanel.transparentBackground }), _jsx(Switch, { id: `${fieldId}-transparent`, checked: transparent, onCheckedChange: setTransparent })] }))] })), isSvg && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx(Label, { htmlFor: `${fieldId}-editable-text`, className: "text-xs font-medium text-foreground-muted", children: downloadPanel.keepTextEditable }), _jsx(Switch, { id: `${fieldId}-editable-text`, "aria-describedby": `${fieldId}-editable-text-hint`, checked: keepTextEditable, onCheckedChange: setKeepTextEditable })] }), _jsx("p", { id: `${fieldId}-editable-text-hint`, className: "m-0 text-xs text-foreground-muted", children: downloadPanel.keepTextEditableHint })] }), svgTransparency && (_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx(Label, { htmlFor: `${fieldId}-transparent`, className: "text-xs font-medium text-foreground-muted", children: downloadPanel.transparentBackground }), _jsx(Switch, { id: `${fieldId}-transparent`, checked: transparent, onCheckedChange: setTransparent })] }))] })), isMultiPage && (_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx(Label, { htmlFor: `${fieldId}-pages`, className: "text-xs font-medium text-foreground-muted", children: t.shell.downloadPanel.selectPages }), _jsxs(Select, { value: pageSelection, onValueChange: (v) => setPageSelection(v), children: [_jsx(SelectTrigger, { id: `${fieldId}-pages`, size: "sm", className: "w-full", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { position: "popper", className: "z-[10001]", children: [_jsx(SelectItem, { value: "current", children: t.shell.downloadPanel.currentPage }), _jsx(SelectItem, { value: "all", children: t.shell.allPagesZip(pageCount) })] })] })] })), isMultiExporting && exportProgress && exportProgress.total > 0 && (_jsx(ProgressBar, { progress: exportProgress })), pptxProgress && pptxProgress.total > 0 && _jsx(ProgressBar, { progress: pptxProgress }), impressumMissing && impressumGate && impressum && (_jsxs(_Fragment, { children: [_jsx(DownloadNotice, { tone: "info", children: t.shell.downloadPanel.imprintMissingNotice }), _jsx(ImpressumForm, { gate: impressumGate, impressum: impressum })] })), isPdf && print?.untestedNotice && (_jsx(DownloadNotice, { tone: "info", children: print.untestedNotice })), isPptx && slideDeck && carousel?.pptxFontHint && (_jsx(DownloadNotice, { tone: "info", children: carousel.pptxFontHint[slideDeck.locale] })), isPdf &&
139
+ printWarnings.map((warning) => (_jsx(DownloadNotice, { tone: "info", children: warning }, warning))), downloadError && _jsx(DownloadNotice, { children: downloadError }), exportError && !isMultiExporting && _jsx(DownloadNotice, { children: exportError }), exportNotice && _jsx(DownloadNotice, { tone: "info", children: exportNotice }), _jsxs(Button, { variant: "brand", className: "w-full rounded-lg", onClick: handleDownload, disabled: isDownloading || isMultiExporting, children: [isDownloading || isMultiExporting ? (_jsx(Skeleton, { className: "size-3.5 rounded-full" })) : (_jsx(PiDownloadSimple, { className: "size-3.5" })), isDownloading ? t.shell.downloading : t.shell.download] }), reportsExport && report?.fallback && (_jsx(DownloadNotice, { tone: "info", children: downloadPanel.pdfFallbackNotice[report.fallback.kind] })), reportsExport && report && report.missingElements.length > 0 && (_jsx(DownloadNotice, { children: downloadPanel.missingNotice(report.missingElements.length) })), reportsExport && report && report.reducedRasters.length > 0 && (_jsx(DownloadNotice, { tone: "info", children: downloadPanel.reducedRasterNotice })), reportsExport && report && report.defaultInstanceFonts.length > 0 && (_jsx(DownloadNotice, { tone: "info", children: downloadPanel.variableFontNotice(report.defaultInstanceFonts.join(', ')) })), reportsExport && rasterReasons.length > 0 && (_jsx(DownloadNotice, { tone: "info", children: downloadPanel.rasterNotice(rasterReasons.join(', ')) }))] }));
102
140
  }
@@ -1,4 +1,4 @@
1
- import { type CanvasDownloadChoice, type PrintExportProps, type SlideDeckExportProps } from './DownloadSection.js';
1
+ import { type CanvasDownloadChoice, type PrintExportProps, type SlideDeckExportProps, type VectorExportProps } from './DownloadSection.js';
2
2
  export interface ShareDropdownProps {
3
3
  onCaptureCanvas: () => Promise<string | null>;
4
4
  onDownload: (format: CanvasDownloadChoice, pixelRatio: number, transparent: boolean) => void | Promise<void>;
@@ -22,6 +22,8 @@ export interface ShareDropdownProps {
22
22
  printExport?: PrintExportProps | null;
23
23
  /** Set for slide formats: the download section offers PowerPoint and a PDF of all pages. */
24
24
  slideDeck?: SlideDeckExportProps | null;
25
+ /** SVG download; without it the download section offers no SVG. */
26
+ vectorExport?: VectorExportProps | null;
25
27
  /**
26
28
  * Optional host-supplied "invite people" action. When provided, the share
27
29
  * popover shows a "Personen" icon button that opens the host's collaborator
@@ -51,4 +53,4 @@ export interface ShareDropdownProps {
51
53
  */
52
54
  getPhotoCredit?: () => string;
53
55
  }
54
- export declare function ShareDropdown({ onCaptureCanvas, onDownload, onNavigateToGallery, canvasText, canvasWidth, canvasHeight, shareToken, pageCount, onDownloadAllZip, onShareAllPages, isMultiExporting, exportProgress, exportError, exportNotice, printExport, slideDeck, onInvitePeople, onSaveAsTemplate, hostControl, getPhotoCredit, }: ShareDropdownProps): import("react").JSX.Element;
56
+ export declare function ShareDropdown({ onCaptureCanvas, onDownload, onNavigateToGallery, canvasText, canvasWidth, canvasHeight, shareToken, pageCount, onDownloadAllZip, onShareAllPages, isMultiExporting, exportProgress, exportError, exportNotice, printExport, slideDeck, vectorExport, onInvitePeople, onSaveAsTemplate, hostControl, getPhotoCredit, }: ShareDropdownProps): import("react").JSX.Element;
@@ -16,7 +16,7 @@ import { useIsCanvasMobile } from '../../hooks/useIsCanvasMobile.js';
16
16
  import { AltTextField, useCaptionAltText, useShareAltText, withAltText, } from '../../sidebar/components/AltTextField.js';
17
17
  import { withPhotoCredit } from '../../utils/photoCredit.js';
18
18
  import { DownloadSection, } from './DownloadSection.js';
19
- export function ShareDropdown({ onCaptureCanvas, onDownload, onNavigateToGallery, canvasText, canvasWidth, canvasHeight, shareToken, pageCount = 1, onDownloadAllZip, onShareAllPages, isMultiExporting = false, exportProgress, exportError, exportNotice, printExport, slideDeck, onInvitePeople, onSaveAsTemplate, hostControl, getPhotoCredit, }) {
19
+ export function ShareDropdown({ onCaptureCanvas, onDownload, onNavigateToGallery, canvasText, canvasWidth, canvasHeight, shareToken, pageCount = 1, onDownloadAllZip, onShareAllPages, isMultiExporting = false, exportProgress, exportError, exportNotice, printExport, slideDeck, vectorExport, onInvitePeople, onSaveAsTemplate, hostControl, getPhotoCredit, }) {
20
20
  const t = useMessages();
21
21
  const isMobile = useIsCanvasMobile();
22
22
  const [ownOpen, setOwnOpen] = useState(false);
@@ -92,7 +92,7 @@ export function ShareDropdown({ onCaptureCanvas, onDownload, onNavigateToGallery
92
92
  setOpen(v);
93
93
  if (!v)
94
94
  setView('main');
95
- }, children: [hostControl ? (_jsx(PopoverAnchor, { className: "absolute right-3 top-0 size-0" })) : (_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { size: "sm", className: "ml-auto h-9 rounded-full bg-white px-4 font-extrabold text-[var(--editor-green-deep)] hover:bg-white/90 max-canvas-mobile:h-8 max-canvas-mobile:px-3", children: [_jsx(IoShareOutline, { className: "size-4" }), _jsx("span", { children: t.shell.share })] }) })), _jsxs(PopoverContent, { align: "end", sideOffset: 8, className: "w-80 p-0 overflow-hidden", children: [view === 'download' ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "px-4 pt-3 pb-1", children: _jsxs("button", { type: "button", onClick: () => setView('main'), className: "flex items-center gap-2 bg-transparent border-none cursor-pointer p-0 text-sm font-semibold text-foreground transition-colors duration-150 hover:text-primary-600", children: [_jsx(PiArrowLeft, { size: 16 }), "Download"] }) }), _jsx("div", { className: "px-4 pt-2 pb-4", children: _jsx(DownloadSection, { onDownload: onDownload, onDownloadAllZip: onDownloadAllZip, pageCount: pageCount, isMultiExporting: isMultiExporting, exportProgress: exportProgress, exportError: exportError, exportNotice: exportNotice, printExport: printExport, slideDeck: slideDeck }) })] })) : (_jsxs(_Fragment, { children: [_jsx("div", { className: "px-4 pt-4 pb-2", children: _jsx("h3", { className: "text-base font-semibold text-foreground m-0", children: t.shell.share }) }), _jsxs(IconButtonRow, { gap: "lg", padding: "md", className: "justify-center py-3", children: [_jsx(IconButton, { size: "sm", icon: _jsx(PiDownloadSimple, {}), label: t.shell.downloadTab, onClick: () => setView('download') }), shareRoute !== null && (_jsx(IconButton, { size: "sm", icon: isSharing ? (_jsx(Skeleton, { className: "size-4 rounded-full" })) : shareSuccess ? (_jsx(PiCheck, {})) : (_jsx(IoShareOutline, {})), label: shareSuccess ? t.shell.shared : t.shell.share, onClick: handleNativeShare, disabled: isSharing })), onSaveAsTemplate && (_jsx(IconButton, { size: "sm", icon: _jsx(PiFloppyDisk, {}), label: t.shell.template, onClick: () => {
95
+ }, children: [hostControl ? (_jsx(PopoverAnchor, { className: "absolute right-3 top-0 size-0" })) : (_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { size: "sm", className: "ml-auto h-9 rounded-full bg-white px-4 font-extrabold text-[var(--editor-green-deep)] hover:bg-white/90 max-canvas-mobile:h-8 max-canvas-mobile:px-3", children: [_jsx(IoShareOutline, { className: "size-4" }), _jsx("span", { children: t.shell.share })] }) })), _jsxs(PopoverContent, { align: "end", sideOffset: 8, className: "w-80 p-0 overflow-hidden", children: [view === 'download' ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "px-4 pt-3 pb-1", children: _jsxs("button", { type: "button", onClick: () => setView('main'), className: "flex items-center gap-2 bg-transparent border-none cursor-pointer p-0 text-sm font-semibold text-foreground transition-colors duration-150 hover:text-primary-600", children: [_jsx(PiArrowLeft, { size: 16 }), "Download"] }) }), _jsx("div", { className: "px-4 pt-2 pb-4", children: _jsx(DownloadSection, { onDownload: onDownload, onDownloadAllZip: onDownloadAllZip, pageCount: pageCount, isMultiExporting: isMultiExporting, exportProgress: exportProgress, exportError: exportError, exportNotice: exportNotice, printExport: printExport, slideDeck: slideDeck, vectorExport: vectorExport }) })] })) : (_jsxs(_Fragment, { children: [_jsx("div", { className: "px-4 pt-4 pb-2", children: _jsx("h3", { className: "text-base font-semibold text-foreground m-0", children: t.shell.share }) }), _jsxs(IconButtonRow, { gap: "lg", padding: "md", className: "justify-center py-3", children: [_jsx(IconButton, { size: "sm", icon: _jsx(PiDownloadSimple, {}), label: t.shell.downloadTab, onClick: () => setView('download') }), shareRoute !== null && (_jsx(IconButton, { size: "sm", icon: isSharing ? (_jsx(Skeleton, { className: "size-4 rounded-full" })) : shareSuccess ? (_jsx(PiCheck, {})) : (_jsx(IoShareOutline, {})), label: shareSuccess ? t.shell.shared : t.shell.share, onClick: handleNativeShare, disabled: isSharing })), onSaveAsTemplate && (_jsx(IconButton, { size: "sm", icon: _jsx(PiFloppyDisk, {}), label: t.shell.template, onClick: () => {
96
96
  setOpen(false);
97
97
  onSaveAsTemplate();
98
98
  } })), onInvitePeople && (_jsx(IconButton, { size: "sm", icon: _jsx(PiUserPlus, {}), label: t.shell.people, onClick: () => {
@@ -1,8 +1,21 @@
1
- /** Export: PPTX (fonts, model, writer), print and slide PDFs, and zipped page images. */
1
+ /**
2
+ * Export: PPTX (fonts, model, writer), print and slide PDFs, SVG (recorder, resolver, writer, font
3
+ * files), and zipped page images.
4
+ */
2
5
  export { pptxFamily, type PptxFontMapper, registerPptxFonts } from '../export/pptx/pptxFonts.js';
3
6
  export { type PptxPageState } from '../export/pptx/buildPptxModel.js';
4
7
  export { type PptxDeckModel, type PptxSlideModel, type PptxItem } from '../export/pptx/types.js';
5
8
  export { writePptx, PPTX_MIME_TYPE } from '../export/pptx/writePptx.js';
6
9
  export { exportPrintPdf, lowResolutionWarnings, type PrintExportPage, type PrintExportImage, } from '../export/printExport.js';
7
10
  export { exportSlidesPdf } from '../export/slidesPdf.js';
11
+ export { resolveFontFiles, type FontFile, type FontFileSet, type FontSourceDeps, } from '../export/fonts/fontFiles.js';
12
+ export { fetchImageBytes, rasterizeOps, reencodeImage } from '../export/scene/browserDeps.js';
13
+ export { pngFromDataUrl } from '../export/scene/imageBytes.js';
14
+ export { recordPageScene, type RecordPageOptions } from '../export/scene/recordPageScene.js';
15
+ export { resolveScene, type ResolveDeps } from '../export/scene/resolveScene.js';
16
+ export { emptyReport, type ClipPath, type ColorStop, type ExportReport, type ExportScene, type FontSpec, type Matrix, type Paint, type PathCommand, type RasterReason, type RecordedScene, type SceneImageRef, type SceneImageSource, type SceneItem, type SceneOp, type Shadow, type StrokeStyle, } from '../export/scene/types.js';
17
+ export { writePdf, type WritePdfOptions } from '../export/pdf/writePdf.js';
18
+ export { writeSvg, type WriteSvgOptions } from '../export/svg/writeSvg.js';
19
+ export { createVectorDeps, type CreateVectorDepsOptions, type VectorExportCanvas, } from '../export/vectorDeps.js';
20
+ export { exportPagesPdf, exportPagesSvg, type PdfExportDeps, type PdfExportOptions, type VectorExportDeps, type VectorExportOptions, type VectorExportResult, } from '../export/vectorExport.js';
8
21
  export { zipPageImages } from '../utils/zipPageImages.js';
@@ -1,7 +1,20 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-only
2
- /** Export: PPTX (fonts, model, writer), print and slide PDFs, and zipped page images. */
2
+ /**
3
+ * Export: PPTX (fonts, model, writer), print and slide PDFs, SVG (recorder, resolver, writer, font
4
+ * files), and zipped page images.
5
+ */
3
6
  export { pptxFamily, registerPptxFonts } from '../export/pptx/pptxFonts.js';
4
7
  export { writePptx, PPTX_MIME_TYPE } from '../export/pptx/writePptx.js';
5
8
  export { exportPrintPdf, lowResolutionWarnings, } from '../export/printExport.js';
6
9
  export { exportSlidesPdf } from '../export/slidesPdf.js';
10
+ export { resolveFontFiles, } from '../export/fonts/fontFiles.js';
11
+ export { fetchImageBytes, rasterizeOps, reencodeImage } from '../export/scene/browserDeps.js';
12
+ export { pngFromDataUrl } from '../export/scene/imageBytes.js';
13
+ export { recordPageScene } from '../export/scene/recordPageScene.js';
14
+ export { resolveScene } from '../export/scene/resolveScene.js';
15
+ export { emptyReport, } from '../export/scene/types.js';
16
+ export { writePdf } from '../export/pdf/writePdf.js';
17
+ export { writeSvg } from '../export/svg/writeSvg.js';
18
+ export { createVectorDeps, } from '../export/vectorDeps.js';
19
+ export { exportPagesPdf, exportPagesSvg, } from '../export/vectorExport.js';
7
20
  export { zipPageImages } from '../utils/zipPageImages.js';
@@ -1,6 +1,6 @@
1
1
  /** Host services: the service types `CanvasEditorProvider` takes, their browser defaults, toasts, storage keys and screen-corner reservations. */
2
2
  export { type CanvasEditorServices, type CanvasEditorHostServices, type CanvasSlotBudgetService, } from '../CanvasEditorProvider.js';
3
- export { browserFileDelivery, type CanvasCarouselService, type CanvasFeedbackService, type CanvasImageUrlService, type CanvasImprintParts, type CanvasImprintService, type CanvasMediaItem, type CanvasMediaLibraryService, type CanvasMediaUploadResult, type CanvasMediaUploadState, type CanvasPrintService, plainImageUrls, } from '../hostServices.js';
3
+ export { browserFileDelivery, type CanvasCarouselService, type CanvasExportFontService, type CanvasFeedbackService, type CanvasImageUrlService, type CanvasImprintParts, type CanvasImprintService, type CanvasMediaItem, type CanvasMediaLibraryService, type CanvasMediaUploadResult, type CanvasMediaUploadState, type CanvasPrintService, plainImageUrls, } from '../hostServices.js';
4
4
  export { type EditorToast, type EditorToastOptions, registerToast, type EditorToastAction, } from '../utils/editorToast.js';
5
5
  export { registerHostStorageKeys, type HostStorageKeyName } from '../utils/hostStorageKeys.js';
6
6
  export { type MeasuredCornerReservation, type MeasuredCornerReservationHook, registerMeasuredCornerReservation, type ScreenCorner, } from '../utils/cornerReservation.js';
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Finds the font files behind a recorded text op's `FontSpec`, for the writers that draw glyph
3
+ * outlines (SVG) or embed fonts (PDF).
4
+ *
5
+ * Sources, first one with a file wins: the host's `exportFonts` service, the brand pack's font
6
+ * faces, then the page's own `@font-face` rules. A CSS family can come as several files, one per
7
+ * `unicode-range`; `fileFor` picks the one that covers a code point. Nothing here is cached
8
+ * between exports: the caller passes the `Map` it wants to share.
9
+ */
10
+ import { type BrandFontFace } from '@ggraphic/core';
11
+ import { type FontkitFont, type FontkitFsType } from './glyphs.js';
12
+ import { type Variation } from './variation.js';
13
+ import type { CanvasExportFontService } from '../../hostServices.js';
14
+ import type { FontSpec } from '../scene/types.js';
15
+ /**
16
+ * How far a browser shears the upright cut it draws for an italic nobody ships: Skia's fake italic
17
+ * is `skewX(-1/4)`, a quarter of the height above the baseline to the right.
18
+ */
19
+ export declare const SYNTHETIC_ITALIC_SLANT = 0.25;
20
+ export interface FontFile {
21
+ bytes: Uint8Array;
22
+ font: FontkitFont;
23
+ /** What the font's licence flags allow; see `embeddingOf`. */
24
+ embeddable: 'yes' | 'outlines-only' | 'bitmap-only';
25
+ /** The `unicode-range` the stylesheet declared for the file; null = the whole font. */
26
+ ranges: readonly [number, number][] | null;
27
+ /**
28
+ * How far a writer shears the glyphs, per unit of height above the baseline: 0 for a real cut,
29
+ * `SYNTHETIC_ITALIC_SLANT` for the upright cut that stands in for an italic the family lacks.
30
+ */
31
+ slant: number;
32
+ /**
33
+ * True for a cut lighter than 600 that stands in for a weight of 600 or more the family does not
34
+ * ship: a writer draws it emboldened like a browser does (`fakeBoldWidth`).
35
+ */
36
+ fakeBold: boolean;
37
+ /**
38
+ * How `font` stands to the weight asked for when the file is a variable font (`none` for any
39
+ * other): `instance` = `font` is the instance for that weight, `default-only` = it could not be
40
+ * made and `font` draws the file's default instance, which a writer reports.
41
+ */
42
+ variation: Variation;
43
+ }
44
+ export interface FontFileSet {
45
+ face: FontSpec;
46
+ /** In declaration order; empty when no source has the face. */
47
+ files: readonly FontFile[];
48
+ /**
49
+ * The file that draws `codePoint`, or null. A file covers a code point only if its declared
50
+ * range includes it AND the font has a glyph for it: the glyph check alone is not enough for a
51
+ * file that claims a range it does not fully cover, and the range alone is not enough because
52
+ * fontkit silently answers `.notdef`. Where ranges overlap the later file wins, as in a browser.
53
+ */
54
+ fileFor(codePoint: number): FontFile | null;
55
+ }
56
+ /** The members of `CSSFontFaceRule` the resolver reads, so a test needs no DOM. */
57
+ export interface FontFaceRuleLike {
58
+ style: {
59
+ getPropertyValue(name: string): string;
60
+ };
61
+ }
62
+ export interface FontSourceDeps {
63
+ host?: CanvasExportFontService;
64
+ brandFaces?: readonly BrandFontFace[];
65
+ /** `BrandFonts.boldFamilies`: regular family → the family whose regular cut is its bold. */
66
+ boldFamilies?: Readonly<Record<string, string>>;
67
+ /** Default: the `@font-face` rules of `document.styleSheets` (none without a document). Injected in tests. */
68
+ cssRules?: () => Iterable<FontFaceRuleLike>;
69
+ /** Default: `fetch`. A download that fails or answers an error status is a missing font. */
70
+ fetchBytes?: (url: string) => Promise<Uint8Array | null>;
71
+ /**
72
+ * The files by `family|weight|style`, shared by the faces of one export. The caller creates it
73
+ * and drops it with the export; there is no module-level cache.
74
+ */
75
+ cache?: Map<string, Promise<readonly FontFile[]>>;
76
+ }
77
+ export declare function resolveFontFiles(face: FontSpec, deps: FontSourceDeps): Promise<FontFileSet>;
78
+ /**
79
+ * What the licence flags of a font (`OS/2.fsType`) allow: 0x0002 (restricted licence) = its
80
+ * outlines may be drawn but the font must not travel in the file; 0x0200 = only bitmaps may be
81
+ * embedded. Preview/print, editable and no-subsetting (0x0004, 0x0008, 0x0100) allow embedding.
82
+ * Takes the flag object fontkit decodes the field into as well as the raw number.
83
+ */
84
+ export declare function embeddingOf(fsType: FontkitFsType): FontFile['embeddable'];
85
+ /**
86
+ * The code point ranges of a CSS `unicode-range` value: `U+26`, `U+0-7F` and `U+4??`. Tokens
87
+ * that are not a valid range are dropped.
88
+ */
89
+ export declare function parseUnicodeRange(value: string): [number, number][];
90
+ /**
91
+ * The six capital letters a PDF font name carries before the `+` for a subset (`ABCDEF+Name`),
92
+ * derived from the face and the index of the file in its set, so the same export names its
93
+ * subsets the same way every time. pdf-lib's own default name has no such prefix.
94
+ */
95
+ export declare function subsetTag(face: FontSpec, fileIndex: number): string;
96
+ /**
97
+ * The `@font-face` rules of every style sheet of the document, imports and grouping rules
98
+ * included. The default of `FontSourceDeps.cssRules`; exported for its own test.
99
+ */
100
+ export declare function documentFontFaces(): Iterable<CSSFontFaceRule>;
@@ -0,0 +1,333 @@
1
+ import { resolveFontFamily } from '../../utils/fontAliases.js';
2
+ import { loadFontkit } from './glyphs.js';
3
+ import { variationInstance } from './variation.js';
4
+ /**
5
+ * How far a browser shears the upright cut it draws for an italic nobody ships: Skia's fake italic
6
+ * is `skewX(-1/4)`, a quarter of the height above the baseline to the right.
7
+ */
8
+ export const SYNTHETIC_ITALIC_SLANT = 0.25;
9
+ export async function resolveFontFiles(face, deps) {
10
+ const key = `${face.family}|${face.weight}|${face.style}`;
11
+ let files = deps.cache?.get(key);
12
+ if (!files) {
13
+ files = loadFiles(face, deps);
14
+ deps.cache?.set(key, files);
15
+ }
16
+ return fileSet(face, await files);
17
+ }
18
+ function fileSet(face, files) {
19
+ return {
20
+ face,
21
+ files,
22
+ fileFor(codePoint) {
23
+ for (let i = files.length - 1; i >= 0; i--) {
24
+ const file = files[i];
25
+ if (covers(file, codePoint))
26
+ return file;
27
+ }
28
+ return null;
29
+ },
30
+ };
31
+ }
32
+ function covers(file, codePoint) {
33
+ const inRange = file.ranges === null || file.ranges.some(([from, to]) => codePoint >= from && codePoint <= to);
34
+ return inRange && file.font.hasGlyphForCodePoint(codePoint);
35
+ }
36
+ // ── Embedding permission ────────────────────────────────────────────────────
37
+ const FS_NO_EMBEDDING = 0x0002;
38
+ const FS_BITMAP_ONLY = 0x0200;
39
+ /**
40
+ * What the licence flags of a font (`OS/2.fsType`) allow: 0x0002 (restricted licence) = its
41
+ * outlines may be drawn but the font must not travel in the file; 0x0200 = only bitmaps may be
42
+ * embedded. Preview/print, editable and no-subsetting (0x0004, 0x0008, 0x0100) allow embedding.
43
+ * Takes the flag object fontkit decodes the field into as well as the raw number.
44
+ */
45
+ export function embeddingOf(fsType) {
46
+ const bits = typeof fsType === 'number'
47
+ ? fsType
48
+ : (fsType.noEmbedding ? FS_NO_EMBEDDING : 0) | (fsType.bitmapOnly ? FS_BITMAP_ONLY : 0);
49
+ if (bits & FS_BITMAP_ONLY)
50
+ return 'bitmap-only';
51
+ if (bits & FS_NO_EMBEDDING)
52
+ return 'outlines-only';
53
+ return 'yes';
54
+ }
55
+ // ── unicode-range ───────────────────────────────────────────────────────────
56
+ const MAX_CODE_POINT = 0x10ffff;
57
+ /**
58
+ * The code point ranges of a CSS `unicode-range` value: `U+26`, `U+0-7F` and `U+4??`. Tokens
59
+ * that are not a valid range are dropped.
60
+ */
61
+ export function parseUnicodeRange(value) {
62
+ const ranges = [];
63
+ for (const token of value.split(',')) {
64
+ const match = /^\s*u\+([0-9a-f?]{1,6})(?:-([0-9a-f]{1,6}))?\s*$/i.exec(token);
65
+ if (!match)
66
+ continue;
67
+ const start = match[1];
68
+ const end = match[2];
69
+ let range;
70
+ if (start.includes('?')) {
71
+ if (end !== undefined)
72
+ continue;
73
+ range = [parseInt(start.replace(/\?/g, '0'), 16), parseInt(start.replace(/\?/g, 'f'), 16)];
74
+ }
75
+ else {
76
+ const from = parseInt(start, 16);
77
+ range = [from, end === undefined ? from : parseInt(end, 16)];
78
+ }
79
+ if (range[0] <= range[1] && range[1] <= MAX_CODE_POINT)
80
+ ranges.push(range);
81
+ }
82
+ return ranges;
83
+ }
84
+ // ── Subset tag ──────────────────────────────────────────────────────────────
85
+ /**
86
+ * The six capital letters a PDF font name carries before the `+` for a subset (`ABCDEF+Name`),
87
+ * derived from the face and the index of the file in its set, so the same export names its
88
+ * subsets the same way every time. pdf-lib's own default name has no such prefix.
89
+ */
90
+ export function subsetTag(face, fileIndex) {
91
+ // FNV-1a, 32 bit, over the UTF-16 units of the key.
92
+ const key = `${face.family}|${face.weight}|${face.style}|${fileIndex}`;
93
+ let hash = 0x811c9dc5;
94
+ for (let i = 0; i < key.length; i++) {
95
+ hash = Math.imul(hash ^ key.charCodeAt(i), 0x01000193) >>> 0;
96
+ }
97
+ let tag = '';
98
+ for (let i = 0; i < 6; i++) {
99
+ tag += String.fromCharCode(65 + (hash % 26));
100
+ hash = Math.floor(hash / 26);
101
+ }
102
+ return tag;
103
+ }
104
+ async function loadFiles(face, deps) {
105
+ const family = bareFamily(resolveFontFamily(face.family));
106
+ const boldFamily = face.weight >= 600 ? deps.boldFamilies?.[family] : undefined;
107
+ const attempts = boldFamily
108
+ ? [
109
+ { family: boldFamily, weight: 400 },
110
+ { family, weight: face.weight },
111
+ ]
112
+ : [{ family, weight: face.weight }];
113
+ const find = async (style) => {
114
+ for (const attempt of attempts) {
115
+ const { files, served } = await filesFor(attempt.family, attempt.weight, style, deps);
116
+ if (files.length === 0)
117
+ continue;
118
+ // A bold asked for and a lighter cut served (the bold family's own regular is not that).
119
+ const fakeBold = attempt.weight >= 600 && served !== null && served < 600;
120
+ // A variable font covers the weights of its axis whatever its @font-face says.
121
+ return fakeBold
122
+ ? files.map((file) => (file.font.variationAxes?.['wght'] ? file : { ...file, fakeBold }))
123
+ : files;
124
+ }
125
+ return [];
126
+ };
127
+ const files = await find(face.style);
128
+ if (files.length > 0 || face.style === 'normal')
129
+ return files;
130
+ // An italic the family does not ship. A style is never traded for a weight above (a real italic
131
+ // of another weight beats the upright), but with no italic at all a browser slants the upright
132
+ // cut, so the export does: the file is the upright one, flagged for the writers to shear.
133
+ return (await find('normal')).map((file) => ({ ...file, slant: SYNTHETIC_ITALIC_SLANT }));
134
+ }
135
+ /** The files for one family and weight, and the weight they serve (null: unknown). */
136
+ async function filesFor(family, weight, style, deps) {
137
+ // The host's service is code we do not control: a throw is a font it does not have, the same
138
+ // as a download that fails, and the next source is asked.
139
+ let hosted = null;
140
+ try {
141
+ hosted = await deps.host?.load({ family, weight, style });
142
+ }
143
+ catch {
144
+ hosted = null;
145
+ }
146
+ if (hosted) {
147
+ const file = await toFontFile(hosted, null, weight);
148
+ // The host does not say which weight it served; the font's own class does (a host that
149
+ // answers a bold request with its regular is the case fake bold exists for).
150
+ const declared = file?.font['OS/2']?.usWeightClass;
151
+ if (file)
152
+ return { files: [file], served: declared && declared > 0 ? declared : null };
153
+ }
154
+ const fetchBytes = deps.fetchBytes ?? fetchOverHttp;
155
+ // The brand's faces first; the page's `@font-face` rules only if the brand has none.
156
+ const sources = [
157
+ () => brandCandidates(deps.brandFaces ?? [], family),
158
+ () => cssCandidates((deps.cssRules ?? documentFontFaces)(), family),
159
+ ];
160
+ for (const candidatesOf of sources) {
161
+ const picked = pickCandidates(candidatesOf(), weight, style);
162
+ const files = await loadCandidates(picked, fetchBytes, weight);
163
+ if (files.length > 0) {
164
+ const [first] = picked;
165
+ return { files, served: first ? Math.min(Math.max(weight, first.low), first.high) : null };
166
+ }
167
+ }
168
+ return { files: [], served: null };
169
+ }
170
+ function brandCandidates(faces, family) {
171
+ const wanted = family.toLowerCase();
172
+ return faces
173
+ .filter((face) => face.family.toLowerCase() === wanted)
174
+ .map((face) => ({
175
+ low: face.weight ?? 400,
176
+ high: face.weight ?? 400,
177
+ style: face.style ?? 'normal',
178
+ urls: [face.src],
179
+ ranges: null,
180
+ }));
181
+ }
182
+ function cssCandidates(rules, family) {
183
+ const wanted = family.toLowerCase();
184
+ const candidates = [];
185
+ for (const rule of rules) {
186
+ const declared = rule.style.getPropertyValue.bind(rule.style);
187
+ if (bareFamily(declared('font-family')).toLowerCase() !== wanted)
188
+ continue;
189
+ const urls = readableUrls(declared('src'));
190
+ if (urls.length === 0)
191
+ continue;
192
+ const [low, high] = parseWeights(declared('font-weight'));
193
+ const ranges = parseUnicodeRange(declared('unicode-range'));
194
+ candidates.push({
195
+ low,
196
+ high,
197
+ style: /^\s*(italic|oblique)/i.test(declared('font-style')) ? 'italic' : 'normal',
198
+ urls,
199
+ ranges: ranges.length > 0 ? ranges : null,
200
+ });
201
+ }
202
+ return candidates;
203
+ }
204
+ /**
205
+ * The candidates serving the style and the weight closest to `weight`. A style is never traded
206
+ * for a weight: an italic of another weight is closer to what was asked than the upright cut of
207
+ * the right one. An empty answer is for `loadFiles` to turn into a slanted upright cut.
208
+ */
209
+ function pickCandidates(candidates, weight, style) {
210
+ const styled = candidates.filter((c) => c.style === style);
211
+ const served = (c) => Math.min(Math.max(weight, c.low), c.high);
212
+ const best = nearestWeight(styled.map(served), weight);
213
+ return styled.filter((c) => served(c) === best);
214
+ }
215
+ /**
216
+ * CSS Fonts 4, "font matching": the exact weight; else for 400 to 500 the heavier weights up to
217
+ * 500 (ascending), then the lighter ones (descending), then those above 500; below 400 the
218
+ * lighter ones first, above 500 the heavier ones first, each followed by the other side.
219
+ */
220
+ function nearestWeight(available, target) {
221
+ if (available.length === 0 || available.includes(target))
222
+ return target;
223
+ const lighter = available.filter((w) => w < target).sort((a, b) => b - a);
224
+ const heavier = available.filter((w) => w > target).sort((a, b) => a - b);
225
+ if (target > 500)
226
+ return heavier[0] ?? lighter[0];
227
+ if (target >= 400)
228
+ return heavier.find((w) => w <= 500) ?? lighter[0] ?? heavier[0];
229
+ return lighter[0] ?? heavier[0];
230
+ }
231
+ /** `normal`, `bold`, `700` or a variable-font range `100 900`. */
232
+ function parseWeights(value) {
233
+ const weights = value
234
+ .trim()
235
+ .split(/\s+/)
236
+ .map((token) => (token === 'normal' ? 400 : token === 'bold' ? 700 : Number(token)))
237
+ .filter((weight) => Number.isFinite(weight) && weight > 0);
238
+ if (weights.length === 0)
239
+ return [400, 400];
240
+ return [Math.min(...weights), Math.max(...weights)];
241
+ }
242
+ async function loadCandidates(candidates, fetchBytes, weight) {
243
+ const files = await Promise.all(candidates.map(async (candidate) => {
244
+ for (const url of candidate.urls) {
245
+ const bytes = await fetchBytes(url).catch(() => null);
246
+ const file = bytes && (await toFontFile(bytes, candidate.ranges, weight));
247
+ if (file)
248
+ return file;
249
+ }
250
+ return null;
251
+ }));
252
+ return files.filter((file) => file !== null);
253
+ }
254
+ async function toFontFile(bytes, ranges, weight) {
255
+ const parsed = await parseFont(bytes);
256
+ if (!parsed)
257
+ return null;
258
+ const { font, variation } = variationInstance(parsed, weight);
259
+ return {
260
+ bytes,
261
+ font,
262
+ embeddable: embeddingOf(parsed['OS/2']?.fsType ?? 0),
263
+ ranges,
264
+ slant: 0,
265
+ fakeBold: false,
266
+ variation,
267
+ };
268
+ }
269
+ async function parseFont(bytes) {
270
+ const fontkit = await loadFontkit();
271
+ try {
272
+ // Boundary cast: fontkit's shipped declarations lack what `FontkitFont` adds (see glyphs.ts).
273
+ const font = fontkit.create(bytes);
274
+ // A collection (TTC) answers `create` with its list of fonts rather than a font.
275
+ return typeof font.glyphForCodePoint === 'function' ? font : null;
276
+ }
277
+ catch {
278
+ return null;
279
+ }
280
+ }
281
+ // ── CSS sources and the network ─────────────────────────────────────────────
282
+ /** `url(...)` entries of a `src` descriptor in a format fontkit reads, in order; `local()` is skipped. */
283
+ function readableUrls(src) {
284
+ const entry = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\)(?:\s*format\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\))?/gi;
285
+ const urls = [];
286
+ for (const match of src.matchAll(entry)) {
287
+ const url = match[1] ?? match[2] ?? match[3] ?? '';
288
+ const format = (match[4] ?? match[5] ?? match[6])?.toLowerCase().replace(/-variations$/, '');
289
+ const readable = format
290
+ ? ['woff2', 'woff', 'truetype', 'opentype'].includes(format)
291
+ : !/\.(eot|svg)(?:[?#]|$)/i.test(url);
292
+ if (url && readable)
293
+ urls.push(url);
294
+ }
295
+ return urls;
296
+ }
297
+ /** The family without the quotes CSS allows around it. */
298
+ function bareFamily(family) {
299
+ return family.trim().replace(/^(['"])(.*)\1$/, '$2');
300
+ }
301
+ async function fetchOverHttp(url) {
302
+ const response = await fetch(url);
303
+ return response.ok ? new Uint8Array(await response.arrayBuffer()) : null;
304
+ }
305
+ /**
306
+ * The `@font-face` rules of every style sheet of the document, imports and grouping rules
307
+ * included. The default of `FontSourceDeps.cssRules`; exported for its own test.
308
+ */
309
+ export function* documentFontFaces() {
310
+ if (typeof document === 'undefined')
311
+ return;
312
+ for (const sheet of Array.from(document.styleSheets))
313
+ yield* fontFacesIn(sheet);
314
+ }
315
+ function* fontFacesIn(container) {
316
+ let rules;
317
+ try {
318
+ rules = container.cssRules;
319
+ }
320
+ catch {
321
+ return; // a cross-origin sheet without CORS hides its rules
322
+ }
323
+ for (const rule of Array.from(rules)) {
324
+ if (rule instanceof CSSFontFaceRule)
325
+ yield rule;
326
+ else if (rule instanceof CSSImportRule) {
327
+ if (rule.styleSheet)
328
+ yield* fontFacesIn(rule.styleSheet);
329
+ }
330
+ else if (rule instanceof CSSGroupingRule)
331
+ yield* fontFacesIn(rule);
332
+ }
333
+ }