@perkyzz/emvb 0.2.1 → 0.3.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 (78) hide show
  1. package/package.json +1 -1
  2. package/src/admin/editor/A11yCopilot.tsx +126 -0
  3. package/src/admin/editor/CommandPalette.tsx +118 -0
  4. package/src/admin/editor/Editor.tsx +274 -12
  5. package/src/admin/editor/EditorOverlay.tsx +6 -0
  6. package/src/admin/editor/PerfMeter.tsx +121 -0
  7. package/src/admin/editor/ShareLink.tsx +164 -0
  8. package/src/admin/editor/Timeline.tsx +274 -0
  9. package/src/admin/editor/TopBar.tsx +4 -0
  10. package/src/admin/editor/canvas/CanvasFrame.tsx +12 -3
  11. package/src/admin/editor/canvas/SelectionOverlay.tsx +1 -1
  12. package/src/admin/editor/collection-previews.ts +91 -0
  13. package/src/admin/editor/editor-css.ts +5 -3
  14. package/src/admin/editor/feature-css.ts +105 -0
  15. package/src/admin/editor/host.ts +2 -0
  16. package/src/admin/editor/live-data.tsx +71 -0
  17. package/src/admin/editor/palette-items.ts +105 -0
  18. package/src/admin/editor/palette.ts +67 -0
  19. package/src/admin/editor/panels/AddPanel.tsx +47 -2
  20. package/src/admin/editor/panels/ClassesSection.tsx +5 -1
  21. package/src/admin/editor/panels/ElementPanel.tsx +34 -3
  22. package/src/admin/editor/panels/LayersPanel.tsx +38 -1
  23. package/src/admin/editor/panels/LeftPanel.tsx +4 -1
  24. package/src/admin/editor/panels/SettingsPanel.tsx +12 -0
  25. package/src/admin/editor/panels/SiteStylesDrawer.tsx +2 -0
  26. package/src/admin/editor/panels/TokenScales.tsx +168 -0
  27. package/src/admin/editor/panels/VariableSection.tsx +9 -4
  28. package/src/admin/editor/panels/settings/AudienceEditor.tsx +215 -0
  29. package/src/admin/editor/panels/settings/BindingsEditor.tsx +221 -0
  30. package/src/admin/editor/panels/settings/ClassChipInput.tsx +1 -1
  31. package/src/admin/editor/panels/settings/EffectsControls.tsx +2 -2
  32. package/src/admin/editor/panels/settings/MotionControl.tsx +252 -0
  33. package/src/admin/editor/panels/settings/StateSwitcher.tsx +1 -1
  34. package/src/admin/editor/panels/settings/StyleRow.tsx +12 -0
  35. package/src/admin/editor/panels/settings/StyleSources.tsx +94 -0
  36. package/src/admin/editor/panels/settings/VariableBinding.tsx +1 -1
  37. package/src/admin/editor/panels/settings/VariantEditor.tsx +83 -0
  38. package/src/admin/editor/panels/settings/length-units.ts +1 -1
  39. package/src/admin/editor/panels/settings/style-sections.ts +2 -1
  40. package/src/admin/editor/shortcuts.ts +2 -1
  41. package/src/admin/editor/useEditorShortcuts.ts +8 -0
  42. package/src/admin/editor/useNodeActions.ts +38 -15
  43. package/src/admin/ui.ts +4 -4
  44. package/src/astro/request-data.ts +97 -0
  45. package/src/astro/resolve-theme.ts +35 -5
  46. package/src/astro/resolve.ts +8 -2
  47. package/src/astro/theme-posts.ts +32 -0
  48. package/src/astro/visitor.ts +142 -0
  49. package/src/constants.ts +1 -1
  50. package/src/core/a11y/audit.ts +282 -0
  51. package/src/core/arrange.ts +91 -0
  52. package/src/core/audience/rules.ts +104 -0
  53. package/src/core/audience/variants.ts +51 -0
  54. package/src/core/css/generate.ts +20 -2
  55. package/src/core/css/trace.ts +169 -0
  56. package/src/core/data/bindings.ts +257 -0
  57. package/src/core/design/tokens.ts +127 -0
  58. package/src/core/elements/dynamic-elements.ts +87 -2
  59. package/src/core/elements/index.ts +2 -0
  60. package/src/core/history/diff.ts +152 -0
  61. package/src/core/index.ts +111 -0
  62. package/src/core/migrate/index.ts +4 -1
  63. package/src/core/nesting.ts +1 -0
  64. package/src/core/perf/meter.ts +160 -0
  65. package/src/core/perf/scripts.ts +58 -0
  66. package/src/core/recipes/index.ts +433 -0
  67. package/src/core/render/index.ts +51 -4
  68. package/src/core/render/loop.ts +54 -7
  69. package/src/core/render/pagination.ts +9 -1
  70. package/src/core/sanitize/css.ts +39 -3
  71. package/src/core/sanitize/motion.ts +129 -0
  72. package/src/core/schema/design.ts +25 -2
  73. package/src/core/schema/layout.ts +168 -18
  74. package/src/core/schema/motion.ts +14 -0
  75. package/src/core/schema/style.ts +48 -3
  76. package/src/core/share/link.ts +147 -0
  77. package/src/core/theme/dynamic.ts +49 -0
  78. package/src/core/theme/pagination.ts +56 -0
