@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
@@ -12,6 +12,7 @@ import type {
12
12
  AccordionItemNode,
13
13
  DividerNode,
14
14
  HeadingNode,
15
+ TocNode,
15
16
  IconNode,
16
17
  ImageNode,
17
18
  LabelNode,
@@ -35,6 +36,7 @@ import { menu, menuItem } from "./menu.ts";
35
36
  import { checkbox, form, radio, selectEl, submit, textInput, textareaEl } from "./form-elements.ts";
36
37
  import {
37
38
  loop,
39
+ loopEmpty,
38
40
  pagination,
39
41
  section,
40
42
  postContent,
@@ -46,7 +48,7 @@ import {
46
48
  postAuthor,
47
49
  } from "./dynamic-elements.ts";
48
50
 
49
- const HEADING_TAGS = ["h1", "h2", "h3", "h4", "h5", "h6"] as const;
51
+ export const HEADING_TAGS = ["h1", "h2", "h3", "h4", "h5", "h6"] as const;
50
52
 
51
53
  const newTabAttrs = (newTab: boolean | undefined): Record<string, string> =>
52
54
  newTab ? { target: "_blank", rel: "noopener noreferrer" } : {};
@@ -256,7 +258,7 @@ const link: ElementDefinition<LinkNode> = {
256
258
  const button: ElementDefinition<ButtonNode> = {
257
259
  baseCss:
258
260
  // The look sits in :where() so site tag defaults, classes and local styles all win (W-148).
259
- ".emvb-button{display:inline-flex;align-items:center;justify-content:center;margin:0;font:inherit;text-decoration:none;cursor:pointer}:where(.emvb-button){color:inherit;background:transparent;border:1px solid currentColor;border-radius:6px;padding:0.625em 1.25em;line-height:1.2}",
261
+ ".emvb-button{display:inline-flex;align-items:center;justify-content:center;gap:0.5em;margin:0;font:inherit;text-decoration:none;cursor:pointer}:where(.emvb-button){color:inherit;background:transparent;border:1px solid currentColor;border-radius:6px;padding:0.625em 1.25em;line-height:1.2}.emvb-button-icon{display:inline-flex;flex:none}.emvb-button-icon svg{width:100%;height:100%;display:block}.emvb-button-icon--sm{width:1em;height:1em}.emvb-button-icon--md{width:1.25em;height:1.25em}.emvb-button-icon--lg{width:1.5em;height:1.5em}.emvb-figure{margin:0}.emvb-figcaption{margin-top:0.35em}.emvb-image-link{display:contents}",
260
262
  defaults: () => ({ type: "button", props: { text: "Button" } }),
261
263
  descriptor: {
262
264
  type: "button",
@@ -273,25 +275,86 @@ const button: ElementDefinition<ButtonNode> = {
273
275
  message: "Use a full URL such as https://example.com or a path such as /pricing.",
274
276
  },
275
277
  { key: "newTab", kind: "boolean", label: "Open in a new tab", optional: true },
278
+ { key: "iconId", kind: "icon", label: "Icon", optional: true },
279
+ {
280
+ key: "iconPosition",
281
+ kind: "select",
282
+ label: "Icon position",
283
+ optional: true,
284
+ options: [
285
+ { value: "before", label: "Before the label" },
286
+ { value: "after", label: "After the label" },
287
+ ],
288
+ },
289
+ {
290
+ key: "iconSize",
291
+ kind: "select",
292
+ label: "Icon size",
293
+ optional: true,
294
+ options: [
295
+ { value: "sm", label: "Small" },
296
+ { value: "md", label: "Medium" },
297
+ { value: "lg", label: "Large" },
298
+ ],
299
+ },
300
+ { key: "iconGap", kind: "int", label: "Gap (px)", optional: true },
276
301
  ],
277
302
  },
278
303
  build: (node, attrs) => {
279
304
  const href = node.props.href !== undefined ? sanitizeHref(node.props.href) : undefined;
305
+ const children = buttonChildren(node);
280
306
  if (href) {
281
307
  return {
282
308
  tag: "a",
283
309
  attrs: { ...attrs, href, ...newTabAttrs(node.props.newTab) },
284
- children: [node.props.text],
310
+ children,
285
311
  };
286
312
  }
287
313
  return {
288
314
  tag: "button",
289
315
  attrs: { ...attrs, type: "button" },
290
- children: [node.props.text],
316
+ children,
291
317
  };
292
318
  },
293
319
  };
294
320
 
321
+ function buttonChildren(node: ButtonNode): (VNode | string)[] {
322
+ const buttonText = node.props.text;
323
+ const picked = node.props.iconSvg ? sanitizeSvgMarkup(node.props.iconSvg) : undefined;
324
+ const bundled = picked || !node.props.iconId ? undefined : getBundledIcon(node.props.iconId);
325
+ if (!picked && !bundled) return [buttonText];
326
+ const svg: VNode = {
327
+ tag: "svg",
328
+ attrs: picked
329
+ ? { ...picked.attrs, focusable: "false", "aria-hidden": "true" }
330
+ : {
331
+ xmlns: "http://www.w3.org/2000/svg",
332
+ viewBox: "0 0 24 24",
333
+ fill: "none",
334
+ stroke: "currentColor",
335
+ "stroke-width": "2",
336
+ "stroke-linecap": "round",
337
+ "stroke-linejoin": "round",
338
+ focusable: "false",
339
+ "aria-hidden": "true",
340
+ },
341
+ children: picked
342
+ ? picked.children
343
+ : (bundled?.children ?? []).map((child) => ({
344
+ tag: child.tag,
345
+ attrs: { ...child.attrs },
346
+ children: [],
347
+ })),
348
+ };
349
+ const size = node.props.iconSize ?? "md";
350
+ const icon: VNode = {
351
+ tag: "span",
352
+ attrs: { class: `emvb-button-icon emvb-button-icon--${size}`, "aria-hidden": "true" },
353
+ children: [svg],
354
+ };
355
+ return node.props.iconPosition === "after" ? [buttonText, icon] : [icon, buttonText];
356
+ }
357
+
295
358
  const list: ElementDefinition<ListNode> = {
296
359
  baseCss: ".emvb-list{margin:0;padding-inline-start:1.25em}.emvb-list li{margin:0}",
297
360
  defaults: () => ({ type: "list", props: { items: ["Item"] } }),
@@ -346,6 +409,17 @@ const image: ElementDefinition<ImageNode> = {
346
409
  },
347
410
  // The first big image people see (hero, LCP) shouldn't wait for lazy loading (W-226).
348
411
  { key: "priority", kind: "boolean", label: "Load right away", optional: true },
412
+ {
413
+ key: "href",
414
+ kind: "href",
415
+ label: "Link URL",
416
+ optional: true,
417
+ message: "Use a full URL or a path such as /pricing. Size styles stay on the image.",
418
+ },
419
+ { key: "newTab", kind: "boolean", label: "Open link in a new tab", optional: true },
420
+ { key: "caption", kind: "text", label: "Caption", optional: true },
421
+ { key: "focalX", kind: "int", label: "Focal point X (%)", optional: true },
422
+ { key: "focalY", kind: "int", label: "Focal point Y (%)", optional: true },
349
423
  {
350
424
  key: "width",
351
425
  kind: "int",
@@ -383,10 +457,51 @@ const image: ElementDefinition<ImageNode> = {
383
457
  if (decorative) imgAttrs.role = "presentation";
384
458
  if (node.props.width !== undefined) imgAttrs.width = String(node.props.width);
385
459
  if (node.props.height !== undefined) imgAttrs.height = String(node.props.height);
386
- return { tag: "img", attrs: imgAttrs, children: [] };
460
+ const sources = imageSources(node.props.src, node.props.sources);
461
+ if (sources) {
462
+ imgAttrs.srcset = sources;
463
+ imgAttrs.sizes = "100vw";
464
+ }
465
+ const img: VNode = { tag: "img", attrs: imgAttrs, children: [] };
466
+ const href = node.props.href ? sanitizeHref(node.props.href) : undefined;
467
+ const linked: VNode = href
468
+ ? {
469
+ tag: "a",
470
+ attrs: { href, class: "emvb-image-link", ...newTabAttrs(node.props.newTab) },
471
+ children: [img],
472
+ }
473
+ : img;
474
+ const caption = node.props.caption?.trim();
475
+ if (!caption) return linked;
476
+ return {
477
+ tag: "figure",
478
+ attrs: { class: "emvb-figure" },
479
+ children: [
480
+ linked,
481
+ { tag: "figcaption", attrs: { class: "emvb-figcaption" }, children: [caption] },
482
+ ],
483
+ };
387
484
  },
388
485
  };
389
486
 
487
+ function imageSources(
488
+ src: string,
489
+ sources: { src: string; width: number }[] | undefined,
490
+ ): string | undefined {
491
+ if (!sources || sources.length === 0) return undefined;
492
+ const parts: string[] = [];
493
+ const seen = new Set<string>();
494
+ for (const source of sources) {
495
+ const url = sanitizeMediaUrl(source.src);
496
+ // A comma or space is another srcset candidate, so one field would request a second host.
497
+ if (!url || /[\s,]/.test(url) || url === sanitizeMediaUrl(src) || seen.has(url)) continue;
498
+ if (!Number.isInteger(source.width) || source.width < 1 || source.width > 8000) continue;
499
+ seen.add(url);
500
+ parts.push(`${url} ${source.width}w`);
501
+ }
502
+ return parts.length > 0 ? parts.join(", ") : undefined;
503
+ }
504
+
390
505
  /** Root stroke widths the Stroke width control can override (W-237); Lucide and Tabler use 2. */
391
506
  const ICON_STROKE_WIDTHS = ["1", "1.5", "2", "2.5", "3"] as const;
392
507
 
@@ -625,6 +740,9 @@ const video: ElementDefinition<VideoNode> = {
625
740
  loading: "lazy",
626
741
  referrerpolicy: "strict-origin-when-cross-origin",
627
742
  allow: "encrypted-media; picture-in-picture; fullscreen",
743
+ // The player can run on its own origin. It cannot navigate this page.
744
+ sandbox:
745
+ "allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox",
628
746
  },
629
747
  children: [],
630
748
  };
@@ -643,6 +761,26 @@ const video: ElementDefinition<VideoNode> = {
643
761
  },
644
762
  };
645
763
 
764
+ const SVG_WSP = String.raw`[ \t\r\n]`;
765
+ const SVG_NUM = String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?`;
766
+ const SVG_SEP = `(?:${SVG_WSP}*,${SVG_WSP}*|${SVG_WSP}+)`;
767
+ const VIEW_BOX = new RegExp(
768
+ `^${SVG_WSP}*${SVG_NUM}${SVG_SEP}${SVG_NUM}${SVG_SEP}(${SVG_NUM})${SVG_SEP}(${SVG_NUM})${SVG_WSP}*$`,
769
+ );
770
+
771
+ /** Longer side at `size`; the other side keeps the viewBox ratio. Square or unreadable stays square. */
772
+ function svgBox(size: number, viewBox: string | undefined): { width: string; height: string } {
773
+ const match = VIEW_BOX.exec(viewBox ?? "");
774
+ const vbWidth = Number(match?.[1]);
775
+ const vbHeight = Number(match?.[2]);
776
+ const across = vbWidth / vbHeight;
777
+ const down = vbHeight / vbWidth;
778
+ const valid = vbWidth > 0 && [across, down].every((ratio) => Number.isFinite(ratio) && ratio > 0);
779
+ if (!valid) return { width: String(size), height: String(size) };
780
+ const side = (ratio: number) => String(Math.max(1, Math.round(size * Math.min(1, ratio))));
781
+ return { width: side(across), height: side(down) };
782
+ }
783
+
646
784
  const DEFAULT_SVG =
647
785
  '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 12h8"/></svg>';
648
786
 
@@ -699,8 +837,7 @@ const svgEl: ElementDefinition<SvgNode> = {
699
837
  const svgAttrs: Record<string, string> = {
700
838
  ...tree.attrs,
701
839
  xmlns: tree.attrs.xmlns ?? "http://www.w3.org/2000/svg",
702
- width: String(size),
703
- height: String(size),
840
+ ...svgBox(size, tree.attrs.viewBox),
704
841
  focusable: "false",
705
842
  };
706
843
  if (!svgAttrs.fill && !svgAttrs.stroke) {
@@ -839,6 +976,27 @@ const grid: ElementDefinition<GridNode> = {
839
976
  label: String(n),
840
977
  })),
841
978
  },
979
+ {
980
+ key: "columnTracks",
981
+ kind: "list-items",
982
+ label: "Custom tracks",
983
+ optional: true,
984
+ message: "One track per line: 1fr, 2fr, 3fr, auto, min-content, max-content, or a length.",
985
+ },
986
+ {
987
+ key: "columnTracksTablet",
988
+ kind: "list-items",
989
+ label: "Custom tracks on tablet",
990
+ optional: true,
991
+ message: "Leave empty to follow the desktop tracks.",
992
+ },
993
+ {
994
+ key: "columnTracksMobile",
995
+ kind: "list-items",
996
+ label: "Custom tracks on mobile",
997
+ optional: true,
998
+ message: "Leave empty to follow the next wider device.",
999
+ },
842
1000
  ...BOX_LINK_FIELDS,
843
1001
  ],
844
1002
  },
@@ -902,8 +1060,27 @@ const accordionItem: ElementDefinition<AccordionItemNode> = {
902
1060
  },
903
1061
  };
904
1062
 
1063
+ const toc: ElementDefinition<TocNode> = {
1064
+ baseCss:
1065
+ ".emvb-toc{margin:0}.emvb-toc-title{margin:0 0 0.5em;font:inherit;font-weight:600}.emvb-toc ol{margin:0;padding-inline-start:1.25em}.emvb-toc a{color:inherit}",
1066
+ defaults: () => ({ type: "toc", props: {} }),
1067
+ descriptor: {
1068
+ type: "toc",
1069
+ name: "Table of contents",
1070
+ group: "content",
1071
+ defaultTab: "content",
1072
+ fields: [{ key: "title", kind: "text", label: "Title", optional: true }],
1073
+ },
1074
+ build: (node, attrs) => ({
1075
+ tag: "nav",
1076
+ attrs: { ...attrs, "aria-label": node.props.title?.trim() || "Table of contents" },
1077
+ children: [],
1078
+ }),
1079
+ };
1080
+
905
1081
  export const ELEMENTS = {
906
1082
  heading,
1083
+ toc,
907
1084
  container,
908
1085
  "layout-section": layoutSection,
909
1086
  spacer,
@@ -931,6 +1108,7 @@ export const ELEMENTS = {
931
1108
  "post-date": postDate,
932
1109
  "post-author": postAuthor,
933
1110
  loop,
1111
+ "loop-empty": loopEmpty,
934
1112
  pagination,
935
1113
  section,
936
1114
  "div-block": divBlock,
@@ -1,5 +1,5 @@
1
1
  import { isFormNode, type Layout, type LayoutNode } from "../schema/layout.ts";
2
- import { nodeChildren } from "../tree-ops.ts";
2
+ import { forEachNode, someNode } from "../tree-ops.ts";
3
3
  import { fieldsOf, type FormDefinitions } from "./definition.ts";
4
4
 
5
5
  export type MissingRequiredField = {
@@ -8,14 +8,9 @@ export type MissingRequiredField = {
8
8
  field: string;
9
9
  };
10
10
 
11
- function walk(node: LayoutNode, visit: (node: LayoutNode) => void): void {
12
- visit(node);
13
- for (const child of nodeChildren(node)) walk(child, visit);
14
- }
15
-
16
11
  function boundFields(form: LayoutNode): Set<string> {
17
12
  const names = new Set<string>();
18
- walk(form, (node) => {
13
+ forEachNode(form, (node) => {
19
14
  if (
20
15
  node.type === "text-input" ||
21
16
  node.type === "textarea" ||
@@ -38,7 +33,7 @@ export function findMissingRequiredFields(
38
33
  definitions: FormDefinitions,
39
34
  ): MissingRequiredField[] {
40
35
  const missing: MissingRequiredField[] = [];
41
- walk(layout.root, (node) => {
36
+ forEachNode(layout.root, (node) => {
42
37
  if (!isFormNode(node) || !node.props.formId) return;
43
38
  const definition = definitions.get(node.props.formId);
44
39
  if (!definition) return;
@@ -53,9 +48,5 @@ export function findMissingRequiredFields(
53
48
  }
54
49
 
55
50
  export function layoutHasForm(layout: Layout): boolean {
56
- let found = false;
57
- walk(layout.root, (node) => {
58
- if (isFormNode(node) && node.props.formId.trim()) found = true;
59
- });
60
- return found;
51
+ return someNode(layout.root, (node) => isFormNode(node) && node.props.formId.trim() !== "");
61
52
  }
@@ -0,0 +1,152 @@
1
+ import { withFreshIds } from "../arrange.ts";
2
+ import { MAX_NODES } from "../limits.ts";
3
+ import type { Layout, LayoutNode } from "../schema/layout.ts";
4
+ import { insertNode, nodeChildren, updateNode } from "../tree-ops.ts";
5
+
6
+ export type SectionChange = {
7
+ id: string;
8
+ type: string;
9
+ label?: string;
10
+ kind: "added" | "removed" | "changed" | "moved" | "same";
11
+ /** Elements inside that differ (added, removed or edited), for changed sections. */
12
+ edits: number;
13
+ };
14
+
15
+ /** A stable text of a node without its children, to tell edits from unchanged nodes. */
16
+ function own(node: LayoutNode): string {
17
+ const { children: _children, ...rest } = node as LayoutNode & { children?: unknown };
18
+ return JSON.stringify(rest);
19
+ }
20
+
21
+ function index(node: LayoutNode, into = new Map<string, LayoutNode>()): Map<string, LayoutNode> {
22
+ into.set(node.id, node);
23
+ for (const child of nodeChildren(node)) index(child, into);
24
+ return into;
25
+ }
26
+
27
+ /** How many elements differ between two versions of a subtree. */
28
+ function editsBetween(before: LayoutNode, after: LayoutNode): number {
29
+ const a = index(before);
30
+ const b = index(after);
31
+ let edits = 0;
32
+ for (const [id, node] of a) {
33
+ const other = b.get(id);
34
+ if (!other) edits += 1;
35
+ else if (own(node) !== own(other)) edits += 1;
36
+ else if (
37
+ nodeChildren(node)
38
+ .map((c) => c.id)
39
+ .join() !==
40
+ nodeChildren(other)
41
+ .map((c) => c.id)
42
+ .join()
43
+ )
44
+ edits += 1;
45
+ }
46
+ for (const id of b.keys()) if (!a.has(id)) edits += 1;
47
+ return edits;
48
+ }
49
+
50
+ const describe = (node: LayoutNode) => ({
51
+ id: node.id,
52
+ type: node.type,
53
+ ...(node.label ? { label: node.label } : {}),
54
+ });
55
+
56
+ /**
57
+ * What changed between an older version and the current page, section by section (W-315). A
58
+ * section is a child of the page root. Sections only in the old version are "removed"; in
59
+ * page order, with removed ones at their old position.
60
+ */
61
+ export function diffSections(older: Layout, current: Layout): SectionChange[] {
62
+ const before = older.root.children;
63
+ const after = current.root.children;
64
+ const beforeIds = new Map(before.map((node, i) => [node.id, i]));
65
+ const afterIds = new Set(after.map((node) => node.id));
66
+ const changes: SectionChange[] = [];
67
+ const removedAt = new Map<number, LayoutNode[]>();
68
+ for (const [i, node] of before.entries()) {
69
+ if (!afterIds.has(node.id)) removedAt.set(i, [...(removedAt.get(i) ?? []), node]);
70
+ }
71
+ const keptOrder = before.filter((n) => afterIds.has(n.id)).map((n) => n.id);
72
+ const nowOrder = after.filter((n) => beforeIds.has(n.id)).map((n) => n.id);
73
+ const flush = (upTo: number) => {
74
+ for (const [at, nodes] of [...removedAt].filter(([pos]) => pos <= upTo)) {
75
+ for (const node of nodes) changes.push({ ...describe(node), kind: "removed", edits: 0 });
76
+ removedAt.delete(at);
77
+ }
78
+ };
79
+ for (const node of after) {
80
+ const old = beforeIds.get(node.id);
81
+ if (old === undefined) {
82
+ changes.push({ ...describe(node), kind: "added", edits: 0 });
83
+ continue;
84
+ }
85
+ flush(old);
86
+ const oldNode = before[old] as LayoutNode;
87
+ const edits = editsBetween(oldNode, node);
88
+ const moved = keptOrder.indexOf(node.id) !== nowOrder.indexOf(node.id);
89
+ changes.push({
90
+ ...describe(node),
91
+ kind: edits > 0 ? "changed" : moved ? "moved" : "same",
92
+ edits,
93
+ });
94
+ }
95
+ flush(Number.POSITIVE_INFINITY);
96
+ return changes;
97
+ }
98
+
99
+ const count = (node: LayoutNode): number =>
100
+ 1 + nodeChildren(node).reduce((sum, child) => sum + count(child), 0);
101
+
102
+ /**
103
+ * Puts one section of an older version back on the current page (W-315): it replaces the
104
+ * current section with the same id, or, if it was removed, goes back near its old place. Ids
105
+ * already used elsewhere on the page are renewed, so the page stays valid.
106
+ */
107
+ export function restoreSection(
108
+ current: Layout,
109
+ older: Layout,
110
+ sectionId: string,
111
+ ): { ok: true; layout: Layout } | { ok: false; reason: string } {
112
+ const oldIndex = older.root.children.findIndex((n) => n.id === sectionId);
113
+ const section = older.root.children[oldIndex];
114
+ if (!section) return { ok: false, reason: "That section isn't in this version." };
115
+ const replacing = current.root.children.find((n) => n.id === sectionId);
116
+ const elsewhere = new Set(index(current.root).keys());
117
+ if (replacing) for (const id of index(replacing).keys()) elsewhere.delete(id);
118
+ const clashes = [...index(section).keys()].some((id) => elsewhere.has(id));
119
+ const incoming = clashes ? withFreshIds(current, section) : section;
120
+ const size = count(current.root) - (replacing ? count(replacing) : 0) + count(incoming);
121
+ if (size > MAX_NODES) return { ok: false, reason: "The page would have too many elements." };
122
+ if (replacing && !clashes) {
123
+ return { ok: true, layout: updateNode(current, sectionId, () => structuredClone(section)) };
124
+ }
125
+ // Removed (or renewed): after the nearest earlier section that is still on the page.
126
+ const before = new Set(older.root.children.slice(0, oldIndex).map((n) => n.id));
127
+ let at = 0;
128
+ for (const [i, node] of current.root.children.entries()) if (before.has(node.id)) at = i + 1;
129
+ if (replacing) {
130
+ at = current.root.children.indexOf(replacing);
131
+ const without = {
132
+ ...current,
133
+ root: { ...current.root, children: current.root.children.filter((n) => n !== replacing) },
134
+ };
135
+ return {
136
+ ok: true,
137
+ layout: insertNode(without, current.root.id, at, structuredClone(incoming)),
138
+ };
139
+ }
140
+ return { ok: true, layout: insertNode(current, current.root.id, at, structuredClone(incoming)) };
141
+ }
142
+
143
+ /** The ids each kind of change covers, for outlining a diff on a rendered page (W-315). */
144
+ export function changedIds(
145
+ changes: SectionChange[],
146
+ ): Record<"added" | "removed" | "changed", string[]> {
147
+ const out = { added: [] as string[], removed: [] as string[], changed: [] as string[] };
148
+ for (const c of changes) {
149
+ if (c.kind === "added" || c.kind === "removed" || c.kind === "changed") out[c.kind].push(c.id);
150
+ }
151
+ return out;
152
+ }
package/src/core/index.ts CHANGED
@@ -42,6 +42,14 @@ export {
42
42
  isUnknownNode,
43
43
  FormNode,
44
44
  LoopNode,
45
+ LoopEmptyNode,
46
+ Variant,
47
+ AB_TEST_NAME,
48
+ Audience,
49
+ AUDIENCE_DEVICES,
50
+ AUDIENCE_SEGMENT,
51
+ LOOP_DISPLAYS,
52
+ LOOP_ORDERS,
45
53
  SectionNode,
46
54
  TextInputNode,
47
55
  TextareaNode,
@@ -55,6 +63,10 @@ export {
55
63
  PostImageNode,
56
64
  PostLinkNode,
57
65
  PaginationNode,
66
+ BIND_SOURCES,
67
+ Binding,
68
+ type BindSource,
69
+ type NodeExtras,
58
70
  } from "./schema/layout.ts";
59
71
  export {
60
72
  type FieldKind,
@@ -106,6 +118,8 @@ export {
106
118
  type DesignValidation,
107
119
  } from "./validate.ts";
108
120
  export { nestingIssues } from "./nesting.ts";
121
+ export { mergeDesign, type DesignConflict } from "./design/merge.ts";
122
+ export { designChanges, designChangeLabel, type DesignChange } from "./design/diff.ts";
109
123
  export {
110
124
  DESIGN_SCHEMA_VERSION,
111
125
  DEFAULT_STYLE_TAGS,
@@ -210,6 +224,25 @@ export {
210
224
  } from "./sanitize/svg-upload.ts";
211
225
  export { resolveEmbedUrl, type EmbedTarget } from "./sanitize/embed-url.ts";
212
226
  export { summarizeLayout, type LayoutSummary } from "./stats.ts";
227
+ export {
228
+ BINDABLE_FIELDS,
229
+ BIND_SOURCE_LABELS,
230
+ MAX_BOUND_LENGTH,
231
+ POST_BIND_KEYS,
232
+ SITE_BIND_KEYS,
233
+ applyBindings,
234
+ boundValue,
235
+ bindableFields,
236
+ hasBindings,
237
+ layoutUsesSource,
238
+ paramsFromSearch,
239
+ resolveBinding,
240
+ siteBindingValues,
241
+ withBinding,
242
+ type BindKind,
243
+ type BindableField,
244
+ type BindingData,
245
+ } from "./data/bindings.ts";
213
246
  export {
214
247
  findNode,
215
248
  updateNode,
@@ -225,8 +258,15 @@ export {
225
258
  REASONS,
226
259
  addNode,
227
260
  addNodeNear,
261
+ addSectionNear,
228
262
  canDrop,
229
263
  duplicateNode,
264
+ wrapNode,
265
+ WRAP_TYPES,
266
+ type WrapType,
267
+ createVariantB,
268
+ endAbTest,
269
+ defaultTestName,
230
270
  firstChild,
231
271
  insertionPoint,
232
272
  moveDown,
@@ -336,6 +376,10 @@ export {
336
376
  portableTextToVNodes,
337
377
  collectLoopItemPartIds,
338
378
  collectSectionPartIds,
379
+ collectCollectionLoops,
380
+ loopPermalink,
381
+ parseLoopFilter,
382
+ type CollectionLoop,
339
383
  resolvePostForRender,
340
384
  resolvePostsForLoop,
341
385
  type ThemePostFields,
@@ -378,3 +422,80 @@ export {
378
422
  type PasteMode,
379
423
  type ReadClip,
380
424
  } from "./clipboard.ts";
425
+ export {
426
+ layoutScripts,
427
+ nodeScript,
428
+ SCRIPT_BYTES,
429
+ SCRIPT_LABELS,
430
+ typeMayAddScript,
431
+ type PageScript,
432
+ } from "./perf/scripts.ts";
433
+ export {
434
+ measurePage,
435
+ PERF_BUDGETS,
436
+ type PerfKind,
437
+ type PerfReport,
438
+ type SectionWeight,
439
+ } from "./perf/meter.ts";
440
+ export {
441
+ abCookieName,
442
+ collectAbTests,
443
+ pickArm,
444
+ variantShows,
445
+ type AbArm,
446
+ type AbTest,
447
+ } from "./audience/variants.ts";
448
+ export {
449
+ audienceShows,
450
+ audienceSummary,
451
+ clockIn,
452
+ deviceFromUserAgent,
453
+ layoutUsesAudience,
454
+ layoutUsesVisitorRule,
455
+ type VisitorInfo,
456
+ } from "./audience/rules.ts";
457
+ export { changedIds, diffSections, restoreSection, type SectionChange } from "./history/diff.ts";
458
+ export {
459
+ applyTokens,
460
+ DEFAULT_FLUID_RANGE,
461
+ fluidClamp,
462
+ SCALE_RATIOS,
463
+ spaceScale,
464
+ typeScale,
465
+ type ScaleInput,
466
+ } from "./design/tokens.ts";
467
+ export {
468
+ applyA11yFix,
469
+ applyAllA11yFixes,
470
+ auditPage,
471
+ contrastRatio,
472
+ type A11yIssue,
473
+ type A11yReport,
474
+ } from "./a11y/audit.ts";
475
+ export {
476
+ defaultTagFor,
477
+ inheritedStyle,
478
+ traceStyle,
479
+ type StyleSource,
480
+ type StyleTrace,
481
+ type TraceDevice,
482
+ } from "./css/trace.ts";
483
+ export { MOTION_EFFECTS, MOTION_LIMITS, type MotionEffect } from "./schema/motion.ts";
484
+ export {
485
+ recipeNode,
486
+ SECTION_RECIPES,
487
+ siteTokens,
488
+ type RecipeId,
489
+ type RecipeTokens,
490
+ } from "./recipes/index.ts";
491
+ export {
492
+ decodeSharedPage,
493
+ encodeSharedPage,
494
+ LONG_LINK_CHARS,
495
+ PLAYGROUND_URL,
496
+ sharedFromHash,
497
+ shareUrl,
498
+ type SharedPage,
499
+ type ShareRead,
500
+ } from "./share/link.ts";
501
+ export { canvasStyleUrls, MAX_CANVAS_STYLES } from "./canvas-styles.ts";
@@ -0,0 +1,27 @@
1
+ import type { LayoutNode } from "./schema/layout.ts";
2
+
3
+ /** Local style keys. Classes and `query` stay on the element (D-033, W-355). */
4
+ const LOCAL_STYLE_KEYS = ["style", "states", "devices", "hiddenOn"] as const;
5
+
6
+ export type LocalStyle = Pick<LayoutNode, (typeof LOCAL_STYLE_KEYS)[number]>;
7
+
8
+ /** The local style of a node; classes stay behind (D-033). */
9
+ export function localStyleOf(node: LayoutNode): LocalStyle {
10
+ const copied: LocalStyle = {};
11
+ for (const key of LOCAL_STYLE_KEYS) {
12
+ const value = node[key];
13
+ if (value !== undefined) (copied as Record<string, unknown>)[key] = structuredClone(value);
14
+ }
15
+ return copied;
16
+ }
17
+
18
+ /** Replaces style, states, devices and hiddenOn. Other fields stay. `query` is not a local style. */
19
+ export function withLocalStyle<T extends LayoutNode>(node: T, copied: LocalStyle): T {
20
+ const next = { ...node } as Record<string, unknown>;
21
+ for (const key of LOCAL_STYLE_KEYS) {
22
+ delete next[key];
23
+ const value = copied[key];
24
+ if (value !== undefined) next[key] = structuredClone(value);
25
+ }
26
+ return next as T;
27
+ }