@cosmicdrift/kumiko-samples 0.418.0 → 0.420.0

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 (90) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +11 -1
  3. package/packages/bundled-features/src/shared/index.ts +6 -0
  4. package/packages/bundled-features/src/shared/tenant-scoped-subject.ts +28 -0
  5. package/packages/bundled-features/src/signature/changes.json +6 -0
  6. package/packages/bundled-features/src/signature/feature.ts +1 -1
  7. package/packages/bundled-features/src/signature/grant.ts +13 -14
  8. package/packages/bundled-features/src/signature/png.ts +33 -12
  9. package/packages/bundled-features/src/template-resolver/api.ts +17 -7
  10. package/packages/bundled-features/src/template-resolver/changes.json +62 -0
  11. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +10 -9
  12. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +170 -0
  13. package/packages/bundled-features/src/template-resolver/document-frames.ts +68 -0
  14. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +682 -0
  15. package/packages/bundled-features/src/template-resolver/document-ops.ts +170 -128
  16. package/packages/bundled-features/src/template-resolver/document-print-only.ts +65 -0
  17. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +53 -19
  18. package/packages/bundled-features/src/template-resolver/feature.ts +15 -0
  19. package/packages/bundled-features/src/template-resolver/handlers/apply-layout.write.ts +137 -0
  20. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +87 -0
  21. package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +2 -2
  22. package/packages/bundled-features/src/template-resolver/handlers/document-blocks.query.ts +13 -8
  23. package/packages/bundled-features/src/template-resolver/handlers/document-region.ts +47 -0
  24. package/packages/bundled-features/src/template-resolver/handlers/failure-reason.ts +13 -0
  25. package/packages/bundled-features/src/template-resolver/handlers/import-bundle-system.write.ts +3 -0
  26. package/packages/bundled-features/src/template-resolver/handlers/layout-source.query.ts +17 -5
  27. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +16 -4
  28. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +20 -6
  29. package/packages/bundled-features/src/template-resolver/handlers/publish-templates.write.ts +69 -0
  30. package/packages/bundled-features/src/template-resolver/handlers/set.write.ts +7 -0
  31. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +15 -3
  32. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +159 -0
  33. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +25 -10
  34. package/packages/bundled-features/src/template-resolver/handlers/upsert-system.write.ts +7 -3
  35. package/packages/bundled-features/src/template-resolver/handlers/usage.query.ts +131 -18
  36. package/packages/bundled-features/src/template-resolver/handlers/validate.query.ts +10 -0
  37. package/packages/bundled-features/src/template-resolver/i18n.ts +3 -0
  38. package/packages/bundled-features/src/template-resolver/index.ts +39 -0
  39. package/packages/bundled-features/src/template-resolver/layout-regions.ts +54 -16
  40. package/packages/bundled-features/src/template-resolver/print-document.ts +3 -1
  41. package/packages/bundled-features/src/template-resolver/seeding.ts +4 -0
  42. package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +11 -1
  43. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +37 -1
  44. package/packages/bundled-features/src/template-resolver/template-meta.ts +31 -6
  45. package/packages/bundled-features/src/template-resolver/template-preview.ts +29 -9
  46. package/packages/bundled-features/src/template-resolver/template-validation.ts +10 -3
  47. package/packages/bundled-features/src/template-resolver/web/constants.ts +33 -0
  48. package/packages/bundled-features/src/template-resolver/web/document-blocks.ts +5 -0
  49. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +93 -25
  50. package/packages/bundled-features/src/template-resolver/web/document-editor-fonts.ts +13 -0
  51. package/packages/bundled-features/src/template-resolver/web/document-editor.tsx +4 -1
  52. package/packages/bundled-features/src/template-resolver/web/document-fonts.ts +21 -0
  53. package/packages/bundled-features/src/template-resolver/web/document-frame-control.ts +428 -0
  54. package/packages/bundled-features/src/template-resolver/web/document-frame-node-view.tsx +207 -0
  55. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +246 -0
  56. package/packages/bundled-features/src/template-resolver/web/document-print-defaults.ts +59 -0
  57. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +381 -0
  58. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +80 -0
  59. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +87 -19
  60. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +214 -0
  61. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +185 -16
  62. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +70 -7
  63. package/packages/bundled-features/src/template-resolver/web/document-tiptap-context.ts +13 -1
  64. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +25 -4
  65. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +276 -23
  66. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +449 -10
  67. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +108 -17
  68. package/packages/bundled-features/src/template-resolver/web/document-toolbar-blocks.ts +20 -0
  69. package/packages/bundled-features/src/template-resolver/web/fontsource-css.d.ts +2 -0
  70. package/packages/bundled-features/src/template-resolver/web/i18n.ts +32 -0
  71. package/packages/bundled-features/src/template-resolver/web/index.ts +38 -0
  72. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +16 -0
  73. package/packages/bundled-features/src/template-resolver/web/placeholder-text.ts +6 -3
  74. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +7 -0
  75. package/packages/bundled-features/src/template-resolver/web/use-document-tiptap-model.ts +74 -5
  76. package/packages/bundled-features/src/tenant/company-config.ts +48 -0
  77. package/packages/bundled-features/src/tenant/feature.ts +11 -0
  78. package/packages/bundled-features/src/tenant/i18n.ts +14 -0
  79. package/samples/apps/ui-walkthrough/src/app/auth-constants.ts +51 -0
  80. package/samples/apps/ui-walkthrough/src/app/seed-print-editor-tenants.ts +118 -0
  81. package/samples/apps/ui-walkthrough/src/app/seed-templates.ts +2 -0
  82. package/samples/apps/ui-walkthrough/src/app/server.ts +9 -1
  83. package/samples/apps/ui-walkthrough/src/app/template-seed-data.ts +27 -1
  84. package/samples/apps/ui-walkthrough/src/features/rental/i18n.ts +8 -0
  85. package/samples/apps/ui-walkthrough/src/features/rental/screens.ts +1 -0
  86. package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
  87. package/samples/apps/use-all-bundled/feature-manifest.json +236 -0
  88. package/samples/recipes/pdf-letterhead/README.md +23 -0
  89. package/samples/recipes/pdf-letterhead/package.json +12 -0
  90. package/samples/recipes/pdf-letterhead/src/letterhead.ts +92 -0
