Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
254 lines
11 KiB
TypeScript
254 lines
11 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState, useSyncExternalStore, type RefObject } from "react";
|
|
import Link from "next/link";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
|
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
|
import { Input } from "@/app/components/ui/input";
|
|
import { Label } from "@/app/components/ui/label";
|
|
import { Switch } from "@/app/components/ui/switch";
|
|
import { Textarea } from "@/app/components/ui/textarea";
|
|
import { ErrorState } from "@/app/components/ui/states";
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
|
|
import { CopyAddress } from "./CopyAddress";
|
|
import { BLOCK_LABELS, BLOCK_TYPES, pageAddress, type CmsBlock } from "@/app/lib/cmsPages";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import { BlockFields } from "./BlockFields";
|
|
import { usePageDraft } from "./usePageDraft";
|
|
import { LeaveGuard } from "./LeaveGuard";
|
|
import { VisualEditor } from "./visual/VisualEditor";
|
|
|
|
// The landing-page editor, ported from babyboo's PageEditor. State and actions live in usePageDraft, owned here so
|
|
// they survive a window resize that switches between the on-page editor (1024 px and up) and the form editor.
|
|
|
|
export type Draft = ReturnType<typeof usePageDraft>;
|
|
/** Asks before the destructive actions; the dialogs are the editor's, whichever layout shows. */
|
|
export interface Ask { remove(): void; discard(): void }
|
|
|
|
export function FieldError({ message }: { message?: string }) {
|
|
return message ? <p role="alert" className="text-sm text-destructive">{message}</p> : null;
|
|
}
|
|
|
|
const WIDE = "(min-width: 1024px)";
|
|
const wideNow = () => window.matchMedia(WIDE).matches;
|
|
const onWideChange = (cb: () => void) => {
|
|
const query = window.matchMedia(WIDE);
|
|
query.addEventListener("change", cb);
|
|
return () => query.removeEventListener("change", cb);
|
|
};
|
|
|
|
/** pageId edits a page; fromId opens an unsaved copy of one (Duplicate); initialBlocks start a new page (templates). */
|
|
export function PageEditor(props: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
|
|
const t = useT();
|
|
const p = usePageDraft(props);
|
|
const wide = useSyncExternalStore(onWideChange, wideNow, () => false);
|
|
const [confirmDelete, setConfirmDelete] = useState(false);
|
|
const [confirmDiscard, setConfirmDiscard] = useState(false);
|
|
const ask: Ask = { remove: () => setConfirmDelete(true), discard: () => setConfirmDiscard(true) };
|
|
|
|
if (p.loadError) return <ErrorState message={t(p.loadError)} />;
|
|
if (p.loading) return null;
|
|
|
|
return (
|
|
<>
|
|
{wide ? <VisualEditor p={p} ask={ask} /> : <FormEditor p={p} ask={ask} />}
|
|
<LeaveGuard dirty={p.dirty} />
|
|
{confirmDiscard ? (
|
|
<ConfirmDialog
|
|
title={t("PagesDiscardTitle")}
|
|
message={t("PagesDiscardMessage", { title: p.draft.title })}
|
|
confirmLabel={t("PagesDiscardChanges")}
|
|
destructive
|
|
busy={p.saving}
|
|
onConfirm={() => void p.discardChanges().finally(() => setConfirmDiscard(false))}
|
|
onCancel={() => setConfirmDiscard(false)}
|
|
/>
|
|
) : null}
|
|
{confirmDelete ? (
|
|
<ConfirmDialog
|
|
title={t("PagesDeleteTitle")}
|
|
message={t("PagesDeleteMessage", { title: p.draft.title })}
|
|
confirmLabel={t("PagesDelete")}
|
|
destructive
|
|
busy={p.saving}
|
|
onConfirm={() => void p.remove().then((ok) => { if (!ok) setConfirmDelete(false); })}
|
|
onCancel={() => setConfirmDelete(false)}
|
|
/>
|
|
) : null}
|
|
</>
|
|
);
|
|
}
|
|
|
|
/** The page's own links: its address, Duplicate, Preview and, once published, View page. */
|
|
export function PageLinks({ p }: { p: Draft }) {
|
|
const t = useT();
|
|
const { draft, saved, code } = p;
|
|
return (
|
|
<>
|
|
{saved && code ? <span className="mr-auto"><CopyAddress address={pageAddress(code, saved.slug)} /></span> : null}
|
|
{draft.id != null ? (
|
|
<>
|
|
<Button variant="outline" asChild>
|
|
<Link href={`/pages/new?from=${draft.id}`}>{t("PagesDuplicate")}</Link>
|
|
</Button>
|
|
<Button variant="outline" asChild>
|
|
<Link href={`/pages/${draft.id}/preview`}>{t("PagesPreview")}</Link>
|
|
</Button>
|
|
</>
|
|
) : null}
|
|
{saved?.status === "PUBLISHED" && code ? (
|
|
<Button variant="outline" asChild>
|
|
<a href={pageAddress(code, saved.slug)} target="_blank" rel="noopener noreferrer">{t("PagesViewPage")}</a>
|
|
</Button>
|
|
) : null}
|
|
</>
|
|
);
|
|
}
|
|
|
|
/** The save outcome, and for a published page with unsaved-to-live edits, Publish changes and Discard changes. */
|
|
export function PageMessages({ p, ask, banner }: { p: Draft; ask: Ask; banner?: RefObject<HTMLDivElement | null> }) {
|
|
const t = useT();
|
|
return (
|
|
<>
|
|
{p.summary && <p role="alert" className="text-sm text-destructive">{p.summary}</p>}
|
|
{p.notice && <p role="status" className="text-sm text-positive">{t(p.notice)}</p>}
|
|
{p.hasDraft && p.draft.status === "PUBLISHED" ? (
|
|
<div ref={banner} className="flex scroll-mt-20 flex-wrap items-center gap-2 rounded-md border border-warning/30 bg-warning/10 px-3 py-2 text-sm">
|
|
<p className="mr-auto">{t("PagesDraftBanner")}</p>
|
|
<Button type="button" size="sm" variant="outline" disabled={p.saving} onClick={ask.discard}>{t("PagesDiscardChanges")}</Button>
|
|
<Button type="button" size="sm" disabled={p.saving} onClick={() => void p.publishChanges()}>{t("PagesPublishChanges")}</Button>
|
|
</div>
|
|
) : null}
|
|
</>
|
|
);
|
|
}
|
|
|
|
/** Company (a super admin's new page), title, slug and meta description. */
|
|
export function PageSettings({ p }: { p: Draft }) {
|
|
const t = useT();
|
|
const { draft, errors, saving, code } = p;
|
|
return (
|
|
<Card>
|
|
<CardHeader><CardTitle>{t("PagesPageCard")}</CardTitle></CardHeader>
|
|
<CardContent className="space-y-4">
|
|
{p.isSuper && p.isNew ? (
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="page-company">{t("Company")}</Label>
|
|
<Select value={draft.companyId ? String(draft.companyId) : ""} disabled={saving} onValueChange={(v) => p.changeCompany(Number(v))}>
|
|
<SelectTrigger id="page-company" aria-invalid={!!errors.companyId} className="w-full"><SelectValue placeholder={t("SelectCompany")} /></SelectTrigger>
|
|
<SelectContent>
|
|
{p.companies.map((c) => <SelectItem key={c.id} value={String(c.id)}>{c.code}</SelectItem>)}
|
|
</SelectContent>
|
|
</Select>
|
|
<FieldError message={errors.companyId} />
|
|
</div>
|
|
) : null}
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="page-title">{t("Title")}</Label>
|
|
<Input id="page-title" value={draft.title} disabled={saving} aria-invalid={!!errors.title} onChange={(e) => p.setTitle(e.target.value)} />
|
|
<FieldError message={errors.title} />
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="page-slug">{t("PagesSlug")}</Label>
|
|
<Input id="page-slug" value={draft.slug} disabled={saving} aria-invalid={!!errors.slug} onChange={(e) => p.patch({ slug: e.target.value, slugTouched: true })} />
|
|
<p className="text-xs text-muted-foreground">{t("PagesAddressHint", { address: pageAddress(code || "…", draft.slug || "…") })}</p>
|
|
<FieldError message={errors.slug} />
|
|
</div>
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor="page-meta">{t("PagesMetaDescription")}</Label>
|
|
<Textarea id="page-meta" rows={3} value={draft.metaDescription} disabled={saving} aria-invalid={!!errors.metaDescription} onChange={(e) => p.patch({ metaDescription: e.target.value })} />
|
|
<p className="tabular text-xs text-muted-foreground">{`${draft.metaDescription.trim().length}/160`}</p>
|
|
<FieldError message={errors.metaDescription} />
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
/** Draft or published, and the hide-header switch. */
|
|
export function StatusSettings({ p }: { p: Draft }) {
|
|
const t = useT();
|
|
const { draft, errors, saving } = p;
|
|
return (
|
|
<Card>
|
|
<CardHeader><CardTitle>{t("Status")}</CardTitle></CardHeader>
|
|
<CardContent className="space-y-2">
|
|
{(["DRAFT", "PUBLISHED"] as const).map((s) => (
|
|
<label key={s} className="flex items-center gap-2 text-sm">
|
|
<input type="radio" name="page-status" value={s} checked={draft.status === s} disabled={saving} onChange={() => p.patch({ status: s })} />
|
|
{t(s === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
|
|
</label>
|
|
))}
|
|
<FieldError message={errors.status} />
|
|
<div className="flex items-center gap-2 pt-2 text-sm">
|
|
<Switch id="page-hide-header" checked={draft.hideHeader} disabled={saving} onCheckedChange={(on) => p.patch({ hideHeader: on })} />
|
|
<Label htmlFor="page-hide-header">{t("PagesHideHeader")}</Label>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
/** The form editor: narrow windows. */
|
|
function FormEditor({ p, ask }: { p: Draft; ask: Ask }) {
|
|
const t = useT();
|
|
const { draft, rows, errors, saving } = p;
|
|
// Save sits below a long form, so the unpublished-changes banner is scrolled into view after a save that leaves one.
|
|
const draftBanner = useRef<HTMLDivElement>(null);
|
|
useEffect(() => {
|
|
if (p.revealDraft) draftBanner.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
|
|
}, [p.revealDraft]);
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
<div className="flex flex-wrap items-center justify-end gap-2"><PageLinks p={p} /></div>
|
|
<PageMessages p={p} ask={ask} banner={draftBanner} />
|
|
|
|
<div className="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
|
|
<div className="space-y-4">
|
|
<PageSettings p={p} />
|
|
{rows.map((row, index) => (
|
|
<BlockFields
|
|
key={row.key}
|
|
id={row.key}
|
|
block={row.block}
|
|
index={index}
|
|
count={rows.length}
|
|
errors={p.blockErrors(index)}
|
|
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(index, delta)}
|
|
onRemove={() => p.removeBlock(row.key)}
|
|
onChooseImage={(file) => p.chooseImage(row.key, file)}
|
|
onUploadImage={p.uploadImage}
|
|
/>
|
|
))}
|
|
<FieldError message={errors.blocks} />
|
|
|
|
<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>
|
|
</div>
|
|
|
|
<div className="space-y-4"><StatusSettings p={p} /></div>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
|
{draft.id != null ? (
|
|
<Button type="button" variant="outline" className="text-destructive" disabled={saving} onClick={ask.remove}>
|
|
{t("PagesDelete")}
|
|
</Button>
|
|
) : <span />}
|
|
<Button type="button" disabled={saving} onClick={() => void p.save()}>{t("Save")}</Button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|