@cosmicdrift/kumiko-samples 0.422.0 → 0.424.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 (75) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +11 -1
  3. package/packages/bundled-features/src/document-draft/README.md +84 -0
  4. package/packages/bundled-features/src/document-draft/changes.json +8 -0
  5. package/packages/bundled-features/src/document-draft/entity.ts +125 -0
  6. package/packages/bundled-features/src/document-draft/feature.ts +56 -0
  7. package/packages/bundled-features/src/document-draft/handlers/blocks.query.ts +63 -0
  8. package/packages/bundled-features/src/document-draft/handlers/by-subject.query.ts +50 -0
  9. package/packages/bundled-features/src/document-draft/handlers/create.write.ts +110 -0
  10. package/packages/bundled-features/src/document-draft/handlers/discard.write.ts +32 -0
  11. package/packages/bundled-features/src/document-draft/handlers/finalize.write.ts +103 -0
  12. package/packages/bundled-features/src/document-draft/handlers/patch.write.ts +86 -0
  13. package/packages/bundled-features/src/document-draft/handlers/revise.write.ts +46 -0
  14. package/packages/bundled-features/src/document-draft/handlers/save.write.ts +53 -0
  15. package/packages/bundled-features/src/document-draft/i18n.ts +22 -0
  16. package/packages/bundled-features/src/document-draft/index.ts +21 -0
  17. package/packages/bundled-features/src/document-draft/lib.ts +77 -0
  18. package/packages/bundled-features/src/document-draft/options.ts +51 -0
  19. package/packages/bundled-features/src/document-draft/payloads.ts +45 -0
  20. package/packages/bundled-features/src/document-draft/screens/editor-screen.ts +17 -0
  21. package/packages/bundled-features/src/document-draft/user-data.ts +63 -0
  22. package/packages/bundled-features/src/document-draft/web/client-plugin.tsx +20 -0
  23. package/packages/bundled-features/src/document-draft/web/constants.ts +56 -0
  24. package/packages/bundled-features/src/document-draft/web/editor-screen.tsx +418 -0
  25. package/packages/bundled-features/src/document-draft/web/i18n.ts +54 -0
  26. package/packages/bundled-features/src/document-draft/web/index.ts +14 -0
  27. package/packages/bundled-features/src/helpdesk/changes.json +6 -0
  28. package/packages/bundled-features/src/shared/index.ts +6 -0
  29. package/packages/bundled-features/src/{signature → shared}/subject-scope.ts +17 -6
  30. package/packages/bundled-features/src/signature/changes.json +6 -0
  31. package/packages/bundled-features/src/signature/feature.ts +1 -1
  32. package/packages/bundled-features/src/signature/handlers/cancel.write.ts +1 -1
  33. package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +1 -1
  34. package/packages/bundled-features/src/signature/handlers/request.write.ts +1 -1
  35. package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +1 -1
  36. package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +1 -1
  37. package/packages/bundled-features/src/signature/options.ts +2 -1
  38. package/packages/bundled-features/src/signature/subject-queries.ts +1 -1
  39. package/packages/bundled-features/src/template-resolver/api.ts +3 -1
  40. package/packages/bundled-features/src/template-resolver/boot-rules.ts +5 -0
  41. package/packages/bundled-features/src/template-resolver/changes.json +30 -0
  42. package/packages/bundled-features/src/template-resolver/feature.ts +15 -1
  43. package/packages/bundled-features/src/template-resolver/handlers/create-variant.write.ts +134 -0
  44. package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +3 -0
  45. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +44 -1
  46. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +12 -1
  47. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +111 -11
  48. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +29 -4
  49. package/packages/bundled-features/src/template-resolver/handlers/upsert-tenant.write.ts +1 -0
  50. package/packages/bundled-features/src/template-resolver/handlers/variants.query.ts +89 -0
  51. package/packages/bundled-features/src/template-resolver/i18n.ts +1 -0
  52. package/packages/bundled-features/src/template-resolver/index.ts +22 -0
  53. package/packages/bundled-features/src/template-resolver/seeding.ts +16 -1
  54. package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +56 -6
  55. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +5 -5
  56. package/packages/bundled-features/src/template-resolver/template-meta.ts +1 -0
  57. package/packages/bundled-features/src/template-resolver/template-variants.ts +50 -0
  58. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +10 -1
  59. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +10 -4
  60. package/packages/bundled-features/src/template-resolver/web/i18n.ts +26 -0
  61. package/packages/bundled-features/src/template-resolver/web/index.ts +5 -0
  62. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +5 -0
  63. package/packages/bundled-features/src/template-resolver/web/system-placeholders.ts +17 -0
  64. package/packages/bundled-features/src/tenant/changes.json +7 -0
  65. package/packages/bundled-features/src/tenant/handlers/update-member-roles.write.ts +1 -1
  66. package/packages/bundled-features/src/tenant/i18n.ts +0 -1
  67. package/packages/bundled-features/src/tenant-inactivity/changes.json +7 -0
  68. package/packages/bundled-features/src/tenant-inactivity/constants.ts +1 -1
  69. package/packages/bundled-features/src/tenant-lifecycle/changes.json +7 -0
  70. package/packages/bundled-features/src/tenant-lifecycle/constants.ts +1 -1
  71. package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
  72. package/samples/apps/use-all-bundled/feature-manifest.json +37 -1
  73. package/samples/apps/use-all-bundled/kumiko/migrations/0069_document-draft.rebuild.json +4 -0
  74. package/samples/apps/use-all-bundled/src/app/client.tsx +3 -0
  75. package/samples/apps/use-all-bundled/src/run-config.ts +8 -0