@@ -0,0 +1,169 @@
1
+ import type { DefaultStyleTag, DesignSystem } from "../schema/design.ts";
2
+ import type { LayoutNode } from "../schema/layout.ts";
3
+ import type { StyleStateName } from "../schema/state-names.ts";
4
+ import type { StyleProps } from "../schema/style.ts";
5
+
6
+ export type TraceDevice = "desktop" | "tablet" | "mobile";
7
+
8
+ /** Where one style value comes from (W-318). */
9
+ export type StyleSource = {
10
+ kind: "default" | "class" | "local";
11
+ /** "Site default (H2)", ".card", "This element". */
12
+ label: string;
13
+ /** Desktop, Tablet, Mobile, or a state such as Hover. */
14
+ layer: string;
15
+ classId?: string;
16
+ value: unknown;
17
+ };
18
+
19
+ /** For one property: the value that applies and the ones it overrides, strongest first. */
20
+ export type StyleTrace = { winner: StyleSource; overridden: StyleSource[] };
21
+
22
+ /** The tag a node renders whose Site styles default applies (W-318). */
23
+ export function defaultTagFor(node: LayoutNode): DefaultStyleTag | undefined {
24
+ const props = node.props as Record<string, unknown>;
25
+ switch (node.type) {
26
+ case "heading": {
27
+ const level = typeof props["level"] === "number" ? props["level"] : 2;
28
+ return `h${Math.min(6, Math.max(1, level))}` as DefaultStyleTag;
29
+ }
30
+ case "text":
31
+ return props["tag"] === "div" ? undefined : "p";
32
+ case "link":
33
+ return "a";
34
+ case "button":
35
+ return typeof props["href"] === "string" && props["href"].trim() ? "a" : "button";
36
+ default:
37
+ return undefined;
38
+ }
39
+ }
40
+
41
+ const LAYER = { desktop: "Desktop", tablet: "Tablet", mobile: "Mobile" } as const;
42
+ const STATE_LABEL: Record<StyleStateName, string> = {
43
+ hover: "Hover",
44
+ focus: "Focus",
45
+ active: "Active",
46
+ };
47
+
48
+ type Owner = {
49
+ kind: "class" | "local";
50
+ label: string;
51
+ classId?: string;
52
+ style?: StyleProps;
53
+ devices?: { tablet?: StyleProps; mobile?: StyleProps };
54
+ states?: Partial<Record<StyleStateName, StyleProps>>;
55
+ };
56
+
57
+ /**
58
+ * Every style layer that applies to a node on a device and in a state, weakest first, in the
59
+ * cascade EmVB emits (W-318): the tag's Site styles default, each class in site order (later
60
+ * classes win), then the element's own styles; within each, Desktop then Tablet then Mobile;
61
+ * state styles last, classes before the element.
62
+ */
63
+ export function styleLayers(
64
+ node: LayoutNode,
65
+ design: DesignSystem,
66
+ device: TraceDevice = "desktop",
67
+ state: StyleStateName | "normal" = "normal",
68
+ ): { source: Omit<StyleSource, "value">; style: StyleProps }[] {
69
+ const layers: { source: Omit<StyleSource, "value">; style: StyleProps }[] = [];
70
+ const tag = defaultTagFor(node);
71
+ const tagStyle = tag ? design.defaults?.[tag] : undefined;
72
+ if (tag && tagStyle) {
73
+ layers.push({
74
+ source: { kind: "default", label: `Site default (${tag.toUpperCase()})`, layer: "Desktop" },
75
+ style: tagStyle,
76
+ });
77
+ }
78
+ const applied = new Set(node.classes ?? []);
79
+ const owners: Owner[] = [];
80
+ for (const cls of design.classes ?? []) {
81
+ if (!applied.has(cls.id)) continue;
82
+ const owner: Owner = {
83
+ kind: "class",
84
+ label: `.${cls.name}`,
85
+ classId: cls.id,
86
+ style: cls.style,
87
+ };
88
+ if (cls.devices) owner.devices = cls.devices;
89
+ if (cls.states) owner.states = cls.states;
90
+ owners.push(owner);
91
+ }
92
+ owners.push({
93
+ kind: "local",
94
+ label: "This element",
95
+ ...(node.style ? { style: node.style } : {}),
96
+ ...(node.devices ? { devices: node.devices } : {}),
97
+ ...(node.states ? { states: node.states as Owner["states"] } : {}),
98
+ });
99
+ for (const owner of owners) {
100
+ const base = {
101
+ kind: owner.kind,
102
+ label: owner.label,
103
+ ...(owner.classId ? { classId: owner.classId } : {}),
104
+ };
105
+ if (owner.style) layers.push({ source: { ...base, layer: LAYER.desktop }, style: owner.style });
106
+ if (device !== "desktop" && owner.devices?.tablet) {
107
+ layers.push({ source: { ...base, layer: LAYER.tablet }, style: owner.devices.tablet });
108
+ }
109
+ if (device === "mobile" && owner.devices?.mobile) {
110
+ layers.push({ source: { ...base, layer: LAYER.mobile }, style: owner.devices.mobile });
111
+ }
112
+ }
113
+ if (state !== "normal") {
114
+ for (const owner of owners) {
115
+ const style = owner.states?.[state];
116
+ if (!style) continue;
117
+ layers.push({
118
+ source: {
119
+ kind: owner.kind,
120
+ label: owner.label,
121
+ ...(owner.classId ? { classId: owner.classId } : {}),
122
+ layer: STATE_LABEL[state],
123
+ },
124
+ style,
125
+ });
126
+ }
127
+ }
128
+ return layers;
129
+ }
130
+
131
+ /** Where each set property of a node comes from (W-318), by property name. */
132
+ export function traceStyle(
133
+ node: LayoutNode,
134
+ design: DesignSystem,
135
+ device: TraceDevice = "desktop",
136
+ state: StyleStateName | "normal" = "normal",
137
+ ): Record<string, StyleTrace> {
138
+ const all: Record<string, StyleSource[]> = {};
139
+ for (const { source, style } of styleLayers(node, design, device, state)) {
140
+ for (const [key, value] of Object.entries(style)) {
141
+ if (value === undefined) continue;
142
+ (all[key] ??= []).push({ ...source, value });
143
+ }
144
+ }
145
+ const out: Record<string, StyleTrace> = {};
146
+ for (const [key, sources] of Object.entries(all)) {
147
+ const strongest = sources.toReversed();
148
+ out[key] = { winner: strongest[0] as StyleSource, overridden: strongest.slice(1) };
149
+ }
150
+ return out;
151
+ }
152
+
153
+ /**
154
+ * What a node's own style edit sits on top of (W-318): every value from its tag default and its
155
+ * classes on this device (and, on Tablet/Mobile or in a state, from its own wider layers). The
156
+ * editor shows these as the controls' inherited values.
157
+ */
158
+ export function inheritedStyle(
159
+ node: LayoutNode,
160
+ design: DesignSystem,
161
+ device: TraceDevice,
162
+ state: StyleStateName | "normal",
163
+ ): StyleProps {
164
+ const layers = styleLayers(node, design, device, state);
165
+ // Drop the layer being edited: the element's own on this device and state.
166
+ const editing = state !== "normal" ? STATE_LABEL[state] : LAYER[device];
167
+ const below = layers.filter((l) => !(l.source.kind === "local" && l.source.layer === editing));
168
+ return Object.assign({}, ...below.map((l) => l.style)) as StyleProps;
169
+ }
@@ -0,0 +1,257 @@
1
+ import type { Binding, BindSource, LayoutNode } from "../schema/layout.ts";
2
+ import { sanitizeHref } from "../sanitize/href.ts";
3
+ import { sanitizeMediaUrl } from "../sanitize/media-url.ts";
4
+ import type { ThemePostFields } from "../theme/dynamic.ts";
5
+
6
+ /**
7
+ * Live data bindings (W-307). A text, image or link field can read a post field, a site setting
8
+ * or a URL parameter instead of its typed value. The typed value stays as the fallback, so a page
9
+ * never shows an empty heading because a parameter is missing. Values are plain text: the element
10
+ * still escapes text and sanitizes links and image URLs, exactly as for a typed value.
11
+ */
12
+
13
+ /** How a bound value is used, which decides how it's cleaned before the element sees it. */
14
+ export type BindKind = "text" | "url" | "image";
15
+
16
+ export type BindableField = { key: string; label: string; kind: BindKind };
17
+
18
+ const TEXT = (label = "Text"): BindableField => ({ key: "text", label, kind: "text" });
19
+ const HREF = (label = "Link"): BindableField => ({ key: "href", label, kind: "url" });
20
+
21
+ /** Which props of which elements can be bound. Anything else in `bind` is ignored on render. */
22
+ export const BINDABLE_FIELDS: Readonly<Record<string, readonly BindableField[]>> = {
23
+ heading: [TEXT(), HREF()],
24
+ text: [TEXT()],
25
+ label: [TEXT()],
26
+ link: [TEXT(), HREF("URL")],
27
+ button: [TEXT(), HREF()],
28
+ image: [
29
+ { key: "src", label: "Image", kind: "image" },
30
+ { key: "alt", label: "Alt text", kind: "text" },
31
+ ],
32
+ icon: [HREF(), { key: "title", label: "Title", kind: "text" }],
33
+ "menu-item": [TEXT("Label"), HREF()],
34
+ container: [HREF()],
35
+ "div-block": [HREF()],
36
+ flexbox: [HREF()],
37
+ grid: [HREF()],
38
+ };
39
+
40
+ export const bindableFields = (type: string): readonly BindableField[] =>
41
+ Object.hasOwn(BINDABLE_FIELDS, type) ? (BINDABLE_FIELDS[type] ?? []) : [];
42
+
43
+ /** The post fields the editor offers by name; any other key reads the post's own data. */
44
+ export const POST_BIND_KEYS = [
45
+ { key: "title", label: "Title" },
46
+ { key: "excerpt", label: "Excerpt" },
47
+ { key: "permalink", label: "Permalink" },
48
+ { key: "slug", label: "Slug" },
49
+ { key: "publishedAt", label: "Published date" },
50
+ { key: "authorName", label: "Author" },
51
+ { key: "featuredImageUrl", label: "Featured image" },
52
+ { key: "featuredImageAlt", label: "Featured image alt" },
53
+ ] as const;
54
+
55
+ /** Site settings hosts pass in by default (EmDash's `getSiteSettings`). */
56
+ export const SITE_BIND_KEYS = [
57
+ { key: "title", label: "Site title" },
58
+ { key: "tagline", label: "Tagline" },
59
+ { key: "url", label: "Site URL" },
60
+ ] as const;
61
+
62
+ export const BIND_SOURCE_LABELS: Readonly<Record<BindSource, string>> = {
63
+ post: "Post field",
64
+ site: "Site setting",
65
+ param: "URL parameter",
66
+ };
67
+
68
+ /** Where bound values come from on this render. */
69
+ export type BindingData = {
70
+ post?: ThemePostFields;
71
+ site?: Readonly<Record<string, string>>;
72
+ params?: Readonly<Record<string, string>>;
73
+ /** The page's origin; a URL-parameter link or image must stay on it unless `outside` (W-307). */
74
+ origin?: string;
75
+ };
76
+
77
+ /** Longest bound value an element receives; longer values are cut (URL parameters are untrusted). */
78
+ export const MAX_BOUND_LENGTH = 500;
79
+
80
+ const POST_KEYS = new Set<string>(POST_BIND_KEYS.map((k) => k.key));
81
+
82
+ function scalar(value: unknown): string | undefined {
83
+ if (typeof value === "string") return value;
84
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
85
+ if (typeof value === "boolean") return value ? "true" : "false";
86
+ return undefined;
87
+ }
88
+
89
+ function postValue(post: ThemePostFields | undefined, key: string): string | undefined {
90
+ if (!post) return undefined;
91
+ if (POST_KEYS.has(key)) return scalar((post as Record<string, unknown>)[key]);
92
+ const fields = post.fields;
93
+ if (!fields || !Object.hasOwn(fields, key)) return undefined;
94
+ return scalar(fields[key]);
95
+ }
96
+
97
+ /** Text with control characters removed and its length capped. */
98
+ function clean(value: string): string {
99
+ let out = "";
100
+ for (const char of value) {
101
+ const code = char.codePointAt(0) ?? 0;
102
+ if (code === 10 || code === 9) out += char === "\t" ? " " : char;
103
+ else if (code >= 32 && code !== 127) out += char;
104
+ if (out.length >= MAX_BOUND_LENGTH) break;
105
+ }
106
+ return out.slice(0, MAX_BOUND_LENGTH).trim();
107
+ }
108
+
109
+ /** The live value of one binding, or undefined when its source has nothing for this key. */
110
+ export function resolveBinding(binding: Binding, data: BindingData): string | undefined {
111
+ let raw: string | undefined;
112
+ if (binding.source === "post") raw = postValue(data.post, binding.key);
113
+ else if (binding.source === "site") {
114
+ raw = data.site && Object.hasOwn(data.site, binding.key) ? data.site[binding.key] : undefined;
115
+ } else {
116
+ raw =
117
+ data.params && Object.hasOwn(data.params, binding.key) ? data.params[binding.key] : undefined;
118
+ }
119
+ if (raw === undefined) return undefined;
120
+ const value = clean(raw);
121
+ return value.length > 0 ? value : undefined;
122
+ }
123
+
124
+ /** True when the node has at least one binding render would use. */
125
+ export function hasBindings(node: LayoutNode): boolean {
126
+ const bind = node.bind;
127
+ if (!bind) return false;
128
+ return bindableFields(node.type).some((field) => Object.hasOwn(bind, field.key));
129
+ }
130
+
131
+ /**
132
+ * Whether a URL stays on this site: relative (`/path`, `?q`, `#top`, `page`), or absolute on
133
+ * `origin`. `//host` and other schemes are outside; without an origin, only relative URLs pass.
134
+ */
135
+ function isSameSiteUrl(value: string, origin: string | undefined): boolean {
136
+ const url = value.trim();
137
+ if (/^[/\\]{2}/.test(url)) return false;
138
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) return true;
139
+ if (!origin) return false;
140
+ try {
141
+ return new URL(url).origin === new URL(origin).origin;
142
+ } catch {
143
+ return false;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * The value a bound field shows (W-307), after every check render applies, or undefined when
149
+ * the typed value shows instead: nothing to read, a link or image the sanitizer refuses, or a
150
+ * URL-parameter link or image to another site without "Allow outside sites".
151
+ */
152
+ export function boundValue(
153
+ field: BindableField,
154
+ binding: Binding,
155
+ data: BindingData,
156
+ multiline = false,
157
+ ): string | undefined {
158
+ let value = resolveBinding(binding, data);
159
+ if (value === undefined) return undefined;
160
+ if (!multiline) value = value.replace(/\s*\n\s*/g, " ");
161
+ if (field.kind === "url" && !sanitizeHref(value)) return undefined;
162
+ if (field.kind === "image" && !sanitizeMediaUrl(value)) return undefined;
163
+ if (
164
+ field.kind !== "text" &&
165
+ binding.source === "param" &&
166
+ !binding.outside &&
167
+ !isSameSiteUrl(value, data.origin)
168
+ ) {
169
+ return undefined;
170
+ }
171
+ return value;
172
+ }
173
+
174
+ /**
175
+ * The node with its bound props replaced by live values (W-307). Unbindable keys, empty values and
176
+ * links or images the sanitizer would refuse leave the typed prop as it is, so a bad URL parameter
177
+ * can't blank a button or an image. A URL parameter can't send a link or image off the site unless
178
+ * the binding allows outside sites (see `boundValue`). A bound text field that is single-line stays single-line.
179
+ */
180
+ export function applyBindings(node: LayoutNode, data: BindingData): LayoutNode {
181
+ const bind = node.bind;
182
+ if (!bind) return node;
183
+ let props: Record<string, unknown> | undefined;
184
+ for (const field of bindableFields(node.type)) {
185
+ const binding = Object.hasOwn(bind, field.key) ? bind[field.key] : undefined;
186
+ if (!binding) continue;
187
+ const value = boundValue(field, binding, data, field.kind === "text" && node.type === "text");
188
+ if (value === undefined) continue;
189
+ props ??= { ...(node.props as Record<string, unknown>) };
190
+ props[field.key] = value;
191
+ // A bound image is no longer the media library item it was picked from.
192
+ if (field.kind === "image") delete props["mediaId"];
193
+ }
194
+ return props ? ({ ...node, props } as LayoutNode) : node;
195
+ }
196
+
197
+ /** Sets or clears one binding, dropping `bind` once it is empty. */
198
+ export function withBinding(
199
+ node: LayoutNode,
200
+ key: string,
201
+ binding: Binding | undefined,
202
+ ): LayoutNode {
203
+ const next: Record<string, Binding> = { ...node.bind };
204
+ if (binding) next[key] = binding;
205
+ else delete next[key];
206
+ const { bind: _old, ...rest } = node;
207
+ return (Object.keys(next).length > 0 ? { ...rest, bind: next } : rest) as LayoutNode;
208
+ }
209
+
210
+ /** Search parameters as a plain record, first value per name, with names and values capped. */
211
+ export function paramsFromSearch(search: URLSearchParams): Record<string, string> {
212
+ const params: Record<string, string> = {};
213
+ let count = 0;
214
+ for (const [name, value] of search) {
215
+ if (count >= 50) break;
216
+ if (!/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(name) || Object.hasOwn(params, name)) continue;
217
+ params[name] = value.slice(0, MAX_BOUND_LENGTH * 4);
218
+ count += 1;
219
+ }
220
+ return params;
221
+ }
222
+
223
+ /** Site settings as flat text for bindings (W-307): `title`, `tagline`, `url`, `social.github`… */
224
+ export function siteBindingValues(settings: unknown): Record<string, string> {
225
+ const out: Record<string, string> = {};
226
+ if (!settings || typeof settings !== "object") return out;
227
+ const add = (key: string, value: unknown) => {
228
+ if (typeof value === "string" && value.trim()) out[key] = value.trim();
229
+ else if (typeof value === "number" && Number.isFinite(value)) out[key] = String(value);
230
+ };
231
+ for (const [key, value] of Object.entries(settings as Record<string, unknown>)) {
232
+ if (key === "seo") continue;
233
+ if (value && typeof value === "object") {
234
+ if (key === "logo" || key === "favicon") {
235
+ const media = value as { src?: unknown; url?: unknown };
236
+ add(key, media.src ?? media.url);
237
+ continue;
238
+ }
239
+ for (const [inner, innerValue] of Object.entries(value as Record<string, unknown>)) {
240
+ add(`${key}.${inner}`, innerValue);
241
+ }
242
+ continue;
243
+ }
244
+ add(key, value);
245
+ }
246
+ return out;
247
+ }
248
+
249
+ /** Whether any node in the tree reads a source (hosts fetch site settings only when needed). */
250
+ export function layoutUsesSource(root: LayoutNode, source: BindSource): boolean {
251
+ const walk = (node: LayoutNode): boolean => {
252
+ if (node.bind && Object.values(node.bind).some((b) => b.source === source)) return true;
253
+ const children: unknown = (node as { children?: unknown }).children;
254
+ return Array.isArray(children) && (children as LayoutNode[]).some(walk);
255
+ };
256
+ return walk(root);
257
+ }
@@ -0,0 +1,127 @@
1
+ import type { DesignSystem, FluidRange, LengthVariable } from "../schema/design.ts";
2
+
3
+ /** Screen widths fluid sizes grow between when the site sets none (W-316). */
4
+ export const DEFAULT_FLUID_RANGE: FluidRange = { minWidth: 360, maxWidth: 1280 };
5
+
6
+ const round = (n: number, places = 4) => Number(n.toFixed(places));
7
+
8
+ /**
9
+ * `clamp()` growing from `min` px at the range's small screen to `max` px at its large one
10
+ * (W-316), in rem so it follows the visitor's font size. Equal sizes give a plain rem value.
11
+ */
12
+ export function fluidClamp(
13
+ min: number,
14
+ max: number,
15
+ range: FluidRange = DEFAULT_FLUID_RANGE,
16
+ ): string {
17
+ const lo = Math.min(min, max);
18
+ const hi = Math.max(min, max);
19
+ if (lo === hi || range.maxWidth <= range.minWidth) return `${round(max / 16)}rem`;
20
+ const slope = (max - min) / (range.maxWidth - range.minWidth);
21
+ const intercept = min - slope * range.minWidth;
22
+ return `clamp(${round(lo / 16)}rem, ${round(intercept / 16)}rem + ${round(slope * 100)}vw, ${round(hi / 16)}rem)`;
23
+ }
24
+
25
+ /** Musical ratios type scales use, with their names (W-316). */
26
+ export const SCALE_RATIOS = [
27
+ { value: 1.125, label: "Major second · 1.125" },
28
+ { value: 1.2, label: "Minor third · 1.2" },
29
+ { value: 1.25, label: "Major third · 1.25" },
30
+ { value: 1.333, label: "Perfect fourth · 1.333" },
31
+ { value: 1.4, label: "Augmented fourth · 1.4" },
32
+ { value: 1.5, label: "Perfect fifth · 1.5" },
33
+ { value: 1.618, label: "Golden ratio · 1.618" },
34
+ ] as const;
35
+
36
+ export type ScaleInput = {
37
+ /** Body size on large screens, px. */
38
+ base: number;
39
+ ratio: number;
40
+ /** Body size on small screens, px; unset = not fluid. */
41
+ minBase?: number;
42
+ /** Ratio on small screens (usually smaller); unset = `ratio`. */
43
+ minRatio?: number;
44
+ };
45
+
46
+ const TYPE_STEPS = [
47
+ { id: "fs-xs", name: "Text XS", step: -2 },
48
+ { id: "fs-s", name: "Text S", step: -1 },
49
+ { id: "fs-m", name: "Text M", step: 0 },
50
+ { id: "fs-l", name: "Text L", step: 1 },
51
+ { id: "fs-xl", name: "Heading S", step: 2 },
52
+ { id: "fs-2xl", name: "Heading M", step: 3 },
53
+ { id: "fs-3xl", name: "Heading L", step: 4 },
54
+ { id: "fs-4xl", name: "Display", step: 5 },
55
+ ] as const;
56
+
57
+ const SPACE_STEPS = [
58
+ { id: "space-3xs", name: "Space 3XS", times: 0.25 },
59
+ { id: "space-2xs", name: "Space 2XS", times: 0.5 },
60
+ { id: "space-xs", name: "Space XS", times: 0.75 },
61
+ { id: "space-s", name: "Space S", times: 1 },
62
+ { id: "space-m", name: "Space M", times: 1.5 },
63
+ { id: "space-l", name: "Space L", times: 2 },
64
+ { id: "space-xl", name: "Space XL", times: 3 },
65
+ { id: "space-2xl", name: "Space 2XL", times: 4 },
66
+ { id: "space-3xl", name: "Space 3XL", times: 6 },
67
+ ] as const;
68
+
69
+ const valid = (n: number | undefined, lo: number, hi: number): n is number =>
70
+ typeof n === "number" && Number.isFinite(n) && n >= lo && n <= hi;
71
+
72
+ function token(id: string, name: string, max: number, min: number | undefined): LengthVariable {
73
+ const big = round(Math.min(1000, max), 2);
74
+ return {
75
+ id,
76
+ name,
77
+ value: { value: big, unit: "px" },
78
+ ...(min !== undefined && round(min, 2) !== big
79
+ ? { fluid: { min: round(Math.min(1000, min), 2), max: big } }
80
+ : {}),
81
+ };
82
+ }
83
+
84
+ /**
85
+ * A type scale from a base size and a ratio (W-316): eight sizes from Text XS to Display. With a
86
+ * small-screen base (and ratio), each size is fluid between the two.
87
+ */
88
+ export function typeScale(input: ScaleInput): LengthVariable[] {
89
+ if (!valid(input.base, 8, 64) || !valid(input.ratio, 1.01, 2)) return [];
90
+ const minBase = valid(input.minBase, 8, 64) ? input.minBase : undefined;
91
+ const minRatio = valid(input.minRatio, 1.01, 2) ? input.minRatio : input.ratio;
92
+ return TYPE_STEPS.map(({ id, name, step }) =>
93
+ token(
94
+ id,
95
+ name,
96
+ input.base * input.ratio ** step,
97
+ minBase === undefined ? undefined : minBase * minRatio ** step,
98
+ ),
99
+ );
100
+ }
101
+
102
+ /** A spacing scale from one base gap (W-316): nine steps from 3XS to 3XL; fluid like type. */
103
+ export function spaceScale(input: { base: number; minBase?: number }): LengthVariable[] {
104
+ if (!valid(input.base, 2, 64)) return [];
105
+ const minBase = valid(input.minBase, 2, 64) ? input.minBase : undefined;
106
+ return SPACE_STEPS.map(({ id, name, times }) =>
107
+ token(id, name, input.base * times, minBase === undefined ? undefined : minBase * times),
108
+ );
109
+ }
110
+
111
+ /**
112
+ * Adds generated tokens to the site's font sizes or spacing (W-316). A token whose id exists
113
+ * replaces it in place, so elements using it pick up the new size; others are appended.
114
+ */
115
+ export function applyTokens(
116
+ design: DesignSystem,
117
+ list: "fontSizes" | "spacings",
118
+ tokens: LengthVariable[],
119
+ ): DesignSystem {
120
+ const current = design.variables[list] ?? [];
121
+ const byId = new Map(tokens.map((t) => [t.id, t]));
122
+ const replaced = current.map((v) => byId.get(v.id) ?? v);
123
+ const have = new Set(current.map((v) => v.id));
124
+ const limit = list === "fontSizes" ? 50 : 100;
125
+ const added = tokens.filter((t) => !have.has(t.id)).slice(0, Math.max(0, limit - current.length));
126
+ return { ...design, variables: { ...design.variables, [list]: [...replaced, ...added] } };
127
+ }
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ LoopEmptyNode,
2
3
  LoopNode,
3
4
  SectionNode,
4
5
  PostAuthorNode,
@@ -151,9 +152,21 @@ export const postLink: ElementDefinition<PostLinkNode> = {
151
152
  build: (_node, attrs) => ({ tag: "a", attrs: { ...attrs, href: "#" }, children: ["Post link"] }),
152
153
  };
153
154
 
155
+ /** How a Loop shows its items (W-308). */
156
+ const DISPLAY_OPTIONS = [
157
+ { value: "list", label: "List" },
158
+ { value: "grid", label: "Grid" },
159
+ { value: "cards", label: "Cards" },
160
+ ];
161
+
154
162
  export const loop: ElementDefinition<LoopNode> = {
155
163
  baseCss:
156
- ".emvb-loop{display:flex;flex-direction:column;min-width:0;gap:1rem}.emvb-loop[data-emvb-loop-empty]{min-height:48px;padding:12px;color:var(--text-color-kumo-subtle,#666);background:var(--color-kumo-tint,#eee)}",
164
+ ".emvb-loop{display:flex;flex-direction:column;min-width:0;gap:1rem}.emvb-loop[data-emvb-loop-empty]{min-height:48px;padding:12px;color:var(--text-color-kumo-subtle,#666);background:var(--color-kumo-tint,#eee)}" +
165
+ // W-308: grid and cards share one item design; phones get one column.
166
+ ".emvb-loop-grid,.emvb-loop-cards{display:grid;grid-template-columns:repeat(var(--emvb-loop-columns,3),minmax(0,1fr))}" +
167
+ ".emvb-loop-cards>.emvb-loop-item{padding:1rem;border:1px solid color-mix(in srgb,currentColor 15%,transparent);border-radius:12px;background:color-mix(in srgb,currentColor 3%,transparent)}" +
168
+ ".emvb-loop-grid>.emvb-loop-empty,.emvb-loop-cards>.emvb-loop-empty{grid-column:1/-1}" +
169
+ "@media (max-width: 767px){.emvb-loop-grid,.emvb-loop-cards{grid-template-columns:minmax(0,1fr)}}",
157
170
  defaults: () => ({ type: "loop", props: {}, children: [] }),
158
171
  descriptor: {
159
172
  type: "loop",
@@ -161,6 +174,48 @@ export const loop: ElementDefinition<LoopNode> = {
161
174
  group: "dynamic",
162
175
  defaultTab: "content",
163
176
  fields: [
177
+ {
178
+ key: "collection",
179
+ kind: "text",
180
+ label: "Collection",
181
+ optional: true,
182
+ message:
183
+ "A collection's slug, such as posts or team, lists its entries on any page. Leave it empty on an Archive part to list the archive's posts.",
184
+ },
185
+ {
186
+ key: "display",
187
+ kind: "select",
188
+ label: "Show as",
189
+ optional: true,
190
+ options: DISPLAY_OPTIONS,
191
+ },
192
+ {
193
+ key: "columns",
194
+ kind: "int",
195
+ max: 6,
196
+ label: "Columns",
197
+ optional: true,
198
+ message: "1 to 6 columns for Grid and Cards (one on phones). Leave it empty for 3.",
199
+ },
200
+ {
201
+ key: "limit",
202
+ kind: "int",
203
+ max: 50,
204
+ label: "Entries to show",
205
+ optional: true,
206
+ message: "1 to 50 entries from the collection. Leave it empty for 6.",
207
+ },
208
+ {
209
+ key: "order",
210
+ kind: "select",
211
+ label: "Order",
212
+ optional: true,
213
+ options: [
214
+ { value: "newest", label: "Newest first" },
215
+ { value: "oldest", label: "Oldest first" },
216
+ { value: "title", label: "By title" },
217
+ ],
218
+ },
164
219
  {
165
220
  key: "itemPartId",
166
221
  kind: "text",
@@ -180,12 +235,33 @@ export const loop: ElementDefinition<LoopNode> = {
180
235
  },
181
236
  ],
182
237
  },
238
+ build: (node, attrs, children) => {
239
+ const display = node.props.display;
240
+ const extra = display === "grid" || display === "cards" ? ` emvb-loop-${display}` : "";
241
+ return {
242
+ tag: "div",
243
+ attrs: { ...attrs, class: `${attrs.class ?? ""}${extra}`.trim() },
244
+ children,
245
+ };
246
+ },
247
+ };
248
+
249
+ export const loopEmpty: ElementDefinition<LoopEmptyNode> = {
250
+ baseCss: ".emvb-loop-empty{display:flex;flex-direction:column;min-width:0;gap:.5rem}",
251
+ defaults: () => ({ type: "loop-empty", props: {}, children: [] }),
252
+ descriptor: {
253
+ type: "loop-empty",
254
+ name: "Empty state",
255
+ group: "dynamic",
256
+ defaultTab: "style",
257
+ fields: [],
258
+ },
183
259
  build: (_node, attrs, children) => ({ tag: "div", attrs, children }),
184
260
  };
185
261
 
186
262
  export const pagination: ElementDefinition<PaginationNode> = {
187
263
  baseCss:
188
- ".emvb-pagination{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem}.emvb-pagination a{color:inherit}.emvb-pagination a[aria-current=page]{font-weight:700;text-decoration:none}",
264
+ ".emvb-pagination{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem}.emvb-pagination a{color:inherit}.emvb-pagination a[aria-current=page]{font-weight:700;text-decoration:none}.emvb-pagination-count{opacity:.75}",
189
265
  defaults: () => ({ type: "pagination", props: {} }),
190
266
  descriptor: {
191
267
  type: "pagination",
@@ -195,6 +271,15 @@ export const pagination: ElementDefinition<PaginationNode> = {
195
271
  fields: [
196
272
  { key: "prevText", kind: "text", label: "Previous text", optional: true },
197
273
  { key: "nextText", kind: "text", label: "Next text", optional: true },
274
+ { key: "showCount", kind: "boolean", label: "Show page count", optional: true },
275
+ {
276
+ key: "countText",
277
+ kind: "text",
278
+ label: "Count text",
279
+ optional: true,
280
+ message:
281
+ '{page} and {total} are filled in. EmDash 1.2 doesn\'t report a total, so the count shows "Page N" until it does.',
282
+ },
198
283
  ],
199
284
  },
200
285
  // Rendered by core/render/pagination.ts from the archive's page data (W-222).