@perkyzz/emvb 0.5.0 → 0.6.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 (86) hide show
  1. package/README.md +4 -0
  2. package/THIRD_PARTY_NOTICES.md +23 -1
  3. package/licenses/exif-js.LICENSE +21 -0
  4. package/licenses/fflate.LICENSE +21 -0
  5. package/licenses/glfx.js.LICENSE +19 -0
  6. package/licenses/mini-photo-editor.LICENSE +21 -0
  7. package/licenses/photocn.LICENSE +21 -0
  8. package/package.json +2 -1
  9. package/src/admin/editor/Editor.tsx +6 -0
  10. package/src/admin/editor/collection-previews.ts +6 -1
  11. package/src/admin/editor/editor-chrome.tsx +49 -0
  12. package/src/admin/editor/editor-commands.ts +13 -0
  13. package/src/admin/editor/editor-css.ts +3 -0
  14. package/src/admin/editor/panels/ColorControl.tsx +5 -4
  15. package/src/admin/editor/panels/LayersPanel.tsx +13 -3
  16. package/src/admin/editor/panels/VariableSection.tsx +5 -3
  17. package/src/admin/editor/panels/settings/FieldControl.tsx +18 -7
  18. package/src/admin/editor/panels/settings/MediaPicker.tsx +154 -4
  19. package/src/admin/editor/panels/settings/RequiredFieldsNotice.tsx +76 -0
  20. package/src/admin/editor/panels/variable-values.ts +14 -0
  21. package/src/admin/editor/store.ts +7 -3
  22. package/src/admin/image-editor/BlurFocus.tsx +112 -0
  23. package/src/admin/image-editor/Canvas.tsx +261 -0
  24. package/src/admin/image-editor/CropOverlay.tsx +390 -0
  25. package/src/admin/image-editor/CurvesPanel.tsx +394 -0
  26. package/src/admin/image-editor/ExportDialog.tsx +354 -0
  27. package/src/admin/image-editor/ImageEditButton.tsx +83 -0
  28. package/src/admin/image-editor/ImageEditorDialog.tsx +786 -0
  29. package/src/admin/image-editor/MetadataPanel.tsx +183 -0
  30. package/src/admin/image-editor/announce.tsx +65 -0
  31. package/src/admin/image-editor/crop-geometry.ts +161 -0
  32. package/src/admin/image-editor/curve-math.ts +177 -0
  33. package/src/admin/image-editor/data-url-fetch.ts +59 -0
  34. package/src/admin/image-editor/engine.ts +55 -0
  35. package/src/admin/image-editor/exif.ts +82 -0
  36. package/src/admin/image-editor/flatten.ts +54 -0
  37. package/src/admin/image-editor/gpu-fit.ts +81 -0
  38. package/src/admin/image-editor/image-editor-css.ts +398 -0
  39. package/src/admin/image-editor/load.ts +109 -0
  40. package/src/admin/image-editor/panels.tsx +287 -0
  41. package/src/admin/image-editor/parts.tsx +565 -0
  42. package/src/admin/image-editor/save.ts +125 -0
  43. package/src/admin/image-editor/tone-panels.tsx +338 -0
  44. package/src/admin/image-editor/tools.ts +59 -0
  45. package/src/admin/image-editor/worker.ts +111 -0
  46. package/src/admin/media-api.ts +113 -3
  47. package/src/admin/ui.ts +5 -0
  48. package/src/astro/EmVBPage.astro +11 -2
  49. package/src/astro/render.ts +3 -0
  50. package/src/astro/resolve-theme.ts +15 -4
  51. package/src/astro/visitor.ts +4 -3
  52. package/src/constants.ts +1 -1
  53. package/src/core/arrange.ts +2 -0
  54. package/src/core/data/bindings.ts +12 -6
  55. package/src/core/design/classes.ts +5 -3
  56. package/src/core/design/diff.ts +3 -1
  57. package/src/core/design/merge.ts +3 -1
  58. package/src/core/design/transfer.ts +13 -2
  59. package/src/core/design/variables.ts +2 -1
  60. package/src/core/elements/dynamic-elements.ts +9 -1
  61. package/src/core/elements/form-elements.ts +16 -17
  62. package/src/core/elements/plain-text.ts +2 -2
  63. package/src/core/forms/binding.ts +148 -1
  64. package/src/core/history/diff.ts +32 -4
  65. package/src/core/image-edit/schema.ts +145 -0
  66. package/src/core/image-edit/summary.ts +58 -0
  67. package/src/core/index.ts +14 -0
  68. package/src/core/limits.ts +10 -0
  69. package/src/core/migrate/index.ts +3 -1
  70. package/src/core/perf/meter.ts +9 -1
  71. package/src/core/render/dynamic-post.ts +2 -1
  72. package/src/core/render/form.ts +24 -6
  73. package/src/core/render/index.ts +26 -5
  74. package/src/core/schema/layout.ts +11 -1
  75. package/src/core/share/link.ts +5 -2
  76. package/src/core/stable-json.ts +15 -0
  77. package/src/core/theme/dynamic.ts +21 -18
  78. package/src/core/theme/pagination.ts +30 -3
  79. package/src/core/theme/popup-rules.ts +10 -5
  80. package/src/mcp/ports.ts +8 -1
  81. package/src/mcp/read.ts +68 -1
  82. package/src/mcp/tools.ts +1 -1
  83. package/src/mcp/write.ts +100 -18
  84. package/src/server/agent-settings.ts +28 -3
  85. package/src/server/icon-routes.ts +8 -5
  86. package/src/server/mcp-routes.ts +68 -10
