Files
co-lite/solvway-admin-portal/app/components/pages/BlockFields.tsx
T
ngqileandClaude Opus 5.5 e4ad18a8a3 feat(pages): a top bar section, section labels and serif headings
Landing pages gain a Top bar section (the company logo and an optional button,
kept at the top of the window, first section only), a short label above the
headings of five section types, and serif section headings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-04 12:28:09 +08:00

395 lines
19 KiB
TypeScript

"use client";
import { useState, type ReactNode } from "react";
import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
import { BLOCK_LABELS, ICONS, LOOKS, imageSrc, type CmsBlock, type CmsCard, type Look } from "@/app/lib/cmsPages";
import { Button } from "@/app/components/ui/button";
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 { useT } from "@/app/lib/i18n/MessagesProvider";
import { RichTextEditor } from "./RichTextEditor";
import { CopyAddress } from "./CopyAddress";
// One block of the page editor, ported from babyboo's BlockFields: a fieldset with move/remove and its type's fields.
/** Field paths (relative to the block) each type shows inline; any other error shows at the block's top. Every type also shows "anchor". */
const INLINE: Record<string, string[]> = {
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl", "eventUuid", "fullWidth", "formHeading", "formText", "thanksText", "cards"],
RICH_TEXT: ["html"],
IMAGE_TEXT: ["imageId", "imagePosition", "eyebrow", "heading", "html", "buttonLabel", "buttonUrl"],
FAQ: ["eyebrow", "heading", "items"],
FORM: ["heading", "eventUuid", "thanksText"],
HTML: ["html"],
FEATURES: ["eyebrow", "heading", "text", "cards"],
STEPS: ["eyebrow", "heading", "cards"],
TRUST: ["cards"],
CTA: ["eyebrow", "heading", "text", "buttonLabel", "buttonUrl"],
FOOTER: ["cards", "text"],
TOPBAR: ["buttonLabel", "buttonUrl"],
};
const LISTED = /^(items\[\d+\]\.(question|answer)|cards\[\d+\]\.(icon|title|text))$/;
// add-page-sections: labels for looks, feature icons and each card type's wording.
const LOOK_LABELS: Record<Look, string> = { DEFAULT: "PagesLookDefault", MUTED: "PagesLookMuted", DARK: "PagesLookDark", ACCENT: "PagesLookAccent" };
const ICON_LABELS: Record<string, string> = {
wifi: "PagesIconWifi", phone: "PagesIconPhone", tv: "PagesIconTv", monitor: "PagesIconMonitor", lock: "PagesIconLock",
"shield-check": "PagesIconShieldCheck", cloud: "PagesIconCloud", wrench: "PagesIconWrench", headset: "PagesIconHeadset",
users: "PagesIconUsers", calendar: "PagesIconCalendar", star: "PagesIconStar",
};
// add-hero-full-width: a hero's points are title-only cards, and it may have none.
// add-landing-thanks-and-footer: a footer's columns are title-and-text cards, 1 to 4.
const CARD_KINDS: Record<string, { legend: string; add: string; icon: boolean; text: boolean; min: number; max: number; empty: CmsCard }> = {
FEATURES: { legend: "PagesCardN", add: "PagesAddCard", icon: true, text: true, min: 2, max: 6, empty: { icon: "star", title: "", text: "" } },
STEPS: { legend: "PagesStepN", add: "PagesAddStep", icon: false, text: true, min: 2, max: 6, empty: { title: "", text: "" } },
TRUST: { legend: "PagesItemN", add: "PagesAddItem", icon: false, text: false, min: 2, max: 6, empty: { title: "" } },
HERO: { legend: "PagesPointN", add: "PagesAddPoint", icon: false, text: false, min: 0, max: 6, empty: { title: "" } },
FOOTER: { legend: "PagesColumnN", add: "PagesAddColumn", icon: false, text: true, min: 1, max: 4, empty: { title: "", text: "" } },
};
const SELECT = "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
export interface EventOption {
uuid: string;
name: string;
}
function FieldError({ message }: { message?: string }) {
return message ? <p role="alert" className="text-sm text-destructive">{message}</p> : null;
}
function Field({ id, label, error, children }: { id: string; label: string; error?: string; children: ReactNode }) {
return (
<div className="space-y-1.5">
<Label htmlFor={id}>{label}</Label>
{children}
<FieldError message={error} />
</div>
);
}
export function BlockFields(props: {
block: CmsBlock;
/** Stable per-block key, for element ids. */
id: number;
index: number;
count: number;
/** Translated server errors for this block, keyed by path relative to it ("buttonUrl", "items[1].answer"). */
errors: Record<string, string>;
saving: boolean;
events: EventOption[];
/** A chosen image that uploads on save: its file name and, once read, a data-URL preview. */
pendingImage?: { name: string; preview?: string };
onChange: (update: (block: CmsBlock) => CmsBlock) => void;
onMove: (delta: -1 | 1) => void;
onRemove: () => void;
onChooseImage: (file: File) => void;
/** Uploads an image for a Custom HTML block at once (add-html-image-upload); rejects with the reason to show. */
onUploadImage?: (file: File) => Promise<number>;
}) {
const { block, id, index, count, errors, saving, events, pendingImage, onChange, onMove, onRemove } = props;
const t = useT();
const set = (patch: Partial<CmsBlock>) => onChange((b) => ({ ...b, ...patch }));
const fid = (name: string) => `block-${id}-${name}`;
const topErrors = Object.entries(errors).filter(([path]) => path !== "anchor" && path !== "look" && !INLINE[block.type]?.includes(path) && !LISTED.test(path));
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor" | "formHeading" | "formText" | "thanksText" | "eyebrow", labelCode: string) => (
<Field id={fid(name)} label={t(labelCode)} error={errors[name]}>
<Input id={fid(name)} value={block[name] ?? ""} disabled={saving} aria-invalid={!!errors[name]} onChange={(e) => set({ [name]: e.target.value })} />
</Field>
);
const richText = (labelCode: string) => (
<Field id={fid("html")} label={t(labelCode)} error={errors.html}>
<RichTextEditor id={fid("html")} label={t(labelCode)} value={block.html ?? ""} disabled={saving} invalid={!!errors.html} onChange={(html) => set({ html })} />
</Field>
);
// add-html-image-upload: this panel's uploads, newest first; their links are pasted into the HTML by hand.
const [uploads, setUploads] = useState<number[]>([]);
const [uploadError, setUploadError] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
async function upload(file: File) {
if (!props.onUploadImage) return;
setUploadError(null);
setUploading(true);
try {
const imageId = await props.onUploadImage(file);
setUploads((u) => [imageId, ...u]);
} catch (err) {
setUploadError(err instanceof Error ? err.message : String(err));
} finally {
setUploading(false);
}
}
const preview = pendingImage?.preview ?? (block.imageId ? imageSrc(block.imageId) : undefined);
// The FORM block's event, and the hero's optional sign-up form (add-hero-signup-form): the same picker and hint.
const eventPicker = (labelCode: string, emptyCode: string) => (
<Field id={fid("event")} label={t(labelCode)} error={errors.eventUuid}>
<select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid}
onChange={(e) => set(e.target.value ? { eventUuid: e.target.value } : { eventUuid: null, formHeading: undefined, formText: undefined, thanksText: undefined })}>
<option value="">{t(emptyCode)}</option>
{events.map((ev) => <option key={ev.uuid} value={ev.uuid}>{ev.name}</option>)}
{block.eventUuid && !events.some((ev) => ev.uuid === block.eventUuid) ? (
<option value={block.eventUuid}>{t("PagesUnavailableEvent")}</option>
) : null}
</select>
<p className="text-xs text-muted-foreground">{t("PagesFormEventHint")}</p>
</Field>
);
const image = (
<Field id={fid("image")} label={t("PagesImage")} error={errors.imageId}>
<Input
id={fid("image")}
type="file"
accept="image/png,image/jpeg,image/webp"
disabled={saving}
onChange={(e) => {
const file = e.target.files?.[0];
if (file) props.onChooseImage(file);
}}
/>
{pendingImage ? <p className="text-xs text-muted-foreground">{t("PagesUploadsOnSave", { name: pendingImage.name })}</p> : null}
{/* eslint-disable-next-line @next/next/no-img-element -- a local data URL or an uploaded image of unknown size */}
{preview ? <img src={preview} alt={t("PagesImagePreview")} className="max-h-40 rounded-md border" /> : null}
</Field>
);
const kind = CARD_KINDS[block.type];
const cards = block.cards ?? [];
const setCards = (next: CmsCard[]) => set({ cards: next });
const moveCard = (i: number, delta: -1 | 1) => {
const next = [...cards];
[next[i], next[i + delta]] = [next[i + delta], next[i]];
setCards(next);
};
const cardList = kind ? (
<>
{cards.map((card, i) => {
const err = (f: string) => errors[`cards[${i}].${f}`];
const cardField = (f: "title" | "text", label: string, multiline: boolean) => (
<Field id={fid(`c${i}${f}`)} label={label} error={err(f)}>
{multiline
? <Textarea id={fid(`c${i}${f}`)} rows={2} value={card[f] ?? ""} disabled={saving} aria-invalid={!!err(f)}
onChange={(e) => setCards(cards.map((c, j) => (j === i ? { ...c, [f]: e.target.value } : c)))} />
: <Input id={fid(`c${i}${f}`)} value={card[f] ?? ""} disabled={saving} aria-invalid={!!err(f)}
onChange={(e) => setCards(cards.map((c, j) => (j === i ? { ...c, [f]: e.target.value } : c)))} />}
</Field>
);
return (
<fieldset key={i} className="space-y-2 rounded-md border p-3">
<legend className="px-1 text-sm font-medium">{t(kind.legend, { number: i + 1 })}</legend>
{kind.icon ? (
<Field id={fid(`c${i}icon`)} label={t("PagesCardIcon")} error={err("icon")}>
<select id={fid(`c${i}icon`)} className={SELECT} value={card.icon ?? "star"} disabled={saving} aria-invalid={!!err("icon")}
onChange={(e) => setCards(cards.map((c, j) => (j === i ? { ...c, icon: e.target.value } : c)))}>
{Object.keys(ICONS).map((name) => <option key={name} value={name}>{t(ICON_LABELS[name])}</option>)}
</select>
</Field>
) : null}
{cardField("title", kind.min ? t("PagesCardTitle") : t(kind.legend, { number: i + 1 }), false)}
{kind.text ? cardField("text", t("PagesCardText"), true) : null}
<div className="flex flex-wrap gap-1">
<Button type="button" variant="ghost" size="sm" disabled={saving || i === 0} onClick={() => moveCard(i, -1)}>{t("PagesMoveUp")}</Button>
<Button type="button" variant="ghost" size="sm" disabled={saving || i === cards.length - 1} onClick={() => moveCard(i, 1)}>{t("PagesMoveDown")}</Button>
<Button type="button" variant="ghost" size="sm" disabled={saving || cards.length <= kind.min} onClick={() => setCards(cards.filter((_, j) => j !== i))}>{t("PagesRemoveCard")}</Button>
</div>
</fieldset>
);
})}
<FieldError message={errors.cards} />
<Button type="button" variant="outline" size="sm" disabled={saving || cards.length >= kind.max} onClick={() => setCards([...cards, { ...kind.empty }])}>
<Plus aria-hidden="true" className="size-4" />
{t(kind.add)}
</Button>
</>
) : null;
const items = block.items ?? [];
const setItems = (next: typeof items) => set({ items: next });
return (
<fieldset className="space-y-4 rounded-lg border bg-card p-4">
<legend className="px-1 text-sm font-medium">{t("PagesBlockLegend", { number: index + 1, type: t(BLOCK_LABELS[block.type]) })}</legend>
<div className="flex items-center gap-1">
<Button type="button" variant="ghost" size="sm" aria-label={t("PagesMoveUp")} disabled={saving || index === 0} onClick={() => onMove(-1)}>
<ArrowUp aria-hidden="true" className="size-4" />
</Button>
<Button type="button" variant="ghost" size="sm" aria-label={t("PagesMoveDown")} disabled={saving || index === count - 1} onClick={() => onMove(1)}>
<ArrowDown aria-hidden="true" className="size-4" />
</Button>
<Button type="button" variant="ghost" size="sm" aria-label={t("PagesRemoveBlock")} disabled={saving} onClick={onRemove}>
<Trash2 aria-hidden="true" className="size-4" />
</Button>
</div>
{topErrors.map(([path, message]) => <FieldError key={path} message={message} />)}
{block.type === "HERO" && (
<>
{image}
{text("heading", "PagesHeading")}
{text("text", "PagesText")}
{text("buttonLabel", "PagesButtonLabel")}
{text("buttonUrl", "PagesButtonLink")}
<div className="flex items-center gap-2">
<Switch id={fid("fullWidth")} checked={!!block.fullWidth} disabled={saving} onCheckedChange={(on) => set({ fullWidth: on || undefined })} />
<Label htmlFor={fid("fullWidth")}>{t("PagesFullWidth")}</Label>
</div>
{cardList}
{eventPicker("PagesHeroForm", "PagesNoForm")}
{block.eventUuid ? (
<>
{text("formHeading", "PagesFormHeading")}
{text("formText", "PagesFormText")}
{text("thanksText", "PagesThanksText")}
</>
) : null}
</>
)}
{block.type === "RICH_TEXT" && richText("PagesContent")}
{block.type === "IMAGE_TEXT" && (
<>
{image}
<Field id={fid("side")} label={t("PagesImageSide")} error={errors.imagePosition}>
<select id={fid("side")} className={SELECT} value={block.imagePosition ?? "LEFT"} disabled={saving} onChange={(e) => set({ imagePosition: e.target.value as "LEFT" | "RIGHT" })}>
<option value="LEFT">{t("PagesImageLeft")}</option>
<option value="RIGHT">{t("PagesImageRight")}</option>
</select>
</Field>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")}
{richText("PagesText")}
{text("buttonLabel", "PagesButtonLabel")}
{text("buttonUrl", "PagesButtonLink")}
</>
)}
{block.type === "FAQ" && (
<>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")}
{items.map((item, i) => (
<div key={i} className="space-y-2 rounded-md border p-3">
<Field id={fid(`q${i}`)} label={t("PagesQuestionN", { number: i + 1 })} error={errors[`items[${i}].question`]}>
<Input id={fid(`q${i}`)} value={item.question} disabled={saving}
onChange={(e) => setItems(items.map((it, j) => (j === i ? { ...it, question: e.target.value } : it)))} />
</Field>
<Field id={fid(`a${i}`)} label={t("PagesAnswerN", { number: i + 1 })} error={errors[`items[${i}].answer`]}>
<Textarea id={fid(`a${i}`)} rows={3} value={item.answer} disabled={saving}
onChange={(e) => setItems(items.map((it, j) => (j === i ? { ...it, answer: e.target.value } : it)))} />
</Field>
<Button type="button" variant="ghost" size="sm" disabled={saving} onClick={() => setItems(items.filter((_, j) => j !== i))}>
{t("PagesRemoveQuestionN", { number: i + 1 })}
</Button>
</div>
))}
<FieldError message={errors.items} />
<Button type="button" variant="outline" size="sm" disabled={saving} onClick={() => setItems([...items, { question: "", answer: "" }])}>
<Plus aria-hidden="true" className="size-4" />
{t("PagesAddQuestion")}
</Button>
</>
)}
{block.type === "HTML" && (
<Field id={fid("html")} label={t("PagesHtml")} error={errors.html}>
<Textarea id={fid("html")} rows={12} spellCheck={false} className="font-mono text-xs" value={block.html ?? ""} disabled={saving}
aria-invalid={!!errors.html} onChange={(e) => set({ html: e.target.value })} />
<p className="tabular text-xs text-muted-foreground">{`${(block.html ?? "").length}/200000`}</p>
<p className="text-xs text-muted-foreground">{t("PagesHtmlHint")}</p>
</Field>
)}
{block.type === "HTML" && props.onUploadImage && (
<Field id={fid("upload")} label={t("PagesUploadImage")} error={uploadError ?? undefined}>
<Input id={fid("upload")} type="file" accept="image/png,image/jpeg,image/webp" disabled={saving || uploading}
onChange={(e) => {
const file = e.target.files?.[0];
e.target.value = "";
if (file) void upload(file);
}} />
<p className="text-xs text-muted-foreground">{t("PagesUploadImageHint")}</p>
{uploads.map((imageId) => (
<div key={imageId} className="flex items-center gap-2 rounded-md border p-2">
{/* eslint-disable-next-line @next/next/no-img-element -- an uploaded image of unknown size */}
<img src={imageSrc(imageId)} alt={t("PagesImagePreview")} className="size-12 rounded object-cover" />
<CopyAddress address={imageSrc(imageId)} relative />
</div>
))}
</Field>
)}
{block.type === "FORM" && (
<>
{text("heading", "PagesHeading")}
{eventPicker("PagesFormEvent", "PagesChooseEvent")}
{text("thanksText", "PagesThanksText")}
</>
)}
{block.type === "FEATURES" && (
<>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")}
<Field id={fid("text")} label={t("PagesIntro")} error={errors.text}>
<Textarea id={fid("text")} rows={2} value={block.text ?? ""} disabled={saving} aria-invalid={!!errors.text} onChange={(e) => set({ text: e.target.value })} />
</Field>
{cardList}
</>
)}
{block.type === "STEPS" && (
<>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")}
{cardList}
</>
)}
{block.type === "TRUST" && cardList}
{/* add-landing-page-polish: the top bar's button; its logo comes from the company. */}
{block.type === "TOPBAR" && (
<>
{text("buttonLabel", "PagesButtonLabel")}
{text("buttonUrl", "PagesButtonLink")}
</>
)}
{block.type === "FOOTER" && (
<>
{cardList}
{text("text", "PagesFooterLegal")}
</>
)}
{block.type === "CTA" && (
<>
{text("eyebrow", "PagesEyebrow")}
{text("heading", "PagesHeading")}
{text("text", "PagesText")}
{text("buttonLabel", "PagesButtonLabel")}
{text("buttonUrl", "PagesButtonLink")}
</>
)}
{block.type !== "HTML" && block.type !== "TOPBAR" && (
<Field id={fid("look")} label={t("PagesLook")} error={errors.look}>
<select id={fid("look")} className={SELECT} value={block.look ?? "DEFAULT"} disabled={saving} aria-invalid={!!errors.look}
onChange={(e) => set({ look: e.target.value as Look })}>
{LOOKS.map((look) => <option key={look} value={look}>{t(LOOK_LABELS[look])}</option>)}
</select>
</Field>
)}
{/* add-page-anchor-links: the block's id on the page, the target of #name links. */}
<div className="space-y-1">
{text("anchor", "PagesAnchor")}
<p className="text-xs text-muted-foreground">{t("PagesAnchorHint")}</p>
</div>
</fieldset>
);
}