@cosmicdrift/kumiko-samples 0.418.0 → 0.419.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 (79) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +6 -1
  3. package/packages/bundled-features/src/template-resolver/changes.json +38 -0
  4. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +3 -8
  5. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +102 -0
  6. package/packages/bundled-features/src/template-resolver/document-frames.ts +25 -0
  7. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +568 -0
  8. package/packages/bundled-features/src/template-resolver/document-ops.ts +136 -126
  9. package/packages/bundled-features/src/template-resolver/document-print-only.ts +41 -0
  10. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +41 -19
  11. package/packages/bundled-features/src/template-resolver/feature.ts +15 -0
  12. package/packages/bundled-features/src/template-resolver/handlers/apply-layout.write.ts +137 -0
  13. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +87 -0
  14. package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +2 -2
  15. package/packages/bundled-features/src/template-resolver/handlers/document-blocks.query.ts +13 -8
  16. package/packages/bundled-features/src/template-resolver/handlers/document-region.ts +47 -0
  17. package/packages/bundled-features/src/template-resolver/handlers/failure-reason.ts +13 -0
  18. package/packages/bundled-features/src/template-resolver/handlers/import-bundle-system.write.ts +3 -0
  19. package/packages/bundled-features/src/template-resolver/handlers/layout-source.query.ts +17 -5
  20. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +16 -4
  21. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +19 -6
  22. package/packages/bundled-features/src/template-resolver/handlers/publish-templates.write.ts +69 -0
  23. package/packages/bundled-features/src/template-resolver/handlers/set.write.ts +7 -0
  24. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +15 -3
  25. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +122 -0
  26. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +25 -10
  27. package/packages/bundled-features/src/template-resolver/handlers/upsert-system.write.ts +7 -3
  28. package/packages/bundled-features/src/template-resolver/handlers/usage.query.ts +131 -18
  29. package/packages/bundled-features/src/template-resolver/handlers/validate.query.ts +10 -0
  30. package/packages/bundled-features/src/template-resolver/i18n.ts +3 -0
  31. package/packages/bundled-features/src/template-resolver/index.ts +29 -0
  32. package/packages/bundled-features/src/template-resolver/layout-regions.ts +54 -16
  33. package/packages/bundled-features/src/template-resolver/print-document.ts +3 -1
  34. package/packages/bundled-features/src/template-resolver/seeding.ts +4 -0
  35. package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +11 -1
  36. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +37 -1
  37. package/packages/bundled-features/src/template-resolver/template-meta.ts +25 -6
  38. package/packages/bundled-features/src/template-resolver/template-preview.ts +6 -7
  39. package/packages/bundled-features/src/template-resolver/template-validation.ts +10 -3
  40. package/packages/bundled-features/src/template-resolver/web/constants.ts +29 -0
  41. package/packages/bundled-features/src/template-resolver/web/document-blocks.ts +5 -0
  42. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +34 -2
  43. package/packages/bundled-features/src/template-resolver/web/document-editor-fonts.ts +13 -0
  44. package/packages/bundled-features/src/template-resolver/web/document-fonts.ts +21 -0
  45. package/packages/bundled-features/src/template-resolver/web/document-frame-control.ts +428 -0
  46. package/packages/bundled-features/src/template-resolver/web/document-frame-node-view.tsx +207 -0
  47. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +196 -0
  48. package/packages/bundled-features/src/template-resolver/web/document-print-defaults.ts +59 -0
  49. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +246 -0
  50. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +104 -0
  51. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +29 -9
  52. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +107 -0
  53. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +24 -2
  54. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +66 -7
  55. package/packages/bundled-features/src/template-resolver/web/document-tiptap-context.ts +13 -1
  56. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +24 -4
  57. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +149 -4
  58. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +290 -10
  59. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +90 -8
  60. package/packages/bundled-features/src/template-resolver/web/document-toolbar-blocks.ts +20 -0
  61. package/packages/bundled-features/src/template-resolver/web/fontsource-css.d.ts +2 -0
  62. package/packages/bundled-features/src/template-resolver/web/i18n.ts +28 -0
  63. package/packages/bundled-features/src/template-resolver/web/index.ts +34 -0
  64. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +6 -0
  65. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +7 -0
  66. package/packages/bundled-features/src/template-resolver/web/use-document-tiptap-model.ts +74 -5
  67. package/packages/bundled-features/src/tenant/company-config.ts +48 -0
  68. package/packages/bundled-features/src/tenant/feature.ts +11 -0
  69. package/packages/bundled-features/src/tenant/i18n.ts +14 -0
  70. package/samples/apps/ui-walkthrough/src/app/auth-constants.ts +51 -0
  71. package/samples/apps/ui-walkthrough/src/app/seed-print-editor-tenants.ts +118 -0
  72. package/samples/apps/ui-walkthrough/src/app/seed-templates.ts +2 -0
  73. package/samples/apps/ui-walkthrough/src/app/server.ts +9 -1
  74. package/samples/apps/ui-walkthrough/src/app/template-seed-data.ts +27 -1
  75. package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
  76. package/samples/apps/use-all-bundled/feature-manifest.json +236 -0
  77. package/samples/recipes/pdf-letterhead/README.md +23 -0
  78. package/samples/recipes/pdf-letterhead/package.json +12 -0
  79. package/samples/recipes/pdf-letterhead/src/letterhead.ts +92 -0