@@ -0,0 +1,145 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Editor-only record of an image edit (W-481, D-061). Stored on `image.props.edit`; never
5
+ * rendered. `src`/`mediaId`/`width`/`height` on the element point at the edited file, this
6
+ * record points back at the untouched original and holds the photocn recipe to re-open it.
7
+ *
8
+ * The recipe mirrors photocn's `RecipeV1` but is strict and capped, so a crafted recipe can't
9
+ * bloat the layout or crash the renderer. This module has no photocn import (core stays pure).
10
+ */
11
+
12
+ /** Max JSON size of a recipe, in UTF-8 bytes. */
13
+ export const IMAGE_EDIT_RECIPE_MAX_BYTES = 16 * 1024;
14
+ /** Max points per tone curve channel. */
15
+ export const IMAGE_EDIT_CURVE_POINTS_MAX = 32;
16
+
17
+ const Slider = z.number().finite().min(-1).max(1);
18
+ const Unit = z.number().finite().min(0).max(1);
19
+
20
+ const Lights = z
21
+ .strictObject({
22
+ brightness: Slider,
23
+ exposure: Slider,
24
+ gamma: Slider,
25
+ contrast: Slider,
26
+ shadows: Slider,
27
+ highlights: Slider,
28
+ bloom: Slider,
29
+ })
30
+ .partial();
31
+ const Colors = z
32
+ .strictObject({
33
+ temperature: Slider,
34
+ tint: Slider,
35
+ vibrance: Slider,
36
+ saturation: Slider,
37
+ sepia: Slider,
38
+ })
39
+ .partial();
40
+ const Effects = z.strictObject({ clarity: Slider, noise: Slider, vignette: Slider }).partial();
41
+ const Blur = z
42
+ .strictObject({
43
+ bokehstrength: Unit,
44
+ bokehlensout: Unit,
45
+ gaussianstrength: Unit,
46
+ gaussianlensout: Unit,
47
+ centerX: Unit,
48
+ centerY: Unit,
49
+ })
50
+ .partial();
51
+
52
+ const CurvePoint = z.tuple([Unit, Unit]);
53
+ const CurveChannel = z.array(CurvePoint).min(2).max(IMAGE_EDIT_CURVE_POINTS_MAX).nullable();
54
+ const Curves = z.tuple([CurveChannel, CurveChannel, CurveChannel, CurveChannel]);
55
+
56
+ /** Corner targets may sit a little outside the frame (perspective pulls). */
57
+ const Corner = z.tuple([z.number().finite().min(-2).max(3), z.number().finite().min(-2).max(3)]);
58
+ const Rect = z
59
+ .strictObject({
60
+ x: Unit,
61
+ y: Unit,
62
+ width: z.number().finite().gt(0).max(1),
63
+ height: z.number().finite().gt(0).max(1),
64
+ })
65
+ .refine(
66
+ (r) => r.x + r.width <= 1.000001 && r.y + r.height <= 1.000001,
67
+ "The crop must stay inside the image",
68
+ );
69
+ const Geometry = z
70
+ .strictObject({
71
+ quarterTurns: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)]),
72
+ flipX: z.boolean(),
73
+ straighten: z.number().finite().min(-45).max(45),
74
+ perspectiveX: Slider,
75
+ perspectiveY: Slider,
76
+ corners: z.tuple([Corner, Corner, Corner, Corner]).nullable(),
77
+ crop: Rect.nullable(),
78
+ aspectRatio: z.number().finite().min(0.01).max(100).nullable(),
79
+ })
80
+ .partial();
81
+
82
+ /** photocn filter labels are short names ("juno"); unknown ones are ignored by the renderer. */
83
+ const FilterLabel = z.string().regex(/^[A-Za-z0-9 _-]{1,32}$/, "Filter names are short words");
84
+
85
+ /**
86
+ * A blend image must be a same-site path or an https URL; `data:` blends (picked files) are
87
+ * refused because they would put a whole image into the layout.
88
+ */
89
+ const BlendSrc = z
90
+ .string()
91
+ .max(2000)
92
+ .refine(
93
+ (s) => /^\/(?!\/)/.test(s) || /^https:\/\//i.test(s),
94
+ "Blend images must be a site path or an https URL",
95
+ );
96
+
97
+ export const ImageEditRecipe = z.strictObject({
98
+ version: z.literal(1),
99
+ name: z.string().max(80).optional(),
100
+ lights: Lights.optional(),
101
+ colors: Colors.optional(),
102
+ effects: Effects.optional(),
103
+ blur: Blur.optional(),
104
+ curves: Curves.optional(),
105
+ blend: z.strictObject({ src: BlendSrc, mix: Unit }).optional(),
106
+ filters: z.strictObject({ label: FilterLabel, strength: Unit.optional() }).optional(),
107
+ geometry: Geometry.optional(),
108
+ });
109
+ export type ImageEditRecipe = z.infer<typeof ImageEditRecipe>;
110
+
111
+ export const IMAGE_EDIT_FORMATS = ["webp", "jpeg", "png"] as const;
112
+
113
+ export const ImageEditOutput = z.strictObject({
114
+ format: z.enum(IMAGE_EDIT_FORMATS),
115
+ /** 0..1 for webp and jpeg. */
116
+ quality: z.number().finite().min(0.1).max(1).optional(),
117
+ /** The longest side was capped to this many pixels. */
118
+ maxSide: z.number().int().min(16).max(10000).optional(),
119
+ stripGps: z.boolean(),
120
+ });
121
+ export type ImageEditOutput = z.infer<typeof ImageEditOutput>;
122
+
123
+ function byteLength(value: unknown): number {
124
+ return new TextEncoder().encode(JSON.stringify(value)).length;
125
+ }
126
+
127
+ export const ImageEdit = z.strictObject({
128
+ /** Our record version. */
129
+ v: z.literal(1),
130
+ engine: z.literal("photocn"),
131
+ engineVersion: z
132
+ .string()
133
+ .regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]{1,32})?$/, "A version like 0.1.2"),
134
+ recipe: ImageEditRecipe.refine((r) => byteLength(r) <= IMAGE_EDIT_RECIPE_MAX_BYTES, {
135
+ message: `The edit recipe is larger than ${IMAGE_EDIT_RECIPE_MAX_BYTES / 1024} KB`,
136
+ }),
137
+ /** The untouched source in the media library. */
138
+ originalMediaId: z.string().min(1).max(128).optional(),
139
+ /** Same-origin URL of the source, for re-opening when the media item is gone. */
140
+ originalSrc: z.string().min(1).max(2000),
141
+ output: ImageEditOutput,
142
+ /** ISO 8601 timestamp of the save. */
143
+ editedAt: z.iso.datetime({ offset: true }),
144
+ });
145
+ export type ImageEdit = z.infer<typeof ImageEdit>;
@@ -0,0 +1,58 @@
1
+ import type { ImageEditRecipe } from "./schema.ts";
2
+
3
+ const LABELS: Record<string, string> = {
4
+ brightness: "Brightness",
5
+ exposure: "Exposure",
6
+ gamma: "Gamma",
7
+ contrast: "Contrast",
8
+ shadows: "Shadows",
9
+ highlights: "Highlights",
10
+ bloom: "Bloom",
11
+ temperature: "Temperature",
12
+ tint: "Tint",
13
+ vibrance: "Vibrance",
14
+ saturation: "Saturation",
15
+ sepia: "Sepia",
16
+ clarity: "Clarity",
17
+ noise: "Grain",
18
+ vignette: "Vignette",
19
+ };
20
+
21
+ const signed = (n: number) => `${n > 0 ? "+" : ""}${Math.round(n * 100)}`;
22
+ const title = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
23
+
24
+ /**
25
+ * One line for the "Edited" badge tooltip and the Info panel, e.g.
26
+ * "Juno 80% · Cropped · Rotated · Exposure +20 · Saturation -15".
27
+ * At most `max` parts; the rest are counted ("+2 more").
28
+ */
29
+ export function summarizeImageEdit(recipe: ImageEditRecipe, max = 5): string {
30
+ const parts: string[] = [];
31
+ if (recipe.filters) {
32
+ const s = recipe.filters.strength;
33
+ parts.push(
34
+ s === undefined || s >= 1
35
+ ? title(recipe.filters.label)
36
+ : `${title(recipe.filters.label)} ${Math.round(s * 100)}%`,
37
+ );
38
+ }
39
+ const g = recipe.geometry;
40
+ if (g) {
41
+ if (g.crop || g.aspectRatio) parts.push("Cropped");
42
+ if (g.quarterTurns || (g.straighten !== undefined && g.straighten !== 0)) parts.push("Rotated");
43
+ if (g.flipX) parts.push("Flipped");
44
+ if (g.perspectiveX || g.perspectiveY || g.corners) parts.push("Perspective");
45
+ }
46
+ for (const section of [recipe.lights, recipe.colors, recipe.effects]) {
47
+ for (const [key, value] of Object.entries(section ?? {})) {
48
+ if (typeof value === "number" && value !== 0)
49
+ parts.push(`${LABELS[key] ?? key} ${signed(value)}`);
50
+ }
51
+ }
52
+ if (recipe.curves?.some((c) => c !== null)) parts.push("Curves");
53
+ if (recipe.blur && Object.values(recipe.blur).some((v) => v)) parts.push("Blur");
54
+ if (recipe.blend) parts.push("Blend");
55
+ if (parts.length === 0) return "No changes";
56
+ if (parts.length <= max) return parts.join(" · ");
57
+ return `${parts.slice(0, max).join(" · ")} · +${parts.length - max} more`;
58
+ }
package/src/core/index.ts CHANGED
@@ -150,7 +150,11 @@ export { classStylesInListOrder, resolveCascade } from "./design/cascade.ts";
150
150
  export {
151
151
  findMissingRequiredFields,
152
152
  layoutHasForm,
153
+ requiredFieldIssues,
154
+ requiredFieldIssueText,
153
155
  type MissingRequiredField,
156
+ type RequiredFieldInfo,
157
+ type RequiredFieldIssue,
154
158
  } from "./forms/binding.ts";
