import { _ } from '@evershop/evershop/lib/locale/translate/_';
import React, { useEffect, useRef, useState } from 'react';
import { computeMoveSortOrder } from './dropSortOrder.js';
import { isInPageBuilderIframe, postToParent } from './pageBuilderMode.js';
import { WidgetContextProvider } from './WidgetContext.js';
const CHROME_STYLE_ID = 'evershop-pb-chrome-style';
const CHROME_CSS = `
[data-evershop-pb-widget-uid] { transition: outline-color 0.12s ease; outline: 2px solid transparent; outline-offset: -2px; }
[data-evershop-pb-widget-uid]:hover { outline-color: rgba(0, 128, 95, 0.45); }
[data-evershop-pb-widget-uid][data-evershop-pb-selected="true"] { outline-color: rgba(0, 128, 95, 0.95); }
/* Set by PageBuilderBridge on receipt of a 'layer-highlight' message —
clicking a row in the admin's Layers tab highlights the matching widget
in the iframe and scrolls it into view. Same outline color as :hover so
the affordance reads identically. Cleared on body click. */
[data-evershop-pb-widget-uid][data-evershop-pb-layer-hover="true"] {
outline-color: rgba(0, 128, 95, 0.45);
}
[data-evershop-pb-widget-uid] > [data-evershop-pb-toolbar] {
opacity: 0;
pointer-events: none;
transition: opacity 0.12s ease;
}
[data-evershop-pb-widget-uid]:hover > [data-evershop-pb-toolbar],
[data-evershop-pb-widget-uid][data-evershop-pb-selected="true"] > [data-evershop-pb-toolbar],
[data-evershop-pb-widget-uid][data-evershop-pb-layer-hover="true"] > [data-evershop-pb-toolbar] {
opacity: 1;
pointer-events: auto;
}
/* Drop zones — visible only while a page-builder drag is in flight. The
::before pseudo-element renders a corner badge with the area id, sourced
from the zone's data-evershop-pb-area attribute. Page-scoped areas use
the editor's accent green; global areas (data-evershop-global) flip to
violet, matching the demo's "globals are violet" convention. */
[data-evershop-pb-dropzone] {
position: relative;
margin: 0;
background: transparent;
border-radius: 4px;
transition: background 0.12s ease, height 0.12s ease, margin 0.12s ease;
pointer-events: none;
}
body[data-evershop-pb-drag="true"] [data-evershop-pb-dropzone] {
height: 32px;
margin: 6px 0;
background: rgba(0, 128, 95, 0.10);
border: 2px dashed rgba(0, 128, 95, 0.35);
pointer-events: auto;
}
body[data-evershop-pb-drag="true"] [data-evershop-pb-dropzone][data-evershop-pb-active="true"] {
background: rgba(0, 128, 95, 0.25);
border-color: rgba(0, 128, 95, 0.85);
}
/* Area-id badge in the top-left corner of each drop zone, only when a
drag is in flight. */
body[data-evershop-pb-drag="true"] [data-evershop-pb-dropzone][data-evershop-pb-area]::before {
content: attr(data-evershop-pb-area);
position: absolute;
top: 0;
left: 0;
z-index: 1;
padding: 2px 6px;
background: #00805f;
color: #ffffff;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
border-radius: 0 0 4px 0;
pointer-events: none;
line-height: 1;
}
/* Global-area variant: same shape, violet palette. Descendant selector
piggybacks on Area's data-evershop-global attribute so no extra prop
threading is needed — drop zones inside global Areas (header / footer /
etc.) get the violet treatment automatically. */
body[data-evershop-pb-drag="true"] [data-evershop-global="true"] [data-evershop-pb-dropzone] {
background: rgba(124, 58, 237, 0.10);
border-color: rgba(124, 58, 237, 0.35);
}
body[data-evershop-pb-drag="true"] [data-evershop-global="true"] [data-evershop-pb-dropzone][data-evershop-pb-active="true"] {
background: rgba(124, 58, 237, 0.25);
border-color: rgba(124, 58, 237, 0.85);
}
body[data-evershop-pb-drag="true"] [data-evershop-global="true"] [data-evershop-pb-dropzone][data-evershop-pb-area]::before {
background: #7c3aed;
}
/* Collapse the drop zone that follows an EMPTY renderable wrapper. A
layout component that renders null (e.g. Breadcrumb on the homepage,
where there are no breadcrumbs) still gets its display:contents
sort-order wrapper + trailing zone from Area.tsx — without this rule
two bands would stack at the same visual position (the empty wrapper
paints nothing between them). Hiding the trailing zone loses nothing:
both seams sit between the same visible neighbors, so a drop on the
surviving one lands identically. Widget wrappers are never :empty
(they always contain the chrome toolbar). */
body[data-evershop-pb-drag="true"] [data-evershop-pb-sort-order]:empty + [data-evershop-pb-dropzone] {
display: none;
}
`;
/**
* Inject the page-builder chrome stylesheet (widget outlines, toolbar
* visibility, and — critically — the `[data-evershop-pb-dropzone]` sizing /
* visibility rules) once per document. Idempotent via the element-id guard.
*
* Exported because the drop-zone rules must exist even on a route with **no
* widgets** (a fresh store): `WidgetChrome` only mounts per existing widget,
* so `PageBuilderBridge` (always mounted in the iframe) also calls this to
* guarantee the stylesheet is present regardless of widget count.
*/
export function ensureChromeStyleInjected(): void {
if (typeof document === 'undefined') return;
if (document.getElementById(CHROME_STYLE_ID)) return;
const el = document.createElement('style');
el.id = CHROME_STYLE_ID;
el.textContent = CHROME_CSS;
document.head.appendChild(el);
}
// Tiny SVG icon set inlined so the iframe doesn't need to load lucide.
// Sizes are fixed at 14px to match the demo's toolbar density.
function ArrowUpIcon(): React.ReactElement {
return (
);
}
function ArrowDownIcon(): React.ReactElement {
return (
);
}
function CopyIcon(): React.ReactElement {
return (
);
}
function SettingsIcon(): React.ReactElement {
return (
);
}
function TrashIcon(): React.ReactElement {
return (
);
}
const TONE_COLOR: Record<'neutral' | 'accent' | 'danger', string> = {
neutral: 'hsl(215, 16%, 32%)',
accent: '#00805f',
danger: '#e53935'
};
function ChromeIconButton({
label,
tone = 'neutral',
onClick,
children
}: {
label: string;
tone?: 'neutral' | 'accent' | 'danger';
onClick: () => void;
children: React.ReactNode;
}): React.ReactElement {
return (
);
}
/**
* Wraps each widget render in the page-builder iframe with selection
* affordances and a hover toolbar (Settings / Delete). Outside the iframe
* (production storefront), it renders `children` unchanged with no extra
* markup or context — zero overhead.
*
* Drop zones are NOT emitted here — `Area.tsx` owns every seam (one
* `AreaDropZone` after each renderable, widget or layout component, plus
* the area-start zone). The chrome's only drop-related duty is carrying
* `data-evershop-pb-sort-order` on the wrapper so zones can walk it.
*
* Selection / delete are delivered to the admin via same-origin postMessage:
* - { type: 'widget-selected', widgetUid, widgetType, settings }
* - { type: 'widget-delete', widgetUid }
*
* The admin (`Editor.tsx`) listens and dispatches drawer / DELETE-op flows.
*/
interface WidgetChromeProps {
uuid: string;
type: string;
/**
* The Area id this widget render is attached to. A single widget can have
* multiple placements across areas; the toolbar messages include this so
* the admin handler operates on the right placement.
*/
area: string;
/**
* The placement's sort_order. Surfaced as `data-evershop-pb-sort-order`
* on the wrapper so adjacent drop zones can walk DOM siblings and read
* the value when computing where a new drop should land.
*/
sortOrder: number;
settings: Record;
children: React.ReactNode;
}
export function WidgetChrome({
uuid,
type,
area,
sortOrder,
settings,
children
}: WidgetChromeProps): React.ReactElement {
// SSR-stable: first render passes through identically to production.
const [isClient, setIsClient] = useState(false);
const wrapperRef = useRef(null);
useEffect(() => {
setIsClient(true);
}, []);
// Move up / down. Iframe owns the math (same rule as drops): compute the
// target sort_order from the rendered sibling order — layout components
// included — and send it in the message; the admin emits one UPDATE op
// with the value verbatim. Already first / last → null → nothing to move
// past, no message.
const postMove = (direction: 'up' | 'down') => {
const el = wrapperRef.current;
const nextSort = el ? computeMoveSortOrder(el, direction) : null;
if (nextSort == null) return;
postToParent({
type: direction === 'up' ? 'widget-move-up' : 'widget-move-down',
widgetUid: uuid,
area,
sortOrder: nextSort
});
};
const inIframe = isClient && isInPageBuilderIframe();
// Inject the chrome stylesheet ONCE per document instead of per widget.
// Also subscribe to drag-start/drag-end messages from the admin so drop
// zones in the document can react via the body[data-evershop-pb-drag]
// attribute (CSS handles the visual states).
useEffect(() => {
if (!inIframe) return;
ensureChromeStyleInjected();
const onMsg = (event: MessageEvent) => {
if (event.origin !== window.location.origin) return;
const data: any = event.data;
if (!data) return;
if (data.type === 'pb-drag-start') {
document.body.setAttribute('data-evershop-pb-drag', 'true');
} else if (data.type === 'pb-drag-end') {
document.body.removeAttribute('data-evershop-pb-drag');
}
};
window.addEventListener('message', onMsg);
return () => window.removeEventListener('message', onMsg);
}, [inIframe]);
if (!inIframe) {
// Production / non-page-builder: just provide widget context (cheap, no DOM).
return (
{children}
);
}
return (