@@ -12,6 +12,7 @@ import {
12
12
  type WriteFailure,
13
13
  writeFailure,
14
14
  } from "@cosmicdrift/kumiko-framework/errors";
15
+ import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
15
16
  import * as z from "zod";
16
17
  import { requireForTenant } from "../../shared/index.ts";
17
18
  import type { TemplateResourceRow } from "../table.ts";
@@ -23,8 +24,10 @@ import {
23
24
  type TemplateEditPolicy,
24
25
  templateEditAccess,
25
26
  } from "../template-edit-policy.ts";
27
+ import { readVariantOf } from "../template-variants.ts";
26
28
  import { executor } from "./shared.ts";
27
- import { publishGateIssues } from "./template-gates.ts";
29
+ import { publishGateIssues, storedRecord } from "./template-gates.ts";
30
+ import { baseVariableSchemaOf } from "./template-write.ts";
28
31
 
29
32
  type TemplateStatus = "active" | "archived";
30
33
  export type StatusTarget = "own" | "system";
@@ -65,13 +68,34 @@ function planStatusChange(
65
68
  ctx: HandlerContext,
66
69
  row: TemplateResourceRow,
67
70
  status: TemplateStatus,
71
+ baseSchema: Record<string, unknown> | undefined,
68
72
  ): StatusPlan {
69
73
  if (status === "archived") return { ok: true, changes: { status } };
70
- const issues = publishGateIssues(ctx.registry, toWorkingRow(row, row.tenantId));
74
+ const syncedSchema =
75
+ baseSchema === undefined ? {} : { variableSchema: JSON.stringify(baseSchema) };
76
+ const issues = publishGateIssues(ctx.registry, {
77
+ ...toWorkingRow(row, row.tenantId),
78
+ ...syncedSchema,
79
+ });
71
80
  if (issues.length > 0) {
72
81
  return { ok: false, failure: writeFailure(new ValidationError({ fields: [...issues] })) };
73
82
  }
74
- return { ok: true, changes: { ...parseTemplateDraft(row.draft), ...activationChanges(row) } };
83
+ return {
84
+ ok: true,
85
+ changes: { ...parseTemplateDraft(row.draft), ...syncedSchema, ...activationChanges(row) },
86
+ };
87
+ }
88
+
89
+ // A variant goes live with the base's current variables, so a base that gained a variable is gated and served consistently.
90
+ async function baseSchemaForPublish(
91
+ db: LoadedTarget["db"],
92
+ row: TemplateResourceRow,
93
+ ): Promise<Record<string, unknown> | undefined> {
94
+ if (row.scope !== "tenant") return undefined;
95
+ const baseSlug = readVariantOf(storedRecord(toWorkingRow(row, row.tenantId).meta));
96
+ if (baseSlug === null) return undefined;
97
+ const schema = await baseVariableSchemaOf(db, row.tenantId, baseSlug, row.locale);
98
+ return isPlainObject(schema) ? schema : undefined;
75
99
  }
76
100
 
77
101
  type LoadedTarget = Pick<Awaited<ReturnType<typeof loadTargetRow>>, "db" | "scoped">;
@@ -84,7 +108,8 @@ export async function changeRowStatus(
84
108
  row: TemplateResourceRow,
85
109
  status: TemplateStatus,
86
110
  ): Promise<WriteResult<{ readonly id: string; readonly status: TemplateStatus }>> {
87
- const plan = planStatusChange(ctx, row, status);
111
+ const baseSchema = status === "active" ? await baseSchemaForPublish(target.db, row) : undefined;
112
+ const plan = planStatusChange(ctx, row, status, baseSchema);
88
113
  if (!plan.ok) return plan.failure;
89
114
  const result = await executor.update(
90
115
  { id: row.id, version: row.version, changes: plan.changes },
@@ -42,6 +42,7 @@ export function makeUpsertTenantWrite(policy: TemplateEditPolicy) {
42
42
  event.payload.variableSchema,
43
43
  ),
44
44
  payload: event.payload,
45
+ explicitVariableSchema: true,
45
46
  });
46
47
  },
47
48
  });
