@perkyzz/emvb 0.2.1 → 0.4.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 (150) hide show
  1. package/README.md +4 -2
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/package.json +3 -1
  4. package/src/admin/access/role.ts +9 -3
  5. package/src/admin/api.ts +17 -7
  6. package/src/admin/content-api.ts +7 -51
  7. package/src/admin/content-item.ts +22 -0
  8. package/src/admin/design-api.ts +30 -0
  9. package/src/admin/editor/A11yCopilot.tsx +126 -0
  10. package/src/admin/editor/CommandPalette.tsx +118 -0
  11. package/src/admin/editor/Editor.tsx +188 -152
  12. package/src/admin/editor/EditorOverlay.tsx +9 -1
  13. package/src/admin/editor/PerfMeter.tsx +121 -0
  14. package/src/admin/editor/ShareLink.tsx +164 -0
  15. package/src/admin/editor/ShortcutsDialog.tsx +4 -1
  16. package/src/admin/editor/Timeline.tsx +287 -0
  17. package/src/admin/editor/TopBar.tsx +4 -0
  18. package/src/admin/editor/canvas/CanvasFrame.tsx +62 -370
  19. package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
  20. package/src/admin/editor/canvas/SelectionOverlay.tsx +87 -47
  21. package/src/admin/editor/canvas/canvas-scale.ts +20 -0
  22. package/src/admin/editor/canvas/drop-line.ts +24 -0
  23. package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
  24. package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
  25. package/src/admin/editor/collection-previews.ts +114 -0
  26. package/src/admin/editor/editor-chrome.tsx +346 -0
  27. package/src/admin/editor/editor-commands.ts +360 -0
  28. package/src/admin/editor/editor-css.ts +5 -3
  29. package/src/admin/editor/element-chrome.ts +89 -0
  30. package/src/admin/editor/feature-css.ts +105 -0
  31. package/src/admin/editor/host.ts +35 -0
  32. package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
  33. package/src/admin/editor/icons/library.ts +29 -19
  34. package/src/admin/editor/icons/use-icon-library.ts +315 -0
  35. package/src/admin/editor/live-data.tsx +71 -0
  36. package/src/admin/editor/palette-items.ts +136 -0
  37. package/src/admin/editor/palette.ts +68 -0
  38. package/src/admin/editor/panels/AddPanel.tsx +48 -68
  39. package/src/admin/editor/panels/ClassesSection.tsx +5 -1
  40. package/src/admin/editor/panels/ColorControl.tsx +2 -10
  41. package/src/admin/editor/panels/ElementPanel.tsx +74 -102
  42. package/src/admin/editor/panels/LayersPanel.tsx +72 -63
  43. package/src/admin/editor/panels/LeftPanel.tsx +4 -1
  44. package/src/admin/editor/panels/SettingsPanel.tsx +13 -0
  45. package/src/admin/editor/panels/SiteStylesDrawer.tsx +18 -10
  46. package/src/admin/editor/panels/TokenScales.tsx +168 -0
  47. package/src/admin/editor/panels/VariableSection.tsx +10 -14
  48. package/src/admin/editor/panels/inline-error.tsx +11 -0
  49. package/src/admin/editor/panels/settings/AdvancedFields.tsx +87 -1
  50. package/src/admin/editor/panels/settings/AudienceEditor.tsx +285 -0
  51. package/src/admin/editor/panels/settings/BindingsEditor.tsx +221 -0
  52. package/src/admin/editor/panels/settings/ClassChipInput.tsx +1 -1
  53. package/src/admin/editor/panels/settings/DraftTextField.tsx +4 -0
  54. package/src/admin/editor/panels/settings/EffectsControls.tsx +2 -2
  55. package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
  56. package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
  57. package/src/admin/editor/panels/settings/MotionControl.tsx +252 -0
  58. package/src/admin/editor/panels/settings/StateSwitcher.tsx +1 -1
  59. package/src/admin/editor/panels/settings/StyleRow.tsx +26 -2
  60. package/src/admin/editor/panels/settings/StyleSources.tsx +94 -0
  61. package/src/admin/editor/panels/settings/VariableBinding.tsx +1 -1
  62. package/src/admin/editor/panels/settings/VariantEditor.tsx +83 -0
  63. package/src/admin/editor/panels/settings/form-names.ts +7 -11
  64. package/src/admin/editor/panels/settings/length-units.ts +16 -5
  65. package/src/admin/editor/panels/settings/style-sections.ts +7 -2
  66. package/src/admin/editor/panels/style-target.ts +105 -0
  67. package/src/admin/editor/section-templates.ts +43 -21
  68. package/src/admin/editor/shortcuts.ts +6 -1
  69. package/src/admin/editor/store.ts +10 -1
  70. package/src/admin/editor/useClipboardActions.ts +1 -1
  71. package/src/admin/editor/useEditorCommands.ts +61 -13
  72. package/src/admin/editor/useEditorData.ts +7 -1
  73. package/src/admin/editor/useEditorShortcuts.ts +30 -14
  74. package/src/admin/editor/useNodeActions.ts +44 -16
  75. package/src/admin/forms-api.ts +17 -6
  76. package/src/admin/icon-uploads-api.ts +18 -0
  77. package/src/admin/theme-api.ts +5 -18
  78. package/src/admin/ui.ts +4 -4
  79. package/src/astro/content-port.ts +24 -0
  80. package/src/astro/forms/EmVBFormsClient.astro +11 -0
  81. package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
  82. package/src/astro/forms/client.ts +1 -0
  83. package/src/astro/forms-definitions.ts +24 -11
  84. package/src/astro/index.ts +1 -0
  85. package/src/astro/render-session.ts +85 -0
  86. package/src/astro/request-data.ts +109 -0
  87. package/src/astro/resolve-theme.ts +184 -64
  88. package/src/astro/resolve.ts +63 -16
  89. package/src/astro/theme-posts.ts +48 -5
  90. package/src/astro/visitor.ts +204 -0
  91. package/src/constants.ts +1 -1
  92. package/src/core/a11y/audit.ts +282 -0
  93. package/src/core/arrange.ts +150 -34
  94. package/src/core/audience/rules.ts +124 -0
  95. package/src/core/audience/variants.ts +51 -0
  96. package/src/core/canvas-styles.ts +24 -0
  97. package/src/core/clipboard.ts +11 -32
  98. package/src/core/css/generate.ts +29 -2
  99. package/src/core/css/print.ts +12 -0
  100. package/src/core/css/scope.ts +3 -3
  101. package/src/core/css/trace.ts +169 -0
  102. package/src/core/css-keywords.ts +83 -0
  103. package/src/core/data/bindings.ts +255 -0
  104. package/src/core/design/classes.ts +13 -15
  105. package/src/core/design/diff.ts +55 -0
  106. package/src/core/design/merge.ts +127 -0
  107. package/src/core/design/tokens.ts +127 -0
  108. package/src/core/design/variables.ts +25 -21
  109. package/src/core/elements/dynamic-elements.ts +117 -2
  110. package/src/core/elements/form-elements.ts +1 -0
  111. package/src/core/elements/index.ts +185 -7
  112. package/src/core/forms/binding.ts +4 -13
  113. package/src/core/history/diff.ts +152 -0
  114. package/src/core/index.ts +121 -0
  115. package/src/core/local-style.ts +27 -0
  116. package/src/core/migrate/index.ts +12 -4
  117. package/src/core/nesting.ts +4 -22
  118. package/src/core/perf/meter.ts +160 -0
  119. package/src/core/perf/scripts.ts +61 -0
  120. package/src/core/recipes/index.ts +433 -0
  121. package/src/core/record.ts +3 -0
  122. package/src/core/render/context.ts +2 -0
  123. package/src/core/render/dynamic-post.ts +1 -2
  124. package/src/core/render/form.ts +133 -10
  125. package/src/core/render/index.ts +206 -17
  126. package/src/core/render/loop.ts +54 -7
  127. package/src/core/render/pagination.ts +9 -1
  128. package/src/core/render/vnode.ts +12 -2
  129. package/src/core/sanitize/css.ts +129 -80
  130. package/src/core/sanitize/motion.ts +129 -0
  131. package/src/core/sanitize/svg.ts +8 -3
  132. package/src/core/sanitize/url.ts +10 -1
  133. package/src/core/schema/design.ts +29 -8
  134. package/src/core/schema/layout.ts +291 -169
  135. package/src/core/schema/motion.ts +14 -0
  136. package/src/core/schema/style.ts +101 -66
  137. package/src/core/share/link.ts +187 -0
  138. package/src/core/tabs/presence.ts +7 -17
  139. package/src/core/theme/dynamic.ts +242 -32
  140. package/src/core/theme/float.ts +1 -1
  141. package/src/core/theme/pagination.ts +56 -0
  142. package/src/core/tree-ops.ts +57 -0
  143. package/src/index.ts +14 -2
  144. package/src/server/design-routes.ts +4 -1
  145. package/src/server/icon-routes.ts +68 -16
  146. package/src/server/plugin.ts +8 -2
  147. package/src/admin/editor/icons/sets/fontawesome.json +0 -1
  148. package/src/admin/editor/icons/sets/lucide.json +0 -1
  149. package/src/admin/editor/icons/sets/remix.json +0 -1
  150. package/src/admin/editor/icons/sets/tabler.json +0 -1
