@perkyzz/emvb 1.4.0 → 1.4.1

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 (52) hide show
  1. package/package.json +2 -2
  2. package/src/admin/content-item.ts +3 -0
  3. package/src/admin/copy-rich-text.ts +99 -9
  4. package/src/admin/editor/Editor.tsx +7 -2
  5. package/src/admin/editor/collection-previews.ts +7 -8
  6. package/src/admin/editor/extensions/ExtensionPanels.tsx +33 -1
  7. package/src/admin/editor/extensions-context.tsx +16 -1
  8. package/src/admin/editor/feature-css.ts +5 -0
  9. package/src/admin/editor/panels/ConditionsEditor.tsx +18 -0
  10. package/src/admin/editor/panels/ElementPanel.tsx +2 -2
  11. package/src/admin/editor/panels/settings/FieldControl.tsx +15 -0
  12. package/src/admin/editor/panels/settings/FormBindControl.tsx +27 -31
  13. package/src/admin/editor/panels/settings/ImageFieldControl.tsx +106 -0
  14. package/src/admin/editor/panels/settings/loop-context.ts +34 -3
  15. package/src/admin/export-api.ts +2 -0
  16. package/src/admin/extension-outputs.ts +57 -0
  17. package/src/admin/import-forms.ts +133 -0
  18. package/src/admin/pages/ImportElementorDialog.tsx +32 -0
  19. package/src/admin/pages/ImportForms.tsx +71 -0
  20. package/src/admin/setup/plan.ts +2 -0
  21. package/src/admin/ui.ts +7 -0
  22. package/src/admin/widgets/ConvertToRichText.tsx +3 -2
  23. package/src/astro/render.ts +6 -0
  24. package/src/astro/resolve.ts +2 -0
  25. package/src/astro/theme-posts.ts +17 -23
  26. package/src/astro/visitor.ts +14 -5
  27. package/src/constants.ts +1 -1
  28. package/src/core/css/generate.ts +6 -1
  29. package/src/core/css/trace.ts +8 -0
  30. package/src/core/data/bindings.ts +7 -4
  31. package/src/core/elements/dynamic-elements.ts +1 -1
  32. package/src/core/elements/element-nouns.ts +48 -0
  33. package/src/core/export/site.ts +3 -0
  34. package/src/core/extensions/index.ts +2 -0
  35. package/src/core/extensions/placeholder.ts +7 -2
  36. package/src/core/extensions/render-ext.ts +49 -15
  37. package/src/core/import/elementor/context.ts +29 -0
  38. package/src/core/import/elementor/index.ts +23 -2
  39. package/src/core/import/elementor/widgets.ts +137 -17
  40. package/src/core/index.ts +9 -0
  41. package/src/core/render/index.ts +15 -2
  42. package/src/core/schema/layout.ts +4 -1
  43. package/src/core/theme/media-value.ts +88 -0
  44. package/src/core/visitor-cookie.ts +91 -0
  45. package/src/index.ts +28 -1
  46. package/src/mcp/agent-defaults.ts +40 -0
  47. package/src/mcp/extensions.ts +138 -0
  48. package/src/mcp/read.ts +55 -19
  49. package/src/mcp/tools.ts +3 -3
  50. package/src/mcp/write.ts +83 -8
  51. package/src/server/extension-routes.ts +37 -0
  52. package/src/server/plugin.ts +7 -1
@@ -1,5 +1,6 @@
1
- import type { LayoutNode } from "../../../../core/index.ts";
1
+ import type { Layout, LayoutNode } from "../../../../core/index.ts";
2
2
  import type { ThemePartType } from "../../../../core/theme/part-types.ts";
3
+ import { someNode } from "../../../../core/tree-ops.ts";
3
4
 
4
5
  /**
5
6
  * Parts where a Loop can get posts: archive templates, and synced sections (which an archive
@@ -7,17 +8,47 @@ import type { ThemePartType } from "../../../../core/theme/part-types.ts";
7
8
  */
8
9
  const LOOP_PARTS: ReadonlySet<ThemePartType> = new Set(["archive", "section"]);
9
10
 
