@cosmicdrift/kumiko-samples 0.419.0 → 0.421.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 (47) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +6 -1
  3. package/packages/bundled-features/src/auth-email-password/seeding.ts +29 -1
  4. package/packages/bundled-features/src/shared/index.ts +6 -0
  5. package/packages/bundled-features/src/shared/tenant-scoped-subject.ts +28 -0
  6. package/packages/bundled-features/src/signature/changes.json +6 -0
  7. package/packages/bundled-features/src/signature/feature.ts +1 -1
  8. package/packages/bundled-features/src/signature/grant.ts +13 -14
  9. package/packages/bundled-features/src/signature/png.ts +33 -12
  10. package/packages/bundled-features/src/template-resolver/api.ts +17 -7
  11. package/packages/bundled-features/src/template-resolver/changes.json +24 -0
  12. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +7 -1
  13. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +70 -2
  14. package/packages/bundled-features/src/template-resolver/document-frames.ts +43 -0
  15. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +135 -21
  16. package/packages/bundled-features/src/template-resolver/document-ops.ts +35 -3
  17. package/packages/bundled-features/src/template-resolver/document-print-only.ts +24 -0
  18. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +13 -1
  19. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +1 -1
  20. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +2 -1
  21. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +51 -14
  22. package/packages/bundled-features/src/template-resolver/index.ts +11 -1
  23. package/packages/bundled-features/src/template-resolver/template-meta.ts +7 -1
  24. package/packages/bundled-features/src/template-resolver/template-preview.ts +25 -4
  25. package/packages/bundled-features/src/template-resolver/web/constants.ts +4 -0
  26. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +60 -24
  27. package/packages/bundled-features/src/template-resolver/web/document-editor.tsx +4 -1
  28. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +55 -5
  29. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +137 -2
  30. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +2 -26
  31. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +61 -13
  32. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +109 -2
  33. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +161 -14
  34. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +4 -0
  35. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +2 -1
  36. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +132 -24
  37. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +160 -1
  38. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +18 -9
  39. package/packages/bundled-features/src/template-resolver/web/i18n.ts +4 -0
  40. package/packages/bundled-features/src/template-resolver/web/index.ts +4 -0
  41. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +10 -0
  42. package/packages/bundled-features/src/template-resolver/web/placeholder-text.ts +6 -3
  43. package/packages/bundled-features/src/tenant/seeding.ts +70 -0
  44. package/samples/apps/ui-walkthrough/src/features/rental/i18n.ts +8 -0
  45. package/samples/apps/ui-walkthrough/src/features/rental/screens.ts +1 -0
  46. package/samples/recipes/prod-boot-options/README.md +8 -1
  47. package/samples/recipes/prod-boot-options/src/app.ts +3 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-samples",
3
- "version": "0.419.0",
3
+ "version": "0.421.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.419.0",
3
+ "version": "0.421.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",
@@ -611,6 +612,10 @@
611
612
  "types": "./dist/shared/row-bound-grant.d.ts",
612
613
  "default": "./dist/shared/row-bound-grant.js"
613
614
  },
615
+ "./shared/tenant-scoped-subject": {
616
+ "types": "./dist/shared/tenant-scoped-subject.d.ts",
617
+ "default": "./dist/shared/tenant-scoped-subject.js"
618
+ },
614
619
  "./shared/mail-template-body": {
615
620
  "types": "./dist/shared/mail-template-body.d.ts",
616
621
  "default": "./dist/shared/mail-template-body.js"
@@ -24,6 +24,7 @@ import {
24
24
  createSystemUser,
25
25
  type SessionUser,
26
26
  SYSTEM_TENANT_ID,
27
+ SYSTEM_USER_ID,
27
28
  type TenantId,
28
29
  } from "@cosmicdrift/kumiko-framework/engine";
29
30
  import { ConflictError } from "@cosmicdrift/kumiko-framework/errors";
@@ -32,7 +33,12 @@ import { hashPassword, verifyPassword } from "../shared/index.ts";
32
33
  // kumiko-lint-ignore cross-feature-import bootstrap admin seed checks whether the tenant already has members
33
34
  import { tenantMembershipsTable } from "../tenant/membership-table.ts";
34
35
  // kumiko-lint-ignore cross-feature-import auth-tests need user+tenant seed-helpers
35
- import { type SeedTenantHooks, seedTenant, seedTenantMembership } from "../tenant/seeding.ts";
36
+ import {
37
+ addTenantMembershipRoles,
38
+ type SeedTenantHooks,
39
+ seedTenant,
40
+ seedTenantMembership,
41
+ } from "../tenant/seeding.ts";
36
42
  // kumiko-lint-ignore cross-feature-import signup create-only guard reads the user projection by email
37
43
  import { USER_STATUS, userTable } from "../user/schema/user.ts";
38
44
  // kumiko-lint-ignore cross-feature-import auth-tests need user+tenant seed-helpers
@@ -509,3 +515,25 @@ export async function seedBootstrapAdmin(
509
515
  }
510
516
  return seeded;
511
517
  }
