import { FileBrowser } from '@components/admin/FileBrowser.js'; import { normalizeImageSrc } from '@components/common/page-builder/normalizeImageSrc.js'; import { Toaster, toast } from '@components/common/ui/Sonner.js'; import { _ } from '@evershop/evershop/lib/locale/translate/_'; import axios from 'axios'; import { ChevronLeft, ChevronRight, Eye, FileText, Globe, Layers, Monitor, PuzzleIcon, Redo2, Search, Smartphone, Tablet, Undo2 } from 'lucide-react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { FormProvider, useForm, useWatch } from 'react-hook-form'; import { useClient, useQuery } from 'urql'; import { v4 as uuidv4 } from 'uuid'; import { cursorsEqual } from '../../../components/cursorsEqual.js'; import { DeviceButton, type DeviceMode } from '../../../components/DeviceButton.js'; import { EntityScopeSelector } from '../../../components/EntityScopeSelector.js'; import { LayerNode, type LayerWidget } from '../../../components/LayerNode.js'; import { LeftTabButton } from '../../../components/LeftTabButton.js'; import { PageSwitcher } from '../../../components/PageSwitcher.js'; import { PrimaryActionButton } from '../../../components/PrimaryActionButton.js'; import { SessionModeBadge } from '../../../components/SessionModeBadge.js'; import { getWidgetIcon } from '../../../components/widgetIcons.js'; import { WidgetPreviewCard } from '../../../components/WidgetPreviewCard.js'; import { ConfirmDialog } from './ConfirmDialog.js'; import { DiscardConfirmDialog } from './DiscardConfirmDialog.js'; import { ExitConfirmDialog } from './ExitConfirmDialog.js'; import MetafieldGuideDrawer, { type MetafieldSelection } from './MetafieldGuideDrawer.js'; import { PublishDialog } from './PublishDialog.js'; import { RolloutDialog } from './RolloutDialog.js'; import { SessionPicker } from './SessionPicker.js'; import { SettingsDrawer } from './SettingsDrawer.js'; const CHANGESET_OPS_QUERY = ` query ChangesetOps($id: Int!) { changeset(id: $id) { changesetId operations { entityUrn oldPayload newPayload route } } } `; const LAYERS_QUERY = ` query LayersForRoute($route: String!, $changeset: String, $entityUrn: String) { widgetsForRoute(route: $route, changeset: $changeset, entityUrn: $entityUrn) { uuid name type rawSettings placements { uuid route area sortOrder } columns { index widgets { uuid name type rawSettings placements { uuid route area sortOrder } } } } } `; const PAGES_QUERY = ` query Pages { routes { id name path isApi isAdmin editableInPageBuilder } } `; // Entity-scope selector source (spec 03 § 4.2). Generic list of the current // route's scopable entities (e.g. landing pages), served by the entity-scope // registry; fetched client-side only when the route is entity-scoped (see the // `pause` on its useQuery below). const PAGE_BUILDER_SCOPE_ENTITIES_QUERY = ` query PageBuilderScopeEntities($routeId: String!) { pageBuilderScopeEntities(routeId: $routeId) { uuid name urlKey urn status } } `; // Used by the SessionPicker (spec § 7.8) to surface upcoming + currently // live rollout plans the user might want to resume editing. Past plans are // filtered out client-side. // // `DateTime` is a GraphQL **type**, not a scalar (see // modules/base/graphql/types/DateTime/DateTime.graphql), so we have to // select a sub-field. `text(format: "...")` returns a luxon-formatted // string the JS `Date` constructor can parse directly. const ROLLOUT_PLANS_QUERY = ` query RolloutPlans { rolloutPlans { rolloutPlanId uuid name startTime { text(format: "yyyy-LL-dd'T'HH:mm:ssZZ") } endTime { text(format: "yyyy-LL-dd'T'HH:mm:ssZZ") } } } `; type LeftTab = 'widgets' | 'pages' | 'layers'; const DEVICE_WIDTHS: Record = { desktop: null, tablet: '768px', phone: '375px' }; interface WidgetType { code: string; name: string; description: string; category: string | null; /** Optional lucide icon name; resolved via `getWidgetIcon`. */ icon: string | null; defaultSetting: Record | null; } const WIDGET_CATEGORIES: Array<{ key: string; label: string }> = [ { key: 'content', label: _('Content') }, { key: 'commerce', label: _('Commerce') }, { key: 'navigation', label: _('Navigation') }, { key: 'marketing', label: _('Marketing') }, { key: 'layout', label: _('Layout') }, { key: 'other', label: _('Other') } ]; interface RouteInfo { id: string; name: string; path: string; /** * Concrete URL the page-builder iframe loads. For static routes this * matches `path`; for routes with URL params (e.g. `/category/:uuid`) * the resolver substitutes a sample entity. May be null when the * backend has nothing to sample. */ previewPath?: string | null; /** * Non-null when the route has an entity dimension the page builder can * scope to (e.g. `cmsPageView` → every CMS page). Drives the topbar entity * selector. `listQuery` names the GraphQL query enumerating the entities. */ entityScope?: { type: string; listQuery: string } | null; } interface ChangesetInfo { changesetId: number; uuid: string; token: string; /** * Per-route undo/redo cursors as a JSON object. Used to diff against * `rolloutPlan.routeCursors` for the Save-enabled state in rollout mode. */ routeCursors: Record; /** * Set when the user is editing a rollout plan's underlying changeset * (entered the editor via `?session=` from SessionPicker). * Null when editing the user's draft. Drives the topbar SessionModeBadge * appearance and the publish-button-becomes-Save rename. */ rolloutPlan?: { rolloutPlanId: number; uuid: string; name: string; /** * Snapshot of route_cursors at Save time. The live storefront overlay * filters by this; the editor diffs against `changeset.routeCursors` * to decide whether Save is enabled. */ routeCursors: Record; /** ISO 8601 string from luxon; nullable. Matches DateTime.text resolver. */ startTime?: { text: string | null } | null; endTime?: { text: string | null } | null; } | null; } /** * The editor's active entity scope for this session (spec 03 § 4). Null * fields = route-level ("All CMS pages") scope: placement writes go to * `entity_urn = null` and the preview uses the route's sample `previewPath`. * Set by the pageBuilderEdit handler from `?entity=`. */ interface PageBuilderScope { entityUrn: string | null; previewPath: string | null; } interface EditorProps { route: RouteInfo; pageBuilderScope?: PageBuilderScope | null; changeset: ChangesetInfo; widgetTypes: WidgetType[]; addOperationUrl: string; publishUrl: string; createRolloutPlanUrl: string; updateRolloutPlanUrl: string; syncRolloutPlanUrl: string; cancelRolloutPlanUrl: string; moveCurrentChangeUrl: string; discardChangesetUrl: string; pickerHomeUrl: string; dashboardUrl: string; } const PRIMARY_AREA = 'content'; interface SelectedWidget { uid: string; type: string; settings: Record; /** * Optional seed for the SettingsDrawer's placement map. Set when the * widget is freshly inserted via drop: the placement only lives in the * changeset at that moment, not in the published `widget_placement` * table, so the drawer's `widgetByUuid` query (source-only) wouldn't * see it and would fall back to "current route only". */ initialPlacements?: Array<{ uuid: string; route: string; area: string; sortOrder: number; }>; } interface PendingParent { parentUid: string; columnIndex: number; } export default function Editor({ route, pageBuilderScope, changeset, widgetTypes, addOperationUrl, publishUrl, createRolloutPlanUrl, updateRolloutPlanUrl, syncRolloutPlanUrl, cancelRolloutPlanUrl, moveCurrentChangeUrl, discardChangesetUrl, pickerHomeUrl, dashboardUrl }: EditorProps) { // Active entity-scope URN for placement writes (spec 03 § 4.3). Null = // route-level: writes land on `entity_urn = null` (shown on every page of // the route). A page scope stamps the CMS page URN so the placement is // additive to that one page only. `'all'`-route (global) placements always // stay null regardless of scope — enforced at each op site below. const scopeEntityUrn = pageBuilderScope?.entityUrn ?? null; const [changeOrder, setChangeOrder] = useState(0); const [isPublishing, setIsPublishing] = useState(false); const [error, setError] = useState(null); const [selectedWidget, setSelectedWidget] = useState( null ); // Metafield guideline drawer (V1.1) — informational only; values are live // entity data and are never edited from the builder. const [selectedMetafield, setSelectedMetafield] = useState(null); const metafieldDrawerRef = useRef(null); // Inline image editing — `EditableImage` in the canvas posts `edit-image`; // this holds the target widget + the settings fields to write once the // FileBrowser pick resolves. const [imageEdit, setImageEdit] = useState<{ widgetUid: string; fields: { urlField: string; widthField?: string; heightField?: string }; } | null>(null); // Tracks the most recently clicked Layers row so the panel can highlight // it visually. Independent from `selectedWidget` (which controls the // settings drawer) — clicking a layer no longer opens the drawer. const [layerHighlightedUid, setLayerHighlightedUid] = useState( null ); // Force-open the SessionPicker on demand (topbar SessionModeBadge click). // Decoupled from `sessionAcknowledged` so reopening after dismissal still // shows the picker. Closing via Cancel just flips this back to false. const [pickerOpen, setPickerOpen] = useState(false); const [pendingParent, setPendingParent] = useState( null ); const [isPublishDialogOpen, setIsPublishDialogOpen] = useState(false); const [isRolloutDialogOpen, setIsRolloutDialogOpen] = useState(false); // Widgets-palette hover preview state. Captures the hovered widget + // the row's bounding rect + the panel's right edge, so the preview card // can position itself just past the sidebar. Cleared on mouse-leave, // drag-start (don't shadow the drag image), and panel scroll (the // anchor would otherwise drift away from the row). const [hoverPreview, setHoverPreview] = useState<{ widget: WidgetType; rect: DOMRect; anchorX: number; } | null>(null); const leftRailRef = useRef(null); // Schedule-editor dialog, opened by the SessionModeBadge pencil icon in // rollout-edit mode. Kept separate from the rollout-create dialog above so // the two flows don't share state machinery — the schedule editor uses // RolloutDialog in `editingPlan` mode and submits via PATCH; the create // dialog uses the same component without an editingPlan and submits via // POST. Two callbacks, two booleans, one dialog component reused. const [isScheduleEditorOpen, setIsScheduleEditorOpen] = useState(false); const [isUpdatingSchedule, setIsUpdatingSchedule] = useState(false); const [isSyncing, setIsSyncing] = useState(false); const iframeRef = useRef(null); // Page-level form (spec 03 § 2). Holds settings for every widget the // editor knows about, keyed `block..settings.`. Inline-edit // and the settings drawer both write through this form. `useWatch` // below produces per-uid auto-save ops. const pageForm = useForm({ mode: 'onBlur', shouldUnregister: false, defaultValues: { block: {} as Record }> } }); // Per-uid debounce timers and last-saved JSON snapshots. The watch // effect below diffs current form values against the snapshots and // schedules a save per widget that changed. Multiple field edits within // the debounce window collapse into one operation per widget. const saveTimersRef = useRef>({}); const lastSavedSettingsRef = useRef>({}); const initializedSeedsRef = useRef>(new Set()); // Set by undo/redo: the next layers refetch must OVERWRITE the page form // from server truth (not just fill missing uids) and resync the saved- // settings snapshots, so a widget the user edits after an undo doesn't // re-emit the value the undo just reverted. const forceReseedRef = useRef(false); const [activeLeftTab, setActiveLeftTab] = useState('widgets'); const [deviceMode, setDeviceMode] = useState('desktop'); const [reloadCounter, setReloadCounter] = useState(0); const [widgetSearch, setWidgetSearch] = useState(''); // Per demo: starts collapsed (52px). Click any tab icon expands to 260px. const [leftRailCollapsed, setLeftRailCollapsed] = useState(true); const [globalsView, setGlobalsView] = useState(false); // Generic confirm-dialog state. Set the object to open the dialog; null // to close. The handler is stashed on the object so callers don't need // a separate state for each prompt. const [confirmState, setConfirmState] = useState<{ title: string; description: React.ReactNode; confirmLabel?: string; destructive?: boolean; onConfirm: () => void | Promise; } | null>(null); const [confirmBusy, setConfirmBusy] = useState(false); const runConfirm = useCallback(async () => { if (!confirmState) return; setConfirmBusy(true); try { await confirmState.onConfirm(); } finally { setConfirmBusy(false); setConfirmState(null); } }, [confirmState]); // Mirror globals-view state to the iframe via postMessage. Iframe-side // PageBuilderBridge applies/removes the body dataset attribute that // drives the `[data-evershop-global]` outline styles. useEffect(() => { const iframe = iframeRef.current; if (!iframe) return; iframe.contentWindow?.postMessage( { type: 'globals-view', enabled: globalsView }, window.location.origin ); }, [globalsView, reloadCounter]); // (drawer outside-click effect lives below the drawerPinned state // declaration — declaring drawerRef here for early access.) const drawerRef = useRef(null); // Drawer pin state — persisted to localStorage. Default unpinned per // spec § 7.5; click on canvas wrapper deselects when not pinned. // Initialize to the server-rendered default (false) and hydrate from // localStorage AFTER mount — reading storage in the useState initializer // diverges from the SSR HTML and trips React hydration error #418. const [drawerPinned, setDrawerPinned] = useState(false); useEffect(() => { try { if (window.localStorage.getItem('pb_drawer_pinned') === '1') { setDrawerPinned(true); } } catch { /* ignore */ } }, []); const toggleDrawerPin = useCallback(() => { setDrawerPinned((prev) => { const next = !prev; try { if (typeof window !== 'undefined') { window.localStorage.setItem('pb_drawer_pinned', next ? '1' : '0'); } } catch { /* ignore */ } return next; }); }, []); // Close the settings drawer when clicking anywhere outside it (topbar, // left rail, canvas padding). Drawer-internal clicks are ignored, and // pinned drawers stay open. Iframe clicks are routed through the // iframe's own bridge (`pb-canvas-click` / `widget-selected` messages), // so we deliberately skip clicks that land on the iframe element from // the parent's perspective — otherwise we'd race the iframe's own // selection handling and clear the just-selected widget. useEffect(() => { if (!selectedWidget || drawerPinned) return; const onDown = (e: MouseEvent) => { const target = e.target as HTMLElement | null; const drawer = drawerRef.current; if (drawer && target && drawer.contains(target)) return; // Iframe clicks: ignore — the iframe handles its own selection / // deselection through postMessage. Closing here would race with the // iframe's `widget-selected` message and either clobber it or // double-fire deselection. if (target?.tagName === 'IFRAME') return; // Skip closing when clicking inside an alert or dialog popup so the // confirm flow doesn't collapse the drawer state mid-confirm. if (target?.closest('[data-slot="alert-dialog-content"]')) return; if (target?.closest('[data-slot="dialog-content"]')) return; // The file browser portals to , so it is never inside the drawer. // Without this the first click on a thumbnail closed the drawer that // opened the browser, and the browser went with it. if (target?.closest('[data-slot="file-browser"]')) return; setSelectedWidget(null); }; window.addEventListener('mousedown', onDown); return () => window.removeEventListener('mousedown', onDown); }, [selectedWidget, drawerPinned]); // Outside-click close for the metafield guideline drawer — parallel to the // widget drawer's effect above (no pin: the drawer is informational). useEffect(() => { if (!selectedMetafield) return undefined; const onDown = (e: MouseEvent) => { const target = e.target as HTMLElement | null; const drawer = metafieldDrawerRef.current; if (drawer && target && drawer.contains(target)) return; if (target?.tagName === 'IFRAME') return; if (target?.closest('[data-slot="alert-dialog-content"]')) return; if (target?.closest('[data-slot="dialog-content"]')) return; // The file browser portals to , so it is never inside the drawer. // Without this the first click on a thumbnail closed the drawer that // opened the browser, and the browser went with it. if (target?.closest('[data-slot="file-browser"]')) return; setSelectedMetafield(null); }; window.addEventListener('mousedown', onDown); return () => window.removeEventListener('mousedown', onDown); }, [selectedMetafield]); // Session picker (spec § 7.8). Show on ENTRY when the draft has existing // operations (or rollout plans to resume) AND the user hasn't // acknowledged this changeset in this browser tab. The show/skip // decision is made ONCE per mount — latched in `entryDecision` by an // effect further down, after the entry inputs (ops + rollout plans) // first resolve. It must NOT be re-evaluated live: `operations.length` // changes after every edit (postOperation refetches it for the // exit-safety gates), and a live condition summoned the ENTRY dialog // mid-session — publish reloads into a fresh empty draft (auto-skip, // nothing acknowledged), then the very first edit made ops > 0 and // popped "Start a page-builder session" over the user's work. const sessionAckKey = `pb_session_ack_${changeset.changesetId}`; // Start acknowledged (picker hidden) to match SSR, then read sessionStorage // after mount. Reading it in the initializer renders the picker on the // client but not on the server → React hydration error #418. Revealing the // picker one tick later (post-mount) is the intended on-entry behavior. const [sessionAcknowledged, setSessionAcknowledged] = useState(true); // True once the sessionStorage read has actually happened — the entry // decision must not run against the SSR-safe initial `true`. const [sessionAckChecked, setSessionAckChecked] = useState(false); const [entryDecision, setEntryDecision] = useState< 'pending' | 'show' | 'skip' >('pending'); useEffect(() => { try { if (window.sessionStorage.getItem(sessionAckKey) !== '1') { setSessionAcknowledged(false); } } catch { /* ignore */ } setSessionAckChecked(true); }, [sessionAckKey]); const acknowledgeSession = useCallback(() => { setSessionAcknowledged(true); // Acknowledging resolves the entry question either way — if the picker // is currently forced open ('show'), this is what closes it. setEntryDecision('skip'); try { if (typeof window !== 'undefined') { window.sessionStorage.setItem(sessionAckKey, '1'); } } catch { /* ignore */ } }, [sessionAckKey]); // Pull the changeset's operations *before* the exit-confirm hooks below // so their dependency arrays can reference `operations.length` without // tripping TDZ — JS evaluates the deps array eagerly, even though the // effect body runs later. const [opsResult, refetchOps] = useQuery({ query: CHANGESET_OPS_QUERY, variables: { id: changeset.changesetId }, pause: true }); const operations = (opsResult.data as any)?.changeset?.operations ?? []; // Set of route IDs that have any pending op in the current draft. Used // to mark "Draft" status pills on the Pages tab. Spec § 7.7. const routesWithDraftOps = useMemo(() => { const s = new Set(); for (const op of operations as Array<{ route?: string | null }>) { if (op?.route) s.add(op.route); } return s; }, [operations]); // Refetch ops once on mount so the session picker can decide whether // to surface (we need to know if the existing draft has any ops). useEffect(() => { refetchOps({ requestPolicy: 'network-only' }); }, []); // Exit-confirm state. `pendingSavesCount` is incremented when an op // POST is in flight, decremented on response (success or fail). // `pendingExitUrl` holds the destination the user attempted to navigate // to while a save was in flight; the dialog resolves it. const [pendingSavesCount, setPendingSavesCount] = useState(0); const [pendingExitUrl, setPendingExitUrl] = useState(null); // Suppresses the native `beforeunload` prompt for intentional redirects // — publish, schedule-rollout, ExitConfirmDialog's Leave button, and // in-editor anchor clicks. Without this, `operations.length > 0` is // still true at the moment of `window.location.href = …` (the GraphQL // cache hasn't refetched yet, or the changeset legitimately holds // unpublished ops that survive the route switch), so the browser shows // its "Leave site?" prompt right when the user already confirmed they // want to leave. const suppressBeforeUnloadRef = useRef(false); const markIntentionalNavigation = useCallback(() => { suppressBeforeUnloadRef.current = true; // Belt-and-braces reset: if the navigation doesn't actually happen // (e.g. a click handler later calls `preventDefault`, or the user // Ctrl+clicked and we mis-detected it as a normal click), drop the // flag so the next real exit attempt isn't silently allowed. window.setTimeout(() => { suppressBeforeUnloadRef.current = false; }, 500); }, []); // Browser-tab close — native `beforeunload` prompt when there are // outstanding saves OR unpublished operations. Custom UI isn't allowed // for this path; the native dialog is the platform's exit-confirm. useEffect(() => { if (pendingSavesCount === 0 && operations.length === 0) return; const onBeforeUnload = (e: BeforeUnloadEvent) => { if (suppressBeforeUnloadRef.current) return; e.preventDefault(); // Required for some browsers; the actual string is ignored in modern browsers. e.returnValue = ''; }; window.addEventListener('beforeunload', onBeforeUnload); return () => window.removeEventListener('beforeunload', onBeforeUnload); }, [pendingSavesCount, operations.length]); // Cover the plain-anchor case: PageSwitcher and the Pages-tab now use // `` to switch routes inside the // editor. Browser navigates without going through `requestNavigation`, // so we tag the click here (capture phase) and let the navigation // proceed silently. useEffect(() => { const onDocClick = (e: MouseEvent) => { if (e.defaultPrevented) return; if (e.button !== 0) return; if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; const anchor = (e.target as HTMLElement | null)?.closest?.( 'a[href]' ) as HTMLAnchorElement | null; if (!anchor) return; if (anchor.target === '_blank') return; const href = anchor.getAttribute('href') ?? ''; if ( href === pickerHomeUrl || href.startsWith(`${pickerHomeUrl}/`) || href.startsWith(`${pickerHomeUrl}?`) ) { markIntentionalNavigation(); } }; document.addEventListener('click', onDocClick, true); return () => document.removeEventListener('click', onDocClick, true); }, [pickerHomeUrl, markIntentionalNavigation]); // Helper for in-app navigation that may need to confirm. // // Confirm only when LEAVING the page-builder editor — the changeset is // per-user (one draft spans every route the user edits), so route // switching inside the editor preserves all unpublished work and the // dialog would be noise. Logo/back links to the dashboard and any // future leave-editor sites still go through the dialog. // // Two reasons to open it for leave-editor targets: // - In-flight saves: typing that hasn't reached the server yet. // - Saved-but-unpublished operations: the merchandiser usually wants // the "Save as rollout plan" affordance before walking away. const requestNavigation = useCallback( (url: string) => { const stayingInEditor = typeof url === 'string' && (url === pickerHomeUrl || url.startsWith(`${pickerHomeUrl}/`) || url.startsWith(`${pickerHomeUrl}?`)); if (stayingInEditor) { markIntentionalNavigation(); window.location.href = url; return; } if (pendingSavesCount > 0 || operations.length > 0) { setPendingExitUrl(url); return; } markIntentionalNavigation(); window.location.href = url; }, [ pendingSavesCount, operations.length, pickerHomeUrl, markIntentionalNavigation ] ); // Widgets palette: filter by search query (matches name + description), // then bucket by category. Spec § 7.7. While targeting a column we hide // layout-category widgets so the merchandiser can't nest containers. const groupedWidgetTypes = useMemo(() => { const q = widgetSearch.trim().toLowerCase(); const filtered = widgetTypes.filter((wt) => { if (pendingParent && wt.code === 'columns') return false; if (!q) return true; // Match the localized label/description too, so search works in the admin language. const hay = `${_(wt.name)} ${wt.description ? _(wt.description) : ''} ${ wt.code }`.toLowerCase(); return hay.includes(q); }); const buckets = new Map(); for (const wt of filtered) { const key = (wt.category ?? 'other').toLowerCase(); const known = WIDGET_CATEGORIES.some((c) => c.key === key); const bucketKey = known ? key : 'other'; if (!buckets.has(bucketKey)) buckets.set(bucketKey, []); buckets.get(bucketKey)!.push(wt); } return WIDGET_CATEGORIES.map((c) => ({ ...c, widgets: buckets.get(c.key) ?? [] })).filter((g) => g.widgets.length > 0); }, [widgetTypes, widgetSearch, pendingParent]); // Lookup map for the Layers panel: widget code → registry entry. Lets // LayerNode render the canonical widget name + description rather than the // per-instance name + raw type code. const widgetTypesByCode = useMemo(() => { const map = new Map(); for (const wt of widgetTypes) map.set(wt.code, wt); return map; }, [widgetTypes]); const client = useClient(); const [layersResult, refetchLayers] = useQuery({ query: LAYERS_QUERY, // Pass the changeset token so the resolver applies this draft's overlay // before grouping/filtering — Layers stays in sync with what the iframe // actually renders (palette adds, deletes, moves, inline-edits all // reflect immediately instead of only after publish). `entityUrn` scopes // the result to an entity-level session (e.g. one landing page) so Layers // shows the page's own widgets plus the shared route-level ones — matching // the canvas. Null in a route-level editor (unchanged behavior). variables: { route: route.id, changeset: changeset.token, entityUrn: scopeEntityUrn }, pause: true }); const rawLayerWidgets = (layersResult.data as any)?.widgetsForRoute ?? []; // Iframe DOM order — populated by `preview-rendered` postMessages from // PageBuilderBridge after each iframe render. Layers tab sorts widgets // by this so the panel matches what the storefront actually paints // (Area positioning + per-area sort_order combined). Falls back to the // server's MIN(sort_order) ordering until the first message lands. const [iframeWidgetOrder, setIframeWidgetOrder] = useState([]); const layerWidgets = useMemo(() => { if (iframeWidgetOrder.length === 0) return rawLayerWidgets; const indexMap = new Map(); iframeWidgetOrder.forEach((uid, i) => indexMap.set(uid, i)); const sortByDom = (arr: T[]): T[] => [...arr].sort((a, b) => { const ai = indexMap.get(a.uuid ?? '') ?? Number.MAX_SAFE_INTEGER; const bi = indexMap.get(b.uuid ?? '') ?? Number.MAX_SAFE_INTEGER; return ai - bi; }); // Sort top-level widgets AND each container's column children — both // appear in the iframe's flat `[data-evershop-pb-widget-uid]` query so // the index map covers everything. return sortByDom(rawLayerWidgets).map((w: any) => { if (!Array.isArray(w?.columns)) return w; return { ...w, columns: w.columns.map((col: any) => ({ ...col, widgets: Array.isArray(col?.widgets) ? sortByDom(col.widgets) : [] })) }; }); }, [rawLayerWidgets, iframeWidgetOrder]); // Seed pageForm with settings for every widget known on the route // (top-level + nested container children) so field components inside // hydrate from real values. Re-runs whenever // layerWidgets changes (e.g. after reload triggered by undo/redo or // initial mount). Does NOT overwrite values the user is currently // editing — it only fills in missing entries. useEffect(() => { if (!Array.isArray(layerWidgets) || layerWidgets.length === 0) return; // After an undo/redo the server state is authoritative — overwrite every // widget's form settings from `rawSettings` and resync its saved snapshot, // so the reverted value sticks and the auto-save diff sees no phantom // change. Normal seeding only fills MISSING uids so it never clobbers an // in-progress edit. const forceReseed = forceReseedRef.current; forceReseedRef.current = false; const current = pageForm.getValues('block') ?? {}; const next: Record }> = { ...(current as any) }; const visit = (w: any) => { if (!w?.uuid) return; if (forceReseed || !next[w.uuid]) { const settings = (w.rawSettings as Record) ?? {}; next[w.uuid] = { settings }; if (forceReseed) { // Keep the auto-save baseline in lockstep with what we just wrote. lastSavedSettingsRef.current[w.uuid] = JSON.stringify(settings); } } if (Array.isArray(w.columns)) { for (const col of w.columns) { if (Array.isArray(col?.widgets)) col.widgets.forEach(visit); } } }; layerWidgets.forEach(visit); pageForm.setValue('block', next, { shouldDirty: false, shouldTouch: false }); }, [layerWidgets, pageForm]); // Seed-on-selection: when a widget is selected, ensure its settings are // populated in the form via a *reset* (not setValue). RHF's setValue does // NOT sync useFieldArray-driven subcomponents — slide arrays, menu items, // etc. only read from defaultValues at mount or from useFieldArray's // replace(). reset() re-initializes everything, so field arrays pick up // the seeded values. // // `keepDirtyValues` preserves any in-progress edits the user has touched // on other widgets; only non-dirty fields take the new values. useEffect(() => { if (!selectedWidget) return; const current = pageForm.getValues() as { block?: Record }>; }; const existing = current?.block?.[selectedWidget.uid]?.settings; const hasExisting = existing && Object.keys(existing).length > 0; if (hasExisting) return; const nextBlock = { ...(current.block ?? {}), [selectedWidget.uid]: { settings: { ...(selectedWidget.settings ?? {}) } } }; // Snapshot the new settings so the auto-save effect doesn't see this // seed as a user edit and emit a spurious save op. initializedSeedsRef.current.add(selectedWidget.uid); lastSavedSettingsRef.current[selectedWidget.uid] = JSON.stringify( selectedWidget.settings ?? {} ); pageForm.reset( { ...(current as any), block: nextBlock }, { keepDirtyValues: true, keepTouched: true, keepErrors: true } ); }, [selectedWidget?.uid]); const [pagesResult] = useQuery({ query: PAGES_QUERY }); const allRoutes = (pagesResult.data as any)?.routes ?? []; // Entities for the scope selector — only fetched when the current route // actually has an entity dimension (route-level routes pause the query). const [scopeEntitiesResult] = useQuery({ query: PAGE_BUILDER_SCOPE_ENTITIES_QUERY, variables: { routeId: route.id }, pause: !route.entityScope }); const scopePages = useMemo( () => (scopeEntitiesResult.data as any)?.pageBuilderScopeEntities ?? [], [scopeEntitiesResult.data] ); // Rollout plans for the SessionPicker. Filter out past plans (already // ended) so the picker only surfaces things the user might still want // to act on. `startTime` / `endTime` are GraphQL DateTime objects with // a `text` sub-field; flatten to ISO strings for the picker. const [rolloutPlansResult] = useQuery({ query: ROLLOUT_PLANS_QUERY }); const upcomingAndLiveRolloutPlans = useMemo(() => { const plans = (rolloutPlansResult.data as any)?.rolloutPlans ?? []; const now = Date.now(); type Mapped = { rolloutPlanId: number; uuid: string; name: string; startTime: string | null; endTime: string | null; }; type WithStart = Mapped & { startTime: string }; return ( (plans as Array) .map( (p): Mapped => ({ rolloutPlanId: p.rolloutPlanId, uuid: p.uuid, name: p.name, startTime: (p.startTime?.text as string | null) ?? null, endTime: (p.endTime?.text as string | null) ?? null }) ) // Type predicate so the downstream chain (and consumers like // RolloutDialog / SessionPicker) see `startTime: string`, not // `string | null`. .filter((p): p is WithStart => p.startTime != null) .filter((p) => { if (!p.endTime) return true; // indefinite — still actionable return new Date(p.endTime).getTime() > now; }) .sort( (a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime() ) ); }, [rolloutPlansResult.data]); // The session picker's ENTRY decision (see the state block above). Runs // once, as soon as the entry inputs have settled: the sessionStorage ack // read, the mount-time ops refetch, and the rollout-plans query (data or // error — an errored query must not wedge the decision). After the latch // nothing re-evaluates, so mid-session input changes (ops refetch after // every edit) can't resurrect the entry dialog. useEffect(() => { if (entryDecision !== 'pending') return; // Landing via `?session=` already represents an explicit // choice (the user clicked a rollout card in the SessionPicker, or // bookmarked the URL) — skip and acknowledge immediately; the // SessionModeBadge remains the manual escape hatch. if (changeset.rolloutPlan != null) { acknowledgeSession(); return; } if (!sessionAckChecked) return; const opsResolved = opsResult.data != null || opsResult.error != null; const plansResolved = rolloutPlansResult.data != null || rolloutPlansResult.error != null; if (!opsResolved || !plansResolved) return; if ( !sessionAcknowledged && (operations.length > 0 || upcomingAndLiveRolloutPlans.length > 0) ) { setEntryDecision('show'); } else { // Auto-skip: this tab just started (or already owns) this session — // an empty fresh draft, or an ack from a previous visit. Acknowledge // so later edits and reloads in THIS tab never re-ask; a different // tab (its own sessionStorage) still gets the entry picker when it // finds the draft non-empty. acknowledgeSession(); } }, [ entryDecision, changeset.rolloutPlan, sessionAckChecked, sessionAcknowledged, opsResult.data, opsResult.error, rolloutPlansResult.data, rolloutPlansResult.error, operations.length, upcomingAndLiveRolloutPlans.length, acknowledgeSession ]); const pageRoutes = useMemo( () => allRoutes .filter( (r: any) => r.editableInPageBuilder === true && !r.isApi && !r.isAdmin && typeof r.path === 'string' ) // Homepage first, then alphabetical by display name. The raw `routes` // query returns scan/registration order, which reads as random in the // switcher and Pages tab; a stable, predictable order is friendlier. // `.filter` already returned a fresh array, so sorting in place is safe. .sort((a: any, b: any) => { if (a.id === b.id) return 0; if (a.id === 'homepage') return -1; if (b.id === 'homepage') return 1; return (a.name ?? '').localeCompare(b.name ?? ''); }), [allRoutes] ); // Refetch the layers list whenever the iframe reloads (i.e., after any // op was saved). The layers panel shows the changeset-overlayed source, // not the in-flight admin state, so this stays consistent with the iframe. useEffect(() => { // Layers data isn't only for the panel — move/duplicate handlers also // read from `layerWidgets` to find the target's placement uuid + // sort_order. Refetch on mount and after every preview-push so that // toolbar actions always operate on fresh state, even when the user // hasn't opened the Layers tab. // // `route.id`, `changeset.token` and `scopeEntityUrn` are in the dep list // because this is a paused query (`pause: true`): its variables only take // effect when `refetchLayers` is invoked. The entity scope resolves via the // page-level GraphQL data, so `scopeEntityUrn` can be null on the first // commit and become the entity URN a tick later. Without it here the single // mount refetch would fire with the stale null scope and never re-run — the // Layers panel would show only route-level widgets and miss the entity's own // (landing page / entity-scoped CMS page). refetchLayers({ requestPolicy: 'network-only' }); }, [reloadCounter, refetchLayers, route.id, changeset.token, scopeEntityUrn]); // In page scope, preview the SELECTED page's real URL (`/`) so its // own entity-scoped placements layer in (cmsPageView sets the page URN from // whatever URL the iframe loads). Route-level scope falls back to the // resolver's sample entity for dynamic routes (e.g. `/category/:uuid`); // static routes return their declared `path`. const previewablePath = pageBuilderScope?.previewPath || route.previewPath || route.path; const iframeSrc = useMemo(() => { const sep = previewablePath.includes('?') ? '&' : '?'; return `${previewablePath}${sep}changeset=${encodeURIComponent( changeset.token )}`; }, [previewablePath, changeset.token]); /** * Build an editor URL for a route, preserving the current session. When * the user is editing a rollout plan, route-switch links must carry * `?session=` so the next page-handler invocation pins the * editor to the same rollout's changeset (spec § 5.7: one session spans * every route the user touches). Centralized so future navigation sites * can't accidentally drop the session. * * Sites that explicitly want to LEAVE rollout-edit mode ("Continue your * draft", "Start new changeset" in the SessionPicker) build their URL * inline with a bare `${pickerHomeUrl}/edit/` — by design. */ const editPathForRoute = useCallback( (routeId: string): string => { const base = `${pickerHomeUrl}/edit/${encodeURIComponent(routeId)}`; return changeset.rolloutPlan ? `${base}?session=${encodeURIComponent(changeset.rolloutPlan.uuid)}` : base; }, [pickerHomeUrl, changeset.rolloutPlan] ); // Re-scope the CURRENT route to a specific entity (CMS page uuid) or back to // route-level ("All", entityUuid = null), preserving the rollout session. // Distinct from editPathForRoute: that SWITCHES routes (and drops any entity // scope, since the target route may not be entity-scoped); this keeps the // route and toggles the `?entity` scope on it. const scopeHref = useCallback( (entityUuid: string | null): string => { const base = `${pickerHomeUrl}/edit/${encodeURIComponent(route.id)}`; const params: string[] = []; if (changeset.rolloutPlan) { params.push( `session=${encodeURIComponent(changeset.rolloutPlan.uuid)}` ); } if (entityUuid) { params.push(`entity=${encodeURIComponent(entityUuid)}`); } return params.length ? `${base}?${params.join('&')}` : base; }, [pickerHomeUrl, route.id, changeset.rolloutPlan] ); // Monotonic preview-push counter; sent with each data-update message so // the iframe bridge can drop stale responses (race handling per spec // 03 § 7.3.4). const previewSequenceRef = useRef(0); // Cached overlay-applied widgets (uuid, areaId, sortOrder, placementUuid) // captured from the last `pushPreviewToIframe` fetch. The move/duplicate // handlers consult this so they see exactly what the iframe renders — the // GraphQL `widgetsForRoute` resolver reads source state only and would // produce visually-invisible reorders when prior ops have already shifted // sort_orders. const overlayWidgetsRef = useRef< Array<{ uuid: string; type: string; areaId: string[]; sortOrder: number; placementUuid?: string; settings?: Record; }> >([]); const previewBaseUrl = useMemo(() => { const sep = previewablePath.includes('?') ? '&' : '?'; return `${previewablePath}${sep}changeset=${encodeURIComponent( changeset.token )}&ajax=true`; }, [previewablePath, changeset.token]); /** * V2 server-side preview rendering. After any op is saved, fetch the * route's AJAX response (which runs the storefront pipeline with the * changeset overlay applied) and postMessage the resulting eContext to * the iframe. The iframe's `PageBuilderBridge` calls `setData` with the * new graphqlResponse / propsMap / widgets so React re-renders affected * widgets without reloading. This preserves contentEditable focus, scroll * position, and any in-progress UI state in the iframe. */ const pushPreviewToIframe = useCallback(async () => { const iframe = iframeRef.current; if (!iframe || !iframe.contentWindow) return; // Allocate the sequence at INITIATION, before the fetch — not at arrival. // Two edits fired ~300ms apart each start a preview fetch; if the older // (lower-seq) request happens to resolve last and we numbered by arrival, // it would overwrite the newer edit's canvas. Numbering by initiation lets // the bridge's `sequence <= last` guard drop a stale-but-late response so // the newest edit always wins. const seq = (previewSequenceRef.current += 1); // Flip the iframe's LoadingBar on immediately so the merchandiser sees // visible feedback during the ~200–500ms preview rebuild. The bridge // flips it off when the `data-update` message lands below. iframe.contentWindow.postMessage( { type: 'preview-start' }, window.location.origin ); try { const res = await fetch(previewBaseUrl, { method: 'GET', credentials: 'same-origin', headers: { Accept: 'application/json' } }); if (!res.ok) { // The bridge owns the off-flip via data-update; on failure we have // to clear the bar manually or it'll stay stuck at peak. iframe.contentWindow.postMessage( { type: 'data-update', sequence: seq }, window.location.origin ); return; } const json = await res.json(); // A newer push started while this fetch was in flight — drop this stale // result entirely so it can't overwrite the move/duplicate widget cache // or the canvas with older data. if (seq !== previewSequenceRef.current) return; const eContext = json?.eContext; if (!eContext) return; // Cache overlay-applied widgets for move/duplicate handlers (see ref // declaration above). if (Array.isArray(eContext.widgets)) { overlayWidgetsRef.current = eContext.widgets; } iframe.contentWindow.postMessage( { type: 'data-update', graphqlResponse: eContext.graphqlResponse, propsMap: eContext.propsMap, widgets: eContext.widgets, sequence: seq }, window.location.origin ); setReloadCounter((n) => n + 1); } catch { // Best-effort; if preview push fails the user can still hit refresh. // Clear the LoadingBar so it doesn't stay pinned at peak. iframe.contentWindow?.postMessage( { type: 'data-update', sequence: seq }, window.location.origin ); } }, [previewBaseUrl]); // Prime `overlayWidgetsRef` once on mount (and whenever the route changes) // so the very first move/duplicate click works without first triggering an // unrelated pushPreviewToIframe. The iframe is already SSR-rendered with // the overlay applied; we just need the parent to know what's in there. useEffect(() => { let cancelled = false; void (async () => { try { const res = await fetch(previewBaseUrl, { method: 'GET', credentials: 'same-origin', headers: { Accept: 'application/json' } }); if (!res.ok || cancelled) return; const json = await res.json(); const widgets = json?.eContext?.widgets; if (Array.isArray(widgets) && !cancelled) { overlayWidgetsRef.current = widgets; } } catch { // Best-effort prime; pushPreviewToIframe will refresh on next op. } })(); return () => { cancelled = true; }; }, [previewBaseUrl]); const nextChangeOrder = useCallback(() => { let next = 0; setChangeOrder((current) => { next = current + 1; return next; }); return next; }, []); const postOperation = useCallback( async (op: { entity_urn: string; old_payload: Record | null; new_payload: Record | null; }) => { const order = nextChangeOrder(); setPendingSavesCount((n) => n + 1); try { await axios.post(addOperationUrl, { ...op, route: route.id, change_order: order }); setError(null); // Keep `operations` current after every op. Ops are POSTed via axios, // which never invalidates the urql cache, so without this refetch the // `operations.length` exit-safety gates (beforeunload, ExitConfirm, // "Save as rollout") and the Pages-tab "Draft" pills stay frozen at // their mount-time value — inert for everything built this session. refetchOps({ requestPolicy: 'network-only' }); return true; } catch (e) { const msg = (e as any)?.response?.data?.error?.message ?? (e as Error).message ?? _('Failed to save change'); setError(msg); return false; } finally { setPendingSavesCount((n) => Math.max(0, n - 1)); } }, [addOperationUrl, nextChangeOrder, route.id, refetchOps] ); const handleAddWidget = useCallback( async ( widgetType: WidgetType, opts?: { /** * Pre-computed sort_order for the new placement. The iframe owns * this math (see `computeDropSortOrder` and the drop-zone * components in `common/page-builder/`) because only the iframe * sees the full rendered ordering — widgets AND layout components * interleaved. When omitted (e.g. click-to-add in the legacy * palette flow), we fall back to a safe append at 100. */ sortOrder?: number; /** * Override the target area. Defaults to `PRIMARY_AREA` ("content"). * Used when the iframe's drop zone lives in a non-primary Area * (e.g. header, footer) so the placement lands where the user * actually dropped. */ area?: string; /** * Set when the drop target was wrapped in `` (header, * footer, etc.). Defaults the top-level placement to `route='all'` * so the widget shows on every page — matching how those slots * intuitively behave. Doesn't affect child widgets inside a * container; those follow their parent's existing route policy. */ isGlobal?: boolean; } ) => { const widgetUuid = uuidv4(); const widgetName = `${widgetType.name} (new)`; const initialSettings = (widgetType.defaultSetting ?? {}) as Record< string, unknown >; const nextSortOrder = typeof opts?.sortOrder === 'number' && !Number.isNaN(opts.sortOrder) ? opts.sortOrder : 100; const targetArea = opts?.area ?? PRIMARY_AREA; const targetRoute = opts?.isGlobal ? 'all' : route.id; // Is this a drop into a column container? The "+ Add to Column" flow sets // `pendingParent`; a drag-drop only carries the synthetic // `columnsContainer__col_` target area. Parse it so BOTH // paths run the child branch below — children ALWAYS follow their parent's // route, never `isGlobal` (which a child would otherwise inherit from a // surrounding global Area like `content`, wrongly forcing route='all'). const columnAreaMatch = targetArea.match( /^columnsContainer_(.+)_col_(\d+)$/ ); const childContext = pendingParent ?? (columnAreaMatch ? { parentUid: columnAreaMatch[1], columnIndex: Number(columnAreaMatch[2]) } : null); if (childContext) { // Child widget — same shape as a top-level widget, but its placement // targets the parent's synthetic Area // `columnsContainer__col_`. The placement's route // follows the parent: if the parent has any 'all' placement, the // child rides along on every route; otherwise it sticks to the // route the user is currently editing. const parent = (layerWidgets as any[]).find( (w) => w?.uuid === childContext.parentUid ); const parentRoutes: string[] = Array.isArray(parent?.placements) ? parent.placements .filter((p: any) => p && p.entity_urn == null) .map((p: any) => p.route) : []; const childRoute = parentRoutes.includes('all') ? 'all' : route.id; const childArea = `columnsContainer_${childContext.parentUid}_col_${childContext.columnIndex}`; // Sort within the column: a high default that leaves room for // pre-existing children; the visible reorder logic in moveWidget // displaces past the neighbor's sort_order anyway. const siblingCount = parent && Array.isArray(parent.columns) ? parent.columns.find( (c: any) => c.index === childContext.columnIndex )?.widgets?.length ?? 0 : 0; // A drag carries an iframe-computed drop position; click-to-add (the // "+ Add to Column" flow) has none, so it appends past existing children. const childSortOrder = typeof opts?.sortOrder === 'number' && !Number.isNaN(opts.sortOrder) ? opts.sortOrder : 100 + siblingCount; const placementUuid = uuidv4(); const widgetOk = await postOperation({ entity_urn: `urn:evershop:cms:widget_instance:${widgetUuid}`, old_payload: null, new_payload: { uuid: widgetUuid, type: widgetType.code, name: widgetName, settings: initialSettings, status: true } }); if (!widgetOk) return; const placementOk = await postOperation({ entity_urn: `urn:evershop:cms:widget_placement:${placementUuid}`, old_payload: null, new_payload: { uuid: placementUuid, widget_instance_uuid: widgetUuid, route: childRoute, area: childArea, sort_order: childSortOrder, // Global ('all') children can't be page-scoped; otherwise inherit // the editor's active page scope. entity_urn: childRoute === 'all' ? null : scopeEntityUrn } }); if (!placementOk) return; setPendingParent(null); setSelectedWidget({ uid: widgetUuid, type: widgetType.code, settings: initialSettings }); await pushPreviewToIframe(); return; } // Top-level widget: INSERT widget_instance + INSERT widget_placement. const placementUuid = uuidv4(); const widgetOk = await postOperation({ entity_urn: `urn:evershop:cms:widget_instance:${widgetUuid}`, old_payload: null, new_payload: { uuid: widgetUuid, type: widgetType.code, name: widgetName, settings: initialSettings, status: true } }); if (!widgetOk) return; const placementOk = await postOperation({ entity_urn: `urn:evershop:cms:widget_placement:${placementUuid}`, old_payload: null, new_payload: { uuid: placementUuid, widget_instance_uuid: widgetUuid, route: targetRoute, area: targetArea, sort_order: nextSortOrder, // Global ('all') placements are never page-scoped; otherwise stamp // the editor's active page scope (null in All-pages scope). entity_urn: targetRoute === 'all' ? null : scopeEntityUrn } }); if (!placementOk) return; setSelectedWidget({ uid: widgetUuid, type: widgetType.code, settings: initialSettings, // Seed the drawer with the placement we just inserted so the // share dropdown immediately reflects route='all' (global drops) // or the current route, without waiting for an iframe refresh // or a `widgetByUuid` requery. initialPlacements: [ { uuid: placementUuid, route: targetRoute, area: targetArea, sortOrder: nextSortOrder } ] }); pushPreviewToIframe(); }, // `layerWidgets` still consumed by the pendingParent branch (parent lookup // + child placement context). Top-level drops no longer read it — they // use the iframe-computed sortOrder in `opts`. [ postOperation, pushPreviewToIframe, route.id, pendingParent, layerWidgets, scopeEntityUrn ] ); const openPublishDialog = useCallback(() => { refetchOps({ requestPolicy: 'network-only' }); setIsPublishDialogOpen(true); }, [refetchOps]); // Per-route undo/redo state. The buttons disable when there's nothing to // undo (cursor already at 0 for this route) or redo (no ops past the // cursor on this route). The server is the source of truth; we read // canUndo/canRedo from GraphQL and the move-current endpoint's response. const [canUndo, setCanUndo] = useState(false); const [canRedo, setCanRedo] = useState(false); // Local mirrors of the cursor maps so the editor can react to mutations // without a full page reload. `editorCursors` advances on every op / // undo / redo / discard; `savedCursors` only moves when the user clicks // Save (sync). In draft mode `savedCursors` stays at `{}` and the Save // button isn't rendered anyway. const [editorCursors, setEditorCursors] = useState>( () => changeset.routeCursors ?? {} ); const [savedCursors, setSavedCursors] = useState>( () => changeset.rolloutPlan?.routeCursors ?? {} ); const refreshUndoRedoState = useCallback(async () => { try { const sub = await client .query( `query UndoRedoState($id: Int!, $route: String!) { changeset(id: $id) { canUndo(route: $route) canRedo(route: $route) routeCursors rolloutPlan { routeCursors } } }`, { id: changeset.changesetId, route: route.id }, { requestPolicy: 'network-only' } ) .toPromise(); const cs = (sub?.data as any)?.changeset; if (cs) { setCanUndo(!!cs.canUndo); setCanRedo(!!cs.canRedo); if (cs.routeCursors) { setEditorCursors(cs.routeCursors); } if (cs.rolloutPlan?.routeCursors) { setSavedCursors(cs.rolloutPlan.routeCursors); } } } catch { // Best-effort; the buttons stay in their last known state. } }, [client, changeset.changesetId, route.id]); const hasUnsavedRolloutChanges = useMemo( () => !cursorsEqual(editorCursors, savedCursors), [editorCursors, savedCursors] ); // Refresh on mount, on route switch, and whenever an op gets persisted // (signalled via reloadCounter, which bumps after each pushPreviewToIframe). useEffect(() => { void refreshUndoRedoState(); }, [refreshUndoRedoState, reloadCounter]); const handleMoveCurrent = useCallback( async (direction: 'undo' | 'redo') => { try { const res = await axios.post(moveCurrentChangeUrl, { direction, route: route.id }); // The endpoint returns the post-move canUndo/canRedo for this route // — apply immediately so the buttons don't flash to a stale state // before the GraphQL refetch lands. const payload = res?.data?.data; if (payload) { if (typeof payload.canUndo === 'boolean') setCanUndo(payload.canUndo); if (typeof payload.canRedo === 'boolean') setCanRedo(payload.canRedo); } // The undo/redo changed server state under the form's feet. Force the // next layers refetch (triggered by pushPreviewToIframe's reloadCounter // bump) to overwrite the form + snapshots from server truth, so a later // edit can't resurrect the value we just reverted. forceReseedRef.current = true; await pushPreviewToIframe(); } catch (e) { const msg = (e as any)?.response?.data?.error?.message ?? (e as Error).message ?? _('${direction} failed', { direction }); setError(msg); } }, [moveCurrentChangeUrl, pushPreviewToIframe, route.id] ); // Discard dialog (spec § 7.8): the user picks between full and per-route // discard. Op counts come from GraphQL on each open so they reflect the // current state (pending in-flight ops will already be persisted to // `changeset_operation` by the time the dialog renders — auto-save fires // before the discard button is clickable). const [discardDialogOpen, setDiscardDialogOpen] = useState(false); const [discardBusy, setDiscardBusy] = useState(false); const [discardCounts, setDiscardCounts] = useState<{ total: number; currentRoute: number; breakdown: Array<{ route: string; count: number }>; }>({ total: 0, currentRoute: 0, breakdown: [] }); const handleDiscard = useCallback(async () => { // Fetch fresh counts before opening so the per-route label is accurate. try { const sub = await client .query( `query DiscardCounts($id: Int!, $route: String!) { changeset(id: $id) { operationCountForRoute(route: $route) operationCountsByRoute { route count } } }`, { id: changeset.changesetId, route: route.id }, { requestPolicy: 'network-only' } ) .toPromise(); const cs = (sub?.data as any)?.changeset; const breakdown: Array<{ route: string; count: number }> = cs?.operationCountsByRoute ?? []; const total = breakdown.reduce( (sum: number, r: { count: number }) => sum + (r.count ?? 0), 0 ); setDiscardCounts({ total, currentRoute: Number(cs?.operationCountForRoute ?? 0), breakdown }); } catch { // Best-effort; show zeros if the fetch fails. setDiscardCounts({ total: 0, currentRoute: 0, breakdown: [] }); } setDiscardDialogOpen(true); }, [client, changeset.changesetId, route.id]); const performDiscard = useCallback( async (mode: 'all' | 'route') => { setDiscardBusy(true); try { const url = mode === 'route' ? `${discardChangesetUrl}?route=${encodeURIComponent(route.id)}` : discardChangesetUrl; const res = await axios.post(url); const changesetDeleted = res?.data?.data?.changesetDeleted !== false; if (changesetDeleted) { // Full discard, or the route-scoped path emptied the changeset — // either way, navigate back so the picker can mint a fresh one. markIntentionalNavigation(); window.location.href = `${pickerHomeUrl}/edit/${encodeURIComponent( route.id )}`; return; } // Per-route discard with surviving ops on other routes: keep the // session alive, refresh the iframe + undo/redo state. setDiscardDialogOpen(false); setDiscardBusy(false); await pushPreviewToIframe(); await refreshUndoRedoState(); } catch (e) { const msg = (e as any)?.response?.data?.error?.message ?? (e as Error).message ?? _('Discard failed'); setError(msg); setDiscardBusy(false); } }, [ discardChangesetUrl, pickerHomeUrl, route.id, pushPreviewToIframe, refreshUndoRedoState ] ); const handlePublish = useCallback(async () => { if (isPublishing) return; setIsPublishing(true); try { const opCount = operations.length; await axios.post(publishUrl); setError(null); // Reload the CURRENT route rather than redirecting to the picker home // (`pickerHomeUrl`), which unconditionally bounces to the homepage // editor and threw the merchandiser off the page they were editing. // The just-published changeset is now immutable, so the reload's // `getOrCreateDraftChangeset` mints a fresh draft, and the preview // iframe — loaded with the new empty changeset token — renders the // baked-in source, i.e. exactly what was just published. A plain // reload also preserves the route + entity scope (`?entity=…`) exactly. // Persist the success message across the reload so the remounted editor // can flash a Sonner toast (sessionStorage is consumed on read); a // silent reload previously left the merchandiser unsure the publish // succeeded. try { sessionStorage.setItem( 'pb_publish_flash', opCount === 1 ? _('1 change published.') : _('${count} changes published.', { count: String(opCount) }) ); } catch { // sessionStorage can throw in private modes; non-fatal. } markIntentionalNavigation(); window.location.reload(); } catch (e) { const msg = (e as any)?.response?.data?.error?.message ?? (e as Error).message ?? _('Publish failed'); setError(msg); toast.error(msg); } finally { setIsPublishing(false); } }, [publishUrl, isPublishing, operations.length, markIntentionalNavigation]); // Flash the publish-success toast after the post-publish reload lands on // a fresh editor instance. sessionStorage is consumed on read. useEffect(() => { if (typeof window === 'undefined') return; let flash: string | null = null; try { flash = sessionStorage.getItem('pb_publish_flash'); if (flash) sessionStorage.removeItem('pb_publish_flash'); } catch { return; } if (flash) toast.success(flash); }, []); const handleScheduleRollout = useCallback( async (plan: { name: string; startTime: string; endTime: string | null; }) => { if (isPublishing) return; setIsPublishing(true); try { await axios.post(createRolloutPlanUrl, { name: plan.name, changeset_id: changeset.changesetId, start_time: plan.startTime, end_time: plan.endTime }); setError(null); // If the rollout was triggered from the exit-confirm flow's // "Save as rollout plan and leave" option, honor the original // navigation target. Otherwise navigate to the picker home — the // user typically wants to start a fresh session or revisit other // rollouts after scheduling. const dest = pendingExitUrl ?? pickerHomeUrl; setPendingExitUrl(null); markIntentionalNavigation(); window.location.href = dest; } catch (e) { const msg = (e as any)?.response?.data?.error?.message ?? (e as Error).message ?? _('Schedule failed'); setError(msg); } finally { setIsPublishing(false); } }, [ createRolloutPlanUrl, pickerHomeUrl, changeset.changesetId, isPublishing, pendingExitUrl, markIntentionalNavigation ] ); // Save action for rollout-edit mode. Copies the editor's current // route_cursors snapshot into the rollout plan so the live storefront // catches up. User stays in the editor; state refreshes via // refreshUndoRedoState so the Save button reflects the new "no changes // to save" state. const handleSyncRollout = useCallback(async () => { if (isSyncing || !changeset.rolloutPlan) return; setIsSyncing(true); try { await axios.post(syncRolloutPlanUrl); setError(null); await refreshUndoRedoState(); } catch (e) { const msg = (e as any)?.response?.data?.error?.message ?? (e as Error).message ?? _('Save failed'); setError(msg); } finally { setIsSyncing(false); } }, [ syncRolloutPlanUrl, isSyncing, changeset.rolloutPlan, refreshUndoRedoState ]); // Cancel-rollout-plan flow. Opens the generic ConfirmDialog so the // destructive action requires an explicit second click. On confirm we // DELETE the rollout (the underlying changeset is preserved per // cancelRolloutPlan's docstring) and navigate the user to picker home — // their pb-draft is untouched there, so a fresh editing session can // start cleanly. const handleCancelRolloutPlan = useCallback(() => { if (!changeset.rolloutPlan) return; const planName = changeset.rolloutPlan.name; setConfirmState({ title: _('Cancel rollout plan?'), description: ( <> {_('The rollout plan')} {planName}{' '} {_( 'will be removed and the live storefront will stop applying its edits. The underlying changeset and its pending content edits are preserved.' )} ), confirmLabel: _('Cancel rollout'), destructive: true, onConfirm: async () => { await axios.delete(cancelRolloutPlanUrl); markIntentionalNavigation(); window.location.href = pickerHomeUrl; } }); }, [ cancelRolloutPlanUrl, pickerHomeUrl, changeset.rolloutPlan, markIntentionalNavigation, setConfirmState ]); // Schedule editor submit. PATCHes the rollout's name/start/end and closes // the dialog on success. Refreshes via reload because the rollout name // shown in SessionModeBadge comes from the props (SSR query) — easier // than threading the updated values back through props. const handleUpdateRolloutSchedule = useCallback( async (plan: { name: string; startTime: string; endTime: string | null; }) => { if (!changeset.rolloutPlan || isUpdatingSchedule) return; setIsUpdatingSchedule(true); try { await axios.patch(updateRolloutPlanUrl, { name: plan.name, start_time: plan.startTime, end_time: plan.endTime }); setError(null); setIsScheduleEditorOpen(false); window.location.reload(); } catch (e) { const msg = (e as any)?.response?.data?.error?.message ?? (e as Error).message ?? _('Failed to update rollout schedule'); setError(msg); setIsUpdatingSchedule(false); } }, [updateRolloutPlanUrl, changeset.rolloutPlan, isUpdatingSchedule] ); // Persist a UPDATE op for a widget's full new settings, then reload the // iframe so the canvas reflects the new state. const saveWidgetSettings = useCallback( async (uid: string, newSettings: Record) => { await postOperation({ entity_urn: `urn:evershop:cms:widget_instance:${uid}`, old_payload: { settings: '__previous__' }, new_payload: { settings: newSettings } }); // Update the local selectedWidget so the drawer keeps a stable view // of the latest settings if the user re-opens it for the same widget. setSelectedWidget((prev) => prev && prev.uid === uid ? { ...prev, settings: newSettings } : prev ); pushPreviewToIframe(); }, [postOperation, pushPreviewToIframe] ); // Page-level auto-save (spec § 7.3.2). Watch the entire `block` subtree // of the form. On any change, diff current per-uid settings against the // last saved snapshot. For each uid that changed, schedule a 300ms // debounce (clearing any pending one) that saves the full new settings. // Multiple field edits within the window collapse into one op. const blockValues = useWatch({ control: pageForm.control, name: 'block' }); useEffect(() => { const blocks = (blockValues as Record }>) ?? {}; for (const uid of Object.keys(blocks)) { const settings = blocks[uid]?.settings; if (!settings) continue; const stringified = JSON.stringify(settings); // First time we see a uid (form just got seeded with its values), // record the snapshot but don't save — saving now would emit // a no-op for every widget that already exists on the route. if (!initializedSeedsRef.current.has(uid)) { initializedSeedsRef.current.add(uid); lastSavedSettingsRef.current[uid] = stringified; continue; } if (lastSavedSettingsRef.current[uid] === stringified) continue; // Reset the debounce timer for this uid so rapid edits collapse. const existing = saveTimersRef.current[uid]; if (existing) window.clearTimeout(existing); saveTimersRef.current[uid] = window.setTimeout(() => { lastSavedSettingsRef.current[uid] = stringified; delete saveTimersRef.current[uid]; void saveWidgetSettings(uid, settings); }, 300); } }, [blockValues, saveWidgetSettings]); // Cleanup any pending debounces on unmount so a navigating-away tab // doesn't fire a save after we've left. useEffect(() => { return () => { for (const t of Object.values(saveTimersRef.current)) { window.clearTimeout(t); } saveTimersRef.current = {}; }; }, []); // Caller (drawer) generates the placement UUID so it can store it for a // later DELETE op if the user toggles the route off again. Otherwise an // ON → OFF → ON cycle would emit two INSERT ops for the same (widget, // route, area) and trip widget_placement's unique index on publish. // // `area` is the target slot — the drawer derives it from the widget's // existing placements so e.g. a `headerMiddleLeft` widget shared to // another route lands in `headerMiddleLeft` there too, not in `content`. // // `sortOrder` lets the drawer keep an existing placement's slot when // "swapping" a route (e.g. flipping `route='all'` → `route='homepage'`). // Matching sort_order means the storefront's cell dedupe // `(widget_instance_uuid, area, sort_order)` collapses the transient // `[old, new]` pair to one render — no flash during the add→remove gap. const addPlacement = useCallback( async ( targetRouteId: string, placementUuid: string, area: string = PRIMARY_AREA, sortOrder: number = 100 ) => { const ok = await postOperation({ entity_urn: `urn:evershop:cms:widget_placement:${placementUuid}`, old_payload: null, new_payload: { uuid: placementUuid, widget_instance_uuid: selectedWidget?.uid, route: targetRouteId, area, sort_order: sortOrder, // Sharing to the global 'all' route can't be page-scoped; sharing to // this route while in page scope keeps the widget on this page only. entity_urn: targetRouteId === 'all' ? null : scopeEntityUrn } }); if (ok) await pushPreviewToIframe(); }, [postOperation, pushPreviewToIframe, selectedWidget?.uid, scopeEntityUrn] ); const removePlacement = useCallback( async (placementUuid: string) => { const ok = await postOperation({ entity_urn: `urn:evershop:cms:widget_placement:${placementUuid}`, old_payload: { __delete: true }, new_payload: null }); if (ok) await pushPreviewToIframe(); }, [postOperation, pushPreviewToIframe] ); // Flatten layerWidgets into a single list of (top-level + container // children). Children live in `layerWidgets[].columns[].widgets` and // each carries its own placements (synthetic columnsContainer_*). const flatLayerWidgets = useCallback((): any[] => { const out: any[] = []; for (const w of (layerWidgets as any[]) ?? []) { out.push(w); for (const col of (w?.columns as any[]) ?? []) { for (const child of (col?.widgets as any[]) ?? []) { out.push(child); } } } return out; }, [layerWidgets]); // Pick the placement on `area` that the current route renders. Prefer // a route-specific placement, fall back to a route='all' shared one. const placementInArea = useCallback( (placements: any[] | undefined, area: string) => { const ps = Array.isArray(placements) ? placements : []; return ( ps.find((p) => p?.area === area && p?.route === route.id) ?? ps.find((p) => p?.area === area && p?.route === 'all') ?? null ); }, [route.id] ); // Layout-aware move (2026-07-06). The iframe computes the target // sort_order from the full rendered sibling order — layout components // included — via `computeMoveSortOrder` and sends it in the move message // (the same "iframe owns the math" rule as drops). We resolve the // placement from `overlayWidgetsRef` (the post-overlay widgets list from // the most recent preview — source state would disagree after reorders) // and emit ONE UPDATE op with the value verbatim. Collision-safe without // a swap: the target is the midpoint of two RENDER-ADJACENT siblings, so // no third renderable can sort between them. const moveWidgetTo = useCallback( async (uid: string, area: string, targetSort: number) => { const me = overlayWidgetsRef.current.find( (w) => w.uuid === uid && Array.isArray(w.areaId) && w.areaId.includes(area) ); if (!me?.placementUuid) return; await postOperation({ entity_urn: `urn:evershop:cms:widget_placement:${me.placementUuid}`, old_payload: { sort_order: me.sortOrder ?? 0 }, new_payload: { sort_order: targetSort } }); pushPreviewToIframe(); }, [postOperation, pushPreviewToIframe] ); // Legacy move fallback — used only when the move message carries no // iframe-computed `sortOrder` (an older iframe bundle). Can only step // over WIDGET neighbors; layout components are invisible to it. // // The toolbar sends `area` so we operate on the right placement when the // widget has placements in multiple areas (e.g. a basic_menu shared via // 'all/headerMiddleLeft' but also placed in 'cart/content'). Works // uniformly for top-level widgets and container children (children's // siblings live in the same synthetic `columnsContainer__col_` // area). // // Algorithm: swap the two placements' `sort_order` values via two UPDATE // ops. This gives an unambiguous reorder — the earlier `neighbor ± 1` // approach could collide with a third sibling already sitting at that // value, and stable-sort tie-breaking then depended on PostgreSQL row // iteration order, causing the moved widget to land in unexpected slots // (often the very first position). const moveWidget = useCallback( async (uid: string, area: string, direction: 'up' | 'down') => { const overlay = overlayWidgetsRef.current; const siblings = overlay .filter((w) => Array.isArray(w.areaId) && w.areaId.includes(area)) .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0)); const idx = siblings.findIndex((w) => w.uuid === uid); if (idx < 0) return; const me = siblings[idx]; if (!me.placementUuid) return; const neighborIdx = direction === 'up' ? idx - 1 : idx + 1; if (neighborIdx < 0 || neighborIdx >= siblings.length) return; const neighbor = siblings[neighborIdx]; if (!neighbor.placementUuid) return; const meSort = me.sortOrder ?? 0; const neighborSort = neighbor.sortOrder ?? 0; // Already tied — bump my side by a small delta in the desired // direction so the reorder takes visible effect. Falls back to a // single UPDATE; the relative order is otherwise stable-sort dependent. if (meSort === neighborSort) { await postOperation({ entity_urn: `urn:evershop:cms:widget_placement:${me.placementUuid}`, old_payload: { sort_order: meSort }, new_payload: { sort_order: direction === 'up' ? meSort - 1 : meSort + 1 } }); pushPreviewToIframe(); return; } // Swap the two `sort_order` values. Two ops with monotonic // `change_order` so the overlay engine applies them in order; the // intermediate tied state is never observed by the iframe (preview // only refetches after both POSTs resolve). const meOk = await postOperation({ entity_urn: `urn:evershop:cms:widget_placement:${me.placementUuid}`, old_payload: { sort_order: meSort }, new_payload: { sort_order: neighborSort } }); if (!meOk) return; await postOperation({ entity_urn: `urn:evershop:cms:widget_placement:${neighbor.placementUuid}`, old_payload: { sort_order: neighborSort }, new_payload: { sort_order: meSort } }); pushPreviewToIframe(); }, [postOperation, pushPreviewToIframe] ); // Duplicate a widget: clone its settings into a new widget_instance and // place a copy IMMEDIATELY after the original in the same area. // // The naive "copy.sort_order = original.sort_order + 1" produces a tie // when another sibling already sits at that value, and stable sort can // then position the copy somewhere arbitrary in the run. To guarantee the // copy is the immediate next entry, we walk forward from the original // and bump any sibling that would collide (UPDATE op per displaced // sibling) until we hit a natural gap. Common case (no tail collision): // 2 ops total (widget INSERT + placement INSERT). Worst case // (tightly-packed run): N+2 ops. const duplicateWidget = useCallback( async (uid: string, area: string) => { const overlay = overlayWidgetsRef.current; const siblings = overlay .filter((w) => Array.isArray(w.areaId) && w.areaId.includes(area)) .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0)); const idx = siblings.findIndex((w) => w.uuid === uid); if (idx < 0) return; const overlayMe = siblings[idx]; if (!overlayMe.placementUuid) return; // Pull metadata (name, rawSettings, route) from layerWidgets — the // overlay payload carries already-merged `settings` but not `name` or // raw stored shape. const flat = flatLayerWidgets(); const meta = flat.find((w) => w?.uuid === uid); const myPlacement = (meta && placementInArea(meta.placements, area)) ?? null; const copySort = (overlayMe.sortOrder ?? 0) + 1; // Shift down any siblings that would land at or before copySort. // Iterate forward, raising each colliding sibling to `expected` so // every step strictly increases. Stop as soon as a sibling already // sits past expected — there's a natural gap and no more shifting // needed. let expected = copySort + 1; for (let i = idx + 1; i < siblings.length; i++) { const sib = siblings[i]; const sibSort = sib.sortOrder ?? 0; if (sibSort >= expected) break; if (!sib.placementUuid) { expected++; continue; } const bumpOk = await postOperation({ entity_urn: `urn:evershop:cms:widget_placement:${sib.placementUuid}`, old_payload: { sort_order: sibSort }, new_payload: { sort_order: expected } }); if (!bumpOk) return; expected++; } const newWidgetUuid = uuidv4(); const newPlacementUuid = uuidv4(); const widgetOk = await postOperation({ entity_urn: `urn:evershop:cms:widget_instance:${newWidgetUuid}`, old_payload: null, new_payload: { uuid: newWidgetUuid, type: overlayMe.type ?? meta?.type, name: `${meta?.name || meta?.type || overlayMe.type} (copy)`, settings: (meta?.rawSettings as Record | undefined) ?? (overlayMe.settings as Record | undefined) ?? {}, status: true } }); if (!widgetOk) return; await postOperation({ entity_urn: `urn:evershop:cms:widget_placement:${newPlacementUuid}`, old_payload: null, new_payload: { uuid: newPlacementUuid, widget_instance_uuid: newWidgetUuid, route: myPlacement?.route ?? route.id, area, sort_order: copySort, // A copy lands in the same scope as the editor session: global if the // source is on the 'all' route, otherwise the active page scope. // (Increment 3 will read the source placement's own entity_urn once // the Layers query selects it, to preserve cross-scope copies.) entity_urn: (myPlacement?.route ?? route.id) === 'all' ? null : scopeEntityUrn } }); pushPreviewToIframe(); }, [ flatLayerWidgets, placementInArea, postOperation, pushPreviewToIframe, route.id, scopeEntityUrn ] ); // Performs the delete without any confirmation. Wrapped by callers // (the WidgetChrome message handler, the SettingsDrawer footer) that // surface the ConfirmDialog first. const performDeleteWidget = useCallback( async (uid: string) => { // Cascade per spec § 7.10. Children of a container are placements // whose `area` matches `columnsContainer__col_*`. Walk // the subtree breadth-first via `Widget.columns` (which queries the // synthetic-area prefix server-side) and emit a DELETE op per // descendant widget_instance, bottom-up. Each op is its own // change_order entry — undo retraces them one at a time, which is // the documented trade-off for keeping the op model uniform. // // Limitation: source-only walk. Pending child INSERTs from this // session that haven't been published yet don't appear in // `Widget.columns` (resolver reads source widget_placement). On // publish, those orphans become placements pointing at a synthetic // area no one emits — render-time skipping handles the visual. // Cleaning them up properly waits until `widgetsForRoute` / // `Widget.columns` apply changeset overlay. const visited = new Set(); const queue: string[] = [uid]; while (queue.length > 0) { const next = queue.shift() as string; if (visited.has(next)) continue; visited.add(next); const sub = await client .query( `query DescendantsOf($uuid: String!) { widgetByUuid(uuid: $uuid) { columns { widgets { uuid } } } }`, { uuid: next }, { requestPolicy: 'network-only' } ) .toPromise(); const cols = ((sub?.data as any)?.widgetByUuid?.columns as any[] | undefined) ?? []; for (const col of cols) { for (const child of (col?.widgets as any[] | undefined) ?? []) { const childUid = child?.uuid; if (childUid && !visited.has(childUid)) queue.push(childUid); } } } // visited preserves insertion order in JS Sets; reversing yields // leaf-first emission, which keeps the publish path sensible if it // aborts mid-sequence. const ordered = [...visited].reverse(); for (const targetUid of ordered) { await postOperation({ entity_urn: `urn:evershop:cms:widget_instance:${targetUid}`, old_payload: { __delete: true }, new_payload: null }); } setSelectedWidget((prev) => (prev?.uid === uid ? null : prev)); pushPreviewToIframe(); }, [client, postOperation, pushPreviewToIframe] ); const deleteWidget = useCallback( (uid: string, widgetTypeHint?: string) => { // Container widgets (spec § 7.10): if this widget has children, the // confirm copy adds a note about orphaned children. Children's parent // FK becomes NULL on apply (no cascade); they remain in the DB but // stop rendering. const target = (layerWidgets as any[]).find((w) => w?.uuid === uid); const widgetType = (target?.type as string | undefined) ?? widgetTypeHint; const childCount = Array.isArray(target?.columns) ? target.columns.reduce( (sum: number, col: any) => sum + (Array.isArray(col?.widgets) ? col.widgets.length : 0), 0 ) : 0; const niceType = widgetType ? widgetType.replace(/_/g, ' ') : null; const childWidgetLabel = childCount === 1 ? _('1 child widget') : _('${count} child widgets', { count: String(childCount) }); const description = childCount > 0 ? ( niceType ? ( <> {_('Deleting this')} {niceType}{' '} {_('container will also hide')}{' '} {childWidgetLabel}.{' '} {_( 'This will be saved as a pending change you can publish or discard.' )} ) : ( <> {_('Deleting this container will also hide')}{' '} {childWidgetLabel}.{' '} {_( 'This will be saved as a pending change you can publish or discard.' )} ) ) : niceType ? ( <> {_('Delete this')} {niceType}{' '} {_( 'widget? This will be saved as a pending change you can publish or discard.' )} ) : ( <> {_( 'Delete this widget? This will be saved as a pending change you can publish or discard.' )} ); setConfirmState({ title: childCount > 0 ? _('Delete container widget?') : _('Delete widget?'), description, confirmLabel: _('Delete'), destructive: true, onConfirm: () => performDeleteWidget(uid) }); }, [layerWidgets, performDeleteWidget] ); // Read an image's natural dimensions admin-side (mirrors ImagePickerField), // so inline image picks persist width/height like the drawer does. const loadImageDimensions = ( url: string ): Promise<{ width: number; height: number } | null> => new Promise((resolve) => { const img = new window.Image(); img.onload = () => resolve({ width: img.naturalWidth, height: img.naturalHeight }); img.onerror = () => resolve(null); img.src = url; }); // FileBrowser pick handler for inline image editing. Writes the chosen URL // (+ captured dimensions) into the page form; the per-uid debounce collapses // it into a single op — same path as the drawer's ImagePickerField. const handlePickImage = async (file: string) => { if (!imageEdit) return; const { widgetUid, fields } = imageEdit; setImageEdit(null); const url = normalizeImageSrc(file); const base = `block.${widgetUid}`; const dims = url && (fields.widthField || fields.heightField) ? await loadImageDimensions(url) : null; pageForm.setValue(`${base}.${fields.urlField}` as any, url, { shouldDirty: true, shouldTouch: true }); if (dims && fields.widthField) { pageForm.setValue(`${base}.${fields.widthField}` as any, dims.width, { shouldDirty: true }); } if (dims && fields.heightField) { pageForm.setValue(`${base}.${fields.heightField}` as any, dims.height, { shouldDirty: true }); } }; useEffect(() => { const handleMessage = (event: MessageEvent) => { if (event.origin !== window.location.origin) return; const msg = event.data as | { type: 'widget-selected'; widgetUid: string; widgetType: string; settings: Record; } | { type: 'widget-delete'; widgetUid: string; widgetType?: string; } | { type: 'inline-edit'; widgetUid: string; fieldPath: string; value: string; settings: Record; } | { type: 'add-to-column'; parentUid: string; columnIndex: number; } | { type: 'edit-image'; widgetUid: string; fields: { urlField: string; widthField?: string; heightField?: string; }; } | ({ type: 'metafield-select' } & MetafieldSelection) | null; if (!msg) return; if (msg.type === 'widget-selected') { setSelectedMetafield(null); setSelectedWidget({ uid: msg.widgetUid, type: msg.widgetType, settings: msg.settings ?? {} }); return; } if (msg.type === 'metafield-select') { // Mutually exclusive with the widget settings drawer. setSelectedWidget(null); const { type: _t, ...payload } = msg; setSelectedMetafield(payload); return; } if (msg.type === 'widget-delete') { deleteWidget(msg.widgetUid, msg.widgetType); return; } if ( (msg as any).type === 'widget-move-up' || (msg as any).type === 'widget-move-down' ) { const direction = (msg as any).type === 'widget-move-up' ? 'up' : 'down'; const targetSort = (msg as any).sortOrder; if (typeof targetSort === 'number' && !Number.isNaN(targetSort)) { // Iframe-computed target (layout-aware) — store it verbatim. void moveWidgetTo( (msg as any).widgetUid, (msg as any).area, targetSort ); } else { // Older iframe bundle without move math — widget-neighbor swap. void moveWidget((msg as any).widgetUid, (msg as any).area, direction); } return; } if ((msg as any).type === 'widget-duplicate') { void duplicateWidget((msg as any).widgetUid, (msg as any).area); return; } if (msg.type === 'inline-edit') { // Spec § 7.3.1: write the new value into the page-level form. The // per-uid `useWatch` debounce above turns it into a single UPDATE // op — same code path as the settings drawer. Editable already // merged the patch against WidgetContext.settings and supplies // the FULL new settings. const fullSettings = msg.settings ?? {}; pageForm.setValue( `block.${msg.widgetUid}.settings` as any, fullSettings, { shouldDirty: true, shouldTouch: true } ); return; } if (msg.type === 'edit-image') { // Open the FileBrowser over the canvas for this widget+field(s). setImageEdit({ widgetUid: msg.widgetUid, fields: msg.fields }); return; } if (msg.type === 'add-to-column') { setPendingParent({ parentUid: msg.parentUid, columnIndex: msg.columnIndex }); setActiveLeftTab('widgets'); return; } if ((msg as any).type === 'pb-canvas-click') { setSelectedMetafield(null); // Click in iframe but not on a widget. Treat as "click outside the // selection target": close the drawer (unless pinned) and clear // any active layer-row highlight to keep the panel state in sync // with the iframe (which clears its own layer-hover attribute on // body click — see PageBuilderBridge). if (!drawerPinned) setSelectedWidget(null); setLayerHighlightedUid(null); return; } if ((msg as any).type === 'pb-drop') { const widgetType = (msg as any).widgetType as string; const sortOrder = (msg as any).sortOrder; const dropArea = (msg as any).area as string | undefined; const isGlobal = (msg as any).isGlobal === true; const wt = widgetTypes.find((w) => w.code === widgetType); if (!wt) return; // The iframe is the source of truth for drop positioning — it walks // sibling DOM elements (via `computeDropSortOrder`) and computes the // midpoint sort_order locally. We just forward that value plus the // target area to `handleAddWidget`. If the message lacks `sortOrder` // (older iframe build, theoretically), handleAddWidget falls back to // `100` which is safe but not position-aware. // // `isGlobal` is set by the drop zone when the target area is // wrapped in `` (header, footer, etc.). We use it // to default the new placement to `route='all'` so the widget // shows on every page — matching how those slots naturally behave. void handleAddWidget(wt, { sortOrder: typeof sortOrder === 'number' ? sortOrder : undefined, area: dropArea, isGlobal }); return; } if ((msg as any).type === 'preview-rendered') { // The iframe finished a render and reported its widget UUIDs in // DOM order. Layers tab uses this to display widgets in the same // order the storefront actually paints them — Area positioning // (header → content → footer) plus per-area sort_order combined. const order = (msg as any).widgetOrder; if (Array.isArray(order)) { setIframeWidgetOrder(order as string[]); } return; } }; window.addEventListener('message', handleMessage); return () => window.removeEventListener('message', handleMessage); }, [ deleteWidget, pageForm, handleAddWidget, widgetTypes, drawerPinned, moveWidget, moveWidgetTo, duplicateWidget ]); return (
{/* Topbar (52px) */}
{ if (pendingSavesCount > 0) { e.preventDefault(); requestNavigation(dashboardUrl); } }} className="flex items-center gap-2 select-none group" aria-label={_('EverShop · Back to page builder')} > / {route.entityScope && ( <> / )} setPickerOpen(true)} onEditSchedule={ changeset.rolloutPlan ? () => setIsScheduleEditorOpen(true) : undefined } />
setDeviceMode('desktop')} icon={Monitor} label={_('Desktop')} /> setDeviceMode('tablet')} icon={Tablet} label={_('Tablet')} /> setDeviceMode('phone')} icon={Smartphone} label={_('Phone')} />
{_('Preview')} {changeset.rolloutPlan ? ( ) : ( setIsRolloutDialogOpen(true)} onDiscard={handleDiscard} isPublishing={isPublishing} /> )}
{error && (
{error}
)}
{/* Left rail — tabbed: Widgets / Pages / Layers. Collapses to 52px (icons only). */} {/* Canvas — iframe (relative so the drawer can absolute-position over it). Click on the padding area (target === currentTarget) deselects the current widget when the drawer isn't pinned. Spec § 7.5. */} {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions -- click-empty-canvas-to-deselect is a mouse convenience; keyboard users deselect via the layers panel / Escape */}
{ if (drawerPinned) return; if (e.target !== e.currentTarget) return; setSelectedWidget(null); }} >