Files
co-lite/solvway-admin-portal/app/components/pages/BlockFields.tsx
T
ngqileandClaude Opus 5.5 0ee9c217c2 fix(pages): hero grows with its text on phones; name the rich text box
The live check at 360 px clipped the hero heading because the image set a
fixed height. The text now sets the height and the image fills behind it.
The rich text box now carries its field label as an accessible name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 16:54:05 +08:00

191 lines
8.7 KiB
TypeScript

"use client";
import type { ReactNode } from "react";
import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
import { BLOCK_LABELS, imageSrc, type CmsBlock } 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 { Textarea } from "@/app/components/ui/textarea";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { RichTextEditor } from "./RichTextEditor";
// 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. */
const INLINE: Record<string, string[]> = {
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl"],
RICH_TEXT: ["html"],
IMAGE_TEXT: ["imageId", "imagePosition", "heading", "html", "buttonLabel", "buttonUrl"],
FAQ: ["heading", "items"],
FORM: ["heading", "eventUuid"],
};
const LISTED = /^items\[\d+\]\.(question|answer)$/;
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;
}) {
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]) => !INLINE[block.type]?.includes(path) && !LISTED.test(path));
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl", 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>
);
const preview = pendingImage?.preview ?? (block.imageId ? imageSrc(block.imageId) : undefined);
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 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")}
</>
)}
{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("heading", "PagesHeading")}
{richText("PagesText")}
{text("buttonLabel", "PagesButtonLabel")}
{text("buttonUrl", "PagesButtonLink")}
</>
)}
{block.type === "FAQ" && (
<>
{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 === "FORM" && (
<>
{text("heading", "PagesHeading")}
<Field id={fid("event")} label={t("PagesFormEvent")} error={errors.eventUuid}>
<select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid}
onChange={(e) => set({ eventUuid: e.target.value || null })}>
<option value="">{t("PagesChooseEvent")}</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>
</>
)}
</fieldset>
);
}