@perkyzz/emvb 0.2.0 → 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 (80) hide show
  1. package/README.md +2 -2
  2. package/package.json +2 -2
  3. package/src/admin/editor/A11yCopilot.tsx +126 -0
  4. package/src/admin/editor/CommandPalette.tsx +118 -0
  5. package/src/admin/editor/Editor.tsx +274 -12
  6. package/src/admin/editor/EditorOverlay.tsx +6 -0
  7. package/src/admin/editor/PerfMeter.tsx +121 -0
  8. package/src/admin/editor/ShareLink.tsx +164 -0
  9. package/src/admin/editor/Timeline.tsx +274 -0
  10. package/src/admin/editor/TopBar.tsx +4 -0
  11. package/src/admin/editor/canvas/CanvasFrame.tsx +12 -3
  12. package/src/admin/editor/canvas/SelectionOverlay.tsx +1 -1
  13. package/src/admin/editor/collection-previews.ts +91 -0
  14. package/src/admin/editor/editor-css.ts +5 -3
  15. package/src/admin/editor/feature-css.ts +105 -0
  16. package/src/admin/editor/host.ts +2 -0
  17. package/src/admin/editor/live-data.tsx +71 -0
  18. package/src/admin/editor/palette-items.ts +105 -0
  19. package/src/admin/editor/palette.ts +67 -0
  20. package/src/admin/editor/panels/AddPanel.tsx +47 -2
  21. package/src/admin/editor/panels/ClassesSection.tsx +5 -1
  22. package/src/admin/editor/panels/ElementPanel.tsx +34 -3
  23. package/src/admin/editor/panels/LayersPanel.tsx +38 -1
  24. package/src/admin/editor/panels/LeftPanel.tsx +4 -1
  25. package/src/admin/editor/panels/SettingsPanel.tsx +12 -0
  26. package/src/admin/editor/panels/SiteStylesDrawer.tsx +2 -0
  27. package/src/admin/editor/panels/TokenScales.tsx +168 -0
  28. package/src/admin/editor/panels/VariableSection.tsx +9 -4
  29. package/src/admin/editor/panels/settings/AudienceEditor.tsx +215 -0
  30. package/src/admin/editor/panels/settings/BindingsEditor.tsx +221 -0
  31. package/src/admin/editor/panels/settings/ClassChipInput.tsx +1 -1
  32. package/src/admin/editor/panels/settings/EffectsControls.tsx +4 -2
  33. package/src/admin/editor/panels/settings/MotionControl.tsx +252 -0
  34. package/src/admin/editor/panels/settings/StateSwitcher.tsx +1 -1
  35. package/src/admin/editor/panels/settings/StyleRow.tsx +12 -0
  36. package/src/admin/editor/panels/settings/StyleSources.tsx +94 -0
  37. package/src/admin/editor/panels/settings/VariableBinding.tsx +1 -1
  38. package/src/admin/editor/panels/settings/VariantEditor.tsx +83 -0
  39. package/src/admin/editor/panels/settings/length-units.ts +1 -1
  40. package/src/admin/editor/panels/settings/style-sections.ts +2 -1
  41. package/src/admin/editor/shortcuts.ts +2 -1
  42. package/src/admin/editor/useEditorShortcuts.ts +8 -0
  43. package/src/admin/editor/useNodeActions.ts +38 -15
  44. package/src/admin/ui.ts +4 -4
  45. package/src/astro/request-data.ts +97 -0
  46. package/src/astro/resolve-theme.ts +39 -9
  47. package/src/astro/resolve.ts +8 -2
  48. package/src/astro/theme-context.ts +14 -2
  49. package/src/astro/theme-posts.ts +51 -1
  50. package/src/astro/visitor.ts +142 -0
  51. package/src/constants.ts +1 -1
  52. package/src/core/a11y/audit.ts +282 -0
  53. package/src/core/arrange.ts +91 -0
  54. package/src/core/audience/rules.ts +104 -0
  55. package/src/core/audience/variants.ts +51 -0
  56. package/src/core/css/generate.ts +20 -2
  57. package/src/core/css/trace.ts +169 -0
  58. package/src/core/data/bindings.ts +257 -0
  59. package/src/core/design/tokens.ts +127 -0
  60. package/src/core/elements/dynamic-elements.ts +87 -2
  61. package/src/core/elements/index.ts +2 -0
  62. package/src/core/history/diff.ts +152 -0
  63. package/src/core/index.ts +111 -0
  64. package/src/core/migrate/index.ts +4 -1
  65. package/src/core/nesting.ts +1 -0
  66. package/src/core/perf/meter.ts +160 -0
  67. package/src/core/perf/scripts.ts +58 -0
  68. package/src/core/recipes/index.ts +433 -0
  69. package/src/core/render/index.ts +51 -4
  70. package/src/core/render/loop.ts +54 -7
  71. package/src/core/render/pagination.ts +9 -1
  72. package/src/core/sanitize/css.ts +39 -3
  73. package/src/core/sanitize/motion.ts +129 -0
  74. package/src/core/schema/design.ts +25 -2
  75. package/src/core/schema/layout.ts +168 -18
  76. package/src/core/schema/motion.ts +14 -0
  77. package/src/core/schema/style.ts +48 -3
  78. package/src/core/share/link.ts +147 -0
  79. package/src/core/theme/dynamic.ts +49 -0
  80. package/src/core/theme/pagination.ts +56 -0