@@ -1,18 +1,27 @@
1
+ import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
1
2
  import type { Extensions, NodeViewRenderer } from "@tiptap/core";
2
3
  import { ListKeymap } from "@tiptap/extension-list";
3
4
  import { Dropcursor, Gapcursor, Placeholder, UndoRedo } from "@tiptap/extensions";
4
5
  import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
6
+ import type { DocumentFrameControl } from "./document-frame-control.ts";
7
+ import { createFrameView, type FrameViewLabels } from "./document-frame-node-view.tsx";
8
+ import { DocumentPrintEditing, loadDocumentEditorFonts } from "./document-print-decorations.ts";
9
+ import { DOCUMENT_IMAGE_ALIGNMENTS, DocumentFrame } from "./document-print-style.ts";
10
+ import type { RepeatStripOptions } from "./document-repeat-strip.ts";
5
11
  import {
12
+ DOCUMENT_DATE_STYLES,
6
13
  DocumentButton,
7
14
  DocumentImages,
8
15
  DocumentPageBreak,
9
16
  DocumentResource,
10
17
  DocumentSteps,
18
+ DocumentTable,
11
19
  DocumentVariable,
12
20
  documentExtensions,
13
21
  } from "./document-schema.ts";
14
22
  import { readDocumentStepsAttribute } from "./document-steps.ts";
15
- import type { DocumentResourcePreview } from "./document-toolbar-blocks.ts";
23
+ import { documentImageCss } from "./document-style-css.ts";
24
+ import type { DocumentPrintMode, DocumentResourcePreview } from "./document-toolbar-blocks.ts";
16
25
 
17
26
  const DOCUMENT_RESOURCE_SIZE_TOKEN = "{size}";
18
27
  export const DOCUMENT_BLOCK_ATTRIBUTE = "data-document-block";
@@ -31,6 +40,11 @@ export type DocumentEditorLabels = {
31
40
  readonly resourcePreviews?: Readonly<Record<string, DocumentResourcePreview>>;
32
41
  /** Canvas chrome labels every block with its type. */
33
42
  readonly blockLabels?: boolean;
43
+ readonly print?: DocumentPrintMode;
44
+ /** Tag text per frame kind; frames render as movable boxes only with these. */
45
+ readonly frameLabels?: FrameViewLabels;
46
+ readonly reportFrameControl?: (control: DocumentFrameControl | null) => void;
47
+ readonly repeatStrip?: RepeatStripOptions;
34
48
  };
35
49
 
36
50
  function createElementWithClass<K extends keyof HTMLElementTagNameMap>(
@@ -44,7 +58,7 @@ function createElementWithClass<K extends keyof HTMLElementTagNameMap>(
44
58
  return element;
45
59
  }
46
60
 
47
- const CHIP_CLASS = "mx-0.5 inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-xs";
61
+ const CHIP_CLASS = "mx-0.5 inline-flex items-center gap-1 rounded border px-1.5 text-[0.9em]";
48
62
  const USER_CHIP_CLASS = `${CHIP_CLASS} border-primary/30 bg-primary/10 text-primary`;
49
63
  const SYSTEM_CHIP_CLASS = `${CHIP_CLASS} border-input bg-muted text-muted-foreground`;
50
64
 
@@ -59,6 +73,9 @@ function repeatRowListAt(doc: ProseMirrorNode, position: number | undefined): st
59
73
  return null;
60
74
  }
61
75
 
76
+ // Language-neutral: the real value is formatted per locale at render time.
77
+ const DATE_STYLE_CHIP_HINTS = { short: "15.01.2026", long: "15. Jan 2026" } as const;
78
+
62
79
  // The chip is display only: the stored node carries just the name, so a
63
80
  // label never reaches the document.
