"use client"; import { useEffect, useRef, useState, type DragEvent, type KeyboardEvent, type ReactNode } from "react"; import { ArrowDown, ArrowLeft, ArrowUp, Copy, GripVertical, Plus, Redo2, Trash2, Undo2 } from "lucide-react"; import { Badge } from "@/app/components/ui/badge"; import { Button } from "@/app/components/ui/button"; import { BLOCK_LABELS, BLOCK_TYPES, type BlockType } from "@/app/lib/cmsPages"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import { BlockFields } from "../BlockFields"; import { LandingPage } from "../CmsBlocks"; import type { PageEdit } from "../CmsEdit"; import { PageCanvas, type Device } from "../PageCanvas"; import { FieldError, PageLinks, PageMessages, PageSettings, StatusSettings, type Ask, type Draft } from "../PageEditor"; // The on-page editor (add-page-visual-editor): the page on a canvas, edited in place, with the selected section's // settings (or the page's) in the side panel. State and actions are the shared usePageDraft. /** The focused element, looking into same-origin frames (the canvas). */ function focused(): HTMLElement | null { let el = document.activeElement; while (el instanceof HTMLIFrameElement && el.contentDocument?.activeElement) el = el.contentDocument.activeElement; return el as HTMLElement | null; } export function VisualEditor({ p, ask }: { p: Draft; ask: Ask }) { const t = useT(); const { draft, rows, saving } = p; const [device, setDevice] = useState("DESKTOP"); // The "Add section" menu open at this place, and a section being dragged with where it would land. const [adding, setAdding] = useState(null); const [drag, setDrag] = useState<{ from: number; to: number | null } | null>(null); const file = useRef(null); const imageFor = useRef(null); const canvas = useRef(null); const selected = p.selected != null && p.selected < rows.length ? p.selected : null; const row = selected != null ? rows[selected] : null; // A refused block: bring it into view on the canvas. useEffect(() => { if (!p.revealed) return; const doc = canvas.current?.querySelector("iframe")?.contentDocument; doc?.querySelector(`[data-index="${p.revealed.index}"]`)?.scrollIntoView?.({ behavior: "smooth", block: "center" }); }, [p.revealed]); /** Undo and redo put back values: a focused field is let go first, so it shows them. */ const history = (redo: boolean) => { focused()?.blur(); if (redo) p.redo(); else p.undo(); }; const onKeyDown = (e: KeyboardEvent | globalThis.KeyboardEvent) => { if (!(e.ctrlKey || e.metaKey) || e.key.toLowerCase() !== "z") return; // Inside rich text, its own undo works on the text until it loses focus. if ((e.target as Element).closest?.(".ProseMirror")) return; e.preventDefault(); history(e.shiftKey); }; // Focus that fell out of the editor (a toolbar button removed with its section drops it on the canvas body; a // button that just went disabled drops it on the page): the key still undoes, unless the editor already handled it // or it is typing in some other field. useEffect(() => { const onBody = (e: globalThis.KeyboardEvent) => { const el = e.target as HTMLElement; if (!e.defaultPrevented && !el.isContentEditable && !el.closest?.("input, textarea, select")) onKeyDown(e); }; const docs = [document, canvas.current?.querySelector("iframe")?.contentDocument].filter((d): d is Document => !!d); docs.forEach((d) => d.addEventListener("keydown", onBody)); return () => docs.forEach((d) => d.removeEventListener("keydown", onBody)); }); const addMenu = (at: number) => (
{BLOCK_TYPES.map((type: BlockType) => ( ))}
); const dropZone = (i: number) => { if (!drag) return null; const over = (e: DragEvent) => { e.preventDefault(); const box = e.currentTarget.getBoundingClientRect(); const to = e.clientY < box.top + box.height / 2 ? i : i + 1; if (drag.to !== to) setDrag({ ...drag, to }); }; const drop = (e: DragEvent) => { e.preventDefault(); if (drag.to != null) p.moveBlockTo(drag.from, drag.to > drag.from ? drag.to - 1 : drag.to); setDrag(null); }; return (
{drag.to === i ?
: null} {drag.to === i + 1 ?
: null}
); }; const tool = (label: string, icon: ReactNode, onClick: () => void, disabled?: boolean) => ( ); const edit: PageEdit = { selected, select: (i) => { p.select(i); setAdding(null); }, text: (i, path, value) => p.text(rows[i].key, path, value), html: (i, value) => p.html(rows[i].key, value), image: (i) => { imageFor.current = rows[i].key; file.current?.click(); }, preview: (i) => p.pending[rows[i]?.key]?.preview, stale: p.stale, frameVersion: p.frameVersion, chrome: (i) => ( <> {selected === i ? (
e.stopPropagation()} className="absolute top-2 right-2 z-30 flex items-center gap-0.5 rounded-md border bg-popover p-0.5 text-popover-foreground shadow-md"> { e.dataTransfer.setData("text/plain", String(i)); e.dataTransfer.effectAllowed = "move"; setDrag({ from: i, to: null }); }} onDragEnd={() => setDrag(null)}> {tool(t("PagesMoveUp"), , () => p.moveBlock(i, -1), i === 0)} {tool(t("PagesMoveDown"), , () => p.moveBlock(i, 1), i === rows.length - 1)} {tool(t("PagesDuplicateSection"), , () => p.duplicateBlock(i))} {tool(t("PagesRemoveBlock"), , () => p.removeBlock(rows[i].key))}
) : null}
{adding === i + 1 ? addMenu(i + 1) : null}
{dropZone(i)} ), }; return (

{draft.title || t("PagesUntitled")}

{t(draft.status === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
{(["DESKTOP", "PHONE"] as const).map((d) => ( ))}
{draft.id != null ? ( ) : null}
r.block) }} preview // A page never saved has no saved version to show: its Custom HTML frames stay blank, marked "Save to update". frameBase={draft.id != null ? `/pages/${draft.id}/preview/frame` : "about:blank#"} edit={edit} />
{ const chosen = e.target.files?.[0]; if (chosen && imageFor.current != null) p.chooseImage(imageFor.current, chosen); e.target.value = ""; }} />
); }