@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
@@ -70,6 +70,8 @@ export function renderStored(
70
70
  pageId: string,
71
71
  formDefinitions?: FormDefinitions,
72
72
  dynamic?: ThemeDynamicData,
73
+ /** A theme part: generated ids get a suffix of its own (W-527). */
74
+ partIds = false,
73
75
  ): RenderedPage {
74
76
  const { layout, problem } = inspectLayout(raw);
75
77
  if (!layout) {
@@ -95,6 +97,7 @@ export function renderStored(
95
97
  formDefinitions,
96
98
  dynamic,
97
99
  scope: pageId,
100
+ ...(partIds ? { partIds } : {}),
98
101
  },
99
102
  );
100
103
  return {
@@ -29,6 +29,7 @@ import {
29
29
  type TriggersDoc,
30
30
  archivePagePath,
31
31
  loopPerPage,
32
+ paginationTitleText,
32
33
  type ArchivePagination,
33
34
  } from "../core/index.ts";
34
35
  import { THEME_PARTS_COLLECTION } from "../constants.ts";
@@ -105,11 +106,16 @@ export type ResolvedThemeParts = {
105
106
  canonicalPath?: string;
106
107
  /**
107
108
  * The archive's title when an Archive part renders: "Posts", or the category/tag slug
108
- * (W-229). Hosts build "Posts – page 2" with `archivePageTitle`.
109
+ * (W-229). Hosts build "Posts – page 2" with `archivePageTitle` and `archiveTitleText`.
109
110
  */
110
111
  archiveTitle?: string;
111
112
  /** The archive page number when an Archive part renders (1 for the bare URL). */
112
113
  archivePage?: number;
114
+ /**
115
+ * The Archive part's Pagination "Page title text", when set (W-529). Pass it to
116
+ * `archivePageTitle(archiveTitle, page, archiveTitleText)` for the site's own wording.
117
+ */
118
+ archiveTitleText?: string;
113
119
  /** The site's text direction from Site styles when a part renders, for `<html dir>` (W-230). */
114
120
  dir?: "ltr" | "rtl" | "auto";
115
121
  };
@@ -484,7 +490,7 @@ export async function resolveThemePartsWith(
484
490
  ...Object.values(dynamic?.loopTemplates ?? {}),
485
491
  ]),
486
492
  );
487
- const page = renderStored(stored.layout, design, stored.id, formDefinitions, dynamic);
493
+ const page = renderStored(stored.layout, design, stored.id, formDefinitions, dynamic, true);
488
494
  rendered.push(page);
489
495
  // W-216: a header or footer part is the page's banner or contentinfo landmark (hosts put it
490
496
  // straight in <body> instead of their own <header>/<footer>).
@@ -511,7 +517,7 @@ export async function resolveThemePartsWith(
511
517
  };
512
518
 
513
519
  let pastLastPage = false;
