Files
FlorteSite/src/components/EditorScreen.tsx
T
faumaray 75e03b42f7 init
Signed-off-by: faumaray <faumaray@gmail.com>
2026-05-04 08:30:15 +03:00

607 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { KindPill } from "@/components/Pills";
import { api } from "@/lib/client";
import { KIND_ORDER, KINDS, type KindId } from "@/lib/kinds";
import type { EntryDTO } from "@/lib/serialize";
type Mode = "rich" | "fields" | "stats";
const DEFAULT_FIELDS_BY_KIND: Partial<Record<KindId, [string, string][]>> = {
npc: [
["Race", ""],
["Pronouns", ""],
["Alignment", ""],
["Status", ""],
["Location", ""],
["Affiliation", ""],
],
pc: [
["Class & Level", ""],
["Player", ""],
["Race", ""],
["Background", ""],
],
location: [
["Region", ""],
["Population", ""],
["Government", ""],
["Climate", ""],
],
faction: [
["Headquarters", ""],
["Leader", ""],
["Allies", ""],
["Enemies", ""],
],
item: [
["Type", ""],
["Rarity", ""],
["Attunement", ""],
["Owner", ""],
],
deity: [
["Domain", ""],
["Symbol", ""],
["Alignment", ""],
],
beast: [
["Type", ""],
["Size", ""],
["Habitat", ""],
],
};
const STAT_KEYS = ["AC", "HP", "Speed", "STR", "DEX", "CON", "INT", "WIS", "CHA",
"Saving Throws", "Damage Resist.", "Condition Imm.", "Senses", "Languages", "Challenge"];
export function EditorScreen({ existing }: { existing?: EntryDTO }) {
const router = useRouter();
const isEdit = !!existing;
const [kind, setKind] = useState<KindId>((existing?.kind as KindId) ?? "npc");
const [title, setTitle] = useState(existing?.title ?? "");
const [subtitle, setSubtitle] = useState(existing?.subtitle ?? "");
const [summary, setSummary] = useState(existing?.summary ?? "");
const [body, setBody] = useState(existing?.body ?? "");
const [isPublic, setIsPublic] = useState(existing?.isPublic ?? false);
const [tags, setTags] = useState<string[]>(existing?.tags ?? []);
const [tagDraft, setTagDraft] = useState("");
const [fields, setFields] = useState<[string, string][]>(() => {
if (existing?.fields && Object.keys(existing.fields).length)
return Object.entries(existing.fields).map(([k, v]) => [k, String(v)]);
return DEFAULT_FIELDS_BY_KIND[(existing?.kind as KindId) ?? "npc"]?.slice() ?? [];
});
const [newFieldKey, setNewFieldKey] = useState("");
const [stats, setStats] = useState<[string, string][]>(() =>
Object.entries(existing?.stats ?? {}).map(([k, v]) => [k, String(v)])
);
const [abilities, setAbilities] = useState<{ name: string; text: string }[]>(
existing?.abilities ?? []
);
const [mode, setMode] = useState<Mode>("rich");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [suggestions, setSuggestions] = useState<EntryDTO[]>([]);
const [showSuggest, setShowSuggest] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// load suggestion candidates once
useEffect(() => {
api<EntryDTO[]>("/api/entries").then(setSuggestions).catch(() => {});
}, []);
// Caret-aware [[ suggestion popover
useEffect(() => {
const ta = textareaRef.current;
if (!ta) return;
const txt = body.slice(0, ta.selectionStart ?? body.length);
setShowSuggest(/\[\[$/.test(txt));
}, [body]);
const wordCount = useMemo(
() => (body.trim() ? body.trim().split(/\s+/).length : 0),
[body]
);
const linkCount = useMemo(() => {
const re = /\[\[([^\]]+)\]\]/g;
let n = 0;
while (re.exec(body) !== null) n++;
return n;
}, [body]);
const insertSuggestion = (title: string) => {
const ta = textareaRef.current;
if (!ta) return;
const start = ta.selectionStart ?? body.length;
const next = body.slice(0, start) + title + "]]" + body.slice(start);
setBody(next);
setShowSuggest(false);
requestAnimationFrame(() => {
ta.focus();
ta.selectionStart = ta.selectionEnd = start + title.length + 2;
});
};
const addField = () => {
if (!newFieldKey.trim()) return;
setFields((f) => [...f, [newFieldKey.trim(), ""]]);
setNewFieldKey("");
};
const updateField = (i: number, k: string, v: string) =>
setFields((f) => f.map((x, idx) => (idx === i ? [k, v] : x)));
const removeField = (i: number) =>
setFields((f) => f.filter((_, idx) => idx !== i));
const addTag = () => {
const t = tagDraft.trim().replace(/^#/, "").toLowerCase();
if (!t) return;
if (!tags.includes(t)) setTags((s) => [...s, t]);
setTagDraft("");
};
const setStat = (i: number, k: string, v: string) =>
setStats((s) => s.map((x, idx) => (idx === i ? [k, v] : x)));
const addStat = (k?: string) => setStats((s) => [...s, [k ?? "", ""]]);
const removeStat = (i: number) => setStats((s) => s.filter((_, idx) => idx !== i));
const addAbility = () => setAbilities((a) => [...a, { name: "", text: "" }]);
const removeAbility = (i: number) =>
setAbilities((a) => a.filter((_, idx) => idx !== i));
const submit = async () => {
if (!title.trim()) {
setError("Title required");
return;
}
setBusy(true);
setError(null);
const fieldsObj: Record<string, string> = {};
for (const [k, v] of fields) {
if (k.trim()) fieldsObj[k.trim()] = v;
}
const statsObj: Record<string, string> = {};
for (const [k, v] of stats) {
if (k.trim()) statsObj[k.trim()] = v;
}
const payload = {
kind,
title: title.trim(),
subtitle: subtitle.trim(),
summary: summary.trim(),
body,
isPublic,
tags,
fields: fieldsObj,
stats: statsObj,
abilities,
};
try {
if (isEdit && existing) {
await api(`/api/entries/${existing.slug}`, {
method: "PATCH",
body: JSON.stringify(payload),
});
router.push(`/article/${existing.slug}`);
} else {
const created = await api<EntryDTO>("/api/entries", {
method: "POST",
body: JSON.stringify(payload),
});
router.push(`/article/${created.slug}`);
}
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
};
const onDelete = async () => {
if (!existing) return;
if (!confirm(`Delete "${existing.title}"?`)) return;
await api(`/api/entries/${existing.slug}`, { method: "DELETE" });
router.push("/search");
};
return (
<div className="flo-screen flo-editor">
<div className="flo-editor-bar">
<div className="flo-editor-left">
<KindPill kind={kind} />
<select
className="flo-select"
value={kind}
onChange={(e) => setKind(e.target.value as KindId)}
>
{KIND_ORDER.map((k) => (
<option key={k} value={k}>
{KINDS[k].label}
</option>
))}
</select>
{isEdit && (
<span className="flo-mono flo-mono-dim">
editing · {existing!.slug}
</span>
)}
</div>
<div className="flo-editor-right">
{isEdit && (
<button className="flo-btn flo-btn-ghost flo-btn-danger" onClick={onDelete}>
Delete
</button>
)}
<button
className="flo-btn flo-btn-ghost"
onClick={() => router.back()}
>
Cancel
</button>
<button className="flo-btn" onClick={submit} disabled={busy}>
{busy ? "Saving…" : isEdit ? "Save changes" : "Publish to Codex"}
</button>
</div>
</div>
{error && <div className="flo-error">{error}</div>}
<div className="flo-editor-grid">
<div className="flo-editor-main">
<input
className="flo-editor-title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Inscribe a title…"
/>
<input
className="flo-editor-sub"
value={subtitle}
onChange={(e) => setSubtitle(e.target.value)}
placeholder="Subtitle, epithet, or kenning…"
/>
<div className="flo-editor-toolbar">
<button
className="flo-tool"
type="button"
title="Heading"
onClick={() => insertAtCaret(textareaRef, body, setBody, "\n## Heading\n")}
>H</button>
<button
className="flo-tool"
type="button"
title="Quote"
onClick={() => insertAtCaret(textareaRef, body, setBody, "\n> ")}
>❝</button>
<button
className="flo-tool"
type="button"
title="Wikilink"
onClick={() => insertAtCaret(textareaRef, body, setBody, "[[")}
>
<span className="flo-mono">[[</span>
</button>
<button
className="flo-tool"
type="button"
title="Secret block"
onClick={() =>
insertAtCaret(
textareaRef,
body,
setBody,
"\n::secret\nDM-only paragraph here.\n::end\n"
)
}
>🜂</button>
<div className="flo-tool-sep" />
<button
className={"flo-tool flo-tool-mode " + (mode === "rich" ? "is-active" : "")}
onClick={() => setMode("rich")}
type="button"
>Body</button>
<button
className={"flo-tool flo-tool-mode " + (mode === "fields" ? "is-active" : "")}
onClick={() => setMode("fields")}
type="button"
>Fields</button>
{kind === "beast" && (
<button
className={"flo-tool flo-tool-mode " + (mode === "stats" ? "is-active" : "")}
onClick={() => setMode("stats")}
type="button"
>Stat block</button>
)}
</div>
{mode === "rich" && (
<>
<input
className="flo-input"
style={{ marginBottom: 12 }}
value={summary}
onChange={(e) => setSummary(e.target.value)}
placeholder="One-line summary (shown in the codex stack)"
/>
<div className="flo-editor-canvas">
<textarea
ref={textareaRef}
className="flo-editor-textarea"
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder="Inscribe the body. Use ## for headings, > for quotes, [[Link]] for cross-references, and ::secret …::end blocks for DM-only sections."
/>
{showSuggest && (
<div className="flo-suggest">
<div className="flo-suggest-hd">Link to existing entry</div>
{suggestions
.slice(0, 6)
.map((s) => (
<button
key={s.slug}
type="button"
className="flo-suggest-item"
onClick={() => insertSuggestion(s.title)}
>
<span className="flo-suggest-glyph">
{KINDS[s.kind as KindId]?.glyph ?? "❖"}
</span>
<span>{s.title}</span>
<span className="flo-mono flo-mono-dim">↵</span>
</button>
))}
{suggestions.length === 0 && (
<div className="flo-suggest-item is-new">
<span className="flo-suggest-glyph">+</span>
<span>No entries yet. Type a name and continue.</span>
</div>
)}
</div>
)}
</div>
<div className="flo-editor-meta">
<div>
<span className="flo-mono flo-mono-dim">words</span>
<span className="flo-mono">{wordCount}</span>
</div>
<div>
<span className="flo-mono flo-mono-dim">[[links]]</span>
<span className="flo-mono">{linkCount}</span>
</div>
</div>
</>
)}
{mode === "fields" && (
<div className="flo-side-section">
<h3>Structured fields</h3>
<div className="flo-fields-edit">
{fields.map(([k, v], i) => (
<div key={i} className="flo-field-row">
<input
className="flo-input flo-input-mono"
style={{ padding: "5px 8px", fontSize: 11 }}
value={k}
onChange={(e) => updateField(i, e.target.value, v)}
/>
<div style={{ display: "flex", gap: 6 }}>
<input
className="flo-field-val"
value={v}
onChange={(e) => updateField(i, k, e.target.value)}
/>
<button
className="flo-x"
type="button"
title="Remove"
onClick={() => removeField(i)}
>
×
</button>
</div>
</div>
))}
<div style={{ display: "flex", gap: 6, marginTop: 6 }}>
<input
className="flo-input flo-input-mono"
style={{ padding: "6px 8px", flex: 1, fontSize: 11 }}
placeholder="new field name…"
value={newFieldKey}
onChange={(e) => setNewFieldKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
addField();
}
}}
/>
<button className="flo-add-field" type="button" onClick={addField}>
+ add field
</button>
</div>
</div>
</div>
)}
{mode === "stats" && (
<div className="flo-side-section">
<h3>Bestiary stat block</h3>
<div className="flo-fields-edit">
{stats.map(([k, v], i) => (
<div key={i} className="flo-field-row">
<input
className="flo-input flo-input-mono"
style={{ padding: "5px 8px", fontSize: 11 }}
value={k}
onChange={(e) => setStat(i, e.target.value, v)}
/>
<div style={{ display: "flex", gap: 6 }}>
<input
className="flo-field-val"
value={v}
onChange={(e) => setStat(i, k, e.target.value)}
/>
<button
className="flo-x"
type="button"
title="Remove"
onClick={() => removeStat(i)}
>
×
</button>
</div>
</div>
))}
<div style={{ display: "flex", gap: 4, flexWrap: "wrap", marginTop: 6 }}>
{STAT_KEYS.map((k) => (
<button
key={k}
type="button"
className="flo-chip"
onClick={() => addStat(k)}
>
+ {k}
</button>
))}
</div>
</div>
<h3 style={{ marginTop: 18 }}>Traits / Actions</h3>
<div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
{abilities.map((ab, i) => (
<div
key={i}
style={{ display: "flex", gap: 8, alignItems: "flex-start" }}
>
<input
className="flo-input"
style={{ width: 180, fontSize: 13 }}
placeholder="Name"
value={ab.name}
onChange={(e) =>
setAbilities((arr) =>
arr.map((x, idx) => (idx === i ? { ...x, name: e.target.value } : x))
)
}
/>
<textarea
className="flo-textarea"
style={{ flex: 1, minHeight: 60, fontSize: 13 }}
placeholder="Description"
value={ab.text}
onChange={(e) =>
setAbilities((arr) =>
arr.map((x, idx) => (idx === i ? { ...x, text: e.target.value } : x))
)
}
/>
<button
type="button"
className="flo-x"
onClick={() => removeAbility(i)}
>
×
</button>
</div>
))}
<button type="button" className="flo-add-field" onClick={addAbility}>
+ add ability
</button>
</div>
</div>
)}
</div>
<aside className="flo-editor-side">
<div className="flo-side-section">
<h3>Visibility</h3>
<div className="flo-vis-toggle">
<button
type="button"
className={"flo-vis-opt " + (isPublic ? "is-active" : "")}
onClick={() => setIsPublic(true)}
>
<span className="flo-glyph">◐</span>
<div>
<div>Players & DM</div>
<small>Visible in player portal</small>
</div>
</button>
<button
type="button"
className={"flo-vis-opt " + (!isPublic ? "is-active" : "")}
onClick={() => setIsPublic(false)}
>
<span className="flo-glyph">●</span>
<div>
<div>DM only</div>
<small>Hidden from the player portal</small>
</div>
</button>
</div>
<div className="flo-vis-hint">
Sections wrapped in <code className="flo-mono">::secret … ::end</code>
{" "}stay hidden from players even on a public page.
</div>
</div>
<div className="flo-side-section">
<h3>Tags</h3>
<div className="flo-tag-edit">
{tags.map((t) => (
<span key={t} className="flo-tag-pill">
#{t}{" "}
<span
className="flo-x"
onClick={() => setTags((arr) => arr.filter((x) => x !== t))}
>
×
</span>
</span>
))}
<input
className="flo-tag-input"
placeholder="add tag…"
value={tagDraft}
onChange={(e) => setTagDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
addTag();
}
}}
/>
</div>
</div>
</aside>
</div>
</div>
);
}
function insertAtCaret(
ref: React.RefObject<HTMLTextAreaElement | null>,
body: string,
setBody: (s: string) => void,
insert: string
) {
const ta = ref.current;
if (!ta) {
setBody(body + insert);
return;
}
const start = ta.selectionStart ?? body.length;
const end = ta.selectionEnd ?? body.length;
const next = body.slice(0, start) + insert + body.slice(end);
setBody(next);
requestAnimationFrame(() => {
ta.focus();
const pos = start + insert.length;
ta.selectionStart = ta.selectionEnd = pos;
});
}