518
+
519
+ /**
520
+ * Boot top-up for the bootstrap owner: adds the roles the owner's existing membership in the tenant
521
+ * lacks. Only a membership the system user created and last wrote is touched, so a human role change since then is not reverted at boot; the mail is unique per account, so the account is the owner named in the env.
522
+ */
523
+ export async function ensureBootstrapAdminRoles(
524
+ db: DbConnection,
525
+ options: {
526
+ readonly email: string;
527
+ readonly tenantId: TenantId;
528
+ readonly roles: readonly string[];
529
+ },
530
+ ): Promise<{ readonly added: readonly string[] }> {
531
+ const owner = await findExistingUserRowForEmail(db, options.email);
532
+ if (typeof owner?.["id"] !== "string") return { added: [] };
533
+ return addTenantMembershipRoles(db, {
534
+ userId: owner["id"],
535
+ tenantId: options.tenantId,
536
+ roles: options.roles,
537
+ onlyIfInsertedBy: SYSTEM_USER_ID,
538
+ });
539
+ }
@@ -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,28 @@
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
+ },
2
26
  {
3
27
  "version": "0.419.0",
4
28
  "type": "improvement",
@@ -8,10 +8,12 @@ import { conditionScopeElement, withParsedDocument } from "./document-sanitizer.
8
8
  import {
9
9
  DOCUMENT_CONDITION_ATTRIBUTE,
10
10
  DOCUMENT_TEXT_ALIGNMENTS,
11
+ type DocumentDateStyle,
11
12
  isAllowedDocumentUrlHref,
12
13
  isDocumentPlaceholderHref,
13
14
  isDocumentReferenceName,
14
15
  isDocumentResourceKey,
16
+ readDocumentDateStyle,
15
17
  } from "./web/document-schema.ts";
16
18
 
17
19
  // Private-use characters mark where a Handlebars expression goes. Author text
@@ -69,9 +71,12 @@ function valueExpression(
69
71
  path: string,
70
72
  def: TemplateVariableDef | undefined,
71
73
  isWholeBlock: boolean,
74
+ dateStyle: DocumentDateStyle | null,
72
75
  ): string {
73
76
  if (def?.type === "money") return `{{money ${path}}}`;
74
- if (def?.type === "date") return `{{date ${path}}}`;
77
+ if (def?.type === "date") {
78
+ return dateStyle === null ? `{{date ${path}}}` : `{{date ${path} dateStyle="${dateStyle}"}}`;
79
+ }
75
80
  if (def?.type === "percent") return `{{percent ${path}}}`;
76
81
  if (def?.type === "richText") {
77
82
  return isWholeBlock ? `{{richText ${path}}}` : `{{richText ${path} inline=true}}`;
@@ -93,6 +98,7 @@ function rewriteVariable(element: ScanElement, state: CompileState): void {
93
98
  valueExpression(
94
99
  ...pathAndDef(name, element, state),
95
100
  state.blockRichTextSpans.has(element),
101
+ readDocumentDateStyle(element),
96
102
  ),
97
103
  )
98
104
  : "",
@@ -1,16 +1,30 @@
1
1
  import type { Element as ScanElement } from "happy-dom";
2
2
  import {
3
+ ROW_LINE_ABOVE_ATTRIBUTE,
4
+ ROW_LINE_BELOW_ATTRIBUTE,
3
5
  readBlockStyleAttributes,
4
6
  readCellBackground,
7
+ readCellPaddingMm,
5
8
  readColwidth,
9
+ readDividerColor,
10
+ readDividerWeightPt,
6
11
  readFrameAttributes,
12
+ readImageAlign,
13
+ readImageWidthMm,
14
+ readRowLine,
15
+ readTableAlign,
16
+ readTableWidthMm,
7
17
  readTextStyleAttributes,
8
18
  } from "./web/document-print-style.ts";
9
19
  import {
10
20
  documentBlockStyleCss,
11
21
  documentCellStyleCss,
22
+ documentDividerCss,
12
23
  documentFrameCss,
24
+ documentImageCss,
25
+ documentTableCss,
13
26
  documentTextStyleCss,
27
+ resolveRowEdges,
14
28
  } from "./web/document-style-css.ts";
15
29
 
16
30
  // Appended after an existing style (data-align) so the alignment survives.
@@ -77,14 +91,66 @@ function applyFrames(root: ScanElement): void {
77
91
  }
78
92
  }
79
93
 
94
+ function ownRows(table: ScanElement): ScanElement[] {
95
+ return Array.from(table.querySelectorAll("tr")).filter((row) => row.closest("table") === table);
96
+ }
97
+
80
98
  function applyTables(root: ScanElement): void {
81
99
  for (const table of Array.from(root.querySelectorAll("table"))) {
82
100
  if (table.getAttribute("data-borders") === "none") addClass(table, "kumiko-table-plain");
83
101
  const widths = firstRowColumnWidths(table);
84
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
+ });
85
131
  }
86
- for (const cell of Array.from(root.querySelectorAll("td, th"))) {
87
- appendStyle(cell, documentCellStyleCss({ background: readCellBackground(cell) }));
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
+ );
88
154
  }