11
+ /** A Loop that lists a collection of its own (W-308) rather than the archive's posts. */
12
+ const collectionOf = (node: LayoutNode): string | undefined => {
13
+ const collection = node.type === "loop" ? node.props.collection : undefined;
14
+ return typeof collection === "string" && collection ? collection : undefined;
15
+ };
16
+
17
+ /**
18
+ * W-1090 (#31): an archive's Pagination pages through the archive's posts, which only a Loop
19
+ * without a collection lists. True when the archive has Loops and all of them list a collection.
20
+ */
21
+ const onlyCollectionLoops = (layout: Layout): boolean =>
22
+ someNode(layout.root, (n) => collectionOf(n) !== undefined) &&
23
+ !someNode(layout.root, (n) => n.type === "loop" && collectionOf(n) === undefined);
24
+
10
25
  /**
11
26
  * W-271: a Loop or Pagination outside an archive template previews sample posts on the canvas,
12
- * but the live page gets no posts, so it renders nothing there. Undefined where it can work.
27
+ * but the live page gets no posts, so it renders nothing there. W-1090 (#31): in an archive
28
+ * template, a Loop with a collection lists the same entries on every archive page. Undefined
29
+ * where it works as it looks.
13
30
  */
14
31
  export function loopContextNote(
15
32
  node: LayoutNode,
16
33
  partType: ThemePartType | undefined,
34
+ layout?: Layout | null,
17
35
  ): string | undefined {
36
+ if (partType === "archive" && collectionOf(node)) {
37
+ return "This Loop lists its own collection, so it shows the same entries on every page of the archive and ignores the archive's category or tag. To list the archive's posts page by page, leave Collection empty.";
38
+ }
39
+ if (
40
+ partType === "archive" &&
41
+ node.type === "pagination" &&
42
+ layout &&
43
+ onlyCollectionLoops(layout)
44
+ ) {
45
+ return "Pagination pages through the archive's posts, but the Loop here lists its own collection, so every page would show the same entries. To page through the archive, leave its Collection empty.";
46
+ }
18
47
  if (partType && LOOP_PARTS.has(partType)) return undefined;
48
+ // W-308: a collection Loop lists its entries on any page.
49
+ if (collectionOf(node)) return undefined;
19
50
  if (node.type === "loop") {
20
- return "A Loop lists posts only in an Archive template. Here the editor shows sample posts, but the live page shows nothing. Build post lists in Theme Builder › Archive.";
51
+ return "A Loop lists posts only in an Archive template. Here the editor shows sample posts, but the live page shows nothing. Build post lists in Theme Builder › Archive, or pick a Collection to list its entries here.";
21
52
  }
22
53
  if (node.type === "pagination") {
23
54
  return "Pagination shows only in an Archive template with more than one page. Here the live page shows nothing.";
@@ -123,6 +123,8 @@ export async function loadExportData(
123
123
  });
124
124
  }
125
125
  if (item.seo?.description) page.description = item.seo.description;
126
+ if (item.locale) page.locale = item.locale;
127
+ if (item.translationGroup) page.translationGroup = item.translationGroup;
126
128
  return page;
127
129
  })
128
130
  .toSorted((a, b) => a.title.localeCompare(b.title));
@@ -177,3 +177,60 @@ export function useExtensionOutputs(
177
177
  }, [key, fetcher, retry]);
178
178
  return outputs;
179
179
  }