@@ -0,0 +1,91 @@
1
+ import * as React from "react";
2
+ import {
3
+ collectCollectionLoops,
4
+ type CollectionLoop,
5
+ type Layout,
6
+ type ThemePostFields,
7
+ } from "../../core/index.ts";
8
+ import { requestJson, type Fetcher } from "../api.ts";
9
+
10
+ type ContentItem = { id: string; slug?: string | null; data?: Record<string, unknown> };
11
+
12
+ const text = (value: unknown): string => (typeof value === "string" ? value : "");
13
+
14
+ /** A content API item as Loop fields; the host's mapping covers images and plain fields. */
15
+ function previewPost(item: ContentItem, collection: string): ThemePostFields {
16
+ const data = item.data ?? {};
17
+ const slug = item.slug || text(data["slug"]);
18
+ const image = data["featured_image"] ?? data["image"];
19
+ const src =
20
+ typeof image === "string"
21
+ ? image
22
+ : image && typeof image === "object" && "src" in image
23
+ ? text((image as { src?: unknown }).src)
24
+ : "";
25
+ const fields: Record<string, string> = {};
26
+ for (const [key, value] of Object.entries(data).slice(0, 100)) {
27
+ if (typeof value === "string" && value.length <= 2000) fields[key] = value;
28
+ }
29
+ return {
30
+ id: item.id,
31
+ slug: slug || item.id,
32
+ title: text(data["title"]) || text(data["name"]),
33
+ excerpt: text(data["excerpt"]),
34
+ content: "",
35
+ permalink: `/${collection}/${slug || item.id}`,
36
+ ...(src ? { featuredImageUrl: src, featuredImageAlt: text(data["title"]) } : {}),
37
+ fields,
38
+ };
39
+ }
40
+
41
+ const ORDER: Record<string, string> = {
42
+ newest: "orderBy=createdAt&order=desc",
43
+ oldest: "orderBy=createdAt&order=asc",
44
+ title: "orderBy=title&order=asc",
45
+ };
46
+
47
+ /**
48
+ * Real entries for collection Loops on the canvas (W-308), read through the content API. A
49
+ * collection the role can't read, or that doesn't exist, keeps the sample entries.
50
+ */
51
+ export function useCollectionPreviews(
52
+ layout: Layout | null,
53
+ fetcher: Fetcher,
54
+ ): Record<string, ThemePostFields[]> {
55
+ const loops = layout ? collectCollectionLoops(layout) : [];
56
+ const key = loops.length > 0 ? JSON.stringify(loops) : "";
57
+ const [entries, setEntries] = React.useState<Record<string, ThemePostFields[]>>({});
58
+ React.useEffect(() => {
59
+ if (!key) {
60
+ setEntries({});
61
+ return;
62
+ }
63
+ let cancelled = false;
64
+ const wanted = JSON.parse(key) as CollectionLoop[];
65
+ void Promise.all(
66
+ wanted.map(async (loop) => {
67
+ try {
68
+ const body = await requestJson<{
69
+ items?: { id: string; slug?: string | null; data?: Record<string, unknown> }[];
70
+ }>(
71
+ fetcher,
72
+ `/_emdash/api/content/${loop.collection}?limit=${loop.limit}&${ORDER[loop.order] ?? ORDER["newest"]}`,
73
+ );
74
+ const items = (body?.items ?? []).map((item) => previewPost(item, loop.collection));
75
+ return [loop.nodeId, items] as const;
76
+ } catch {
77
+ return undefined;
78
+ }
79
+ }),
80
+ ).then((results) => {
81
+ if (cancelled) return;
82
+ const next: Record<string, ThemePostFields[]> = {};
83
+ for (const result of results) if (result) next[result[0]] = result[1];
84
+ setEntries(next);
85
+ });
86
+ return () => {
87
+ cancelled = true;
88
+ };
89
+ }, [key, fetcher]);
90
+ return entries;
91
+ }
@@ -1,11 +1,12 @@
1
1
  /**
2
- * Editor chrome styles. The admin's Tailwind build is precompiled, so EmVB ships its
2
+ * Editor chrome styles (DESIGN.md). The admin's Tailwind build is precompiled, so EmVB ships its
3
3
  * own rules, scoped to the editor root and built only from Kumo variables. Panels keep their
4
4
  * 1 px borders inside their width, so the canvas gets exactly the space between them (D-025).
5
5
  * Density is compact (28 px controls, 44 px top bar, 256/288 panels) with near-opaque
6
6
  * elevated cards (hairline rings, soft lift shadows, light blur); the canvas stage stays clear.
7
7
  */