514
- let archiveInfo: { title?: string; page: number } | undefined;
520
+ let archiveInfo: { title?: string; page: number; titleText?: string } | undefined;
515
521
  const renderPart = async (
516
522
  winner: ThemePartCandidate | null,
517
523
  ): Promise<RenderedThemePart | null> => {
@@ -528,7 +534,11 @@ export async function resolveThemePartsWith(
528
534
  : referenced;
529
535
  // A page past the last one has no posts; the host answers 404 (W-221).
530
536
  if (winner === contentWinner && dynamic?.pagination) {
531
- archiveInfo = { title: dynamic.archiveTitle, page: dynamic.pagination.page };
537
+ archiveInfo = {
538
+ title: dynamic.archiveTitle,
539
+ page: dynamic.pagination.page,
540
+ titleText: layout ? paginationTitleText(layout) : undefined,
541
+ };
532
542
  }
533
543
  if (winner === contentWinner && (dynamic?.pagination?.page ?? 1) > 1) {
534
544
  pastLastPage = (dynamic?.posts ?? []).length === 0;
@@ -630,6 +640,7 @@ export async function resolveThemePartsWith(
630
640
  ...(design.direction ? { dir: design.direction } : {}),
631
641
  ...(archiveInfo?.title ? { archiveTitle: archiveInfo.title } : {}),
632
642
  ...(archiveInfo ? { archivePage: archiveInfo.page } : {}),
643
+ ...(archiveInfo?.titleText ? { archiveTitleText: archiveInfo.titleText } : {}),
633
644
  ...(empty.canonicalPath ? { canonicalPath: empty.canonicalPath } : {}),
634
645
  };
635
646
  }
@@ -108,6 +108,8 @@ function requestCookie(astro: VisitorAstro, name: string): string | undefined {
108
108
  }
109
109
 
110
110
  const COUNTRY = /^[A-Z]{2}$/;
111
+ /** XX is Cloudflare's "unknown" and T1 is Tor: neither is a country (W-514: host facts too). */
112
+ const isCountry = (code: string) => COUNTRY.test(code) && code !== "XX" && code !== "T1";
111
113
 
112
114
  /**
113
115
  * The visitor's country from the edge: Cloudflare's header or `request.cf`, or Vercel's header.
@@ -123,8 +125,7 @@ function countryOf(astro: VisitorAstro): string | undefined {
123
125
  ];
124
126
  for (const value of candidates) {
125
127
  const code = typeof value === "string" ? value.trim().toUpperCase() : "";
126
- // XX is Cloudflare's "unknown" and T1 is Tor: neither is a country.
127
- if (COUNTRY.test(code) && code !== "XX" && code !== "T1") return code;
128
+ if (isCountry(code)) return code;
128
129
  }
129
130
  return undefined;
130
131
  }
@@ -159,7 +160,7 @@ export function hostVisitorFacts(host: HostVisitor | undefined): Partial<Visitor
159
160
  facts.segments = segments;
160
161
  }
161
162
  const country = typeof host.country === "string" ? host.country.trim().toUpperCase() : "";
162
- if (COUNTRY.test(country)) facts.country = country;
163
+ if (isCountry(country)) facts.country = country;
163
164
  if (host.device === "mobile" || host.device === "tablet" || host.device === "desktop")
164
165
  facts.device = host.device;
165
166
  if (typeof host.returning === "boolean") facts.returning = host.returning;
package/src/constants.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export const PLUGIN_ID = "emvb";
2
- export const PLUGIN_VERSION = "0.5.0";
2
+ export const PLUGIN_VERSION = "0.6.0";
3
3
  export const PACKAGE_NAME = "@perkyzz/emvb";
4
4
  export const ADMIN_ENTRY = `${PACKAGE_NAME}/admin`;
5
5
  export const PAGES_COLLECTION = "emvb_pages";
@@ -204,6 +204,8 @@ export function moveNode(layout: Layout, id: string, parentId: string, index: nu
204
204
  const from = locate(layout, id) as Located & { parent: ContainerNode | FormNode | LoopNode };
205
205
  const sameParent = from.parent.id === parentId;
206
206
  const at = sameParent && from.index < index ? index - 1 : index;
207
+ // W-521: a drop on its own spot is no edit; the same layout tells callers nothing changed.
208
+ if (sameParent && at === from.index) return { ok: true, layout, selected: id };
207
209
  const { layout: without, removed } = removeNode(layout, id);
208
210
  if (!removed) return refuse(REASONS.missing);
209
211
  return { ok: true, layout: insertNode(without, parentId, at, removed.node), selected: id };
@@ -100,11 +100,12 @@ function clean(value: string): string {
100
100
  let out = "";
101
101
  for (const char of value) {
102
102
  const code = char.codePointAt(0) ?? 0;
103
- if (code === 10 || code === 9) out += char === "\t" ? " " : char;
104
- else if (code >= 32 && code !== 127) out += char;
105
- if (out.length >= MAX_BOUND_LENGTH) break;
103
+ const kept = code === 9 ? " " : code === 10 || (code >= 32 && code !== 127) ? char : "";
104
+ // W-502: cutting at a UTF-16 length split an emoji at the limit into a broken half.
105
+ if (out.length + kept.length > MAX_BOUND_LENGTH) break;
106
+ out += kept;
106
107
  }
107
- return out.slice(0, MAX_BOUND_LENGTH).trim();
108
+ return out.trim();
108
109
  }
109
110
 
110
111
  /** The live value of one binding, or undefined when its source has nothing for this key. */
@@ -189,8 +190,13 @@ export function applyBindings(node: LayoutNode, data: BindingData): LayoutNode {
189
190
  if (value === undefined) continue;
190
191
  props ??= { ...(node.props as Record<string, unknown>) };
191
192
  props[field.key] = value;
192
- // A bound image is no longer the media library item it was picked from.
193
- if (field.kind === "image") delete props["mediaId"];
193
+ // A bound image is no longer the media library item it was picked from. W-501: nor are the
194
+ // typed picture's extra sizes; with `w` descriptors the browser picks only from srcset, so
195
+ // they hid the bound image on most screens.
196
+ if (field.kind === "image") {
197
+ delete props["mediaId"];
198
+ delete props["sources"];
199
+ }
194
200
  }
195
201
  return props ? ({ ...node, props } as LayoutNode) : node;
196
202
  }
@@ -1,3 +1,4 @@
1
+ import { clipText } from "../limits.ts";
1
2
  import type { DesignSystem } from "../schema/design.ts";
2
3
  import type { Layout, LayoutNode } from "../schema/layout.ts";
3
4
  import type { StyleProps } from "../schema/style.ts";
@@ -99,7 +100,8 @@ export function cleanClassName(name: string): string {
99
100
  const code = ch.charCodeAt(0);
100
101
  return code < 32 || code === 127 ? " " : ch;
101
102
  }).join("");