180
+
181
+ /** W-1088: values of the sources extension panels name, by source id (`ext:<package>/<name>`). */
182
+ export type ExtensionSourceValues = ReadonlyMap<string, Readonly<Record<string, string>> | null>;
183
+
184
+ /**
185
+ * W-1088 (#36): asks the server for the values of every source an extension panel names. Values
186
+ * are plain strings (cleaned on the server); anything else in the answer is dropped. `null` for a
187
+ * source the server couldn't read; the whole map is empty when the request fails.
188
+ */
189
+ export async function fetchExtensionSourceValues(fetcher: Fetcher): Promise<ExtensionSourceValues> {
190
+ const out = new Map<string, Readonly<Record<string, string>> | null>();
191
+ try {
192
+ const body = await requestJson<{ sources?: { id?: unknown; values?: unknown }[] }>(
193
+ fetcher,
194
+ `/_emdash/api/plugins/${PLUGIN_ID}/editor/extensions/sources`,
195
+ );
196
+ for (const item of Array.isArray(body?.sources) ? body.sources : []) {
197
+ if (typeof item?.id !== "string") continue;
198
+ const raw = item.values;
199
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
200
+ out.set(item.id, null);
201
+ continue;
202
+ }
203
+ const values: Record<string, string> = {};
204
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
205
+ if (typeof value === "string") values[key] = value;
206
+ }
207
+ out.set(item.id, values);
208
+ }
209
+ } catch {
210
+ // The panels say the values couldn't be loaded.
211
+ }
212
+ return out;
213
+ }
214
+
215
+ /**
216
+ * W-1088 (#36): source values for the extension panels, loaded once the site's manifests are in
217
+ * when a panel names a source. Undefined while loading (or when no panel names one).
218
+ */
219
+ export function useExtensionSourceValues(
220
+ fetcher: Fetcher,
221
+ manifests: readonly ExtensionManifest[],
222
+ ): ExtensionSourceValues | undefined {
223
+ const wanted = manifests.some((m) => m.panels?.some((panel) => panel.source));
224
+ const [values, setValues] = React.useState<ExtensionSourceValues | undefined>(undefined);
225
+ React.useEffect(() => {
226
+ if (!wanted) return;
227
+ let cancelled = false;
228
+ void fetchExtensionSourceValues(fetcher).then((found) => {
229
+ if (!cancelled) setValues(found);
230
+ });
231
+ return () => {
232
+ cancelled = true;
233
+ };
234
+ }, [fetcher, wanted]);
235
+ return values;
236
+ }
@@ -0,0 +1,133 @@
1
+ import type { ImportedForm, ImportedFormField, Layout } from "../core/index.ts";
2
+ import type { LayoutNode } from "../core/schema/layout.ts";
3
+ import { ApiError, requestJson, type Fetcher } from "./api.ts";
4
+
5
+ const CREATE = "/_emdash/api/plugins/emdash-forms/forms/create";
6
+
7
+ /** A forms-plugin slug (`^[a-z][a-z0-9-]*$`, 100 at most) from a form's name, unique on the site. */
8
+ function formSlug(name: string, taken: ReadonlySet<string>): string {
9
+ const base =
10
+ name
11
+ .normalize("NFKD")
12
+ .replaceAll(/[̀-ͯ]/g, "")
13
+ .toLowerCase()
14
+ .replaceAll(/[^a-z0-9]+/g, "-")
15
+ .replace(/^[^a-z]+/, "")
16
+ .replace(/-+$/, "")
17
+ .slice(0, 90) || "imported-form";
18
+ let slug = base;
19
+ for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`;
20
+ return slug;
21
+ }
22
+
23
+ /** One field as the forms plugin's `forms/create` takes it. */
24
+ function pluginField(field: ImportedFormField) {
25
+ const validation = {
26
+ ...(field.min === undefined ? {} : { min: field.min }),
27
+ ...(field.max === undefined ? {} : { max: field.max }),
28
+ };
29
+ return {
30
+ id: field.name,
31
+ type: field.type,
32
+ label: field.label,
33
+ name: field.name,
34
+ required: field.required,
35
+ width: "full",
36
+ ...(field.placeholder ? { placeholder: field.placeholder } : {}),
37
+ ...(field.options?.length ? { options: field.options } : {}),
38
+ ...(Object.keys(validation).length > 0 ? { validation } : {}),
39
+ };
40
+ }
41
+
42
+ /**
43
+ * W-1091 (#27): the body that creates an imported Elementor form in EmDash Forms (the plugin's
44
+ * admin route, plugins:manage), or null when it has no field the plugin can hold. Pages without
45
+ * fields are left out, since the plugin needs at least one field on each.
46
+ */
47
+ function formCreateBody(form: ImportedForm, slug: string) {
48
+ const pages = form.pages
49
+ .filter((page) => page.fields.length > 0)
50
+ .map((page) =>
51
+ page.title
52
+ ? { title: page.title, fields: page.fields.map(pluginField) }
53
+ : { fields: page.fields.map(pluginField) },
54
+ );
55
+ if (pages.length === 0) return null;
56
+ return {
57
+ name: form.name,
58
+ slug,
59
+ pages,
60
+ settings: {
61
+ submitLabel: form.submitLabel,
62
+ ...(form.successMessage ? { confirmationMessage: form.successMessage } : {}),
63
+ ...(pages.length > 1 && form.nextLabel ? { nextLabel: form.nextLabel } : {}),
64
+ ...(pages.length > 1 && form.prevLabel ? { prevLabel: form.prevLabel } : {}),
65
+ },
66
+ };
67
+ }
68
+
69
+ export type CreatedForms = {
70
+ /** EmVB Form node id → the new forms-plugin form id. */
71
+ ids: Map<string, string>;
72
+ /** Forms that couldn't be made (by name), with why. */
73
+ failed: { name: string; message: string }[];
74
+ };
75
+
76
+ /**
77
+ * W-1091 (#27): creates each imported form in EmDash Forms, one at a time. A refusal for lack of
78
+ * rights stops at once (nothing more would succeed) and is thrown, so the import doesn't go on
79
+ * with a half-made set; any other failure is reported and the rest go on.
80
+ */
81
+ export async function createImportedForms(
82
+ fetcher: Fetcher,
83
+ forms: readonly ImportedForm[],
84
+ takenSlugs: ReadonlySet<string>,
85
+ ): Promise<CreatedForms> {
86
+ const taken = new Set(takenSlugs);
87
+ const result: CreatedForms = { ids: new Map(), failed: [] };
88
+ for (const form of forms) {
89
+ const slug = formSlug(form.name, taken);
90
+ taken.add(slug);
91
+ const body = formCreateBody(form, slug);
92
+ if (!body) {
93
+ result.failed.push({ name: form.name, message: "it has no fields to send" });
94
+ continue;
95
+ }
96
+ try {
97
+ // oxlint-disable-next-line no-await-in-loop -- one form at a time; failures are per form
98
+ const created = await requestJson<{ id: string }>(fetcher, CREATE, {
99
+ method: "POST",
100
+ body,
101
+ });
102
+ result.ids.set(form.nodeId, created.id);
103
+ } catch (error) {
104
+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
105
+ throw new ApiError(
106
+ error.status,
107
+ error.code,
108
+ "Only administrators can create forms in EmDash Forms. Untick “Create the forms in EmDash Forms” to import without them, then connect each form in its settings.",
109
+ );
110
+ }
111
+ result.failed.push({
112
+ name: form.name,
113
+ message: error instanceof Error ? error.message : String(error),
114
+ });
115
+ }
116
+ }
117
+ return result;
118
+ }
119
+
120
+ /** The layout with each created form's id on its Form element. */
121
+ export function withFormIds(layout: Layout, ids: ReadonlyMap<string, string>): Layout {
122
+ if (ids.size === 0) return layout;
123
+ const visit = (node: LayoutNode): LayoutNode => {
124
+ const formId = node.type === "form" ? ids.get(node.id) : undefined;
125
+ const children = (node as { children?: LayoutNode[] }).children;
126
+ return {
127
+ ...node,
128
+ ...(formId ? { props: { ...node.props, formId } } : {}),
129
+ ...(children ? { children: children.map(visit) } : {}),
130
+ } as LayoutNode;
131
+ };
132
+ return { ...layout, root: visit(layout.root) as Layout["root"] };
133
+ }
@@ -19,10 +19,13 @@ import type { MenuLink } from "../../core/import/elementor/context.ts";
19
19
  import { editorUrl } from "../editor/exit.ts";
20
20
  import { loadIconSet } from "../editor/icons/library.ts";
21
21
  import { createThemePart } from "../theme-api.ts";
22
+ import { type FormsCapability, loadFormsCapability } from "../forms-api.ts";
23
+ import { createImportedForms, withFormIds } from "../import-forms.ts";
22
24
  import { saveDesign } from "../design-api.ts";
23
25
  import { loadDesign } from "../editor/useEditorData.ts";
24
26
  import { BUTTON, FIELD } from "../ui.ts";
25
27
  import { CreateDialog } from "./CreateDialog.tsx";
28
+ import { ImportForms } from "./ImportForms.tsx";
26
29
  import { ImportReport } from "./ImportReport.tsx";
27
30
  import { type Copy, fileNameOf, ImportImageCopies } from "./ImportImageCopies.tsx";
28
31
  import {
@@ -133,6 +136,9 @@ export function ImportElementorDialog({
133
136
  // W-1026: the site's own menus (from its WordPress import) for imported Nav Menus, by name.
134
137
  // A menu the site doesn't have is kept as no links, so it is asked for once.
135
138
  const [siteMenus, setSiteMenus] = React.useState<ReadonlyMap<string, MenuLink[]>>(new Map());
139
+ // W-1091 (#27): imported forms can be created in EmDash Forms (off until asked).
140
+ const [createForms, setCreateForms] = React.useState(false);
141
+ const [formsCapability, setFormsCapability] = React.useState<FormsCapability>();
136
142
  const iconsLoad = React.useRef<Promise<IconMap> | undefined>(undefined);
137
143
  const fileRef = React.useRef<HTMLInputElement>(null);
138
144
  const kitRef = React.useRef<HTMLInputElement>(null);
@@ -156,6 +162,7 @@ export function ImportElementorDialog({
156
162
  setCopies(new Map());
157
163
  setSession((n) => n + 1);
158
164
  setSiteMenus(new Map());
165
+ setCreateForms(false);
159
166
  }
160
167
  }
161
168
 
@@ -192,6 +199,18 @@ export function ImportElementorDialog({
192
199
  const missingSvgs = result?.ok ? result.svgFiles : [];
193
200
  const linkedPages = result?.ok ? result.pageLinks : [];
194
201
  const oldImages = result?.ok ? result.images.filter((url) => !copies.has(url)) : [];
202
+ const importedForms = result?.ok ? result.forms : [];
203
+ const hasForms = importedForms.length > 0;
204
+ React.useEffect(() => {
205
+ if (!hasForms || formsCapability) return;
206
+ let live = true;
207
+ void loadFormsCapability(fetcher).then((found) => {
208
+ if (live) setFormsCapability(found);
209
+ });
210
+ return () => {
211
+ live = false;
212
+ };
213
+ }, [hasForms, formsCapability, fetcher]);
195
214
 
196
215
  // W-1026: fetch each menu the export's Nav Menus name once; the import re-runs with them.
197
216
  const wantedMenus = (result?.ok ? result.menus : []).filter((name) => !siteMenus.has(name));
@@ -278,6 +297,13 @@ export function ImportElementorDialog({
278
297
  }
279
298
  writePageLinks(pageLinks);
280
299
  let layout = imported.layout;
300
+ if (createForms && imported.forms.length > 0) {
301
+ // W-1091 (#27): each form becomes an EmDash form and the page's Form points at it.
302
+ const known = await loadFormsCapability(fetcher);
303
+ const slugs = new Set(known.status === "ready" ? known.forms.map((f) => f.slug) : []);
304
+ const made = await createImportedForms(fetcher, imported.forms, slugs);
305
+ layout = withFormIds(layout, made.ids);
306
+ }
281
307
  if (imported.classes.length > 0) {
282
308
  // W-958 (D-060): never changes a class already on the site; identical ones are reused, a
283
309
  // different one with the same name is added as a numbered copy. Classes are saved first,
@@ -520,6 +546,12 @@ export function ImportElementorDialog({
520
546
  ))}
521
547
  </Select>
522
548
  )}
549
+ <ImportForms
550
+ forms={importedForms}
551
+ capability={formsCapability}
552
+ create={createForms}
553
+ onCreateChange={setCreateForms}
554
+ />
523
555
  <ElementorReport result={result} {...(target === "part" ? { partType } : {})} />
524
556
  </div>
525
557
  </CreateDialog>
@@ -0,0 +1,71 @@
1
+ import { Checkbox } from "@cloudflare/kumo";
2
+ import type { ImportedForm, ImportedFormField } from "../../core/index.ts";
3
+ import type { FormsCapability } from "../forms-api.ts";
4
+
5
+ /** How a field reads in the list: "Email (email, required)". */
6
+ function fieldSummary(field: ImportedFormField): string {
7
+ const notes = [field.type, ...(field.required ? ["required"] : [])];
8
+ const label = field.label === field.name ? field.name : `${field.label} [${field.name}]`;
9
+ return `${label} (${notes.join(", ")})`;
10
+ }
11
+
12
+ /**
13
+ * W-1091 (#27): Elementor forms arrive as EmVB Forms that aren't connected to a form yet, so they
14
+ * show nothing on the live site. The import says so where it can't be missed, lists each form's
15
+ * fields (names and types) and success message, and offers to create them in EmDash Forms.
16
+ */
17
+ export function ImportForms({
18
+ forms,
19
+ capability,
20
+ create,
21
+ onCreateChange,
22
+ }: {
23
+ forms: readonly ImportedForm[];
24
+ /** The forms plugin: there and listable, there for an id only, or not installed. */
25
+ capability: FormsCapability | undefined;
26
+ create: boolean;
27
+ onCreateChange: (create: boolean) => void;
28
+ }) {
29
+ if (forms.length === 0) return null;
30
+ const one = forms.length === 1;
31
+ return (
32
+ <section className="emvb-import-forms" aria-label="Forms" data-emvb-import-forms="">
33
+ <p className="emvb-import-summary">
34
+ {one
35
+ ? "This page has a form that needs connecting to an EmDash form. Until it is, it doesn't show on your live site."
36
+ : `This page has ${forms.length} forms that need connecting to EmDash forms. Until they are, they don't show on your live site.`}
37
+ </p>
38
+ <ul>
39
+ {forms.map((form) => {
40
+ const fields = form.pages.flatMap((page) => page.fields);
41
+ return (
42
+ <li key={form.nodeId} data-emvb-import-form="">
43
+ <strong>{form.name}:</strong>{" "}
44
+ {fields.length > 0 ? fields.map(fieldSummary).join(", ") : "no fields"}.
45
+ {form.successMessage ? ` Success message: “${form.successMessage}”` : ""}
46
+ </li>
47
+ );
48
+ })}
49
+ </ul>
50
+ {capability?.status === "missing" ? (
51
+ <p className="emvb-helper">
52
+ Install the EmDash Forms plugin, create {one ? "the form" : "the forms"} there, then pick{" "}
53
+ {one ? "it" : "each"} in the Form's settings.
54
+ </p>
55
+ ) : (
56
+ <>
57
+ <Checkbox
58
+ label="Create the forms in EmDash Forms"
59
+ checked={create}
60
+ onCheckedChange={(checked: boolean) => onCreateChange(checked)}
61
+ />
62
+ <p className="emvb-helper">
63
+ {create
64
+ ? "Each becomes an EmDash form with these fields, types and success message, connected to the page. Needs an administrator."
65
+ : "Or create them in Forms yourself, then pick each in the Form's settings."}
66
+ </p>
67
+ </>
68
+ )}
69
+ </section>
70
+ );
71
+ }
@@ -13,6 +13,8 @@ export type FieldState = {
13
13
  required?: boolean;
14
14
  validation?: { options?: string[] } | null;
15
15
  defaultValue?: unknown;
16
+ /** EmDash i18n: false when the field is shared by every language of an entry. */
17
+ translatable?: boolean;
16
18
  };
