"use client"; import { useState, useEffect, useRef } from "react"; import { v4 as uuidv4 } from "uuid"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Field, FieldError, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field"; import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group"; import { Block, BlockType, Page, PageMeta, PageType } from "@/lib/pages/types"; import { Globe2Icon, PlusIcon, Trash2Icon, XIcon, ChevronDownIcon, ChevronUpIcon, ImageIcon, QuoteIcon, AlertCircleIcon, MinusIcon, ListIcon, TableIcon, TypeIcon, AlignLeftIcon, InfoIcon, DotIcon, ListOrderedIcon, LinkIcon, MoveDiagonalIcon, MoveDiagonal2Icon } from "lucide-react"; import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "./ui/select"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { cn } from "@/lib/utils"; import { Separator } from "./ui/separator"; import { Alert } from "./ui/alert"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { uploadPageImage, getImagePreviewUrl } from "@/lib/pages/actions"; import { ImageUploader } from "@/components/image-uploader"; import { Slider } from "@/components/ui/slider"; import { Label } from "@/components/ui/label"; export type EditorData = { title: string; type: PageType; slug: string; location: string; tags: string[]; blocks: Block[]; }; type EditorProps = { page?: Page | null; type?: PageType; initialBlocks?: Block[]; onChange: (data: EditorData) => void; errors?: { title?: string[]; slug?: string[] }; }; const BLOCK_ICONS: Record = { PARAGRAPH: , HEADING: , IMAGE: , QUOTE: , CALLOUT: , DIVIDER: , LIST: , TABLE: , LINK: }; const BLOCK_LABELS: Record = { PARAGRAPH: "Text", HEADING: "Heading", IMAGE: "Image", QUOTE: "Quote", CALLOUT: "Callout", DIVIDER: "Divider", LIST: "List", TABLE: "Table", LINK: "Link" }; export default function Editor({ page, initialBlocks = [], onChange, errors }: EditorProps) { const meta = (page?.meta as PageMeta) ?? {}; const [title, setTitle] = useState(page?.title ?? ""); const [type, setType] = useState(page?.type ?? "NEWS"); const [slug, setSlug] = useState(page?.slug ?? ""); const [location, setLocation] = useState(meta.location ?? ""); const [tags, setTags] = useState(meta.tags ?? []); const [tagInput, setTagInput] = useState(""); const [blocks, setBlocks] = useState(initialBlocks); const [previewUrls, setPreviewUrls] = useState>(new Map()); const previewCacheRef = useRef>(new Map()); useEffect(() => { onChange({ title, type, slug: slug || title.toLowerCase().replace(/\s+/g, "-"), location, tags, blocks, }); }, [title, slug, location, tags, blocks]); useEffect(() => { const imageBlocks = blocks.filter( (b) => b.type === "IMAGE" && !!(b.content as { type: string; url?: string }).url ); const unresolved = imageBlocks.filter((b) => !previewCacheRef.current.has(b.id)); if (unresolved.length === 0) return; let cancelled = false; Promise.all( unresolved.map(async (b) => { try { const url = await getImagePreviewUrl((b.content as { type: string; url: string }).url); return { id: b.id, url }; } catch { return null; } }) ).then((results) => { if (cancelled) return; const newEntries = results.filter((r): r is { id: string; url: string } => r !== null); if (newEntries.length === 0) return; const next = new Map(previewCacheRef.current); for (const { id, url } of newEntries) next.set(id, url); previewCacheRef.current = next; setPreviewUrls(new Map(next)); }); return () => { cancelled = true; }; }, [blocks]); function addTag() { const trimmed = tagInput.trim(); if (!trimmed || tags.includes(trimmed)) return; setTags([...tags, trimmed]); setTagInput(""); } function removeTag(tag: string) { setTags(tags.filter((t) => t !== tag)); } function addBlock(blockType: BlockType) { setBlocks([ ...blocks, { id: uuidv4(), pageId: page?.id ?? "", parentId: null, type: blockType, position: blocks.length, content: getDefaultContent(blockType), }, ]); } function removeBlock(id: string) { setBlocks(blocks.filter((b) => b.id !== id)); previewCacheRef.current.delete(id); setPreviewUrls((prev) => { const next = new Map(prev); next.delete(id); return next; }); } function updateBlock(id: string, content: Block["content"]) { setBlocks(blocks.map((b) => (b.id === id ? { ...b, content } : b))); } function moveBlock(from: number, to: number) { const updated = [...blocks]; const [moved] = updated.splice(from, 1); updated.splice(to, 0, moved); setBlocks(updated.map((b, i) => ({ ...b, position: i }))); } function moveBlockUp(index: number) { if (index === 0) return; moveBlock(index, index - 1); } function moveBlockDown(index: number) { if (index === blocks.length - 1) return; moveBlock(index, index + 1); } return (

Meta

Title { setTitle(e.target.value); if (!page) setSlug(e.target.value.toLowerCase().replace(/\s+/g, "-")); }} /> {errors?.title && ({ message: m }))} />} Page type Slug setSlug(e.target.value)} /> {errors?.slug && ({ message: m }))} />} {type === "NEWS" && ( Location setLocation(e.target.value)} /> )} {type === "NEWS" && ( Tags setTagInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addTag(); } }} /> Add {tags.length > 0 && (
{tags.map((tag) => ( removeTag(tag)}> {tag} ))}
)}
)}

