@perkyzz/emvb 0.3.0 → 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 (121) 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 +1 -1
  10. package/src/admin/editor/Editor.tsx +106 -332
  11. package/src/admin/editor/EditorOverlay.tsx +3 -1
  12. package/src/admin/editor/PerfMeter.tsx +1 -1
  13. package/src/admin/editor/ShortcutsDialog.tsx +4 -1
  14. package/src/admin/editor/Timeline.tsx +16 -3
  15. package/src/admin/editor/canvas/CanvasFrame.tsx +51 -368
  16. package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
  17. package/src/admin/editor/canvas/SelectionOverlay.tsx +86 -46
  18. package/src/admin/editor/canvas/canvas-scale.ts +20 -0
  19. package/src/admin/editor/canvas/drop-line.ts +24 -0
  20. package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
  21. package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
  22. package/src/admin/editor/collection-previews.ts +28 -5
  23. package/src/admin/editor/editor-chrome.tsx +346 -0
  24. package/src/admin/editor/editor-commands.ts +360 -0
  25. package/src/admin/editor/element-chrome.ts +89 -0
  26. package/src/admin/editor/feature-css.ts +15 -15
  27. package/src/admin/editor/host.ts +33 -0
  28. package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
  29. package/src/admin/editor/icons/library.ts +29 -19
  30. package/src/admin/editor/icons/use-icon-library.ts +315 -0
  31. package/src/admin/editor/palette-items.ts +36 -5
  32. package/src/admin/editor/palette.ts +3 -2
  33. package/src/admin/editor/panels/AddPanel.tsx +2 -67
  34. package/src/admin/editor/panels/ColorControl.tsx +2 -10
  35. package/src/admin/editor/panels/ElementPanel.tsx +40 -99
  36. package/src/admin/editor/panels/LayersPanel.tsx +34 -62
  37. package/src/admin/editor/panels/SettingsPanel.tsx +1 -0
  38. package/src/admin/editor/panels/SiteStylesDrawer.tsx +16 -10
  39. package/src/admin/editor/panels/VariableSection.tsx +1 -10
  40. package/src/admin/editor/panels/inline-error.tsx +11 -0
  41. package/src/admin/editor/panels/settings/AdvancedFields.tsx +87 -1
  42. package/src/admin/editor/panels/settings/AudienceEditor.tsx +73 -3
  43. package/src/admin/editor/panels/settings/DraftTextField.tsx +4 -0
  44. package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
  45. package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
  46. package/src/admin/editor/panels/settings/StyleRow.tsx +14 -2
  47. package/src/admin/editor/panels/settings/form-names.ts +7 -11
  48. package/src/admin/editor/panels/settings/length-units.ts +15 -4
  49. package/src/admin/editor/panels/settings/style-sections.ts +5 -1
  50. package/src/admin/editor/panels/style-target.ts +105 -0
  51. package/src/admin/editor/section-templates.ts +43 -21
  52. package/src/admin/editor/shortcuts.ts +4 -0
  53. package/src/admin/editor/store.ts +10 -1
  54. package/src/admin/editor/useClipboardActions.ts +1 -1
  55. package/src/admin/editor/useEditorCommands.ts +61 -13
  56. package/src/admin/editor/useEditorData.ts +7 -1
  57. package/src/admin/editor/useEditorShortcuts.ts +23 -15
  58. package/src/admin/editor/useNodeActions.ts +6 -1
  59. package/src/admin/forms-api.ts +17 -6
  60. package/src/admin/icon-uploads-api.ts +18 -0
  61. package/src/admin/theme-api.ts +5 -18
  62. package/src/astro/content-port.ts +24 -0
  63. package/src/astro/forms/EmVBFormsClient.astro +11 -0
  64. package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
  65. package/src/astro/forms/client.ts +1 -0
  66. package/src/astro/forms-definitions.ts +24 -11
  67. package/src/astro/index.ts +1 -0
  68. package/src/astro/render-session.ts +85 -0
  69. package/src/astro/request-data.ts +20 -8
  70. package/src/astro/resolve-theme.ts +166 -76
  71. package/src/astro/resolve.ts +57 -16
  72. package/src/astro/theme-posts.ts +16 -5
  73. package/src/astro/visitor.ts +67 -5
  74. package/src/constants.ts +1 -1
  75. package/src/core/arrange.ts +63 -38
  76. package/src/core/audience/rules.ts +22 -2
  77. package/src/core/canvas-styles.ts +24 -0
  78. package/src/core/clipboard.ts +11 -32
  79. package/src/core/css/generate.ts +9 -0
  80. package/src/core/css/print.ts +12 -0
  81. package/src/core/css/scope.ts +3 -3
  82. package/src/core/css-keywords.ts +83 -0
  83. package/src/core/data/bindings.ts +4 -6
  84. package/src/core/design/classes.ts +13 -15
  85. package/src/core/design/diff.ts +55 -0
  86. package/src/core/design/merge.ts +127 -0
  87. package/src/core/design/variables.ts +25 -21
  88. package/src/core/elements/dynamic-elements.ts +30 -0
  89. package/src/core/elements/form-elements.ts +1 -0
  90. package/src/core/elements/index.ts +183 -7
  91. package/src/core/forms/binding.ts +4 -13
  92. package/src/core/index.ts +10 -0
  93. package/src/core/local-style.ts +27 -0
  94. package/src/core/migrate/index.ts +9 -4
  95. package/src/core/nesting.ts +4 -23
  96. package/src/core/perf/scripts.ts +9 -6
  97. package/src/core/record.ts +3 -0
  98. package/src/core/render/context.ts +2 -0
  99. package/src/core/render/dynamic-post.ts +1 -2
  100. package/src/core/render/form.ts +133 -10
  101. package/src/core/render/index.ts +155 -13
  102. package/src/core/render/vnode.ts +12 -2
  103. package/src/core/sanitize/css.ts +90 -77
  104. package/src/core/sanitize/svg.ts +8 -3
  105. package/src/core/sanitize/url.ts +10 -1
  106. package/src/core/schema/design.ts +5 -7
  107. package/src/core/schema/layout.ts +153 -181
  108. package/src/core/schema/style.ts +53 -63
  109. package/src/core/share/link.ts +68 -28
  110. package/src/core/tabs/presence.ts +7 -17
  111. package/src/core/theme/dynamic.ts +200 -39
  112. package/src/core/theme/float.ts +1 -1
  113. package/src/core/tree-ops.ts +57 -0
  114. package/src/index.ts +14 -2
  115. package/src/server/design-routes.ts +4 -1
  116. package/src/server/icon-routes.ts +68 -16
  117. package/src/server/plugin.ts +8 -2
  118. package/src/admin/editor/icons/sets/fontawesome.json +0 -1
  119. package/src/admin/editor/icons/sets/lucide.json +0 -1
  120. package/src/admin/editor/icons/sets/remix.json +0 -1
  121. package/src/admin/editor/icons/sets/tabler.json +0 -1
