@perkyzz/emvb 1.4.1 → 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.
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  [![Website](https://img.shields.io/badge/website-emvb.dev-1f6feb)](https://emvb.dev) [![npm](https://img.shields.io/npm/v/@perkyzz/emvb)](https://www.npmjs.com/package/@perkyzz/emvb)
13
13
 
14
- A visual page builder plugin for [EmDash CMS](https://github.com/emdash-cms/emdash) 1.4 and 1.5 (built and tested on 1.5.0, tested on 1.4.0). Pages are built in a full-screen editor inside the EmDash admin and published as plain HTML and CSS. It runs on Node (SQLite) and Cloudflare Workers (D1).
14
+ A visual page builder plugin for [EmDash CMS](https://github.com/emdash-cms/emdash) 1.4, 1.5 and 1.6. Pages are built in a full-screen editor inside the EmDash admin and published as plain HTML and CSS. It runs on Node (SQLite) and Cloudflare Workers (D1).
15
15
 
16
16
  ![The EmVB editor](https://raw.githubusercontent.com/PerkyZZ999/EmVB/main/site/public/screenshots/editor-1600.webp)
17
17
 
@@ -25,7 +25,7 @@ Library pictures can be cropped, adjusted, filtered and saved as a new media ite
25
25
  npm i @perkyzz/emvb
26
26
  ```
27
27
 
28
- Peers, which an EmDash 1.4 or 1.5 site already has: `emdash` >=1.4.0 <2, `astro` ^7, `react` and `react-dom` ^19, `@cloudflare/kumo` 2.6.0 (EmDash 1.4) or 2.15.0 (EmDash 1.5) and `@phosphor-icons/react` ^2.1.10. `@emdash-cms/plugin-forms` is optional and enables forms: 0.2.13 on EmDash 1.5, 0.2.9 to 0.2.12 on EmDash 1.4. Use the Astro version your EmDash site already has: each release is installed on stock `create-emdash` sites of EmDash 1.4.0 and 1.5.0.
28
+ EmDash 1.4–1.6 sites provide the required peers: `emdash` >=1.4.0 <2, `astro` ^7, `react` and `react-dom` ^19, `@phosphor-icons/react` ^2.1.10 and the exact `@cloudflare/kumo` version each EmDash release pins (2.6.0, 2.15.0 and 2.19.0 respectively). For forms, install `@emdash-cms/plugin-forms` 0.2.9–0.2.12 on 1.4, 0.2.13 on 1.5 or 0.2.14 on 1.6. Keep the Astro version your site's scaffold installs. Releases get stock-install smoke tests on 1.4.0, 1.5.0 and 1.6.0.
29
29
 
30
30
  Dependencies installed with it: `zod` and [`@perkyzz/emvb-icons`](https://www.npmjs.com/package/@perkyzz/emvb-icons), the icon sets for the editor's Icon library. Only the editor loads them; a placed icon is saved into the page as SVG.
31
31
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@perkyzz/emvb",
3
- "version": "1.4.1",
3
+ "version": "1.4.2",
4
4
  "description": "Visual page builder plugin for EmDash CMS",
5
5
  "keywords": [
6
6
  "astro",
@@ -50,24 +50,24 @@
50
50
  "test:astro": "bun --bun vitest run"
51
51
  },
52
52
  "dependencies": {
53
- "@perkyzz/emvb-icons": "1.4.1",
53
+ "@perkyzz/emvb-icons": "1.4.2",
54
54
  "photocn": "0.1.2",
55
55
  "zod": ">=4.5.4 <5"
56
56
  },
57
57
  "devDependencies": {
58
- "@cloudflare/kumo": "2.15.0",
59
- "@emdash-cms/plugin-forms": "0.2.13",
58
+ "@cloudflare/kumo": "2.19.0",
59
+ "@emdash-cms/plugin-forms": "0.2.14",
60
60
  "@phosphor-icons/react": "2.1.10",
61
61
  "@types/react": "19.3.0",
62
62
  "@types/react-dom": "19.3.0",
63
63
  "astro": "7.4.12",
64
- "emdash": "1.5.0",
64
+ "emdash": "1.6.0",
65
65
  "react": "19.3.1",
66
66
  "react-dom": "19.3.1",
67
67
  "vitest": "5.1.0"
68
68
  },
69
69
  "peerDependencies": {
70
- "@cloudflare/kumo": "2.6.0 || 2.15.0",
70
+ "@cloudflare/kumo": "2.6.0 || 2.15.0 || 2.19.0",
71
71
  "@emdash-cms/plugin-forms": "^0.2.9",
72
72
  "@phosphor-icons/react": "^2.1.10",
73
73
  "astro": "^7.0.0",
@@ -7,6 +7,7 @@ import {
7
7
  type DesignSystem,
8
8
  type FormDefinitions,
9
9
  type Layout,
10
+ type StickyFrame,
10
11
  type ThemeDynamicData,
11
12
  } from "../core/index.ts";
12
13
  import type { PageRuntime } from "../core/elements/widgets.ts";
@@ -32,6 +33,8 @@ export type RenderedPage = {
32
33
  * `EmVBPage` and the theme parts' `css` write each once per response.
33
34
  */
34
35
  extensions?: string[];
36
+ /** W-1097: a theme part's sticky top-level box, for its wrapper (`wrapThemePart`). */
37
+ stickyFrame?: StickyFrame;
35
38
  };
36
39
 
37
40
  /** The design document through the in-process public route (no HTTP round trip, D-013). */
@@ -140,6 +143,7 @@ export function renderStored(
140
143
  baseTypes,
141
144
  runtimes,
142
145
  extensions,
146
+ stickyFrame,
143
147
  } = result;
144
148
  for (const warning of result.warnings) {
145
149
  if (warning.code !== "refused-markup") continue;
@@ -156,5 +160,6 @@ export function renderStored(
156
160
  ...(extensions.length > 0 ? { extensions } : {}),
157
161
  ...(design.direction ? { dir: design.direction } : {}),
158
162
  baseTypes,
163
+ ...(stickyFrame ? { stickyFrame } : {}),
159
164
  };
160
165
  }
@@ -2,7 +2,6 @@ import { emdashContent, type ContentPort } from "./content-port.ts";
2
2
  import { formIdsInLayouts } from "./forms-definitions.ts";
3
3
  import {
4
4
  collectLoopItemPartIds,
5
- escapeAttr,
6
5
  collectSectionPartIds,
7
6
  contentPartTypeForContext,
8
7
  defaultConditions,
@@ -20,6 +19,7 @@ import {
20
19
  validateTriggers,
21
20
  wrapFloatMarkup,
22
21
  wrapPopupMarkup,
22
+ wrapThemePart,
23
23
  type ChromeLabels,
24
24
  type FloatSettings,
25
25
  type Layout,
@@ -47,12 +47,6 @@ import { decodePathSegment, themeContextFrom } from "./theme-context.ts";
47
47
  import { entryTimestamp, themePostFromEntry } from "./theme-posts.ts";
48
48
  import { probeCounter, totalPagesFor, type PostCounter } from "./page-count.ts";
49
49
 
50
- /** The landmark element for a part's wrapper (W-216); other parts get a plain div. */
51
- const WRAPPER_TAGS: Partial<Record<string, "header" | "footer">> = {
52
- header: "header",
53
- footer: "footer",
54
- };
55
-
56
50
  export type RenderedThemePart = {
57
51
  id: string;
58
52
  title: string;
@@ -559,6 +553,8 @@ export async function resolveThemePartsWith(
559
553
  const rendered: RenderedPage[] = [];
560
554
  // W-971: each part's scoped sheet, to write the shared rules once in `css`.
561
555
  const sheets = new Map<string, { css: string; scope: string; baseTypes: readonly string[] }>();
556
+ // W-1097: sticky header and footer wrappers' rules, after the parts' own sheets.
557
+ const wrapperCss: string[] = [];
562
558
  // W-307: bound fields in a part read site settings and URL parameters too.
563
559
  // W-312/W-313: synced sections and Loop items the part uses count too.
564
560
  const boundFor = (stored: StoredPart, referenced: ThemeDynamicData | undefined) =>
@@ -608,14 +604,14 @@ export async function resolveThemePartsWith(
608
604
  // straight in <body> instead of their own <header>/<footer>).
609
605
  // W-586: a part that already has its own header or footer box keeps that one as the landmark;
610
606
  // a second wrapper around it would nest <header> in <header> (invalid, two banners).
611
- const ownLandmark = /<(?:header|footer)[\s>]/.test(page.html);
612
- const tag = (!ownLandmark && WRAPPER_TAGS[stored.partType]) || "div";
613
- const partId = escapeAttr(stored.id);
614
- const html = page.html
615
- ? `<${tag} class="emvb-theme-${stored.partType}" data-emvb-theme-part="${partId}">${page.html}</${tag}>`
616
- : "";
607
+ // W-1097: a sticky top-level box makes the wrapper sticky (`wrapper.css`, else empty).
608
+ const wrapper = wrapThemePart(stored.partType, stored.id, page.html, page.stickyFrame);
609
+ if (wrapper.css) wrapperCss.push(wrapper.css);
617
610
  // W-1086: a part's own css stays whole; the shared `css` below writes extension sheets once.
618
- return { html, css: page.css + extensionStylesheets(page.extensions ?? []) };
611
+ return {
612
+ html: wrapper.html,
613
+ css: page.css + extensionStylesheets(page.extensions ?? []) + wrapper.css,
614
+ };
619
615
  };
620
616
 
621
617
  /** Synced sections and loop items a part uses, for every part type (W-200). */
@@ -756,7 +752,7 @@ export async function resolveThemePartsWith(
756
752
  const sheet = part ? sheets.get(part.id) : undefined;
757
753
  return sheet ? [sheet] : [];
758
754
  });
759
- const cssParts = [sharedPartCss(ordered)];
755
+ const cssParts = [sharedPartCss(ordered), ...wrapperCss];
760
756
  // W-1086: each extension stylesheet once for all the parts; the page in this response skips them.
761
757
  const extensionIds = [...new Set(rendered.flatMap((page) => page.extensions ?? []))].toSorted();
762
758
  cssParts.push(extensionStylesheets(extensionIds));
@@ -46,8 +46,11 @@ function heldAtBottom(el: HTMLElement): boolean {
46
46
  }
47
47
 
48
48
  export function initSticky(root: ParentNode = document): void {
49
+ // W-1097: a sticky header or footer part's wrapper hides for its box; the box stays in it.
49
50
  const all = [...root.querySelectorAll<HTMLElement>("[data-emvb-sticky-hide]")].filter(
50
- (el) => el.dataset["emvbReady"] === undefined,
51
+ (el) =>
52
+ el.dataset["emvbReady"] === undefined &&
53
+ !el.parentElement?.closest("[data-emvb-sticky-hide]"),
51
54
  );
52
55
  if (all.length === 0) return;
53
56
  const reduced = globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
package/src/constants.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export const PLUGIN_ID = "emvb";
2
- export const PLUGIN_VERSION = "1.4.1";
2
+ export const PLUGIN_VERSION = "1.4.2";
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";
@@ -14,6 +14,6 @@ export const EXPORT_RUNTIMES = {
14
14
  map: "(()=>{var r=/^https:\\/\\/www\\.(?:openstreetmap\\.org\\/export\\/embed\\.html|google\\.com\\/maps)\\?/;function s(t){let o=t.dataset.src??\"\";if(!r.test(o))return;let e=t.ownerDocument.createElement(\"iframe\");e.setAttribute(\"sandbox\",\"allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox\"),e.src=o,e.title=t.dataset.title||\"Map\",e.height=t.dataset.height||\"360\",e.loading=\"lazy\",e.referrerPolicy=\"no-referrer-when-downgrade\",t.replaceChildren(e),e.focus()}function a(t=document){for(let o of t.querySelectorAll(\"[data-emvb-map]\")){if(o.dataset.emvbReady!==void 0)continue;let e=o.querySelector(\".emvb-map-frame\"),n=e?.querySelector(\".emvb-map-load\");if(!e||!n)continue;o.dataset.emvbReady=\"\",n.addEventListener(\"click\",()=>s(e))}}a();})();",
15
15
  headline: "(()=>{function v(e){let t;try{t=JSON.parse(e.dataset.emvbRotate??\"\")}catch{return}if(!Array.isArray(t))return;let n=t.filter((a)=>typeof a===\"string\"&&a.trim()!==\"\");if(n.length<2)return;let o=Number(e.dataset.interval),r=Number(e.dataset.turns);return{words:n,interval:Number.isFinite(o)?Math.min(10,Math.max(1.5,o)):2.5,turns:Number.isFinite(r)?Math.min(5,Math.max(1,Math.round(r))):2}}function p(e,t){let n=e.ownerDocument,o=e.closest(\"h1, h2, h3, h4, h5, h6\")??e,r=[...e.childNodes].find((s)=>s.nodeType===Node.TEXT_NODE);if(!r)return;let a=r,d=n.createElement(\"span\");d.className=\"emvb-headline-sr\",d.textContent=t.words[0]??\"\",e.before(d),e.setAttribute(\"aria-hidden\",\"true\");let i=n.createElement(\"button\");i.type=\"button\",i.className=\"emvb-headline-pause\",i.setAttribute(\"aria-pressed\",\"false\"),i.textContent=\"Pause\",o.after(i);let u=0,m=t.words.length*t.turns,h=setInterval(()=>{if(u++,a.textContent=t.words[u%t.words.length]??\"\",u<m)return;let s=n.activeElement===i,b=i.nextElementSibling;if(c(),s)l(b)},t.interval*1000);function c(){clearInterval(h),a.textContent=t.words[0]??\"\",e.removeAttribute(\"aria-hidden\"),d.remove(),i.remove()}function l(s){if(s instanceof HTMLElement&&s.matches(\"a[href], button, input, select, textarea, [tabindex]\"))s.focus();else if(o instanceof HTMLElement)o.tabIndex=-1,o.focus()}i.addEventListener(\"click\",()=>{let s=i.nextElementSibling;c(),l(s)})}function f(e=document){if(globalThis.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches===!0)return;for(let n of e.querySelectorAll(\"[data-emvb-rotate]\")){if(n.dataset.emvbReady!==void 0)continue;n.dataset.emvbReady=\"\";let o=v(n);if(o)p(n,o)}}f();})();",
16
16
  share: "(()=>{function o(a=document){let e=globalThis.navigator;if(typeof e?.share!==\"function\")return;for(let t of a.querySelectorAll(\"[data-emvb-share-list]\")){if(t.dataset.emvbReady!==void 0)continue;t.dataset.emvbReady=\"\",t.querySelector(\"[data-emvb-share]\")?.addEventListener(\"click\",()=>{let n=t.ownerDocument;e.share({title:n.title,url:n.location.href.split(\"#\")[0]}).catch(()=>{})})}}o();})();",
17
- sticky: "(()=>{function d(e,t,o){let i=e.style.translate;if(i===t)return;if(e.style.translate=t,o||typeof e.animate!==\"function\")return;e.animate([{translate:i||\"0 0\"},{translate:t||\"0 0\"}],{duration:250,easing:\"ease\"})}function s(e,t){delete e.dataset.emvbAway,d(e,\"\",t)}function u(e){return e.getPropertyValue(\"--emvb-sticky-hide\").trim()!==\"0\"}function y(e){let{top:t,height:o}=e.getBoundingClientRect();return t+o/2>globalThis.innerHeight/2}function c(e=document){let t=[...e.querySelectorAll(\"[data-emvb-sticky-hide]\")].filter((n)=>n.dataset.emvbReady===void 0);if(t.length===0)return;let o=globalThis.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches===!0;for(let n of t)n.dataset.emvbReady=\"\",n.addEventListener(\"focusin\",()=>s(n,o));let i=globalThis.scrollY,l=0,m=()=>{let n=globalThis.scrollY;if(Math.abs(n-i)<4)return;let r=n>i;i=n;for(let a of t){let f=getComputedStyle(a);if(!u(f)){if(a.dataset.emvbAway!==void 0)s(a,o)}else if(r&&n>a.offsetHeight&&!a.contains(document.activeElement)){if(a.dataset.emvbAway!==void 0)continue;a.dataset.emvbAway=\"\",d(a,y(a)?\"0 100%\":\"0 -100%\",o)}else if(!r)s(a,o)}};globalThis.addEventListener(\"scroll\",()=>{cancelAnimationFrame(l),l=requestAnimationFrame(m)},{passive:!0})}c();})();",
17
+ sticky: "(()=>{function d(e,t,i){let o=e.style.translate;if(o===t)return;if(e.style.translate=t,i||typeof e.animate!==\"function\")return;e.animate([{translate:o||\"0 0\"},{translate:t||\"0 0\"}],{duration:250,easing:\"ease\"})}function s(e,t){delete e.dataset.emvbAway,d(e,\"\",t)}function u(e){return e.getPropertyValue(\"--emvb-sticky-hide\").trim()!==\"0\"}function y(e){let{top:t,height:i}=e.getBoundingClientRect();return t+i/2>globalThis.innerHeight/2}function c(e=document){let t=[...e.querySelectorAll(\"[data-emvb-sticky-hide]\")].filter((n)=>n.dataset.emvbReady===void 0&&!n.parentElement?.closest(\"[data-emvb-sticky-hide]\"));if(t.length===0)return;let i=globalThis.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches===!0;for(let n of t)n.dataset.emvbReady=\"\",n.addEventListener(\"focusin\",()=>s(n,i));let o=globalThis.scrollY,l=0,m=()=>{let n=globalThis.scrollY;if(Math.abs(n-o)<4)return;let r=n>o;o=n;for(let a of t){let f=getComputedStyle(a);if(!u(f)){if(a.dataset.emvbAway!==void 0)s(a,i)}else if(r&&n>a.offsetHeight&&!a.contains(document.activeElement)){if(a.dataset.emvbAway!==void 0)continue;a.dataset.emvbAway=\"\",d(a,y(a)?\"0 100%\":\"0 -100%\",i)}else if(!r)s(a,i)}};globalThis.addEventListener(\"scroll\",()=>{cancelAnimationFrame(l),l=requestAnimationFrame(m)},{passive:!0})}c();})();",
18
18
  theme: "(()=>{var n=\"emvb-theme\";function s(){try{let e=localStorage.getItem(n);return e===\"light\"||e===\"dark\"?e:null}catch{return null}}var d=()=>globalThis.matchMedia?.(\"(prefers-color-scheme: dark)\").matches===!0,c=()=>{let e=document.documentElement.dataset.emvbTheme;return e===\"dark\"||e!==\"light\"&&d()};function r(){let e=String(c());for(let t of document.querySelectorAll(\"[data-emvb-theme-toggle]\"))t.setAttribute(\"aria-pressed\",e)}function m(e=document){let t=s();if(t)document.documentElement.dataset.emvbTheme=t;for(let o of e.querySelectorAll(\"[data-emvb-theme-toggle]\")){if(o.dataset.emvbReady!==void 0)continue;o.dataset.emvbReady=\"\",o.addEventListener(\"click\",()=>{let a=c()?\"light\":\"dark\";document.documentElement.dataset.emvbTheme=a;try{localStorage.setItem(n,a)}catch{}r()})}globalThis.matchMedia?.(\"(prefers-color-scheme: dark)\").addEventListener?.(\"change\",r),r()}m();})();",
19
19
  } as const;
@@ -24,6 +24,7 @@ import {
24
24
  validateTriggers,
25
25
  wrapFloatMarkup,
26
26
  wrapPopupMarkup,
27
+ wrapThemePart,
27
28
  type ConditionsDoc,
28
29
  type DesignSystem,
29
30
  type FloatSettings,
@@ -365,17 +366,9 @@ export function buildSiteExport(input: {
365
366
  ...extensionOutputs,
366
367
  });
367
368
  if (scopeOnly) return result;
368
- const ownLandmark = /<(?:header|footer)[\s>]/.test(result.html);
369
- const tag =
370
- !ownLandmark && (part.partType === "header" || part.partType === "footer")
371
- ? part.partType
372
- : "div";
373
- return {
374
- ...result,
375
- html: result.html
376
- ? `<${tag} class="emvb-theme-${part.partType}" data-emvb-theme-part="${escapeAttr(part.id)}">${result.html}</${tag}>`
377
- : "",
378
- };
369
+ // W-1097: the same wrapper as the live site, sticky when the part's top-level box is.
370
+ const wrapper = wrapThemePart(part.partType, part.id, result.html, result.stickyFrame);
371
+ return { ...result, html: wrapper.html, css: result.css + wrapper.css };
379
372
  };
380
373
 
381
374
  for (const page of input.pages) {
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,
@@ -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";
@@ -113,6 +114,11 @@ export type RenderResult = {
113
114
  * stylesheets are not in `css`; write `extensionStylesheets(ids)` once per document instead.
114
115
  */
115
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;
116
122
  };
117
123
 
118
124
  const ID = /^[A-Za-z0-9_-]{4,24}$/;
@@ -416,6 +422,9 @@ export function renderPage(
416
422
  // W-1086: the extensions whose elements rendered, for their stylesheet and runtime.
417
423
  const extensionsUsed = new Set<string>();
418
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;
419
428
  const ctx: RenderContext = {
420
429
  takeSectionBudget: (nodes) => {
421
430
  if (nodes > sectionBudget) return false;
@@ -788,6 +797,11 @@ export function renderPage(
788
797
  attrs["data-emvb-sticky-hide"] = "";
789
798
  runtimes.add("sticky");
790
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
+ }
791
805
  // W-1067: the canvas runs no widget scripts, so a Theme toggle waiting for its own stayed
792
806
  // hidden there; the editor shows it as it looks once ready.
793
807
  if (mode === "editor" && type === "theme-toggle") attrs["data-emvb-ready"] = "";
@@ -977,6 +991,7 @@ export function renderPage(
977
991
  warnings,
978
992
  baseTypes: [...usedTypes],
979
993
  extensions,
994
+ ...(stickyFrame ? { stickyFrame } : {}),
980
995
  };
981
996
  }
982
997
 
@@ -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
+ }