Content

{blocks.length === 0 && (

No blocks yet. Add one below.

)}
{blocks.map((block, index) => (
updateBlock(block.id, content)} previewUrls={previewUrls} onPreviewReady={(id, url) => { previewCacheRef.current.set(id, url); setPreviewUrls((prev) => new Map(prev).set(id, url)); }} />
))}
{(["PARAGRAPH", "HEADING", "IMAGE", "QUOTE", "CALLOUT", "DIVIDER", "LIST", "TABLE", "LINK"] as BlockType[]).map((t) => ( addBlock(t)} className="gap-2">

{BLOCK_ICONS[t]}

{BLOCK_LABELS[t]}

))}
); } function BlockInput({ block, onChange, previewUrls, onPreviewReady }: { block: Block; onChange: (c: Block["content"]) => void; previewUrls?: Map; onPreviewReady?: (id: string, url: string) => void }) { switch (block.type) { case "PARAGRAPH": return ( onChange({ type: "PARAGRAPH", text: e.target.value })} /> ); case "HEADING": const level = (block.content as { type: "HEADING"; text: string; level: 1 | 2 | 3 }).level; return (
onChange({ type: "HEADING", text: e.target.value, level: (block.content as { type: "HEADING"; text: string; level: 1 | 2 | 3 }).level ?? 2 })} />
); case "QUOTE": return (
onChange({ type: "QUOTE", text: e.target.value, author: (block.content as { type: "QUOTE"; text: string; author?: string }).author })} /> onChange({ type: "QUOTE", text: (block.content as { type: "QUOTE"; text: string; author?: string }).text, author: e.target.value })} />
); case "CALLOUT": return ( onChange({ type: "CALLOUT", title: e.target.value, text: (block.content as { type: "CALLOUT"; title: string; text: string }).text ?? "" })} /> onChange({ type: "CALLOUT", title: (block.content as { type: "CALLOUT"; title: string; text: string }).title ?? "", text: e.target.value })} /> ); case "IMAGE": return ( ); case "DIVIDER": return ; case "LIST": return onChange(c)} />; case "TABLE": return onChange(c)} />; case "LINK": return (
onChange({ type: "LINK", label: e.target.value, href: (block.content as { type: "LINK"; label: string; href: string }).href ?? "", }) } /> onChange({ type: "LINK", label: (block.content as { type: "LINK"; label: string; href: string }).label ?? "", href: e.target.value, }) } />
); default: return

{block.type} — editor coming soon