@@ -0,0 +1,433 @@
1
+ import { contrastRatio } from "../a11y/audit.ts";
2
+ import type { DesignSystem } from "../schema/design.ts";
3
+ import type { Layout, LayoutNode } from "../schema/layout.ts";
4
+ import type { StyleProps } from "../schema/style.ts";
5
+ import { nodeChildren, newNodeId } from "../tree-ops.ts";
6
+
7
+ type Color = NonNullable<StyleProps["color"]>;
8
+ type Size = NonNullable<StyleProps["fontSize"]>;
9
+
10
+ /** What a recipe takes from Site styles (W-320); unset parts fall back to plain values. */
11
+ export type RecipeTokens = {
12
+ accent?: Color;
13
+ onAccent?: Color;
14
+ ink?: Color;
15
+ muted?: Color;
16
+ surface?: Color;
17
+ display: Size;
18
+ heading: Size;
19
+ subheading: Size;
20
+ body: Size;
21
+ small: Size;
22
+ sectionSpace: Size;
23
+ blockSpace: Size;
24
+ gap: Size;
25
+ tight: Size;
26
+ buttonClass?: string;
27
+ cardClass?: string;
28
+ /** Plain words for what came from the site, for the Add panel. */
29
+ used: string[];
30
+ };
31
+
32
+ const px = (value: number): Size => ({ value, unit: "px" });
33
+
34
+ type Named = { id: string; name: string };
35
+ const words = (v: Named) => `${v.id} ${v.name}`.toLowerCase();
36
+
37
+ /** The first variable whose id or name matches a pattern, trying patterns in order. */
38
+ function pick<T extends Named>(
39
+ list: readonly T[] | undefined,
40
+ ...patterns: RegExp[]
41
+ ): T | undefined {
42
+ for (const pattern of patterns) {
43
+ const found = list?.find((v) => pattern.test(words(v)));
44
+ if (found) return found;
45
+ }
46
+ return undefined;
47
+ }
48
+
49
+ const byId = <T extends Named>(list: readonly T[] | undefined, ...ids: string[]): T | undefined => {
50
+ for (const id of ids) {
51
+ const found = list?.find((v) => v.id === id);
52
+ if (found) return found;
53
+ }
54
+ return undefined;
55
+ };
56
+
57
+ /**
58
+ * The site's colours, type scale, spacing scale and button/card classes a recipe uses (W-320).
59
+ * Colours are matched by name (Primary, Brand, Accent; Text, Ink; Surface, Background…), sizes by
60
+ * the Scales ids (`fs-4xl`, `space-xl`…) or similar names; anything missing falls back.
61
+ */
62
+ export function siteTokens(design: DesignSystem): RecipeTokens {
63
+ const { colors, fontSizes, spacings } = design.variables;
64
+ const used: string[] = [];
65
+ const color = (v: Named | undefined): Color | undefined => {
66
+ if (!v) return undefined;
67
+ used.push(v.name);
68
+ return { var: v.id };
69
+ };
70
+ const sized =
71
+ (from: "fontSize" | "spacing") =>
72
+ (v: Named | undefined, fallback: number): Size => {
73
+ if (!v) return px(fallback);
74
+ used.push(v.name);
75
+ return { var: v.id, from };
76
+ };
77
+ const size = sized("fontSize");
78
+ const space = sized("spacing");
79
+ const accentVar = pick(colors, /\b(primary|brand)\b/, /accent/, /\bmain\b/) ?? colors[0];
80
+ const tokens: RecipeTokens = {
81
+ display: size(byId(fontSizes, "fs-4xl", "fs-3xl") ?? pick(fontSizes, /display|hero|huge/), 48),
82
+ heading: size(byId(fontSizes, "fs-2xl") ?? pick(fontSizes, /\bh2\b|heading (m|l)|title/), 32),
83
+ subheading: size(byId(fontSizes, "fs-xl") ?? pick(fontSizes, /\bh3\b|heading s|subtitle/), 22),
84
+ body: size(byId(fontSizes, "fs-m") ?? pick(fontSizes, /body|base|text m|normal/), 17),
85
+ small: size(byId(fontSizes, "fs-s") ?? pick(fontSizes, /small|caption|text s/), 14),
86
+ sectionSpace: space(
87
+ byId(spacings, "space-3xl", "space-2xl") ?? pick(spacings, /section|huge|2xl|xxl/),
88
+ 80,
89
+ ),
90
+ blockSpace: space(byId(spacings, "space-l") ?? pick(spacings, /\blarge\b|\bl\b/), 32),
91
+ gap: space(byId(spacings, "space-m") ?? pick(spacings, /medium|\bm\b/), 24),
92
+ tight: space(byId(spacings, "space-xs", "space-s") ?? pick(spacings, /small|\bs\b|xs/), 12),
93
+ used,
94
+ };
95
+ const accent = color(accentVar);
96
+ if (accent) tokens.accent = accent;
97
+ const others = colors.filter((c) => c !== accentVar);
98
+ const ink = color(pick(others, /\b(text|ink|foreground|body)\b/, /\bdark\b|black/));
99
+ if (ink) tokens.ink = ink;
100
+ const muted = color(pick(others, /muted|subtle|grey|gray|secondary text/));
101
+ if (muted) tokens.muted = muted;
102
+ const surface = color(pick(others, /surface|background|\bbg\b|light|canvas/));
103
+ if (surface) tokens.surface = surface;
104
+ const onAccent = color(pick(others, /on[- ]?(primary|brand|accent)|inverse|white/));
105
+ if (onAccent) tokens.onAccent = onAccent;
106
+ else if (accentVar && /^#[0-9a-f]{6}$/i.test(accentVar.value)) {
107
+ // No "on accent" colour: white or near-black, whichever reads better on the accent.
108
+ tokens.onAccent =
109
+ contrastRatio(accentVar.value, "#ffffff") >= contrastRatio(accentVar.value, "#111111")
110
+ ? "#ffffff"
111
+ : "#111111";
112
+ }
113
+ const buttonCls = pick(design.classes, /\b(button|btn)\b/, /cta/);
114
+ if (buttonCls) {
115
+ tokens.buttonClass = buttonCls.id;
116
+ used.push(`.${buttonCls.name}`);
117
+ }
118
+ const cardCls = pick(design.classes, /\bcard\b/, /tile|panel|box/);
119
+ if (cardCls) {
120
+ tokens.cardClass = cardCls.id;
121
+ used.push(`.${cardCls.name}`);
122
+ }
123
+ tokens.used = [...new Set(used)];
124
+ return tokens;
125
+ }
126
+
127
+ type Draft = Omit<LayoutNode, "id"> & { children?: Draft[] };
128
+
129
+ const pad = (block: Size, inline: Size = px(24)): StyleProps => ({
130
+ paddingTop: block,
131
+ paddingBottom: block,
132
+ paddingLeft: inline,
133
+ paddingRight: inline,
134
+ });
135
+
136
+ const withClass = (draft: Draft, cls: string | undefined): Draft =>
137
+ cls ? { ...draft, classes: [cls] } : draft;
138
+
139
+ const heading = (text: string, level: number, fontSize: Size, extra: StyleProps = {}): Draft =>
140
+ ({ type: "heading", props: { text, level }, style: { fontSize, ...extra } }) as Draft;
141
+ const text = (value: string, t: RecipeTokens, extra: StyleProps = {}): Draft =>
142
+ ({
143
+ type: "text",
144
+ props: { text: value },
145
+ style: { fontSize: t.body, ...(t.muted ? { color: t.muted } : {}), ...extra },
146
+ }) as Draft;
147
+
148
+ function button(label: string, t: RecipeTokens, primary = true): Draft {
149
+ if (t.buttonClass) {
150
+ return withClass({ type: "button", props: { text: label, href: "#" } } as Draft, t.buttonClass);
151
+ }
152
+ const style: StyleProps = {
153
+ paddingTop: px(12),
154
+ paddingBottom: px(12),
155
+ paddingLeft: px(24),
156
+ paddingRight: px(24),
157
+ borderRadius: px(8),
158
+ fontWeight: 600,
159
+ };
160
+ if (primary && t.accent) {
161
+ style.backgroundColor = t.accent;
162
+ style.color = t.onAccent ?? "#ffffff";
163
+ } else if (t.accent) {
164
+ style.color = t.accent;
165
+ style.borderWidth = px(1);
166
+ style.borderStyle = "solid";
167
+ style.borderColor = t.accent;
168
+ }
169
+ return { type: "button", props: { text: label, href: "#" }, style } as Draft;
170
+ }
171
+
172
+ const flex = (children: Draft[], style: StyleProps): Draft =>
173
+ ({
174
+ type: "flexbox",
175
+ props: {},
176
+ style: { flexDirection: "row", flexWrap: "wrap", ...style },
177
+ children,
178
+ }) as Draft;
179
+ const column = (children: Draft[], style: StyleProps = {}): Draft =>
180
+ ({
181
+ type: "flexbox",
182
+ props: {},
183
+ style: { flexDirection: "column", flexWrap: "nowrap", ...style },
184
+ children,
185
+ }) as Draft;
186
+ const grid = (columns: number, children: Draft[], t: RecipeTokens): Draft =>
187
+ ({
188
+ type: "grid",
189
+ props: { columns, columnsTablet: Math.min(columns, 2), columnsMobile: 1 },
190
+ style: { gap: t.gap },
191
+ children,
192
+ }) as Draft;
193
+
194
+ function band(t: RecipeTokens, children: Draft[], extra: StyleProps = {}): Draft {
195
+ return {
196
+ type: "layout-section",
197
+ props: { tag: "section" },
198
+ style: { ...pad(t.sectionSpace), ...extra },
199
+ children,
200
+ } as Draft;
201
+ }
202
+
203
+ function card(t: RecipeTokens, children: Draft[]): Draft {
204
+ const base = column(children, { gap: t.tight });
205
+ if (t.cardClass) return withClass(base, t.cardClass);
206
+ return {
207
+ ...base,
208
+ style: {
209
+ ...base.style,
210
+ ...pad(t.blockSpace, t.blockSpace),
211
+ borderRadius: px(12),
212
+ borderWidth: px(1),
213
+ borderStyle: "solid",
214
+ borderColor: "#e5e7eb",
215
+ ...(t.surface ? { backgroundColor: t.surface } : {}),
216
+ },
217
+ };
218
+ }
219
+
220
+ type Options = { topLevel: 1 | 2 };
221
+
222
+ /** Section recipes (W-320): whole sections built from the site's own tokens. */
223
+ export const SECTION_RECIPES = [
224
+ {
225
+ id: "hero",
226
+ name: "Hero",
227
+ description: "Big headline, a line of text and two buttons.",
228
+ build: (t: RecipeTokens, o: Options): Draft =>
229
+ band(
230
+ t,
231
+ [
232
+ column(
233
+ [
234
+ heading("Say what you do in one line", o.topLevel, t.display, {
235
+ ...(t.ink ? { color: t.ink } : {}),
236
+ lineHeight: 1.1,
237
+ }),
238
+ text("A sentence or two on who it's for and why it's better.", t, {
239
+ fontSize: t.subheading,
240
+ maxWidth: px(640),
241
+ }),
242
+ flex([button("Get started", t), button("Learn more", t, false)], {
243
+ gap: t.tight,
244
+ justifyContent: "center",
245
+ marginTop: t.tight,
246
+ }),
247
+ ],
248
+ { gap: t.gap, alignItems: "center", textAlign: "center" },
249
+ ),
250
+ ],
251
+ t.surface ? { backgroundColor: t.surface } : {},
252
+ ),
253
+ },
254
+ {
255
+ id: "features",
256
+ name: "Features",
257
+ description: "A heading over three cards.",
258
+ build: (t: RecipeTokens): Draft =>
259
+ band(t, [
260
+ column(
261
+ [
262
+ heading("Why people choose us", 2, t.heading, {
263
+ textAlign: "center",
264
+ }),
265
+ grid(
266
+ 3,
267
+ ["Fast", "Simple", "Yours"].map((title) =>
268
+ card(t, [
269
+ heading(title, 3, t.subheading),
270
+ text("One or two sentences about this benefit.", t),
271
+ ]),
272
+ ),
273
+ t,
274
+ ),
275
+ ],
276
+ { gap: t.blockSpace },
277
+ ),
278
+ ]),
279
+ },
280
+ {
281
+ id: "cta",
282
+ name: "Call to action",
283
+ description: "A coloured band with a headline and a button.",
284
+ build: (t: RecipeTokens): Draft =>
285
+ band(
286
+ t,
287
+ [
288
+ column(
289
+ [
290
+ heading(
291
+ "Ready to start?",
292
+ 2,
293
+ t.heading,
294
+ t.accent ? { color: t.onAccent ?? "#ffffff" } : {},
295
+ ),
296
+ text(
297
+ "Tell visitors what happens when they click.",
298
+ t,
299
+ t.accent ? { color: t.onAccent ?? "#ffffff" } : {},
300
+ ),
301
+ t.accent && !t.buttonClass
302
+ ? ({
303
+ type: "button",
304
+ props: { text: "Start now", href: "#" },
305
+ style: {
306
+ paddingTop: px(12),
307
+ paddingBottom: px(12),
308
+ paddingLeft: px(28),
309
+ paddingRight: px(28),
310
+ borderRadius: px(8),
311
+ fontWeight: 600,
312
+ backgroundColor: t.onAccent ?? "#ffffff",
313
+ color: t.accent,
314
+ },
315
+ } as Draft)
316
+ : button("Start now", t),
317
+ ],
318
+ { gap: t.gap, alignItems: "center", textAlign: "center" },
319
+ ),
320
+ ],
321
+ t.accent ? { backgroundColor: t.accent } : {},
322
+ ),
323
+ },
324
+ {
325
+ id: "testimonial",
326
+ name: "Testimonial",
327
+ description: "A quote with the person's name.",
328
+ build: (t: RecipeTokens): Draft =>
329
+ band(t, [
330
+ column(
331
+ [
332
+ text("“EmVB made our site feel like ours again. We ship pages in minutes.”", t, {
333
+ fontSize: t.subheading,
334
+ ...(t.ink ? { color: t.ink } : {}),
335
+ maxWidth: px(720),
336
+ }),
337
+ text("Alex Doe, Founder at Example", t, { fontSize: t.small, fontWeight: 600 }),
338
+ ],
339
+ { gap: t.gap, alignItems: "center", textAlign: "center" },
340
+ ),
341
+ ]),
342
+ },
343
+ {
344
+ id: "stats",
345
+ name: "Stats",
346
+ description: "Three numbers that prove it.",
347
+ build: (t: RecipeTokens): Draft =>
348
+ band(t, [
349
+ grid(
350
+ 3,
351
+ [
352
+ ["10k+", "Happy customers"],
353
+ ["99.9%", "Uptime"],
354
+ ["24/7", "Support"],
355
+ ].map(([value, label]) =>
356
+ column(
357
+ [
358
+ text(value ?? "", t, {
359
+ fontSize: t.display,
360
+ fontWeight: 700,
361
+ ...(t.accent ? { color: t.accent } : {}),
362
+ }),
363
+ text(label ?? "", t, { fontSize: t.small }),
364
+ ],
365
+ { gap: t.tight, alignItems: "center", textAlign: "center" },
366
+ ),
367
+ ),
368
+ t,
369
+ ),
370
+ ]),
371
+ },
372
+ {
373
+ id: "faq",
374
+ name: "FAQ",
375
+ description: "Questions that open to their answers, no script.",
376
+ build: (t: RecipeTokens): Draft =>
377
+ band(t, [
378
+ column(
379
+ [
380
+ heading("Questions and answers", 2, t.heading),
381
+ {
382
+ type: "accordion",
383
+ props: {},
384
+ children: [
385
+ ["How long does it take?", "Most people are set up in an afternoon."],
386
+ ["Can I cancel?", "Any time, from your account page."],
387
+ ["Do you offer support?", "Yes, by email, every day."],
388
+ ].map(([q, a]) => ({
389
+ type: "accordion-item",
390
+ props: { summary: q ?? "" },
391
+ children: [text(a ?? "", t)],
392
+ })),
393
+ } as Draft,
394
+ ],
395
+ { gap: t.blockSpace, maxWidth: px(760) },
396
+ ),
397
+ ]),
398
+ },
399
+ ] as const;
400
+
401
+ export type RecipeId = (typeof SECTION_RECIPES)[number]["id"];
402
+
403
+ function hasH1(node: LayoutNode): boolean {
404
+ const props = node.props as Record<string, unknown>;
405
+ if (node.type === "heading" && props["level"] === 1) return true;
406
+ if (node.type === "post-title") return true;
407
+ return nodeChildren(node).some(hasH1);
408
+ }
409
+
410
+ function withIds(draft: Draft, random: () => number): LayoutNode {
411
+ const { children, ...rest } = draft;
412
+ const node = { ...rest, id: newNodeId(random) } as LayoutNode;
413
+ if (!children) return node;
414
+ return { ...node, children: children.map((child) => withIds(child, random)) } as LayoutNode;
415
+ }
416
+
417
+ /**
418
+ * A recipe's section, adapted to the site's styles (W-320). The hero's headline is the page's
419
+ * H1 only when the page has none yet. Ids are new; pass the result through `withFreshIds` (or
420
+ * `addNodeNear`) as for any new element.
421
+ */
422
+ export function recipeNode(
423
+ id: string,
424
+ design: DesignSystem,
425
+ layout: Layout | null,
426
+ random: () => number = Math.random,
427
+ ): LayoutNode | undefined {
428
+ const recipe = SECTION_RECIPES.find((r) => r.id === id);
429
+ if (!recipe) return undefined;
430
+ const topLevel = layout && hasH1(layout.root) ? 2 : 1;
431
+ const node = withIds(recipe.build(siteTokens(design), { topLevel }), random);
432
+ return { ...node, label: recipe.name } as LayoutNode;
433
+ }
@@ -0,0 +1,3 @@
1
+ /** A plain object. Arrays and null are not records. */
2
+ export const isRecord = (value: unknown): value is Record<string, unknown> =>
3
+ typeof value === "object" && value !== null && !Array.isArray(value);
@@ -18,4 +18,6 @@ export type RenderContext = {
18
18
  * stay with their own copy.
19
19
  */
20
20
  uniqueId: (base: string) => string;
21
+ /** The form whose children are rendering, so each field reads that form's definition. */
22
+ formId?: string;
21
23
  };