@@ -0,0 +1,196 @@
1
+ // Editor-only rendering of the print model: free values (font, size, spacing, cell colours, table
2
+ // borders) are drawn as ProseMirror decorations, so they never reach getHTML. The same
3
+ // document-style-css builders as the PDF compile keep the editor and the print in step.
4
+
5
+ import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
6
+ import { Extension } from "@tiptap/core";
7
+ import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
8
+ import { Plugin, PluginKey, type Selection } from "@tiptap/pm/state";
9
+ import { Decoration, DecorationSet } from "@tiptap/pm/view";
10
+ import type { DocumentFont } from "./document-fonts.ts";
11
+ import { DOCUMENT_FONTS } from "./document-fonts.ts";
12
+ import type { DocumentFrameControl, FrameLocation } from "./document-frame-control.ts";
13
+ import {
14
+ buildFrameControl,
15
+ FRAME_NODE_NAME,
16
+ FRAME_SELECTED_ATTRIBUTE,
17
+ frameFlowBottomMm,
18
+ frameLocationOf,
19
+ isSenderLine,
20
+ } from "./document-frame-control.ts";
21
+ import { type RepeatStripOptions, repeatStripDecorations } from "./document-repeat-strip.ts";
22
+ import {
23
+ addressParagraphCss,
24
+ DOCUMENT_LINE_VARIABLE,
25
+ documentBlockStyleCss,
26
+ documentCellStyleCss,
27
+ documentTextStyleCss,
28
+ PARAGRAPH_DEFAULT_LINE_HEIGHT,
29
+ } from "./document-style-css.ts";
30
+
31
+ // Metric-compatible web fonts (@fontsource) stand in for the print service's installed fonts.
32
+ const EDITOR_FONT_STACKS: Readonly<Record<DocumentFont, string>> = {
33
+ arial: 'Arimo,"Liberation Sans",Arial,sans-serif',
34
+ times: 'Tinos,"Liberation Serif","Times New Roman",serif',
35
+ courier: 'Cousine,"Liberation Mono","Courier New",monospace',
36
+ calibri: "Carlito,Calibri,sans-serif",
37
+ cambria: "Caladea,Cambria,serif",
38
+ };
39
+
40
+ // Fonts are cosmetic: the stacks fall back to system fonts when the chunk fails to load.
41
+ export function loadDocumentEditorFonts(): Promise<unknown> {
42
+ return import("./document-editor-fonts.ts").catch(() => undefined);
43
+ }
44
+
45
+ const TEXT_STYLE_MARK = "documentTextStyle";
46
+ const BLOCK_STYLE_NODES: readonly string[] = ["paragraph", "heading"];
47
+ const CELL_NODES: readonly string[] = ["tableCell", "tableHeader"];
48
+
49
+ function numberOrNull(value: unknown): number | null {
50
+ return typeof value === "number" ? value : null;
51
+ }
52
+
53
+ function stringOrNull(value: unknown): string | null {
54
+ return typeof value === "string" ? value : null;
55
+ }
56
+
57
+ function textStyleDecoration(node: ProseMirrorNode, from: number): Decoration | null {
58
+ const mark = node.marks.find((candidate) => candidate.type.name === TEXT_STYLE_MARK);
59
+ if (mark === undefined) return null;
60
+ const font = mark.attrs["font"];
61
+ const declarations = [
62
+ documentTextStyleCss({
63
+ color: stringOrNull(mark.attrs["color"]),
64
+ sizePt: numberOrNull(mark.attrs["sizePt"]),
65
+ }),
66
+ isOneOf(DOCUMENT_FONTS, font) ? `font-family:${EDITOR_FONT_STACKS[font]}` : "",
67
+ ].filter((part) => part !== "");
68
+ return declarations.length === 0
69
+ ? null
70
+ : Decoration.inline(from, from + node.nodeSize, { style: declarations.join(";") });
71
+ }
72
+
73
+ function isAddressFrame(node: ProseMirrorNode | null): boolean {
74
+ return node?.type.name === FRAME_NODE_NAME && node.attrs["preset"] === "address";
75
+ }
76
+
77
+ function nodeDecoration(
78
+ node: ProseMirrorNode,
79
+ from: number,
80
+ parent: ProseMirrorNode | null,
81
+ index: number,
82
+ ): Decoration | null {
83
+ const name = node.type.name;
84
+ const to = from + node.nodeSize;
85
+ if (BLOCK_STYLE_NODES.includes(name)) {
86
+ const style = [
87
+ documentBlockStyleCss({
88
+ lineHeight: numberOrNull(node.attrs["lineHeight"]),
89
+ spaceBeforePt: numberOrNull(node.attrs["spaceBeforePt"]),
90
+ spaceAfterPt: numberOrNull(node.attrs["spaceAfterPt"]),
91
+ }),
92
+ name === "paragraph" && isAddressFrame(parent)
93
+ ? addressParagraphCss(index === 0 && isSenderLine(node))
94
+ : "",
95
+ ]
96
+ .filter((part) => part !== "")
97
+ .join(";");
98
+ return style === "" ? null : Decoration.node(from, to, { style });
99
+ }
100
+ if (CELL_NODES.includes(name)) {
101
+ const style = documentCellStyleCss({ background: stringOrNull(node.attrs["background"]) });
102
+ return style === "" ? null : Decoration.node(from, to, { style });
103
+ }
104
+ if (name === "table" && node.attrs["borders"] === "none") {
105
+ return Decoration.node(from, to, { "data-borders": "none" });
106
+ }
107
+ return null;
108
+ }
109
+
110
+ // Frames are not rebuilt by the selection alone, so the selected one is marked by a decoration the
111
+ // node view styles; the same location drives the side panel.
112
+ function buildDecorations(
113
+ doc: ProseMirrorNode,
114
+ selection: Selection,
115
+ extra: readonly Decoration[],
116
+ ): DecorationSet {
117
+ const decorations: Decoration[] = [];
118
+ const selectedFrame = frameLocationOf(selection);
119
+ doc.descendants((node, pos, parent, index) => {
120
+ if (node.type.name === FRAME_NODE_NAME && selectedFrame?.pos === pos) {
121
+ decorations.push(
122
+ Decoration.node(pos, pos + node.nodeSize, { [FRAME_SELECTED_ATTRIBUTE]: "" }),
123
+ );
124
+ }
125
+ const decoration = node.isInline
126
+ ? textStyleDecoration(node, pos)
127
+ : nodeDecoration(node, pos, parent, index);
128
+ if (decoration !== null) decorations.push(decoration);
129
+ });
130
+ return DecorationSet.create(doc, [...decorations, ...extra]);
131
+ }
132
+
133
+ const FLOW_PADDING_CSS =
134
+ "padding-top:max(0px,calc((var(--frame-flow-bottom) - var(--page-margin-top-mm,0)) * var(--paper-mm,1mm)))";
135
+ // The paper's own text size and the shared paragraph defaults, so editor lines measure like the PDF's.
136
+ const PAGE_TEXT_CSS = `font-size:var(--paper-font-size,inherit);line-height:${PARAGRAPH_DEFAULT_LINE_HEIGHT};${DOCUMENT_LINE_VARIABLE}:calc(var(--paper-font-size) * ${PARAGRAPH_DEFAULT_LINE_HEIGHT})`;
137
+
138
+ export type DocumentPrintEditingOptions = {
139
+ /** Frames exist (PDF body): reserve the flow area below frames that push the text down. */
140
+ readonly frames: boolean;
141
+ readonly reportFrameControl: ((control: DocumentFrameControl | null) => void) | null;
142
+ /** Shows the table strip that switches the repeated header row; null renders none. */
143
+ readonly repeatStrip: RepeatStripOptions | null;
144
+ };
145
+
146
+ const DECORATION_KEY = new PluginKey<DecorationSet>("documentPrintDecorations");
147
+
148
+ export const DocumentPrintEditing = Extension.create<DocumentPrintEditingOptions>({
149
+ name: "documentPrintEditing",
150
+ addOptions() {
151
+ return { frames: false, reportFrameControl: null, repeatStrip: null };
152
+ },
153
+ addProseMirrorPlugins() {
154
+ const { frames, reportFrameControl, repeatStrip } = this.options;
155
+ const { editor } = this;
156
+ const stripOf = (doc: ProseMirrorNode): readonly Decoration[] =>
157
+ repeatStrip === null || !editor.options.editable
158
+ ? []
159
+ : repeatStripDecorations(doc, editor, repeatStrip);
160
+ const decorations = new Plugin<DecorationSet>({
161
+ key: DECORATION_KEY,
162
+ state: {
163
+ init: (_config, state) => buildDecorations(state.doc, state.selection, stripOf(state.doc)),
164
+ apply: (tr, previous) =>
165
+ tr.docChanged || tr.selectionSet
166
+ ? buildDecorations(tr.doc, tr.selection, stripOf(tr.doc))
167
+ : previous,
168
+ },
169
+ props: {
170
+ decorations: (state) => DECORATION_KEY.getState(state),
171
+ attributes: (state): Record<string, string> =>
172
+ frames
173
+ ? {
174
+ style: `--frame-flow-bottom:${frameFlowBottomMm(state.doc)};${FLOW_PADDING_CSS};${PAGE_TEXT_CSS}`,
175
+ }
176
+ : {},
177
+ },
178
+ });
179
+ if (!frames || reportFrameControl === null) return [decorations];
180
+ const reporter = new Plugin({
181
+ view: () => {
182
+ let last: FrameLocation | null = null;
183
+ return {
184
+ update: (view) => {
185
+ const location = view.editable ? frameLocationOf(view.state.selection) : null;
186
+ if (location?.pos === last?.pos && location?.node === last?.node) return;
187
+ last = location;
188
+ reportFrameControl(location === null ? null : buildFrameControl(editor, location));
189
+ },
190
+ destroy: () => reportFrameControl(null),
191
+ };
192
+ },
193
+ });
194
+ return [decorations, reporter];
195
+ },
196
+ });
@@ -0,0 +1,59 @@
1
+ import type { Translate } from "@cosmicdrift/kumiko-renderer/headless";
2
+ import { DOCUMENT_FONT_LABELS } from "./document-fonts.ts";
3
+ import { documentLinePt, PARAGRAPH_DEFAULT_LINE_HEIGHT } from "./document-style-css.ts";
4
+ import type { DocumentLayoutValues } from "./document-toolbar-blocks.ts";
5
+ import { PDF_DEFAULT_FONT_SIZE_PT } from "./pdf-constants.ts";
6
+
7
+ export type PrintDefaultLabels = {
8
+ readonly font: string;
9
+ readonly size: string;
10
+ readonly lineHeight: string;
11
+ readonly spaceBefore: string;
12
+ readonly spaceAfter: string;
13
+ readonly formatSize: (value: number) => string;
14
+ readonly formatLineHeight: (value: number) => string;
15
+ readonly formatSpaceBefore: (value: number) => string;
16
+ readonly formatSpaceAfter: (value: number) => string;
17
+ };
18
+
19
+ // The first option of every print select stands for "inherit"; it shows the value the layout
20
+ // gives, or the control's own name when the layout is not known (mail, no layout).
21
+ export function printDefaultLabelsOf(
22
+ t: Translate,
23
+ locale: string,
24
+ values: DocumentLayoutValues,
25
+ ): PrintDefaultLabels {
26
+ const formatNumber = (value: number): string => new Intl.NumberFormat(locale).format(value);
27
+ const formatSize = (value: number): string =>
28
+ t("documentDesigner.editor.defaultSize", { value: formatNumber(value) });
29
+ const formatLineHeight = (value: number): string =>
30
+ t("documentDesigner.editor.defaultLineHeight", { value: formatNumber(value) });
31
+ const formatSpaceBefore = (value: number): string =>
32
+ t("documentDesigner.editor.defaultSpaceBefore", { value: formatNumber(value) });
33
+ const formatSpaceAfter = (value: number): string =>
34
+ t("documentDesigner.editor.defaultSpaceAfter", { value: formatNumber(value) });
35
+ const known = <T>(value: T | undefined, label: (known: T) => string, fallbackKey: string) =>
36
+ value === undefined ? t(fallbackKey) : label(value);
37
+ return {
38
+ font: known(
39
+ values.fontFamily,
40
+ (font) => DOCUMENT_FONT_LABELS[font],
41
+ "documentDesigner.editor.font",
42
+ ),
43
+ size: known(values.fontSizePt, formatSize, "documentDesigner.editor.fontSize"),
44
+ // Without a layout value the paragraph still has the shared print default, so show that.
45
+ lineHeight: formatLineHeight(values.lineHeight ?? PARAGRAPH_DEFAULT_LINE_HEIGHT),
46
+ spaceBefore: known(
47
+ values.spaceBeforePt,
48
+ formatSpaceBefore,
49
+ "documentDesigner.editor.spaceBeforeShort",
50
+ ),
51
+ spaceAfter: formatSpaceAfter(
52
+ values.spaceAfterPt ?? documentLinePt(values.fontSizePt ?? PDF_DEFAULT_FONT_SIZE_PT),
53
+ ),
54
+ formatSize,
55
+ formatLineHeight,
56
+ formatSpaceBefore,
57
+ formatSpaceAfter,
58
+ };
59
+ }
@@ -0,0 +1,246 @@
1
+ // Print-only styling of the document model: character and paragraph styles, absolutely placed
2
+ // frames, table borders and cell backgrounds. Serialized as data-* attributes (never style) so
3
+ // the sanitizer keeps its guarantee that no CSS comes from the input; compile-document-styles.ts
4
+ // turns the validated values into CSS. The read* functions are the single place that validates a
5
+ // raw attribute, used by the tiptap parse rules here and by the compile step.
6
+ import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
7
+ import { Extension, Mark, mergeAttributes, Node } from "@tiptap/core";
8
+ import { DOCUMENT_FONTS, type DocumentFont } from "./document-fonts.ts";
9
+ import type {
10
+ DocumentBlockStyle,
11
+ DocumentFrameBox,
12
+ DocumentTextStyle,
13
+ } from "./document-style-css.ts";
14
+ import { HEX_COLOR_PATTERN } from "./mail-layout-constants.ts";
15
+
16
+ export const TEXT_SIZE_PT_RANGE = { min: 4, max: 72 } as const;
17
+ export const LINE_HEIGHT_RANGE = { min: 0.8, max: 3 } as const;
18
+ export const PARAGRAPH_SPACE_PT_RANGE = { min: 0, max: 200 } as const;
19
+ export const FRAME_MM_RANGE = { min: 0, max: 1000 } as const;
20
+ export const COLWIDTH_PX_RANGE = { min: 1, max: 5000 } as const;
21
+
22
+ export const FRAME_PRESETS = ["address", "text"] as const;
23
+ export type DocumentFramePreset = (typeof FRAME_PRESETS)[number];
24
+
25
+ type AttributeSource = { getAttribute(name: string): string | null };
26
+
27
+ type Range = { readonly min: number; readonly max: number };
28
+
29
+ const PLAIN_DECIMAL = /^\d+(\.\d+)?$/;
30
+
31
+ function readNumber(raw: string | null, range: Range): number | null {
32
+ if (raw === null || !PLAIN_DECIMAL.test(raw)) return null;
33
+ const value = Number(raw);
34
+ return Number.isFinite(value) && value >= range.min && value <= range.max ? value : null;
35
+ }
36
+
37
+ function readHexColor(raw: string | null): string | null {
38
+ return raw !== null && HEX_COLOR_PATTERN.test(raw) ? raw : null;
39
+ }
40
+
41
+ function readFont(raw: string | null): DocumentFont | null {
42
+ return isOneOf(DOCUMENT_FONTS, raw) ? raw : null;
43
+ }
44
+
45
+ export function readTextStyleAttributes(element: AttributeSource): Required<DocumentTextStyle> {
46
+ return {
47
+ color: readHexColor(element.getAttribute("data-color")),
48
+ font: readFont(element.getAttribute("data-font")),
49
+ sizePt: readNumber(element.getAttribute("data-size-pt"), TEXT_SIZE_PT_RANGE),
50
+ };
51
+ }
52
+
53
+ export function readBlockStyleAttributes(element: AttributeSource): Required<DocumentBlockStyle> {
54
+ return {
55
+ lineHeight: readNumber(element.getAttribute("data-line-height"), LINE_HEIGHT_RANGE),
56
+ spaceBeforePt: readNumber(element.getAttribute("data-space-before"), PARAGRAPH_SPACE_PT_RANGE),
57
+ spaceAfterPt: readNumber(element.getAttribute("data-space-after"), PARAGRAPH_SPACE_PT_RANGE),
58
+ };
59
+ }
60
+
61
+ export type DocumentFrameAttributes = DocumentFrameBox & {
62
+ readonly preset: DocumentFramePreset | null;
63
+ readonly reserveFlow: boolean;
64
+ };
65
+
66
+ export function readFrameAttributes(element: AttributeSource): DocumentFrameAttributes | null {
67
+ const xMm = readNumber(element.getAttribute("data-x"), FRAME_MM_RANGE);
68
+ const yMm = readNumber(element.getAttribute("data-y"), FRAME_MM_RANGE);
69
+ const widthMm = readNumber(element.getAttribute("data-width"), FRAME_MM_RANGE);
70
+ const heightMm = readNumber(element.getAttribute("data-height"), FRAME_MM_RANGE);
71
+ if (xMm === null || yMm === null || widthMm === null || heightMm === null) return null;
72
+ const preset = element.getAttribute("data-frame-preset");
73
+ return {
74
+ xMm,
75
+ yMm,
76
+ widthMm,
77
+ heightMm,
78
+ preset: isOneOf(FRAME_PRESETS, preset) ? preset : null,
79
+ reserveFlow: element.getAttribute("data-frame-flow") !== "over",
80
+ };
81
+ }
82
+
83
+ export function readCellBackground(element: AttributeSource): string | null {
84
+ return readHexColor(element.getAttribute("data-background"));
85
+ }
86
+
87
+ export function readColwidth(element: AttributeSource): number[] | null {
88
+ const raw = element.getAttribute("data-colwidth");
89
+ if (raw === null) return null;
90
+ const widths = raw.split(",").map((part) => readNumber(part.trim(), COLWIDTH_PX_RANGE));
91
+ return widths.length > 0 && widths.every((width): width is number => width !== null)
92
+ ? widths
93
+ : null;
94
+ }
95
+
96
+ function definedAttributes(entries: ReadonlyArray<readonly [string, unknown]>) {
97
+ return Object.fromEntries(
98
+ entries.filter(([, value]) => value !== null && value !== undefined && value !== false),
99
+ );
100
+ }
101
+
102
+ export const DocumentTextStyleMark = Mark.create({
103
+ name: "documentTextStyle",
104
+ addAttributes() {
105
+ return { color: { default: null }, font: { default: null }, sizePt: { default: null } };
106
+ },
107
+ parseHTML() {
108
+ return [
109
+ {
110
+ tag: "span[data-text-style]",
111
+ getAttrs: (element) => {
112
+ const style = readTextStyleAttributes(element);
113
+ return style.color === null && style.font === null && style.sizePt === null
114
+ ? false
115
+ : style;
116
+ },
117
+ },
118
+ ];
119
+ },
120
+ renderHTML({ mark }) {
121
+ return [
122
+ "span",
123
+ {
124
+ "data-text-style": "",
125
+ ...definedAttributes([
126
+ ["data-color", mark.attrs["color"]],
127
+ ["data-font", mark.attrs["font"]],
128
+ ["data-size-pt", mark.attrs["sizePt"]],
129
+ ]),
130
+ },
131
+ 0,
132
+ ];
133
+ },
134
+ });
135
+
136
+ function numberAttribute(attribute: string, range: Range, key: string) {
137
+ return {
138
+ default: null,
139
+ parseHTML: (element: AttributeSource) => readNumber(element.getAttribute(attribute), range),
140
+ renderHTML: (attributes: Record<string, unknown>) => {
141
+ const value: unknown = attributes[key];
142
+ return typeof value === "number" ? { [attribute]: String(value) } : {};
143
+ },
144
+ };
145
+ }
146
+
147
+ export const DocumentBlockStyleAttributes = Extension.create({
148
+ name: "documentBlockStyle",
149
+ addGlobalAttributes() {
150
+ return [
151
+ {
152
+ types: ["paragraph", "heading"],
153
+ attributes: {
154
+ lineHeight: numberAttribute("data-line-height", LINE_HEIGHT_RANGE, "lineHeight"),
155
+ spaceBeforePt: numberAttribute(
156
+ "data-space-before",
157
+ PARAGRAPH_SPACE_PT_RANGE,
158
+ "spaceBeforePt",
159
+ ),
160
+ spaceAfterPt: numberAttribute(
161
+ "data-space-after",
162
+ PARAGRAPH_SPACE_PT_RANGE,
163
+ "spaceAfterPt",
164
+ ),
165
+ },
166
+ },
167
+ ];
168
+ },
169
+ });
170
+
171
+ export const documentTableBordersAttribute = {
172
+ borders: {
173
+ default: null,
174
+ parseHTML: (element: AttributeSource) =>
175
+ element.getAttribute("data-borders") === "none" ? "none" : null,
176
+ renderHTML: (attributes: Record<string, unknown>) =>
177
+ attributes["borders"] === "none" ? { "data-borders": "none" } : {},
178
+ },
179
+ };
180
+
181
+ export const documentCellPrintAttributes = {
182
+ background: {
183
+ default: null,
184
+ parseHTML: (element: AttributeSource) => readCellBackground(element),
185
+ renderHTML: (attributes: Record<string, unknown>) => {
186
+ const background: unknown = attributes["background"];
187
+ return typeof background === "string" && HEX_COLOR_PATTERN.test(background)
188
+ ? { "data-background": background }
189
+ : {};
190
+ },
191
+ },
192
+ colwidth: {
193
+ default: null,
194
+ parseHTML: (element: AttributeSource) => readColwidth(element),
195
+ renderHTML: (attributes: Record<string, unknown>) => {
196
+ const widths: unknown = attributes["colwidth"];
197
+ return Array.isArray(widths) && widths.length > 0
198
+ ? { "data-colwidth": widths.join(",") }
199
+ : {};
200
+ },
201
+ },
202
+ };
203
+
204
+ export const DocumentFrame = Node.create({
205
+ name: "documentFrame",
206
+ group: "block",
207
+ content: "block+",
208
+ isolating: true,
209
+ defining: true,
210
+ addAttributes() {
211
+ return {
212
+ xMm: { default: 0 },
213
+ yMm: { default: 0 },
214
+ widthMm: { default: 0 },
215
+ heightMm: { default: 0 },
216
+ preset: { default: null },
217
+ reserveFlow: { default: true },
218
+ };
219
+ },
220
+ parseHTML() {
221
+ return [
222
+ {
223
+ tag: "div[data-frame]",
224
+ getAttrs: (element) => readFrameAttributes(element) ?? false,
225
+ },
226
+ ];
227
+ },
228
+ renderHTML({ node }) {
229
+ const { xMm, yMm, widthMm, heightMm, preset, reserveFlow } = node.attrs;
230
+ return [
231
+ "div",
232
+ mergeAttributes(
233
+ { "data-frame": "" },
234
+ {
235
+ "data-x": String(xMm),
236
+ "data-y": String(yMm),
237
+ "data-width": String(widthMm),
238
+ "data-height": String(heightMm),
239
+ },
240
+ isOneOf(FRAME_PRESETS, preset) ? { "data-frame-preset": preset } : {},
241
+ reserveFlow === false ? { "data-frame-flow": "over" } : {},
242
+ ),
243
+ 0,
244
+ ];
245
+ },
246
+ });
@@ -0,0 +1,104 @@
1
+ import type { Editor } from "@tiptap/core";
2
+ import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
3
+ import { Decoration } from "@tiptap/pm/view";
4
+
5
+ export type RepeatStripOptions = {
6
+ readonly label: (listNames: readonly string[]) => string;
7
+ readonly headerLabel: string;
8
+ };
9
+
10
+ // Table start + first row + first cell: the widget sits in front of the first cell's content.
11
+ const FIRST_CELL_CONTENT_OFFSET = 3;
12
+ const FIRST_ROW_OFFSET_FROM_WIDGET = FIRST_CELL_CONTENT_OFFSET - 1;
13
+
14
+ // Sits in the line of space the table gets above it (one document line), never taller than that.
15
+ const STRIP_CLASS =
16
+ "absolute bottom-full left-0 z-20 box-border flex h-[calc(var(--doc-line,1.25rem)-1px)] select-none items-center gap-2.5 whitespace-nowrap rounded-full border border-input bg-card pr-0.5 pl-2 text-[calc(var(--doc-line,1.25rem)*0.5)] font-normal uppercase leading-none tracking-wide text-muted-foreground";
17
+ const BUTTON_CLASS =
18
+ "cursor-pointer rounded-full border px-1.5 py-px text-[1em] font-medium leading-none normal-case tracking-normal";
19
+ const BUTTON_OFF_CLASS = `${BUTTON_CLASS} border-input bg-card text-foreground`;
20
+ const BUTTON_ON_CLASS = `${BUTTON_CLASS} border-foreground bg-card text-foreground`;
21
+
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
+ function createStrip(
48
+ editor: Editor,
49
+ label: string,
50
+ headerLabel: string,
51
+ headerRepeats: boolean,
52
+ getPos: () => number | undefined,
53
+ ): HTMLElement {
54
+ const strip = document.createElement("div");
55
+ strip.className = STRIP_CLASS;
56
+ strip.contentEditable = "false";
57
+ strip.setAttribute("data-testid", "document-repeat-strip");
58
+ const name = document.createElement("span");
59
+ name.textContent = label;
60
+ const button = document.createElement("button");
61
+ button.type = "button";
62
+ button.className = headerRepeats ? BUTTON_ON_CLASS : BUTTON_OFF_CLASS;
63
+ button.setAttribute("aria-pressed", String(headerRepeats));
64
+ button.setAttribute("data-testid", "document-repeat-header-toggle");
65
+ button.textContent = headerLabel;
66
+ button.addEventListener("mousedown", (event) => event.preventDefault());
67
+ button.addEventListener("click", () => {
68
+ const pos = getPos();
69
+ if (pos !== undefined) toggleHeaderAt(editor, pos - FIRST_ROW_OFFSET_FROM_WIDGET);
70
+ });
71
+ strip.append(name, button);
72
+ return strip;
73
+ }
74
+
75
+ // Editor-only: a widget never reaches getHTML or the PDF, and it is absolutely placed on the
76
+ // table's top edge so it takes no height.
77
+ export function repeatStripDecorations(
78
+ doc: ProseMirrorNode,
79
+ editor: Editor,
80
+ options: RepeatStripOptions,
81
+ ): Decoration[] {
82
+ const decorations: Decoration[] = [];
83
+ doc.descendants((node, pos) => {
84
+ if (node.type.name !== "table") return;
85
+ const lists = repeatListsOf(node);
86
+ const firstCellContent = node.firstChild?.firstChild;
87
+ if (lists.length === 0 || firstCellContent === null || firstCellContent === undefined) return;
88
+ const headerRepeats = node.firstChild?.attrs["repeatHeader"] === true;
89
+ const label = options.label(lists);
90
+ decorations.push(
91
+ Decoration.widget(
92
+ pos + FIRST_CELL_CONTENT_OFFSET,
93
+ (_view, getPos) => createStrip(editor, label, options.headerLabel, headerRepeats, getPos),
94
+ {
95
+ side: -1,
96
+ key: `repeat-strip:${label}:${headerRepeats}`,
97
+ ignoreSelection: true,
98
+ stopEvent: () => true,
99
+ },
100
+ ),
101
+ );
102
+ });
103
+ return decorations;
104
+ }
@@ -13,6 +13,13 @@ import {
13
13
  isAllowedDocumentUrlHref,
14
14
  isDocumentPlaceholderHref,
15
15
  } from "./document-link-policy.ts";