; } } function ListEditor({ content, onChange }: { content: { type: "LIST"; style: "BULLET" | "ORDERED"; items: string[] }; onChange: (c: { type: "LIST"; style: "BULLET" | "ORDERED"; items: string[] }) => void }) { const items = content.items ?? [""]; function updateItem(index: number, value: string) { const updated = [...items]; updated[index] = value; onChange({ ...content, items: updated }); } function addItem() { onChange({ ...content, items: [...items, ""] }); } function removeItem(index: number) { const updated = items.filter((_, i) => i !== index); onChange({ ...content, items: updated.length ? updated : [""] }); } function handleKeyDown(e: React.KeyboardEvent, index: number) { if (e.key === "Enter") { e.preventDefault(); const updated = [...items]; updated.splice(index + 1, 0, ""); onChange({ ...content, items: updated }); setTimeout(() => { const inputs = document.querySelectorAll(`[data-list-item]`); (inputs[index + 1] as HTMLInputElement)?.focus(); }, 0); } if (e.key === "Backspace" && items[index] === "" && items.length > 1) { e.preventDefault(); removeItem(index); } } return (
{items.map((item, index) => (
{content.style === "ORDERED" ? `${index + 1}.` : } updateItem(index, e.target.value)} onKeyDown={(e) => handleKeyDown(e, index)} /> {items.length > 1 && ( )}
))}
); } function TableEditor({ content, onChange }: { content: { type: "TABLE"; headers: string[]; rows: string[][] }; onChange: (c: { type: "TABLE"; headers: string[]; rows: string[][] }) => void }) { const headers = content.headers ?? ["Column 1"]; const rows = content.rows ?? []; function updateHeader(index: number, value: string) { const updated = [...headers]; updated[index] = value; onChange({ ...content, headers: updated }); } function addColumn() { onChange({ ...content, headers: headers.concat(""), rows: rows.map((row) => [...row, ""]) }); } function removeColumn(colIndex: number) { if (headers.length <= 1) return; onChange({ ...content, headers: headers.filter((_, i) => i !== colIndex), rows: rows.map((row) => row.filter((_, i) => i !== colIndex)), }); } function addRow() { onChange({ ...content, rows: [...rows, headers.map(() => "")] }); } function removeRow(rowIndex: number) { onChange({ ...content, rows: rows.filter((_, i) => i !== rowIndex) }); } function updateCell(rowIndex: number, colIndex: number, value: string) { onChange({ ...content, rows: rows.map((row, ri) => ri === rowIndex ? row.map((cell, ci) => (ci === colIndex ? value : cell)) : row), }); } return (
{headers.map((header, ci) => (
updateHeader(ci, e.target.value)} /> {headers.length > 1 && ( )}
))}
{rows.map((row, ri) => ( {row.map((cell, ci) => ( updateCell(ri, ci, e.target.value)} /> ))} ))}
); } function ImageBlock({ block, previewUrl, onChange, onPreviewReady }: { block: Block; previewUrl?: string; onChange: (c: Block["content"]) => void; onPreviewReady: (id: string, url: string) => void }) { const content = block.content as { type: "IMAGE"; url: string; caption?: string; width?: number }; const [isUploading, setIsUploading] = useState(false); const [isDragging, setIsDragging] = useState(false); const [supportsDrag, setSupportsDrag] = useState(false); const dragStartRef = useRef<{ x: number; width: number } | null>(null); const imgRef = useRef(null); useEffect(() => { setSupportsDrag(window.matchMedia("(hover: hover) and (pointer: fine)").matches); }, []); const currentWidth = content.width; function handleDragStart(e: React.PointerEvent) { e.preventDefault(); e.stopPropagation(); const startWidth = imgRef.current?.offsetWidth ?? 500; dragStartRef.current = { x: e.clientX, width: startWidth }; setIsDragging(true); function handleMove(ev: PointerEvent) { if (!dragStartRef.current) return; const delta = ev.clientX - dragStartRef.current.x; const newWidth = Math.round( Math.min(800, Math.max(150, dragStartRef.current.width + delta)) ); onChange({ type: "IMAGE", url: content.url, caption: content.caption ?? "", width: newWidth }); } function handleUp() { setIsDragging(false); dragStartRef.current = null; window.removeEventListener("pointermove", handleMove); window.removeEventListener("pointerup", handleUp); } window.addEventListener("pointermove", handleMove); window.addEventListener("pointerup", handleUp); } async function handleFileSelect(file: File) { setIsUploading(true); try { const key = await uploadPageImage(file); const url = await getImagePreviewUrl(key); onPreviewReady(block.id, url); onChange({ type: "IMAGE", url: key, caption: content.caption ?? "", width: content.width }); } catch (e) { console.error("Failed to upload image:", e); } finally { setIsUploading(false); } } function handleRemove() { onChange({ type: "IMAGE", url: "", caption: content.caption ?? "", width: content.width }); } return (
onChange({ type: "IMAGE", url: content.url, caption, width: content.width })} resizeHandle={ supportsDrag && content.url ? ( ) : null } /> {content.url && !supportsDrag && (
{currentWidth ?? 800}px
onChange({ type: "IMAGE", url: content.url, caption: content.caption ?? "", width: v })} />
)}
); } function AutoResizeTextarea({ value, onChange, className, placeholder }: { value: string; onChange: (e: React.ChangeEvent) => void; className?: string; placeholder?: string }) { const ref = useRef(null); useEffect(() => { if (ref.current) { ref.current.style.height = "auto"; ref.current.style.height = `${ref.current.scrollHeight}px`; } }, [value]); return