@@ -0,0 +1,89 @@
1
+ import { selectMany } from "@cosmicdrift/kumiko-framework/db";
2
+ import { defineQueryHandler } from "@cosmicdrift/kumiko-framework/engine";
3
+ import * as z from "zod";
4
+ import { type TemplateResourceRow, templateResourcesTable } from "../table.ts";
5
+ import { deliveryPolicyOf, isRowServed } from "../template-delivery-policy.ts";
6
+ import {
7
+ isVariantSlugOf,
8
+ readVariantOf,
9
+ VARIANT_KIND,
10
+ VARIANT_SEPARATOR,
11
+ } from "../template-variants.ts";
12
+ import { ACTIVE_TEMPLATE_STATUS, FALLBACK_LOCALE, SYSTEM_TENANT_ID } from "../web/constants.ts";
13
+ import { localeSchema, templateSlugSchema } from "./shared.ts";
14
+ import { parseStoredJson } from "./template-gates.ts";
15
+
16
+ const VARIANT_ROW_LIMIT = 500;
17
+
18
+ export type VariantSummary = {
19
+ readonly slug: string;
20
+ readonly title: string | null;
21
+ readonly scope: "system" | "tenant";
22
+ readonly locale: string;
23
+ };
24
+
25
+ // Tenant rows win over system rows of the same slug, the requested locale over the fallback locale.
26
+ function precedence(row: TemplateResourceRow, locale: string): number {
27
+ return (row.tenantId === SYSTEM_TENANT_ID ? 1 : 0) + (row.locale === locale ? 0 : 2);
28
+ }
29
+
30
+ export const variantsQuery = defineQueryHandler({
31
+ name: "variants",
32
+ schema: z.object({ baseSlug: templateSlugSchema, locale: localeSchema }),
33
+ access: {
34
+ openToAll: {
35
+ reason:
36
+ "lists only slug, title, scope and locale of the variants the caller's own tenant can print; " +
37
+ "whoever may create a document from the base template must be able to pick a variant, " +
38
+ "and the app's role names are unknown here",
39
+ },
40
+ },
41
+ description:
42
+ "Lists the active variants of a PDF document template (kind document-pdf, slug <baseSlug>:<name>) that the caller's tenant can use: the app's system variants and the tenant's own, each with slug, title (text or a translation key), scope (system or tenant) and locale. A tenant variant replaces a system variant of the same slug. Only published variants appear, and tenant variants only while the app still allows variants for the base template. Pass a returned slug as the variant when rendering the document.",
43
+ handler: async (query, ctx) => {
44
+ const { baseSlug, locale } = query.payload;
45
+ const locales = locale === FALLBACK_LOCALE ? [locale] : [locale, FALLBACK_LOCALE];
46
+ const rows: TemplateResourceRow[] = [];
47
+ for (const rowLocale of locales) {
48
+ const found = await selectMany<TemplateResourceRow>(
49
+ ctx.db,
50
+ templateResourcesTable,
51
+ {
52
+ kind: VARIANT_KIND,
53
+ status: ACTIVE_TEMPLATE_STATUS,
54
+ locale: rowLocale,
55
+ tenantId: { in: [query.user.tenantId, SYSTEM_TENANT_ID] },
56
+ // Slugs are kebab segments joined by ":", so the base slug holds no LIKE wildcard.
57
+ slug: { like: `${baseSlug}${VARIANT_SEPARATOR}%` },
58
+ },
59
+ { limit: VARIANT_ROW_LIMIT },
60
+ );
61
+ rows.push(...found);
62
+ }
63
+ // Delivery does not depend on the caller: a SystemAdmin sees the same list as the tenant's users.
64
+ const deliveryPolicy = deliveryPolicyOf(ctx.registry);
65
+ const delivered = rows.filter(
66
+ (row) =>
67
+ isVariantSlugOf(row.slug, baseSlug) &&
68
+ readVariantOf(parseStoredJson(row.meta)) === baseSlug &&
69
+ isRowServed(deliveryPolicy, row),
70
+ );
71
+ const best = new Map<string, TemplateResourceRow>();
72
+ for (const row of delivered) {
73
+ const current = best.get(row.slug);
74
+ if (current === undefined || precedence(row, locale) < precedence(current, locale)) {
75
+ best.set(row.slug, row);
76
+ }
77
+ }
78
+ return [...best.values()]
79
+ .map(
80
+ (row): VariantSummary => ({
81
+ slug: row.slug,
82
+ title: row.title,
83
+ scope: row.tenantId === SYSTEM_TENANT_ID ? "system" : "tenant",
84
+ locale: row.locale,
85
+ }),
86
+ )
87
+ .sort((a, b) => a.slug.localeCompare(b.slug));
88
+ },
89
+ });
@@ -25,4 +25,5 @@ export const TEMPLATE_RESOLVER_I18N: Readonly<Record<string, { readonly en: stri
25
25
  [handlerTitleKey(H.applyLayout)]: { en: "Apply PDF layout" },
26
26
  [handlerTitleKey(H.createLayout)]: { en: "Create PDF layout" },
27
27
  [handlerTitleKey(H.publishTemplates)]: { en: "Publish several templates" },
28
+ [handlerTitleKey(H.createVariant)]: { en: "Create PDF template variant" },
28
29
  };
@@ -23,15 +23,24 @@ export {
23
23
  flattenFramesForPreview,
24
24
  readTopLevelFrames,
25
25
  } from "./document-frames.ts";
26
+ export { allowedBlocksFor } from "./document-op-blocks.ts";
27
+ export {
28
+ applyDocumentOps,
29
+ type DocumentOp,
30
+ documentBlocksOf,
31
+ documentOpsSchema,
32
+ } from "./document-ops.ts";
26
33
  export {
27
34
  type DocumentViolation,
28
35
  type DocumentViolationCode,
29
36
  documentViolationsToFieldIssues,
30
37
  flattenParagraphsToLineBreaks,
38
+ parseDocumentJson,
31
39
  type SanitizeBodyResult,
32
40
  type SanitizeHtmlResult,
33
41
  sanitizeDocumentHtml,
34
42
  sanitizeTemplateBody,
43
+ serializeDocumentJson,
35
44
  } from "./document-sanitizer.ts";
