@cosmicdrift/kumiko-samples 0.419.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 (43) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +6 -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 +24 -0
  11. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +7 -1
  12. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +70 -2
  13. package/packages/bundled-features/src/template-resolver/document-frames.ts +43 -0
  14. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +135 -21
  15. package/packages/bundled-features/src/template-resolver/document-ops.ts +35 -3
  16. package/packages/bundled-features/src/template-resolver/document-print-only.ts +24 -0
  17. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +13 -1
  18. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +1 -1
  19. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +2 -1
  20. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +51 -14
  21. package/packages/bundled-features/src/template-resolver/index.ts +11 -1
  22. package/packages/bundled-features/src/template-resolver/template-meta.ts +7 -1
  23. package/packages/bundled-features/src/template-resolver/template-preview.ts +25 -4
  24. package/packages/bundled-features/src/template-resolver/web/constants.ts +4 -0
  25. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +60 -24
  26. package/packages/bundled-features/src/template-resolver/web/document-editor.tsx +4 -1
  27. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +55 -5
  28. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +137 -2
  29. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +2 -26
  30. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +61 -13
  31. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +109 -2
  32. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +161 -14
  33. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +4 -0
  34. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +2 -1
  35. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +132 -24
  36. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +160 -1
  37. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +18 -9
  38. package/packages/bundled-features/src/template-resolver/web/i18n.ts +4 -0
  39. package/packages/bundled-features/src/template-resolver/web/index.ts +4 -0
  40. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +10 -0
  41. package/packages/bundled-features/src/template-resolver/web/placeholder-text.ts +6 -3
  42. package/samples/apps/ui-walkthrough/src/features/rental/i18n.ts +8 -0
  43. package/samples/apps/ui-walkthrough/src/features/rental/screens.ts +1 -0
@@ -14,7 +14,11 @@ export {
14
14
  compileDocumentBodyToHandlebars,
15
15
  toResourceDataUri,
16
16
  } from "./compile-document-body.ts";
