@perkyzz/emvb 0.5.0 → 0.7.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 (212) 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/access/RequireEditor.tsx +7 -7
  10. package/src/admin/access/role.ts +5 -2
  11. package/src/admin/content-api.ts +10 -3
  12. package/src/admin/content-item.ts +1 -1
  13. package/src/admin/editor/A11yCopilot.tsx +104 -56
  14. package/src/admin/editor/CommandPalette.tsx +29 -13
  15. package/src/admin/editor/Editor.tsx +88 -20
  16. package/src/admin/editor/EditorToasts.tsx +26 -0
  17. package/src/admin/editor/PerfMeter.tsx +97 -72
  18. package/src/admin/editor/ShareLink.tsx +107 -72
  19. package/src/admin/editor/ShortcutsDialog.tsx +27 -16
  20. package/src/admin/editor/Timeline.tsx +255 -160
  21. package/src/admin/editor/TopBar.tsx +71 -14
  22. package/src/admin/editor/canvas/CanvasFrame.tsx +10 -1
  23. package/src/admin/editor/canvas/CanvasTextEdit.tsx +8 -2
  24. package/src/admin/editor/canvas/drop-line.ts +11 -3
  25. package/src/admin/editor/canvas/frame-focus-ring.ts +37 -0
  26. package/src/admin/editor/canvas/use-canvas-dnd.ts +32 -3
  27. package/src/admin/editor/canvas/vnode-react.tsx +7 -0
  28. package/src/admin/editor/collection-previews.ts +16 -1
  29. package/src/admin/editor/dialogs.tsx +38 -14
  30. package/src/admin/editor/dnd/drop-target.ts +26 -1
  31. package/src/admin/editor/edited-noun.ts +15 -0
  32. package/src/admin/editor/editor-chrome.tsx +108 -7
  33. package/src/admin/editor/editor-commands.ts +15 -1
  34. package/src/admin/editor/editor-css.ts +75 -22
  35. package/src/admin/editor/element-chrome.ts +21 -11
  36. package/src/admin/editor/feature-css.ts +45 -13
  37. package/src/admin/editor/icons/IconLibraryDialog.tsx +52 -11
  38. package/src/admin/editor/icons/library.ts +1 -1
  39. package/src/admin/editor/icons/use-icon-library.ts +5 -2
  40. package/src/admin/editor/ime.ts +29 -0
  41. package/src/admin/editor/palette-items.ts +10 -3
  42. package/src/admin/editor/panels/AddPanel.tsx +35 -10
  43. package/src/admin/editor/panels/ClassesSection.tsx +18 -7
  44. package/src/admin/editor/panels/ColorControl.tsx +135 -27
  45. package/src/admin/editor/panels/ConditionsEditor.tsx +52 -26
  46. package/src/admin/editor/panels/ElementPanel.tsx +134 -24
  47. package/src/admin/editor/panels/LayersPanel.tsx +68 -22
  48. package/src/admin/editor/panels/PageSettings.tsx +66 -35
  49. package/src/admin/editor/panels/SiteStylesDrawer.tsx +170 -32
  50. package/src/admin/editor/panels/TokenScales.tsx +76 -36
  51. package/src/admin/editor/panels/TriggerSettings.tsx +50 -12
  52. package/src/admin/editor/panels/TriggersEditor.tsx +2 -1
  53. package/src/admin/editor/panels/VariableSection.tsx +53 -21
  54. package/src/admin/editor/panels/color-space.ts +9 -3
  55. package/src/admin/editor/panels/settings/AdvancedFields.tsx +12 -2
  56. package/src/admin/editor/panels/settings/AudienceEditor.tsx +51 -35
  57. package/src/admin/editor/panels/settings/BackgroundControls.tsx +55 -11
  58. package/src/admin/editor/panels/settings/BackgroundFill.tsx +3 -2
  59. package/src/admin/editor/panels/settings/BindingsEditor.tsx +15 -18
  60. package/src/admin/editor/panels/settings/BoxControl.tsx +2 -1
  61. package/src/admin/editor/panels/settings/ClassChip.tsx +21 -9
  62. package/src/admin/editor/panels/settings/ClassChipInput.tsx +24 -16
  63. package/src/admin/editor/panels/settings/DraftTextField.tsx +41 -3
  64. package/src/admin/editor/panels/settings/EffectsControls.tsx +38 -14
  65. package/src/admin/editor/panels/settings/FieldBindControl.tsx +46 -28
  66. package/src/admin/editor/panels/settings/FieldControl.tsx +38 -15
  67. package/src/admin/editor/panels/settings/FormBindControl.tsx +2 -2
  68. package/src/admin/editor/panels/settings/HintedSwitch.tsx +33 -0
  69. package/src/admin/editor/panels/settings/IconControls.tsx +12 -8
  70. package/src/admin/editor/panels/settings/IconPicker.tsx +2 -0
  71. package/src/admin/editor/panels/settings/ImageSourcesField.tsx +3 -1
  72. package/src/admin/editor/panels/settings/ItemList.tsx +15 -2
  73. package/src/admin/editor/panels/settings/LengthRow.tsx +8 -6
  74. package/src/admin/editor/panels/settings/MediaPicker.tsx +274 -20
  75. package/src/admin/editor/panels/settings/MotionControl.tsx +28 -15
  76. package/src/admin/editor/panels/settings/NumberRow.tsx +9 -3
  77. package/src/admin/editor/panels/settings/PanelSelect.tsx +50 -0
  78. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +25 -18
  79. package/src/admin/editor/panels/settings/RequiredFieldsNotice.tsx +141 -0
  80. package/src/admin/editor/panels/settings/StyleRow.tsx +10 -3
  81. package/src/admin/editor/panels/settings/StyleSources.tsx +4 -1
  82. package/src/admin/editor/panels/settings/VariantEditor.tsx +10 -1
  83. package/src/admin/editor/panels/settings/box-link-name.ts +6 -2
  84. package/src/admin/editor/panels/settings/class-suggest.ts +7 -7
  85. package/src/admin/editor/panels/settings/query-style.ts +38 -9
  86. package/src/admin/editor/panels/settings/svg-images.ts +13 -0
  87. package/src/admin/editor/panels/site-list.tsx +20 -6
  88. package/src/admin/editor/panels/variable-values.ts +25 -4
  89. package/src/admin/editor/restore-deleted.ts +21 -2
  90. package/src/admin/editor/section-templates.ts +81 -12
  91. package/src/admin/editor/shortcuts.ts +17 -2
  92. package/src/admin/editor/store.ts +14 -3
  93. package/src/admin/editor/useEditorCommands.ts +61 -15
  94. package/src/admin/editor/useEditorData.ts +4 -2
  95. package/src/admin/editor/useEditorShortcuts.ts +17 -7
  96. package/src/admin/editor/useNodeActions.ts +61 -6
  97. package/src/admin/editor/useSave.ts +22 -7
  98. package/src/admin/forms-api.ts +2 -0
  99. package/src/admin/image-editor/BlurFocus.tsx +112 -0
  100. package/src/admin/image-editor/Canvas.tsx +261 -0
  101. package/src/admin/image-editor/CropOverlay.tsx +390 -0
  102. package/src/admin/image-editor/CurvesPanel.tsx +395 -0
  103. package/src/admin/image-editor/ExportDialog.tsx +384 -0
  104. package/src/admin/image-editor/ImageEditButton.tsx +83 -0
  105. package/src/admin/image-editor/ImageEditorDialog.tsx +828 -0
  106. package/src/admin/image-editor/MetadataPanel.tsx +194 -0
  107. package/src/admin/image-editor/announce.tsx +65 -0
  108. package/src/admin/image-editor/crop-geometry.ts +162 -0
  109. package/src/admin/image-editor/curve-math.ts +177 -0
  110. package/src/admin/image-editor/data-url-fetch.ts +59 -0
  111. package/src/admin/image-editor/engine.ts +55 -0
  112. package/src/admin/image-editor/exif.ts +82 -0
  113. package/src/admin/image-editor/flatten.ts +54 -0
  114. package/src/admin/image-editor/gpu-fit.ts +81 -0
  115. package/src/admin/image-editor/image-editor-css.ts +400 -0
  116. package/src/admin/image-editor/load.ts +116 -0
  117. package/src/admin/image-editor/panels.tsx +287 -0
  118. package/src/admin/image-editor/parts.tsx +614 -0
  119. package/src/admin/image-editor/save.ts +141 -0
  120. package/src/admin/image-editor/tone-panels.tsx +338 -0
  121. package/src/admin/image-editor/tools.ts +59 -0
  122. package/src/admin/image-editor/worker.ts +111 -0
  123. package/src/admin/media-api.ts +114 -3
  124. package/src/admin/pages/AgentsPage.tsx +138 -27
  125. package/src/admin/pages/CreateDialog.tsx +97 -30
  126. package/src/admin/pages/NewPageDialog.tsx +21 -3
  127. package/src/admin/pages/NewThemePartDialog.tsx +11 -3
  128. package/src/admin/pages/PageList.tsx +14 -6
  129. package/src/admin/pages/SetupShell.tsx +28 -12
  130. package/src/admin/pages/ThemePartList.tsx +27 -7
  131. package/src/admin/pages/list-kit.tsx +106 -24
  132. package/src/admin/search.ts +15 -0
  133. package/src/admin/setup/useSetupStatus.ts +1 -1
  134. package/src/admin/theme-api.ts +13 -3
  135. package/src/admin/ui.ts +78 -22
  136. package/src/astro/EmVBPage.astro +11 -2
  137. package/src/astro/floats/runtime.ts +21 -0
  138. package/src/astro/menu/runtime.ts +34 -1
  139. package/src/astro/popups/runtime.ts +33 -3
  140. package/src/astro/render.ts +6 -0
  141. package/src/astro/resolve-theme.ts +67 -14
  142. package/src/astro/resolve.ts +9 -1
  143. package/src/astro/tabs/runtime.ts +12 -0
  144. package/src/astro/theme-posts.ts +2 -2
  145. package/src/astro/visitor.ts +6 -3
  146. package/src/constants.ts +1 -1
  147. package/src/core/a11y/audit.ts +171 -24
  148. package/src/core/arrange.ts +29 -6
  149. package/src/core/audience/rules.ts +5 -1
  150. package/src/core/audience/variants.ts +29 -3
  151. package/src/core/clipboard.ts +7 -0
  152. package/src/core/css/generate.ts +31 -6
  153. package/src/core/data/bindings.ts +19 -6
  154. package/src/core/design/classes.ts +20 -9
  155. package/src/core/design/diff.ts +9 -1
  156. package/src/core/design/merge.ts +93 -3
  157. package/src/core/design/tokens.ts +16 -2
  158. package/src/core/design/transfer.ts +46 -8
  159. package/src/core/design/variables.ts +32 -10
  160. package/src/core/elements/dynamic-elements.ts +53 -6
  161. package/src/core/elements/form-elements.ts +68 -30
  162. package/src/core/elements/index.ts +83 -38
  163. package/src/core/elements/menu.ts +37 -19
  164. package/src/core/elements/plain-text.ts +2 -2
  165. package/src/core/elements/select-prompt.ts +3 -0
  166. package/src/core/elements/svg-ids.ts +39 -0
  167. package/src/core/forms/binding.ts +190 -2
  168. package/src/core/forms/definition.ts +72 -0
  169. package/src/core/history/diff.ts +49 -4
  170. package/src/core/icons/catalog.ts +3 -2
  171. package/src/core/image-edit/schema.ts +155 -0
  172. package/src/core/image-edit/summary.ts +61 -0
  173. package/src/core/index.ts +29 -1
  174. package/src/core/limits.ts +21 -0
  175. package/src/core/migrate/index.ts +3 -1
  176. package/src/core/perf/meter.ts +51 -8
  177. package/src/core/recipes/index.ts +5 -4
  178. package/src/core/render/context.ts +8 -0
  179. package/src/core/render/dynamic-post.ts +71 -13
  180. package/src/core/render/extras.ts +77 -4
  181. package/src/core/render/form.ts +164 -12
  182. package/src/core/render/index.ts +179 -22
  183. package/src/core/render/loop.ts +43 -7
  184. package/src/core/render/pagination.ts +18 -4
  185. package/src/core/render/section.ts +27 -0
  186. package/src/core/render/tabs.ts +12 -3
  187. package/src/core/render/vnode.ts +1 -1
  188. package/src/core/sanitize/css.ts +15 -2
  189. package/src/core/sanitize/embed-url.ts +42 -5
  190. package/src/core/sanitize/url.ts +2 -1
  191. package/src/core/schema/layout.ts +26 -7
  192. package/src/core/share/link.ts +5 -2
  193. package/src/core/stable-json.ts +15 -0
  194. package/src/core/stats.ts +2 -1
  195. package/src/core/theme/conditions.ts +3 -1
  196. package/src/core/theme/dynamic.ts +57 -23
  197. package/src/core/theme/float.ts +9 -2
  198. package/src/core/theme/pagination.ts +57 -10
  199. package/src/core/theme/popup-markup.ts +23 -5
  200. package/src/core/theme/popup-rules.ts +11 -5
  201. package/src/core/theme/triggers.ts +3 -2
  202. package/src/core/tree-ops.ts +27 -0
  203. package/src/mcp/ports.ts +8 -1
  204. package/src/mcp/rate-limit.ts +2 -1
  205. package/src/mcp/read.ts +82 -3
  206. package/src/mcp/refs.ts +18 -0
  207. package/src/mcp/tools.ts +1 -1
  208. package/src/mcp/write.ts +271 -25
  209. package/src/server/agent-settings.ts +29 -4
  210. package/src/server/hooks.ts +5 -3
  211. package/src/server/icon-routes.ts +33 -9
  212. package/src/server/mcp-routes.ts +74 -11
