@perkyzz/emvb 1.4.0 → 1.4.2

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 (57) hide show
  1. package/README.md +2 -2
  2. package/package.json +6 -6
  3. package/src/admin/content-item.ts +3 -0
  4. package/src/admin/copy-rich-text.ts +99 -9
  5. package/src/admin/editor/Editor.tsx +7 -2
  6. package/src/admin/editor/collection-previews.ts +7 -8
  7. package/src/admin/editor/extensions/ExtensionPanels.tsx +33 -1
  8. package/src/admin/editor/extensions-context.tsx +16 -1
  9. package/src/admin/editor/feature-css.ts +5 -0
  10. package/src/admin/editor/panels/ConditionsEditor.tsx +18 -0
  11. package/src/admin/editor/panels/ElementPanel.tsx +2 -2
  12. package/src/admin/editor/panels/settings/FieldControl.tsx +15 -0
  13. package/src/admin/editor/panels/settings/FormBindControl.tsx +27 -31
  14. package/src/admin/editor/panels/settings/ImageFieldControl.tsx +106 -0
  15. package/src/admin/editor/panels/settings/loop-context.ts +34 -3
  16. package/src/admin/export-api.ts +2 -0
  17. package/src/admin/extension-outputs.ts +57 -0
  18. package/src/admin/import-forms.ts +133 -0
  19. package/src/admin/pages/ImportElementorDialog.tsx +32 -0
  20. package/src/admin/pages/ImportForms.tsx +71 -0
  21. package/src/admin/setup/plan.ts +2 -0
  22. package/src/admin/ui.ts +7 -0
  23. package/src/admin/widgets/ConvertToRichText.tsx +3 -2
  24. package/src/astro/render.ts +11 -0
  25. package/src/astro/resolve-theme.ts +11 -15
  26. package/src/astro/resolve.ts +2 -0
  27. package/src/astro/theme-posts.ts +17 -23
  28. package/src/astro/visitor.ts +14 -5
  29. package/src/astro/widgets/sticky.ts +4 -1
  30. package/src/constants.ts +1 -1
  31. package/src/core/css/generate.ts +6 -1
  32. package/src/core/css/trace.ts +8 -0
  33. package/src/core/data/bindings.ts +7 -4
  34. package/src/core/elements/dynamic-elements.ts +1 -1
  35. package/src/core/elements/element-nouns.ts +48 -0
  36. package/src/core/export/runtimes.generated.ts +1 -1
  37. package/src/core/export/site.ts +7 -11
  38. package/src/core/extensions/index.ts +2 -0
  39. package/src/core/extensions/placeholder.ts +7 -2
  40. package/src/core/extensions/render-ext.ts +49 -15
  41. package/src/core/import/elementor/context.ts +29 -0
  42. package/src/core/import/elementor/index.ts +23 -2
  43. package/src/core/import/elementor/widgets.ts +137 -17
  44. package/src/core/index.ts +11 -0
  45. package/src/core/render/index.ts +30 -2
  46. package/src/core/schema/layout.ts +4 -1
  47. package/src/core/theme/media-value.ts +88 -0
  48. package/src/core/theme/part-wrapper.ts +100 -0
  49. package/src/core/visitor-cookie.ts +91 -0
  50. package/src/index.ts +28 -1
  51. package/src/mcp/agent-defaults.ts +40 -0
  52. package/src/mcp/extensions.ts +138 -0
  53. package/src/mcp/read.ts +55 -19
  54. package/src/mcp/tools.ts +3 -3
  55. package/src/mcp/write.ts +83 -8
  56. package/src/server/extension-routes.ts +37 -0
  57. package/src/server/plugin.ts +7 -1
@@ -8,7 +8,13 @@ import { MAX_TABS, MAX_TEXT_LENGTH } from "../../limits.ts";
8
8
  import { FIELD_NAME_PATTERN, ICON_SVG_MAX, MAX_INPUT_NUMBER } from "../../schema/layout.ts";
9
9
  import { sanitizeHref } from "../../sanitize/href.ts";
10
10
  import { sanitizeMediaUrl } from "../../sanitize/media-url.ts";
