@ggraphic/editor 0.0.0 → 0.1.0-alpha.1

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 (136) hide show
  1. package/README.md +16 -3
  2. package/THIRD_PARTY_NOTICES +25 -1
  3. package/dist/brand/brandRegistry.d.ts +11 -3
  4. package/dist/brand/brandRegistry.js +18 -3
  5. package/dist/brand/documentBrand.d.ts +16 -0
  6. package/dist/brand/documentBrand.js +6 -0
  7. package/dist/components/CanvasContextMenu/CanvasActionSheet.js +2 -1
  8. package/dist/components/CanvasContextMenu/CanvasContextMenu.js +3 -2
  9. package/dist/components/CanvasEditor/CanvasEditorShell.js +43 -34
  10. package/dist/components/CanvasTextOverlay.js +14 -5
  11. package/dist/components/CustomColorSwatch.js +3 -2
  12. package/dist/components/GenericCanvas.js +21 -5
  13. package/dist/components/RichTextField.js +6 -1
  14. package/dist/components/SelectionPill.js +2 -1
  15. package/dist/components/TextFormatButtons.js +12 -23
  16. package/dist/components/TopBar/ContextControls.js +4 -2
  17. package/dist/components/TopBar/modules/FloatingColorPicker.js +3 -1
  18. package/dist/components/TopBar/modules/FloatingFontRoleControl.js +2 -2
  19. package/dist/components/kindRenderers.d.ts +1 -1
  20. package/dist/components/markerMark.d.ts +6 -1
  21. package/dist/components/markerMark.js +7 -11
  22. package/dist/configs/factory/actionFactories.d.ts +38 -9
  23. package/dist/configs/factory/actionFactories.js +53 -36
  24. package/dist/configs/types.d.ts +13 -2
  25. package/dist/export/pptx/buildPptxModel.d.ts +3 -0
  26. package/dist/export/pptx/buildPptxModel.js +5 -5
  27. package/dist/export/pptx/exportPptxDeck.d.ts +4 -1
  28. package/dist/export/pptx/exportPptxDeck.js +5 -2
  29. package/dist/export/pptx/textModel.d.ts +6 -2
  30. package/dist/export/pptx/textModel.js +14 -11
  31. package/dist/hooks/useFloatingModuleHandlers.js +2 -2
  32. package/dist/hooks/useMultiPageExport.js +1 -1
  33. package/dist/i18n/de.d.ts +14 -0
  34. package/dist/i18n/de.js +14 -0
  35. package/dist/i18n/en.js +12 -0
  36. package/dist/page/actions.d.ts +66 -0
  37. package/dist/page/actions.js +353 -0
  38. package/dist/page/config.d.ts +15 -0
  39. package/dist/page/config.js +91 -0
  40. package/dist/page/fitting.d.ts +6 -0
  41. package/dist/page/fitting.js +26 -0
  42. package/dist/page/hug.d.ts +10 -0
  43. package/dist/page/hug.js +18 -0
  44. package/dist/page/instantiate.d.ts +8 -0
  45. package/dist/page/instantiate.js +30 -0
  46. package/dist/page/logoSize.d.ts +8 -0
  47. package/dist/page/logoSize.js +29 -0
  48. package/dist/page/pageState.d.ts +41 -0
  49. package/dist/page/pageState.js +59 -0
  50. package/dist/page/seeds.d.ts +14 -0
  51. package/dist/page/seeds.js +40 -0
  52. package/dist/page/slotBudgets.d.ts +22 -0
  53. package/dist/page/slotBudgets.js +18 -0
  54. package/dist/page/templatePack.d.ts +31 -0
  55. package/dist/page/templatePack.js +55 -0
  56. package/dist/page/typography.d.ts +11 -0
  57. package/dist/page/typography.js +13 -0
  58. package/dist/primitives/CanvasRichText.js +7 -4
  59. package/dist/primitives/CanvasStage.js +3 -2
  60. package/dist/primitives/UserImagePrimitive.js +3 -1
  61. package/dist/sidebar/sections/ChartSettingsSection.d.ts +1 -1
  62. package/dist/sidebar/sections/ChartSettingsSection.js +5 -2
  63. package/dist/sidebar/sections/CombinedTextSection.js +4 -3
  64. package/dist/sidebar/sections/DiagrammeSection.js +10 -11
  65. package/dist/sidebar/sections/FormenSection.d.ts +3 -1
  66. package/dist/sidebar/sections/FormenSection.js +25 -13
  67. package/dist/sidebar/sections/GenericShareSection.js +3 -2
  68. package/dist/sidebar/sections/IllustrationSettings.js +4 -3
  69. package/dist/sidebar/sections/ImageAdjustSection.js +6 -5
  70. package/dist/sidebar/sections/assets/ElementThumb.js +3 -1
  71. package/dist/sidebar/sections/assets/useElementCatalog.d.ts +2 -1
  72. package/dist/sidebar/sections/assets/useElementCatalog.js +30 -15
  73. package/dist/sidebar/sections/effects/GradientSettings.js +4 -2
  74. package/dist/sidebar/sections/effects/OutlineSettings.js +4 -3
  75. package/dist/sidebar/sections/effects/ShadowSettings.js +4 -3
  76. package/dist/sidebar/sections/tools/BlobCreatorTool.js +11 -6
  77. package/dist/sidebar/sections/tools/GradientTextTool.js +14 -12
  78. package/dist/sidebar/sections/tools/TextPathCreatorTool.js +15 -13
  79. package/dist/sidebar/sections/tools/ToolsSection.js +5 -3
  80. package/dist/styles/compiled.css +2 -0
  81. package/dist/testing/documentBrandConfig.d.ts +14 -0
  82. package/dist/testing/documentBrandConfig.js +60 -0
  83. package/dist/testing/documentBrandPacks.d.ts +10 -0
  84. package/dist/testing/documentBrandPacks.js +45 -0
  85. package/dist/ui/alert-dialog.js +3 -2
  86. package/dist/ui/button.d.ts +2 -2
  87. package/dist/ui/dialog.js +3 -2
  88. package/dist/ui/editorScope.d.ts +10 -0
  89. package/dist/ui/editorScope.js +9 -0
  90. package/dist/ui/popover.js +2 -1
  91. package/dist/ui/select.js +2 -1
  92. package/dist/utils/canvasAssets.d.ts +7 -1
  93. package/dist/utils/canvasLayerManager.d.ts +14 -0
  94. package/dist/utils/canvasLayerManager.js +24 -0
  95. package/dist/utils/circleBadgeUtils.d.ts +3 -1
  96. package/dist/utils/circleBadgeUtils.js +5 -5
  97. package/dist/utils/colorNames.d.ts +7 -2
  98. package/dist/utils/colorNames.js +14 -5
  99. package/dist/utils/fontMarkSupport.d.ts +11 -0
  100. package/dist/utils/fontMarkSupport.js +27 -5
  101. package/dist/utils/frameUtils.d.ts +3 -2
  102. package/dist/utils/frameUtils.js +3 -2
  103. package/dist/utils/illustrations/registry.d.ts +4 -1
  104. package/dist/utils/illustrations/registry.js +5 -3
  105. package/dist/utils/illustrations/svgCache.js +13 -6
  106. package/dist/utils/illustrations/types.d.ts +1 -1
  107. package/dist/utils/imageFilters.d.ts +4 -2
  108. package/dist/utils/imageFilters.js +3 -2
  109. package/dist/utils/imageLook.d.ts +4 -2
  110. package/dist/utils/imageLook.js +4 -2
  111. package/dist/utils/layerLabels.js +3 -6
  112. package/dist/utils/markerBoxes.d.ts +16 -1
  113. package/dist/utils/markerBoxes.js +2 -15
  114. package/dist/utils/markerColors.d.ts +12 -5
  115. package/dist/utils/markerColors.js +8 -15
  116. package/dist/utils/photoPlaceholder.d.ts +4 -1
  117. package/dist/utils/photoPlaceholder.js +5 -3
  118. package/dist/utils/pillBadgeUtils.d.ts +3 -2
  119. package/dist/utils/pillBadgeUtils.js +5 -5
  120. package/dist/utils/shapes.d.ts +4 -2
  121. package/dist/utils/shapes.js +4 -2
  122. package/dist/utils/textUtils.js +2 -10
  123. package/dist/utils/zipPageImages.d.ts +2 -1
  124. package/dist/utils/zipPageImages.js +3 -2
  125. package/package.json +14 -7
  126. package/skills/ggraphic-embed/SKILL.md +145 -0
  127. package/dist/components/MobileSelectionPill.d.ts +0 -40
  128. package/dist/components/MobileSelectionPill.js +0 -85
  129. package/dist/components/TopBar/modules/FloatingGradientControl.d.ts +0 -9
  130. package/dist/components/TopBar/modules/FloatingGradientControl.js +0 -35
  131. package/dist/components/TopBar/modules/FloatingOutlineControl.d.ts +0 -11
  132. package/dist/components/TopBar/modules/FloatingOutlineControl.js +0 -31
  133. package/dist/components/TopBar/modules/FloatingShadowControl.d.ts +0 -12
  134. package/dist/components/TopBar/modules/FloatingShadowControl.js +0 -40
  135. package/dist/utils/balkenUtils.d.ts +0 -22
  136. package/dist/utils/balkenUtils.js +0 -8