102
- return spaced.replace(/ {2,}/g, " ").trim().slice(0, 60).trim();
103
+ const spacedTrim = spaced.replace(/ {2,}/g, " ").trim();
104
+ return clipText(spacedTrim, 60).trim();
103
105
  }
104
106
 
105
107
  export function localToClassRefusal(design: DesignSystem, node: LayoutNode): string | null {
@@ -120,7 +122,7 @@ export function localStylesToClass(
120
122
  node: LayoutNode,
121
123
  name: string,
122
124
  ): { design: DesignSystem; node: LayoutNode; classId: string } | null {
123
- const trimmed = name.trim().slice(0, 60);
125
+ const trimmed = clipText(name.trim(), 60);
124
126
  if (!trimmed || localToClassRefusal(design, node)) return null;
125
127
  const classes = design.classes ?? [];
126
128
  const base = slugify(trimmed).slice(0, 34) || "class";
@@ -154,7 +156,7 @@ export function duplicateClass(
154
156
  // At the cap the copy would make the design invalid and the save fail (W-218).
155
157
  if (!source || classes.length >= MAX_CLASSES) return design;
156
158
  // W-277: "Card copy", then "Card copy 2"…, so the copy's name is free too.
157
- const stem = `${source.name.slice(0, 52).trim()} copy`;
159
+ const stem = `${clipText(source.name, 52).trim()} copy`;
158
160
  let baseName = stem;
159
161
  for (let n = 2; n <= MAX_CLASSES && classNameTaken(design, baseName); n++) {
160
162
  baseName = `${stem} ${n}`;
@@ -1,3 +1,4 @@
1
+ import { sameJson } from "../stable-json.ts";
1
2
  import type { DesignSystem } from "../schema/design.ts";
2
3
 
3
4
  export type DesignChange = {
@@ -6,7 +7,8 @@ export type DesignChange = {
6
7
  name: string;
7
8
  };
8
9
 
9
- const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
10
+ /** Key order is ignored: an edit that removes and re-adds a value is no change (W-519). */
11
+ const same = sameJson;
10
12
 
11
13
  /** What Publish styles will write: draft compared with the published design (W-340). */
12
14
  export function designChanges(published: DesignSystem, draft: DesignSystem): DesignChange[] {
@@ -1,8 +1,10 @@
1
+ import { sameJson } from "../stable-json.ts";
1
2
  import { emptyDesign, type DesignSystem } from "../schema/design.ts";
2
3
 
3
4
  export type DesignConflict = { kind: "variable" | "class" | "setting"; name: string };
4
5
 
5
- const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
6
+ /** Key order is ignored: an edit that removes and re-adds a value is no change (W-519). */
7
+ const same = sameJson;
6
8
 
7
9
  type Named = { id: string; name: string };
8
10
 
@@ -1,3 +1,4 @@
1
+ import { clipText, MAX_DESIGN_BYTES } from "../limits.ts";
1
2
  import { DesignSystem as DesignSystemSchema, DESIGN_SCHEMA_VERSION } from "../schema/design.ts";
2
3
  import type { DesignSystem } from "../schema/design.ts";
3
4
  import { DESIGN_MIGRATIONS, upgradeLayout } from "../migrate/index.ts";
@@ -21,7 +22,7 @@ export type DesignImport =
21
22
  function freeName(name: string, taken: Set<string>): string {
22
23
  for (let n = 2; ; n++) {
23
24
  const suffix = ` ${n}`;
24
- const next = `${name.slice(0, 60 - suffix.length).trim()}${suffix}`;
25
+ const next = `${clipText(name, 60 - suffix.length).trim()}${suffix}`;
25
26
  if (!taken.has(next.toLowerCase())) return next;
26
27
  }
27
28
  }
@@ -83,7 +84,17 @@ export function designFromJson(text: string): DesignImport {
83
84
  }
84
85
  const result = DesignSystemSchema.safeParse(upgraded.doc);
85
86
  if (!result.success) return { ok: false, message: "That file is not an EmVB design document." };
86
- return { ok: true, ...uniqueImportNames(result.data) };
87
+ const imported = uniqueImportNames(result.data);
88
+ // W-516: the file cap is 1 MB, but the saved design is capped lower; a design over that cap
89
+ // replaced the site styles in the editor and then every save of them was refused.
90
+ const bytes = new TextEncoder().encode(JSON.stringify(imported.design)).length;
91
+ if (bytes > MAX_DESIGN_BYTES) {
92
+ return {
93
+ ok: false,
94
+ message: `That design is ${Math.ceil(bytes / 1024)} KB; site styles can be at most ${MAX_DESIGN_BYTES / 1024} KB. Remove some classes or variables from the file, then import it again.`,
95
+ };
96
+ }
97
+ return { ok: true, ...imported };
87
98
  }
88
99
 
89
100
  /** The largest design file Import reads (W-214); the saved design is capped far lower. */
@@ -1,3 +1,4 @@
1
+ import { clipText } from "../limits.ts";
1
2
  import type { DesignSystem } from "../schema/design.ts";
2
3
  import type { Layout } from "../schema/layout.ts";
3
4
  import { cleanClassName } from "./classes.ts";
@@ -279,7 +280,7 @@ export function duplicateVariable(
279
280
  // A copy past the cap, or a name past 60 characters, would fail to save (W-219).
280
281
  if (!source || variableListFull(design, kind)) return design;
281
282
  // W-278: "Brand copy", then "Brand copy 2"…, so the copy's name is free too.
282
- const stem = `${source.name.slice(0, 52).trim()} copy`;
283
+ const stem = `${clipText(source.name, 52).trim()} copy`;
283
284
  let name = stem;
284
285
  for (let n = 2; n <= MAX_VARIABLES[kind] && variableNameTaken(design, kind, name); n++) {
285
286
  name = `${stem} ${n}`;
@@ -166,7 +166,7 @@ export const loop: ElementDefinition<LoopNode> = {
166
166
  ".emvb-loop-grid,.emvb-loop-cards{display:grid;grid-template-columns:repeat(var(--emvb-loop-columns,3),minmax(0,1fr))}" +
167
167
  ".emvb-loop-cards>.emvb-loop-item{padding:1rem;border:1px solid color-mix(in srgb,currentColor 15%,transparent);border-radius:12px;background:color-mix(in srgb,currentColor 3%,transparent)}" +
168
168
  ".emvb-loop-grid>.emvb-loop-empty,.emvb-loop-cards>.emvb-loop-empty{grid-column:1/-1}" +
169
- "@media (max-width: 767px){.emvb-loop-grid,.emvb-loop-cards{grid-template-columns:minmax(0,1fr)}}",
169
+ "@media (max-width: 767.98px){.emvb-loop-grid,.emvb-loop-cards{grid-template-columns:minmax(0,1fr)}}",
170
170
  defaults: () => ({ type: "loop", props: {}, children: [] }),
171
171
  descriptor: {
172
172
  type: "loop",
@@ -310,6 +310,14 @@ export const pagination: ElementDefinition<PaginationNode> = {
310
310
  message:
311
311
  '{page} and {total} are filled in. EmDash 1.2 doesn\'t report a total, so the count shows "Page N" until it does.',
312
312
  },
313
+ {
314
+ key: "titleText",
315
+ kind: "text",
316
+ label: "Page title text",
317
+ optional: true,
318
+ message:
319
+ 'The browser title of page 2 onward. {title} and {page} are filled in; unset is "{title} – page {page}".',
320
+ },
313
321
  ],
314
322
  },
315
323
  // Rendered by core/render/pagination.ts from the archive's page data (W-222).
@@ -44,7 +44,8 @@ const FORM_FIELD_CSS =
44
44
  ':where(.emvb-form .ec-form-input[aria-invalid="true"]){border-color:#b3261e}' +
45
45
  ':where(.emvb-form input[type="checkbox"],.emvb-form input[type="radio"]){width:1.1em;height:1.1em;margin:0;accent-color:currentColor}' +
46
46
  ":where(.emvb-form .emvb-form-checkbox-label,.emvb-form .emvb-form-radio-label){display:inline-flex;align-items:center;gap:.5em}" +
47
- ":where(.emvb-form .emvb-radio-group){display:flex;flex-direction:column;gap:6px;margin:0;padding:0;border:0}" +
47
+ ":where(.emvb-form .emvb-radio-group){display:flex;flex-direction:column;gap:6px;margin:0;padding:0;border:0;min-width:0}" +
48
+ ":where(.emvb-form .emvb-radio-group>legend){float:left;width:100%;margin:0 0 -2px;padding:0}" +
48
49
  ":where(.emvb-form .ec-form-error){font-size:.875em;color:#b3261e}";
49
50
 
50
51
  export const form: ElementDefinition<FormNode> = {
@@ -185,15 +186,22 @@ export const radio: ElementDefinition<RadioNode> = {
185
186
  const name = node.props.field;
186
187
  // Options filled from definition in W-035; placeholder single option for schema/render smoke.
187
188
  const id = controlId(node.id);
188
- // W-442: a fieldset can't be the target of <label for>, so the question named nothing and
189
- // the group was read without it. The label names the group through aria-labelledby.
190
- const labelled: Record<string, string> = node.props.label
191
- ? { "aria-labelledby": `${id}-label` }
192
- : {};
189
+ // W-524: the question is the fieldset's <legend>, so the group is named natively (it was a
190
+ // <label> pointing at nothing plus aria-labelledby, W-442). The id stays for old references.
191
+ const legend: VNode[] = node.props.label
192
+ ? [
193
+ {
194
+ tag: "legend",
195
+ attrs: { class: "emvb-form-label", id: `${id}-label` },
196
+ children: [node.props.label],
197
+ },
198
+ ]
199
+ : [];
193
200
  const control: VNode = {
194
201
  tag: "fieldset",
195
- attrs: { class: "emvb-radio-group", ...labelled },
202
+ attrs: { class: "emvb-radio-group" },
196
203
  children: [
204
+ ...legend,
197
205
  {
198
206
  tag: "label",
199
207
  attrs: { class: "emvb-form-radio-label" },
@@ -204,16 +212,7 @@ export const radio: ElementDefinition<RadioNode> = {
204
212
  },
205
213
  ],
206
214
  };
207
- const label: VNode[] = node.props.label
208
- ? [
209
- {
210
- tag: "label",
211
- attrs: { class: "emvb-form-label", id: `${id}-label` },
212
- children: [node.props.label],
213
- },
214
- ]
215
- : [];
216
- return fieldBox(attrs, [...label, control, errorSlot(name)]);
215
+ return fieldBox(attrs, [control, errorSlot(name)]);
217
216
  },
218
217
  };
219
218
 
@@ -1,4 +1,4 @@
1
- import { MAX_TEXT_LENGTH } from "../limits.ts";
1
+ import { clipText, MAX_TEXT_LENGTH } from "../limits.ts";
2
2
  import type { LayoutNode } from "../schema/layout.ts";
3
3
 
4
4
  /** Elements whose visible words are one `props.text` string (W-097). */
@@ -23,7 +23,7 @@ export function isMultilineText(node: LayoutNode): boolean {
23
23
  /** The string a canvas edit may store. Over-long text is cut to the schema limit. */
24
24
  export function commitPlainText(text: string, multiline: boolean): string {
25
25
  const flat = multiline ? text : text.replaceAll("\n", "");
26
- return flat.slice(0, MAX_TEXT_LENGTH);
26
+ return clipText(flat, MAX_TEXT_LENGTH);
27
27
  }
28
28
 
29
29
  export function withPlainText(node: LayoutNode, text: string): LayoutNode {
@@ -1,5 +1,6 @@
1
1
  import { isFormNode, type Layout, type LayoutNode } from "../schema/layout.ts";
2
- import { forEachNode, someNode } from "../tree-ops.ts";
2
+ import { audienceSummary } from "../audience/rules.ts";
3
+ import { forEachNode, nodeChildren, someNode } from "../tree-ops.ts";
3
4
  import { fieldsOf, type FormDefinitions } from "./definition.ts";
4
5
 
5
6
  export type MissingRequiredField = {
@@ -50,3 +51,149 @@ export function findMissingRequiredFields(
50
51
  export function layoutHasForm(layout: Layout): boolean {
51
52
  return someNode(layout.root, (node) => isFormNode(node) && node.props.formId.trim() !== "");
52
53
  }
54
+
55
+ /** A field as the forms plugin defines it; only what the checks below read. */
56
+ export type RequiredFieldInfo = { name: string; label: string; required: boolean };
57
+
58
+ /**
59
+ * A required field visitors can't fill (W-511): `missing` has no control in the form; `hidden`
60
+ * has its controls hidden on some device, where the form then can never be sent (the forms
61
+ * client checks the hidden control and writes its error where nobody sees it).
62
+ */
63
+ export type RequiredFieldIssue =
64
+ | { kind: "missing"; formNodeId: string; field: string; label: string }
65
+ | {
66
+ kind: "hidden";
67
+ formNodeId: string;
68
+ field: string;
69
+ label: string;
70
+ /** The bound control (the first one, when the field is bound more than once). */
71
+ nodeId: string;
72
+ devices: string[];
73
+ }
74
+ | {
75
+ kind: "audience";
76
+ formNodeId: string;
77
+ field: string;
78
+ label: string;
79
+ nodeId: string;
80
+ /** Who sees it, e.g. "Only CA · returning", or "Variant B of A/B test hero". */
81
+ who: string;
82
+ };
83
+
84
+ const FIELD_TYPES = new Set(["text-input", "textarea", "select", "checkbox", "radio"]);
85
+ const DEVICE_ORDER = ["desktop", "tablet", "mobile"];
86
+
87
+ /** Each bound field's controls, with the devices each is hidden on (itself or an ancestor). */
88
+ type Control = { nodeId: string; hidden: Set<string>; who?: string };
89
+
90
+ /**
91
+ * W-513: who an element is limited to, by a Visitors rule or as one arm of an A/B test, or
92
+ * undefined when everyone sees it.
93
+ */
94
+ function restriction(node: LayoutNode): string | undefined {
95
+ const audience = node.audience;
96
+ if (audience) {
97
+ const { hide, timeZone: _zone, ...rules } = audience;
98
+ if (hide || Object.values(rules).some((rule) => rule !== undefined)) {
99
+ return audienceSummary(audience);
100
+ }
101
+ }
102
+ if (node.variant) {
103
+ return `Variant ${node.variant.arm.toUpperCase()} of A/B test ${node.variant.test}`;
104
+ }
105
+ return undefined;
106
+ }
107
+
108
+ function boundControls(form: LayoutNode): Map<string, Control[]> {
109
+ const found = new Map<string, Control[]>();
110
+ const walk = (node: LayoutNode, inherited: ReadonlySet<string>, limited: string | undefined) => {
111
+ const own = (node as { hiddenOn?: readonly string[] }).hiddenOn ?? [];
112
+ const hidden = own.length ? new Set([...inherited, ...own]) : inherited;
113
+ const who = limited ?? restriction(node);
114
+ if (FIELD_TYPES.has(node.type)) {
115
+ const field = (node.props as { field?: unknown }).field;
116
+ if (typeof field === "string" && field) {
117
+ const control: Control = { nodeId: node.id, hidden: new Set(hidden) };
118
+ if (who) control.who = who;
119
+ found.set(field, [...(found.get(field) ?? []), control]);
120
+ }
121
+ }
122
+ for (const child of nodeChildren(node)) walk(child, hidden, who);
123
+ };
124
+ // The form's own hiddenOn or audience hides the whole form, which loses no answers: not counted.
125
+ for (const child of nodeChildren(form)) walk(child, new Set(), undefined);
126
+ return found;
127
+ }
128
+
129
+ /**
130
+ * Two controls that split the visitors between them (A and B of one test, or "Only X" and
131
+ * "Hidden for X") still reach everyone.
132
+ */
133
+ function coversEveryone(controls: readonly Control[]): boolean {
134
+ const who = new Set(controls.map((control) => control.who));
135
+ for (const label of who) {
136
+ if (!label) continue;
137
+ const ab = /^Variant ([AB]) of (A\/B test .+)$/.exec(label);
138
+ if (ab && who.has(`Variant ${ab[1] === "A" ? "B" : "A"} of ${ab[2]}`)) return true;
139
+ if (label.startsWith("Only ") && who.has(`Hidden for ${label.slice(5)}`)) return true;
140
+ }
141
+ return false;
142
+ }
143
+
144
+ /** W-511: required fields of the form element's definition that visitors can't fill. */
145
+ export function requiredFieldIssues(
146
+ form: LayoutNode,
147
+ fields: readonly RequiredFieldInfo[],
148
+ ): RequiredFieldIssue[] {
149
+ const controls = boundControls(form);
150
+ const issues: RequiredFieldIssue[] = [];
151
+ for (const field of fields) {
152
+ if (!field.required) continue;
153
+ const label = field.label.trim() || field.name;
154
+ const bound = controls.get(field.name);
155
+ if (!bound?.length) {
156
+ issues.push({ kind: "missing", formNodeId: form.id, field: field.name, label });
157
+ continue;
158
+ }
159
+ // Hidden on a device only when every control for the field is hidden there.
160
+ const devices = DEVICE_ORDER.filter((device) => bound.every((c) => c.hidden.has(device)));
161
+ if (devices.length) {
162
+ issues.push({
163
+ kind: "hidden",
164
+ formNodeId: form.id,
165
+ field: field.name,
166
+ label,
167
+ nodeId: (bound[0] as { nodeId: string }).nodeId,
168
+ devices,
169
+ });
170
+ continue;
171
+ }
172
+ // W-513: only some visitors see every control for the field; the rest can't send the form.
173
+ const first = bound[0] as Control;
174
+ if (bound.every((control) => control.who !== undefined) && !coversEveryone(bound)) {
175
+ issues.push({
176
+ kind: "audience",
177
+ formNodeId: form.id,
178
+ field: field.name,
179
+ label,
180
+ nodeId: first.nodeId,
181
+ who: first.who as string,
182
+ });
183
+ }
184
+ }
185
+ return issues;
186
+ }
187
+
188
+ /** The sentence the editor and describe_page show for one issue (W-511). */
189
+ export function requiredFieldIssueText(issue: RequiredFieldIssue): string {
190
+ if (issue.kind === "missing") {
191
+ return `“${issue.label}” is required by the form but has no field here, so the form can't be sent. Add a field bound to ${issue.field}, or make it optional in Forms.`;
192
+ }
193
+ if (issue.kind === "audience") {
194
+ return `“${issue.label}” is required but shown only to some visitors (${issue.who}), so everyone else can't send the form. Remove the rule from the field, or make it optional in Forms.`;
195
+ }
196
+ const where =
197
+ issue.devices.length === 3 ? "on every device" : `on ${issue.devices.join(" and ")}`;
198
+ return `“${issue.label}” is required but hidden ${where}, so visitors there can't send the form. Show the field there, or make it optional in Forms.`;
199
+ }
@@ -1,5 +1,6 @@
1
1
  import { withFreshIds } from "../arrange.ts";
2
2
  import { MAX_NODES } from "../limits.ts";
3
+ import { stableJson } from "../stable-json.ts";
3
4
  import type { Layout, LayoutNode } from "../schema/layout.ts";
4
5
  import { insertNode, nodeChildren, updateNode } from "../tree-ops.ts";
5
6
 
@@ -12,10 +13,13 @@ export type SectionChange = {
12
13
  edits: number;
13
14
  };
14
15
 
15
- /** A stable text of a node without its children, to tell edits from unchanged nodes. */
16
+ /**
17
+ * A stable text of a node without its children, to tell edits from unchanged nodes. Key order
18
+ * is ignored, so the same element saved and reloaded doesn't count as edited (W-518).
19
+ */
16
20
  function own(node: LayoutNode): string {
17
21
  const { children: _children, ...rest } = node as LayoutNode & { children?: unknown };
18
- return JSON.stringify(rest);
22
+ return stableJson(rest);
19
23
  }
20
24
 
21
25
  function index(node: LayoutNode, into = new Map<string, LayoutNode>()): Map<string, LayoutNode> {
@@ -96,6 +100,27 @@ export function diffSections(older: Layout, current: Layout): SectionChange[] {
96
100
  return changes;
97
101
  }
98
102
 
103
+ /** `node` without the CSS ids that `taken` already holds, so a restored section never repeats one. */
104
+ function withoutTakenHtmlIds(node: LayoutNode, taken: Set<string>): LayoutNode {
105
+ const kids = nodeChildren(node);
106
+ const { htmlId, ...rest } = node;
107
+ const keep = htmlId && !taken.has(htmlId) ? { htmlId } : {};
108
+ const out = { ...rest, ...keep } as LayoutNode;
109
+ if (kids.length === 0) return out;
110
+ return { ...out, children: kids.map((child) => withoutTakenHtmlIds(child, taken)) } as LayoutNode;
111
+ }
112
+
113
+ const htmlIdsOf = (node: LayoutNode, skip?: LayoutNode): Set<string> => {
114
+ const ids = new Set<string>();
115
+ const walk = (n: LayoutNode) => {
116
+ if (n === skip) return;
117
+ if (n.htmlId) ids.add(n.htmlId);
118
+ for (const child of nodeChildren(n)) walk(child);
119
+ };
120
+ walk(node);
121
+ return ids;
122
+ };
123
+
99
124
  const count = (node: LayoutNode): number =>
100
125
  1 + nodeChildren(node).reduce((sum, child) => sum + count(child), 0);
101
126
 
@@ -116,11 +141,14 @@ export function restoreSection(
116
141
  const elsewhere = new Set(index(current.root).keys());
117
142
  if (replacing) for (const id of index(replacing).keys()) elsewhere.delete(id);
118
143
  const clashes = [...index(section).keys()].some((id) => elsewhere.has(id));
119
- const incoming = clashes ? withFreshIds(current, section) : section;
144
+ // CSS ids another section took since then stay there: a repeat made the page fail to save (W-517).
145
+ const takenHtml = htmlIdsOf(current.root, replacing);
146
+ const fresh = clashes ? withFreshIds(current, section) : section;
147
+ const incoming = withoutTakenHtmlIds(fresh, takenHtml);
120
148
  const size = count(current.root) - (replacing ? count(replacing) : 0) + count(incoming);
121
149
  if (size > MAX_NODES) return { ok: false, reason: "The page would have too many elements." };
122
150
  if (replacing && !clashes) {
123
- return { ok: true, layout: updateNode(current, sectionId, () => structuredClone(section)) };
151
+ return { ok: true, layout: updateNode(current, sectionId, () => structuredClone(incoming)) };
124
152
  }
125
153
  // Removed (or renewed): after the nearest earlier section that is still on the page.
126
154
  const before = new Set(older.root.children.slice(0, oldIndex).map((n) => n.id));