17
- export { flattenFramesForPreview, readTopLevelFrames } from "./document-frames.ts";
17
+ export {
18
+ flattenAddressSenderLine,
19
+ flattenFramesForPreview,
20
+ readTopLevelFrames,
21
+ } from "./document-frames.ts";
18
22
  export {
19
23
  type DocumentViolation,
20
24
  type DocumentViolationCode,
@@ -38,7 +42,9 @@ export { localeSchema } from "./handlers/shared.ts";
38
42
  export {
39
43
  companyConfigKey,
40
44
  defaultPdfLayoutSlug,
45
+ effectivePdfLayout,
41
46
  readTenantConfigText,
47
+ resolveDefaultPdfLayout,
42
48
  } from "./handlers/tenant-settings.ts";
43
49
  export {
44
50
  isHexColor,
@@ -131,13 +137,17 @@ export {
131
137
  FALLBACK_LOCALE,
132
138
  NON_RENDER_KINDS,
133
139
  type NonRenderKind,
140
+ PDF_CORNER_MARK_INSET_MM,
141
+ PDF_CORNER_MARK_LEG_MM,
134
142
  PDF_DEFAULT_FONT_SIZE_PT,
135
143
  PDF_DEFAULT_MARGIN_MM,
144
+ PDF_FOLD_MARKS,
136
145
  PDF_FOOTER_MARGIN_MM,
137
146
  PDF_HEADER_MARGIN_MM,
138
147
  PDF_ORIENTATIONS,
139
148
  PDF_PAGE_FORMATS,
140
149
  PDF_TABLE_STYLES,
150
+ type PdfFoldMarks,
141
151
  type PdfOrientation,
142
152
  type PdfPageFormat,
143
153
  type PdfTableStyle,
@@ -13,7 +13,7 @@ import {
13
13
  MAIL_LAYOUT_FONTS,
14
14
  MAIL_LAYOUT_WIDTHS,
15
15
  } from "./web/mail-layout-constants.ts";
16
- import { PDF_TABLE_STYLES } from "./web/pdf-constants.ts";
16
+ import { PDF_FOLD_MARKS, PDF_TABLE_STYLES } from "./web/pdf-constants.ts";
17
17
 
18
18
  // One or more kebab segments joined by ":" — notification templates are seeded
19
19
  // under their qualified name `feature:notify:name`.
@@ -123,6 +123,12 @@ const pdfLayoutMetaSchema = z
123
123
  textColor: hexColor.optional(),
124
124
  tableStyle: z.enum(PDF_TABLE_STYLES).optional(),
125
125
  tableHeaderBackground: hexColor.optional(),
126
+ tableLineColor: hexColor.optional(),
127
+ foldMarks: z.enum(PDF_FOLD_MARKS).optional(),
128
+ cornerMarks: z.boolean().optional(),
129
+ paperColor: hexColor.optional(),
130
+ headerOnFirstPage: z.boolean().optional(),
131
+ footerOnFirstPage: z.boolean().optional(),
126
132
  })
127
133
  .strict();
128
134
 
@@ -37,7 +37,7 @@ import {
37
37
  } from "./api.ts";
38
38
  import { collectDocumentResourceKeys } from "./compile-document-body.ts";
39
39
  import { parseStoredJson } from "./handlers/template-gates.ts";
40
- import { defaultPdfLayoutSlug } from "./handlers/tenant-settings.ts";
40
+ import { effectivePdfLayout } from "./handlers/tenant-settings.ts";
41
41
  import { validateTemplateDraft } from "./handlers/validate.query.ts";
42
42
  import {
43
43
  type LayoutRegions,
@@ -356,11 +356,20 @@ async function resolvePdfLayout(
356
356
  user: SessionUser,
357
357
  slug: string,
358
358
  locale: string,
359
+ resolvedForCaller: TemplateResource | null = null,
360
+ working = false,
359
361
  ): Promise<PreviewLayout | null> {
360
362
  const api = createTemplateResolverApi(ctx.db, ctx.registry);
361
363
  const find = async (tenantId: string): Promise<TemplateResource | null> => {
364
+ if (resolvedForCaller !== null && tenantId === user.tenantId) return resolvedForCaller;
362
365
  try {
363
- return await api.resolveLayout({ tenantId, slug, kind: "pdf-layout", locale });
366
+ return await api.resolveLayout({
367
+ tenantId,
368
+ slug,
369
+ kind: "pdf-layout",
370
+ locale,
371
+ working,
372
+ });
364
373
  } catch (e) {
365
374
  if (e instanceof TemplateNotFoundError) return null;
366
375
  throw e;
@@ -381,6 +390,17 @@ async function resolvePdfLayout(
381
390
  return { slug, scope: layout.scope, html, regions: readLayoutRegions(html) };
382
391
  }
383
392
 
393
+ async function resolvePreviewPdfLayout(
394
+ ctx: HandlerContext,
395
+ user: SessionUser,
396
+ ownSlug: string | undefined,
397
+ locale: string,
398
+ working: boolean,
399
+ ): Promise<PreviewLayout | null> {
400
+ const { slug, resolved } = await effectivePdfLayout(ctx, user.tenantId, ownSlug, locale, working);
401
+ return resolvePdfLayout(ctx, user, slug, locale, resolved, working);
402
+ }
403
+
384
404
  function missingResourceCheck(missing: readonly string[]): PreviewCheck {
385
405
  return {
386
406
  code: "resources_resolved",
@@ -454,11 +474,12 @@ async function renderDocumentPreview(
454
474
  html: content,
455
475
  text: null,
456
476
  attachments: [],
457
- layout: await resolvePdfLayout(
477
+ layout: await resolvePreviewPdfLayout(
458
478
  ctx,
459
479
  user,
460
- pdfMeta?.layoutSlug ?? (await defaultPdfLayoutSlug(ctx, user.tenantId, input.locale)),
480
+ pdfMeta?.layoutSlug,
461
481
  input.locale,
482
+ input.content !== undefined,
462
483
  ),
463
484
  sampleValues,
464
485
  checks: [missingResourceCheck(validation.warnings.map((w) => w.detail)), requiredCheck],
@@ -86,13 +86,17 @@ export const ACTIVE_TEMPLATE_STATUS = "active" satisfies TemplateStatus;
86
86
 
87
87
  export { HEX_COLOR_PATTERN } from "./mail-layout-constants.ts";
88
88
  export {
89
+ PDF_CORNER_MARK_INSET_MM,
90
+ PDF_CORNER_MARK_LEG_MM,
89
91
  PDF_DEFAULT_FONT_SIZE_PT,
90
92
  PDF_DEFAULT_MARGIN_MM,
93
+ PDF_FOLD_MARKS,
91
94
  PDF_FOOTER_MARGIN_MM,
92
95
  PDF_HEADER_MARGIN_MM,
93
96
  PDF_ORIENTATIONS,
94
97
  PDF_PAGE_FORMATS,
95
98
  PDF_TABLE_STYLES,
99
+ type PdfFoldMarks,
96
100
  type PdfOrientation,
97
101
  type PdfPageFormat,
98
102
  type PdfTableStyle,
@@ -1,3 +1,4 @@
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";
@@ -5,9 +6,10 @@ import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
5
6
  import type { DocumentFrameControl } from "./document-frame-control.ts";
6
7
  import { createFrameView, type FrameViewLabels } from "./document-frame-node-view.tsx";
7
8
  import { DocumentPrintEditing, loadDocumentEditorFonts } from "./document-print-decorations.ts";
8
- import { DocumentFrame } from "./document-print-style.ts";
9
+ import { DOCUMENT_IMAGE_ALIGNMENTS, DocumentFrame } from "./document-print-style.ts";
9
10
  import type { RepeatStripOptions } from "./document-repeat-strip.ts";
10
11
  import {
12
+ DOCUMENT_DATE_STYLES,
11
13
  DocumentButton,
12
14
  DocumentImages,
13
15
  DocumentPageBreak,
@@ -18,6 +20,7 @@ import {
18
20
  documentExtensions,
19
21
  } from "./document-schema.ts";
20
22
  import { readDocumentStepsAttribute } from "./document-steps.ts";
23
+ import { documentImageCss } from "./document-style-css.ts";
21
24
  import type { DocumentPrintMode, DocumentResourcePreview } from "./document-toolbar-blocks.ts";
22
25
 
23
26
  const DOCUMENT_RESOURCE_SIZE_TOKEN = "{size}";
@@ -70,6 +73,9 @@ function repeatRowListAt(doc: ProseMirrorNode, position: number | undefined): st
70
73
  return null;
71
74
  }
72
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
+
73
79
  // The chip is display only: the stored node carries just the name, so a
74
80
  // label never reaches the document.
75
81
  export function createVariableView(
@@ -90,6 +96,11 @@ export function createVariableView(
90
96
  const hasOwnLabel = label !== undefined && label !== "" && label !== name;
91
97
  dom.append(document.createTextNode(hasOwnLabel ? label : name));
92
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
+ }
93
104
  return { dom };
94
105
  };
95
106
  }
@@ -108,6 +119,53 @@ function createBlockLabel(text: string): HTMLSpanElement {
108
119
  return label;
109
120
  }
110
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
+
111
169
  function createResourceView(labels: DocumentEditorLabels): NodeViewRenderer {
112
170
  return ({ node }) => {
113
171
  const key = String(node.attrs["resource"]);
@@ -130,29 +188,7 @@ function createResourceView(labels: DocumentEditorLabels): NodeViewRenderer {
130
188
  dom.append(label);
131
189
  }
132
190
  if (hasImage) {
133
- const image = createElementWithClass("img", "max-w-[180px] rounded");
134
- image.src = preview.src;
135
- image.alt = typeof node.attrs["alt"] === "string" ? node.attrs["alt"] : key;
136
- dom.append(image);
137
- // An empty caption means "no caption", not the key.
138
- const caption = preview.caption ?? key;
139
- if (caption !== "") {
140
- const captionElement = createElementWithClass(
141
- "span",
142
- "whitespace-nowrap text-[11px]",
143
- caption.replace(` · ${DOCUMENT_RESOURCE_SIZE_TOKEN}`, ""),
144
- );
145
- // The size is only known once the browser decoded the image (possibly already, from cache).
146
- const showSize = (): void => {
147
- captionElement.textContent = caption.replace(
148
- DOCUMENT_RESOURCE_SIZE_TOKEN,
149
- `${image.naturalWidth} × ${image.naturalHeight} px`,
150
- );
151
- };
152
- image.addEventListener("load", showSize);
153
- if (image.complete && image.naturalWidth > 0) showSize();
154
- dom.append(captionElement);
155
- }
191
+ appendResourceImage(dom, node, key, preview);
156
192
  } else {
157
193
  dom.append(
158
194
  createElementWithClass("span", "font-medium", labels.image),
@@ -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.
@@ -18,14 +18,18 @@ import {
18
18
  frameLocationOf,
19
19
  isSenderLine,
20
20
  } from "./document-frame-control.ts";
21
+ import { DOCUMENT_TABLE_ALIGNMENTS, readRowLineAttributes } from "./document-print-style.ts";
21
22
  import { type RepeatStripOptions, repeatStripDecorations } from "./document-repeat-strip.ts";
22
23
  import {
23
24
  addressParagraphCss,
24
25
  DOCUMENT_LINE_VARIABLE,
25
26
  documentBlockStyleCss,
26
27
  documentCellStyleCss,
28
+ documentDividerCss,
29
+ documentTableCss,
27
30
  documentTextStyleCss,
28
31
  PARAGRAPH_DEFAULT_LINE_HEIGHT,
32
+ resolveRowEdges,
29
33
  } from "./document-style-css.ts";
30
34
 
31
35
  // Metric-compatible web fonts (@fontsource) stand in for the print service's installed fonts.
@@ -97,16 +101,61 @@ function nodeDecoration(
97
101
  .join(";");
98
102
  return style === "" ? null : Decoration.node(from, to, { style });
99
103
  }
100
- if (CELL_NODES.includes(name)) {
101
- const style = documentCellStyleCss({ background: stringOrNull(node.attrs["background"]) });
104
+ if (name === "divider") {
105
+ const style = documentDividerCss({
106
+ color: stringOrNull(node.attrs["color"]),
107
+ weightPt: numberOrNull(node.attrs["weightPt"]),
108
+ });
102
109
  return style === "" ? null : Decoration.node(from, to, { style });
103
110
  }
104
- if (name === "table" && node.attrs["borders"] === "none") {
105
- return Decoration.node(from, to, { "data-borders": "none" });
106
- }
107
111
  return null;
108
112
  }
109
113
 
114
+ // Cell padding, outer-column insets and row rules depend on the table and row around a cell, so
115
+ // the table decorates its own cells; the rules mirror the PDF compile's edge resolution.
116
+ function tableDecorations(table: ProseMirrorNode, from: number): Decoration[] {
117
+ const align = table.attrs["align"];
118
+ const tableStyle = documentTableCss({
119
+ widthMm: numberOrNull(table.attrs["widthMm"]),
120
+ align: isOneOf(DOCUMENT_TABLE_ALIGNMENTS, align) ? align : null,
121
+ });
122
+ const decorations: Decoration[] = [];
123
+ const tableAttrs: Record<string, string> = {
124
+ ...(table.attrs["borders"] === "none" ? { "data-borders": "none" } : {}),
125
+ ...(tableStyle === "" ? {} : { style: tableStyle }),
126
+ };
127
+ if (Object.keys(tableAttrs).length > 0) {
128
+ decorations.push(Decoration.node(from, from + table.nodeSize, tableAttrs));
129
+ }
130
+ const paddingMm = numberOrNull(table.attrs["cellPaddingMm"]);
131
+ const rows: { node: ProseMirrorNode; pos: number }[] = [];
132
+ table.forEach((row, offset) => {
133
+ rows.push({ node: row, pos: from + 1 + offset });
134
+ });
135
+ const edges = resolveRowEdges(
136
+ rows.map((row) => ({
137
+ ...readRowLineAttributes(row.node.attrs),
138
+ repeats: typeof row.node.attrs["each"] === "string",
139
+ })),
140
+ );
141
+ rows.forEach((row, rowIndex) => {
142
+ row.node.forEach((cell, offset, cellIndex) => {
143
+ if (!CELL_NODES.includes(cell.type.name)) return;
144
+ const style = documentCellStyleCss({
145
+ background: stringOrNull(cell.attrs["background"]),
146
+ paddingMm,
147
+ isFirstInRow: cellIndex === 0,
148
+ isLastInRow: cellIndex === row.node.childCount - 1,
149
+ edges: edges[rowIndex],
150
+ });
151
+ if (style === "") return;
152
+ const cellFrom = row.pos + 1 + offset;
153
+ decorations.push(Decoration.node(cellFrom, cellFrom + cell.nodeSize, { style }));
154
+ });
155
+ });
156
+ return decorations;
157
+ }
158
+
110
159
  // Frames are not rebuilt by the selection alone, so the selected one is marked by a decoration the
111
160
  // node view styles; the same location drives the side panel.
112
161
  function buildDecorations(
@@ -122,6 +171,7 @@ function buildDecorations(
122
171
  Decoration.node(pos, pos + node.nodeSize, { [FRAME_SELECTED_ATTRIBUTE]: "" }),
123
172
  );
124
173
  }
174
+ if (node.type.name === "table") decorations.push(...tableDecorations(node, pos));
125
175
  const decoration = node.isInline
126
176
  ? textStyleDecoration(node, pos)
127
177
  : nodeDecoration(node, pos, parent, index);
@@ -3,12 +3,13 @@
3
3
  // the sanitizer keeps its guarantee that no CSS comes from the input; compile-document-styles.ts
4
4
  // turns the validated values into CSS. The read* functions are the single place that validates a
5
5
  // raw attribute, used by the tiptap parse rules here and by the compile step.
6
- import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
6
+ import { isOneOf, isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
7
7
  import { Extension, Mark, mergeAttributes, Node } from "@tiptap/core";
8
8
  import { DOCUMENT_FONTS, type DocumentFont } from "./document-fonts.ts";
9
9
  import type {
10
10
  DocumentBlockStyle,
11
11
  DocumentFrameBox,
12
+ DocumentRowLine,
12
13
  DocumentTextStyle,
13
14
  } from "./document-style-css.ts";
14
15
  import { HEX_COLOR_PATTERN } from "./mail-layout-constants.ts";
@@ -18,6 +19,16 @@ export const LINE_HEIGHT_RANGE = { min: 0.8, max: 3 } as const;
18
19
  export const PARAGRAPH_SPACE_PT_RANGE = { min: 0, max: 200 } as const;
19
20
  export const FRAME_MM_RANGE = { min: 0, max: 1000 } as const;
20
21
  export const COLWIDTH_PX_RANGE = { min: 1, max: 5000 } as const;
22
+ export const IMAGE_WIDTH_MM_RANGE = { min: 0.1, max: 210 } as const;
23
+ export const DIVIDER_WEIGHT_PT_RANGE = { min: 0.25, max: 4 } as const;
24
+ export const CELL_PADDING_MM_RANGE = { min: 0, max: 10 } as const;
25
+ export const TABLE_WIDTH_MM_RANGE = IMAGE_WIDTH_MM_RANGE;
26
+
27
+ export const DOCUMENT_IMAGE_ALIGNMENTS = ["left", "center", "right"] as const;
28
+ export type DocumentImageAlignment = (typeof DOCUMENT_IMAGE_ALIGNMENTS)[number];
29
+
30
+ export const DOCUMENT_TABLE_ALIGNMENTS = DOCUMENT_IMAGE_ALIGNMENTS;
31
+ export type DocumentTableAlignment = DocumentImageAlignment;
21
32
 
22
33
  export const FRAME_PRESETS = ["address", "text"] as const;
23
34
  export type DocumentFramePreset = (typeof FRAME_PRESETS)[number];
@@ -80,6 +91,63 @@ export function readFrameAttributes(element: AttributeSource): DocumentFrameAttr
80
91
  };
81
92
  }
82
93
 
94
+ export function readImageWidthMm(element: AttributeSource): number | null {
95
+ return readNumber(element.getAttribute("data-width-mm"), IMAGE_WIDTH_MM_RANGE);
96
+ }
97
+
98
+ export function readImageAlign(element: AttributeSource): DocumentImageAlignment | null {
99
+ const align = element.getAttribute("data-align");
100
+ return isOneOf(DOCUMENT_IMAGE_ALIGNMENTS, align) ? align : null;
101
+ }
102
+
103
+ export function readDividerColor(element: AttributeSource): string | null {
104
+ return readHexColor(element.getAttribute("data-color"));
105
+ }
106
+
107
+ export function readDividerWeightPt(element: AttributeSource): number | null {
108
+ return readNumber(element.getAttribute("data-weight-pt"), DIVIDER_WEIGHT_PT_RANGE);
109
+ }
110
+
111
+ export function readCellPaddingMm(element: AttributeSource): number | null {
112
+ return readNumber(element.getAttribute("data-cell-padding-mm"), CELL_PADDING_MM_RANGE);
113
+ }
114
+
115
+ export function readTableWidthMm(element: AttributeSource): number | null {
116
+ return readNumber(element.getAttribute("data-table-width-mm"), TABLE_WIDTH_MM_RANGE);
117
+ }
118
+
119
+ export function readTableAlign(element: AttributeSource): DocumentTableAlignment | null {
120
+ const align = element.getAttribute("data-table-align");
121
+ return isOneOf(DOCUMENT_TABLE_ALIGNMENTS, align) ? align : null;
122
+ }
123
+
124
+ export const ROW_LINE_ABOVE_ATTRIBUTE = "data-line-above";
125
+ export const ROW_LINE_BELOW_ATTRIBUTE = "data-line-below";
126
+
127
+ // Serialized as "#rrggbb 0.75": one attribute per edge keeps the data-* allowlist small.
128
+ export function readRowLine(element: AttributeSource, attribute: string): DocumentRowLine | null {
129
+ const raw = element.getAttribute(attribute);
130
+ if (raw === null) return null;
131
+ const [color, weight, ...rest] = raw.split(" ");
132
+ const weightPt = readNumber(weight ?? null, DIVIDER_WEIGHT_PT_RANGE);
133
+ const hexColor = readHexColor(color ?? null);
134
+ return rest.length === 0 && hexColor !== null && weightPt !== null
135
+ ? { color: hexColor, weightPt }
136
+ : null;
137
+ }
138
+
139
+ function isRowLine(value: unknown): value is DocumentRowLine {
140
+ if (!isPlainObject(value)) return false;
141
+ const { color, weightPt } = value;
142
+ return (
143
+ typeof color === "string" &&
144
+ HEX_COLOR_PATTERN.test(color) &&
145
+ typeof weightPt === "number" &&
146
+ weightPt >= DIVIDER_WEIGHT_PT_RANGE.min &&
147
+ weightPt <= DIVIDER_WEIGHT_PT_RANGE.max
148
+ );
149
+ }
150
+
83
151
  export function readCellBackground(element: AttributeSource): string | null {
84
152
  return readHexColor(element.getAttribute("data-background"));
85
153
  }
@@ -168,7 +236,7 @@ export const DocumentBlockStyleAttributes = Extension.create({
168
236
  },
169
237
  });
170
238
 
171
- export const documentTableBordersAttribute = {
239
+ export const documentTablePrintAttributes = {
172
240
  borders: {
173
241
  default: null,
174
242
  parseHTML: (element: AttributeSource) =>
@@ -176,8 +244,59 @@ export const documentTableBordersAttribute = {
176
244
  renderHTML: (attributes: Record<string, unknown>) =>
177
245
  attributes["borders"] === "none" ? { "data-borders": "none" } : {},
178
246
  },
247
+ cellPaddingMm: {
248
+ default: null,
249
+ parseHTML: (element: AttributeSource) => readCellPaddingMm(element),
250
+ renderHTML: (attributes: Record<string, unknown>) => {
251
+ const value: unknown = attributes["cellPaddingMm"];
252
+ return typeof value === "number" ? { "data-cell-padding-mm": String(value) } : {};
253
+ },
254
+ },
255
+ widthMm: {
256
+ default: null,
257
+ parseHTML: (element: AttributeSource) => readTableWidthMm(element),
258
+ renderHTML: (attributes: Record<string, unknown>) => {
259
+ const value: unknown = attributes["widthMm"];
260
+ return typeof value === "number" ? { "data-table-width-mm": String(value) } : {};
261
+ },
262
+ },
263
+ align: {
264
+ default: null,
265
+ parseHTML: (element: AttributeSource) => readTableAlign(element),
266
+ renderHTML: (attributes: Record<string, unknown>) => {
267
+ const value: unknown = attributes["align"];
268
+ return isOneOf(DOCUMENT_TABLE_ALIGNMENTS, value) ? { "data-table-align": value } : {};
269
+ },
270
+ },
271
+ };
272
+
273
+ function rowLineAttribute(attribute: string, key: string) {
274
+ return {
275
+ default: null,
276
+ parseHTML: (element: AttributeSource) => readRowLine(element, attribute),
277
+ renderHTML: (attributes: Record<string, unknown>) => {
278
+ const line: unknown = attributes[key];
279
+ return isRowLine(line) ? { [attribute]: `${line.color} ${line.weightPt}` } : {};
280
+ },
281
+ };
282
+ }
283
+
284
+ export const documentRowLineAttributes = {
285
+ lineAbove: rowLineAttribute(ROW_LINE_ABOVE_ATTRIBUTE, "lineAbove"),
286
+ lineBelow: rowLineAttribute(ROW_LINE_BELOW_ATTRIBUTE, "lineBelow"),
179
287
  };
180
288
 
289
+ export function readRowLineAttributes(attrs: Readonly<Record<string, unknown>>): {
290
+ readonly lineAbove: DocumentRowLine | null;
291
+ readonly lineBelow: DocumentRowLine | null;
292
+ } {
293
+ const { lineAbove, lineBelow } = attrs;
294
+ return {
295
+ lineAbove: isRowLine(lineAbove) ? lineAbove : null,
296
+ lineBelow: isRowLine(lineBelow) ? lineBelow : null,
297
+ };
298
+ }
299
+
181
300
  export const documentCellPrintAttributes = {
182
301
  background: {
183
302
  default: null,
@@ -201,6 +320,22 @@ export const documentCellPrintAttributes = {
201
320
  },
202
321
  };
203
322
 
323
+ export function imagePrintHtmlAttributes(attrs: Record<string, unknown>): Record<string, string> {
324
+ const { widthMm, align } = attrs;
325
+ return {
326
+ ...(typeof widthMm === "number" ? { "data-width-mm": String(widthMm) } : {}),
327
+ ...(isOneOf(DOCUMENT_IMAGE_ALIGNMENTS, align) ? { "data-align": align } : {}),
328
+ };
329
+ }
330
+
331
+ export function dividerPrintHtmlAttributes(attrs: Record<string, unknown>): Record<string, string> {
332
+ const { color, weightPt } = attrs;
333
+ return {
334
+ ...(typeof color === "string" && HEX_COLOR_PATTERN.test(color) ? { "data-color": color } : {}),
335
+ ...(typeof weightPt === "number" ? { "data-weight-pt": String(weightPt) } : {}),
336
+ };
337
+ }
338
+
204
339
  export const DocumentFrame = Node.create({
205
340
  name: "documentFrame",
206
341
  group: "block",
@@ -1,6 +1,7 @@
1
1
  import type { Editor } from "@tiptap/core";
2
2
  import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
3
3
  import { Decoration } from "@tiptap/pm/view";
4
+ import { repeatListsOf, toggleRepeatHeaderAt } from "./document-tiptap-helpers.ts";
4
5
 
5
6
  export type RepeatStripOptions = {
6
7
  readonly label: (listNames: readonly string[]) => string;
@@ -19,31 +20,6 @@ const BUTTON_CLASS =
19
20
  const BUTTON_OFF_CLASS = `${BUTTON_CLASS} border-input bg-card text-foreground`;
20
21
  const BUTTON_ON_CLASS = `${BUTTON_CLASS} border-foreground bg-card text-foreground`;
21
22
 
22
- function repeatListsOf(table: ProseMirrorNode): string[] {
23
- const lists: string[] = [];
24
- table.forEach((row) => {
25
- const each: unknown = row.attrs["each"];
26
- if (typeof each === "string" && each !== "" && !lists.includes(each)) lists.push(each);
27
- });
28
- return lists;
29
- }
30
-
31
- function toggleHeaderAt(editor: Editor, rowPos: number): void {
32
- editor
33
- .chain()
34
- .focus()
35
- .command(({ tr }) => {
36
- const row = tr.doc.nodeAt(rowPos);
37
- if (row === null) return false;
38
- tr.setNodeMarkup(rowPos, undefined, {
39
- ...row.attrs,
40
- repeatHeader: row.attrs["repeatHeader"] !== true,
41
- });
42
- return true;
43
- })
44
- .run();
45
- }
46
-
47
23
  function createStrip(
48
24
  editor: Editor,
49
25
  label: string,
@@ -66,7 +42,7 @@ function createStrip(
66
42
  button.addEventListener("mousedown", (event) => event.preventDefault());
67
43
  button.addEventListener("click", () => {
68
44
  const pos = getPos();
69
- if (pos !== undefined) toggleHeaderAt(editor, pos - FIRST_ROW_OFFSET_FROM_WIDGET);
45
+ if (pos !== undefined) toggleRepeatHeaderAt(editor, pos - FIRST_ROW_OFFSET_FROM_WIDGET);
70
46
  });
71
47
  strip.append(name, button);
72
48
  return strip;