89
155
  }
90
156
 
@@ -93,6 +159,8 @@ function applyTables(root: ScanElement): void {
93
159
  export function applyDocumentPrintStyles(root: ScanElement): void {
94
160
  applyFrames(root);
95
161
  applyTables(root);
162
+ applyImages(root);
163
+ applyDividers(root);
96
164
  for (const span of Array.from(root.querySelectorAll("span[data-text-style]"))) {
97
165
  appendStyle(span, documentTextStyleCss(readTextStyleAttributes(span)));
98
166
  }
@@ -1,7 +1,10 @@
1
1
  // Server-only (happy-dom). Frames are read from the stored body for page planning, and flattened
2
2
  // for the editor preview, which shows the body outside a page where absolute coordinates mean nothing.
3
+ import type { Element as ScanElement, Node as ScanNode } from "happy-dom";
4
+ import { appendStyle } from "./compile-document-styles.ts";
3
5
  import { withParsedDocument } from "./document-sanitizer.ts";
4
6
  import { type DocumentFrameAttributes, readFrameAttributes } from "./web/document-print-style.ts";
7
+ import { addressParagraphCss, SENDER_LINE_SIZE_PT } from "./web/document-style-css.ts";
5
8
 
6
9
  const PREVIEW_FRAME_STYLE =
7
10
  "margin:8px 0;padding:6px;border:1px dashed #9ca3af;white-space:pre-line";
@@ -23,3 +26,43 @@ export function flattenFramesForPreview(compiledHtml: string): string {
23
26
  return body.innerHTML;
24
27
  });
25
28
  }
29
+
30
+ const TEXT_NODE_TYPE = 3;
31
+ const ELEMENT_NODE_TYPE = 1;
32
+ const SENDER_SIZE_SELECTOR = `[data-size-pt="${SENDER_LINE_SIZE_PT}"]`;
33
+ const ADDRESS_FIRST_PARAGRAPH_SELECTOR =
34
+ "div.kumiko-frame[data-frame-preset=address] > p:first-child";
35
+
36
+ function nonBlankTextNodes(node: ScanNode): ScanNode[] {
37
+ if (node.nodeType === TEXT_NODE_TYPE) return (node.textContent ?? "").trim() === "" ? [] : [node];
38
+ if (node.nodeType !== ELEMENT_NODE_TYPE) return [];
39
+ return Array.from(node.childNodes).flatMap(nonBlankTextNodes);
40
+ }
41
+
42
+ // Without the sender checkbox the first paragraph is the recipient and must stay as written.
43
+ function isSenderLine(paragraph: ScanElement): boolean {
44
+ const texts = nonBlankTextNodes(paragraph);
45
+ return (
46
+ texts.length > 0 &&
47
+ texts.every((text) => text.parentElement?.closest(SENDER_SIZE_SELECTOR) != null)
48
+ );
49
+ }
50
+
51
+ // The sender line is a single line, so a multi-line company address has to read with the same
52
+ // separator the editor uses between name and address. Its rule and spacing come from the same
53
+ // CSS builder as the editor decoration.
54
+ export function flattenAddressSenderLine(compiledHtml: string): string {
55
+ if (!compiledHtml.includes("data-frame-preset")) return compiledHtml;
56
+ return withParsedDocument(compiledHtml, (body) => {
57
+ let changed = false;
58
+ for (const paragraph of Array.from(body.querySelectorAll(ADDRESS_FIRST_PARAGRAPH_SELECTOR))) {
59
+ if (!isSenderLine(paragraph)) continue;
60
+ for (const text of nonBlankTextNodes(paragraph)) {
61
+ text.textContent = (text.textContent ?? "").replace(/\s*\r?\n\s*/g, " · ");
62
+ }
63
+ appendStyle(paragraph, addressParagraphCss(true));
64
+ changed = true;
65
+ }
66
+ return changed ? body.innerHTML : compiledHtml;
67
+ });
68
+ }