@@ -65,8 +65,11 @@ export async function loadPptxImage(src) {
65
65
  return null;
66
66
  }
67
67
  }
68
- export async function exportPptxDeck({ pages, format, rasterizeElement, title, onProgress, }) {
69
- const model = buildPptxModel(pages, format, { measure: measureTextWidthWithFont });
68
+ export async function exportPptxDeck({ pages, format, rasterizeElement, title, brand, onProgress, }) {
69
+ const model = buildPptxModel(pages, format, {
70
+ measure: measureTextWidthWithFont,
71
+ ...(brand ? { brand } : {}),
72
+ });
70
73
  const { blob } = await writePptx(model, {
71
74
  rasterize: (request, slideIndex) => rasterizeElement(slideIndex, request.elementId),
72
75
  loadImage: loadPptxImage,
@@ -1,11 +1,15 @@
1
+ import { type BrandPack } from '@ggraphic/core';
1
2
  import type { PptxParagraph } from './types.js';
2
3
  import type { AdditionalText } from '@ggraphic/editor/configs/types';
3
4
  /** Breite eines Textstücks in px; im Browser die echte Messung (`defaultMeasure`). */
4
5
  export type PptxMeasureText = (text: string, fontSize: number, fontFamily: string, fontStyle: string) => number;
5
6
  /** Ohne Messung: halbe Schriftgröße je Zeichen, wie der Rückfall in `measureTextWidthWithFont`. */
6
7
  export declare const estimateMeasure: PptxMeasureText;
7
- /** Markdown-lite des Textfelds → Absätze mit Läufen und Aufzählung. */
8
- export declare function textParagraphs(text: AdditionalText): PptxParagraph[];
8
+ /**
9
+ * Markdown-lite des Textfelds → Absätze mit Läufen und Aufzählung. `brand`:
10
+ * das Paket des Dokuments, für Marker ohne Stil der Vorlage; Vorgabe: das aktive.
11
+ */
12
+ export declare function textParagraphs(text: AdditionalText, brand?: BrandPack): PptxParagraph[];
9
13
  /**
10
14
  * Wie viele Zeilen der Text bei `width` umbricht — für die Höhe der Box, die
11
15
  * PowerPoint als Drehmitte braucht. Wortweise, wie Konva `wrap="word"`.
@@ -1,4 +1,3 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
1
  import { defaultTextMarker, markerInkOn } from '@ggraphic/editor/utils/markerColors';
3
2
  import { markdownLiteToRichText } from '@ggraphic/schema';
4
3
  /** Ohne Messung: halbe Schriftgröße je Zeichen, wie der Rückfall in `measureTextWidthWithFont`. */
@@ -10,9 +9,10 @@ function markColor(node, type) {
10
9
  /**
11
10
  * Ein Lauf, wie `CanvasRichText` ihn zeichnet: eine eigene Passagenfarbe färbt
12
11
  * nur, die Akzentschrift der Vorlage gilt für Akzentläufe ohne eigene Farbe;
13
- * im Markerkasten steht die Schrift, die zum Kasten passt.
12
+ * im Markerkasten steht die Schrift, die zum Kasten passt — Kasten und Schrift
13
+ * der Marke des Dokuments, wenn die Vorlage keinen Markerstil hat.
14
14
  */
15
- function toRun(node, text, baseBold, baseItalic) {
15
+ function toRun(node, text, baseBold, baseItalic, brand) {
16
16
  const has = (type) => !!node.marks?.some((mark) => mark.type === type);
17
17
  const accentColor = has('accent') ? markColor(node, 'accent') : null;
18
18
  const asAccent = has('accent') && !!text.accent && !accentColor;
@@ -22,10 +22,10 @@ function toRun(node, text, baseBold, baseItalic) {
22
22
  let color = accentColor ?? (asAccent ? text.accent.fill : text.fill);
23
23
  let highlight = null;
24
24
  if (has('marker')) {
25
- const marker = text.marker ?? defaultTextMarker();
25
+ const marker = text.marker ?? defaultTextMarker(brand);
26
26
  const markerColor = markColor(node, 'marker');
27
27
  highlight = markerColor ?? marker.fill;
28
- color = accentColor ?? (markerColor ? markerInkOn(markerColor) : marker.color);
28
+ color = accentColor ?? (markerColor ? markerInkOn(markerColor, brand) : marker.color);
29
29
  }
30
30
  const run = {
31
31
  text: node.text ?? '',
@@ -38,11 +38,11 @@ function toRun(node, text, baseBold, baseItalic) {
38
38
  };
39
39
  return run;
40
40
  }
41
- function paragraphOf(node, bullet, text, baseBold, baseItalic) {
41
+ function paragraphOf(node, bullet, text, baseBold, baseItalic, brand) {
42
42
  const runs = [];
43
43
  for (const child of node?.content ?? []) {
44
44
  if (child.type === 'text')
45
- runs.push(toRun(child, text, baseBold, baseItalic));
45
+ runs.push(toRun(child, text, baseBold, baseItalic, brand));
46
46
  else if (child.type === 'hardBreak')
47
47
  runs.push({ ...emptyRun(text), text: '\n' });
48
48
  }
@@ -59,8 +59,11 @@ function emptyRun(text) {
59
59
  fontFace: null,
60
60
  };
61
61
  }
62
- /** Markdown-lite des Textfelds → Absätze mit Läufen und Aufzählung. */
63
- export function textParagraphs(text) {
62
+ /**
63
+ * Markdown-lite des Textfelds → Absätze mit Läufen und Aufzählung. `brand`:
64
+ * das Paket des Dokuments, für Marker ohne Stil der Vorlage; Vorgabe: das aktive.
65
+ */
66
+ export function textParagraphs(text, brand) {
64
67
  const style = text.fontStyle ?? 'normal';
65
68
  // A numeric weight replaces the bold part of the style; PowerPoint knows only bold or not.
66
69
  const baseBold = text.fontWeight !== undefined ? text.fontWeight >= 600 : style.includes('bold');
@@ -72,11 +75,11 @@ export function textParagraphs(text) {
72
75
  const start = typeof block.attrs?.start === 'number' ? block.attrs.start : 1;
73
76
  const bullet = block.type === 'orderedList' ? { type: 'number', startAt: start } : { type: 'bullet' };
74
77
  for (const item of block.content ?? []) {
75
- paragraphs.push(paragraphOf(item.content?.[0] ?? null, bullet, text, baseBold, baseItalic));
78
+ paragraphs.push(paragraphOf(item.content?.[0] ?? null, bullet, text, baseBold, baseItalic, brand));
76
79
  }
77
80
  continue;
78
81
  }
79
- paragraphs.push(paragraphOf(block, null, text, baseBold, baseItalic));
82
+ paragraphs.push(paragraphOf(block, null, text, baseBold, baseItalic, brand));
80
83
  }
81
84
  return paragraphs;
82
85
  }
@@ -233,8 +233,8 @@ export function useFloatingModuleHandlers(options) {
233
233
  const img = state.userImageInstances?.find((u) => u.id === id);
234
234
  if (!img)
235
235
  return;
236
- actions.updateUserImage?.(id, imageLookPatch(look, img, typeof state.brandScheme === 'string' ? state.brandScheme : null));
237
- }, [actions, state]);
236
+ actions.updateUserImage?.(id, imageLookPatch(look, img, typeof state.brandScheme === 'string' ? state.brandScheme : null, config.brand));
237
+ }, [actions, state, config.brand]);
238
238
  const handleGradientSelect = useCallback((gradient) => {
239
239
  if (!activeFloatingModule)
240
240
  return;
@@ -84,7 +84,7 @@ export function useMultiPageExport({ canvasRefs, canvasType, }) {
84
84
  try {
85
85
  for (let i = 0; i < images.length; i++) {
86
86
  setNotice(messages().export.sending(i + 1, images.length));
87
- await fileDelivery.downloadDataUrl(images[i], `${prefix}-${canvasType}-page-${i + 1}.${format === 'jpeg' ? 'jpg' : format}`);
87
+ await fileDelivery.downloadDataUrl(images[i], `${prefix}-${canvasType}-${messages().export.pageFile}-${i + 1}.${format === 'jpeg' ? 'jpg' : format}`);
88
88
  sent = i + 1;
89
89
  }
90
90
  }
package/dist/i18n/de.d.ts CHANGED
@@ -139,6 +139,7 @@ export declare const de: {
139
139
  textFormat: {
140
140
  toolbar: string;
141
141
  bold: string;
142
+ boldNeedsItalicCut: string;
142
143
  italic: string;
143
144
  underline: string;
144
145
  accent: string;
@@ -179,6 +180,8 @@ export declare const de: {
179
180
  sending: (i: number, total: number) => string;
180
181
  partlySent: (sent: number) => string;
181
182
  allSent: string;
183
+ /** The word in an exported page's file name: `<name>-seite-2.png`. */
184
+ pageFile: string;
182
185
  };
183
186
  formats: {
184
187
  names: Record<string, string>;
@@ -774,6 +777,17 @@ export declare const de: {
774
777
  impressumSubmit: string;
775
778
  };
776
779
  };
780
+ /** The tabs of a free page (`createPageConfig`). */
781
+ pageTabs: {
782
+ text: string;
783
+ textAriaLabel: string;
784
+ elements: string;
785
+ elementsAriaLabel: string;
786
+ uploads: string;
787
+ uploadsAriaLabel: string;
788
+ tools: string;
789
+ toolsAriaLabel: string;
790
+ };
777
791
  topBar: {
778
792
  cropAction: string;
779
793
  aiTemplate: string;
package/dist/i18n/de.js CHANGED
@@ -140,6 +140,7 @@ export const de = {
140
140
  textFormat: {
141
141
  toolbar: 'Textformatierung',
142
142
  bold: 'Fett (⌘B)',
143
+ boldNeedsItalicCut: 'Fett – diese Schrift hat keinen fett-kursiven Schnitt',
143
144
  italic: 'Kursiv (⌘I)',
144
145
  underline: 'Unterstrichen (⌘U)',
145
146
  accent: 'Akzent',
@@ -180,6 +181,8 @@ export const de = {
180
181
  sending: (i, total) => `Seite ${i} von ${total} wird gesendet …`,
181
182
  partlySent: (sent) => `${sent === 1 ? 'Seite 1 wurde' : `Die Seiten 1 bis ${sent} wurden`} einzeln gesendet, Seite ${sent + 1} nicht.`,
182
183
  allSent: 'Die Seiten wurden einzeln gesendet.',
184
+ /** The word in an exported page's file name: `<name>-seite-2.png`. */
185
+ pageFile: 'seite',
183
186
  },
184
187
  formats: {
185
188
  names: {
@@ -839,6 +842,17 @@ export const de = {
839
842
  impressumSubmit: 'Übernehmen',
840
843
  },
841
844
  },
845
+ /** The tabs of a free page (`createPageConfig`). */
846
+ pageTabs: {
847
+ text: 'Text',
848
+ textAriaLabel: 'Text: Text hinzufügen und bearbeiten',
849
+ elements: 'Elemente',
850
+ elementsAriaLabel: 'Elemente: Formen, Icons, Illustrationen und Emoji',
851
+ uploads: 'Uploads',
852
+ uploadsAriaLabel: 'Uploads: deine eigenen Bilder',
853
+ tools: 'Werkzeuge',
854
+ toolsAriaLabel: 'Werkzeuge: QR-Code, Blob, Verlaufstext und Text auf einem Pfad',
855
+ },
842
856
  topBar: {
843
857
  cropAction: 'Zuschneiden',
844
858
  aiTemplate: 'Vorlage',
package/dist/i18n/en.js CHANGED
@@ -129,6 +129,7 @@ export const en = {
129
129
  textFormat: {
130
130
  toolbar: 'Text formatting',
131
131
  bold: 'Bold (⌘B)',
132
+ boldNeedsItalicCut: 'Bold – this font has no bold italic cut',
132
133
  italic: 'Italic (⌘I)',
133
134
  underline: 'Underline (⌘U)',
134
135
  accent: 'Accent',
@@ -169,6 +170,7 @@ export const en = {
169
170
  sending: (i, total) => `Sending page ${i} of ${total} …`,
170
171
  partlySent: (sent) => `${sent === 1 ? 'Page 1 was' : `Pages 1 to ${sent} were`} sent individually, page ${sent + 1} was not.`,
171
172
  allSent: 'The pages were sent individually.',
173
+ pageFile: 'page',
172
174
  },
173
175
  formats: {
174
176
  names: {
@@ -828,6 +830,16 @@ export const en = {
828
830
  impressumSubmit: 'Apply',
829
831
  },
830
832
  },
833
+ pageTabs: {
834
+ text: 'Text',
835
+ textAriaLabel: 'Text: add and edit text',
836
+ elements: 'Elements',
837
+ elementsAriaLabel: 'Elements: shapes, icons, illustrations and emoji',
838
+ uploads: 'Uploads',
839
+ uploadsAriaLabel: 'Uploads: your own images',
840
+ tools: 'Tools',
841
+ toolsAriaLabel: 'Tools: QR code, blob, gradient text and text on a path',
842
+ },
831
843
  topBar: {
832
844
  cropAction: 'Crop',
833
845
  aiTemplate: 'Template',
@@ -0,0 +1,66 @@
1
+ /**
2
+ * What a free page can do with its elements: texts, shapes, icons, emoji,
3
+ * illustrations, placed images and the background colour. The editor calls these by name
4
+ * (`OptionalCanvasActions`): the canvas for moves and edits, the sidebar
5
+ * sections for adding, the delete key for removing (`utils/elementKinds.ts`).
6
+ *
7
+ * Every action is one user intent and records one history entry.
8
+ */
9
+ import { type BindingRef, type FontRole } from '@ggraphic/core';
10
+ import { type LiftedBlock } from '@ggraphic/editor/blocks/liftedBlock';
11
+ import { type IconState } from '@ggraphic/editor/configs/factory/baseTypes';
12
+ import { type AdditionalText } from '@ggraphic/editor/configs/types';
13
+ import { type TextPreview } from '@ggraphic/editor/hooks/useCanvasElementHandlers';
14
+ import { type AssetInstance } from '@ggraphic/editor/utils/canvasAssets';
15
+ import { type ExternalIconPayload } from '@ggraphic/editor/utils/externalIcons';
16
+ import { type IllustrationInstance } from '@ggraphic/editor/utils/illustrations/types';
17
+ import { type ShapeInstance, type ShapeType } from '@ggraphic/editor/utils/shapes';
18
+ import { type ElementPlacement, type UserImageInstance, type UserImagePlacement } from '@ggraphic/editor/utils/userImageUtils';
19
+ import { type PageState } from './pageState.js';
20
+ import { type TemplateLookup } from './slotBudgets.js';
21
+ type SetState = (partial: Partial<PageState> | ((prev: PageState) => PageState)) => void;
22
+ type SaveHistory = (state?: PageState) => void;
23
+ /**
24
+ * The actions of a `width` × `height` page. `templateOf` is the host's catalogue: a text on a page
25
+ * made from one of its templates fits within the line limit of its slot.
26
+ */
27
+ export declare function createPageActions(getState: () => PageState, setState: SetState, saveToHistory: SaveHistory, debouncedSaveToHistory: SaveHistory, width: number, height: number, templateOf?: TemplateLookup): {
28
+ addHeader: () => void;
29
+ addSubheader: () => void;
30
+ addText: () => void;
31
+ addBodyTextWithContent: (content: string) => void;
32
+ updateAdditionalText: (id: string, partial: Partial<AdditionalText>) => void;
33
+ /**
34
+ * Sets the font of a free text to a brand role (`fontRoleOptions`): the family and the binding
35
+ * to the role are written together, so the text keeps following the role when the brand changes
36
+ * (a family set without the binding would lose it on the next rebind). One history step; the
37
+ * size is refitted to the new font and the plates that hug the text follow.
38
+ */
39
+ setAdditionalTextFontRole: (id: string, role: FontRole) => void;
40
+ /**
41
+ * How the page will look once a text edit is committed, while it is still being typed: the
42
+ * size the draft fits at and the plates that hug it. A function of the committed page that
43
+ * changes and records nothing; the canvas draws the result over the page until the edit ends,
44
+ * and the commit (`updateAdditionalText`) is what writes. Null for a text that is gone.
45
+ */
46
+ previewAdditionalText: (id: string, draft: string) => TextPreview | null;
47
+ removeAdditionalText: (id: string) => void;
48
+ addShape: (type: ShapeType, color?: string, options?: ElementPlacement) => void;
49
+ updateShape: (id: string, partial: Partial<ShapeInstance>) => void;
50
+ removeShape: (id: string) => void;
51
+ toggleIcon: (id: string, selected: boolean, options?: ElementPlacement, external?: ExternalIconPayload) => void;
52
+ updateIcon: (id: string, partial: Partial<IconState>) => void;
53
+ addAsset: (assetId: string, options?: ElementPlacement) => void;
54
+ updateAsset: (id: string, partial: Partial<AssetInstance>) => void;
55
+ removeAsset: (id: string) => void;
56
+ addIllustration: (id: string, options?: ElementPlacement) => void;
57
+ updateIllustration: (id: string, partial: Partial<IllustrationInstance>) => void;
58
+ removeIllustration: (id: string) => void;
59
+ addUserImageFromUrl: (url: string, fileName: string, options?: UserImagePlacement) => void;
60
+ updateUserImage: (id: string, partial: Partial<UserImageInstance>) => void;
61
+ removeUserImage: (id: string) => void;
62
+ insertBlock: (block: LiftedBlock) => void;
63
+ setBackgroundColor: (color: string, ref?: BindingRef) => void;
64
+ };
65
+ export type PageActions = ReturnType<typeof createPageActions>;
66
+ export {};
@@ -0,0 +1,353 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ /**
3
+ * What a free page can do with its elements: texts, shapes, icons, emoji,
4
+ * illustrations, placed images and the background colour. The editor calls these by name
5
+ * (`OptionalCanvasActions`): the canvas for moves and edits, the sidebar
6
+ * sections for adding, the delete key for removing (`utils/elementKinds.ts`).
7
+ *
8
+ * Every action is one user intent and records one history entry.
9
+ */
10
+ import { resolveRef, withBinding, withoutBinding, } from '@ggraphic/core';
11
+ import { activeBrand } from '@ggraphic/editor/brand/brandRegistry';
12
+ import { blockElementIds } from '@ggraphic/editor/blocks/liftedBlock';
13
+ import { createAssetInstance } from '@ggraphic/editor/utils/canvasAssets';
14
+ import { createInstanceId } from '@ggraphic/editor/utils/duplicateElement';
15
+ import { iconInstanceIdsFor, placedIconId } from '@ggraphic/editor/utils/iconInstances';
16
+ import { createIllustration } from '@ggraphic/editor/utils/illustrations/registry';
17
+ import { createShape } from '@ggraphic/editor/utils/shapes';
18
+ import { createUserImageInstanceFromUrl, } from '@ggraphic/editor/utils/userImageUtils';
19
+ import { fittedFontSize } from './fitting.js';
20
+ import { withHuggedPlates } from './hug.js';
21
+ import { noTemplates } from './slotBudgets.js';
22
+ import { headlineFont, bodyFont, fontStackFor, scaleFor } from './typography.js';
23
+ let idCounter = 0;
24
+ const newId = (prefix) => `${prefix}-${Date.now().toString(36)}-${(idCounter++).toString(36)}`;
25
+ const withLayer = (order, id) => [...(order ?? []), id];
26
+ const withoutLayer = (order, id) => (order ?? []).filter((entry) => entry !== id);
27
+ /** The shape fields a person sets by moving or resizing it on the canvas. */
28
+ const HAND_GEOMETRY = ['x', 'y', 'width', 'height'];
29
+ /** A readable ink on the page's current background. */
30
+ function inkFor(background) {
31
+ const match = activeBrand().backgrounds.find((b) => b.color.toLowerCase() === background.toLowerCase());
32
+ if (match)
33
+ return match.ink;
34
+ const hex = background.replace('#', '');
35
+ if (hex.length !== 6)
36
+ return activeBrand().colors.textOnDark;
37
+ const [r, g, b] = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
38
+ const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
39
+ return luminance > 0.5 ? activeBrand().colors.textOnLight : activeBrand().colors.textOnDark;
40
+ }
41
+ /** `role` is the brand font the preset's family stands for: a new text follows it from the start. */
42
+ const TEXT_PRESETS = {
43
+ header: {
44
+ text: 'Headline',
45
+ size: 88,
46
+ font: headlineFont,
47
+ role: 'headline',
48
+ style: 'bold',
49
+ },
50
+ subheader: {
51
+ text: 'Subheading',
52
+ size: 52,
53
+ font: headlineFont,
54
+ role: 'headline',
55
+ style: 'normal',
56
+ },
57
+ body: {
58
+ text: 'Your text here',
59
+ size: 36,
60
+ font: bodyFont,
61
+ role: 'body',
62
+ style: 'normal',
63
+ },
64
+ };
65
+ /**
66
+ * The actions of a `width` × `height` page. `templateOf` is the host's catalogue: a text on a page
67
+ * made from one of its templates fits within the line limit of its slot.
68
+ */
69
+ export function createPageActions(getState, setState, saveToHistory, debouncedSaveToHistory, width, height, templateOf = noTemplates) {
70
+ const s = scaleFor(width, height);
71
+ /** Applies `change` and records it, immediately or coalesced with its neighbours. */
72
+ const commit = (change, debounced = false) => {
73
+ setState(change);
74
+ (debounced ? debouncedSaveToHistory : saveToHistory)(change(getState()));
75
+ };
76
+ const addText = (type, content) => {
77
+ const preset = TEXT_PRESETS[type];
78
+ const textWidth = Math.round(width * 0.7);
79
+ const text = {
80
+ id: newId('text'),
81
+ text: content ?? preset.text,
82
+ type,
83
+ x: Math.round((width - textWidth) / 2),
84
+ y: Math.round(height * (type === 'header' ? 0.3 : type === 'subheader' ? 0.42 : 0.52)),
85
+ width: textWidth,
86
+ fontSize: Math.round(preset.size * s),
87
+ fontFamily: preset.font(),
88
+ bind: withBinding(undefined, 'fontFamily', {
89
+ ref: `font.${preset.role}`,
90
+ value: activeBrand().fonts[preset.role],
91
+ }),
92
+ fontStyle: preset.style,
93
+ fill: inkFor(getState().backgroundColor),
94
+ align: 'center',
95
+ lineHeight: type === 'body' ? 1.3 : activeBrand().lineHeightFactor,
96
+ };
97
+ commit((prev) => ({
98
+ ...prev,
99
+ additionalTexts: [...prev.additionalTexts, text],
100
+ layerOrder: withLayer(prev.layerOrder, text.id),
101
+ }));
102
+ };
103
+ /**
104
+ * A text with a prototype size (`maxFontSize`) at the size it fits at on `page`, which a new
105
+ * text, a new font or a new brand font changes; any other text, or one that already fits, as it is.
106
+ */
107
+ const refitted = (text, page) => {
108
+ const fitted = fittedFontSize(text, page, height, templateOf);
109
+ return fitted === null || fitted === text.fontSize ? text : { ...text, fontSize: fitted };
110
+ };
111
+ return {
112
+ // ── Texts ────────────────────────────────────────────────────────────────
113
+ addHeader: () => addText('header'),
114
+ addSubheader: () => addText('subheader'),
115
+ addText: () => addText('body'),
116
+ addBodyTextWithContent: (content) => addText('body', content),
117
+ updateAdditionalText: (id, partial) => commit((prev) =>
118
+ // The plates that hug a text follow its new lines, width or size.
119
+ withHuggedPlates({
120
+ ...prev,
121
+ additionalTexts: prev.additionalTexts.map((t) => {
122
+ if (t.id !== id)
123
+ return t;
124
+ const next = { ...t, ...partial };
125
+ // A committed text change refits a text with a prototype size: shrink as it grows,
126
+ // grow back as it shrinks. A size set by hand in the same change stands.
127
+ if (!('text' in partial) || 'fontSize' in partial)
128
+ return next;
129
+ return refitted(next, prev);
130
+ }),
131
+ }), true),
132
+ /**
133
+ * Sets the font of a free text to a brand role (`fontRoleOptions`): the family and the binding
134
+ * to the role are written together, so the text keeps following the role when the brand changes
135
+ * (a family set without the binding would lose it on the next rebind). One history step; the
136
+ * size is refitted to the new font and the plates that hug the text follow.
137
+ */
138
+ setAdditionalTextFontRole: (id, role) => {
139
+ const ref = `font.${role}`;
140
+ const family = resolveRef(ref, activeBrand(), null);
141
+ if (family === null || !getState().additionalTexts.some((t) => t.id === id))
142
+ return;
143
+ commit((prev) => withHuggedPlates({
144
+ ...prev,
145
+ additionalTexts: prev.additionalTexts.map((t) => t.id === id
146
+ ? refitted({
147
+ ...t,
148
+ fontFamily: fontStackFor(role, family),
149
+ bind: withBinding(t.bind, 'fontFamily', { ref, value: family }),
150
+ }, prev)
151
+ : t),
152
+ }));
153
+ },
154
+ /**
155
+ * How the page will look once a text edit is committed, while it is still being typed: the
156
+ * size the draft fits at and the plates that hug it. A function of the committed page that
157
+ * changes and records nothing; the canvas draws the result over the page until the edit ends,
158
+ * and the commit (`updateAdditionalText`) is what writes. Null for a text that is gone.
159
+ */
160
+ previewAdditionalText: (id, draft) => {
161
+ const prev = getState();
162
+ const current = prev.additionalTexts.find((t) => t.id === id);
163
+ if (!current)
164
+ return null;
165
+ const fitted = fittedFontSize({ ...current, text: draft }, prev, height, templateOf);
166
+ const fontSize = fitted ?? current.fontSize;
167
+ // The text itself stays as it was: the editor shows the draft, the commit writes it.
168
+ const additionalTexts = prev.additionalTexts.map((t) => t.id === id ? { ...t, fontSize } : t);
169
+ const hugged = withHuggedPlates({
170
+ ...prev,
171
+ additionalTexts: prev.additionalTexts.map((t) => t.id === id ? { ...t, text: draft, fontSize } : t),
172
+ });
173
+ return {
174
+ fontSize: fitted,
175
+ overrides: { additionalTexts, shapeInstances: hugged.shapeInstances },
176
+ };
177
+ },
178
+ removeAdditionalText: (id) => commit((prev) => ({
179
+ ...prev,
180
+ additionalTexts: prev.additionalTexts.filter((t) => t.id !== id),
181
+ layerOrder: withoutLayer(prev.layerOrder, id),
182
+ })),
183
+ // ── Shapes ───────────────────────────────────────────────────────────────
184
+ addShape: (type, color, options) => {
185
+ const center = options?.center ?? { x: width / 2, y: height / 2 };
186
+ const shape = createShape(type, center.x, center.y, activeBrand().colors.secondary, color);
187
+ const placed = { ...shape, id: newId('shape') };
188
+ commit((prev) => ({
189
+ ...prev,
190
+ shapeInstances: [...prev.shapeInstances, placed],
191
+ layerOrder: withLayer(prev.layerOrder, placed.id),
192
+ }));
193
+ },
194
+ updateShape: (id, partial) => commit((prev) => ({
195
+ ...prev,
196
+ shapeInstances: prev.shapeInstances.map((x) => {
197
+ if (x.id !== id)
198
+ return x;
199
+ const next = { ...x, ...partial };
200
+ // A plate placed or sized by hand stops hugging its text; otherwise the next text
201
+ // edit, rebind or AI fill would snap it back.
202
+ if (!('hug' in next) || !HAND_GEOMETRY.some((k) => k in partial))
203
+ return next;
204
+ const { hug: _hug, ...free } = next;
205
+ return free;
206
+ }),
207
+ }), true),
208
+ removeShape: (id) => commit((prev) => ({
209
+ ...prev,
210
+ shapeInstances: prev.shapeInstances.filter((x) => x.id !== id),
211
+ layerOrder: withoutLayer(prev.layerOrder, id),
212
+ })),
213
+ // ── Icons ────────────────────────────────────────────────────────────────
214
+ // `selectedIcons` lists instance ids; the first copy of an icon carries its catalogue id.
215
+ toggleIcon: (id, selected, options, external) => {
216
+ if (selected) {
217
+ const placed = placedIconId(id, getState().selectedIcons, () => createInstanceId('icon'));
218
+ const iconState = {
219
+ x: options?.center?.x ?? width / 2,
220
+ y: options?.center?.y ?? height / 2,
221
+ scale: s,
222
+ rotation: 0,
223
+ color: inkFor(getState().backgroundColor),
224
+ opacity: 1,
225
+ // An icon from the icon search: the page keeps its markup (to draw it) and its source (to credit it).
226
+ ...(placed.iconId ? { iconId: placed.iconId } : {}),
227
+ ...(external ? { svg: external.svg, source: external.source } : {}),
228
+ };
229
+ commit((prev) => ({
230
+ ...prev,
231
+ selectedIcons: [...prev.selectedIcons, placed.id],
232
+ iconStates: { ...prev.iconStates, [placed.id]: iconState },
233
+ layerOrder: withLayer(prev.layerOrder, placed.id),
234
+ }));
235
+ return;
236
+ }
237
+ commit((prev) => {
238
+ const doomed = new Set(iconInstanceIdsFor(id, prev.selectedIcons, prev.iconStates));
239
+ return {
240
+ ...prev,
241
+ selectedIcons: prev.selectedIcons.filter((i) => !doomed.has(i)),
242
+ iconStates: Object.fromEntries(Object.entries(prev.iconStates).filter(([key]) => !doomed.has(key))),
243
+ layerOrder: (prev.layerOrder ?? []).filter((entry) => !doomed.has(entry)),
244
+ };
245
+ });
246
+ },
247
+ updateIcon: (id, partial) => commit((prev) => ({
248
+ ...prev,
249
+ iconStates: { ...prev.iconStates, [id]: { ...prev.iconStates[id], ...partial } },
250
+ }), true),
251
+ // ── Emoji and other catalogue graphics ───────────────────────────────────
252
+ addAsset: (assetId, options) => {
253
+ const placed = {
254
+ ...createAssetInstance(assetId, width, height),
255
+ ...options?.center,
256
+ };
257
+ commit((prev) => ({
258
+ ...prev,
259
+ assetInstances: [...prev.assetInstances, placed],
260
+ layerOrder: withLayer(prev.layerOrder, placed.id),
261
+ }));
262
+ },
263
+ updateAsset: (id, partial) => commit((prev) => ({
264
+ ...prev,
265
+ assetInstances: prev.assetInstances.map((x) => (x.id === id ? { ...x, ...partial } : x)),
266
+ }), true),
267
+ removeAsset: (id) => commit((prev) => ({
268
+ ...prev,
269
+ assetInstances: prev.assetInstances.filter((x) => x.id !== id),
270
+ layerOrder: withoutLayer(prev.layerOrder, id),
271
+ })),
272
+ // ── Illustrations ────────────────────────────────────────────────────────
273
+ addIllustration: (id, options) => {
274
+ void createIllustration(id, width, height).then((created) => {
275
+ // The primitive centres the artwork on x/y.
276
+ const placed = { ...created, ...options?.center };
277
+ commit((prev) => ({
278
+ ...prev,
279
+ illustrationInstances: [...prev.illustrationInstances, placed],
280
+ layerOrder: withLayer(prev.layerOrder, placed.id),
281
+ }));
282
+ });
283
+ },
284
+ updateIllustration: (id, partial) => commit((prev) => ({
285
+ ...prev,
286
+ illustrationInstances: prev.illustrationInstances.map((x) => x.id === id ? { ...x, ...partial } : x),
287
+ }), true),
288
+ removeIllustration: (id) => commit((prev) => ({
289
+ ...prev,
290
+ illustrationInstances: prev.illustrationInstances.filter((x) => x.id !== id),
291
+ layerOrder: withoutLayer(prev.layerOrder, id),
292
+ })),
293
+ // ── Placed images (uploads) ──────────────────────────────────────────────
294
+ addUserImageFromUrl: (url, fileName, options) => {
295
+ void createUserImageInstanceFromUrl(url, fileName, width, height, options).then((image) => commit((prev) => ({
296
+ ...prev,
297
+ userImageInstances: [...prev.userImageInstances, image],
298
+ layerOrder: withLayer(prev.layerOrder, image.id),
299
+ })));
300
+ },
301
+ updateUserImage: (id, partial) => commit((prev) => ({
302
+ ...prev,
303
+ userImageInstances: prev.userImageInstances.map((x) => x.id === id ? { ...x, ...partial } : x),
304
+ }), true),
305
+ removeUserImage: (id) => commit((prev) => ({
306
+ ...prev,
307
+ userImageInstances: prev.userImageInstances.filter((x) => x.id !== id),
308
+ layerOrder: withoutLayer(prev.layerOrder, id),
309
+ })),
310
+ // ── Blocks ───────────────────────────────────────────────────────────────
311
+ // A placed block is one history step; its parts form a group, and the page takes the block's
312
+ // colour world when it has none, so a brand change later rebinds the block as it does the page.
313
+ insertBlock: (block) => {
314
+ // Once, outside `commit`: it runs the change for the state and again for the history entry.
315
+ const ids = blockElementIds(block);
316
+ const group = {
317
+ id: newId('group'),
318
+ ...(block.blockRef && { blockRef: block.blockRef }),
319
+ elementIds: ids,
320
+ };
321
+ commit((prev) => {
322
+ return {
323
+ ...prev,
324
+ additionalTexts: [...prev.additionalTexts, ...block.additionalTexts],
325
+ shapeInstances: [...prev.shapeInstances, ...block.shapeInstances],
326
+ assetInstances: [...(prev.assetInstances ?? []), ...block.assetInstances],
327
+ chartInstances: [...(prev.chartInstances ?? []), ...block.chartInstances],
328
+ userImageInstances: [...prev.userImageInstances, ...block.userImageInstances],
329
+ pillBadgeInstances: [...(prev.pillBadgeInstances ?? []), ...block.pillBadgeInstances],
330
+ circleBadgeInstances: [
331
+ ...(prev.circleBadgeInstances ?? []),
332
+ ...block.circleBadgeInstances,
333
+ ],
334
+ selectedIcons: [...prev.selectedIcons, ...block.selectedIcons],
335
+ iconStates: { ...prev.iconStates, ...block.iconStates },
336
+ layerOrder: [...(prev.layerOrder ?? []), ...block.layerOrder],
337
+ // A group of one is no group (`pruneGroups` would drop it anyway).
338
+ ...(ids.length > 1 && { groups: [...(prev.groups ?? []), group] }),
339
+ ...(!prev.brandScheme && block.brandScheme && { brandScheme: block.brandScheme }),
340
+ };
341
+ });
342
+ },
343
+ // ── Background ───────────────────────────────────────────────────────────
344
+ // A swatch pick carries its role: the ground then follows the brand. A free colour unbinds it.
345
+ setBackgroundColor: (color, ref) => commit((prev) => {
346
+ const { bind: _previous, ...rest } = prev;
347
+ const bind = ref
348
+ ? withBinding(prev.bind, 'backgroundColor', { ref, value: color })
349
+ : withoutBinding(prev.bind, 'backgroundColor');
350
+ return { ...rest, backgroundColor: color, ...(bind ? { bind } : {}) };
351
+ }, true),
352
+ };
353
+ }