36
45
  export { createTemplateResolverFeature, type TemplateResolverOptions } from "./feature.ts";
37
46
  export type { LayoutSourceResponse, LayoutSourceRow } from "./handlers/layout-source.query.ts";
@@ -86,6 +95,11 @@ export {
86
95
  } from "./table.ts";
87
96
  export { type TemplateBundle, templateBundleSchema } from "./template-bundle.ts";
88
97
  export type { TemplateDeliveryPolicy } from "./template-delivery-policy.ts";
98
+ export {
99
+ diffTemplateBlocks,
100
+ splitTemplateBlocks,
101
+ type TemplateDiffBlock,
102
+ } from "./template-diff.ts";
89
103
  export {
90
104
  type TemplateEditPolicy,
91
105
  type TenantEditableTemplate,
@@ -124,6 +138,14 @@ export {
124
138
  type TemplateValidation,
125
139
  validateTemplatePlaceholders,
126
140
  } from "./template-validation.ts";
141
+ export {
142
+ isVariantSlugOf,
143
+ readVariantOf,
144
+ VARIANT_NAME_MAX_LENGTH,
145
+ VARIANT_UNKNOWN_REASON,
146
+ variantNameSchema,
147
+ variantSlug,
148
+ } from "./template-variants.ts";
127
149
  export {
128
150
  type UserContentEntryRow,
129
151
  userContentEntriesTable,
@@ -42,6 +42,7 @@ import { activeStampChanges, servedStampChanges } from "./template-draft.ts";
42
42
  import { refuseReservedLayoutSlug } from "./template-edit-policy.ts";
43
43
  import { templateSlugSchema } from "./template-meta.ts";
44
44
  import { variablesFromSchema } from "./template-validation.ts";
45
+ import { variantOfMatchesSlug } from "./template-variants.ts";
45
46
  import { type ContentFormat, TEXT_BLOCK_KIND, type UpsertKind } from "./web/constants.ts";
46
47
  import { TEMPLATE_RESOLVER_FEATURE, TemplateResolverHandlers } from "./web/qualified-names.ts";
47
48
 
@@ -83,6 +84,8 @@ export type SeedSystemTemplateOptions = {
83
84
  * system admin uploaded through resource-upload. */
84
85
  readonly linkedResources?: Record<string, string>;
85
86
  readonly meta?: unknown;
87
+ /** Seeds the template as a variant of this base slug (kind `document-pdf`, slug `<variantOf>:<name>`); the app must also list the base with `variants: true` in tenantEditable for tenants to get their own. */
88
+ readonly variantOf?: string;
86
89
  readonly title?: string;
87
90
  /** Translatable title for the overview and designer, stored in the title column; the client
88
91
  * shows the translation and falls back to the key. Mutually exclusive with `title`. */
@@ -108,6 +111,17 @@ function seedTitleColumn(opts: SeedSystemTemplateOptions, label: string): string
108
111
  return opts.titleI18nKey ?? opts.title ?? null;
109
112
  }
110
113
 
114
+ function seedRawMeta(opts: SeedSystemTemplateOptions, label: string): unknown {
115
+ const rawMeta =
116
+ opts.variantOf === undefined
117
+ ? opts.meta
118
+ : { ...(isPlainObject(opts.meta) ? opts.meta : {}), variantOf: opts.variantOf };
119
+ if (!variantOfMatchesSlug(opts.slug, rawMeta)) {
120
+ throw new Error(`${label} rejected: invalid_variant_of (slug must be <variantOf>:<name>)`);
121
+ }
122
+ return rawMeta;
123
+ }
124
+
111
125
  export async function seedSystemTemplate(
112
126
  db: DbConnection,
113
127
  opts: SeedSystemTemplateOptions,
@@ -128,12 +142,13 @@ export async function seedSystemTemplate(
128
142
  throw new Error(`${label} rejected: reserved_layout_slug`);
129
143
  }
130
144
  const title = seedTitleColumn(opts, label);
145
+ const rawMeta = seedRawMeta(opts, label);
131
146
  const evaluated = evaluateTemplateWrite({
132
147
  kind: opts.kind,
133
148
  scope: "system",
134
149
  contentFormat: opts.contentFormat,
135
150
  content: opts.content,
136
- rawMeta: opts.meta,
151
+ rawMeta,
137
152
  variables: variablesFromSchema(opts.variableSchema ?? {}),
138
153
  resourceKeys: Object.keys(opts.linkedResources ?? {}),
139
154
  });
@@ -1,14 +1,64 @@
1
1
  import type { Registry } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { isPlainObject, propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
3
+ import { isVariantSlugOf, readVariantOf, VARIANT_KIND } from "./template-variants.ts";
3
4
  import { SYSTEM_TENANT_ID, TENANT_LAYOUT_SLUG_PREFIX } from "./web/constants.ts";
4
5
  import { TEMPLATE_RESOLVER_FEATURE } from "./web/qualified-names.ts";
5
6
 
6
7
  type DeliveryTarget = { readonly kind: string; readonly slug: string };
8
+ type PolicyEntry = DeliveryTarget & { readonly variants?: true };
9
+
10
+ type PolicyTarget = DeliveryTarget & {
11
+ /** Stored JSON text or a payload object; undefined when the caller has no row or payload yet. */
12
+ readonly meta?: unknown;
13
+ };
14
+
15
+ function variantOfOfMeta(meta: unknown): string | null {
16
+ if (typeof meta !== "string") return readVariantOf(meta);
17
+ try {
18
+ return readVariantOf(JSON.parse(meta));
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ // An exact-slug entry always wins, so a separate template that merely has a ":" in its slug
25
+ // is never taken for a variant of another entry.
26
+ export function findVariantsEntry<Entry extends PolicyEntry>(
27
+ entries: readonly Entry[],
28
+ target: DeliveryTarget,
29
+ ): Entry | undefined {
30
+ if (entries.some((entry) => entry.kind === target.kind && entry.slug === target.slug)) {
31
+ return undefined;
32
+ }
33
+ return entries.find(
34
+ (entry) =>
35
+ entry.variants === true &&
36
+ entry.kind === VARIANT_KIND &&
37
+ entry.kind === target.kind &&
38
+ isVariantSlugOf(target.slug, entry.slug),
39
+ );
40
+ }
41
+
42
+ // An entry covers its own slug and, with `variants`, the variants of a PDF template: targets whose
43
+ // meta.variantOf is the entry's slug. A target without meta (slug-only pre-check) is judged by
44
+ // slug alone; writeTemplateRow then requires the variantOf.
45
+ export function findPolicyEntry<Entry extends PolicyEntry>(
46
+ entries: readonly Entry[],
47
+ target: PolicyTarget,
48
+ ): Entry | undefined {
49
+ const exact = entries.find((entry) => entry.kind === target.kind && entry.slug === target.slug);
50
+ if (exact !== undefined) return exact;
51
+ const variantsEntry = findVariantsEntry(entries, target);
52
+ if (variantsEntry === undefined) return undefined;
53
+ return target.meta === undefined || variantOfOfMeta(target.meta) === variantsEntry.slug
54
+ ? variantsEntry
55
+ : undefined;
56
+ }
7
57
 
8
58
  // What decides whether a tenant row may be served. Independent of who reads: delivery must not
9
59
  // change with the caller's roles, so this is not the edit policy.
10
60
  export type TemplateDeliveryPolicy = {
11
- readonly tenantEditable: readonly DeliveryTarget[];
61
+ readonly tenantEditable: readonly PolicyEntry[];
12
62
  /** Kinds of collections mounted with an explicit `access`; their tenant rows are edited by design. */
13
63
  readonly collectionKinds: readonly string[];
14
64
  };
@@ -26,12 +76,12 @@ function unlocksTenantLayouts(policy: TemplateDeliveryPolicy): boolean {
26
76
 
27
77
  export function isTenantOverrideServed(
28
78
  policy: TemplateDeliveryPolicy,
29
- target: DeliveryTarget,
79
+ target: PolicyTarget,
30
80
  ): boolean {
31
81
  return (
32
82
  policy.collectionKinds.includes(target.kind) ||
33
83
  (isTenantLayout(target) && unlocksTenantLayouts(policy)) ||
34
- policy.tenantEditable.some((entry) => entry.kind === target.kind && entry.slug === target.slug)
84
+ findPolicyEntry(policy.tenantEditable, target) !== undefined
35
85
  );
36
86
  }
37
87
 
@@ -39,17 +89,17 @@ export function isTenantOverrideServed(
39
89
  // is listed in tenantEditable. For these a system row of the same slug must win.
40
90
  export function isServedByCollectionOnly(
41
91
  policy: TemplateDeliveryPolicy,
42
- target: DeliveryTarget,
92
+ target: PolicyTarget,
43
93
  ): boolean {
44
94
  return (
45
95
  policy.collectionKinds.includes(target.kind) &&
46
- !policy.tenantEditable.some((entry) => entry.kind === target.kind && entry.slug === target.slug)
96
+ findPolicyEntry(policy.tenantEditable, target) === undefined
47
97
  );
48
98
  }
49
99
 
50
100
  export function isRowServed(
51
101
  policy: TemplateDeliveryPolicy,
52
- row: DeliveryTarget & { readonly tenantId: string },
102
+ row: PolicyTarget & { readonly tenantId: string },
53
103
  ): boolean {
54
104
  return row.tenantId === SYSTEM_TENANT_ID || isTenantOverrideServed(policy, row);
55
105
  }
@@ -13,7 +13,7 @@ import {
13
13
  } from "@cosmicdrift/kumiko-framework/errors";
14
14
  import type { TemplateWriteScope } from "./layout-regions.ts";
15
15
  import { type TemplateResourceRow, templateResourcesTable } from "./table.ts";
16
- import { isTenantLayout } from "./template-delivery-policy.ts";
16
+ import { findPolicyEntry, isTenantLayout } from "./template-delivery-policy.ts";
17
17
  import { isSystemAdmin } from "./template-draft.ts";
18
18
  import { TENANT_LAYOUT_SLUG_PREFIX, type TemplateKind } from "./web/constants.ts";
19
19
  import { TemplateResolverErrors } from "./web/qualified-names.ts";
@@ -22,13 +22,15 @@ export type TenantEditableTemplate = {
22
22
  readonly kind: TemplateKind;
23
23
  readonly slug: string;
24
24
  readonly access: RoleAccessRule;
25
+ /** Lets a tenant create variants (`<slug>:<name>`) of this PDF template; they follow this entry's access and delivery. Only for kind `document-pdf`. */
26
+ readonly variants?: true;
25
27
  };
26
28
 
27
29
  export type TemplateEditPolicy = {
28
30
  readonly tenantEditable: readonly TenantEditableTemplate[];
29
31
  };
30
32
 
31
- type EditTarget = { readonly slug: string; readonly kind: string };
33
+ type EditTarget = { readonly slug: string; readonly kind: string; readonly meta?: unknown };
32
34
  type EditUser = Pick<SessionUser, "roles">;
33
35
 
34
36
  const SYSTEM_ADMIN_ROLE = "SystemAdmin";
@@ -48,9 +50,7 @@ export function mayEditTemplate(
48
50
  ): boolean {
49
51
  if (isSystemAdmin(user)) return true;
50
52
  if (isTenantLayout(target)) return mayEditTenantLayouts(policy, user);
51
- const entry = policy.tenantEditable.find(
52
- (candidate) => candidate.slug === target.slug && candidate.kind === target.kind,
53
- );
53
+ const entry = findPolicyEntry(policy.tenantEditable, target);
54
54
  return entry !== undefined && hasAccess(user, entry.access);
55
55
  }
56
56
 
@@ -81,6 +81,7 @@ export const pdfAttachmentFileNamePatternSchema = singleLine(200)
81
81
  const pdfMetaSchema = z
82
82
  .object({
83
83
  layoutSlug: templateSlugSchema.optional(),
84
+ variantOf: templateSlugSchema.optional(),
84
85
  pageFormat: z.enum(PDF_PAGE_FORMATS).optional(),
85
86
  orientation: z.enum(PDF_ORIENTATIONS).optional(),
86
87
  printBackground: z.boolean().optional(),
@@ -0,0 +1,50 @@
1
+ import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
2
+ import * as z from "zod";
3
+
4
+ export const VARIANT_SEPARATOR = ":";
5
+ export const VARIANT_KIND = "document-pdf" as const;
6
+ export const VARIANT_NAME_MAX_LENGTH = 40;
7
+ export const VARIANT_UNKNOWN_REASON = "template_variant_unknown";
8
+
9
+ // One kebab segment: the variant slug is `<base>:<name>` and a second ":" would read as another base.
10
+ export const variantNameSchema = z
11
+ .string()
12
+ .min(1)
13
+ .max(VARIANT_NAME_MAX_LENGTH)
14
+ .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, "name must be kebab-case (lowercase, digits, dashes)");
15
+
16
+ export function variantSlug(baseSlug: string, name: string): string {
17
+ return `${baseSlug}${VARIANT_SEPARATOR}${name}`;
18
+ }
19
+
20
+ export function isVariantSlugOf(slug: string, baseSlug: string): boolean {
21
+ const prefix = `${baseSlug}${VARIANT_SEPARATOR}`;
22
+ return slug.startsWith(prefix) && variantNameSchema.safeParse(slug.slice(prefix.length)).success;
23
+ }
24
+
25
+ // Stored meta is untrusted JSON; only a string counts as a base slug.
26
+ export function readVariantOf(meta: unknown): string | null {
27
+ const variantOf = propertyOf(meta, "variantOf");
28
+ return typeof variantOf === "string" ? variantOf : null;
29
+ }
30
+
31
+ export function variantOfMatchesSlug(slug: string, meta: unknown): boolean {
32
+ const variantOf = readVariantOf(meta);
33
+ return variantOf === null || isVariantSlugOf(slug, variantOf);
34
+ }
35
+
36
+ // German special letters are transliterated and the rest kebab-cased, so any title yields a valid name.
37
+ export function variantNameFromTitle(title: string): string {
38
+ return title
39
+ .toLowerCase()
40
+ .replace(/ä/g, "ae")
41
+ .replace(/ö/g, "oe")
42
+ .replace(/ü/g, "ue")
43
+ .replace(/ß/g, "ss")
44
+ .normalize("NFD")
45
+ .replace(/[̀-ͯ]/g, "")
46
+ .replace(/[^a-z0-9]+/g, "-")
47
+ .replace(/^-+|-+$/g, "")
48
+ .slice(0, VARIANT_NAME_MAX_LENGTH)
49
+ .replace(/-+$/g, "");
50
+ }
@@ -29,9 +29,17 @@ function tableClasses(canvas: boolean, page: boolean): string {
29
29
  : "[&_table]:mb-2 [&_table]:mt-6 [&_.ProseMirror>:first-child_table]:mt-0 [&_.ProseMirror>table:first-child]:mt-0",
30
30
  "[&_td:last-child>p[data-size=small][data-align=right]]:whitespace-nowrap",
31
31
  )
32
- : "[&_table]:my-2";
32
+ : cn(
33
+ "[&_table]:my-2",
34
+ // The repeat strip is absolutely placed above its table and needs a line of room inside the wrapper.
35
+ "[&_.tableWrapper:has([data-testid=document-repeat-strip])_table]:mt-[var(--doc-line,1.25rem)]!",
36
+ );
33
37
  }
34
38
 
39
+ // A wide table scrolls inside its wrapper instead of pushing past the editor frame. Not on the
40
+ // paper canvas, where tables are bounded by the page.
41
+ const TABLE_SCROLL_CLASS = "[&_.tableWrapper]:max-w-full [&_.tableWrapper]:overflow-x-auto";
42
+
35
43
  // The PDF prints cells top-aligned, header like body text and no rules unless the layout sets a
36
44
  // table style; the dashed outline only marks the cells while editing, like the frame outline.
37
45
  function cellClasses(canvas: boolean, print: DocumentPrintMode): string {
@@ -82,6 +90,7 @@ export function renderEditorContent(
82
90
  "[&_a]:underline [&_a]:text-primary",
83
91
  "[&_strong]:font-bold [&_em]:italic [&_u]:underline",
84
92
  tableClasses(canvas, page),
93
+ !page && TABLE_SCROLL_CLASS,
85
94
  // A layout region has no content below its table; margins there only inflate the region box.
86
95
  hosted && "[&_td>div]:my-0 [&_.ProseMirror>.tableWrapper:last-child_table]:mb-0",
87
96
  "[&_table]:w-full [&_table]:border-collapse",
@@ -186,6 +186,12 @@ function renderPrintBlockMenu(c: TiptapContext): ReactNode {
186
186
  );
187
187
  }
188
188
 
189
+ // The form-field toolbar wraps on desktop; under md every row is one line that swipes sideways.
190
+ // `relative` makes the row the containing block of absolutely placed children (hidden inputs, popover
191
+ // anchors); without it they escape the scroll clip and widen the page.
192
+ const NARROW_SCROLL_ROW =
193
+ "relative gap-1 p-1 max-md:flex-nowrap max-md:overflow-x-auto md:flex-wrap [&>*]:shrink-0";
194
+
189
195
  function renderPrintStyleRow(c: TiptapContext): ReactNode {
190
196
  const { canvas } = c;
191
197
  return (
@@ -193,8 +199,8 @@ function renderPrintStyleRow(c: TiptapContext): ReactNode {
193
199
  className={cn(
194
200
  "flex items-center border-b border-input",
195
201
  canvas
196
- ? "min-h-9 flex-wrap gap-1.5 bg-background px-1.5 py-1 [&>*]:shrink-0"
197
- : "flex-wrap gap-1 p-1",
202
+ ? "relative min-h-9 gap-1.5 bg-background px-1.5 py-1 max-md:flex-nowrap max-md:overflow-x-auto md:flex-wrap [&>*]:shrink-0"
203
+ : NARROW_SCROLL_ROW,
198
204
  )}
199
205
  >
200
206
  {renderPrintTextStyleGroup(c)}
@@ -245,8 +251,8 @@ function renderMainToolbarRow(c: TiptapContext): ReactNode {
245
251
  className={cn(
246
252
  "flex items-center border-b border-input",
247
253
  canvas
248
- ? "min-h-9 flex-nowrap gap-0 overflow-hidden bg-background px-1.5 [&>*]:shrink-0 [&_button]:h-7 [&_button]:gap-1 [&_button]:px-1 [&_button]:text-xs"
249
- : "flex-wrap gap-1 p-1",
254
+ ? "relative min-h-9 flex-nowrap gap-0 overflow-x-auto bg-background md:overflow-hidden px-1.5 [&>*]:shrink-0 [&_button]:h-7 [&_button]:gap-1 [&_button]:px-1 [&_button]:text-xs"
255
+ : NARROW_SCROLL_ROW,
250
256
  )}
251
257
  >
252
258
  {renderParagraphStyleSelect(c)}
@@ -8,6 +8,22 @@ import type { TranslationsByLocale } from "@cosmicdrift/kumiko-renderer";
8
8
 
9
9
  export const defaultTranslations: TranslationsByLocale = {
10
10
  en: {
11
+ "template-resolver.systemPlaceholder.tenantName": "Company name",
12
+ "template-resolver.systemPlaceholder.signature": "Signature",
13
+ "template-resolver.systemPlaceholder.imprint": "Imprint",
14
+ "template-resolver.systemPlaceholder.unsubscribeUrl": "Unsubscribe link",
15
+ "template-resolver.systemPlaceholder.page": "Page number",
16
+ "template-resolver.systemPlaceholder.pages": "Page count",
17
+ "template-resolver.systemPlaceholder.companyAddress": "Address",
18
+ "template-resolver.systemPlaceholder.companyPhone": "Phone",
19
+ "template-resolver.systemPlaceholder.companyEmail": "Email",
20
+ "template-resolver.systemPlaceholder.companyWebsite": "Website",
21
+ "template-resolver.systemPlaceholder.companyRegister": "Commercial register",
22
+ "template-resolver.systemPlaceholder.companyVatId": "VAT ID",
23
+ "template-resolver.systemPlaceholder.companyManagement": "Management",
24
+ "template-resolver.systemPlaceholder.companyBank": "Bank",
25
+ "template-resolver.systemPlaceholder.companyIban": "IBAN",
26
+ "template-resolver.systemPlaceholder.companyBic": "BIC",
11
27
  "template-resolver.documentEditor.button": "Button",
12
28
  "template-resolver.documentEditor.buttonDefaultText": "Confirm",
13
29
  "template-resolver.documentEditor.buttonTarget": "Button target",
@@ -112,6 +128,16 @@ export const defaultTranslations: TranslationsByLocale = {
112
128
  "templateResolver.errors.patch.regionNotAllowed":
113
129
  "A region only applies to PDF layouts, not to {kind}.",
114
130
  "templateResolver.errors.patch.layoutExists": "A layout with the slug {slug} already exists.",
131
+ "templateResolver.errors.patch.variantsNotEnabled":
132
+ "Variants are not enabled for the template {slug}.",
133
+ "templateResolver.errors.patch.variantExists": "A variant with the slug {slug} already exists.",
134
+ "templateResolver.errors.patch.variantNameInvalid":
135
+ "The short name must be lowercase letters, digits and dashes; give one or change the title.",
136
+ "templateResolver.errors.patch.variablesInheritedFromBase":
137
+ "A variant uses the variables of its base template {slug}; change them there.",
138
+ "templateResolver.errors.patch.invalidVariantOf":
139
+ "The variant must belong to the base template in its slug.",
140
+ "templateResolver.errors.variantUnknown": "The variant {variant} does not exist.",
115
141
  "templateResolver.errors.template.reservedLayoutSlug":
116
142
  "The prefix {prefix} is reserved for tenant layouts.",
117
143
  "templateResolver.errors.patch.emptyFormat": "Give at least one of align, style or textStyle.",
@@ -79,4 +79,9 @@ export {
79
79
  TemplateResolverHandlers,
80
80
  TemplateResolverQueries,
81
81
  } from "./qualified-names.ts";
82
+ export {
83
+ SYSTEM_PLACEHOLDER_TYPE,
84
+ systemPlaceholderLabel,
85
+ translatedOr,
86
+ } from "./system-placeholders.ts";
82
87
  export { WebPreviewRenderer } from "./web-preview-renderer.tsx";
@@ -23,6 +23,7 @@ export const TemplateResolverHandlers = {
23
23
  applyLayout: "template-resolver:write:apply-layout",
24
24
  createLayout: "template-resolver:write:create-layout",
25
25
  publishTemplates: "template-resolver:write:publish-templates",
26
+ createVariant: "template-resolver:write:create-variant",
26
27
  } as const;
27
28
 
28
29
  // The config feature's write handler, which applyLayout dispatches to for the tenant default layout.
@@ -43,6 +44,7 @@ export const TemplateResolverQueries = {
43
44
  documentBlocks: "template-resolver:query:document-blocks",
44
45
  exportBundle: "template-resolver:query:export-bundle",
45
46
  sendTestStatus: "template-resolver:query:send-test-status",
47
+ variants: "template-resolver:query:variants",
46
48
  // Public pair — anonymous-reachable, kind pinned to text-block.
47
49
  bySlug: "template-resolver:query:by-slug",
48
50
  byTenant: "template-resolver:query:by-tenant",
@@ -85,4 +87,7 @@ export const TemplateResolverErrors = {
85
87
  testMailNoChannel: "template_test_mail_no_channel",
86
88
  testMailNoAddress: "template_test_mail_no_address",
87
89
  testMailFailed: "template_test_mail_failed",
90
+ variantsNotEnabled: "variants_not_enabled",
91
+ variantExists: "variant_exists",
92
+ variantNameInvalid: "variant_name_invalid",
88
93
  } as const;
@@ -0,0 +1,17 @@
1
+ import type { Translate } from "@cosmicdrift/kumiko-renderer/headless";
2
+
3
+ // Placeholders the renderer fills in; only the ones that are not plain text are listed.
4
+ export const SYSTEM_PLACEHOLDER_TYPE: Readonly<Partial<Record<string, "link">>> = {
5
+ imprint: "link",
6
+ unsubscribeUrl: "link",
7
+ };
8
+
9
+ // t() returns the key itself without a translation.
10
+ export function translatedOr(t: Translate, key: string, fallback: string): string {
11
+ const translated = t(key);
12
+ return translated === key ? fallback : translated;
13
+ }
14
+
15
+ export function systemPlaceholderLabel(t: Translate, name: string): string {
16
+ return translatedOr(t, `template-resolver.systemPlaceholder.${name}`, name);
17
+ }
@@ -1,4 +1,11 @@
1
1
  [
2
+ {
3
+ "version": "0.423.0",
4
+ "type": "breaking",
5
+ "title": "The TenantOwner role option is removed from the member roles form",
6
+ "detail": "The role option label `tenant:entity:__action-form__:field:roles:option:TenantOwner` is gone together with the role.",
7
+ "migration": "Remove any app translation or screen reference to the `TenantOwner` role option."
8
+ },
2
9
  {
3
10
  "version": "0.414.0",
4
11
  "type": "fix",
@@ -74,7 +74,7 @@ export const updateMemberRolesWrite = defineWriteHandler({
74
74
  // are session-scoped (event.user.tenantId).
75
75
  access: { roles: ["system", ...access.admin] },
76
76
  description:
77
- "Sets the roles a user holds in a tenant, rejecting reserved role names and any grant that would raise the target above the caller; roles the caller could not grant (platform roles such as DataProtectionOfficer or TenantOwner, undeclared or higher-tier app roles) are kept, only the system user replaces the full list; admins act on their own tenant, SystemAdmins on any.",
77
+ "Sets the roles a user holds in a tenant, rejecting reserved role names and any grant that would raise the target above the caller; roles the caller could not grant (platform roles such as DataProtectionOfficer, undeclared or higher-tier app roles) are kept, only the system user replaces the full list; admins act on their own tenant, SystemAdmins on any.",
78
78
  agent: { risk: "high" },
79
79
  handler: async (event, ctx) => {
80
80
  if (!ctx.systemDb) {