8
8
  import { UI_CSS } from "../ui.ts";
9
+ import { FEATURE_CSS } from "./feature-css.ts";
9
10
 
10
11
  export const EDITOR_CSS = `${UI_CSS}
11
12
  [data-emvb-editor] {
@@ -339,7 +340,7 @@ export const EDITOR_CSS = `${UI_CSS}
339
340
  }
340
341
  .emvb-unit-btn:hover, .emvb-unit-btn[data-popup-open] { background: var(--color-kumo-tint); color: var(--text-color-kumo-default); }
341
342
  .emvb-unit-btn:focus-visible { outline: 2px solid var(--color-kumo-brand); outline-offset: -2px; }
342
- /* Variable button and bound-variable chip (W-087) */
343
+ /* Variable button and bound-variable chip (W-087, DESIGN.md "variable chip") */
343
344
  .emvb-var-btn {
344
345
  display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto;
345
346
  width: 28px; height: 28px; margin-top: 28px; padding: 0; border: 0; border-radius: 6px;
@@ -431,7 +432,7 @@ export const EDITOR_CSS = `${UI_CSS}
431
432
  .emvb-icon-current-text strong { font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
432
433
  .emvb-icon-current-text span { color: var(--text-color-kumo-subtle); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
433
434
 
434
- /* Class chip input (W-087): one 28 px box holding the chips and the text input */
435
+ /* Class chip input (W-087, DESIGN.md): one 28 px box holding the chips and the text input */
435
436
  .emvb-class-field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 8px; }
436
437
  .emvb-chip-anchor { position: relative; }
437
438
  .emvb-chip-box {
@@ -622,4 +623,5 @@ export const EDITOR_CSS = `${UI_CSS}
622
623
  background: var(--color-kumo-elevated);
623
624
  }
624
625
  }