155
159
  export {
156
160
  fieldsOf,
@@ -390,6 +394,7 @@ export {
390
394
  archivePageTitle,
391
395
  DEFAULT_PER_PAGE,
392
396
  loopPerPage,
397
+ paginationTitleText,
393
398
  MAX_ARCHIVE_PAGE,
394
399
  paginationItems,
395
400
  splitArchivePage,
@@ -499,3 +504,12 @@ export {
499
504
  type ShareRead,
500
505
  } from "./share/link.ts";
501
506
  export { canvasStyleUrls, MAX_CANVAS_STYLES } from "./canvas-styles.ts";
507
+ export {
508
+ IMAGE_EDIT_CURVE_POINTS_MAX,
509
+ IMAGE_EDIT_FORMATS,
510
+ IMAGE_EDIT_RECIPE_MAX_BYTES,
511
+ ImageEdit,
512
+ ImageEditOutput,
513
+ ImageEditRecipe,
514
+ } from "./image-edit/schema.ts";
515
+ export { summarizeImageEdit } from "./image-edit/summary.ts";
@@ -7,3 +7,13 @@ export const MAX_NODES = 2000;
7
7
  export const MAX_TEXT_LENGTH = 2000;
8
8
  /** Tabs show at most this many panels; the CSS-only switcher has a rule per tab. */
9
9
  export const MAX_TABS = 12;
10
+
11
+ /**
12
+ * W-509: `text` cut to at most `max` UTF-16 units, as schema limits count, without leaving half
13
+ * of an emoji (a lone surrogate) at the end.
14
+ */
15
+ export function clipText(text: string, max: number): string {
16
+ if (text.length <= max) return text;
17
+ const code = text.charCodeAt(max - 1);
18
+ return text.slice(0, code >= 0xd800 && code <= 0xdbff ? max - 1 : max);
19
+ }
@@ -16,7 +16,8 @@ export type Migration = (doc: Record<string, unknown>) => Record<string, unknown
16
16
  * (bindings, and the rest of the W-307 feature batch), and v13 → v14 (W-329 onward) adds
17
17
  * optional fields only (audience segments, Loop options, `ch` and negative margins), and
18
18
  * v14 → v15 (W-341 onward) adds optional fields only (direction, image link and caption,
19
- * button icons, table of contents, container queries). Every other value is unchanged.
19
+ * button icons, table of contents, container queries), and layout v15 → v16 (W-481) adds the
20
+ * optional image `edit` record. Every other value is unchanged.
20
21
  */
21
22
  const unchanged: Migration = (doc) => doc;
22
23
 
@@ -74,6 +75,7 @@ export const LAYOUT_MIGRATIONS: Readonly<Record<number, Migration>> = {
74
75
  12: unchanged,
75
76
  13: unchanged,
76
77
  14: unchanged,
78
+ 15: unchanged,
77
79
  };
78
80
 
79
81
  /** `DESIGN_MIGRATIONS[n]` upgrades a version-n design document to version n + 1. */
@@ -2,6 +2,7 @@ import type { DesignSystem } from "../schema/design.ts";
2
2
  import { isParentNode, type Layout, type LayoutNode } from "../schema/layout.ts";
3
3
  import { renderPage } from "../render/index.ts";
4
4
  import type { ThemeDynamicData } from "../theme/dynamic.ts";
5
+ import { resolveEmbedUrl } from "../sanitize/embed-url.ts";
5
6
  import { layoutScripts, SCRIPT_BYTES, type PageScript } from "./scripts.ts";
6
7
 
7
8
  /** Budgets per page (W-310), in bytes over the wire. Generous for a marketing page. */
@@ -58,6 +59,11 @@ const hasBackgroundImage = (node: LayoutNode): boolean => {
58
59
  });