64
81
  export function createVariableView(
@@ -79,6 +96,11 @@ export function createVariableView(
79
96
  const hasOwnLabel = label !== undefined && label !== "" && label !== name;
80
97
  dom.append(document.createTextNode(hasOwnLabel ? label : name));
81
98
  if (hasOwnLabel) dom.title = name;
99
+ const dateStyle: unknown = node.attrs["dateStyle"];
100
+ if (isOneOf(DOCUMENT_DATE_STYLES, dateStyle)) {
101
+ dom.setAttribute("data-date-style", dateStyle);
102
+ dom.append(document.createTextNode(` · ${DATE_STYLE_CHIP_HINTS[dateStyle]}`));
103
+ }
82
104
  return { dom };
83
105
  };
84
106
  }
@@ -97,6 +119,53 @@ function createBlockLabel(text: string): HTMLSpanElement {
97
119
  return label;
98
120
  }
99
121
 
122
+ type ResourcePreview = NonNullable<DocumentEditorLabels["resourcePreviews"]>[string];
123
+
124
+ function appendResourceImage(
125
+ dom: HTMLElement,
126
+ node: ProseMirrorNode,
127
+ key: string,
128
+ preview: ResourcePreview,
129
+ ): void {
130
+ const widthMm = node.attrs["widthMm"];
131
+ const align = node.attrs["align"];
132
+ const sized = typeof widthMm === "number";
133
+ const bleeds = node.attrs["bleed"] === true;
134
+ const image = createElementWithClass(
135
+ "img",
136
+ sized || bleeds ? "rounded" : "max-w-[180px] rounded",
137
+ );
138
+ // The same builder as the PDF, so the editor size follows the paper scale.
139
+ image.style.cssText = documentImageCss({
140
+ widthMm: typeof widthMm === "number" ? widthMm : null,
141
+ align: isOneOf(DOCUMENT_IMAGE_ALIGNMENTS, align) ? align : null,
142
+ });
143
+ if (bleeds) image.style.width = "100%";
144
+ if (sized || bleeds) dom.style.display = "block";
145
+ image.src = preview.src;
146
+ image.alt = typeof node.attrs["alt"] === "string" ? node.attrs["alt"] : key;
147
+ dom.append(image);
148
+ // An empty caption means "no caption", not the key.
149
+ const caption = preview.caption ?? key;
150
+ if (caption !== "") {
151
+ const captionElement = createElementWithClass(
152
+ "span",
153
+ "whitespace-nowrap text-[11px]",
154
+ caption.replace(` · ${DOCUMENT_RESOURCE_SIZE_TOKEN}`, ""),
155
+ );
156
+ // The size is only known once the browser decoded the image (possibly already, from cache).
157
+ const showSize = (): void => {
158
+ captionElement.textContent = caption.replace(
159
+ DOCUMENT_RESOURCE_SIZE_TOKEN,
160
+ `${image.naturalWidth} × ${image.naturalHeight} px`,
161
+ );
162
+ };
163
+ image.addEventListener("load", showSize);
164
+ if (image.complete && image.naturalWidth > 0) showSize();
165
+ dom.append(captionElement);
166
+ }
167
+ }
168
+
100
169
  function createResourceView(labels: DocumentEditorLabels): NodeViewRenderer {
101
170
  return ({ node }) => {
102
171
  const key = String(node.attrs["resource"]);
@@ -119,29 +188,7 @@ function createResourceView(labels: DocumentEditorLabels): NodeViewRenderer {
119
188
  dom.append(label);
120
189
  }
121
190
  if (hasImage) {
122
- const image = createElementWithClass("img", "max-w-[180px] rounded");
123
- image.src = preview.src;
124
- image.alt = typeof node.attrs["alt"] === "string" ? node.attrs["alt"] : key;
125
- dom.append(image);
126
- // An empty caption means "no caption", not the key.
127
- const caption = preview.caption ?? key;
128
- if (caption !== "") {
129
- const captionElement = createElementWithClass(
130
- "span",
131
- "whitespace-nowrap text-[11px]",
132
- caption.replace(` · ${DOCUMENT_RESOURCE_SIZE_TOKEN}`, ""),
133
- );
134
- // The size is only known once the browser decoded the image (possibly already, from cache).
135
- const showSize = (): void => {
136
- captionElement.textContent = caption.replace(
137
- DOCUMENT_RESOURCE_SIZE_TOKEN,
138
- `${image.naturalWidth} × ${image.naturalHeight} px`,
139
- );
140
- };
141
- image.addEventListener("load", showSize);
142
- if (image.complete && image.naturalWidth > 0) showSize();
143
- dom.append(captionElement);
144
- }
191
+ appendResourceImage(dom, node, key, preview);
145
192
  } else {
146
193
  dom.append(
147
194
  createElementWithClass("span", "font-medium", labels.image),
@@ -252,6 +299,16 @@ export function createDocumentEditorExtensions(labels: DocumentEditorLabels): Ex
252
299
  return DocumentSteps.extend({ addNodeView: () => createStepsView(labels) });
253
300
  case DocumentImages.name:
254
301
  return DocumentImages.extend({ addNodeView: () => createImagesView(labels) });
302
+ case DocumentTable.name:
303
+ return labels.print !== undefined && labels.print !== "none"
304
+ ? DocumentTable.configure({ resizable: true })
305
+ : extension;
306
+ case DocumentFrame.name: {
307
+ const { frameLabels } = labels;
308
+ return frameLabels === undefined
309
+ ? extension
310
+ : DocumentFrame.extend({ addNodeView: () => createFrameView(frameLabels) });
311
+ }
255
312
  case DocumentPageBreak.name:
256
313
  return DocumentPageBreak.extend({
257
314
  addNodeView: () => createPageBreakView(labels.pageBreak),
@@ -260,9 +317,20 @@ export function createDocumentEditorExtensions(labels: DocumentEditorLabels): Ex
260
317
  return extension;
261
318
  }
262
319
  });
320
+ const print = labels.print ?? "none";
321
+ if (print !== "none") void loadDocumentEditorFonts();
263
322
  // No TrailingNode: it appends an empty paragraph that breaks the HTML roundtrip.
264
323
  return [
265
324
  ...base,
325
+ ...(print === "none"
326
+ ? []
327
+ : [
328
+ DocumentPrintEditing.configure({
329
+ frames: print === "page",
330
+ reportFrameControl: labels.reportFrameControl ?? null,
331
+ repeatStrip: labels.repeatStrip ?? null,
332
+ }),
333
+ ]),
266
334
  UndoRedo,
267
335
  Gapcursor,
268
336
  Dropcursor,
@@ -0,0 +1,13 @@
1
+ /// <reference path="./fontsource-css.d.ts" />
2
+ // Loaded only through loadDocumentEditorFonts (a dynamic import), so the font CSS stays out of the
3
+ // main bundle and is evaluated once per session.
4
+ import "@fontsource/arimo/latin-400.css";
5
+ import "@fontsource/arimo/latin-700.css";
6
+ import "@fontsource/tinos/latin-400.css";
7
+ import "@fontsource/tinos/latin-700.css";
8
+ import "@fontsource/cousine/latin-400.css";
9
+ import "@fontsource/cousine/latin-700.css";
10
+ import "@fontsource/carlito/latin-400.css";
11
+ import "@fontsource/carlito/latin-700.css";
12
+ import "@fontsource/caladea/latin-400.css";
13
+ import "@fontsource/caladea/latin-700.css";
@@ -6,6 +6,8 @@ import { TextareaContentEditor } from "@cosmicdrift/kumiko-renderer";
6
6
  import { createContext, lazy, type ReactNode, Suspense, useContext } from "react";
7
7
  import type { DocumentEditorProps, DocumentToolbarBlock } from "./document-toolbar-blocks.ts";
8
8
 
9
+ const NO_BLOCKS: readonly DocumentToolbarBlock[] = [];
10
+
9
11
  const LazyDocumentTiptapEditor = lazy(() => import("./document-tiptap-editor.tsx"));
10
12
 
11
13
  // The editor registry only hands ContentEditorProps to an editor, so the
@@ -17,7 +19,8 @@ export const DocumentBlocksContext = createContext<readonly DocumentToolbarBlock
17
19
 
18
20
  export function DocumentContentEditor(props: DocumentEditorProps): ReactNode {
19
21
  const contextBlocks = useContext(DocumentBlocksContext);
20
- const editorProps = props.blocks === undefined ? { ...props, blocks: contextBlocks } : props;
22
+ const blocks = props.blocks ?? (props.formatting === "text" ? NO_BLOCKS : contextBlocks);
23
+ const editorProps = { ...props, blocks };
21
24
  return (
22
25
  <Suspense
23
26
  // Read-only without chips: a textarea would insert {{name}} text and plaintext into a document body.
@@ -0,0 +1,21 @@
1
+ export const DOCUMENT_FONTS = ["arial", "times", "courier", "calibri", "cambria"] as const;
2
+ export type DocumentFont = (typeof DOCUMENT_FONTS)[number];
3
+
4
+ export const DOCUMENT_FONT_LABELS: Readonly<Record<DocumentFont, string>> = {
5
+ arial: "Arial",
6
+ times: "Times New Roman",
7
+ courier: "Courier New",
8
+ calibri: "Calibri",
9
+ cambria: "Cambria",
10
+ };
11
+
12
+ // The first family is the metric-compatible font installed in the print service, so the PDF
13
+ // wraps lines like the Office font the author picked.
14
+ // Single quotes only: the stacks land in double-quoted style attributes, where a double quote ends the attribute.
15
+ export const DOCUMENT_FONT_PRINT_STACKS: Readonly<Record<DocumentFont, string>> = {
16
+ arial: "'Liberation Sans',Arial,sans-serif",
17
+ times: "'Liberation Serif','Times New Roman',serif",
18
+ courier: "'Liberation Mono','Courier New',monospace",
19
+ calibri: "Carlito,Calibri,sans-serif",
20
+ cambria: "Caladea,Cambria,serif",
21
+ };
@@ -0,0 +1,428 @@
1
+ import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
2
+ import type { Editor, JSONContent } from "@tiptap/core";
3
+ import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
4
+ import type { Selection } from "@tiptap/pm/state";
5
+ import { type DocumentFrameAttributes, FRAME_PRESETS } from "./document-print-style.ts";
6
+ import {
7
+ type DocumentFrameBox,
8
+ FRAME_FLOW_GAP_MM,
9
+ SENDER_LINE_SIZE_PT,
10
+ } from "./document-style-css.ts";
11
+
12
+ export type DocumentFrameControl = {
13
+ readonly attrs: DocumentFrameAttributes;
14
+ readonly update: (patch: Partial<DocumentFrameAttributes>) => void;
15
+ readonly remove: () => void;
16
+ readonly senderLine: boolean;
17
+ readonly setSenderLine: (on: boolean) => void;
18
+ /** Variable name of the placeholder in the last paragraph, null without one. */
19
+ readonly recipient: string | null;
20
+ readonly setRecipient: (variableName: string | null) => void;
21
+ };
22
+
23
+ export const FRAME_NODE_NAME = "documentFrame";
24
+ export const FRAME_SELECTED_ATTRIBUTE = "data-frame-selected";
25
+ export const FRAME_STEP_MM = 0.5;
26
+ export const FRAME_MIN_SIZE_MM = 10;
27
+ export const FRAME_HANDLES = ["nw", "n", "ne", "e", "se", "s", "sw", "w"] as const;
28
+ export type FrameHandle = (typeof FRAME_HANDLES)[number];
29
+
30
+ const TEXT_STYLE_MARK = "documentTextStyle";
31
+ const DIN_5008_FORM_A_Y_MM = 27;
32
+ const DIN_5008_FORM_B_Y_MM = 45;
33
+
34
+ const ADDRESS_FRAME_BOX: DocumentFrameBox = { xMm: 20, yMm: 45, widthMm: 85, heightMm: 45 };
35
+ const TEXT_FRAME_BOX: DocumentFrameBox = { xMm: 125, yMm: 50, widthMm: 65, heightMm: 34 };
36
+
37
+ export function roundToHalfMm(value: number): number {
38
+ return Math.round(value / FRAME_STEP_MM) * FRAME_STEP_MM;
39
+ }
40
+
41
+ export function moveFrameBox(box: DocumentFrameBox, dxMm: number, dyMm: number): DocumentFrameBox {
42
+ return {
43
+ ...box,
44
+ xMm: Math.max(0, roundToHalfMm(box.xMm + dxMm)),
45
+ yMm: Math.max(0, roundToHalfMm(box.yMm + dyMm)),
46
+ };
47
+ }
48
+
49
+ // The edge opposite the dragged corner stays put, so a clamp never shifts the whole frame.
50
+ export function resizeFrameBox(
51
+ box: DocumentFrameBox,
52
+ handle: FrameHandle,
53
+ dxMm: number,
54
+ dyMm: number,
55
+ ): DocumentFrameBox {
56
+ const right = box.xMm + box.widthMm;
57
+ const bottom = box.yMm + box.heightMm;
58
+ const movesLeft = handle === "nw" || handle === "sw" || handle === "w";
59
+ const movesRight = handle === "ne" || handle === "se" || handle === "e";
60
+ const movesTop = handle === "nw" || handle === "ne" || handle === "n";
61
+ const movesBottom = handle === "sw" || handle === "se" || handle === "s";
62
+ const left = movesLeft
63
+ ? Math.min(Math.max(0, roundToHalfMm(box.xMm + dxMm)), right - FRAME_MIN_SIZE_MM)
64
+ : box.xMm;
65
+ const top = movesTop
66
+ ? Math.min(Math.max(0, roundToHalfMm(box.yMm + dyMm)), bottom - FRAME_MIN_SIZE_MM)
67
+ : box.yMm;
68
+ const newRight = movesRight
69
+ ? Math.max(left + FRAME_MIN_SIZE_MM, roundToHalfMm(right + dxMm))
70
+ : right;
71
+ const newBottom = movesBottom
72
+ ? Math.max(top + FRAME_MIN_SIZE_MM, roundToHalfMm(bottom + dyMm))
73
+ : bottom;
74
+ return { xMm: left, yMm: top, widthMm: newRight - left, heightMm: newBottom - top };
75
+ }
76
+
77
+ export const FRAME_SNAP_TOLERANCE_MM = 1.5;
78
+
79
+ export type FrameSnapTargets = {
80
+ readonly xLinesMm: readonly number[];
81
+ readonly yLinesMm: readonly number[];
82
+ readonly widthsMm: readonly number[];
83
+ readonly heightsMm: readonly number[];
84
+ };
85
+
86
+ export type FrameGuides = { readonly xMm: number | null; readonly yMm: number | null };
87
+
88
+ type AxisMode = "move" | "low" | "high" | "none";
89
+ type AxisSnap = { readonly start: number; readonly size: number; readonly guide: number | null };
90
+
91
+ function nearestWithin(
92
+ value: number,
93
+ candidates: readonly number[],
94
+ toleranceMm: number,
95
+ ): number | null {
96
+ let best: number | null = null;
97
+ for (const candidate of candidates) {
98
+ const distance = Math.abs(candidate - value);
99
+ if (distance <= toleranceMm && (best === null || distance < Math.abs(best - value))) {
100
+ best = candidate;
101
+ }
102
+ }
103
+ return best;
104
+ }
105
+
106
+ function snapMove(
107
+ start: number,
108
+ size: number,
109
+ lines: readonly number[],
110
+ toleranceMm: number,
111
+ ): AxisSnap {
112
+ const unchanged: AxisSnap = { start, size, guide: null };
113
+ const end = start + size;
114
+ const leading = nearestWithin(start, lines, toleranceMm);
115
+ const trailing = nearestWithin(end, lines, toleranceMm);
116
+ const leadingDistance = leading === null ? Infinity : Math.abs(leading - start);
117
+ const trailingDistance = trailing === null ? Infinity : Math.abs(trailing - end);
118
+ if (leading !== null && leadingDistance <= trailingDistance) {
119
+ return { start: leading, size, guide: leading };
120
+ }
121
+ if (trailing !== null) {
122
+ const snappedStart = trailing - size;
123
+ return snappedStart >= 0 ? { start: snappedStart, size, guide: trailing } : unchanged;
124
+ }
125
+ return unchanged;
126
+ }
127
+
128
+ // The dragged edge snaps to a line or the size to another frame's size; the fixed edge stays.
129
+ function snapResize(
130
+ start: number,
131
+ size: number,
132
+ mode: "low" | "high",
133
+ lines: readonly number[],
134
+ sizes: readonly number[],
135
+ toleranceMm: number,
136
+ ): AxisSnap {
137
+ const unchanged: AxisSnap = { start, size, guide: null };
138
+ const end = start + size;
139
+ const dragged = mode === "low" ? start : end;
140
+ const fixed = mode === "low" ? end : start;
141
+ const line = nearestWithin(dragged, lines, toleranceMm);
142
+ const matchedSize = nearestWithin(size, sizes, toleranceMm);
143
+ const lineDistance = line === null ? Infinity : Math.abs(line - dragged);
144
+ const sizeDistance = matchedSize === null ? Infinity : Math.abs(matchedSize - size);
145
+ const resolve = (candidateSize: number, guide: number | null): AxisSnap => {
146
+ const candidateStart = mode === "low" ? fixed - candidateSize : start;
147
+ return candidateSize >= FRAME_MIN_SIZE_MM && candidateStart >= 0
148
+ ? { start: candidateStart, size: candidateSize, guide }
149
+ : unchanged;
150
+ };
151
+ if (line !== null && lineDistance <= sizeDistance) {
152
+ return resolve(mode === "low" ? fixed - line : line - fixed, line);
153
+ }
154
+ if (matchedSize !== null) return resolve(matchedSize, null);
155
+ return unchanged;
156
+ }
157
+
158
+ function snapAxis(
159
+ start: number,
160
+ size: number,
161
+ mode: AxisMode,
162
+ lines: readonly number[],
163
+ sizes: readonly number[],
164
+ toleranceMm: number,
165
+ ): AxisSnap {
166
+ if (mode === "none") return { start, size, guide: null };
167
+ if (mode === "move") return snapMove(start, size, lines, toleranceMm);
168
+ return snapResize(start, size, mode, lines, sizes, toleranceMm);
169
+ }
170
+
171
+ export function snapFrameBox(
172
+ box: DocumentFrameBox,
173
+ gesture: FrameHandle | "move",
174
+ targets: FrameSnapTargets,
175
+ toleranceMm: number = FRAME_SNAP_TOLERANCE_MM,
176
+ ): { readonly box: DocumentFrameBox; readonly guides: FrameGuides } {
177
+ const xMode: AxisMode =
178
+ gesture === "move"
179
+ ? "move"
180
+ : gesture.includes("w")
181
+ ? "low"
182
+ : gesture.includes("e")
183
+ ? "high"
184
+ : "none";
185
+ const yMode: AxisMode =
186
+ gesture === "move"
187
+ ? "move"
188
+ : gesture.includes("n")
189
+ ? "low"
190
+ : gesture.includes("s")
191
+ ? "high"
192
+ : "none";
193
+ const x = snapAxis(box.xMm, box.widthMm, xMode, targets.xLinesMm, targets.widthsMm, toleranceMm);
194
+ const y = snapAxis(
195
+ box.yMm,
196
+ box.heightMm,
197
+ yMode,
198
+ targets.yLinesMm,
199
+ targets.heightsMm,
200
+ toleranceMm,
201
+ );
202
+ return {
203
+ box: { xMm: x.start, yMm: y.start, widthMm: x.size, heightMm: y.size },
204
+ guides: { xMm: x.guide, yMm: y.guide },
205
+ };
206
+ }
207
+
208
+ export type PageEdgesMm = {
209
+ readonly marginLeftMm: number;
210
+ readonly marginRightMm: number;
211
+ readonly marginTopMm: number;
212
+ readonly widthMm: number;
213
+ };
214
+
215
+ export function collectSnapTargets(
216
+ doc: ProseMirrorNode,
217
+ ownPos: number,
218
+ page: PageEdgesMm,
219
+ ): FrameSnapTargets {
220
+ const xLinesMm = [page.marginLeftMm, page.widthMm - page.marginRightMm];
221
+ const yLinesMm = [page.marginTopMm];
222
+ const widthsMm: number[] = [];
223
+ const heightsMm: number[] = [];
224
+ doc.forEach((child, offset) => {
225
+ if (child.type.name !== FRAME_NODE_NAME || offset === ownPos) return;
226
+ const other = frameAttributesOf(child);
227
+ xLinesMm.push(other.xMm, other.xMm + other.widthMm);
228
+ yLinesMm.push(other.yMm, other.yMm + other.heightMm);
229
+ widthsMm.push(other.widthMm);
230
+ heightsMm.push(other.heightMm);
231
+ });
232
+ return { xLinesMm, yLinesMm, widthsMm, heightsMm };
233
+ }
234
+
235
+ export type FrameTagKind = "addressFormA" | "addressFormB" | "address" | "text";
236
+
237
+ export function frameTagKind(preset: DocumentFrameAttributes["preset"], yMm: number): FrameTagKind {
238
+ if (preset !== "address") return "text";
239
+ if (Math.abs(yMm - DIN_5008_FORM_A_Y_MM) < FRAME_STEP_MM) return "addressFormA";
240
+ if (Math.abs(yMm - DIN_5008_FORM_B_Y_MM) < FRAME_STEP_MM) return "addressFormB";
241
+ return "address";
242
+ }
243
+
244
+ export function frameFlowBottomMm(doc: ProseMirrorNode): number {
245
+ let bottom = 0;
246
+ doc.forEach((child) => {
247
+ if (child.type.name !== FRAME_NODE_NAME) return;
248
+ const attrs = frameAttributesOf(child);
249
+ if (attrs.reserveFlow)
250
+ bottom = Math.max(bottom, attrs.yMm + attrs.heightMm + FRAME_FLOW_GAP_MM);
251
+ });
252
+ return bottom;
253
+ }
254
+
255
+ function numberAttr(value: unknown): number {
256
+ return typeof value === "number" ? value : 0;
257
+ }
258
+
259
+ export function frameAttributesOf(node: ProseMirrorNode): DocumentFrameAttributes {
260
+ const { xMm, yMm, widthMm, heightMm, preset, reserveFlow } = node.attrs;
261
+ return {
262
+ xMm: numberAttr(xMm),
263
+ yMm: numberAttr(yMm),
264
+ widthMm: numberAttr(widthMm),
265
+ heightMm: numberAttr(heightMm),
266
+ preset: isOneOf(FRAME_PRESETS, preset) ? preset : null,
267
+ reserveFlow: reserveFlow !== false,
268
+ };
269
+ }
270
+
271
+ const EMPTY_PARAGRAPH: JSONContent = { type: "paragraph" };
272
+
273
+ function senderLineParagraph(): JSONContent {
274
+ const marks = [{ type: TEXT_STYLE_MARK, attrs: { sizePt: SENDER_LINE_SIZE_PT } }];
275
+ return {
276
+ type: "paragraph",
277
+ content: [
278
+ { type: "variable", attrs: { name: "tenantName" }, marks },
279
+ { type: "text", text: " · ", marks },
280
+ { type: "variable", attrs: { name: "companyAddress" }, marks },
281
+ ],
282
+ };
283
+ }
284
+
285
+ function frameNode(
286
+ box: DocumentFrameBox,
287
+ preset: DocumentFrameAttributes["preset"],
288
+ content: JSONContent[],
289
+ reserveFlow: boolean,
290
+ ): JSONContent {
291
+ return { type: FRAME_NODE_NAME, attrs: { ...box, preset, reserveFlow }, content };
292
+ }
293
+
294
+ export function addressFrameContent(): JSONContent {
295
+ return frameNode(ADDRESS_FRAME_BOX, "address", [senderLineParagraph(), EMPTY_PARAGRAPH], true);
296
+ }
297
+
298
+ export function textFrameContent(): JSONContent {
299
+ return frameNode(TEXT_FRAME_BOX, "text", [EMPTY_PARAGRAPH], false);
300
+ }
301
+
302
+ export function columnsTableContent(): JSONContent {
303
+ return {
304
+ type: "table",
305
+ attrs: { borders: "none" },
306
+ content: [
307
+ {
308
+ type: "tableRow",
309
+ content: [1, 2, 3, 4].map(() => ({ type: "tableCell", content: [EMPTY_PARAGRAPH] })),
310
+ },
311
+ ],
312
+ };
313
+ }
314
+
315
+ // Frames are only valid as top-level body nodes, ahead of the flowing text.
316
+ export function insertFrame(editor: Editor, frame: JSONContent): void {
317
+ let pos = 0;
318
+ const { doc } = editor.state;
319
+ for (let index = 0; index < doc.childCount; index++) {
320
+ const child = doc.child(index);
321
+ if (child.type.name !== FRAME_NODE_NAME) break;
322
+ pos += child.nodeSize;
323
+ }
324
+ editor.chain().focus().insertContentAt(pos, frame).setNodeSelection(pos).run();
325
+ }
326
+
327
+ export type FrameLocation = { readonly pos: number; readonly node: ProseMirrorNode };
328
+
329
+ export function frameLocationOf(selection: Selection): FrameLocation | null {
330
+ const { $from, from, to } = selection;
331
+ const after = $from.nodeAfter;
332
+ if (after?.type.name === FRAME_NODE_NAME && from + after.nodeSize === to) {
333
+ return { pos: from, node: after };
334
+ }
335
+ for (let depth = $from.depth; depth > 0; depth--) {
336
+ const node = $from.node(depth);
337
+ if (node.type.name === FRAME_NODE_NAME) return { pos: $from.before(depth), node };
338
+ }
339
+ return null;
340
+ }
341
+
342
+ export function isSenderLine(paragraph: ProseMirrorNode | null | undefined): boolean {
343
+ if (paragraph === null || paragraph === undefined) return false;
344
+ if (paragraph.type.name !== "paragraph" || paragraph.childCount === 0) return false;
345
+ let everyChildSmall = true;
346
+ paragraph.forEach((child) => {
347
+ const small = child.marks.some(
348
+ (mark) => mark.type.name === TEXT_STYLE_MARK && mark.attrs["sizePt"] === SENDER_LINE_SIZE_PT,
349
+ );
350
+ if (!small) everyChildSmall = false;
351
+ });
352
+ return everyChildSmall;
353
+ }
354
+
355
+ function recipientOf(frame: ProseMirrorNode): string | null {
356
+ const last = frame.lastChild;
357
+ if (last === null || last.type.name !== "paragraph") return null;
358
+ if (frame.childCount === 1 && isSenderLine(last)) return null;
359
+ let name: string | null = null;
360
+ last.forEach((child) => {
361
+ const value: unknown = child.attrs["name"];
362
+ if (name === null && child.type.name === "variable" && typeof value === "string") name = value;
363
+ });
364
+ return name;
365
+ }
366
+
367
+ export function buildFrameControl(editor: Editor, location: FrameLocation): DocumentFrameControl {
368
+ const { pos } = location;
369
+ const currentFrame = (): ProseMirrorNode | null => {
370
+ const node = editor.state.doc.nodeAt(pos);
371
+ return node !== null && node.type.name === FRAME_NODE_NAME ? node : null;
372
+ };
373
+ return {
374
+ attrs: frameAttributesOf(location.node),
375
+ update: (patch) => {
376
+ const frame = currentFrame();
377
+ if (frame === null) return;
378
+ editor.view.dispatch(
379
+ editor.state.tr.setNodeMarkup(pos, undefined, { ...frame.attrs, ...patch }),
380
+ );
381
+ },
382
+ remove: () => {
383
+ const frame = currentFrame();
384
+ if (frame === null) return;
385
+ editor.view.dispatch(editor.state.tr.delete(pos, pos + frame.nodeSize));
386
+ },
387
+ senderLine: isSenderLine(location.node.firstChild),
388
+ setSenderLine: (on) => {
389
+ const frame = currentFrame();
390
+ const first = frame?.firstChild;
391
+ if (frame === null || first === null || first === undefined) return;
392
+ const present = isSenderLine(first);
393
+ const { tr, schema } = editor.state;
394
+ if (on && !present) {
395
+ tr.insert(pos + 1, schema.nodeFromJSON(senderLineParagraph()));
396
+ } else if (!on && present) {
397
+ const end = pos + 1 + first.nodeSize;
398
+ if (frame.childCount === 1)
399
+ tr.replaceWith(pos + 1, end, schema.nodeFromJSON(EMPTY_PARAGRAPH));
400
+ else tr.delete(pos + 1, end);
401
+ } else return;
402
+ editor.view.dispatch(tr);
403
+ },
404
+ recipient: recipientOf(location.node),
405
+ setRecipient: (variableName) => {
406
+ const frame = currentFrame();
407
+ const last = frame?.lastChild;
408
+ if (frame === null || last === null || last === undefined) return;
409
+ const { tr, schema } = editor.state;
410
+ const variable =
411
+ variableName === null ? null : schema.nodes["variable"]?.create({ name: variableName });
412
+ const frameEnd = pos + frame.nodeSize - 1;
413
+ const lastIsRecipient =
414
+ last.type.name === "paragraph" && !(frame.childCount === 1 && isSenderLine(last));
415
+ if (!lastIsRecipient) {
416
+ const paragraph = schema.nodes["paragraph"]?.create(null, variable ?? undefined);
417
+ if (paragraph === undefined) return;
418
+ tr.insert(frameEnd, paragraph);
419
+ } else {
420
+ const from = frameEnd - last.nodeSize + 1;
421
+ const to = frameEnd - 1;
422
+ if (variable === null || variable === undefined) tr.delete(from, to);
423
+ else tr.replaceWith(from, to, variable);
424
+ }
425
+ editor.view.dispatch(tr);
426
+ },
427
+ };
428
+ }