@@ -1,3 +1,4 @@
1
+ import { HEADING_TAGS } from "../elements/index.ts";
1
2
  import type { LayoutNode, POST_DATE_FORMATS } from "../schema/layout.ts";
2
3
  import { sanitizeHref } from "../sanitize/href.ts";
3
4
  import { sanitizeMediaUrl } from "../sanitize/media-url.ts";
@@ -31,8 +32,6 @@ type PostField = {
31
32
  render: (node: LayoutNode, attrs: Attrs, post: ThemePostFields) => VNode | undefined;
32
33
  };
33
34
 
34
- const HEADING_TAGS = ["h1", "h2", "h3", "h4", "h5", "h6"] as const;
35
-
36
35
  type PostDateFormat = (typeof POST_DATE_FORMATS)[number];
37
36
 
38
37
  /** In UTC, so the date doesn't move with the server's time zone. */
@@ -7,6 +7,9 @@ import type { VNode } from "./vnode.ts";
7
7
 
8
8
  export const FORMS_SUBMIT_PATH = "/_emdash/api/plugins/emdash-forms/submit";
9
9
 
10
+ /** What a paused form shows on the page (W-326). */
11
+ export const FORM_PAUSED_TEXT = "This form isn't accepting responses right now.";
12
+
10
13
  const honeypot = (inputId: string): VNode => ({
11
14
  tag: "div",
12
15
  attrs: {
@@ -64,16 +67,34 @@ export function renderForm(
64
67
  children: ["Bind a form in settings to preview it here."],
65
68
  };
66
69
  }
70
+ // W-326: a paused form says so, in place of fields that can't be sent (the forms plugin refuses
71
+ // its submissions), with no form, inputs or Submit button.
72
+ if (ctx.definitions.get(formId)?.status === "paused") {
73
+ return {
74
+ tag: "div",
75
+ attrs: {
76
+ ...attrs,
77
+ class: `${attrs.class} emvb-form-paused`.trim(),
78
+ role: "status",
79
+ "data-emvb-form-paused": "",
80
+ },
81
+ children: [{ tag: "p", attrs: {}, children: [FORM_PAUSED_TEXT] }],
82
+ };
83
+ }
67
84
  // W-203: the forms client puts this label back on the button after each submit, so it must be
68
85
  // the label the page shows, not the form definition's.
69
86
  const submitLabel =
70
87
  firstSubmitLabel(node.children) ??
71
88
  ctx.definitions.get(formId)?.settings.submitLabel ??
72
89
  "Submit";
90
+ const previousForm = ctx.formId;
91
+ ctx.formId = formId;
92
+ const fieldNodes = ctx.children(node.children, dynamic);
93
+ ctx.formId = previousForm;
73
94
  const page: VNode = {
74
95
  tag: "div",
75
96
  attrs: { "data-page": "0" },
76
- children: ctx.children(node.children, dynamic),
97
+ children: fieldNodes,
77
98
  };
78
99
  return {
79
100
  tag: "form",
@@ -131,6 +152,107 @@ const LENGTH_TYPES = new Set(["text", "email", "tel", "url", "textarea"]);
131
152
  const isControl = (node: VNode) =>
132
153
  ["input", "select", "textarea"].includes(node.tag) && node.attrs.type !== "hidden";
133
154
 
155
+ /**
156
+ * A `pattern` the browser can compile. A group that can repeat and that itself contains `|` or
157
+ * another quantifier (`(a+)+`, `(a|aa)+`) is left off: it can hang the visitor's tab while they
158
+ * type. A pattern that does not compile is left off too.
159
+ */
160
+ function hasControlChar(value: string): boolean {
161
+ for (const char of value) {
162
+ const code = char.charCodeAt(0);
163
+ if (code < 32 || code === 127) return true;
164
+ }
165
+ return false;
166
+ }
167
+
168
+ /** How much of `pattern` at `index` is a quantifier, and whether it can repeat enough to hang. */
169
+ function quantifierAt(
170
+ pattern: string,
171
+ index: number,
172
+ ): { consumed: number; dangerous: boolean; repeats: boolean } {
173
+ const none = { consumed: 0, dangerous: false, repeats: false };
174
+ const ch = pattern[index];
175
+ if (ch === "+" || ch === "*") {
176
+ const lazy = pattern[index + 1] === "?" ? 1 : 0;
177
+ return { consumed: 1 + lazy, dangerous: true, repeats: true };
178
+ }
179
+ if (ch === "?") return { consumed: 1, dangerous: false, repeats: false };
180
+ if (ch !== "{") return none;
181
+ const match = /^\{(\d+)(?:\s*,\s*(\d+)?)?\}\??/.exec(pattern.slice(index));
182
+ if (!match) return none;
183
+ const min = Number(match[1]);
184
+ const hasComma = match[0].includes(",");
185
+ const max =
186
+ match[2] === undefined ? (hasComma ? Number.POSITIVE_INFINITY : min) : Number(match[2]);
187
+ if (max < min) return none;
188
+ return { consumed: match[0].length, dangerous: max > 20, repeats: max > 1 };
189
+ }
190
+
191
+ /**
192
+ * True when a group that contains `|` or a quantifier is itself repeated without a small bound.
193
+ * `(abc)+` and `(https?:\/\/)?` stay allowed.
194
+ */
195
+ function repeatsARiskyGroup(pattern: string): boolean {
196
+ const stack: { risky: boolean }[] = [];
197
+ let inClass = false;
198
+ const mark = () => {
199
+ const frame = stack[stack.length - 1];
200
+ if (frame) frame.risky = true;
201
+ };
202
+ for (let i = 0; i < pattern.length; i += 1) {
203
+ const ch = pattern[i];
204
+ if (ch === "\\") {
205
+ i += 1;
206
+ continue;
207
+ }
208
+ if (inClass) {
209
+ if (ch === "]") inClass = false;
210
+ continue;
211
+ }
212
+ if (ch === "[") {
213
+ inClass = true;
214
+ continue;
215
+ }
216
+ if (ch === "(") {
217
+ stack.push({ risky: false });
218
+ continue;
219
+ }
220
+ if (ch === ")") {
221
+ const frame = stack.pop();
222
+ if (!frame) return true;
223
+ const quantifier = quantifierAt(pattern, i + 1);
224
+ if (quantifier.dangerous && frame.risky) return true;
225
+ if (quantifier.repeats || frame.risky) mark();
226
+ i += quantifier.consumed;
227
+ continue;
228
+ }
229
+ if (ch === "|" || ch === "+" || ch === "*" || ch === "?") {
230
+ mark();
231
+ continue;
232
+ }
233
+ if (ch === "{") {
234
+ const quantifier = quantifierAt(pattern, i);
235
+ if (quantifier.consumed === 0) continue;
236
+ mark();
237
+ i += quantifier.consumed - 1;
238
+ }
239
+ }
240
+ return false;
241
+ }
242
+
243
+ function safeInputPattern(pattern: string): string | undefined {
244
+ const value = pattern.trim();
245
+ if (!value || value.length > 200 || hasControlChar(value)) return undefined;
246
+ if (repeatsARiskyGroup(value)) return undefined;
247
+ try {
248
+ const compiled = new RegExp(value);
249
+ compiled.test("");
250
+ } catch {
251
+ return undefined;
252
+ }
253
+ return value;
254
+ }
255
+
134
256
  /**
135
257
  * W-297: what the forms plugin's own embed puts on a control: the input type (so phones show the
136
258
  * right keyboard), `required`, and the length, range and pattern limits, plus a visible mark on
@@ -151,7 +273,8 @@ function withFieldMeta(vnode: VNode, node: LayoutNode, meta: PublicFormField): V
151
273
  if (rules.max !== undefined) limits.max = String(rules.max);
152
274
  }
153
275
  if (node.type === "text-input" && kind !== "number" && kind !== "date" && rules.pattern) {
154
- limits.pattern = rules.pattern;
276
+ const pattern = safeInputPattern(rules.pattern);
277
+ if (pattern) limits.pattern = pattern;
155
278
  }
156
279
  }
157
280
  const mark: VNode = {
@@ -186,20 +309,20 @@ function withFieldMeta(vnode: VNode, node: LayoutNode, meta: PublicFormField): V
186
309
  });
187
310
  }
188
311
 
189
- /** Fills a field from the first bound form definition that has it: options, type, limits. */
312
+ /** Fills a field from the form it sits in: options, type, limits. Other forms are left alone. */
190
313
  export function withFieldOptions(
191
314
  vnode: VNode,
192
315
  node: LayoutNode,
193
316
  definitions: FormDefinitions,
317
+ formId?: string,
194
318
  ): VNode {
195
319
  const field = (node.props as { field?: unknown }).field;
196
- if (typeof field !== "string") return vnode;
197
- for (const definition of definitions.values()) {
198
- const meta = fieldByName(definition, field);
199
- if (!meta) continue;
200
- return withFieldMeta(withOptions(vnode, node, meta), node, meta);
201
- }
202
- return vnode;
320
+ if (typeof field !== "string" || !formId) return vnode;
321
+ const definition = definitions.get(formId);
322
+ if (!definition) return vnode;
323
+ const meta = fieldByName(definition, field);
324
+ if (!meta) return vnode;
325
+ return withFieldMeta(withOptions(vnode, node, meta), node, meta);
203
326
  }
204
327
 
205
328
  /** A select or radio field filled with the definition's options. */