687 lines
26 KiB
TypeScript
687 lines
26 KiB
TypeScript
"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 } 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";
|
|
|
|
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<BlockType, React.ReactNode> = {
|
|
PARAGRAPH: <AlignLeftIcon size={14} />,
|
|
HEADING: <TypeIcon size={14} />,
|
|
IMAGE: <ImageIcon size={14} />,
|
|
QUOTE: <QuoteIcon size={14} />,
|
|
CALLOUT: <AlertCircleIcon size={14} />,
|
|
DIVIDER: <MinusIcon size={14} />,
|
|
LIST: <ListIcon size={14} />,
|
|
TABLE: <TableIcon size={14} />,
|
|
LINK: <LinkIcon size={14} />
|
|
};
|
|
|
|
const BLOCK_LABELS: Record<BlockType, string> = {
|
|
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<PageType>(page?.type ?? "NEWS");
|
|
const [slug, setSlug] = useState(page?.slug ?? "");
|
|
const [location, setLocation] = useState(meta.location ?? "");
|
|
const [tags, setTags] = useState<string[]>(meta.tags ?? []);
|
|
const [tagInput, setTagInput] = useState("");
|
|
const [blocks, setBlocks] = useState<Block[]>(initialBlocks);
|
|
const [previewUrls, setPreviewUrls] = useState<Map<string, string>>(new Map());
|
|
const previewCacheRef = useRef<Map<string, string>>(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 (
|
|
<div className="flex flex-col gap-10">
|
|
<FieldSet>
|
|
<h2 className="md:mb-4">Meta</h2>
|
|
<FieldGroup>
|
|
<Field data-invalid={!!errors?.title?.length}>
|
|
<FieldLabel htmlFor="title">Title</FieldLabel>
|
|
<InputGroup>
|
|
<InputGroupInput
|
|
id="title"
|
|
aria-invalid={!!errors?.title?.length}
|
|
value={title}
|
|
placeholder="Enter page title"
|
|
onChange={(e) => {
|
|
setTitle(e.target.value);
|
|
if (!page) setSlug(e.target.value.toLowerCase().replace(/\s+/g, "-"));
|
|
}}
|
|
/>
|
|
</InputGroup>
|
|
{errors?.title && <FieldError errors={errors.title.map(m => ({ message: m }))} />}
|
|
</Field>
|
|
<Field>
|
|
<FieldLabel htmlFor="type">Page type</FieldLabel>
|
|
<Select defaultValue={type} onValueChange={(e) => setType(e as PageType)}>
|
|
<SelectTrigger>
|
|
<SelectValue placeholder="Type" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectGroup>
|
|
<SelectItem value="PAGE">Page</SelectItem>
|
|
<SelectItem value="NEWS">News</SelectItem>
|
|
</SelectGroup>
|
|
</SelectContent>
|
|
</Select>
|
|
</Field>
|
|
<Field data-invalid={!!errors?.slug?.length}>
|
|
<FieldLabel htmlFor="slug">Slug</FieldLabel>
|
|
<InputGroup>
|
|
<InputGroupInput id="slug" aria-invalid={!!errors?.slug?.length} value={slug} placeholder="page-slug" onChange={(e) => setSlug(e.target.value)} />
|
|
</InputGroup>
|
|
{errors?.slug && <FieldError errors={errors.slug.map(m => ({ message: m }))} />}
|
|
</Field>
|
|
{type === "NEWS" && (
|
|
<Field>
|
|
<FieldLabel htmlFor="location">Location</FieldLabel>
|
|
<InputGroup>
|
|
<InputGroupAddon align="inline-start">
|
|
<Globe2Icon size={14} className="text-muted-foreground" />
|
|
</InputGroupAddon>
|
|
<InputGroupInput id="location" value={location} placeholder="Liberty City, European Federation" onChange={(e) => setLocation(e.target.value)} />
|
|
</InputGroup>
|
|
</Field>
|
|
)}
|
|
{type === "NEWS" && (
|
|
<Field>
|
|
<FieldLabel htmlFor="tags">Tags</FieldLabel>
|
|
<InputGroup>
|
|
<InputGroupInput
|
|
id="tags"
|
|
value={tagInput}
|
|
placeholder="Add a tag and press Enter"
|
|
onChange={(e) => setTagInput(e.target.value)}
|
|
onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addTag(); } }}
|
|
/>
|
|
<InputGroupAddon align="inline-end">
|
|
<InputGroupButton onClick={addTag}>Add</InputGroupButton>
|
|
</InputGroupAddon>
|
|
</InputGroup>
|
|
{tags.length > 0 && (
|
|
<div className="flex flex-row gap-2 flex-wrap mt-3">
|
|
{tags.map((tag) => (
|
|
<Badge key={tag} variant="secondary" className="flex gap-1 items-center cursor-pointer" onClick={() => removeTag(tag)}>
|
|
{tag}
|
|
<XIcon size={11} />
|
|
</Badge>
|
|
))}
|
|
</div>
|
|
)}
|
|
</Field>
|
|
)}
|
|
</FieldGroup>
|
|
</FieldSet>
|
|
|
|
<div className="flex flex-col gap-4">
|
|
<h2 className="md:mb-4">Content</h2>
|
|
{blocks.length === 0 && (
|
|
<p className="text-sm text-muted-foreground">No blocks yet. Add one below.</p>
|
|
)}
|
|
<div className="flex flex-col gap-4 md:gap-6">
|
|
{blocks.map((block, index) => (
|
|
<div key={block.id} className="group relative flex flex-row gap-2 md:gap-4 items-start py-1">
|
|
<div className="flex-1 min-w-0">
|
|
<BlockInput
|
|
block={block}
|
|
onChange={(content) => updateBlock(block.id, content)}
|
|
previewUrls={previewUrls}
|
|
onPreviewReady={(id, url) => {
|
|
previewCacheRef.current.set(id, url);
|
|
setPreviewUrls((prev) => new Map(prev).set(id, url));
|
|
}}
|
|
/>
|
|
</div>
|
|
<div className="flex flex-col gap-1 items-center lg:opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
|
|
<Button variant="ghost" onClick={() => moveBlockUp(index)} disabled={index === 0} size="icon-sm">
|
|
<ChevronUpIcon />
|
|
</Button>
|
|
<Button variant="ghost" onClick={() => moveBlockDown(index)} disabled={index === blocks.length - 1} size="icon-sm">
|
|
<ChevronDownIcon />
|
|
</Button>
|
|
<Button variant="ghost" onClick={() => removeBlock(block.id)} size="icon-sm">
|
|
<Trash2Icon />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
|
|
<div className="mt-4">
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button variant="outline" size="sm" className="gap-1.5 text-muted-foreground">
|
|
<PlusIcon size={14} />
|
|
<p>Add block</p>
|
|
<ChevronDownIcon size={12} />
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent align="start" className="w-44">
|
|
{(["PARAGRAPH", "HEADING", "IMAGE", "QUOTE", "CALLOUT", "DIVIDER", "LIST", "TABLE", "LINK"] as BlockType[]).map((t) => (
|
|
<DropdownMenuItem key={t} onClick={() => addBlock(t)} className="gap-2">
|
|
<p className="text-muted-foreground">{BLOCK_ICONS[t]}</p>
|
|
<p>{BLOCK_LABELS[t]}</p>
|
|
</DropdownMenuItem>
|
|
))}
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function BlockInput({ block, onChange, previewUrls, onPreviewReady }: { block: Block; onChange: (c: Block["content"]) => void; previewUrls?: Map<string, string>; onPreviewReady?: (id: string, url: string) => void }) {
|
|
switch (block.type) {
|
|
case "PARAGRAPH":
|
|
return (
|
|
<AutoResizeTextarea
|
|
className="w-full bg-transparent resize-none outline-none leading-relaxed placeholder:text-muted-foreground"
|
|
placeholder="Start writing..."
|
|
value={(block.content as { type: "PARAGRAPH"; text: string }).text ?? ""}
|
|
onChange={(e) => onChange({ type: "PARAGRAPH", text: e.target.value })}
|
|
/>
|
|
);
|
|
|
|
case "HEADING":
|
|
const level = (block.content as { type: "HEADING"; text: string; level: 1 | 2 | 3 }).level;
|
|
|
|
return (
|
|
<div className="flex items-center gap-2">
|
|
<input
|
|
className={cn(
|
|
"flex-1 min-w-0 bg-transparent outline-none tracking-tight placeholder:text-muted-foreground",
|
|
{
|
|
"text-2xl sm:text-3xl": level === 1,
|
|
"text-xl sm:text-2xl": level === 2,
|
|
"text-lg sm:text-xl": level === 3,
|
|
}
|
|
)}
|
|
placeholder="Heading"
|
|
value={(block.content as { type: "HEADING"; text: string; level: 1 | 2 | 3 }).text ?? ""}
|
|
onChange={(e) => onChange({ type: "HEADING", text: e.target.value, level: (block.content as { type: "HEADING"; text: string; level: 1 | 2 | 3 }).level ?? 2 })}
|
|
/>
|
|
<Select
|
|
value={String((block.content as { type: "HEADING"; text: string; level: 1 | 2 | 3 }).level ?? 2)}
|
|
onValueChange={(v) => onChange({ type: "HEADING", text: (block.content as { type: "HEADING"; text: string; level: 1 | 2 | 3 }).text ?? "", level: Number(v) as 1 | 2 | 3 })}
|
|
>
|
|
<SelectTrigger className="w-16 h-7 opacity-0 group-hover:opacity-100 transition-opacity">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="1">H1</SelectItem>
|
|
<SelectItem value="2">H2</SelectItem>
|
|
<SelectItem value="3">H3</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
);
|
|
|
|
case "QUOTE":
|
|
return (
|
|
<div className="flex flex-col gap-2 border-l-2 border-muted-foreground pl-4">
|
|
<AutoResizeTextarea
|
|
className="w-full bg-transparent resize-none outline-none leading-relaxed placeholder:text-muted-foreground"
|
|
placeholder="Quote text..."
|
|
value={(block.content as { type: "QUOTE"; text: string; author?: string }).text ?? ""}
|
|
onChange={(e) => onChange({ type: "QUOTE", text: e.target.value, author: (block.content as { type: "QUOTE"; text: string; author?: string }).author })}
|
|
/>
|
|
<input
|
|
className="w-full bg-transparent outline-none text-sm text-muted-foreground placeholder:text-muted-foreground/60"
|
|
placeholder="— Author"
|
|
value={(block.content as { type: "QUOTE"; text: string; author?: string }).author ?? ""}
|
|
onChange={(e) => onChange({ type: "QUOTE", text: (block.content as { type: "QUOTE"; text: string; author?: string }).text, author: e.target.value })}
|
|
/>
|
|
</div>
|
|
);
|
|
|
|
case "CALLOUT":
|
|
return (
|
|
<Alert>
|
|
<InfoIcon />
|
|
<input
|
|
className="w-full bg-transparent outline-none text-sm font-medium placeholder:text-muted-foreground"
|
|
placeholder="Callout title"
|
|
value={(block.content as { type: "CALLOUT"; title: string; text: string }).title ?? ""}
|
|
onChange={(e) => onChange({ type: "CALLOUT", title: e.target.value, text: (block.content as { type: "CALLOUT"; title: string; text: string }).text ?? "" })}
|
|
/>
|
|
<AutoResizeTextarea
|
|
className="w-full bg-transparent resize-none outline-none text-sm leading-relaxed text-muted-foreground placeholder:text-muted-foreground/60"
|
|
placeholder="Callout text..."
|
|
value={(block.content as { type: "CALLOUT"; title: string; text: string }).text ?? ""}
|
|
onChange={(e) => onChange({ type: "CALLOUT", title: (block.content as { type: "CALLOUT"; title: string; text: string }).title ?? "", text: e.target.value })}
|
|
/>
|
|
</Alert>
|
|
);
|
|
|
|
case "IMAGE":
|
|
return (
|
|
<ImageBlock
|
|
block={block}
|
|
previewUrl={previewUrls?.get(block.id)}
|
|
onChange={onChange}
|
|
onPreviewReady={onPreviewReady!}
|
|
/>
|
|
);
|
|
|
|
case "DIVIDER":
|
|
return <Separator />;
|
|
|
|
case "LIST":
|
|
return <ListEditor content={block.content as { type: "LIST"; style: "BULLET" | "ORDERED"; items: string[] }} onChange={(c) => onChange(c)} />;
|
|
|
|
case "TABLE":
|
|
return <TableEditor content={block.content as { type: "TABLE"; headers: string[]; rows: string[][] }} onChange={(c) => onChange(c)} />;
|
|
|
|
case "LINK":
|
|
return (
|
|
<div className="flex flex-row gap-2.5">
|
|
<LinkIcon size={16} />
|
|
<div className="flex flex-col gap-2">
|
|
<input
|
|
className="w-full bg-transparent outline-none text-sm"
|
|
placeholder="Link label"
|
|
value={(block.content as { type: "LINK"; label: string; href: string }).label ?? ""}
|
|
onChange={(e) =>
|
|
onChange({
|
|
type: "LINK",
|
|
label: e.target.value,
|
|
href: (block.content as { type: "LINK"; label: string; href: string }).href ?? "",
|
|
})
|
|
}
|
|
/>
|
|
|
|
<input
|
|
className="w-full bg-transparent outline-none text-sm text-muted-foreground"
|
|
placeholder="URL"
|
|
value={(block.content as { type: "LINK"; label: string; href: string }).href ?? ""}
|
|
onChange={(e) =>
|
|
onChange({
|
|
type: "LINK",
|
|
label: (block.content as { type: "LINK"; label: string; href: string }).label ?? "",
|
|
href: e.target.value,
|
|
})
|
|
}
|
|
/>
|
|
</div>
|
|
</div>
|
|
);
|
|
|
|
default:
|
|
return <p className="text-muted-foreground text-sm py-1.5">{block.type} — editor coming soon</p>;
|
|
}
|
|
}
|
|
|
|
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 (
|
|
<div className="flex flex-col gap-2">
|
|
<div className="flex items-center gap-2 mb-2">
|
|
<Select value={content.style} onValueChange={(v) => onChange({ ...content, style: v as "BULLET" | "ORDERED" })}>
|
|
<SelectTrigger>
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="BULLET"><ListIcon />Bullet</SelectItem>
|
|
<SelectItem value="ORDERED"><ListOrderedIcon /> Ordered</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div className="flex flex-col gap-1">
|
|
{items.map((item, index) => (
|
|
<div key={index} className="flex items-center gap-2">
|
|
<span className="text-muted-foreground w-4 shrink-0 text-right">
|
|
{content.style === "ORDERED" ? `${index + 1}.` : <DotIcon />}
|
|
</span>
|
|
<input
|
|
data-list-item
|
|
className="w-64 bg-transparent outline-none py-0.5 placeholder:text-muted-foreground"
|
|
placeholder="List item"
|
|
value={item}
|
|
onChange={(e) => updateItem(index, e.target.value)}
|
|
onKeyDown={(e) => handleKeyDown(e, index)}
|
|
/>
|
|
{items.length > 1 && (
|
|
<Button variant="ghost" onClick={() => removeItem(index)} size="icon-sm" >
|
|
<XIcon />
|
|
</Button>
|
|
)}
|
|
</div>
|
|
))}
|
|
</div>
|
|
<Button className="w-max mt-2 text-muted-foreground" variant="outline" onClick={addItem} size="sm">
|
|
<PlusIcon />
|
|
Add item
|
|
</Button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
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 (
|
|
<div className="flex flex-col gap-2 py-1 overflow-x-auto">
|
|
<Table>
|
|
<TableHeader>
|
|
<TableRow>
|
|
{headers.map((header, ci) => (
|
|
<TableHead key={ci}>
|
|
<div className="flex flex-row items-center">
|
|
<input
|
|
className="flex-1 bg-transparent outline-none placeholder:text-muted-foreground min-w-0"
|
|
placeholder={`Column ${ci + 1}`}
|
|
value={header}
|
|
onChange={(e) => updateHeader(ci, e.target.value)}
|
|
/>
|
|
{headers.length > 1 && (
|
|
<Button variant="ghost" onClick={() => removeColumn(ci)} size="icon-sm" >
|
|
<XIcon />
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</TableHead>
|
|
))}
|
|
<TableHead>
|
|
<Button variant="ghost" onClick={addColumn} size="icon-sm" >
|
|
<PlusIcon />
|
|
</Button>
|
|
</TableHead>
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{rows.map((row, ri) => (
|
|
<TableRow key={ri}>
|
|
{row.map((cell, ci) => (
|
|
<TableCell key={ci}>
|
|
<input className="w-full bg-transparent outline-none placeholder:text-muted-foreground min-w-0" placeholder="Value" value={cell} onChange={(e) => updateCell(ri, ci, e.target.value)} />
|
|
</TableCell>
|
|
))}
|
|
<TableCell>
|
|
<Button variant="ghost" onClick={() => removeRow(ri)} size="icon-sm" >
|
|
<XIcon />
|
|
</Button>
|
|
</TableCell>
|
|
</TableRow>
|
|
))}
|
|
</TableBody>
|
|
</Table>
|
|
<Button className="w-max mt-2 text-muted-foreground" variant="outline" onClick={addRow} size="sm">
|
|
<PlusIcon />
|
|
Add row
|
|
</Button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
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 };
|
|
const [isUploading, setIsUploading] = useState(false);
|
|
|
|
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 ?? "" });
|
|
} catch (e) {
|
|
console.error("Failed to upload image:", e);
|
|
} finally {
|
|
setIsUploading(false);
|
|
}
|
|
}
|
|
|
|
function handleRemove() {
|
|
onChange({ type: "IMAGE", url: "", caption: content.caption ?? "" });
|
|
}
|
|
|
|
return (
|
|
<ImageUploader
|
|
id={`image-${block.id}`}
|
|
label=""
|
|
variant="editor"
|
|
value={previewUrl}
|
|
onFileSelect={handleFileSelect}
|
|
onRemove={handleRemove}
|
|
isUploading={isUploading}
|
|
caption={content.caption}
|
|
onCaptionChange={(caption) => onChange({ type: "IMAGE", url: content.url, caption })}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function AutoResizeTextarea({ value, onChange, className, placeholder }: { value: string; onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void; className?: string; placeholder?: string }) {
|
|
const ref = useRef<HTMLTextAreaElement>(null);
|
|
|
|
useEffect(() => {
|
|
if (ref.current) {
|
|
ref.current.style.height = "auto";
|
|
ref.current.style.height = `${ref.current.scrollHeight}px`;
|
|
}
|
|
}, [value]);
|
|
|
|
return <textarea ref={ref} rows={1} className={cn("overflow-hidden", className)} placeholder={placeholder} value={value} onChange={onChange} />;
|
|
}
|
|
|
|
function getDefaultContent(type: BlockType): Block["content"] {
|
|
switch (type) {
|
|
case "PARAGRAPH": return { type: "PARAGRAPH", text: "" };
|
|
case "HEADING": return { type: "HEADING", text: "", level: 2 };
|
|
case "QUOTE": return { type: "QUOTE", text: "" };
|
|
case "CALLOUT": return { type: "CALLOUT", title: "", text: "" };
|
|
case "DIVIDER": return { type: "DIVIDER" };
|
|
case "LIST": return { type: "LIST", style: "BULLET", items: [""] };
|
|
case "TABLE": return { type: "TABLE", headers: ["", ""], rows: [["", ""]] };
|
|
case "IMAGE": return { type: "IMAGE", url: "", caption: "" };
|
|
case "LINK": return { type: "LINK", label: "", href: "" };
|
|
default: return { type: "PARAGRAPH", text: "" };
|
|
}
|
|
} |