@@ -1,4 +1,25 @@
1
1
  import { z } from "zod";
2
+ import {
3
+ ALIGN_ITEMS,
4
+ BACKGROUND_POSITIONS,
5
+ BACKGROUND_REPEATS,
6
+ BACKGROUND_SIZES,
7
+ BORDER_STYLES,
8
+ CURSORS,
9
+ FLEX_DIRECTIONS,
10
+ FLEX_WRAPS,
11
+ HEX_COLOR,
12
+ JUSTIFY_CONTENT,
13
+ LENGTH_UNITS,
14
+ OBJECT_FITS,
15
+ OVERFLOWS,
16
+ POSITIONS,
17
+ TEXT_ALIGNS,
18
+ TEXT_DECORATIONS,
19
+ TEXT_TRANSFORMS,
20
+ TRANSITION_EASINGS,
21
+ TRANSITION_PROPERTIES,
22
+ } from "../css-keywords.ts";
2
23
  import { isSafeFontStack } from "../sanitize/css.ts";
3
24
  import { sanitizeMediaUrl } from "../sanitize/media-url.ts";
4
25
  import { POPUP_DEVICES } from "../theme/popup-rules.ts";
@@ -10,13 +31,13 @@ export const VariableRef = z.strictObject({
10
31
  from: z.enum(["color", "font", "fontSize", "spacing"]).optional(),
11
32
  });
12
33
 
13
- const HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
14
34
  export const ColorValue = z.union([
15
35
  z.string().regex(HEX_COLOR, "Use a hex color such as #1a2b3c"),
16
36
  VariableRef,
17
37
  ]);
18
38
 
19
- const LengthUnit = z.enum(["px", "rem", "em", "%", "vw", "vh"]);
39
+ /** `ch` since W-331: the width of a "0", for readable line lengths such as 65ch. */
40
+ const LengthUnit = z.enum(LENGTH_UNITS);
20
41
 