626
+ ${FEATURE_CSS}
625
627
  `;
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Editor styles for the W-307 feature batch (bindings, palette, meters, timeline…), kept apart
3
+ * from the core chrome in editor-css.ts. Kumo variables only.
4
+ */
5
+ export const FEATURE_CSS = `
6
+ .emvb-native-select, .emvb-native-input {
7
+ height: var(--emvb-control, 28px);
8
+ min-width: 0;
9
+ padding: 0 8px;
10
+ border: 1px solid var(--color-kumo-line);
11
+ border-radius: 6px;
12
+ background: var(--color-kumo-base);
13
+ color: var(--text-color-kumo-default);
14
+ font: inherit;
15
+ }
16
+ .emvb-native-select:focus-visible, .emvb-native-input:focus-visible {
17
+ outline: 2px solid var(--color-kumo-brand);
18
+ outline-offset: 1px;
19
+ }
20
+ .emvb-bind { display: grid; gap: 8px; padding-top: 8px; border-top: 1px solid var(--color-kumo-hairline); }
21
+ .emvb-bind-title { margin: 0; font-size: 12px; font-weight: 600; }
22
+ .emvb-bind-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 6px; align-items: center; }
23
+ .emvb-bind-row > .emvb-bind-label { grid-column: 1 / -1; font-size: 12px; color: var(--text-color-kumo-subtle); }
24
+ .emvb-bind-live { grid-column: 1 / -1; margin: 0; font-size: 12px; color: var(--text-color-kumo-default); overflow-wrap: anywhere; }
25
+ .emvb-bind-live > b { font-weight: 600; }
26
+ .emvb-bind-outside { grid-column: 1 / -1; display: grid; gap: 4px; }
27
+ .emvb-bind-outside > label { display: flex; gap: 6px; align-items: center; font-size: 12px; }
28
+ .emvb-bind-warning { margin: 0; padding: 6px 8px; border-radius: 6px; font-size: 12px; background: var(--color-kumo-warning-tint, #fef3c7); color: var(--text-color-kumo-default); }
29
+ .emvb-js-badge { margin-left: auto; padding: 0 4px; border-radius: 4px; font-size: 10px; font-weight: 700; line-height: 16px; background: var(--color-kumo-warning-tint, #fef3c7); color: var(--text-color-kumo-default); }
30
+ .emvb-element-tile { position: relative; }
31
+ .emvb-element-tile > .emvb-js-badge { position: absolute; top: 4px; right: 4px; }
32
+ .emvb-perf-bars { display: grid; gap: 8px; margin: 12px 0; padding: 0; list-style: none; }
33
+ .emvb-perf-bars > li { display: grid; grid-template-columns: 90px 1fr auto; gap: 8px; align-items: center; font-size: 13px; }
34
+ .emvb-perf-bar { display: block; height: 8px; border-radius: 4px; background: var(--color-kumo-tint); overflow: hidden; }
35
+ .emvb-perf-bar > span { display: block; height: 100%; background: var(--color-kumo-brand); }
36
+ .emvb-perf-bars > li[data-over] .emvb-perf-bar > span { background: var(--color-kumo-danger, #dc2626); }
37
+ .emvb-perf-value { font-variant-numeric: tabular-nums; color: var(--text-color-kumo-subtle); }
38
+ .emvb-perf-warnings { margin: 8px 0; padding-left: 18px; font-size: 13px; }
39
+ .emvb-perf-heading { margin: 12px 0 4px; font-size: 13px; font-weight: 600; }
40
+ .emvb-perf-sections { margin: 0 0 8px; padding-left: 18px; font-size: 13px; }
41
+ .emvb-topbar-meter { font-variant-numeric: tabular-nums; font-size: 12px; }
42
+ .emvb-js-badge + .emvb-ab-badge { margin-left: 2px; }
43
+ .emvb-ab-badge { background: var(--color-kumo-info-tint, #dbeafe); }
44
+ .emvb-aud-checks { display: flex; flex-wrap: wrap; gap: 4px 10px; margin: 0; padding: 0; border: 0; font-size: 12px; }
45
+ .emvb-aud-checks > legend { width: 100%; padding: 0; margin-bottom: 2px; }
46
+ .emvb-palette { padding: 0; overflow: hidden; }
47
+ .emvb-palette-input { width: 100%; height: 44px; padding: 0 16px; border: 0; border-bottom: 1px solid var(--color-kumo-line); background: transparent; color: var(--text-color-kumo-default); font: inherit; font-size: 15px; outline: none; }
48
+ .emvb-palette-list { max-height: min(60vh, 420px); overflow-y: auto; margin: 0; padding: 4px; list-style: none; }
49
+ .emvb-palette-group { padding: 8px 10px 2px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; color: var(--text-color-kumo-subtle); }
50
+ .emvb-palette-item { display: flex; justify-content: space-between; gap: 12px; padding: 6px 10px; border-radius: 6px; cursor: pointer; font-size: 13px; }
51
+ .emvb-palette-item[aria-selected="true"] { background: var(--color-kumo-tint); }
52
+ .emvb-palette-hint { color: var(--text-color-kumo-subtle); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 50%; }
53
+ .emvb-palette-empty { padding: 12px; color: var(--text-color-kumo-subtle); font-size: 13px; }
54
+ .emvb-palette-tips { margin: 0; padding: 6px 12px; border-top: 1px solid var(--color-kumo-line); font-size: 11px; color: var(--text-color-kumo-subtle); }
55
+ .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
56
+ .emvb-timeline-body { display: grid; grid-template-columns: 200px 1fr; gap: 16px; margin: 12px 0; min-height: 0; }
57
+ .emvb-timeline-list { margin: 0; padding: 0; list-style: none; max-height: 60vh; overflow-y: auto; }
58
+ .emvb-timeline-version { width: 100%; padding: 6px 8px; border: 0; border-radius: 6px; background: transparent; color: inherit; font: inherit; font-size: 12px; text-align: start; cursor: pointer; }
59
+ .emvb-timeline-version[aria-current="true"] { background: var(--color-kumo-tint); font-weight: 600; }
60
+ .emvb-timeline-frames { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
61
+ .emvb-timeline-frames figure { margin: 0; }
62
+ .emvb-timeline-frames figcaption { font-size: 12px; color: var(--text-color-kumo-subtle); margin-bottom: 4px; }
63
+ .emvb-timeline-frame { width: 100%; height: 260px; border: 1px solid var(--color-kumo-line); border-radius: 6px; background: #fff; }
64
+ .emvb-timeline-changes { margin: 8px 0; padding: 0; list-style: none; font-size: 13px; display: grid; gap: 4px; }
65
+ .emvb-timeline-changes > li { display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; }
66
+ .emvb-timeline-kind { font-weight: 600; }
67
+ .emvb-timeline-changes > li[data-kind="added"] .emvb-timeline-kind { color: #15803d; }
68
+ .emvb-timeline-changes > li[data-kind="removed"] .emvb-timeline-kind { color: #b91c1c; }
69
+ .emvb-timeline-changes > li[data-kind="changed"] .emvb-timeline-kind { color: #b45309; }
70
+ .emvb-tokens-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; align-items: end; }
71
+ .emvb-tokens-grid > label { display: grid; gap: 4px; min-width: 0; }
72
+ .emvb-tokens-fluid { display: flex !important; align-items: center; gap: 4px; font-size: 12px; }
73
+ .emvb-tokens-preview { margin: 8px 0; padding: 0; list-style: none; display: grid; gap: 4px; font-size: 12px; }
74
+ .emvb-tokens-preview > li { display: grid; grid-template-columns: 48px 1fr auto; gap: 8px; align-items: center; }
75
+ .emvb-tokens-sample { display: inline-block; height: 1em; line-height: 1; }
76
+ .emvb-tokens-preview .emvb-tokens-sample:empty { height: 8px; border-radius: 2px; background: var(--color-kumo-brand); }
77
+ .emvb-tokens-preview code { font-size: 11px; color: var(--text-color-kumo-subtle); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 180px; }
78
+ .emvb-a11y-score { height: 28px; padding: 0 8px; border: 1px solid var(--color-kumo-line); border-radius: 999px; background: transparent; color: var(--text-color-kumo-default); font: inherit; font-size: 12px; cursor: pointer; white-space: nowrap; }
79
+ .emvb-a11y-score[data-band="good"] b, .emvb-a11y [data-band="good"] { color: #15803d; }
80
+ .emvb-a11y-score[data-band="fair"] b, .emvb-a11y [data-band="fair"] { color: #b45309; }
81
+ .emvb-a11y-score[data-band="poor"] b, .emvb-a11y [data-band="poor"] { color: #b91c1c; }
82
+ .emvb-a11y-score:focus-visible { outline: 2px solid var(--color-kumo-brand); outline-offset: 1px; }
83
+ .emvb-a11y-issues { margin: 12px 0; padding: 0; list-style: none; display: grid; gap: 8px; max-height: 50vh; overflow-y: auto; }
84
+ .emvb-a11y-issues > li { display: flex; gap: 8px; align-items: flex-start; justify-content: space-between; font-size: 13px; padding-left: 8px; border-left: 3px solid #d97706; }
85
+ .emvb-a11y-issues > li[data-severity="error"] { border-left-color: #dc2626; }
86
+ .emvb-a11y-actions { display: flex; gap: 8px; justify-content: flex-end; }
87
+ .emvb-sources { margin: 4px 0 8px; font-size: 12px; }
88
+ .emvb-sources > summary { cursor: pointer; display: flex; justify-content: space-between; gap: 8px; font-weight: 600; }
89
+ .emvb-sources-count { font-weight: 400; color: var(--text-color-kumo-subtle); }
90
+ .emvb-sources ul { margin: 6px 0 0; padding: 0; list-style: none; display: grid; gap: 6px; }
91
+ .emvb-sources li { display: grid; grid-template-columns: 1fr auto; gap: 0 8px; padding-left: 6px; border-left: 2px solid var(--color-kumo-line); }
92
+ .emvb-sources li[data-kind="class"] { border-left-color: #7c3aed; }
93
+ .emvb-sources li[data-kind="default"] { border-left-color: #0d9488; }
94
+ .emvb-sources li[data-kind="local"] { border-left-color: var(--color-kumo-brand); }
95
+ .emvb-sources-value { font-family: ui-monospace, monospace; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 120px; }
96
+ .emvb-sources-from, .emvb-sources-over { grid-column: 1 / -1; color: var(--text-color-kumo-subtle); }
97
+ .emvb-sources-over { text-decoration: line-through; text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); }
98
+ .emvb-recipe-list { display: grid; gap: 6px; }
99
+ .emvb-recipe-tile { display: grid; gap: 2px; text-align: start; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--color-kumo-line); background: var(--color-kumo-base, transparent); cursor: pointer; font: inherit; color: inherit; }
100
+ .emvb-recipe-tile:hover, .emvb-recipe-tile:focus-visible { border-color: var(--color-kumo-brand); }
101
+ .emvb-recipe-name { font-weight: 600; font-size: 13px; }
102
+ .emvb-recipe-desc { font-size: 12px; color: var(--text-color-kumo-subtle); }
103
+ .emvb-motion-effect { display: grid; grid-template-columns: 1fr 1fr auto; gap: 6px; align-items: end; }
104
+ .emvb-motion-name { grid-column: 1 / -1; font-size: 12px; font-weight: 600; }
105
+ `;
@@ -15,6 +15,8 @@ export type EditorHost = {
15
15
  * admin (the playground) sets false, so those links don't lead nowhere (W-289). Default true.
16
16
  */
17
17
  adminLinks?: boolean;
18
+ /** Where shared page links open (W-321). Default emvb.dev/playground. */
19
+ playgroundUrl?: string;
18
20
  };
19
21
 
20
22
  const defaultEditorHost: EditorHost = {
@@ -0,0 +1,71 @@
1
+ import * as React from "react";
2
+ import { siteBindingValues } from "../../core/index.ts";
3
+ import { readEnvelope, type Fetcher } from "../api.ts";
4
+
5
+ /**
6
+ * Live values for bound fields on the canvas (W-307): the site's settings, read once, and the
7
+ * URL parameters the editor previews with (`?plan=pro`), which only exist in the editor.
8
+ */
9
+ type LiveData = {
10
+ site: Readonly<Record<string, string>>;
11
+ params: Readonly<Record<string, string>>;
12
+ /** The preview query as typed, e.g. `plan=pro&utm_source=mail`. */
13
+ query: string;
14
+ setQuery: (query: string) => void;
15
+ };
16
+
17
+ const EMPTY: LiveData = { site: {}, params: {}, query: "", setQuery: () => undefined };
18
+
19
+ export const LiveDataContext = React.createContext<LiveData>(EMPTY);
20
+
21
+ export const useLiveData = () => React.useContext(LiveDataContext);
22
+
23
+ /**
24
+ * The site's origin while editing (W-307): the EmDash admin runs on the site itself, so a
25
+ * URL-parameter link to this origin counts as same-site on the canvas too.
26
+ */
27
+ export const siteOrigin = (): string | undefined => globalThis.location?.origin || undefined;
28
+
29
+ /** `a=1&b=two` (a leading `?` is fine) as a record, first value per name. */
30
+ function previewParams(query: string): Record<string, string> {
31
+ const params: Record<string, string> = {};
32
+ const search = new URLSearchParams(query.trim().replace(/^\?/, ""));
33
+ for (const [name, value] of search) if (!Object.hasOwn(params, name)) params[name] = value;
34
+ return params;
35
+ }
36
+
37
+ /** The site's settings as binding values; empty when the role can't read them. */
38
+ function useSiteSettings(fetcher: Fetcher): Record<string, string> {
39
+ const [site, setSite] = React.useState<Record<string, string>>({});
40
+ React.useEffect(() => {
41
+ let cancelled = false;
42
+ fetcher("/_emdash/api/settings")
43
+ .then(async (response) => {
44
+ if (!response.ok) return;
45
+ const body = await readEnvelope<unknown>(response);
46
+ if (!cancelled) setSite(siteBindingValues(body.data));
47
+ })
48
+ .catch(() => undefined);
49
+ return () => {
50
+ cancelled = true;
51
+ };
52
+ }, [fetcher]);
53
+ return site;
54
+ }
55
+
56
+ /** Provides live data to the editor. */
57
+ export function LiveDataProvider({
58
+ fetcher,
59
+ children,
60
+ }: {
61
+ fetcher: Fetcher;
62
+ children: React.ReactNode;
63
+ }) {
64
+ const site = useSiteSettings(fetcher);
65
+ const [query, setQuery] = React.useState("");
66
+ const value = React.useMemo(
67
+ () => ({ site, params: previewParams(query), query, setQuery }),
68
+ [site, query],
69
+ );
70
+ return <LiveDataContext.Provider value={value}>{children}</LiveDataContext.Provider>;
71
+ }
@@ -0,0 +1,105 @@
1
+ import {
2
+ ELEMENT_DESCRIPTORS,
3
+ SECTION_RECIPES,
4
+ type DesignSystem,
5
+ type ElementType,
6
+ type Layout,
7
+ type LayoutNode,
8
+ } from "../../core/index.ts";
9
+ import { ELEMENT_NAMES } from "./panels/ElementPanel.tsx";
10
+ import type { PaletteItem } from "./palette.ts";
11
+
12
+ export type PaletteActions = {
13
+ layout: Layout | null;
14
+ design: DesignSystem;
15
+ selected: LayoutNode | null;
16
+ formsAvailable: boolean;
17
+ insert: (type: ElementType) => void;
18
+ /** Adds a section recipe (W-320). */
19
+ insertRecipe?: (id: string) => void;
20
+ select: (id: string) => void;
21
+ applyClass: (nodeId: string, classId: string) => void;
22
+ actions: { id: string; label: string; hint?: string; keywords?: string; run: () => void }[];
23
+ };
24
+
25
+ const MAX_LAYERS = 400;
26
+
27
+ function textOf(node: LayoutNode): string {
28
+ const props = node.props as Record<string, unknown>;
29
+ for (const key of ["text", "label", "title", "alt", "name"]) {
30
+ const value = props[key];
31
+ if (typeof value === "string" && value.trim()) return value.trim().slice(0, 40);
32
+ }
33
+ return "";
34
+ }
35
+
36
+ /** Every palette command for the editor's current state (W-314). */
37
+ export function paletteItems(ctx: PaletteActions): PaletteItem[] {
38
+ const items: PaletteItem[] = ctx.actions.map((action) => ({
39
+ id: `action:${action.id}`,
40
+ group: "Actions",
41
+ label: action.label,
42
+ ...(action.hint ? { hint: action.hint } : {}),
43
+ ...(action.keywords ? { keywords: action.keywords } : {}),
44
+ run: action.run,
45
+ }));
46
+ for (const descriptor of ELEMENT_DESCRIPTORS) {
47
+ if (descriptor.type === "form" && !ctx.formsAvailable) continue;
48
+ items.push({
49
+ id: `insert:${descriptor.type}`,
50
+ group: "Insert",
51
+ label: `Insert ${descriptor.name}`,
52
+ keywords: `${descriptor.type} ${descriptor.group}`,
53
+ run: () => ctx.insert(descriptor.type as ElementType),
54
+ });
55
+ }
56
+ const insertRecipe = ctx.insertRecipe;
57
+ if (insertRecipe && ctx.layout) {
58
+ for (const recipe of SECTION_RECIPES) {
59
+ items.push({
60
+ id: `recipe:${recipe.id}`,
61
+ group: "Insert",
62
+ label: `Insert ${recipe.name} section`,
63
+ hint: "Recipe",
64
+ keywords: `recipe section block template ${recipe.description}`,
65
+ run: () => insertRecipe(recipe.id),
66
+ });
67
+ }
68
+ }
69
+ if (ctx.layout) {
70
+ let count = 0;
71
+ const walk = (node: LayoutNode, depth: number): void => {
72
+ if (count >= MAX_LAYERS) return;
73
+ count += 1;
74
+ const name = node.label || ELEMENT_NAMES[node.type] || node.type;
75
+ const text = textOf(node);
76
+ items.push({
77
+ id: `layer:${node.id}`,
78
+ group: "Jump to",
79
+ label: depth === 0 ? "Page (root)" : name,
80
+ ...(text ? { hint: `“${text}”` } : {}),
81
+ keywords: `${node.type} ${text}`,
82
+ run: () => ctx.select(node.id),
83
+ });
84
+ if ("children" in node && Array.isArray(node.children)) {
85
+ for (const child of node.children as LayoutNode[]) walk(child, depth + 1);
86
+ }
87
+ };
88
+ walk(ctx.layout.root, 0);
89
+ }
90
+ const selected = ctx.selected;
91
+ if (selected) {
92
+ for (const cls of ctx.design.classes ?? []) {
93
+ if (selected.classes?.includes(cls.id)) continue;
94
+ items.push({
95
+ id: `class:${cls.id}`,
96
+ group: "Apply class",
97
+ label: `Apply .${cls.name}`,
98
+ hint: `to ${selected.label || ELEMENT_NAMES[selected.type] || selected.type}`,
99
+ keywords: cls.id,
100
+ run: () => ctx.applyClass(selected.id, cls.id),
101
+ });
102
+ }
103
+ }
104
+ return items;
105
+ }
@@ -0,0 +1,67 @@
1
+ /** One command in the Ctrl/Cmd+K palette (W-314). */
2
+ export type PaletteItem = {
3
+ id: string;
4
+ group: PaletteGroup;
5
+ label: string;
6
+ /** Shown to the right: a shortcut, an element type, a text preview. */
7
+ hint?: string;
8
+ /** Extra words that should find this item. */
9
+ keywords?: string;
10
+ run: () => void;
11
+ };
12
+
13
+ const PALETTE_GROUPS = ["Actions", "Insert", "Jump to", "Apply class"] as const;
14
+ export type PaletteGroup = (typeof PALETTE_GROUPS)[number];
15
+
16
+ /** Prefixes that narrow the palette to one group, like `>` for actions in code editors. */
17
+ const PREFIXES: Record<string, PaletteGroup> = {
18
+ ">": "Actions",
19
+ "+": "Insert",
20
+ "@": "Jump to",
21
+ ".": "Apply class",
22
+ };
23
+
24
+ /**
25
+ * How well `query` matches `text` (W-314): null when its letters don't all appear in order.
26
+ * Higher is better: a prefix beats a word start, which beats a scattered match.
27
+ */
28
+ export function fuzzyScore(query: string, text: string): number | null {
29
+ const q = query.trim().toLowerCase();
30
+ const t = text.toLowerCase();
31
+ if (!q) return 0;
32
+ if (t.startsWith(q)) return 1000 - t.length;
33
+ const at = t.indexOf(q);
34
+ if (at >= 0) return (/[\s\-_/.]/.test(t[at - 1] ?? " ") ? 800 : 600) - at - t.length / 100;
35
+ let score = 0;
36
+ let from = 0;
37
+ let previous = -2;
38
+ for (const ch of q) {
39
+ if (ch === " ") continue;
40
+ const found = t.indexOf(ch, from);
41
+ if (found < 0) return null;
42
+ score += found === previous + 1 ? 6 : /[\s\-_/.]/.test(t[found - 1] ?? " ") ? 4 : 1;
43
+ previous = found;
44
+ from = found + 1;
45
+ }
46
+ return score - t.length / 100;
47
+ }
48
+
49
+ /**
50
+ * The items for a query, best first, at most `limit` (W-314). An empty query lists every group
51
+ * in order; a leading `>`, `+`, `@` or `.` narrows to Actions, Insert, Jump to or Apply class.
52
+ */
53
+ export function filterPalette(items: PaletteItem[], raw: string, limit = 60): PaletteItem[] {
54
+ const prefix = PREFIXES[raw.trimStart()[0] ?? ""];
55
+ const query = prefix ? raw.trimStart().slice(1) : raw;
56
+ const pool = prefix ? items.filter((item) => item.group === prefix) : items;
57
+ if (!query.trim()) return pool.slice(0, limit);
58
+ const scored: { item: PaletteItem; score: number }[] = [];
59
+ for (const item of pool) {
60
+ const label = fuzzyScore(query, item.label);
61
+ const extra = item.keywords ? fuzzyScore(query, item.keywords) : null;
62
+ const best = Math.max(label ?? -Infinity, extra === null ? -Infinity : extra - 50);
63
+ if (best > -Infinity) scored.push({ item, score: best });
64
+ }
65
+ scored.sort((a, b) => b.score - a.score);
66
+ return scored.slice(0, limit).map((s) => s.item);
67
+ }
@@ -26,7 +26,12 @@ import {
26
26
  RowsIcon,
27
27
  } from "@phosphor-icons/react";
28
28
  import * as React from "react";
29
- import { ELEMENT_DESCRIPTORS, type ElementType } from "../../../core/index.ts";
29
+ import {
30
+ ELEMENT_DESCRIPTORS,
31
+ SECTION_RECIPES,
32
+ typeMayAddScript,
33
+ type ElementType,
34
+ } from "../../../core/index.ts";
30
35
  import { NEW_ELEMENT_MIME } from "../dnd/drop-target.ts";
31
36
  import { FIELD } from "../../ui.ts";
32
37
  import { dragStash } from "../dnd/drag-stash.ts";
@@ -67,6 +72,7 @@ const ICONS: Record<string, typeof TextHIcon> = {
67
72
  "post-date": TextTIcon,
68
73
  "post-author": TextTIcon,
69
74
  loop: ListBulletsIcon,
75
+ "loop-empty": SquareIcon,
70
76
  pagination: ArrowsLeftRightIcon,
71
77
  };
72
78
 
@@ -79,10 +85,13 @@ const GROUPS = [
79
85
 
80
86
  export function AddPanel({
81
87
  onAdd,
88
+ onRecipe,
82
89
  defaultQuery = "",
83
90
  formsAvailable = true,
84
91
  }: {
85
92
  onAdd: (type: ElementType) => void;
93
+ /** Adds a section recipe (W-320); without it, recipes are not offered. */
94
+ onRecipe?: (id: string) => void;
86
95
  /** Test-only initial search string. */
87
96
  defaultQuery?: string;
88
97
  /** Hide the Form group when the forms plugin is missing (W-036). */
@@ -96,6 +105,11 @@ export function AddPanel({
96
105
  (formsAvailable || d.group !== "form") &&
97
106
  (!q || d.name.toLowerCase().includes(q)),
98
107
  );
108
+ const recipes = onRecipe
109
+ ? SECTION_RECIPES.filter(
110
+ (r) => !q || `${r.name} ${r.description} recipe section`.toLowerCase().includes(q),
111
+ )
112
+ : [];
99
113
  return (
100
114
  <div className="emvb-panel-body" data-emvb-panel="add">
101
115
  <Input
@@ -105,7 +119,7 @@ export function AddPanel({
105
119
  onChange={(event) => setQuery(event.target.value)}
106
120
  placeholder="Search elements"
107
121
  />
108
- {matched.length === 0 ? (
122
+ {matched.length === 0 && recipes.length === 0 ? (
109
123
  <p className="emvb-helper">No elements match &quot;{query.trim()}&quot;.</p>
110
124
  ) : (
111
125
  GROUPS.map((group) => {
@@ -133,6 +147,15 @@ export function AddPanel({
133
147
  >
134
148
  <Icon size={20} aria-hidden="true" />
135
149
  <span>{tile.name}</span>
150
+ {typeMayAddScript(tile.type) && (
151
+ <span
152
+ className="emvb-js-badge"
153
+ title="Adds a small script to the page; everything else is zero-JS"
154
+ aria-hidden="true"
155
+ >
156
+ JS
157
+ </span>
158
+ )}
136
159
  </button>
137
160
  );
138
161
  })}
@@ -141,6 +164,28 @@ export function AddPanel({
141
164
  );
142
165
  })
143
166
  )}
167
+ {onRecipe && recipes.length > 0 && (
168
+ <div className="emvb-add-group" data-emvb-recipes="">
169
+ <h3 className="emvb-add-group-title">Section recipes</h3>
170
+ <p className="emvb-helper">
171
+ Whole sections that use your Site styles colours, sizes and classes.
172
+ </p>
173
+ <div className="emvb-recipe-list" aria-label="Section recipes">
174
+ {recipes.map((recipe) => (
175
+ <button
176
+ key={recipe.id}
177
+ type="button"
178
+ className="emvb-recipe-tile"
179
+ data-emvb-recipe={recipe.id}
180
+ onClick={() => onRecipe(recipe.id)}
181
+ >
182
+ <span className="emvb-recipe-name">{recipe.name}</span>
183
+ <span className="emvb-recipe-desc">{recipe.description}</span>
184
+ </button>
185
+ ))}
186
+ </div>
187
+ </div>
188
+ )}
144
189
  </div>
145
190
  );
146
191
  }
@@ -70,7 +70,11 @@ function classKeys(
70
70
  state === "normal"
71
71
  ? withFit
72
72
  : withFit.filter(
73
- (key) => key !== "transition" && key !== "entrance" && key !== "iconAnimation",
73
+ (key) =>
74
+ key !== "transition" &&
75
+ key !== "entrance" &&
76
+ key !== "iconAnimation" &&
77
+ key !== "scrollMotion",
74
78
  )
75
79
  ) as StyleKey[];
76
80
  }