The toolbar hung 20 px above the selected section, so it was cut off for the first section and for any section scrolled to the top of the canvas. It now sits inside the section's top-right corner, and the hero's image button moves to the top-left so the two never overlap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
231 lines
12 KiB
TypeScript
231 lines
12 KiB
TypeScript
"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<Device>("DESKTOP");
|
|
// The "Add section" menu open at this place, and a section being dragged with where it would land.
|
|
const [adding, setAdding] = useState<number | null>(null);
|
|
const [drag, setDrag] = useState<{ from: number; to: number | null } | null>(null);
|
|
const file = useRef<HTMLInputElement>(null);
|
|
const imageFor = useRef<number | null>(null);
|
|
const canvas = useRef<HTMLDivElement>(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) => (
|
|
<div role="menu" aria-label={t("PagesAddSection")} className="absolute top-full left-1/2 z-30 mt-1 grid w-56 -translate-x-1/2 gap-0.5 rounded-md border bg-popover p-1 text-popover-foreground shadow-md">
|
|
{BLOCK_TYPES.map((type: BlockType) => (
|
|
<button key={type} type="button" role="menuitem" className="rounded-sm px-2 py-1.5 text-left text-sm hover:bg-accent hover:text-accent-foreground"
|
|
onClick={(e) => { e.stopPropagation(); p.insertBlock(at, type); setAdding(null); }}>
|
|
{t(BLOCK_LABELS[type])}
|
|
</button>
|
|
))}
|
|
</div>
|
|
);
|
|
|
|
const dropZone = (i: number) => {
|
|
if (!drag) return null;
|
|
const over = (e: DragEvent<HTMLDivElement>) => {
|
|
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<HTMLDivElement>) => {
|
|
e.preventDefault();
|
|
if (drag.to != null) p.moveBlockTo(drag.from, drag.to > drag.from ? drag.to - 1 : drag.to);
|
|
setDrag(null);
|
|
};
|
|
return (
|
|
<div className="absolute inset-0 z-40" onDragOver={over} onDrop={drop}>
|
|
{drag.to === i ? <div className="absolute -top-1 right-0 left-0 h-1 rounded bg-primary" /> : null}
|
|
{drag.to === i + 1 ? <div className="absolute right-0 -bottom-1 left-0 h-1 rounded bg-primary" /> : null}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const tool = (label: string, icon: ReactNode, onClick: () => void, disabled?: boolean) => (
|
|
<Button type="button" size="icon" variant="ghost" className="size-8" aria-label={label} title={label} disabled={disabled || saving}
|
|
onClick={(e) => { e.stopPropagation(); onClick(); }}>
|
|
{icon}
|
|
</Button>
|
|
);
|
|
|
|
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 ? (
|
|
<div role="toolbar" aria-label={t(BLOCK_LABELS[rows[i].block.type])} onClick={(e) => 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">
|
|
<span draggable aria-label={t("PagesDragSection")} title={t("PagesDragSection")}
|
|
className="flex size-8 cursor-grab items-center justify-center rounded-md hover:bg-accent"
|
|
onDragStart={(e) => { e.dataTransfer.setData("text/plain", String(i)); e.dataTransfer.effectAllowed = "move"; setDrag({ from: i, to: null }); }}
|
|
onDragEnd={() => setDrag(null)}>
|
|
<GripVertical aria-hidden="true" className="size-4" />
|
|
</span>
|
|
{tool(t("PagesMoveUp"), <ArrowUp />, () => p.moveBlock(i, -1), i === 0)}
|
|
{tool(t("PagesMoveDown"), <ArrowDown />, () => p.moveBlock(i, 1), i === rows.length - 1)}
|
|
{tool(t("PagesDuplicateSection"), <Copy />, () => p.duplicateBlock(i))}
|
|
{tool(t("PagesRemoveBlock"), <Trash2 />, () => p.removeBlock(rows[i].key))}
|
|
</div>
|
|
) : null}
|
|
<div className={`absolute bottom-0 left-1/2 z-20 -translate-x-1/2 translate-y-1/2 ${selected === i || adding === i + 1 ? "" : "opacity-0 group-hover/section:opacity-100 focus-within:opacity-100"}`}>
|
|
<Button type="button" size="sm" variant="outline" className="h-7 rounded-full bg-background shadow-sm" disabled={saving}
|
|
aria-expanded={adding === i + 1} onClick={(e) => { e.stopPropagation(); setAdding(adding === i + 1 ? null : i + 1); }}>
|
|
<Plus aria-hidden="true" />{t("PagesAddSection")}
|
|
</Button>
|
|
{adding === i + 1 ? addMenu(i + 1) : null}
|
|
</div>
|
|
{dropZone(i)}
|
|
</>
|
|
),
|
|
};
|
|
|
|
return (
|
|
<div className="space-y-3" onKeyDown={onKeyDown} onBlur={p.endTyping}>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<h2 className="max-w-80 truncate text-lg font-semibold">{draft.title || t("PagesUntitled")}</h2>
|
|
<Badge variant={draft.status === "PUBLISHED" ? "positive" : "secondary"}>{t(draft.status === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}</Badge>
|
|
<div role="group" aria-label={t("PagesCanvasView")} className="ml-2 inline-flex rounded-md border p-0.5">
|
|
{(["DESKTOP", "PHONE"] as const).map((d) => (
|
|
<Button key={d} type="button" size="sm" variant={device === d ? "secondary" : "ghost"} aria-pressed={device === d} onClick={() => setDevice(d)}>
|
|
{t(d === "PHONE" ? "PagesPhone" : "PagesDesktop")}
|
|
</Button>
|
|
))}
|
|
</div>
|
|
<Button type="button" size="icon" variant="ghost" aria-label={t("PagesUndo")} title={t("PagesUndo")} disabled={!p.canUndo || saving} onClick={() => history(false)}><Undo2 /></Button>
|
|
<Button type="button" size="icon" variant="ghost" aria-label={t("PagesRedo")} title={t("PagesRedo")} disabled={!p.canRedo || saving} onClick={() => history(true)}><Redo2 /></Button>
|
|
<span className="mx-auto" />
|
|
<PageLinks p={p} />
|
|
{draft.id != null ? (
|
|
<Button type="button" variant="outline" className="text-destructive" disabled={saving} onClick={ask.remove}>{t("PagesDelete")}</Button>
|
|
) : null}
|
|
<Button type="button" disabled={saving} onClick={() => void p.save()}>{t("Save")}</Button>
|
|
</div>
|
|
<PageMessages p={p} ask={ask} />
|
|
|
|
<div className="grid h-[calc(100svh-14rem)] min-h-[480px] grid-cols-[minmax(0,1fr)_360px] gap-4">
|
|
<div ref={canvas} className="min-h-0 rounded-lg border bg-muted/40 p-2">
|
|
<PageCanvas device={device} title={t("PagesCanvas")}>
|
|
<LandingPage
|
|
company={p.branding ?? { code: p.code, name: p.code }}
|
|
page={{ slug: draft.slug, title: draft.title, hideHeader: draft.hideHeader, blocks: rows.map((r) => 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}
|
|
/>
|
|
</PageCanvas>
|
|
</div>
|
|
<aside aria-label={t(row ? BLOCK_LABELS[row.block.type] : "PagesPageSettings")} className="min-h-0 space-y-4 overflow-y-auto pr-1">
|
|
{row && selected != null ? (
|
|
<>
|
|
<Button type="button" variant="ghost" size="sm" onClick={() => p.select(null)}><ArrowLeft aria-hidden="true" />{t("PagesPageSettings")}</Button>
|
|
<BlockFields
|
|
key={row.key}
|
|
id={row.key}
|
|
block={row.block}
|
|
index={selected}
|
|
count={rows.length}
|
|
errors={p.blockErrors(selected)}
|
|
saving={saving}
|
|
events={p.events}
|
|
pendingImage={p.pending[row.key] && { name: p.pending[row.key].file.name, preview: p.pending[row.key].preview }}
|
|
onChange={(update) => p.updateBlock(row.key, update)}
|
|
onMove={(delta) => p.moveBlock(selected, delta)}
|
|
onRemove={() => p.removeBlock(row.key)}
|
|
onChooseImage={(f) => p.chooseImage(row.key, f)}
|
|
/>
|
|
</>
|
|
) : (
|
|
<>
|
|
<PageSettings p={p} />
|
|
<StatusSettings p={p} />
|
|
<div className="space-y-2">
|
|
<p className="text-sm font-medium">{t("PagesAddSection")}</p>
|
|
<div className="flex flex-wrap gap-2">
|
|
{BLOCK_TYPES.map((type) => (
|
|
<Button key={type} type="button" variant="outline" size="sm" disabled={saving} onClick={() => p.addBlock(type)}>
|
|
{t("PagesAddBlock", { type: t(BLOCK_LABELS[type]) })}
|
|
</Button>
|
|
))}
|
|
</div>
|
|
<FieldError message={p.errors.blocks} />
|
|
</div>
|
|
</>
|
|
)}
|
|
</aside>
|
|
</div>
|
|
<input ref={file} type="file" accept="image/png,image/jpeg,image/webp" hidden aria-hidden="true" tabIndex={-1}
|
|
onChange={(e) => {
|
|
const chosen = e.target.files?.[0];
|
|
if (chosen && imageFor.current != null) p.chooseImage(imageFor.current, chosen);
|
|
e.target.value = "";
|
|
}} />
|
|
</div>
|
|
);
|
|
}
|