21
42
  export const Length = z.strictObject({
22
43
  value: z.number().finite().min(0).max(10_000),
@@ -29,7 +50,10 @@ export const LengthValue = z.union([Length, VariableRef]);
29
50
  /** Width, height and margins may also be `auto` (W-088). */
30
51
  const SizeValue = z.union([Length, VariableRef, z.literal("auto")]);
31
52
 
32
- /** Top, right, bottom and left may be negative, `auto` or a spacing variable (W-088). */
53
+ /**
54
+ * Top, right, bottom and left may be negative, `auto` or a spacing variable (W-088); so may
55
+ * margins since W-331, to pull an element over its neighbour.
56
+ */
33
57
  const OffsetValue = z.union([
34
58
  z.strictObject({ value: z.number().finite().min(-10_000).max(10_000), unit: LengthUnit }),
35
59
  VariableRef,
@@ -73,43 +97,45 @@ const Filter = z
73
97
  const Transition = z.strictObject({
74
98
  duration: z.number().int().min(0).max(2000),
75
99
  delay: z.number().int().min(0).max(2000).optional(),
76
- easing: z.enum(["ease", "ease-in", "ease-out", "ease-in-out", "linear"]),
77
- property: z.enum(["all", "colors", "opacity", "shadow", "filter"]),
100
+ easing: z.enum(TRANSITION_EASINGS),
101
+ property: z.enum(TRANSITION_PROPERTIES),
78
102
  });
79
103
 
80
104
  /** Style properties for layout and text elements (W-017 / R-012). Unknown keys are rejected. */
81
105
  export const StyleProps = z.strictObject({
82
- flexDirection: z.enum(["row", "column", "row-reverse", "column-reverse"]).optional(),
83
- flexWrap: z.enum(["nowrap", "wrap", "wrap-reverse"]).optional(),
84
- justifyContent: z
85
- .enum(["flex-start", "flex-end", "center", "space-between", "space-around", "space-evenly"])
86
- .optional(),
87
- alignItems: z.enum(["stretch", "flex-start", "flex-end", "center", "baseline"]).optional(),
106
+ flexDirection: z.enum(FLEX_DIRECTIONS).optional(),
107
+ flexWrap: z.enum(FLEX_WRAPS).optional(),
108
+ justifyContent: z.enum(JUSTIFY_CONTENT).optional(),
109
+ alignItems: z.enum(ALIGN_ITEMS).optional(),
88
110
  gap: LengthValue.optional(),
89
111
  /** How many grid columns this element spans (1–12). */
90
112
  gridColumnSpan: z.number().int().min(1).max(12).optional(),
91
113
  /** How many grid rows this element spans (1–12). */
92
114
  gridRowSpan: z.number().int().min(1).max(12).optional(),
115
+ /** First column line (1–13). With a span, emits `start / span n`. */
116
+ gridColumnStart: z.number().int().min(1).max(13).optional(),
117
+ /** First row line (1–13). With a span, emits `start / span n`. */
118
+ gridRowStart: z.number().int().min(1).max(13).optional(),
93
119
  width: SizeValue.optional(),
94
120
  minWidth: LengthValue.optional(),
95
121
  maxWidth: LengthValue.optional(),
96
122
  height: SizeValue.optional(),
97
123
  minHeight: LengthValue.optional(),
98
124
  maxHeight: LengthValue.optional(),
99
- overflow: z.enum(["visible", "hidden", "clip", "scroll", "auto"]).optional(),
125
+ overflow: z.enum(OVERFLOWS).optional(),
100
126
  aspectRatio: z
101
127
  .union([z.literal("auto"), z.string().regex(ASPECT_RATIO, "Use a ratio such as 16/9")])
102
128
  .optional(),
103
- objectFit: z.enum(["fill", "contain", "cover", "none", "scale-down"]).optional(),
129
+ objectFit: z.enum(OBJECT_FITS).optional(),
104
130
  paddingTop: LengthValue.optional(),
105
131
  paddingRight: LengthValue.optional(),
106
132
  paddingBottom: LengthValue.optional(),
107
133
  paddingLeft: LengthValue.optional(),
108
- marginTop: SizeValue.optional(),
109
- marginRight: SizeValue.optional(),
110
- marginBottom: SizeValue.optional(),
111
- marginLeft: SizeValue.optional(),
112
- position: z.enum(["static", "relative", "absolute", "fixed", "sticky"]).optional(),
134
+ marginTop: OffsetValue.optional(),
135
+ marginRight: OffsetValue.optional(),
136
+ marginBottom: OffsetValue.optional(),
137
+ marginLeft: OffsetValue.optional(),
138
+ position: z.enum(POSITIONS).optional(),
113
139
  top: OffsetValue.optional(),
114
140
  right: OffsetValue.optional(),
115
141
  bottom: OffsetValue.optional(),
@@ -146,10 +172,10 @@ export const StyleProps = z.strictObject({
146
172
  VariableRef,
147
173
  ])
148
174
  .optional(),
149
- textAlign: z.enum(["left", "center", "right", "justify"]).optional(),
150
- textTransform: z.enum(["none", "uppercase", "lowercase", "capitalize"]).optional(),
175
+ textAlign: z.enum(TEXT_ALIGNS).optional(),
176
+ textTransform: z.enum(TEXT_TRANSFORMS).optional(),
151
177
  /** W-113. A button sets `none` in its base CSS, so it is not underlined unless a style says so. */
152
- textDecoration: z.enum(["none", "underline", "overline", "line-through"]).optional(),
178
+ textDecoration: z.enum(TEXT_DECORATIONS).optional(),
153
179
  color: ColorValue.optional(),
154
180
  backgroundColor: ColorValue.optional(),
155
181
  /** http(s) or a site path. Spaces, quotes and parentheses are refused so the URL can sit inside `url("")`. */
@@ -162,21 +188,9 @@ export const StyleProps = z.strictObject({
162
188
  "Use an http(s) URL or a site path, with no spaces or parentheses",
163
189
  )
164
190
  .optional(),
165
- backgroundSize: z.enum(["auto", "cover", "contain"]).optional(),
166
- backgroundPosition: z
167
- .enum([
168
- "center",
169
- "top",
170
- "bottom",
171
- "left",
172
- "right",
173
- "top left",
174
- "top right",
175
- "bottom left",
176
- "bottom right",
177
- ])
178
- .optional(),
179
- backgroundRepeat: z.enum(["no-repeat", "repeat", "repeat-x", "repeat-y"]).optional(),
191
+ backgroundSize: z.enum(BACKGROUND_SIZES).optional(),
192
+ backgroundPosition: z.enum(BACKGROUND_POSITIONS).optional(),
193
+ backgroundRepeat: z.enum(BACKGROUND_REPEATS).optional(),
180
194
  /** Video behind the element. Same URL rules as a background image (W-110). */
181
195
  backgroundVideo: z
182
196
  .string()
@@ -195,19 +209,7 @@ export const StyleProps = z.strictObject({
195
209
  .strictObject({
196
210
  type: z.enum(["linear", "radial", "conic"]),
197
211
  angle: z.number().int().min(0).max(360).optional(),
198
- position: z
199
- .enum([
200
- "center",
201
- "top",
202
- "bottom",
203
- "left",
204
- "right",
205
- "top left",
206
- "top right",
207
- "bottom left",
208
- "bottom right",
209
- ])
210
- .optional(),
212
+ position: z.enum(BACKGROUND_POSITIONS).optional(),
211
213
  stops: z
212
214
  .array(
213
215
  z.strictObject({
@@ -232,7 +234,7 @@ export const StyleProps = z.strictObject({
232
234
  borderRightWidth: LengthValue.optional(),
233
235
  borderBottomWidth: LengthValue.optional(),
234
236
  borderLeftWidth: LengthValue.optional(),
235
- borderStyle: z.enum(["none", "solid", "dashed", "dotted"]).optional(),
237
+ borderStyle: z.enum(BORDER_STYLES).optional(),
236
238
  borderColor: ColorValue.optional(),
237
239
  borderRadius: LengthValue.optional(),
238
240
  /** Per-corner radii (W-138, D-044), after `borderRadius`. */
@@ -243,19 +245,7 @@ export const StyleProps = z.strictObject({
243
245
  opacity: z.number().finite().min(0).max(1).optional(),
244
246
  boxShadow: BoxShadow.optional(),
245
247
  filter: Filter.optional(),
246
- cursor: z
247
- .enum([
248
- "default",
249
- "pointer",
250
- "text",
251
- "move",
252
- "grab",
253
- "not-allowed",
254
- "help",
255
- "crosshair",
256
- "zoom-in",
257
- ])
258
- .optional(),
248
+ cursor: z.enum(CURSORS).optional(),
259
249
  transition: Transition.optional(),
260
250
  /**
261
251
  * Icon element glyph styling (W-237). Emitted as custom properties on the icon's wrapper, so
@@ -40,38 +40,78 @@ function fromBase64Url(text: string): Uint8Array {
40
40
  return bytes;
41
41
  }
42
42
 
43
- async function pipe(
43
+ type ByteWriter = {
44
+ write(chunk?: BufferSource): Promise<void>;
45
+ close(): Promise<void>;
46
+ };
47
+ type ByteReader = {
48
+ read(): Promise<ReadableStreamReadResult<Uint8Array>>;
49
+ cancel(): Promise<void>;
50
+ };
51
+ type BytePipe = {
52
+ readable: { getReader(): ByteReader };
53
+ writable: { getWriter(): ByteWriter };
54
+ };
55
+
56
+ /**
57
+ * Copies bytes through a compression stream. Reading runs alongside the write, and a writer
58
+ * failure rejects even when the reader would wait forever.
59
+ */
60
+ export async function pipeBytes(
44
61
  bytes: Uint8Array,
45
- stream: CompressionStream | DecompressionStream,
62
+ stream: BytePipe,
46
63
  max: number,
47
- ) {
64
+ ): Promise<Uint8Array> {
48
65
  const writer = stream.writable.getWriter();
49
- void writer
50
- .write(bytes as Uint8Array<ArrayBuffer>)
51
- .then(() => writer.close())
52
- .catch(() => {});
53
66
  const reader = stream.readable.getReader();
54
- const parts: Uint8Array[] = [];
55
- let size = 0;
56
- for (;;) {
57
- // Read in order; stop early so a tiny link can't unpack into something huge.
58
- // oxlint-disable-next-line no-await-in-loop
59
- const { done, value } = await reader.read();
60
- if (done) break;
61
- size += value.byteLength;
62
- if (size > max) {
63
- void reader.cancel();
64
- throw new Error("too big");
67
+ let writerError: unknown;
68
+ const writerFailed = new Promise<unknown>((resolve) => {
69
+ writer
70
+ .write(bytes as Uint8Array<ArrayBuffer>)
71
+ .then(() => writer.close())
72
+ .then(
73
+ () => undefined,
74
+ (error: unknown) => {
75
+ writerError = error;
76
+ resolve(error);
77
+ },
78
+ );
79
+ });
80
+ try {
81
+ const parts: Uint8Array[] = [];
82
+ let size = 0;
83
+ for (;;) {
84
+ // Read in order; stop early so a tiny link can't unpack into something huge.
85
+ // oxlint-disable-next-line no-await-in-loop
86
+ const next = await Promise.race([
87
+ reader.read().then(
88
+ (chunk) => ({ kind: "chunk" as const, chunk }),
89
+ (error: unknown) => ({ kind: "failed" as const, error }),
90
+ ),
91
+ writerFailed.then((error) => ({ kind: "failed" as const, error })),
92
+ ]);
93
+ if (next.kind === "failed") throw next.error;
94
+ const { done, value } = next.chunk;
95
+ if (done) break;
96
+ size += value.byteLength;
97
+ if (size > max) {
98
+ void reader.cancel().catch(() => {});
99
+ throw new Error("too big");
100
+ }
101
+ parts.push(value);
65
102
  }
66
- parts.push(value);
67
- }
68
- const out = new Uint8Array(size);
69
- let at = 0;
70
- for (const part of parts) {
71
- out.set(part, at);
72
- at += part.byteLength;
103
+ if (writerError !== undefined) throw writerError;
104
+ const out = new Uint8Array(size);
105
+ let at = 0;
106
+ for (const part of parts) {
107
+ out.set(part, at);
108
+ at += part.byteLength;
109
+ }
110
+ return out;
111
+ } catch (error) {
112
+ void reader.cancel().catch(() => {});
113
+ throw error;
73
114
  }
74
- return out;
75
115
  }
76
116
 
77
117
  /**
@@ -84,7 +124,7 @@ export async function encodeSharedPage(page: SharedPage): Promise<string> {
84
124
  l: page.layout,
85
125
  ...(page.design ? { d: page.design } : {}),
86
126
  });
87
- const packed = await pipe(
127
+ const packed = await pipeBytes(
88
128
  new TextEncoder().encode(json),
89
129
  new CompressionStream("deflate-raw"),
90
130
  Number.MAX_SAFE_INTEGER,
@@ -117,7 +157,7 @@ export async function decodeSharedPage(encoded: string): Promise<ShareRead> {
117
157
  }
118
158
  let parsed: unknown;
119
159
  try {
120
- const bytes = await pipe(
160
+ const bytes = await pipeBytes(
121
161
  fromBase64Url(body),
122
162
  new DecompressionStream("deflate-raw"),
123
163
  MAX_UNPACKED_BYTES,
@@ -1,25 +1,15 @@
1
- import { isTabsNode, type Layout, type LayoutNode } from "../schema/layout.ts";
2
- import { nodeChildren } from "../tree-ops.ts";
3
-
4
- function walk(node: LayoutNode, visit: (node: LayoutNode) => void): void {
5
- visit(node);
6
- for (const child of nodeChildren(node)) walk(child, visit);
7
- }
1
+ import { isTabsNode, type Layout } from "../schema/layout.ts";
2
+ import { nodeChildren, someNode } from "../tree-ops.ts";
8
3
 
9
4
  /** True when the layout includes at least one Tabs element (optional public runtime). */
10
5
  export function layoutHasTabs(layout: Layout): boolean {
11
- let found = false;
12
- walk(layout.root, (node) => {
13
- if (isTabsNode(node)) found = true;
14
- });
15
- return found;
6
+ return someNode(layout.root, (node) => isTabsNode(node));
16
7
  }
17
8
 
18
9
  /** A Menu with a dropdown, so hosts load the Escape-to-close menu script (W-197). */
19
10
  export function layoutHasMenuDropdown(layout: Layout): boolean {
20
- let found = false;
21
- walk(layout.root, (node) => {
22
- if (node.type === "menu-item" && nodeChildren(node).length > 0) found = true;
23
- });
24
- return found;
11
+ return someNode(
12
+ layout.root,
13
+ (node) => node.type === "menu-item" && nodeChildren(node).length > 0,
14
+ );
25
15
  }
@@ -1,8 +1,13 @@
1
1
  import type { VisitorInfo } from "../audience/rules.ts";
2
2
  import type { ArchivePagination } from "./pagination.ts";
3
3
  import type { Layout, LayoutNode } from "../schema/layout.ts";
4
- import { isParentNode } from "../schema/layout.ts";
4
+ import { LOOP_FILTER, LOOP_PERMALINK } from "../schema/layout.ts";
5
+ import { forEachNode, knownChildren } from "../tree-ops.ts";
6
+ import { isRecord } from "../record.ts";
7
+
8
+ const FIELD_SLUG = /^[a-z][a-z0-9_]{0,63}$/;
5
9
  import type { VNode } from "../render/vnode.ts";
10
+ import { sanitizeHref } from "../sanitize/href.ts";
6
11
 
7
12
  /** Normalized post fields for server-side theme binding (framework-free). */
8
13
  export type ThemePostFields = {
@@ -71,22 +76,93 @@ export const SAMPLE_POST: ThemePostFields = {
71
76
  featuredImageAlt: "Featured image",
72
77
  };
73
78
 
74
- const isRecord = (value: unknown): value is Record<string, unknown> =>
75
- Boolean(value) && typeof value === "object";
79
+ const BLOCK_STYLES = new Set(["normal", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote"]);
80
+ /** Portable Text decorators kept as their HTML element (W-328). */
81
+ const DECORATORS: Record<string, string> = {
82
+ strong: "strong",
83
+ em: "em",
84
+ code: "code",
85
+ underline: "u",
86
+ "strike-through": "s",
87
+ };
88
+ const MAX_LIST_DEPTH = 6;
89
+
90
+ /** The links a block defines (`markDefs`), by key, with hrefs that pass the link check. */
91
+ function linkDefs(block: Record<string, unknown>): Map<string, string> {
92
+ const links = new Map<string, string>();
93
+ const defs = Array.isArray(block["markDefs"]) ? block["markDefs"] : [];
94
+ for (const def of defs) {
95
+ if (!isRecord(def) || def["_type"] !== "link" || typeof def["_key"] !== "string") continue;
96
+ const href = typeof def["href"] === "string" ? sanitizeHref(def["href"]) : undefined;
97
+ if (href) links.set(def["_key"], href);
98
+ }
99
+ return links;
100
+ }
101
+
102
+ /** A span's text wrapped in its marks; unknown marks and unsafe links leave plain text. */
103
+ function spanNode(
104
+ span: Record<string, unknown>,
105
+ links: Map<string, string>,
106
+ ): VNode | string | null {
107
+ const text = typeof span["text"] === "string" ? span["text"] : "";
108
+ if (!text) return null;
109
+ const marks = Array.isArray(span["marks"])
110
+ ? span["marks"].filter((m) => typeof m === "string")
111
+ : [];
112
+ let node: VNode | string = text;
113
+ for (const mark of marks.toReversed()) {
114
+ const tag = DECORATORS[mark];
115
+ if (tag) node = { tag, attrs: {}, children: [node] };
116
+ else {
117
+ const href = links.get(mark);
118
+ if (href) node = { tag: "a", attrs: { href }, children: [node] };
119
+ }
120
+ }
121
+ return node;
122
+ }
123
+
124
+ /** A block's spans, with line breaks kept as `<br>`. */
125
+ function inlineNodes(block: Record<string, unknown>): (VNode | string)[] {
126
+ const links = linkDefs(block);
127
+ const children = Array.isArray(block["children"]) ? block["children"] : [];
128
+ const out: (VNode | string)[] = [];
129
+ for (const child of children) {
130
+ if (!isRecord(child) || (child["_type"] !== undefined && child["_type"] !== "span")) continue;
131
+ const node = spanNode(child, links);
132
+ if (node === null) continue;
133
+ if (typeof node === "string" && node.includes("\n")) {
134
+ node.split("\n").forEach((part, i) => {
135
+ if (i > 0) out.push({ tag: "br", attrs: {}, children: [] });
136
+ if (part) out.push(part);
137
+ });
138
+ } else out.push(node);
139
+ }
140
+ return out;
141
+ }
76
142
 
77
- const spanText = (children: unknown) =>
78
- Array.isArray(children)
79
- ? children
80
- .filter(isRecord)
81
- .map((span) => (typeof span["text"] === "string" ? span["text"] : ""))
82
- .join("")
83
- : "";
143
+ /** Adjacent text joined, and the block's outer whitespace trimmed, as before W-328. */
144
+ function tidy(nodes: (VNode | string)[]): (VNode | string)[] {
145
+ const out: (VNode | string)[] = [];
146
+ for (const node of nodes) {
147
+ const last = out.at(-1);
148
+ if (typeof node === "string" && typeof last === "string") out[out.length - 1] = last + node;
149
+ else out.push(node);
150
+ }
151
+ const first = out[0];
152
+ if (typeof first === "string") out[0] = first.trimStart();
153
+ const end = out.at(-1);
154
+ if (typeof end === "string") out[out.length - 1] = end.trimEnd();
155
+ return out.filter((node) => node !== "");
156
+ }
84
157
 
85
- const HEADING_STYLES = new Set(["h1", "h2", "h3", "h4"]);
158
+ const hasText = (nodes: readonly (VNode | string)[]): boolean =>
159
+ nodes.some((n) => (typeof n === "string" ? n.trim() !== "" : hasText(n.children)));
86
160
 
87
161
  /**
88
- * Convert Portable Text (or a plain string) into safe VNodes.
89
- * Marks are flattened to escaped text; only block structure is preserved.
162
+ * Convert Portable Text (or a plain string) into safe VNodes (W-328). Kept: paragraphs, headings
163
+ * (h1–h6), block quotes, bulleted and numbered lists (nested by level), bold, italic, code,
164
+ * underline, strike-through and links whose href passes the link check. Everything else (custom
165
+ * blocks, images, embeds, raw HTML) is left out; text is always escaped by the serializer.
90
166
  */
91
167
  export function portableTextToVNodes(value: unknown): VNode[] {
92
168
  if (typeof value === "string") {
@@ -94,32 +170,66 @@ export function portableTextToVNodes(value: unknown): VNode[] {
94
170
  return trimmed ? [{ tag: "p", attrs: {}, children: [trimmed] }] : [];
95
171
  }
96
172
  if (!Array.isArray(value)) return [];
97
- return value.flatMap((block): VNode[] => {
98
- if (!isRecord(block) || block["_type"] !== "block") return [];
99
- const text = spanText(block["children"]).trim();
100
- if (!text) return [];
101
- const style = block["style"];
102
- const tag = typeof style === "string" && HEADING_STYLES.has(style) ? style : "p";
103
- return [{ tag, attrs: {}, children: [text] }];
104
- });
173
+ const out: VNode[] = [];
174
+ // The open lists, outermost first, while consecutive list items continue them.
175
+ let lists: VNode[] = [];
176
+ for (const block of value) {
177
+ if (!isRecord(block) || block["_type"] !== "block") {
178
+ lists = [];
179
+ continue;
180
+ }
181
+ const inline = tidy(inlineNodes(block));
182
+ const listItem = block["listItem"];
183
+ if (listItem === "bullet" || listItem === "number") {
184
+ const tag = listItem === "number" ? "ol" : "ul";
185
+ const rawLevel = typeof block["level"] === "number" ? Math.floor(block["level"]) : 1;
186
+ const level = Math.min(Math.max(rawLevel, 1), MAX_LIST_DEPTH);
187
+ lists = lists.slice(0, level);
188
+ if (lists.length === level && lists[level - 1]?.tag !== tag)
189
+ lists = lists.slice(0, level - 1);
190
+ while (lists.length < level) {
191
+ const list: VNode = { tag, attrs: {}, children: [] };
192
+ const parent = lists.at(-1);
193
+ if (parent) {
194
+ const lastItem = parent.children.at(-1);
195
+ if (lastItem && typeof lastItem !== "string") lastItem.children.push(list);
196
+ else parent.children.push({ tag: "li", attrs: {}, children: [list] });
197
+ } else out.push(list);
198
+ lists.push(list);
199
+ }
200
+ if (hasText(inline))
201
+ lists[level - 1]?.children.push({ tag: "li", attrs: {}, children: inline });
202
+ continue;
203
+ }
204
+ lists = [];
205
+ if (!hasText(inline)) continue;
206
+ const style =
207
+ typeof block["style"] === "string" && BLOCK_STYLES.has(block["style"])
208
+ ? block["style"]
209
+ : "normal";
210
+ const tag = style === "normal" ? "p" : style;
211
+ out.push({ tag, attrs: {}, children: inline });
212
+ }
213
+ return out.filter((node) =>
214
+ node.tag !== "ul" && node.tag !== "ol" ? true : node.children.length > 0,
215
+ );
105
216
  }
106
217
 
107
218
  /** Collect `loop.itemPartId` values so hosts can load Loop Item templates. */
108
219
  export function collectLoopItemPartIds(layout: Layout): string[] {
109
220
  const ids = new Set<string>();
110
- const walk = (node: LayoutNode): void => {
111
- if (node.type === "loop") {
221
+ forEachNode(
222
+ layout.root,
223
+ (node) => {
224
+ if (node.type !== "loop") return;
112
225
  const id =
113
226
  typeof (node.props as { itemPartId?: unknown }).itemPartId === "string"
114
227
  ? (node.props as { itemPartId: string }).itemPartId.trim()
115
228
  : "";
116
229
  if (id) ids.add(id);
117
- }
118
- if (isParentNode(node)) {
119
- for (const child of node.children) walk(child);
120
- }
121
- };
122
- walk(layout.root);
230
+ },
231
+ knownChildren,
232
+ );
123
233
  return [...ids];
124
234
  }
125
235
 
@@ -129,28 +239,82 @@ export type CollectionLoop = {
129
239
  collection: string;
130
240
  limit: number;
131
241
  order: "newest" | "oldest" | "title";
242
+ /** W-330: where entries link, the image and excerpt fields, and `field = value` filters. */
243
+ permalink?: string;
244
+ imageField?: string;
245
+ excerptField?: string;
246
+ where?: Record<string, string | string[]>;
132
247
  };
133
248
 
249
+ const MAX_LOOP_FILTERS = 5;
250
+
251
+ /**
252
+ * `category=news; team=design` → `{ category: "news", team: "design" }` (W-330); the same field
253
+ * twice becomes a list (either value). At most 5 pairs; anything malformed is left out.
254
+ */
255
+ export function parseLoopFilter(text: unknown): Record<string, string | string[]> | undefined {
256
+ if (typeof text !== "string" || !LOOP_FILTER.test(text)) return undefined;
257
+ const where: Record<string, string | string[]> = {};
258
+ let count = 0;
259
+ for (const pair of text.split(";")) {
260
+ const at = pair.indexOf("=");
261
+ if (at < 0) continue;
262
+ const field = pair.slice(0, at).trim();
263
+ const value = pair.slice(at + 1).trim();
264
+ if (!field || !value || count >= MAX_LOOP_FILTERS) continue;
265
+ count += 1;
266
+ const had = where[field];
267
+ where[field] = had === undefined ? value : [...(Array.isArray(had) ? had : [had]), value];
268
+ }
269
+ return count > 0 ? where : undefined;
270
+ }
271
+
272
+ /** An entry's link from a Loop's pattern (W-330): `{slug}` and `{id}` filled in, URL-encoded. */
273
+ export function loopPermalink(pattern: string, entry: { slug: string; id: string }): string {
274
+ return pattern
275
+ .replaceAll("{slug}", encodeURIComponent(entry.slug))
276
+ .replaceAll("{id}", encodeURIComponent(entry.id));
277
+ }
278
+
134
279
  /** Every collection Loop in a layout, so hosts can fetch their entries (W-308). */
135
280
  export function collectCollectionLoops(layout: Layout): CollectionLoop[] {
136
281
  const loops: CollectionLoop[] = [];
137
282
  const walk = (node: LayoutNode): void => {
138
283
  if (node.type === "loop" && loops.length < 20) {
139
- const props = node.props as { collection?: unknown; limit?: unknown; order?: unknown };
284
+ const props = node.props as {
285
+ collection?: unknown;
286
+ limit?: unknown;
287
+ order?: unknown;
288
+ permalink?: unknown;
289
+ imageField?: unknown;
290
+ excerptField?: unknown;
291
+ filter?: unknown;
292
+ };
140
293
  if (typeof props.collection === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(props.collection)) {
141
294
  const limit =
142
295
  typeof props.limit === "number" && props.limit >= 1 && props.limit <= 50
143
296
  ? Math.floor(props.limit)
144
297
  : 6;
145
298
  const order = props.order === "oldest" || props.order === "title" ? props.order : "newest";
146
- loops.push({ nodeId: node.id, collection: props.collection, limit, order });
299
+ const loop: CollectionLoop = {
300
+ nodeId: node.id,
301
+ collection: props.collection,
302
+ limit,
303
+ order,
304
+ };
305
+ if (typeof props.permalink === "string" && LOOP_PERMALINK.test(props.permalink))
306
+ loop.permalink = props.permalink;
307
+ if (typeof props.imageField === "string" && FIELD_SLUG.test(props.imageField))
308
+ loop.imageField = props.imageField;
309
+ if (typeof props.excerptField === "string" && FIELD_SLUG.test(props.excerptField))
310
+ loop.excerptField = props.excerptField;
311
+ const where = parseLoopFilter(props.filter);
312
+ if (where) loop.where = where;
313
+ loops.push(loop);
147
314
  }
148
315
  }
149
- if (isParentNode(node)) {
150
- for (const child of node.children) walk(child);
151
- }
152
316
  };
153
- walk(layout.root);
317
+ forEachNode(layout.root, walk, knownChildren);
154
318
  return loops;
155
319
  }
156
320
 
@@ -165,11 +329,8 @@ export function collectSectionPartIds(layout: Layout): string[] {
165
329
  : "";
166
330
  if (id) ids.add(id);
167
331
  }
168
- if (isParentNode(node)) {
169
- for (const child of node.children) walk(child);
170
- }
171
332
  };
172
- walk(layout.root);
333
+ forEachNode(layout.root, walk, knownChildren);
173
334
  return [...ids];
174
335
  }
175
336
 
@@ -100,7 +100,7 @@ export function wrapFloatMarkup(
100
100
  ): string {
101
101
  const safeId = escapeAttr(id);
102
102
  const label = escapeAttr(title.trim() || "Notice");
103
- const edge = settings.edge;
103
+ const edge = escapeAttr(settings.edge);
104
104
  const close = settings.dismiss
105
105
  ? `<button type="button" class="emvb-float__close" data-emvb-float-dismiss aria-label="Close"><span aria-hidden="true">×</span></button>`
106
106
  : "";