@@ -0,0 +1,39 @@
1
+ import type { VNode } from "../render/vnode.ts";
2
+
3
+ const URL_REF = /url\(\s*(['"]?)#([^'")\s]+)\1\s*\)/g;
4
+ const ID_LIST_ATTRS = new Set(["aria-labelledby", "aria-describedby"]);
5
+
6
+ /**
7
+ * W-785: ids inside pasted SVG markup ("g", "a", "clip0") were rendered as-is, so two SVGs on
8
+ * a page using the same id resolved every url(#id) and href="#id" to the first one: a second
9
+ * gradient icon painted with the first one's colors. Prefix each internal id with the element's
10
+ * own id and rewrite the references to it. References to ids the SVG doesn't define are left.
11
+ */
12
+ export function scopeSvgIds(children: (VNode | string)[], prefix: string): (VNode | string)[] {
13
+ const ids = new Set<string>();
14
+ const collect = (node: VNode | string): void => {
15
+ if (typeof node === "string") return;
16
+ if (node.attrs.id) ids.add(node.attrs.id);
17
+ node.children.forEach(collect);
18
+ };
19
+ children.forEach(collect);
20
+ if (ids.size === 0) return children;
21
+ const scoped = (id: string) => (ids.has(id) ? `${prefix}-${id}` : id);
22
+ const rewrite = (node: VNode | string): VNode | string => {
23
+ if (typeof node === "string") return node;
24
+ const attrs: Record<string, string> = {};
25
+ for (const [name, value] of Object.entries(node.attrs)) {
26
+ if (name === "id") attrs[name] = scoped(value);
27
+ else if ((name === "href" || name === "xlink:href") && value.startsWith("#"))
28
+ attrs[name] = `#${scoped(value.slice(1))}`;
29
+ else if (ID_LIST_ATTRS.has(name)) attrs[name] = value.split(/\s+/).map(scoped).join(" ");
30
+ else
31
+ attrs[name] = value.replace(
32
+ URL_REF,
33
+ (_m, q: string, id: string) => `url(${q}#${scoped(id)}${q})`,
34
+ );
35
+ }
36
+ return { ...node, attrs, children: node.children.map(rewrite) };
37
+ };
38
+ return children.map(rewrite);
39
+ }
@@ -1,5 +1,13 @@
1
- import { isFormNode, type Layout, type LayoutNode } from "../schema/layout.ts";
2
- import { forEachNode, someNode } from "../tree-ops.ts";
1
+ import {
2
+ isFormNode,
3
+ LAYOUT_SCHEMA_VERSION,
4
+ type Layout,
5
+ type LayoutNode,
6
+ } from "../schema/layout.ts";
7
+ import { loneAbTests } from "../audience/variants.ts";
8
+ import { audienceSummary } from "../audience/rules.ts";
9
+ import { forEachNode, nodeChildren, someNode } from "../tree-ops.ts";
10
+ import { stableJson } from "../stable-json.ts";
3
11
  import { fieldsOf, type FormDefinitions } from "./definition.ts";
4
12
 
5
13
  export type MissingRequiredField = {
@@ -38,6 +46,8 @@ export function findMissingRequiredFields(
38
46
  const definition = definitions.get(node.props.formId);
39
47
  if (!definition) return;
40
48
  const bound = boundFields(node);
49
+ // W-595: a hidden field is sent by the form itself, with no control.
50
+ for (const field of fieldsOf(definition)) if (field.type === "hidden") bound.add(field.name);
41
51
  for (const field of fieldsOf(definition)) {
42
52
  if (field.required && !bound.has(field.name)) {
43
53
  missing.push({ formNodeId: node.id, formId: node.props.formId, field: field.name });
@@ -50,3 +60,181 @@ export function findMissingRequiredFields(
50
60
  export function layoutHasForm(layout: Layout): boolean {
51
61
  return someNode(layout.root, (node) => isFormNode(node) && node.props.formId.trim() !== "");
52
62
  }
63
+
64
+ /** A field as the forms plugin defines it; only what the checks below read. */
65
+ export type RequiredFieldInfo = { name: string; label: string; required: boolean; type?: string };
66
+
67
+ /**
68
+ * A required field visitors can't fill (W-511): `missing` has no control in the form; `hidden`
69
+ * has its controls hidden on some device, where the form then can never be sent (the forms
70
+ * client checks the hidden control and writes its error where nobody sees it).
71
+ */
72
+ export type RequiredFieldIssue =
73
+ | { kind: "missing"; formNodeId: string; field: string; label: string }
74
+ | {
75
+ kind: "hidden";
76
+ formNodeId: string;
77
+ field: string;
78
+ label: string;
79
+ /** The bound control (the first one, when the field is bound more than once). */
80
+ nodeId: string;
81
+ devices: string[];
82
+ }
83
+ | {
84
+ kind: "audience";
85
+ formNodeId: string;
86
+ field: string;
87
+ label: string;
88
+ nodeId: string;
89
+ /** Who sees it, e.g. "Only CA · returning", or "Variant B of A/B test hero". */
90
+ who: string;
91
+ };
92
+
93
+ const FIELD_TYPES = new Set(["text-input", "textarea", "select", "checkbox", "radio"]);
94
+ const DEVICE_ORDER = ["desktop", "tablet", "mobile"];
95
+
96
+ /** Each bound field's controls, with the devices each is hidden on (itself or an ancestor). */
97
+ type Control = { nodeId: string; hidden: Set<string>; who?: string; split?: string };
98
+
99
+ /**
100
+ * W-513: who an element is limited to, by a Visitors rule or as one arm of an A/B test, or
101
+ * undefined when everyone sees it.
102
+ */
103
+ /**
104
+ * W-550: the exact visitors split a node makes, e.g. "ab:hero:a" or "aud:1:{rules}". Two
105
+ * controls cover everyone when they are the two halves of one split; labels alone can't tell
106
+ * (they cut long country lists and leave out the time zone).
107
+ */
108
+ function splitKey(node: LayoutNode, lone: ReadonlySet<string>): string | undefined {
109
+ const audience = node.audience;
110
+ if (audience) {
111
+ const { hide, ...rules } = audience;
112
+ return `aud:${hide ? 1 : 0}:${stableJson(rules)}`;
113
+ }
114
+ if (node.variant && !lone.has(node.variant.test)) {
115
+ return `ab:${node.variant.test}:${node.variant.arm}`;
116
+ }
117
+ return undefined;
118
+ }
119
+
120
+ function restriction(node: LayoutNode, lone: ReadonlySet<string>): string | undefined {
121
+ const audience = node.audience;
122
+ if (audience) {
123
+ const { hide, timeZone: _zone, ...rules } = audience;
124
+ if (hide || Object.values(rules).some((rule) => rule !== undefined)) {
125
+ return audienceSummary(audience);
126
+ }
127
+ }
128
+ // W-628: a test missing an arm isn't run, so its remaining arm reaches everyone.
129
+ if (node.variant && !lone.has(node.variant.test)) {
130
+ return `Variant ${node.variant.arm.toUpperCase()} of A/B test ${node.variant.test}`;
131
+ }
132
+ return undefined;
133
+ }
134
+
135
+ function boundControls(form: LayoutNode): Map<string, Control[]> {
136
+ // A/B arms are siblings, so a test's arms inside a form are all inside it.
137
+ const lone = loneAbTests({ schemaVersion: LAYOUT_SCHEMA_VERSION, root: form } as Layout);
138
+ const found = new Map<string, Control[]>();
139
+ const walk = (
140
+ node: LayoutNode,
141
+ inherited: ReadonlySet<string>,
142
+ limited: { who: string; split?: string } | undefined,
143
+ ) => {
144
+ const own = (node as { hiddenOn?: readonly string[] }).hiddenOn ?? [];
145
+ const hidden = own.length ? new Set([...inherited, ...own]) : inherited;
146
+ let scope = limited;
147
+ if (!scope) {
148
+ const who = restriction(node, lone);
149
+ if (who) scope = { who, split: splitKey(node, lone) };
150
+ }
151
+ if (FIELD_TYPES.has(node.type)) {
152
+ const field = (node.props as { field?: unknown }).field;
153
+ if (typeof field === "string" && field) {
154
+ const control: Control = { nodeId: node.id, hidden: new Set(hidden) };
155
+ if (scope) {
156
+ control.who = scope.who;
157
+ if (scope.split) control.split = scope.split;
158
+ }
159
+ found.set(field, [...(found.get(field) ?? []), control]);
160
+ }
161
+ }
162
+ for (const child of nodeChildren(node)) walk(child, hidden, scope);
163
+ };
164
+ // The form's own hiddenOn or audience hides the whole form, which loses no answers: not counted.
165
+ for (const child of nodeChildren(form)) walk(child, new Set(), undefined);
166
+ return found;
167
+ }
168
+
169
+ /**
170
+ * Two controls that split the visitors between them (A and B of one test, or "Only X" and
171
+ * "Hidden for X") still reach everyone.
172
+ */
173
+ function coversEveryone(controls: readonly Control[]): boolean {
174
+ const splits = new Set(controls.map((control) => control.split));
175
+ for (const key of splits) {
176
+ if (!key) continue;
177
+ const ab = /^ab:(.*):([ab])$/.exec(key);
178
+ if (ab && splits.has(`ab:${ab[1]}:${ab[2] === "a" ? "b" : "a"}`)) return true;
179
+ if (key.startsWith("aud:0:") && splits.has(`aud:1:${key.slice(6)}`)) return true;
180
+ }
181
+ return false;
182
+ }
183
+
184
+ /** W-511: required fields of the form element's definition that visitors can't fill. */
185
+ export function requiredFieldIssues(
186
+ form: LayoutNode,
187
+ fields: readonly RequiredFieldInfo[],
188
+ ): RequiredFieldIssue[] {
189
+ const controls = boundControls(form);
190
+ const issues: RequiredFieldIssue[] = [];
191
+ for (const field of fields) {
192
+ // W-595: a hidden field is sent by the form itself, with no control.
193
+ if (!field.required || field.type === "hidden") continue;
194
+ const label = field.label.trim() || field.name;
195
+ const bound = controls.get(field.name);
196
+ if (!bound?.length) {
197
+ issues.push({ kind: "missing", formNodeId: form.id, field: field.name, label });
198
+ continue;
199
+ }
200
+ // Hidden on a device only when every control for the field is hidden there.
201
+ const devices = DEVICE_ORDER.filter((device) => bound.every((c) => c.hidden.has(device)));
202
+ if (devices.length) {
203
+ issues.push({
204
+ kind: "hidden",
205
+ formNodeId: form.id,
206
+ field: field.name,
207
+ label,
208
+ nodeId: (bound[0] as { nodeId: string }).nodeId,
209
+ devices,
210
+ });
211
+ continue;
212
+ }
213
+ // W-513: only some visitors see every control for the field; the rest can't send the form.
214
+ const first = bound[0] as Control;
215
+ if (bound.every((control) => control.who !== undefined) && !coversEveryone(bound)) {
216
+ issues.push({
217
+ kind: "audience",
218
+ formNodeId: form.id,
219
+ field: field.name,
220
+ label,
221
+ nodeId: first.nodeId,
222
+ who: first.who as string,
223
+ });
224
+ }
225
+ }
226
+ return issues;
227
+ }
228
+
229
+ /** The sentence the editor and describe_page show for one issue (W-511). */
230
+ export function requiredFieldIssueText(issue: RequiredFieldIssue): string {
231
+ if (issue.kind === "missing") {
232
+ 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.`;
233
+ }
234
+ if (issue.kind === "audience") {
235
+ 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.`;
236
+ }
237
+ const where =
238
+ issue.devices.length === 3 ? "on every device" : `on ${issue.devices.join(" and ")}`;
239
+ 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.`;
240
+ }
@@ -43,3 +43,75 @@ export function fieldByName(
43
43
  if (!definition) return undefined;
44
44
  return fieldsOf(definition).find((field) => field.name === name);
45
45
  }
46
+
47
+ /** W-577: a field whose limits no answer can meet (min above max), so the form can't be sent. */
48
+ export type ImpossibleRangeField = {
49
+ name: string;
50
+ label: string;
51
+ kind: "length" | "value" | "both";
52
+ };
53
+
54
+ const above = (lo: unknown, hi: unknown) =>
55
+ typeof lo === "number" && typeof hi === "number" && lo > hi;
56
+
57
+ export function impossibleRangeFields(
58
+ fields: ReadonlyArray<{ name: string; label: string; validation?: unknown }>,
59
+ ): ImpossibleRangeField[] {
60
+ const found: ImpossibleRangeField[] = [];
61
+ for (const field of fields) {
62
+ const v = field.validation;
63
+ if (!v || typeof v !== "object") continue;
64
+ const { minLength, maxLength, min, max } = v as Record<string, unknown>;
65
+ const label = field.label.trim() || field.name;
66
+ const badLength = above(minLength, maxLength);
67
+ const badValue = above(min, max);
68
+ // W-589: report both problems together so fixing one doesn't reveal the other later.
69
+ if (badLength || badValue) {
70
+ const kind = badLength && badValue ? "both" : badLength ? "length" : "value";
71
+ found.push({ name: field.name, label, kind });
72
+ }
73
+ }
74
+ return found;
75
+ }
76
+
77
+ /**
78
+ * W-579: a control that can't send any answer its field accepts. A field with a fixed list of
79
+ * options (select, radio, checkbox group) is refused by the forms plugin unless the value is one
80
+ * of them, so a Text input, Textarea or Checkbox bound to it makes the form unsendable.
81
+ */
82
+ export type MismatchedControl = { nodeId: string; name: string; label: string; fieldType: string };
83
+
84
+ const OPTION_TYPES = new Set(["select", "radio", "checkbox-group"]);
85
+ const FREE_CONTROLS = new Set(["text-input", "textarea", "checkbox"]);
86
+
87
+ type ControlLike = { id: string; type: string; props: unknown; children?: readonly ControlLike[] };
88
+
89
+ export function mismatchedControls(
90
+ form: ControlLike,
91
+ fields: ReadonlyArray<{
92
+ name: string;
93
+ type: string;
94
+ label: string;
95
+ options?: readonly unknown[];
96
+ }>,
97
+ ): MismatchedControl[] {
98
+ const byName = new Map(fields.map((field) => [field.name, field]));
99
+ const found: MismatchedControl[] = [];
100
+ const visit = (node: ControlLike) => {
101
+ if (FREE_CONTROLS.has(node.type)) {
102
+ const name = (node.props as { field?: unknown }).field;
103
+ const field = typeof name === "string" ? byName.get(name) : undefined;
104
+ if (field && OPTION_TYPES.has(field.type) && (field.options?.length ?? 0) > 0) {
105
+ found.push({
106
+ nodeId: node.id,
107
+ name: field.name,
108
+ label: field.label.trim() || field.name,
109
+ fieldType: field.type,
110
+ });
111
+ }
112
+ }
113
+ for (const child of node.children ?? []) visit(child);
114
+ };
115
+ for (const child of form.children ?? []) visit(child);
116
+ return found;
117
+ }
@@ -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
 
@@ -104,6 +129,21 @@ const count = (node: LayoutNode): number =>
104
129
  * current section with the same id, or, if it was removed, goes back near its old place. Ids
105
130
  * already used elsewhere on the page are renewed, so the page stays valid.
106
131
  */
132
+ /** `node` with the A/B mark removed from every element whose id is in `live` (W-636). */
133
+ function withoutCopiedArms(node: LayoutNode, live: ReadonlySet<string>): LayoutNode {
134
+ let next = node;
135
+ if (node.variant && live.has(node.id)) {
136
+ next = { ...node };
137
+ delete next.variant;
138
+ }
139
+ const kids = nodeChildren(next);
140
+ if (kids.length === 0) return next;
141
+ return {
142
+ ...next,
143
+ children: kids.map((child) => withoutCopiedArms(child, live)),
144
+ } as LayoutNode;
145
+ }
146
+
107
147
  export function restoreSection(
108
148
  current: Layout,
109
149
  older: Layout,
@@ -116,11 +156,16 @@ export function restoreSection(
116
156
  const elsewhere = new Set(index(current.root).keys());
117
157
  if (replacing) for (const id of index(replacing).keys()) elsewhere.delete(id);
118
158
  const clashes = [...index(section).keys()].some((id) => elsewhere.has(id));
119
- const incoming = clashes ? withFreshIds(current, section) : section;
159
+ // CSS ids another section took since then stay there: a repeat made the page fail to save (W-517).
160
+ const takenHtml = htmlIdsOf(current.root, replacing);
161
+ // An element still on the page elsewhere comes back as a copy, and a copy is never part of an
162
+ // A/B test (W-629/W-632): it would add a second copy of a live arm (W-636).
163
+ const fresh = clashes ? withFreshIds(current, withoutCopiedArms(section, elsewhere)) : section;
164
+ const incoming = withoutTakenHtmlIds(fresh, takenHtml);
120
165
  const size = count(current.root) - (replacing ? count(replacing) : 0) + count(incoming);
121
166
  if (size > MAX_NODES) return { ok: false, reason: "The page would have too many elements." };
122
167
  if (replacing && !clashes) {
123
- return { ok: true, layout: updateNode(current, sectionId, () => structuredClone(section)) };
168
+ return { ok: true, layout: updateNode(current, sectionId, () => structuredClone(incoming)) };
124
169
  }
125
170
  // Removed (or renewed): after the nearest earlier section that is still on the page.
126
171
  const before = new Set(older.root.children.slice(0, oldIndex).map((n) => n.id));
@@ -62,8 +62,9 @@ export const BUNDLED_ICONS: readonly BundledIcon[] = [
62
62
  label: "Circle Alert",
63
63
  children: [
64
64
  { tag: "circle", attrs: { cx: "12", cy: "12", r: "10" } },
65
- { tag: "line", attrs: {} },
66
- { tag: "line", attrs: {} },
65
+ // W-699: the mark's two lines had no coordinates, so the icon drew an empty circle.
66
+ { tag: "line", attrs: { x1: "12", x2: "12", y1: "8", y2: "12" } },
67
+ { tag: "line", attrs: { x1: "12", x2: "12.01", y1: "16", y2: "16" } },
67
68
  ],
68
69
  },
69
70
  {
@@ -0,0 +1,155 @@
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
+ /** Backslashes and control characters, which URL parsing rewrites or drops. */
86
+ function hasUnsafeUrlChar(s: string): boolean {
87
+ for (const ch of s) {
88
+ const code = ch.charCodeAt(0);
89
+ if (ch === "\\" || code < 0x20 || code === 0x7f) return true;
90
+ }
91
+ return false;
92
+ }
93
+
94
+ /**
95
+ * A blend image must be a same-site path or an https URL; `data:` blends (picked files) are
96
+ * refused because they would put a whole image into the layout.
97
+ */
98
+ const BlendSrc = z
99
+ .string()
100
+ .max(2000)
101
+ .refine(
102
+ // A backslash or control character can turn "/\\host" into another host (W-534).
103
+ (s) => !hasUnsafeUrlChar(s) && (/^\/(?!\/)/.test(s) || /^https:\/\//i.test(s)),
104
+ "Blend images must be a site path or an https URL",
105
+ );
106
+
107
+ export const ImageEditRecipe = z.strictObject({
108
+ version: z.literal(1),
109
+ name: z.string().max(80).optional(),
110
+ lights: Lights.optional(),
111
+ colors: Colors.optional(),
112
+ effects: Effects.optional(),
113
+ blur: Blur.optional(),
114
+ curves: Curves.optional(),
115
+ blend: z.strictObject({ src: BlendSrc, mix: Unit }).optional(),
116
+ filters: z.strictObject({ label: FilterLabel, strength: Unit.optional() }).optional(),
117
+ geometry: Geometry.optional(),
118
+ });
119
+ export type ImageEditRecipe = z.infer<typeof ImageEditRecipe>;
120
+
121
+ export const IMAGE_EDIT_FORMATS = ["webp", "jpeg", "png"] as const;
122
+
123
+ export const ImageEditOutput = z.strictObject({
124
+ format: z.enum(IMAGE_EDIT_FORMATS),
125
+ /** 0..1 for webp and jpeg. */
126
+ quality: z.number().finite().min(0.1).max(1).optional(),
127
+ /** The longest side was capped to this many pixels. */
128
+ maxSide: z.number().int().min(16).max(10000).optional(),
129
+ stripGps: z.boolean(),
130
+ });
131
+ export type ImageEditOutput = z.infer<typeof ImageEditOutput>;
132
+
133
+ function byteLength(value: unknown): number {
134
+ return new TextEncoder().encode(JSON.stringify(value)).length;
135
+ }
136
+
137
+ export const ImageEdit = z.strictObject({
138
+ /** Our record version. */
139
+ v: z.literal(1),
140
+ engine: z.literal("photocn"),
141
+ engineVersion: z
142
+ .string()
143
+ .regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]{1,32})?$/, "A version like 0.1.2"),
144
+ recipe: ImageEditRecipe.refine((r) => byteLength(r) <= IMAGE_EDIT_RECIPE_MAX_BYTES, {
145
+ message: `The edit recipe is larger than ${IMAGE_EDIT_RECIPE_MAX_BYTES / 1024} KB`,
146
+ }),
147
+ /** The untouched source in the media library. */
148
+ originalMediaId: z.string().min(1).max(128).optional(),
149
+ /** Same-origin URL of the source, for re-opening when the media item is gone. */
150
+ originalSrc: z.string().min(1).max(2000),
151
+ output: ImageEditOutput,
152
+ /** ISO 8601 timestamp of the save. */
153
+ editedAt: z.iso.datetime({ offset: true }),
154
+ });
155
+ export type ImageEdit = z.infer<typeof ImageEdit>;
@@ -0,0 +1,61 @@
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 && recipe.filters.strength !== 0) {
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
+ // Shown as a whole percent: a nudge that rounds to 0 is no change (W-551).
49
+ if (typeof value === "number" && Math.round(value * 100) !== 0)
50
+ parts.push(`${LABELS[key] ?? key} ${signed(value)}`);
51
+ }
52
+ }
53
+ if (recipe.curves?.some((c) => c !== null)) parts.push("Curves");
54
+ // The centre alone blurs nothing (W-551).
55
+ const blur = recipe.blur;
56
+ if (blur && (blur.bokehstrength || blur.gaussianstrength)) parts.push("Blur");
57
+ if (recipe.blend) parts.push("Blend");
58
+ if (parts.length === 0) return "No changes";
59
+ if (parts.length <= max) return parts.join(" · ");
60
+ return `${parts.slice(0, max).join(" · ")} · +${parts.length - max} more`;
61
+ }