59
60
  };
60
61
 
62
+ const isPlayerEmbed = (node: LayoutNode): boolean => {
63
+ const url = (node.props as { url?: unknown }).url;
64
+ return typeof url === "string" && resolveEmbedUrl(url)?.kind === "iframe";
65
+ };
66
+
61
67
  /** Images and embeds under a node, with their estimated weight. */
62
68
  function media(node: LayoutNode): { images: number; bytes: number; embeds: number } {
63
69
  let images = 0;
@@ -75,7 +81,9 @@ function media(node: LayoutNode): { images: number; bytes: number; embeds: numbe
75
81
  images += 1;
76
82
  bytes += IMAGE_GUESS;
77
83
  }
78
- if (n.type === "video") {
84
+ // W-508: only a YouTube or Vimeo player is a third-party embed; a media-library video loads
85
+ // its metadata only, and a missing or refused URL renders nothing.
86
+ if (n.type === "video" && isPlayerEmbed(n)) {
79
87
  embeds += 1;
80
88
  bytes += EMBED_BYTES;
81
89
  }
@@ -1,3 +1,4 @@
1
+ import { clipText } from "../limits.ts";
1
2
  import { HEADING_TAGS } from "../elements/index.ts";
2
3
  import type { LayoutNode, POST_DATE_FORMATS } from "../schema/layout.ts";
3
4
  import { sanitizeHref } from "../sanitize/href.ts";
@@ -165,7 +166,7 @@ const POST_FIELDS = new Map<string, PostField>([
165
166
  has: (post) => !!post.authorName?.trim(),
166
167
  render: (_node, attrs, post) => {
167
168
  const name = post.authorName?.trim();
168
- return name ? { tag: "span", attrs, children: [name.slice(0, 200)] } : undefined;
169
+ return name ? { tag: "span", attrs, children: [clipText(name, 200)] } : undefined;
169
170
  },
170
171
  },
171
172
  ],
@@ -296,7 +296,7 @@ function withFieldMeta(vnode: VNode, node: LayoutNode, meta: PublicFormField): V
296
296
  },
297
297
  };
