@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-samples",
3
- "version": "0.418.0",
3
+ "version": "0.420.0",
4
4
  "description": "Source trees of the Kumiko sample recipes, sample apps and bundled features in repo layout, for tooling such as few-shot corpus builds.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-bundled-features",
3
- "version": "0.418.0",
3
+ "version": "0.420.0",
4
4
  "description": "Built-in features — tenant, user, auth, delivery. The stuff you'd rewrite anyway, already typed.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -120,6 +120,7 @@
120
120
  "./shared/signed-token": "./src/shared/signed-token.ts",
121
121
  "./shared/stream-tenant-backfill": "./src/shared/stream-tenant-backfill.ts",
122
122
  "./shared/row-bound-grant": "./src/shared/row-bound-grant.ts",
123
+ "./shared/tenant-scoped-subject": "./src/shared/tenant-scoped-subject.ts",
123
124
  "./shared/mail-template-body": "./src/shared/mail-template-body.ts",
124
125
  "./shared/acknowledged-system-db": "./src/shared/acknowledged-system-db.ts",
125
126
  "./delivery": "./src/delivery/index.ts",
@@ -183,6 +184,11 @@
183
184
  "@cosmicdrift/kumiko-framework": "workspace:*",
184
185
  "@cosmicdrift/kumiko-renderer": "workspace:*",
185
186
  "@cosmicdrift/kumiko-types": "workspace:*",
187
+ "@fontsource/arimo": "^5.3.0",
188
+ "@fontsource/caladea": "^5.3.0",
189
+ "@fontsource/carlito": "^5.3.0",
190
+ "@fontsource/cousine": "^5.3.0",
191
+ "@fontsource/tinos": "^5.3.0",
186
192
  "@mollie/api-client": "^4.6.0",
187
193
  "@node-rs/argon2": "^2.2.2",
188
194
  "@tiptap/core": "^3.32.2",
@@ -606,6 +612,10 @@
606
612
  "types": "./dist/shared/row-bound-grant.d.ts",
607
613
  "default": "./dist/shared/row-bound-grant.js"
608
614
  },