11
- import { type ImportContext, type MenuLink, svgFileId } from "./context.ts";
11
+ import {
12
+ type ImportContext,
13
+ type ImportedForm,
14
+ type ImportedFormField,
15
+ type MenuLink,
16
+ svgFileId,
17
+ } from "./context.ts";
12
18
  import {
13
19
  type Block,
14
20
  cleanText,
@@ -1526,13 +1532,82 @@ function typedField(type: string, raw: Settings): Record<string, unknown> {
1526
1532
 
1527
1533
  const MAX_FORM_STEPS = 20;
1528
1534
 
1535
+ /** W-1091 (#27): the forms plugin's field type for an Elementor field type. */
1536
+ const PLUGIN_FIELD_TYPES: Record<string, string> = {
1537
+ text: "text",
1538
+ email: "email",
1539
+ url: "url",
1540
+ tel: "tel",
1541
+ number: "number",
1542
+ date: "date",
1543
+ time: "text",
1544
+ password: "text",
1545
+ textarea: "textarea",
1546
+ select: "select",
1547
+ radio: "radio",
1548
+ checkbox: "checkbox",
1549
+ acceptance: "checkbox",
1550
+ };
1551
+
1552
+ /**
1553
+ * W-1091 (#27): a field name the forms plugin accepts (a letter, then letters, digits, `_`, `-`):
1554
+ * Elementor's own id when it has one, cleaned up, else the label's words, else the field type.
1555
+ * Each name is used once per form; a repeat gets `_2`, `_3`.
1556
+ */
1557
+ function formFieldName(
1558
+ candidates: readonly { text: string | undefined; lower?: boolean }[],
1559
+ taken: ReadonlySet<string>,
1560
+ fallback: string,
1561
+ ): string {
1562
+ let base = "";
1563
+ for (const { text, lower } of candidates) {
1564
+ const clean = (text ?? "")
1565
+ .normalize("NFKD")
1566
+ .replaceAll(/[\u0300-\u036f]/g, "")
1567
+ .trim()
1568
+ .replaceAll(/[^a-zA-Z0-9_-]+/g, "_")
1569
+ .replace(/^[^a-zA-Z]+/, "")
1570
+ .replace(/[_-]+$/, "")
1571
+ .slice(0, 72);
1572
+ if (clean && FIELD_NAME_PATTERN.test(clean)) {
1573
+ base = lower ? clean.toLowerCase() : clean;
1574
+ break;
1575
+ }
1576
+ }
1577
+ base ||= fallback;
1578
+ let name = base;
1579
+ for (let n = 2; taken.has(name); n++) name = `${base}_${n}`;
1580
+ return name;
1581
+ }
1582
+
1583
+ /** W-1091 (#27): Elementor's `field_options` lines ("Label" or "Label|value") as options. */
1584
+ function formOptions(value: unknown): { label: string; value: string }[] {
1585
+ const options: { label: string; value: string }[] = [];
1586
+ const seen = new Set<string>();
1587
+ for (const line of (str(value) ?? "").split(/\r?\n/).slice(0, 100)) {
1588
+ const [rawLabel = "", rawValue] = line.split("|");
1589
+ const label = plain(rawLabel).text.trim().slice(0, 200);
1590
+ const option = (rawValue === undefined ? label : plain(rawValue).text.trim()).slice(0, 200);
1591
+ if (!label || !option || seen.has(option)) continue;
1592
+ seen.add(option);
1593
+ options.push({ label, value: option });
1594
+ }
1595
+ return options;
1596
+ }
1597
+
1598
+ const isOn = (value: unknown) => value === true || value === "true" || value === "yes";
1599
+
1529
1600
  const form: Widget = (s, ctx, el) => {
1530
1601
  const fields = Array.isArray(s["form_fields"]) ? s["form_fields"].slice(0, 100) : [];
1531
1602
  const loose: N[] = [];
1532
1603
  const steps: { title: string; children: N[] }[] = [];
1604
+ // W-1091 (#27): the same fields as the forms plugin holds them, page by page.
1605
+ const loosePlan: ImportedFormField[] = [];
1606
+ const stepPlans: ImportedFormField[][] = [];
1533
1607
  const names = new Set<string>();
1534
1608
  let nextLabel = "";
1535
1609
  let prevLabel = "";
1610
+ let checkboxLists = 0;
1536
1611
  fields.forEach((raw, i) => {
1537
1612
  if (!isRecord(raw)) return;
1538
1613
  const type = str(raw["field_type"]) ?? "text";
@@ -1540,6 +1615,7 @@ const form: Widget = (s, ctx, el) => {
1540
1615
  if (type === "step") {
1541
1616
  if (steps.length >= MAX_FORM_STEPS) return;
1542
1617
  steps.push({ title: plain(raw["field_label"]).text.slice(0, 200), children: [] });
1618
+ stepPlans.push([]);
1543
1619
  nextLabel ||= plain(raw["next_button"]).text.slice(0, 80);
1544
1620
  prevLabel ||= plain(raw["previous_button"]).text.slice(0, 80);
1545
1621
  return;
@@ -1549,13 +1625,16 @@ const form: Widget = (s, ctx, el) => {
1549
1625
  ctx.note("skipped", el, `Form field type "${type}" was left out.`);
1550
1626
  return;
1551
1627
  }
1552
- let name = str(raw["custom_id"]) ?? "";
1553
- if (!FIELD_NAME_PATTERN.test(name) || name.length > 80 || names.has(name))
1554
- name = `field_${i + 1}`;
1555
- names.add(name);
1556
1628
  const label =
1557
1629
  plain(raw["field_label"]).text.slice(0, 200) ||
1558
1630
  (type === "acceptance" ? plain(raw["acceptance_text"]).text.slice(0, 200) : "");
1631
+ // W-1091 (#27): Elementor's field id (cleaned), else the label, so `name` and `email` stay.
1632
+ const name = formFieldName(
1633
+ [{ text: str(raw["custom_id"]) }, { text: label, lower: true }, { text: type }],
1634
+ names,
1635
+ `field_${i + 1}`,
1636
+ );
1637
+ names.add(name);
1559
1638
  const placeholder = plain(raw["placeholder"]).text.slice(0, 200);
1560
1639
  const field = node(ctx, nodeType, {
1561
1640
  field: name,
@@ -1563,12 +1642,34 @@ const form: Widget = (s, ctx, el) => {
1563
1642
  ...(placeholder && nodeType !== "checkbox" ? { placeholder } : {}),
1564
1643
  ...typedField(type, raw),
1565
1644
  });
1645
+ const options =
1646
+ nodeType === "select" || nodeType === "radio" ? formOptions(raw["field_options"]) : [];
1647
+ if (type === "checkbox" && formOptions(raw["field_options"]).length > 1) checkboxLists += 1;
1648
+ const typed = typedField(type, raw) as { min?: number; max?: number };
1649
+ const planned: ImportedFormField = {
1650
+ name,
1651
+ label: label || name,
1652
+ type: PLUGIN_FIELD_TYPES[type] ?? "text",
1653
+ required: isOn(raw["required"]) || type === "acceptance",
1654
+ ...(placeholder && nodeType !== "checkbox" ? { placeholder } : {}),
1655
+ ...(options.length > 0 ? { options } : {}),
1656
+ ...(typed.min !== undefined ? { min: typed.min } : {}),
1657
+ ...(typed.max !== undefined ? { max: typed.max } : {}),
1658
+ };
1566
1659
  const step = steps[steps.length - 1];
1567
- if (step) step.children.push(field);
1568
- else loose.push(field);
1660
+ if (step) {
1661
+ step.children.push(field);
1662
+ stepPlans[stepPlans.length - 1]?.push(planned);
1663
+ } else {
1664
+ loose.push(field);
1665
+ loosePlan.push(planned);
1666
+ }
1569
1667
  });
1570
1668
  // Fields before the first Step field are a step of their own, as Elementor shows them.
1571
- if (steps.length > 0 && loose.length > 0) steps.unshift({ title: "", children: loose.splice(0) });
1669
+ if (steps.length > 0 && loose.length > 0) {
1670
+ steps.unshift({ title: "", children: loose.splice(0) });
1671
+ stepPlans.unshift(loosePlan.splice(0));
1672
+ }
1572
1673
  const children: N[] = [
1573
1674
  ...loose,
1574
1675
  ...steps.map((step) =>
@@ -1580,8 +1681,11 @@ const form: Widget = (s, ctx, el) => {
1580
1681
  ctx.note(
1581
1682
  "approximated",
1582
1683
  el,
1583
- "Connect each imported form to a form in the forms plugin; field options and email actions weren't imported.",
1684
+ "Each form needs connecting to an EmDash form before it shows on your site; the import can create it in EmDash Forms. Email actions weren't imported.",
1584
1685
  );
1686
+ if (checkboxLists > 0) {
1687
+ ctx.note("approximated", el, "A checkbox list became one checkbox; its options weren't kept.");
1688
+ }
1585
1689
  if (steps.length > 0) {
1586
1690
  ctx.note(
1587
1691
  "approximated",
@@ -1593,14 +1697,30 @@ const form: Widget = (s, ctx, el) => {
1593
1697
  ...(steps.length > 0 && nextLabel ? { nextLabel } : {}),
1594
1698
  ...(steps.length > 0 && prevLabel ? { prevLabel } : {}),
1595
1699
  };
1596
- return [
1597
- node(
1598
- ctx,
1599
- "form",
1600
- { formId: "", ...labels },
1601
- { style: { gap: { value: 10, unit: "px" } }, children },
1602
- ),
1603
- ];
1700
+ const built = node(
1701
+ ctx,
1702
+ "form",
1703
+ { formId: "", ...labels },
1704
+ { style: { gap: { value: 10, unit: "px" } }, children },
1705
+ );
1706
+ const successMessage = plain(s["success_message"]).text.trim().slice(0, 500);
1707
+ const plan: ImportedForm = {
1708
+ nodeId: built.id,
1709
+ name: plain(s["form_name"]).text.trim().slice(0, 200) || "Imported form",
1710
+ pages:
1711
+ steps.length > 0
1712
+ ? steps.map((step, i) =>
1713
+ step.title
1714
+ ? { title: step.title, fields: stepPlans[i] ?? [] }
1715
+ : { fields: stepPlans[i] ?? [] },
1716
+ )
1717
+ : [{ fields: loosePlan }],
1718
+ submitLabel: label,
1719
+ ...(successMessage ? { successMessage } : {}),
1720
+ ...labels,
1721
+ };
1722
+ if (ctx.forms.length < 50) ctx.forms.push(plan);
1723
+ return [built];
1604
1724
  };
1605
1725
 
1606
1726
  /** W-1026: a site menu's links as Menu items (three levels, as the Menu shows). */
package/src/core/index.ts CHANGED
@@ -432,6 +432,8 @@ export {
432
432
  type PopupDevice,
433
433
  } from "./theme/popup-rules.ts";
434
434
 
435
+ export { stickyFrameCss, wrapThemePart, type StickyFrame } from "./theme/part-wrapper.ts";
436
+
435
437
  export {
436
438
  POPUP_CHROME_CSS,
437
439
  wrapPopupMarkup,
@@ -478,6 +480,13 @@ export {
478
480
  type ArchivePagination,
479
481
  type PaginationItem,
480
482
  } from "./theme/pagination.ts";
483
+ export {
484
+ DEFAULT_IMAGE_FIELD,
485
+ automaticImageField,
486
+ entryImageValue,
487
+ imageFieldsOf,
488
+ mediaUrlOf,
489
+ } from "./theme/media-value.ts";
481
490
 
482
491
  export { layoutHasMenuDropdown, layoutHasTabs } from "./tabs/presence.ts";
483
492
  export {
@@ -628,6 +637,8 @@ export {
628
637
  export { portableTextToLayout } from "./portable-text.ts";
629
638
  export {
630
639
  type ElementorImport,
640
+ type ImportedForm,
641
+ type ImportedFormField,
631
642
  type ImportNote,
632
643
  type ImportOptions,
633
644
  importElementor,
@@ -51,6 +51,7 @@ import { sanitizeHref } from "../sanitize/href.ts";
51
51
  import { resolvePostForRender, type ThemeDynamicData } from "../theme/dynamic.ts";
52
52
  import type { FormDefinitions } from "../forms/definition.ts";
53
53
  import { DEVICES, type Device, type EditorDevice } from "../theme/popup-rules.ts";
54
+ import { stickyFrameOf, type StickyFrame } from "../theme/part-wrapper.ts";
54
55
  import { hiddenOnEveryDevice } from "../design/devices.ts";
55
56
  import type { RenderContext, RenderMode } from "./context.ts";
56
57
  import { isDynamicPostNode, renderDynamicPost } from "./dynamic-post.ts";
@@ -69,6 +70,7 @@ import {
69
70
  extensionStylesheets,
70
71
  isExtensionType,
71
72
  renderExtensionNode,
73
+ isExtensionPlaceholder,
72
74
  EXTENSION_PLACEHOLDER_CSS,
73
75
  type ExtensionOutputs,
74
76
  } from "../extensions/index.ts";
@@ -112,6 +114,11 @@ export type RenderResult = {
112
114
  * stylesheets are not in `css`; write `extensionStylesheets(ids)` once per document instead.
113
115
  */
114
116
  extensions: string[];
117
+ /**
118
+ * W-1097: a theme part (`partIds`) whose root, or a box right inside it, is sticky: that box's
119
+ * placement, for the part's wrapper (`wrapThemePart`). Unset for pages and other parts.
120
+ */
121
+ stickyFrame?: StickyFrame;
115
122
  };
116
123
 
117
124
  const ID = /^[A-Za-z0-9_-]{4,24}$/;
@@ -351,6 +358,12 @@ export function renderPage(
351
358
  * `extensions`.
352
359
  */
353
360
  separateExtensionCss?: boolean;
361
+ /**
362
+ * W-1088 (#37): public renders show the placeholder for an extension element that can't
363
+ * render (missing, throwing or illegal output). For the admin's previews of the public page;
364
+ * visitors get nothing in its place. The editor always shows it.
365
+ */
366
+ extensionPlaceholders?: boolean;
354
367
  } = {},
355
368
  ): RenderResult {
356
369
  const mode = opts.mode ?? "public";
@@ -409,6 +422,9 @@ export function renderPage(
409
422
  // W-1086: the extensions whose elements rendered, for their stylesheet and runtime.
410
423
  const extensionsUsed = new Set<string>();
411
424
  let sectionBudget = MAX_SECTION_ELEMENTS;
425
+ // W-1097: a theme part's top-level boxes (its root and the boxes right inside it).
426
+ const topLevel = opts.partIds ? new Set([layout.root, ...nodeChildren(layout.root)]) : undefined;
427
+ let stickyFrame: StickyFrame | undefined;
412
428
  const ctx: RenderContext = {
413
429
  takeSectionBudget: (nodes) => {
414
430
  if (nodes > sectionBudget) return false;
@@ -737,8 +753,7 @@ export function renderPage(
737
753
  if (!Object.hasOwn(ELEMENTS, type)) {
738
754
  // W-927: extension elements render via the Extensions API, or a placeholder when missing.
739
755
  if (isExtensionType(type)) {
740
- usedTypes.add("ext");
741
- return renderExtensionNode(
756
+ const ext = renderExtensionNode(
742
757
  node,
743
758
  mode === "editor" ? "editor" : "public",
744
759
  (nodes) =>
@@ -748,6 +763,13 @@ export function renderPage(
748
763
  opts.extensionOutputs,
749
764
  (pkg) => extensionsUsed.add(pkg),
750
765
  );
766
+ // W-1088 (#37): visitors get nothing for an extension element that can't render; the
767
+ // stored element is kept and renders again once its extension is back.
768
+ if (mode === "public" && !opts.extensionPlaceholders && isExtensionPlaceholder(ext)) {
769
+ return undefined;
770
+ }
771
+ usedTypes.add("ext");
772
+ return ext;
751
773
  }
752
774
  warnings.push({ nodeId, code: "unknown-type", detail: type });
753
775
  if (mode === "public") return undefined;
@@ -775,6 +797,11 @@ export function renderPage(
775
797
  attrs["data-emvb-sticky-hide"] = "";
776
798
  runtimes.add("sticky");
777
799
  }
800
+ // W-1097: the first sticky top-level box of a theme part gives its wrapper the same place.
801
+ if (!stickyFrame && ruleId && topLevel?.has(stored)) {
802
+ const rule = localRules.findLast((r) => r.id === ruleId);
803
+ if (rule) stickyFrame = stickyFrameOf(rule, hidesOnScroll(node as LayoutNode));
804
+ }
778
805
  // W-1067: the canvas runs no widget scripts, so a Theme toggle waiting for its own stayed
779
806
  // hidden there; the editor shows it as it looks once ready.
780
807
  if (mode === "editor" && type === "theme-toggle") attrs["data-emvb-ready"] = "";
@@ -964,6 +991,7 @@ export function renderPage(
964
991
  warnings,
965
992
  baseTypes: [...usedTypes],
966
993
  extensions,
994
+ ...(stickyFrame ? { stickyFrame } : {}),
967
995
  };
968
996
  }
969
997
 
@@ -711,7 +711,10 @@ export const LoopNode = parentNode(
711
711
  .max(200)
712
712
  .regex(LOOP_PERMALINK, "A site path with {slug} or {id}, such as /team/{slug}")
713
713
  .optional(),
714
- /** The entry field holding the image Post Image shows (W-330). Unset = featured_image. */
714
+ /**
715
+ * The entry field holding the image Post Image shows (W-330). Unset = featured_image, else the
716
+ * entry's first image field (W-1090).
717
+ */
715
718
  imageField: z.string().regex(FIELD_SLUG, FIELD_SLUG_HINT).optional(),
716
719
  /** The entry field Post Excerpt shows (W-330). Unset = excerpt. */
717
720
  excerptField: z.string().regex(FIELD_SLUG, FIELD_SLUG_HINT).optional(),
@@ -0,0 +1,88 @@
1
+ /**
2
+ * W-1090 (#32): reading an EmDash image field's value. EmDash's admin stores a local upload as
3
+ * `{ id, provider: "local", meta: { storageKey }, mimeType }` with no `src`, and builds its URL
4
+ * at render time, so a reader that only looked at `src` found no image at all.
5
+ */
6
+
7
+ /** EmDash's own route for local media files (its `INTERNAL_MEDIA_PREFIX`). */
8
+ const LOCAL_MEDIA = "/_emdash/api/media/file/";
9
+ /** The field EmVB has always read when a Loop names none. */
10
+ export const DEFAULT_IMAGE_FIELD = "featured_image";
11
+ const IMAGE_PATH = /\.(?:avif|gif|jpe?g|png|svg|webp)(?:[?#]|$)/i;
12
+
13
+ type MediaLike = {
14
+ id?: unknown;
15
+ provider?: unknown;
16
+ src?: unknown;
17
+ url?: unknown;
18
+ previewUrl?: unknown;
19
+ mimeType?: unknown;
20
+ meta?: unknown;
21
+ };
22
+
23
+ const text = (value: unknown): string | undefined =>
24
+ typeof value === "string" && value.trim() ? value.trim() : undefined;
25
+
26
+ /** A storage key as a path under the media route, or undefined for one that leaves it. */
27
+ function keyPath(key: string): string | undefined {
28
+ const segments = key.split("/");
29
+ if (segments.some((s) => s === "" || s === "." || s === "..")) return undefined;
30
+ return segments.map(encodeURIComponent).join("/");
31
+ }
32
+
33
+ /** The URL an EmDash media value points at: its own URL, else a local file's route. */
34
+ export function mediaUrlOf(value: unknown): string | undefined {
35
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
36
+ const media = value as MediaLike;
37
+ const direct = text(media.src) ?? text(media.url) ?? text(media.previewUrl);
38
+ if (direct) return direct;
39
+ const provider = text(media.provider);
40
+ if (provider && provider !== "local") return undefined;
41
+ const meta = media.meta && typeof media.meta === "object" ? (media.meta as MediaLike) : {};
42
+ const storageKey = text((meta as { storageKey?: unknown }).storageKey);
43
+ const path = storageKey ? keyPath(storageKey) : undefined;
44
+ if (path) return `${LOCAL_MEDIA}${path}`;
45
+ // As EmDash's own image component: a local item without a storage key goes by its id.
46
+ const id = text(media.id);
47
+ return id ? `${LOCAL_MEDIA}${encodeURIComponent(id)}` : undefined;
48
+ }
49
+
50
+ /** True for an image field's value: a media value with an image type or an image file name. */
51
+ export function isImageValue(value: unknown): boolean {
52
+ const url = mediaUrlOf(value);
53
+ if (!url) return false;
54
+ const mimeType = text((value as MediaLike).mimeType);
55
+ if (mimeType) return mimeType.toLowerCase().startsWith("image/");
56
+ return IMAGE_PATH.test(url) || url.startsWith(LOCAL_MEDIA);
57
+ }
58
+
59
+ /**
60
+ * The image an entry shows when its Loop or post names no field: `featured_image` when it has
61
+ * one, else the entry's first field holding an image (the collection's first image field).
62
+ */
63
+ export function automaticImageField(data: Record<string, unknown>): string | undefined {
64
+ if (isImageValue(data[DEFAULT_IMAGE_FIELD])) return DEFAULT_IMAGE_FIELD;
65
+ return Object.keys(data).find((key) => isImageValue(data[key]));
66
+ }
67
+
68
+ /** The image value an entry shows: the named field's, or the automatic one's. */
69
+ export function entryImageValue(data: Record<string, unknown>, field?: string): unknown {
70
+ if (field) return data[field];
71
+ const auto = automaticImageField(data);
72
+ return auto ? data[auto] : undefined;
73
+ }
74
+
75
+ /**
76
+ * The image fields a collection's schema lists, for the editor's picker: `featured_image` first
77
+ * when it is one, as the automatic choice reads it first.
78
+ */
79
+ export function imageFieldsOf(
80
+ fields: readonly { slug: string; type: string; label?: string | null }[],
81
+ ): { slug: string; label: string }[] {
82
+ const images = fields
83
+ .filter((f) => f.type === "image")
84
+ .map((f) => ({ slug: f.slug, label: f.label?.trim() || f.slug }));
85
+ const preferred = images.findIndex((f) => f.slug === DEFAULT_IMAGE_FIELD);
86
+ if (preferred > 0) images.unshift(...images.splice(preferred, 1));
87
+ return images;
88
+ }
@@ -0,0 +1,100 @@
1
+ import type { Declaration } from "../sanitize/css.ts";
2
+ import { escapeAttr } from "../sanitize/escape.ts";
3
+ import { DEVICE_MEDIA } from "./popup-rules.ts";
4
+
5
+ /**
6
+ * W-1097 (#42): a sticky box at the top level of a theme part (the part's root, or a box right
7
+ * inside it), with its placement on each device. A sticky box can't leave its containing block,
8
+ * and a header part's wrapper and root are only as tall as the header, so the box had no room to
9
+ * stick. The part's wrapper takes the same placement instead and sticks along the whole page.
10
+ */
11
+ export type StickyFrame = {
12
+ /** Desktop: `position` (sticky or static), `top`, `bottom`, `z-index`, `--emvb-sticky-hide`. */
13
+ declarations: Declaration[];
14
+ wide?: Declaration[];
15
+ laptop?: Declaration[];
16
+ tablet?: Declaration[];
17
+ mobile?: Declaration[];
18
+ /** The box hides while scrolling down (W-1070): the wrapper hides instead. */
19
+ hide: boolean;
20
+ };
21
+
22
+ type DeviceDeclarations = {
23
+ declarations: Declaration[];
24
+ wide?: Declaration[];
25
+ laptop?: Declaration[];
26
+ tablet?: Declaration[];
27
+ mobile?: Declaration[];
28
+ };
29
+
30
+ const COPIED = new Set(["top", "bottom", "z-index", "--emvb-sticky-hide"]);
31
+
32
+ /** A device's placement for the wrapper: any position but sticky leaves the wrapper in flow. */
33
+ const placement = (list: readonly Declaration[] | undefined): Declaration[] =>
34
+ (list ?? []).flatMap((d) =>
35
+ d.property === "position"
36
+ ? [{ property: "position", value: d.value === "sticky" ? "sticky" : "static" }]
37
+ : COPIED.has(d.property)
38
+ ? [d]
39
+ : [],
40
+ );
41
+
42
+ const sticks = (list: readonly Declaration[] | undefined): boolean =>
43
+ (list ?? []).some((d) => d.property === "position" && d.value === "sticky");
44
+
45
+ /** The frame of a box's rule when the box is sticky on Desktop or any other device. */
46
+ export function stickyFrameOf(rule: DeviceDeclarations, hide: boolean): StickyFrame | undefined {
47
+ const lists = [rule.declarations, rule.wide, rule.laptop, rule.tablet, rule.mobile];
48
+ if (!lists.some(sticks)) return undefined;
49
+ const frame: StickyFrame = { declarations: placement(rule.declarations), hide };
50
+ for (const device of ["wide", "laptop", "tablet", "mobile"] as const) {
51
+ const own = placement(rule[device]);
52
+ if (own.length > 0) frame[device] = own;
53
+ }
54
+ return frame;
55
+ }
56
+
57
+ const block = (selector: string, declarations: readonly Declaration[]) =>
58
+ declarations.length === 0
59
+ ? ""
60
+ : `${selector}{${declarations.map((d) => `${d.property}:${d.value}`).join(";")}}`;
61
+
62
+ /** The wrapper's rules, device by device in the order the part's own sheet writes them. */
63
+ export function stickyFrameCss(selector: string, frame: StickyFrame): string {
64
+ const at = (media: string, list: readonly Declaration[] | undefined) => {
65
+ const css = block(selector, list ?? []);
66
+ return css ? `@media ${media}{${css}}` : "";
67
+ };
68
+ return [
69
+ block(selector, frame.declarations),
70
+ at(DEVICE_MEDIA.wide, frame.wide),
71
+ at(DEVICE_MEDIA.laptop, frame.laptop),
72
+ at(DEVICE_MEDIA.tablet, frame.tablet),
73
+ at(DEVICE_MEDIA.mobile, frame.mobile),
74
+ ].join("");
75
+ }
76
+
77
+ /**
78
+ * A theme part's markup in its wrapper (W-216, W-586): a header or footer part is the page's
79
+ * `<header>` or `<footer>` landmark unless it has its own; other parts get a `<div>`. W-1097: a
80
+ * header or footer part with a sticky top-level box gets a sticky wrapper (`css` holds its rules;
81
+ * empty otherwise, so every other part renders exactly as before).
82
+ */
83
+ export function wrapThemePart(
84
+ partType: string,
85
+ partId: string,
86
+ html: string,
87
+ stickyFrame?: StickyFrame,
88
+ ): { html: string; css: string } {
89
+ if (!html) return { html: "", css: "" };
90
+ const landmark = partType === "header" || partType === "footer";
91
+ const ownLandmark = /<(?:header|footer)[\s>]/.test(html);
92
+ const tag = landmark && !ownLandmark ? partType : "div";
93
+ const frame = landmark ? stickyFrame : undefined;
94
+ const className = `emvb-theme-${partType}${frame ? " emvb-theme-sticky" : ""}`;
95
+ const hide = frame?.hide ? ' data-emvb-sticky-hide=""' : "";
96
+ return {
97
+ html: `<${tag} class="${className}" data-emvb-theme-part="${escapeAttr(partId)}"${hide}>${html}</${tag}>`,
98
+ css: frame ? stickyFrameCss(`.emvb-theme-${partType}.emvb-theme-sticky`, frame) : "",
99
+ };
100
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * W-1092 (#34): when EmVB may set the `emvb_seen` cookie that new/returning Visitors rules use.
3
+ * Set from `emvb({ visitorCookie, visitorCookieConsent })` when the plugin starts; read when a
4
+ * page with such a rule renders. Kept on globalThis for the same reason as the geo-header setting
5
+ * (core/geo-trust.ts): the plugin and the page renderer can load this module twice.
6
+ *
7
+ * - `"always"` (default, as before 1.4.1): set it on a first visit to a page with such a rule.
8
+ * - `"consent"`: only when the request carries the site's own consent cookie with an accepted
9
+ * value. Without consent, EmVB neither reads nor sets it and everyone counts as new.
10
+ * - `"never"`: never read or set; everyone counts as new.
11
+ */
12
+ export type VisitorCookieMode = "always" | "consent" | "never";
13
+
14
+ /** The first-party cookie a site's consent banner sets, and the value(s) that mean "yes". */
15
+ export type VisitorCookieConsent = { cookie: string; value?: string | string[] };
16
+
17
+ export type VisitorCookieSetting = {
18
+ mode: VisitorCookieMode;
19
+ /** Only in "consent" mode; without a valid one, "consent" behaves as "never". */
20
+ consent?: { cookie: string; values: string[] };
21
+ };
22
+
23
+ /** Values that count as consent when the site doesn't name its own (compared case-insensitively). */
24
+ const DEFAULT_CONSENT_VALUES = new Set(["1", "true", "yes", "granted", "accepted", "allow", "all"]);
25
+
26
+ /** A cookie name (an RFC 6265 token), as a site owner would type it. */
27
+ const COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]{1,128}$/;
28
+ const MAX_VALUES = 20;
29
+ const MAX_VALUE_LENGTH = 256;
30
+
31
+ const KEY = Symbol.for("emvb.visitorCookie");
32
+ type Holder = { [KEY]?: VisitorCookieSetting };
33
+
34
+ /** The setting from the two options; anything unrecognised falls back to the safe reading. */
35
+ export function visitorCookieSetting(mode: unknown, consent?: unknown): VisitorCookieSetting {
36
+ if (mode === "never") return { mode: "never" };
37
+ if (mode !== "consent") return { mode: "always" };
38
+ const parsed = consentOption(consent);
39
+ return parsed ? { mode: "consent", consent: parsed } : { mode: "never" };
40
+ }
41
+
42
+ function consentOption(input: unknown): VisitorCookieSetting["consent"] {
43
+ if (!input || typeof input !== "object") return undefined;
44
+ const { cookie, value } = input as { cookie?: unknown; value?: unknown };
45
+ if (typeof cookie !== "string" || !COOKIE_NAME.test(cookie.trim())) return undefined;
46
+ const given = (Array.isArray(value) ? value : [value])
47
+ .filter((v): v is string => typeof v === "string")
48
+ .filter((v) => v.length > 0 && v.length <= MAX_VALUE_LENGTH)
49
+ .slice(0, MAX_VALUES);
50
+ if (value !== undefined && given.length === 0) return undefined;
51
+ return { cookie: cookie.trim(), values: value === undefined ? [] : given };
52
+ }
53
+
54
+ /** The options as `emvb()` passes them to the plugin: only what was set, and only when valid. */
55
+ export function visitorCookieOptions(
56
+ mode: unknown,
57
+ consent: unknown,
58
+ ): { visitorCookie?: VisitorCookieMode; visitorCookieConsent?: VisitorCookieConsent } {
59
+ if (mode !== "always" && mode !== "consent" && mode !== "never") return {};
60
+ const setting = visitorCookieSetting(mode, consent);
61
+ if (setting.mode !== "consent" || !setting.consent) return { visitorCookie: setting.mode };
62
+ const { cookie, values } = setting.consent;
63
+ return {
64
+ visitorCookie: "consent",
65
+ visitorCookieConsent: values.length > 0 ? { cookie, value: values } : { cookie },
66
+ };
67
+ }
68
+
69
+ export function setVisitorCookie(mode: unknown, consent?: unknown): void {
70
+ (globalThis as Holder)[KEY] = visitorCookieSetting(mode, consent);
71
+ }
72
+
73
+ export function visitorCookie(): VisitorCookieSetting {
74
+ return (globalThis as Holder)[KEY] ?? { mode: "always" };
75
+ }
76
+
77
+ /**
78
+ * Whether this request may read and set `emvb_seen`. `readCookie` returns a cookie as the
79
+ * browser sent it. The site's named values match exactly; the defaults ignore case.
80
+ */
81
+ export function visitorCookieAllowed(
82
+ setting: VisitorCookieSetting,
83
+ readCookie: (name: string) => string | undefined,
84
+ ): boolean {
85
+ if (setting.mode === "always") return true;
86
+ if (setting.mode === "never" || !setting.consent) return false;
87
+ const sent = readCookie(setting.consent.cookie);
88
+ if (sent === undefined) return false;
89
+ if (setting.consent.values.length > 0) return setting.consent.values.includes(sent);
90
+ return DEFAULT_CONSENT_VALUES.has(sent.trim().toLowerCase());
91
+ }