17
19
 
18
20
  export type CollectionState = {
package/src/admin/ui.ts CHANGED
@@ -275,6 +275,13 @@ export const UI_CSS = `
275
275
  .emvb-import-report ul { margin: 4px 0 0; padding-inline-start: 18px; display: flex; flex-direction: column; gap: 2px; }
276
276
  .emvb-import-report li { overflow-wrap: anywhere; }
277
277
  .emvb-import-summary { font-weight: 600; }
278
+ .emvb-import-forms {
279
+ display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; border-radius: 6px;
280
+ border-inline-start: 3px solid var(--color-kumo-warning, #b7791f); box-shadow: var(--emvb-elevation-s);
281
+ font-size: 13px; line-height: 1.35; color: var(--text-color-kumo-default);
282
+ }
283
+ .emvb-import-forms ul { margin: 0; padding-inline-start: 18px; display: flex; flex-direction: column; gap: 2px; }
284
+ .emvb-import-forms li { overflow-wrap: anywhere; }
278
285
  .emvb-list-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
279
286
  /* UX-090: 16 px so the title stands above the 14 px field labels under it. */
280
287
  .emvb-dialog :is(h2, [data-slot="title"]) {
@@ -2,6 +2,7 @@ import { Button, Dialog, Loader } from "@cloudflare/kumo";
2
2
  import { TextAlignLeftIcon } from "@phosphor-icons/react";
3
3
  import * as React from "react";
4
4
  import type { Layout } from "../../core/index.ts";
5
+ import { elementCount } from "../../core/elements/element-nouns.ts";
5
6
  import type { Fetcher } from "../api.ts";
6
7
  import { DialogCloseButton } from "../editor/DialogCloseButton.tsx";
7
8
  import { BUTTON, SOLID_DESTRUCTIVE, UI_CSS } from "../ui.ts";
@@ -11,10 +12,10 @@ type Plan = Extract<RichTextPlan, { ok: true }>;
11
12
 
12
13
  const plural = (n: number, one: string) => `${n} ${n === 1 ? one : `${one}s`}`;
13
14
 
14
- /** "form, 2 icons", for what a conversion leaves out. */
15
+ /** "form, 12 icon boxes", for what a conversion leaves out (W-1091: names, real plurals). */
15
16
  export function leftOutText(skipped: Record<string, number>): string {
16
17
  return Object.entries(skipped)
17
- .map(([type, n]) => (n === 1 ? type : `${n} ${type}s`))
18
+ .map(([type, n]) => elementCount(type, n))
18
19
  .join(", ");
19
20
  }
20
21
 
@@ -87,6 +87,11 @@ export function renderStored(
87
87
  partIds = false,
88
88
  /** The page's language, e.g. "fr-CA", for Post Dates (W-688). */
89
89
  lang?: string,
90
+ /**
91
+ * W-1088 (#37): a draft preview shows the placeholder for an extension element that can't
92
+ * render; visitors get nothing in its place.
93
+ */
94
+ extensionPlaceholders = false,
90
95
  ): RenderedPage {
91
96
  const empty: RenderedPage = {
92
97
  html: "",
@@ -114,6 +119,7 @@ export function renderStored(
114
119
  scope: pageId,
115
120
  ...(partIds ? { partIds } : {}),
116
121
  ...(lang ? { lang } : {}),
122
+ ...(extensionPlaceholders ? { extensionPlaceholders } : {}),
117
123
  separateExtensionCss: true,
118
124
  });
119
125
  } catch (error) {
@@ -202,6 +202,8 @@ export async function resolveEmVBPageWith(
202
202
  Object.keys(dynamic).length > 0 ? dynamic : undefined,
203
203
  false,
204
204
  options.lang ?? found.fallbackLocale ?? locale,
205
+ // W-1088 (#37): a draft preview (editors) keeps the missing-extension note.
206
+ Boolean(found.isPreview),
205
207
  ),
206
208
  entry,
207
209
  collection: hosted ? (options.collection as string) : PAGES_COLLECTION,
@@ -1,30 +1,23 @@
1
- import { clipText, loopPermalink, type ThemePostFields } from "../core/index.ts";
1
+ import {
2
+ clipText,
3
+ entryImageValue,
4
+ loopPermalink,
5
+ mediaUrlOf,
6
+ type ThemePostFields,
7
+ } from "../core/index.ts";
2
8
 
3
- type MediaLike = {
4
- src?: unknown;
5
- url?: unknown;
6
- previewUrl?: unknown;
7
- alt?: unknown;
8
- };
9
-
10
- /** Pull a sanitized-ready image URL + alt from an EmDash media / image field value. */
9
+ /**
10
+ * Pull a sanitized-ready image URL + alt from an EmDash media / image field value. W-1090 (#32):
11
+ * a local upload picked in EmDash's admin has no `src`, only its storage key.
12
+ */
11
13
  export function mediaFieldsFrom(value: unknown): {
12
14
  featuredImageUrl?: string;
13
15
  featuredImageAlt?: string;
14
16
  } {
15
17
  if (!value || typeof value !== "object") return {};
16
- const media = value as MediaLike;
17
- const candidates = [media.src, media.url, media.previewUrl];
18
- let featuredImageUrl: string | undefined;
19
- for (const candidate of candidates) {
20
- if (typeof candidate === "string" && candidate.trim()) {
21
- featuredImageUrl = candidate.trim();
22
- break;
23
- }
24
- }
25
- const featuredImageAlt =
26
- typeof media.alt === "string" && media.alt.trim() ? media.alt.trim() : undefined;
27
- return { featuredImageUrl, featuredImageAlt };
18
+ const alt = (value as { alt?: unknown }).alt;
19
+ const featuredImageAlt = typeof alt === "string" && alt.trim() ? alt.trim() : undefined;
20
+ return { featuredImageUrl: mediaUrlOf(value), featuredImageAlt };
28
21
  }
29
22
 
30
23
  /**
@@ -46,7 +39,7 @@ export function themePostFromEntry(
46
39
  permalinkPrefix?: string;
47
40
  /** W-330: a Loop's link pattern, e.g. `/team/{slug}`. */
48
41
  permalinkPattern?: string;
49
- /** W-330: the field with the entry's image, instead of `featured_image`. */
42
+ /** W-330: the field with the entry's image, instead of the automatic one (W-1090). */
50
43
  imageField?: string;
51
44
  /** W-330: the field with the entry's excerpt, instead of `excerpt`. */
52
45
  excerptField?: string;
@@ -67,7 +60,8 @@ export function themePostFromEntry(
67
60
  const permalink = options.permalinkPattern
68
61
  ? loopPermalink(options.permalinkPattern, { slug: slug || id, id: id || slug })
69
62
  : `${prefix.replace(/\/$/, "")}/${slug || id}`;
70
- const media = mediaFieldsFrom(data[options.imageField ?? "featured_image"]);
63
+ // W-1090 (#32): unset reads featured_image, else the entry's first image field.
64
+ const media = mediaFieldsFrom(entryImageValue(data, options.imageField));
71
65
  // W-303: EmDash's own publish date is `data.publishedAt`, a `Date`; a custom field may be text.
72
66
  const publishedAt = ["published_at", "publishedAt", "date"]
73
67
  .map((key) => entryTimestamp(data[key]))
@@ -1,4 +1,5 @@
1
1
  import { geoTrust } from "../core/geo-trust.ts";
2
+ import { visitorCookie, visitorCookieAllowed } from "../core/visitor-cookie.ts";
2
3
  import {
3
4
  AUDIENCE_SEGMENT,
4
5
  abCookieName,
@@ -190,7 +191,8 @@ export function hostVisitorFacts(host: HostVisitor | undefined): Partial<Visitor
190
191
 
191
192
  /**
192
193
  * What the server knows about this visitor, for visitor-aware elements (W-313): country from
193
- * the edge, device from the User-Agent, new or returning from a first-party cookie, and the time.
194
+ * the edge, device from the User-Agent, new or returning from a first-party cookie (when
195
+ * `emvb({ visitorCookie })` allows it, W-1092), and the time.
194
196
  * Facts the host passes (W-329) win over detected ones. Only read when the layout has a rule.
195
197
  */
196
198
  export function visitorFor(
@@ -205,13 +207,20 @@ export function visitorFor(
205
207
  if (country) visitor.country = country;
206
208
  const device = deviceFromUserAgent(headers?.get("user-agent"), headers?.get("sec-ch-ua-mobile"));
207
209
  if (device) visitor.device = device;
210
+ // W-1092 (#34): only a new/returning rule reads or sets the cookie, and only when
211
+ // `emvb({ visitorCookie })` allows it for this request. Otherwise everyone counts as new.
208
212
  if (astro.cookies && layoutUsesVisitorRule(layout)) {
209
- visitor.returning = requestCookie(astro, SEEN_COOKIE) === "1";
210
- if (!visitor.returning) {
213
+ const cookieAllowed = visitorCookieAllowed(visitorCookie(), (name) =>
214
+ requestCookie(astro, name),
215
+ );
216
+ const seen = requestCookie(astro, SEEN_COOKIE);
217
+ visitor.returning = cookieAllowed && seen === "1";
218
+ if (cookieAllowed ? !visitor.returning : seen !== undefined) {
211
219
  try {
212
- astro.cookies.set(SEEN_COOKIE, "1", {
220
+ // Without consent (or in "never" mode) a cookie left from before is cleared.
221
+ astro.cookies.set(SEEN_COOKIE, cookieAllowed ? "1" : "", {
213
222
  path: "/",
214
- maxAge: SEEN_DAYS * 86_400,
223
+ maxAge: cookieAllowed ? SEEN_DAYS * 86_400 : 0,
215
224
  sameSite: "lax",
216
225
  httpOnly: true,
217
226
  secure: astro.url.protocol === "https:",
package/src/constants.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export const PLUGIN_ID = "emvb";
2
- export const PLUGIN_VERSION = "1.4.0";
2
+ export const PLUGIN_VERSION = "1.4.1";
3
3
  export const PACKAGE_NAME = "@perkyzz/emvb";
4
4
  export const ADMIN_ENTRY = `${PACKAGE_NAME}/admin`;
5
5
  export const PAGES_COLLECTION = "emvb_pages";
@@ -119,7 +119,12 @@ function tagDefaultCss(
119
119
  if (!style) continue;
120
120
  // W-670: tracked like classes, so a tag default's entrance gets its keyframes and turns off
121
121
  // for reduced motion.
122
- const selector = `:where(.emvb-root) ${tag}`;
122
+ // W-1090 (#30): a Button with a URL renders as `<a>`, and the `button` default reaches it
123
+ // too, at the same tag weight and after the `a` default. Link elements are not Buttons.
124
+ const selector =
125
+ tag === "button"
126
+ ? ":where(.emvb-root) button,:where(.emvb-root) a:where(.emvb-button)"
127
+ : `:where(.emvb-root) ${tag}`;
123
128
  css += block(selector, track(selector, styleDeclarations(style).declarations));
124
129
  }
125
130
  return css;
@@ -94,6 +94,14 @@ export function styleLayers(
94
94
  style: tagStyle,
95
95
  });
96
96
  }
97
+ // W-1090 (#30): a link Button gets the `button` default too, above the `a` one.
98
+ const buttonStyle = design.defaults?.button;
99
+ if (tag === "a" && node.type === "button" && buttonStyle) {
100
+ layers.push({
101
+ source: { kind: "default", label: "Site default (BUTTON)", layer: "Desktop" },
102
+ style: buttonStyle,
103
+ });
104
+ }
97
105
  const applied = new Set(node.classes ?? []);
98
106
  const owners: Owner[] = [];
99
107
  for (const cls of design.classes ?? []) {
@@ -95,8 +95,11 @@ function postValue(post: ThemePostFields | undefined, key: string): string | und
95
95
  return scalar(fields[key]);
96
96
  }
97
97
 
98
- /** Text with control characters removed and its length capped. */
99
- function clean(value: string): string {
98
+ /**
99
+ * Text with control characters removed and its length capped. W-1088: extension source values
100
+ * are cleaned with it too, with their own (longer) cap.
101
+ */
102
+ export function cleanBoundText(value: string, max = MAX_BOUND_LENGTH): string {
100
103
  let out = "";
101
104
  for (const char of value) {
102
105
  const code = char.codePointAt(0) ?? 0;
@@ -109,7 +112,7 @@ function clean(value: string): string {
109
112
  (code >= 0x2066 && code <= 0x2069);
110
113
  const kept = code === 9 ? " " : code === 10 || (code >= 32 && !dropped) ? char : "";
111
114
  // W-502: cutting at a UTF-16 length split an emoji at the limit into a broken half.
112
- if (out.length + kept.length > MAX_BOUND_LENGTH) break;
115
+ if (out.length + kept.length > max) break;
113
116
  out += kept;
114
117
  }
115
118
  return out.trim();
@@ -126,7 +129,7 @@ export function resolveBinding(binding: Binding, data: BindingData): string | un
126
129
  data.params && Object.hasOwn(data.params, binding.key) ? data.params[binding.key] : undefined;
127
130
  }
128
131
  if (raw === undefined) return undefined;
129
- const value = clean(raw);
132
+ const value = cleanBoundText(raw);
130
133
  return value.length > 0 ? value : undefined;
131
134
  }
132
135