298
298
  }
299
- if (!meta.required || child.tag !== "label") return child;
299
+ if (!meta.required || (child.tag !== "label" && child.tag !== "legend")) return child;
300
300
  if (child.attrs.class === "emvb-form-label") {
301
301
  return { ...child, children: [...child.children, mark] };
302
302
  }
@@ -332,6 +332,10 @@ export function withFieldOptions(
332
332
  return withFieldMeta(withOptions(vnode, node, meta), node, meta);
333
333
  }
334
334
 
335
+ /** The fieldset that holds a radio group's options. */
336
+ const radioGroup = (child: VNode) =>
337
+ child.tag === "fieldset" && (child.attrs.class ?? "").includes("emvb-radio-group");
338
+
335
339
  /** A select or radio field filled with the definition's options. */
336
340
  function withOptions(vnode: VNode, node: LayoutNode, meta: PublicFormField): VNode {
337
341
  const field = meta.name;
@@ -346,10 +350,13 @@ function withOptions(vnode: VNode, node: LayoutNode, meta: PublicFormField): VNo
346
350
  })),
347
351
  ]);
348
352
  }
349
- return replaceChildren(
350
- vnode,
351
- (child) => child.tag === "fieldset" && (child.attrs.class ?? "").includes("emvb-radio-group"),
352
- meta.options.map((option) => ({
353
+ // W-524: the group's <legend> stays; only the placeholder option is replaced.
354
+ const legend = findNode(vnode, radioGroup)?.children.filter(
355
+ (child): child is VNode => typeof child !== "string" && child.tag === "legend",
356
+ );
357
+ return replaceChildren(vnode, radioGroup, [
358
+ ...(legend ?? []),
359
+ ...meta.options.map((option): VNode => ({
353
360
  tag: "label",
354
361
  attrs: { class: "emvb-form-radio-label" },
355
362
  children: [
@@ -361,5 +368,16 @@ function withOptions(vnode: VNode, node: LayoutNode, meta: PublicFormField): VNo
361
368
  ` ${option.label}`,
362
369
  ],
363
370
  })),
364
- );
371
+ ]);
372
+ }
373
+
374
+ /** The first element node `match` accepts, depth first. */
375
+ function findNode(vnode: VNode, match: (node: VNode) => boolean): VNode | undefined {
376
+ if (match(vnode)) return vnode;
377
+ for (const child of vnode.children) {
378
+ if (typeof child === "string") continue;
379
+ const found = findNode(child, match);
380
+ if (found) return found;
381
+ }
382
+ return undefined;
365
383
  }
@@ -6,7 +6,7 @@ import { cssScopeToken, scopeClassName, scopeCss, scopeWrapperCss } from "../css
6
6
  import { ELEMENTS } from "../elements/index.ts";
7
7
  import { controlId } from "../elements/field-id.ts";
8
8
  import { layoutHasForm } from "../forms/binding.ts";
9
- import { forEachNode, someNode } from "../tree-ops.ts";
9
+ import { nodeChildren, someNode } from "../tree-ops.ts";
10
10
  import { layoutHasMenuDropdown, layoutHasTabs } from "../tabs/presence.ts";
11
11
  import type { DesignSystem } from "../schema/design.ts";
12
12
  import {
@@ -201,6 +201,12 @@ export function renderPage(
201
201
  scope?: string;
202
202
  /** Editor canvas: device rules follow this device, not the frame width (W-116). */
203
203
  previewDevice?: PopupDevice;
204
+ /**
205
+ * Theme parts (header, footer, popup, float) render apart from the page, so a synced section
206
+ * on both gave form fields, honeypots and tab groups the same ids: a label in a popup focused
207
+ * the page's field. Their generated ids get a suffix from `scope` (W-527).
208
+ */
209
+ partIds?: boolean;
204
210
  } = {},
205
211
  ): RenderResult {
206
212
  const mode = opts.mode ?? "public";
@@ -229,6 +235,7 @@ export function renderPage(
229
235
  let backgroundVideo = false;
230
236
 
231
237
  const domIds = new Map<string, number>();
238
+ const idSuffix = opts.partIds && opts.scope ? `-t${originHash(opts.scope)}` : "";
232
239
  // W-253: runtimes follow what renders, including synced section and loop item contents,
233
240
  // which the page's own layout doesn't hold.
234
241
  const rendered = { form: false, tabs: false, menuDropdown: false };
@@ -242,7 +249,7 @@ export function renderPage(
242
249
  uniqueId: (base) => {
243
250
  const count = (domIds.get(base) ?? 0) + 1;
244
251
  domIds.set(base, count);
245
- return count === 1 ? base : `${base}-r${count}`;
252
+ return `${base}${count === 1 ? "" : `-r${count}`}${idSuffix}`;
246
253
  },
247
254
  };
248
255
 
@@ -310,6 +317,11 @@ export function renderPage(
310
317
  }
311
318
  }
312
319
  if (node.container) declarations.push({ property: "container-type", value: "inline-size" });
320
+ // W-523: a query container can't size to its content, so in a row (or with align-items other
321
+ // than stretch) it collapsed to 0 px and its content vanished. Full width unless a width is set.
322
+ if (node.container && node.style?.width === undefined && !node.classes?.length) {
323
+ declarations.push({ property: "width", value: "100%" });
324
+ }
313
325
  if (node.type === "image") {
314
326
  const focal = node.props as { focalX?: unknown; focalY?: unknown };
315
327
  const position = objectPosition(focal.focalX, focal.focalY);
@@ -557,15 +569,24 @@ function treeHasType(node: LayoutNode, type: string): boolean {
557
569
  return someNode(node, (current) => current.type === type);
558
570
  }
559
571
 
560
- /** The page's own heading nodes (not synced section or loop item contents). */
572
+ /**
573
+ * The page's own heading nodes (not synced section or loop item contents). W-512: not those
574
+ * inside an element hidden on every device, which never show, so a contents link has nothing
575
+ * to jump to (W-409 covered only the heading's own visibility).
576
+ */
561
577
  function headingAnchors(root: LayoutNode): { node: LayoutNode }[] {
562
578
  const out: { node: LayoutNode }[] = [];
563
- forEachNode(root, (node) => {
579
+ const walk = (node: LayoutNode) => {
580
+ if (node !== root && HIDDEN_DEVICES.every((device) => node.hiddenOn?.includes(device))) return;
564
581
  if (node.type === "heading") out.push({ node });
565
- });
582
+ for (const child of nodeChildren(node)) walk(child);
583
+ };
584
+ walk(root);
566
585
  return out;
567
586
  }
568
587
 
588
+ const HIDDEN_DEVICES = ["desktop", "tablet", "mobile"] as const;
589
+
569
590
  function tocChildren(
570
591
  node: LayoutNode,
571
592
  items: { id: string; text: string }[],
@@ -1,8 +1,11 @@
1
1
  import { z } from "zod";
2
2
  import { MAX_TEXT_LENGTH } from "../limits.ts";
3
+ import { ImageEdit } from "../image-edit/schema.ts";
3
4
  import { DeviceStyles, HiddenOn, Length, StyleProps, StyleStates } from "./style.ts";
4
5
 
5
6
  /**
7
+ * 16 since W-481 (D-061): an optional editor-only `edit` record on images (image editor).
8
+ * Every other value is unchanged.
6
9
  * 15 since W-341: optional per-element `dir`, image link/caption/focal point/sources, button icons,
7
10
  * a table-of-contents element, and container queries. Every other value is unchanged.
8
11
  * 14 since W-329: optional visitor `segments` in an element's audience (the host names them);
@@ -14,7 +17,7 @@ import { DeviceStyles, HiddenOn, Length, StyleProps, StyleStates } from "./style
14
17
  * (`{ angle, from, to }`) become a linear gradient on read.
15
18
  * 11 since W-156 and W-157 (D-045): the layout Section element and an editor-only node label.
16
19
  */
17
- export const LAYOUT_SCHEMA_VERSION = 15;
20
+ export const LAYOUT_SCHEMA_VERSION = 16;
18
21
 
19
22
  export const NodeId = z
20
23
  .string()
@@ -339,6 +342,8 @@ export const ImageNode = leafNode(
339
342
  )
340
343
  .max(6)
341
344
  .optional(),
345
+ /** Editor-only record of an image-editor edit; never rendered (W-481). */
346
+ edit: ImageEdit.optional(),
342
347
  }),
343
348
  ).refine((node) => node.props.decorative === true || node.props.alt.length > 0, {
344
349
  message: "Alt text is required unless the image is marked decorative.",
@@ -640,6 +645,11 @@ export const PaginationNode = leafNode(
640
645
  showCount: z.boolean().optional(),
641
646
  /** The count's text; `{page}` and `{total}` are filled in. Unset = "Page {page} of {total}". */
642
647
  countText: z.string().max(60).optional(),
648
+ /**
649
+ * The page title of archive page 2 onward (W-529); `{title}` and `{page}` are filled in.
650
+ * Unset = "{title} – page {page}". Hosts read it with `archivePageTitle`.
651
+ */
652
+ titleText: z.string().max(60).optional(),
643
653
  }),
644
654
  );
645
655
 
@@ -17,6 +17,9 @@ const MAX_TITLE = 120;
17
17
  /** Unpacked text: a layout and a design at their limits, plus a little JSON. */
18
18
  const MAX_UNPACKED_BYTES = MAX_LAYOUT_BYTES + MAX_DESIGN_BYTES + 4096;
19
19
 
20
+ /** W-507: the title cap counts whole characters, so an emoji at the limit isn't cut in half. */
21
+ const clipTitle = (title: string): string => Array.from(title).slice(0, MAX_TITLE).join("");
22
+
20
23
  export type SharedPage = { title: string; layout: Layout; design?: DesignSystem };
21
24
 
22
25
  export type ShareRead =
@@ -120,7 +123,7 @@ export async function pipeBytes(
120
123
  */
121
124
  export async function encodeSharedPage(page: SharedPage): Promise<string> {
122
125
  const json = JSON.stringify({
123
- t: page.title.slice(0, MAX_TITLE),
126
+ t: clipTitle(page.title),
124
127
  l: page.layout,
125
128
  ...(page.design ? { d: page.design } : {}),
126
129
  });
@@ -176,7 +179,7 @@ export async function decodeSharedPage(encoded: string): Promise<ShareRead> {
176
179
  return { ok: false, reason: "invalid", detail: layout.issues[0]?.message ?? "Bad layout" };
177
180
  }
178
181
  const page: SharedPage = {
179
- title: typeof t === "string" && t.trim() ? t.trim().slice(0, MAX_TITLE) : "Shared page",
182
+ title: typeof t === "string" && t.trim() ? clipTitle(t.trim()) : "Shared page",
180
183
  layout: layout.layout,
181
184
  };
182
185
  if (d !== undefined) {
@@ -0,0 +1,15 @@
1
+ /** Keys sorted at every level: a saved copy comes back in schema order, not edit order. */
2
+ function sorted(value: unknown): unknown {
3
+ if (Array.isArray(value)) return value.map(sorted);
4
+ if (!value || typeof value !== "object") return value;
5
+ const entries = Object.entries(value as Record<string, unknown>).toSorted(([a], [b]) =>
6
+ a < b ? -1 : a > b ? 1 : 0,
7
+ );
8
+ return Object.fromEntries(entries.map(([k, v]) => [k, sorted(v)]));
9
+ }
10
+
11
+ /** JSON text that ignores key order, to compare a saved copy with an edited one (W-518, W-519). */
12
+ export const stableJson = (value: unknown): string => JSON.stringify(sorted(value));
13
+
14
+ /** Same content, whatever the key order (W-519). */
15
+ export const sameJson = (a: unknown, b: unknown): boolean => stableJson(a) === stableJson(b);
@@ -99,27 +99,37 @@ function linkDefs(block: Record<string, unknown>): Map<string, string> {
99
99
  return links;
100
100
  }
101
101
 
102
- /** A span's text wrapped in its marks; unknown marks and unsafe links leave plain text. */
103
- function spanNode(
104
- span: Record<string, unknown>,
105
- links: Map<string, string>,
106
- ): VNode | string | null {
102
+ /** Text with its line breaks as `<br>`. */
103
+ function withBreaks(text: string): (VNode | string)[] {
104
+ const out: (VNode | string)[] = [];
105
+ text.split("\n").forEach((part, i) => {
106
+ if (i > 0) out.push({ tag: "br", attrs: {}, children: [] });
107
+ if (part) out.push(part);
108
+ });
109
+ return out;
110
+ }
111
+
112
+ /**
113
+ * A span's text wrapped in its marks; unknown marks and unsafe links leave plain text. Line
114
+ * breaks become `<br>` inside the marks too: a bold or linked line break was lost (W-525).
115
+ */
116
+ function spanNodes(span: Record<string, unknown>, links: Map<string, string>): (VNode | string)[] {
107
117
  const text = typeof span["text"] === "string" ? span["text"] : "";
108
- if (!text) return null;
118
+ if (!text) return [];
109
119
  const marks = Array.isArray(span["marks"])
110
120
  ? span["marks"].filter((m) => typeof m === "string")
111
121
  : [];
112
- let node: VNode | string = text;
122
+ let nodes = withBreaks(text);
113
123
  // W-392: a link can't hold a link, so only the span's first (outermost) link mark is kept.
114
124
  const link = marks.find((mark) => !DECORATORS[mark] && links.has(mark));
115
125
  for (const mark of new Set(marks.toReversed())) {
116
126
  const tag = DECORATORS[mark];
117
- if (tag) node = { tag, attrs: {}, children: [node] };
127
+ if (tag) nodes = [{ tag, attrs: {}, children: nodes }];
118
128
  else if (mark === link) {
119
- node = { tag: "a", attrs: { href: links.get(mark) as string }, children: [node] };
129
+ nodes = [{ tag: "a", attrs: { href: links.get(mark) as string }, children: nodes }];
120
130
  }
121
131
  }
122
- return node;
132
+ return nodes;
123
133
  }
124
134
 
125
135
  /** A block's spans, with line breaks kept as `<br>`. */
@@ -129,14 +139,7 @@ function inlineNodes(block: Record<string, unknown>): (VNode | string)[] {
129
139
  const out: (VNode | string)[] = [];
130
140
  for (const child of children) {
131
141
  if (!isRecord(child) || (child["_type"] !== undefined && child["_type"] !== "span")) continue;
132
- const node = spanNode(child, links);
133
- if (node === null) continue;
134
- if (typeof node === "string" && node.includes("\n")) {
135
- node.split("\n").forEach((part, i) => {
136
- if (i > 0) out.push({ tag: "br", attrs: {}, children: [] });
137
- if (part) out.push(part);
138
- });
139
- } else out.push(node);
142
+ out.push(...spanNodes(child, links));
140
143
  }
141
144
  return out;
142
145
  }
@@ -88,12 +88,23 @@ export function loopPerPage(layout: Layout): number {
88
88
  return found ?? DEFAULT_PER_PAGE;
89
89
  }
90
90
 
91
+ /** The paged archive title wording when the host passes none (W-229). */
92
+ const PAGED_TITLE = "{title} – page {page}";
93
+
91
94
  /**
92
95
  * A paged archive's title for `<title>` and headings: "Posts – page 2"; page 1 is the bare
93
- * title (W-229).
96
+ * title (W-229). W-529: `template` sets the wording in the site's language, with `{title}` and
97
+ * `{page}` filled in like the Pagination element's "Page {page} of {total}"; one without
98
+ * `{page}` would give every page the same title, so it falls back to the default.
94
99
  */
95
- export function archivePageTitle(title: string, page: number | undefined): string {
96
- return page !== undefined && page > 1 ? `${title} – page ${page}` : title;
100
+ export function archivePageTitle(
101
+ title: string,
102
+ page: number | undefined,
103
+ template?: string,
104
+ ): string {
105
+ if (page === undefined || page <= 1) return title;
106
+ const wording = template?.trim().includes("{page}") ? template.trim() : PAGED_TITLE;
107
+ return wording.replaceAll("{title}", title).replaceAll("{page}", String(page));
97
108
  }
98
109
 
99
110
  /** One entry of a Pagination bar: a page link, the current page, or a gap (W-222). */
@@ -151,3 +162,19 @@ function totalItems(p: ArchivePagination, total: number): PaginationItem[] {
151
162
  if (p.page < total) items.push({ kind: "next", href: archivePagePath(p.basePath, p.page + 1) });
152
163
  return items;
153
164
  }
165
+
166
+ /** The first Pagination element's "Page title text" in an archive layout, if set (W-529). */
167
+ export function paginationTitleText(layout: Layout): string | undefined {
168
+ let found: string | undefined;
169
+ const walk = (node: LayoutNode): void => {
170
+ if (found !== undefined) return;
171
+ if (node.type === "pagination") {
172
+ const text = (node.props as { titleText?: unknown }).titleText;
173
+ found = typeof text === "string" && text.trim() ? text.trim() : "";
174
+ return;
175
+ }
176
+ if (isParentNode(node)) for (const child of node.children) walk(child);
177
+ };
178
+ walk(layout.root);
179
+ return found || undefined;
180
+ }