615
+ "./shared/tenant-scoped-subject": {
616
+ "types": "./dist/shared/tenant-scoped-subject.d.ts",
617
+ "default": "./dist/shared/tenant-scoped-subject.js"
618
+ },
609
619
  "./shared/mail-template-body": {
610
620
  "types": "./dist/shared/mail-template-body.d.ts",
611
621
  "default": "./dist/shared/mail-template-body.js"
@@ -135,5 +135,11 @@ export {
135
135
  findTenantDestructionHoldProvider,
136
136
  type TenantDestructionHoldProvider,
137
137
  } from "./tenant-destruction-hold.ts";
138
+ export {
139
+ parseTenantScopedSubject,
140
+ peekTenantScopedSubject,
141
+ type TenantScopedSubject,
142
+ tenantScopedSubject,
143
+ } from "./tenant-scoped-subject.ts";
138
144
  export { type BurnResult, burnToken, unburnToken } from "./token-burn-store.ts";
139
145
  export { unprocessable } from "./unprocessable.ts";
@@ -0,0 +1,28 @@
1
+ import { isUuid, parseTenantId, type TenantId } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { peekTokenSubject } from "./signed-token.ts";
3
+
4
+ // An anonymous link holder arrives in the default tenant while the row lives in another tenant, so
5
+ // the tenant travels in the (signed) subject. "_" cannot appear in a UUID, and a grant subject
6
+ // must stay free of ":" and ".".
7
+ export type TenantScopedSubject = { readonly tenantId: TenantId; readonly rowId: string };
8
+
9
+ export function tenantScopedSubject(parts: {
10
+ readonly tenantId: string;
11
+ readonly rowId: string;
12
+ }): string {
13
+ return `${parts.tenantId}_${parts.rowId}`;
14
+ }
15
+
16
+ export function parseTenantScopedSubject(subject: string): TenantScopedSubject | null {
17
+ const [rawTenantId, rowId, ...rest] = subject.split("_");
18
+ const tenantId = parseTenantId(rawTenantId);
19
+ if (rest.length > 0 || tenantId === null || !isUuid(rowId)) return null;
20
+ return { tenantId, rowId };
21
+ }
22
+
23
+ // Reads the unverified subject only to pick the tenant to dispatch into; the grant is still
24
+ // verified against the row's current anchor there.
25
+ export function peekTenantScopedSubject(token: string): TenantScopedSubject | null {
26
+ const subject = peekTokenSubject(token);
27
+ return subject === null ? null : parseTenantScopedSubject(subject);
28
+ }
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.420.0",
4
+ "type": "fix",
5
+ "title": "Empty signature images are rejected on any background",
6
+ "detail": "The background of a signature image is now the dominant opaque colour of its border (within a small tolerance) instead of four identical corners, so an opaque blank image with one differing corner pixel no longer passes as signed. A `linkSecret` of only whitespace is refused when `authorizeSubject` is set. The tenant-scoped subject of the signing link is available as `tenantScopedSubject`, `parseTenantScopedSubject` and `peekTenantScopedSubject` in `@cosmicdrift/kumiko-bundled-features/shared/tenant-scoped-subject`."
7
+ },
2
8
  {
3
9
  "version": "0.418.0",
4
10
  "type": "fix",
@@ -41,7 +41,7 @@ import {
41
41
  } from "./web/constants.ts";
42
42
 
43
43
  export function createSignatureFeature(opts: SignatureOptions): FeatureDefinition {
44
- if (opts.authorizeSubject !== undefined && opts.linkSecret === "") {
44
+ if (opts.authorizeSubject !== undefined && opts.linkSecret.trim() === "") {
45
45
  throw new Error("authorizeSubject needs a non-empty linkSecret: it also seals the list cursor");
46
46
  }
47
47
  const signedInAccess = opts.access ?? DEFAULT_SIGNATURE_ACCESS;
@@ -1,10 +1,12 @@
1
- import { isUuid, parseTenantId, type TenantId } from "@cosmicdrift/kumiko-framework/engine";
1
+ import type { TenantId } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import type { Temporal } from "@cosmicdrift/kumiko-types/temporal";
3
3
  import {
4
- peekTokenSubject,
4
+ parseTenantScopedSubject,
5
+ peekTenantScopedSubject,
5
6
  type RowBoundGrantResult,
6
7
  redeemRowBoundGrant,
7
8
  signRowBoundGrant,
9
+ tenantScopedSubject,
8
10
  } from "../shared/index.ts";
9
11
  import { SIGNATURE_LINK_TTL_DAYS } from "./web/constants.ts";
10
12
 
@@ -13,30 +15,27 @@ type AnchorCommit = Parameters<typeof redeemRowBoundGrant>[0]["commitAnchor"];
13
15
  const SIGNATURE_LINK_PURPOSE = "signature-link";
14
16
  const MINUTES_PER_DAY = 24 * 60;
15
17
 
16
- // Signers live in the tenant of the request, but the anonymous link holder arrives in the default
17
- // tenant. The tenant therefore travels in the (signed) subject; "_" cannot appear in a UUID and the
18
- // subject must stay free of ":" and ".".
19
18
  export type SignatureLinkSubject = { readonly tenantId: TenantId; readonly signerId: string };
20
19
 
21
20
  export function signatureLinkSubject(parts: {
22
21
  readonly tenantId: string;
23
22
  readonly signerId: string;
24
23
  }): string {
25
- return `${parts.tenantId}_${parts.signerId}`;
24
+ return tenantScopedSubject({ tenantId: parts.tenantId, rowId: parts.signerId });
25
+ }
26
+
27
+ function toSignatureLinkSubject(
28
+ scoped: ReturnType<typeof parseTenantScopedSubject>,
29
+ ): SignatureLinkSubject | null {
30
+ return scoped === null ? null : { tenantId: scoped.tenantId, signerId: scoped.rowId };
26
31
  }
27
32
 
28
33
  export function parseSignatureLinkSubject(subject: string): SignatureLinkSubject | null {
29
- const [rawTenantId, signerId, ...rest] = subject.split("_");
30
- const tenantId = parseTenantId(rawTenantId);
31
- if (rest.length > 0 || tenantId === null || !isUuid(signerId)) return null;
32
- return { tenantId, signerId };
34
+ return toSignatureLinkSubject(parseTenantScopedSubject(subject));
33
35
  }
34
36
 
35
- // Reads the unverified subject only to pick the tenant to dispatch into; the grant is still
36
- // verified against the signer's current anchor there.
37
37
  export function peekSignatureLinkSubject(token: string): SignatureLinkSubject | null {
38
- const subject = peekTokenSubject(token);
39
- return subject === null ? null : parseSignatureLinkSubject(subject);
38
+ return toSignatureLinkSubject(peekTenantScopedSubject(token));
40
39
  }
41
40
 
42
41
  export function signSignatureLinkToken(args: {
@@ -5,6 +5,7 @@ const MAX_DIMENSION = 3000;
5
5
  const MIN_DIMENSION = 16;
6
6
  const MAX_PIXELS = 4_000_000;
7
7
  const MIN_INK_PIXELS = 20;
8
+ const BACKGROUND_TOLERANCE = 8;
8
9
 
9
10
  const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] as const;
10
11
  const COLOR_TYPE_GRAY_ALPHA = 4;
@@ -126,24 +127,44 @@ function countInkPixels(raw: Uint8Array, header: Header): number {
126
127
  const stride = header.width * bytesPerPixel + 1;
127
128
  const pixelStart = (row: number, column: number): number =>
128
129
  row * stride + 1 + column * bytesPerPixel;
129
- const background = pixelStart(0, 0);
130
130
  const alphaOf = (start: number): number => raw[start + bytesPerPixel - 1] ?? 0;
131
+ const pixelKey = (start: number): string => raw.subarray(start, start + bytesPerPixel).join(",");
132
+
133
+ const borderStarts: number[] = [];
134
+ for (let column = 0; column < header.width; column++) {
135
+ borderStarts.push(pixelStart(0, column), pixelStart(header.height - 1, column));
136
+ }
137
+ for (let row = 1; row < header.height - 1; row++) {
138
+ borderStarts.push(pixelStart(row, 0), pixelStart(row, header.width - 1));
139
+ }
140
+ const opaqueBorderStarts = borderStarts.filter((start) => alphaOf(start) > 0);
141
+ const colorCounts = new Map<string, { count: number; start: number }>();
142
+ for (const start of opaqueBorderStarts) {
143
+ const key = pixelKey(start);
144
+ const entry = colorCounts.get(key);
145
+ if (entry === undefined) colorCounts.set(key, { count: 1, start });
146
+ else entry.count++;
147
+ }
148
+ let background = -1;
149
+ let backgroundCount = 0;
150
+ for (const entry of colorCounts.values()) {
151
+ if (entry.count > backgroundCount) {
152
+ background = entry.start;
153
+ backgroundCount = entry.count;
154
+ }
155
+ }
131
156
  const colorMatchesBackground = (start: number): boolean => {
157
+ if (background < 0) return false;
132
158
  for (let i = 0; i < bytesPerPixel; i++) {
133
- if (raw[start + i] !== raw[background + i]) return false;
159
+ const difference = Math.abs((raw[start + i] ?? 0) - (raw[background + i] ?? 0));
160
+ if (difference > BACKGROUND_TOLERANCE) return false;
134
161
  }
135
162
  return true;
136
163
  };
137
- // Only four identical, opaque corners mean a solid background; a single opaque pixel could be a stroke.
138
- const corners = [
139
- background,
140
- pixelStart(0, header.width - 1),
141
- pixelStart(header.height - 1, 0),
142
- pixelStart(header.height - 1, header.width - 1),
143
- ];
144
- const hasSolidBackground = corners.every(
145
- (corner) => alphaOf(corner) > 0 && colorMatchesBackground(corner),
146
- );
164
+ // Most of the border must be opaque and alike for a solid background; a few opaque border pixels
165
+ // on a transparent canvas could be a stroke.
166
+ const nearBackgroundCount = opaqueBorderStarts.filter(colorMatchesBackground).length;
167
+ const hasSolidBackground = nearBackgroundCount * 2 > borderStarts.length;
147
168
  let ink = 0;
148
169
  for (let row = 0; row < header.height; row++) {
149
170
  for (let column = 0; column < header.width; column++) {
@@ -22,7 +22,7 @@ import {
22
22
  isServedByCollectionOnly,
23
23
  type TemplateDeliveryPolicy,
24
24
  } from "./template-delivery-policy.ts";
25
- import { activeVersionOf, isSystemAdmin, servedVersionOf } from "./template-draft.ts";
25
+ import { activeVersionOf, isSystemAdmin, servedVersionOf, toWorkingRow } from "./template-draft.ts";
26
26
  import { parseTemplateMeta, type TemplateMeta } from "./template-meta.ts";
27
27
  import type { ContentFormat, TemplateKind } from "./web/constants.ts";
28
28
  import { FALLBACK_LOCALE, SYSTEM_TENANT_ID } from "./web/constants.ts";
@@ -70,6 +70,8 @@ export type ResolveLayoutRequest = {
70
70
  readonly slug: string;
71
71
  readonly kind: LayoutKind;
72
72
  readonly locale: string;
73
+ /** Preview of unpublished content: the tenant's own layout counts in its working version (draft rows and open drafts). System layouts always resolve to their active version. */
74
+ readonly working?: boolean;
73
75
  };
74
76
 
75
77
  export type TemplateResolverApi = {
@@ -142,7 +144,7 @@ export function createTemplateResolverApi(
142
144
  throw new TemplateNotFoundError({ slug, kind, locale });
143
145
  },
144
146
 
145
- resolveLayout: async ({ tenantId, slug, kind, locale }) => {
147
+ resolveLayout: async ({ tenantId, slug, kind, locale, working = false }) => {
146
148
  for (const tid of [tenantId, SYSTEM_TENANT_ID]) {
147
149
  if (!isRowServed(deliveryPolicy, { tenantId: tid, kind, slug })) continue;
148
150
  const rows = await selectMany<TemplateResourceRow>(db, templateResourcesTable, {
@@ -150,7 +152,7 @@ export function createTemplateResolverApi(
150
152
  slug,
151
153
  kind,
152
154
  });
153
- const row = pickActiveLayoutRow(rows, locale);
155
+ const row = pickLayoutRow(rows, locale, working && tid !== SYSTEM_TENANT_ID ? tid : null);
154
156
  if (row !== null) return toPublic(row);
155
157
  }
156
158
  throw new TemplateNotFoundError({ slug, kind, locale });
@@ -230,13 +232,21 @@ export async function systemTemplateExists(
230
232
  return rows.length > 0;
231
233
  }
232
234
 
233
- function pickActiveLayoutRow(
235
+ // workingTenantId set: draft rows count too, each shown in its working version.
236
+ function pickLayoutRow(
234
237
  rows: readonly TemplateResourceRow[],
235
238
  locale: string,
239
+ workingTenantId: string | null,
236
240
  ): TemplateResourceRow | null {
237
- const active = rows
238
- .filter((row) => row.status === "active")
239
- .sort((a, b) => activeVersionOf(b) - activeVersionOf(a) || a.locale.localeCompare(b.locale));
241
+ const candidates =
242
+ workingTenantId === null
243
+ ? rows.filter((row) => row.status === "active")
244
+ : rows
245
+ .filter((row) => row.status === "active" || row.status === "draft")
246
+ .map((row) => toWorkingRow(row, workingTenantId));
247
+ const active = candidates.sort(
248
+ (a, b) => activeVersionOf(b) - activeVersionOf(a) || a.locale.localeCompare(b.locale),
249
+ );
240
250
  return (
241
251
  active.find((row) => row.locale === locale) ??
242
252
  active.find((row) => row.locale === FALLBACK_LOCALE) ??
@@ -1,4 +1,66 @@
1
1
  [
2
+ {
3
+ "version": "0.420.0",
4
+ "type": "improvement",
5
+ "title": "Editor controls for letter features",
6
+ "detail": "The content editor bubble gains image width in mm and left/center/right alignment (plus the existing full-bleed switch in layout regions) and a divider bubble with color and weight. The table toolbar gets add-row and remove-row buttons; a row added under the repeat row is a plain row. The pdf-layout settings gain table line color, fold marks and header/footer on page 1 switches; the layout paper shows fold marks on the left edge and dims a region that starts on page 2."
7
+ },
8
+ {
9
+ "version": "0.420.0",
10
+ "type": "improvement",
11
+ "title": "PDF templates cover typical business letters",
12
+ "detail": "patch-draft accepts image `widthMm`, `align` and `bleed` (bleed only in the header or footer of a pdf-layout, otherwise `bleed_not_allowed`), the run `{hardBreak:true}`, table `rowsAfterRepeat`, and divider `color` and `weightPt`. Layout meta gains `tableLineColor`, `foldMarks` (none, din-a, din-b) and `headerOnFirstPage` / `footerOnFirstPage`, plus `cornerMarks` (boolean, angles 10 mm from the paper edge, drawn by pdf-lib like the fold marks) and `paperColor` (`#rrggbb`, pdf-lib fills each page with it underneath all content, bleed images included; absent means white). Tables take `cellPaddingMm` (0 to 10), `widthMm` and `align`; table rows take `lineAbove` / `lineBelow` `{color, weightPt}` that beat `tableLineColor` on that edge, also on the repeat row and `rowsAfterRepeat`; a text run takes `dateStyle` (`short` 15.01.2026 or `long`, the default) for the placeholders in it, which `{{date x dateStyle=\"short\"}}` renders in PDFs and mails. Filled cells in the outer columns keep a small inset so their text no longer sticks out of the fill, and the footer region's table cells are top-aligned like the body. The editor schema loads and writes the new attributes unchanged. renderer-puppeteer-client prints a header or footer that skips page 1 as a second render merged with pdf-lib and draws fold marks on every page. The full-bleed rule is now scoped per region, because Chromium shares one document for header and footer and an unscoped rule moved the footer image to the top edge."
13
+ },
14
+ {
15
+ "version": "0.420.0",
16
+ "type": "fix",
17
+ "title": "PDF preview shows a draft letterhead",
18
+ "detail": "A preview that carries draft content resolves the tenant's own PDF layout in its working version, including layouts that were never published, instead of falling back to the system layout. `resolveLayout` takes an optional `working` flag for this; system layouts always resolve to their active version and real renders are unchanged."
19
+ },
20
+ {
21
+ "version": "0.420.0",
22
+ "type": "fix",
23
+ "title": "A frame past the paper edge is refused on save",
24
+ "detail": "A document-pdf body whose frame reaches past 297 mm (x + width or y + height, the long edge of the largest supported paper) is refused with frame_outside_page instead of printing blank pages before the text. The sender line of an address frame is now flattened on the parsed document, so a line break next to a tag or attribute can no longer corrupt the markup. The configured default PDF layout is looked up once per render and preview."
25
+ },
26
+ {
27
+ "version": "0.419.0",
28
+ "type": "improvement",
29
+ "title": "Frames and text styles in PDF templates",
30
+ "detail": "A PDF body can hold positioned frames (address window at DIN 5008 form B or A, free text frame, as `div[data-frame]` with `data-x`, `data-y`, `data-width`, `data-height` in mm) and text styles (`span[data-text-style]` with font, size in pt and colour, plus line height and paragraph spacing on blocks). Both go through the sanitizer and compile to inline CSS. The font catalog is Arial, Times New Roman, Courier New, Calibri and Cambria; the puppeteer-service image needs the metric-compatible fonts (Carlito, Caladea) next to the Liberation ones, so rebuild it."
31
+ },
32
+ {
33
+ "version": "0.419.0",
34
+ "type": "breaking",
35
+ "title": "signature and imprint are no longer placeholders, company* names are reserved",
36
+ "detail": "In `document-pdf` and `pdf-layout` templates, `signature` and `imprint` are no longer placeholders; a template that uses them fails on save and publish. The ten `company*` names (`companyAddress`, `companyPhone`, `companyEmail`, `companyWebsite`, `companyRegister`, `companyVatId`, `companyManagement`, `companyBank`, `companyIban`, `companyBic`) are now reserved, so a notification variable with such a name fails at boot.",
37
+ "migration": "Remove `signature` and `imprint` from PDF templates and layouts. Rename notification variables that collide with a reserved `company*` name."
38
+ },
39
+ {
40
+ "version": "0.419.0",
41
+ "type": "improvement",
42
+ "title": "Header and footer use the layout font size",
43
+ "detail": "PDF header and footer take the layout's `fontSizePt` and fall back to 10.5pt, the size the editor always showed; before they printed at 9px. Paragraphs in header and footer no longer carry margins. Existing PDF layouts therefore change on the next render: a footer taller than the bottom margin minus 4mm reaches into the page body, so check multi-line footers."
44
+ },
45
+ {
46
+ "version": "0.419.0",
47
+ "type": "improvement",
48
+ "title": "Default PDF layout per tenant, apply-layout and publish-templates",
49
+ "detail": "The tenant config key `template-resolver:config:default-pdf-layout-slug` picks the layout of PDF templates that name none. `template-resolver:write:apply-layout` sets it (mode `all`, no copies) or writes the layout into a tenant draft per chosen template (mode `selected`, text unchanged); `template-resolver:write:publish-templates` activates drafts together and reports per template what failed. The usage query lists the templates a layout serves, with `hasOwnLayout` for those that follow the default."
50
+ },
51
+ {
52
+ "version": "0.419.0",
53
+ "type": "breaking",
54
+ "title": "Line grid, flush tables and the address window in PDF bodies",
55
+ "detail": "PDF bodies print at line height 1.2. Paragraphs, lists, headings and tables are spaced by one body line (`--doc-line`, font size times 1.2) instead of 6pt after a paragraph and browser heading margins; the last element in a cell, list item, frame or the document has no bottom margin. Tables are flush with the text margin: the outer cells lose their left and right padding unless the layout table style is `grid` or the header has a background. Address paragraphs start at the text margin, have no spacing between lines, and the sender line prints at 7pt and wraps instead of being cut off. Flow text below a frame that reserves space starts 8mm under it. In the editor, cells are top-aligned, header cells print like body text, and rules appear only where the layout table style prints them; an untouched layout shows the table style \"plain\", as the PDF always printed it; a dashed outline marks cells while editing. Frames snap to page margins and other frames while moving or resizing (hold Alt to move freely).",
56
+ "migration": "Render existing PDF templates once and check the page breaks. A template that relied on the 6pt paragraph gap sets the spacing per paragraph instead."
57
+ },
58
+ {
59
+ "version": "0.419.0",
60
+ "type": "improvement",
61
+ "title": "patch-draft and create-layout let an agent rebuild PDF templates and layouts",
62
+ "detail": "patch-draft and document-blocks accept inline runs (bold, italic, underline, font, size, color), block formatting, lists, tables with a repeat row, address and text frames, a replaceBody op and a formatBlock op, all checked against the editor's print ranges and fonts. They also take kind pdf-layout with a region (header, signature or footer). The new create-layout handler creates an empty PDF layout draft under the slug tenant-layout-<name>; a tenant may edit, publish and use such layouts as soon as it may edit any PDF template, and system layouts may not take that prefix (reserved_layout_slug). patch-draft is now an agent proposal with risk low; its new refusals use the patch error codes print_style_not_allowed, invalid_table, too_many_blocks and others."
63
+ },
2
64
  {
3
65
  "version": "0.415.0",
4
66
  "type": "fix",
@@ -2,15 +2,18 @@ import type { TemplateVariableDef, TemplateVariables } from "@cosmicdrift/kumiko
2
2
  import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
3
3
  import type { Element as ScanElement } from "happy-dom";
4
4
  import { isResourceImageContentType } from "../shared/index.ts";
5
+ import { appendStyle, applyDocumentPrintStyles } from "./compile-document-styles.ts";
5
6
  import { rewriteStepsBlock } from "./compile-steps-block.ts";
6
7
  import { conditionScopeElement, withParsedDocument } from "./document-sanitizer.ts";
7
8
  import {
8
9
  DOCUMENT_CONDITION_ATTRIBUTE,
9
10
  DOCUMENT_TEXT_ALIGNMENTS,
11
+ type DocumentDateStyle,
10
12
  isAllowedDocumentUrlHref,
11
13
  isDocumentPlaceholderHref,
12
14
  isDocumentReferenceName,
13
15
  isDocumentResourceKey,
16
+ readDocumentDateStyle,
14
17
  } from "./web/document-schema.ts";
15
18
 
16
19
  // Private-use characters mark where a Handlebars expression goes. Author text
@@ -68,9 +71,12 @@ function valueExpression(
68
71
  path: string,
69
72
  def: TemplateVariableDef | undefined,
70
73
  isWholeBlock: boolean,
74
+ dateStyle: DocumentDateStyle | null,
71
75
  ): string {
72
76
  if (def?.type === "money") return `{{money ${path}}}`;
73
- if (def?.type === "date") return `{{date ${path}}}`;
77
+ if (def?.type === "date") {
78
+ return dateStyle === null ? `{{date ${path}}}` : `{{date ${path} dateStyle="${dateStyle}"}}`;
79
+ }
74
80
  if (def?.type === "percent") return `{{percent ${path}}}`;
75
81
  if (def?.type === "richText") {
76
82
  return isWholeBlock ? `{{richText ${path}}}` : `{{richText ${path} inline=true}}`;
@@ -92,6 +98,7 @@ function rewriteVariable(element: ScanElement, state: CompileState): void {
92
98
  valueExpression(
93
99
  ...pathAndDef(name, element, state),
94
100
  state.blockRichTextSpans.has(element),
101
+ readDocumentDateStyle(element),
95
102
  ),
96
103
  )
97
104
  : "",
@@ -253,12 +260,6 @@ const MAIL_HEADING_STYLES: Readonly<Record<string, string>> = {
253
260
  h3: "margin:20px 0 8px 0;font-size:17px;line-height:1.3;font-weight:600;color:#0B0D12",
254
261
  };
255
262
 
256
- // Appended after an existing style (data-align) so the alignment survives.
257
- function appendStyle(element: ScanElement, style: string): void {
258
- const existing = element.getAttribute("style");
259
- element.setAttribute("style", existing === null ? style : `${existing};${style}`);
260
- }
261
-
262
263
  function collectUniqueValidAttributes(
263
264
  html: string,
264
265
  selector: string,
@@ -335,8 +336,7 @@ export function toResourceDataUri(contentType: string, bytes: Uint8Array): strin
335
336
  function rewriteAlignment(element: ScanElement): void {
336
337
  const align = element.getAttribute("data-align");
337
338
  element.removeAttribute("data-align");
338
- if (isOneOf(DOCUMENT_TEXT_ALIGNMENTS, align))
339
- element.setAttribute("style", `text-align:${align}`);
339
+ if (isOneOf(DOCUMENT_TEXT_ALIGNMENTS, align)) appendStyle(element, `text-align:${align}`);
340
340
  }
341
341
 
342
342
  function rewriteResourceImage(
@@ -431,6 +431,7 @@ export function compileDocumentBodyToHandlebars(
431
431
  const scrubbed = html.replaceAll(EXPRESSION_OPEN, "").replaceAll(EXPRESSION_CLOSE, "");
432
432
  const compiled = withParsedDocument(scrubbed, (root) => {
433
433
  stripScriptsAndActiveContent(root, options);
434
+ applyDocumentPrintStyles(root);
434
435
  if (options.alignmentAsInlineStyle === true) applyAlignmentInlineStyles(root);
435
436
  if (options.headingAsInlineStyle === true) applyHeadingInlineStyles(root);
436
437
  if (options.tableAsInlineStyle === true) applyTableInlineStyles(root);
@@ -0,0 +1,170 @@
1
+ import type { Element as ScanElement } from "happy-dom";
2
+ import {
3
+ ROW_LINE_ABOVE_ATTRIBUTE,
4
+ ROW_LINE_BELOW_ATTRIBUTE,
5
+ readBlockStyleAttributes,
6
+ readCellBackground,
7
+ readCellPaddingMm,
8
+ readColwidth,
9
+ readDividerColor,
10
+ readDividerWeightPt,
11
+ readFrameAttributes,
12
+ readImageAlign,
13
+ readImageWidthMm,
14
+ readRowLine,
15
+ readTableAlign,
16
+ readTableWidthMm,
17
+ readTextStyleAttributes,
18
+ } from "./web/document-print-style.ts";
19
+ import {
20
+ documentBlockStyleCss,
21
+ documentCellStyleCss,
22
+ documentDividerCss,
23
+ documentFrameCss,
24
+ documentImageCss,
25
+ documentTableCss,
26
+ documentTextStyleCss,
27
+ resolveRowEdges,
28
+ } from "./web/document-style-css.ts";
29
+
30
+ // Appended after an existing style (data-align) so the alignment survives.
31
+ export function appendStyle(element: ScanElement, style: string): void {
32
+ if (style === "") return;
33
+ const existing = element.getAttribute("style");
34
+ element.setAttribute("style", existing === null ? style : `${existing};${style}`);
35
+ }
36
+
37
+ function addClass(element: ScanElement, className: string): void {
38
+ const existing = element.getAttribute("class");
39
+ element.setAttribute("class", existing === null ? className : `${existing} ${className}`);
40
+ }
41
+
42
+ function roundPercent(value: number): number {
43
+ return Math.round(value * 100) / 100;
44
+ }
45
+
46
+ // Percentages sum to exactly 100 so the table keeps the full content width.
47
+ function columnPercentages(widths: readonly number[]): number[] {
48
+ const total = widths.reduce((sum, width) => sum + width, 0);
49
+ const percentages = widths.map((width) => roundPercent((width / total) * 100));
50
+ const last = percentages.length - 1;
51
+ const others = percentages.slice(0, last).reduce((sum, value) => sum + value, 0);
52
+ percentages[last] = roundPercent(100 - others);
53
+ return percentages;
54
+ }
55
+
56
+ function firstRowColumnWidths(table: ScanElement): number[] | null {
57
+ const firstRow = Array.from(table.querySelectorAll("tr")).find(
58
+ (row) => row.closest("table") === table,
59
+ );
60
+ if (firstRow === undefined) return null;
61
+ const widths: number[] = [];
62
+ for (const cell of Array.from(firstRow.children)) {
63
+ const colwidth = readColwidth(cell);
64
+ const span = Number(cell.getAttribute("colspan") ?? 1);
65
+ if (colwidth === null || colwidth.length !== span) return null;
66
+ widths.push(...colwidth);
67
+ }
68
+ return widths.length > 0 ? widths : null;
69
+ }
70
+
71
+ function insertColgroup(table: ScanElement, widths: readonly number[]): void {
72
+ const document = table.ownerDocument;
73
+ const colgroup = document.createElement("colgroup");
74
+ for (const percentage of columnPercentages(widths)) {
75
+ const col = document.createElement("col");
76
+ col.setAttribute("style", `width:${percentage}%`);
77
+ colgroup.append(col);
78
+ }
79
+ table.insertBefore(colgroup, table.firstChild);
80
+ }
81
+
82
+ function applyFrames(root: ScanElement): void {
83
+ for (const frame of Array.from(root.querySelectorAll("div[data-frame]"))) {
84
+ const box = readFrameAttributes(frame);
85
+ if (box === null) {
86
+ frame.replaceWith(...Array.from(frame.childNodes));
87
+ continue;
88
+ }
89
+ addClass(frame, "kumiko-frame");
90
+ appendStyle(frame, documentFrameCss(box));
91
+ }
92
+ }
93
+
94
+ function ownRows(table: ScanElement): ScanElement[] {
95
+ return Array.from(table.querySelectorAll("tr")).filter((row) => row.closest("table") === table);
96
+ }
97
+
98
+ function applyTables(root: ScanElement): void {
99
+ for (const table of Array.from(root.querySelectorAll("table"))) {
100
+ if (table.getAttribute("data-borders") === "none") addClass(table, "kumiko-table-plain");
101
+ const widths = firstRowColumnWidths(table);
102
+ if (widths !== null) insertColgroup(table, widths);
103
+ appendStyle(
104
+ table,
105
+ documentTableCss({ widthMm: readTableWidthMm(table), align: readTableAlign(table) }),
106
+ );
107
+ const paddingMm = readCellPaddingMm(table);
108
+ const rows = ownRows(table);
109
+ const edges = resolveRowEdges(
110
+ rows.map((row) => ({
111
+ lineAbove: readRowLine(row, ROW_LINE_ABOVE_ATTRIBUTE),
112
+ lineBelow: readRowLine(row, ROW_LINE_BELOW_ATTRIBUTE),
113
+ repeats: row.hasAttribute("data-each"),
114
+ })),
115
+ );
116
+ rows.forEach((row, rowIndex) => {
117
+ const cells = Array.from(row.children).filter((cell) => cell.matches("td, th"));
118
+ cells.forEach((cell, cellIndex) => {
119
+ appendStyle(
120
+ cell,
121
+ documentCellStyleCss({
122
+ background: readCellBackground(cell),
123
+ paddingMm,
124
+ isFirstInRow: cellIndex === 0,
125
+ isLastInRow: cellIndex === cells.length - 1,
126
+ edges: edges[rowIndex],
127
+ }),
128
+ );
129
+ });
130
+ });
131
+ }
132
+ }
133
+
134
+ // A full-bleed image is placed by the region CSS, which an inline width would override.
135
+ function applyImages(root: ScanElement): void {
136
+ for (const image of Array.from(root.querySelectorAll("img[data-width-mm], img[data-align]"))) {
137
+ if (image.hasAttribute("data-bleed")) continue;
138
+ appendStyle(
139
+ image,
140
+ documentImageCss({ widthMm: readImageWidthMm(image), align: readImageAlign(image) }),
141
+ );
142
+ }
143
+ }
144
+
145
+ function applyDividers(root: ScanElement): void {
146
+ for (const divider of Array.from(root.querySelectorAll("hr[data-color], hr[data-weight-pt]"))) {
147
+ appendStyle(
148
+ divider,
149
+ documentDividerCss({
150
+ color: readDividerColor(divider),
151
+ weightPt: readDividerWeightPt(divider),
152
+ }),
153
+ );
154
+ }
155
+ }
156
+
157
+ // Runs before the placeholder rewrites: a rich text block host copies its paragraph's
158
+ // attributes, so the style has to be on the paragraph by then.
159
+ export function applyDocumentPrintStyles(root: ScanElement): void {
160
+ applyFrames(root);
161
+ applyTables(root);
162
+ applyImages(root);
163
+ applyDividers(root);
164
+ for (const span of Array.from(root.querySelectorAll("span[data-text-style]"))) {
165
+ appendStyle(span, documentTextStyleCss(readTextStyleAttributes(span)));
166
+ }
167
+ for (const block of Array.from(root.querySelectorAll("p, h1, h2, h3"))) {
168
+ appendStyle(block, documentBlockStyleCss(readBlockStyleAttributes(block)));
169
+ }
170
+ }