16
+ import {
17
+ DocumentBlockStyleAttributes,
18
+ DocumentFrame,
19
+ DocumentTextStyleMark,
20
+ documentCellPrintAttributes,
21
+ documentTableBordersAttribute,
22
+ } from "./document-print-style.ts";
16
23
  import { isDocumentReferenceName } from "./document-reference-name.ts";
17
24
  import { createDocumentStepsNode } from "./document-steps.ts";
18
25
  import { attributeParseRule } from "./tiptap-attribute-parse-rule.ts";
@@ -68,7 +75,7 @@ export const DocumentResource = Node.create({
68
75
  group: "block",
69
76
  atom: true,
70
77
  addAttributes() {
71
- return { resource: { default: null }, alt: { default: null } };
78
+ return { resource: { default: null }, alt: { default: null }, bleed: { default: false } };
72
79
  },
73
80
  parseHTML() {
74
81
  return [
@@ -77,7 +84,11 @@ export const DocumentResource = Node.create({
77
84
  getAttrs: (element) => {
78
85
  const resource = element.getAttribute("data-resource");
79
86
  if (resource === null || !isDocumentResourceKey(resource)) return false;
80
- return { resource, alt: element.getAttribute("alt") };
87
+ return {
88
+ resource,
89
+ alt: element.getAttribute("alt"),
90
+ bleed: element.hasAttribute("data-bleed"),
91
+ };
81
92
  },
82
93
  },
83
94
  ];
@@ -87,9 +98,11 @@ export const DocumentResource = Node.create({
87
98
  const alt = node.attrs["alt"];
88
99
  return [
89
100
  "img",
90
- alt === null || alt === undefined
91
- ? { "data-resource": node.attrs["resource"] }
92
- : { "data-resource": node.attrs["resource"], alt },
101
+ {
102
+ "data-resource": node.attrs["resource"],
103
+ ...(alt === null || alt === undefined ? {} : { alt }),
104
+ ...(node.attrs["bleed"] === true ? { "data-bleed": "" } : {}),
105
+ },
93
106
  ];
94
107
  },
95
108
  });
@@ -176,13 +189,16 @@ export const DocumentTableRow = TableRow.extend({
176
189
  });
177
190
 
178
191
  export const DocumentTable = Table.extend({
179
- renderHTML() {
180
- return ["table", ["tbody", 0]];
192
+ addAttributes() {
193
+ return { ...(this.parent?.() ?? {}), ...documentTableBordersAttribute };
194
+ },
195
+ renderHTML({ HTMLAttributes }) {
196
+ return ["table", HTMLAttributes, ["tbody", 0]];
181
197
  },
182
198
  });
183
199
 
184
200
  // Span attributes are rendered only when they differ from the default, and
185
- // colwidth (an editor-resize artefact) never, so `<td><p>x</p></td>` is the
201
+ // colwidth and background only when set, so `<td><p>x</p></td>` is the
186
202
  // canonical cell.
187
203
  function plainObjectOrEmpty(value: unknown): Record<string, unknown> {
188
204
  return isPlainObject(value) ? value : {};
@@ -203,8 +219,9 @@ function canonicalCellAttributes(attributes: Record<string, unknown>) {
203
219
  },
204
220
  colwidth: {
205
221
  ...plainObjectOrEmpty(attributes["colwidth"]),
206
- renderHTML: () => ({}),
222
+ ...documentCellPrintAttributes.colwidth,
207
223
  },
224
+ background: documentCellPrintAttributes.background,
208
225
  };
209
226
  }
210
227
 
@@ -347,4 +364,7 @@ export const documentExtensions: Extensions = [
347
364
  DocumentTextAlign,
348
365
  DocumentTextSize,
349
366
  DocumentCondition,
367
+ DocumentTextStyleMark,
368
+ DocumentBlockStyleAttributes,
369
+ DocumentFrame,
350
370
  ];