1
0
Fork 0

feat(npc-dialogue): rich text editor and block lists in dialogue markup

DialogueText gains line-based block lists: consecutive lines starting
with - / * render as bullets, 1. / 2) as ordered lists, with item
content running through the inline parser so markup nests inside items.

Node editing swaps plain textareas for a shared MarkupEditor (line,
narration, lead-in, closing, tooltip, lock message, event message):
a formatting toolbar (bold, italic, code, color, link, bullet and
numbered list), a right-click menu wrapping the selection in tokens,
and a live DialogueText preview on the long-form fields. Storage stays
the plain custom-markup string; the editor only wraps selections.
This commit is contained in:
Jason Fraley 2026-10-14 16:33:23 -04:00
parent c299acbe4f
commit 20c70151e3
4 changed files with 337 additions and 28 deletions

View file

@ -0,0 +1,205 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
/** Friendly color names offered by the color picker (mirrors DialogueText). */
const COLOR_CHOICES = [
"red",
"amber",
"cyan",
"emerald",
"green",
"sky",
"violet",
"purple",
"pink",
"slate",
] as const;
/**
* Textarea for authored dialogue strings with a formatting toolbar, a
* right-click markup menu, and a live `DialogueText` preview. Storage stays
* the plain custom-markup string (this only wraps the selection in tokens);
* one component serves every interpolatable field (line, narration, lead-in,
* closing, tooltip, lock message) so authoring affordances are consistent.
*/
export function MarkupEditor({
value,
onChange,
rows = 4,
placeholder,
className,
textareaRef,
preview = true,
}: {
value: string;
onChange: (next: string) => void;
rows?: number;
placeholder?: string;
/** Extra classes for the textarea itself (sizing/colors per surface). */
className?: string;
/** Optional external ref, e.g. the line box's auto-grow logic. */
textareaRef?: React.RefObject<HTMLTextAreaElement | null>;
/** Show the rendered preview under the box (default true). */
preview?: boolean;
}) {
const innerRef = useRef<HTMLTextAreaElement | null>(null);
const el = () => textareaRef?.current ?? innerRef.current;
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);
// Close the context menu on any outside click or Escape.
useEffect(() => {
if (!menu) return;
const close = () => setMenu(null);
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setMenu(null);
window.addEventListener("mousedown", close);
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("mousedown", close);
window.removeEventListener("keydown", onKey);
};
}, [menu]);
/** Replace the selection with `before + sel + after`, keeping it selected. */
const wrap = (before: string, after: string) => {
const node = el();
if (!node) return;
const start = node.selectionStart;
const end = node.selectionEnd;
const selected = value.slice(start, end);
onChange(value.slice(0, start) + before + selected + after + value.slice(end));
requestAnimationFrame(() => {
node.focus();
node.setSelectionRange(start + before.length, start + before.length + selected.length);
});
};
/** Toggle a line prefix (`- `, `1. `) across the selected lines. */
const toggleLines = (kind: "ul" | "ol") => {
const node = el();
if (!node) return;
const lineStart = value.lastIndexOf("\n", node.selectionStart - 1) + 1;
const nextBreak = value.indexOf("\n", node.selectionEnd);
const lineEnd = nextBreak === -1 ? value.length : nextBreak;
const lines = value.slice(lineStart, lineEnd).split("\n");
const marker = kind === "ul" ? /^(\s*)[-*]\s/ : /^(\s*)\d+[.)]\s/;
const allMarked = lines.every((line) => marker.test(line));
const nextLines = lines.map((line, index) => {
if (allMarked) return line.replace(marker, "$1");
const stripped = line.replace(marker, "$1");
return kind === "ul" ? `- ${stripped}` : `${index + 1}. ${stripped}`;
});
onChange(value.slice(0, lineStart) + nextLines.join("\n") + value.slice(lineEnd));
requestAnimationFrame(() => node.focus());
};
const insertLink = () => {
const node = el();
if (!node) return;
const start = node.selectionStart;
const end = node.selectionEnd;
const selected = value.slice(start, end) || "label";
onChange(`${value.slice(0, start)}[${selected}](${value.slice(end)})`);
requestAnimationFrame(() => {
node.focus();
const urlAt = start + selected.length + 3;
node.setSelectionRange(urlAt, urlAt);
});
};
const toolbarButton =
"h-6 min-w-6 rounded-sm border border-white/15 bg-black/40 px-1.5 font-mono text-[11px] text-white/70 transition-colors hover:border-cyan-400/50 hover:text-cyan-300";
const menuItems: { label: string; run: () => void }[] = [
{ label: "** bold **", run: () => wrap("**", "**") },
{ label: "* italic *", run: () => wrap("*", "*") },
{ label: "` code `", run: () => wrap("`", "`") },
{ label: "[ link ]", run: insertLink },
{ label: "- bullet list", run: () => toggleLines("ul") },
{ label: "1. numbered list", run: () => toggleLines("ol") },
];
return (
<div className="flex flex-col gap-1">
<div className="flex flex-wrap items-center gap-1">
<button type="button" title="Bold" onClick={() => wrap("**", "**")} className={`${toolbarButton} font-bold`}>
B
</button>
<button type="button" title="Italic" onClick={() => wrap("*", "*")} className={`${toolbarButton} italic`}>
I
</button>
<button type="button" title="Code" onClick={() => wrap("`", "`")} className={toolbarButton}>
{"<>"}
</button>
<select
value=""
title="Wrap in a color"
onChange={(e) => e.target.value && wrap(`{${e.target.value}}`, "{/}")}
className="h-6 rounded-sm border border-white/15 bg-zinc-800 px-1 text-[11px] text-white/70"
>
<option value="">color</option>
{COLOR_CHOICES.map((color) => (
<option key={color} value={color}>
{color}
</option>
))}
</select>
<button type="button" title="Link (opens in a popup)" onClick={insertLink} className={toolbarButton}>
link
</button>
<button type="button" title="Bullet list" onClick={() => toggleLines("ul")} className={toolbarButton}>
&bull; list
</button>
<button type="button" title="Numbered list" onClick={() => toggleLines("ol")} className={toolbarButton}>
1. list
</button>
</div>
<textarea
ref={textareaRef ?? innerRef}
value={value}
onChange={(e) => onChange(e.target.value)}
onContextMenu={(e) => {
e.preventDefault();
setMenu({ x: e.clientX, y: e.clientY });
}}
placeholder={placeholder}
rows={rows}
className={
className ??
"bg-zinc-800 border border-white/20 rounded px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
}
/>
{preview && value.trim() !== "" && (
<div className="flex flex-col gap-0.5">
<span className="text-[9px] uppercase tracking-wider text-white/30">Preview</span>
<div className="min-w-0 break-words rounded border border-white/10 bg-black/40 px-2 py-1.5 text-sm text-white/80">
<DialogueText text={value} />
</div>
</div>
)}
{menu && (
<div
className="fixed z-[120] flex min-w-40 flex-col rounded border border-zinc-700 bg-zinc-900 py-1 shadow-xl"
style={{ left: menu.x, top: menu.y }}
onMouseDown={(e) => e.stopPropagation()}
>
{menuItems.map((item) => (
<button
key={item.label}
type="button"
onClick={() => {
item.run();
setMenu(null);
}}
className="px-3 py-1 text-left font-mono text-xs text-white/70 hover:bg-zinc-800 hover:text-cyan-300"
>
{item.label}
</button>
))}
</div>
)}
</div>
);
}

View file

@ -12,7 +12,6 @@ import {
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
@ -30,6 +29,7 @@ import type {
} from "@/lib/npc-dialogue/dialogue";
import { conditionSummary, EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
import { MarkupEditor } from "./MarkupEditor";
import { uploadNpcDialogueAttachment } from "@/app/(frontend)/personnel/contacts/[id]/actions";
interface NodeEditDialogProps {
@ -249,16 +249,16 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
{node.type === "dialogue" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Line</Label>
<Textarea
ref={lineRef}
<MarkupEditor
value={draft.body ?? ""}
onChange={(e) => {
patch({ body: e.target.value || undefined });
onChange={(next) => {
patch({ body: next || undefined });
autoSizeLine();
}}
placeholder="The NPC says…"
rows={4}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30 resize-y"
textareaRef={lineRef}
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
<p className="text-[10px] text-white/40">
Line breaks are kept. **bold**, *italic*, {`{red}color{/}`} and {'`code`'} render
@ -268,7 +268,8 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
with a ternary: {'{{ trust ? friend : hostile }}'}, also {'{{ !key }}'} and
{'{{ rep >= 5 ? elite : rookie }}'}. Branches may nest tokens. Inline
images use {'![alt](url)'} (e.g. {`![coin](/api/media/file/coin.png)`}) and
render at text height.
render at text height. Lines starting with "- " or "1. " become lists.
Right-click the box for a markup menu.
</p>
</div>
)}
@ -277,12 +278,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Lead-in</Label>
<Textarea
<MarkupEditor
value={draft.leadIn ?? ""}
onChange={(e) => patch({ leadIn: e.target.value || undefined })}
onChange={(next) => patch({ leadIn: next || undefined })}
placeholder="Optional line before the choices."
rows={2}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
</div>
@ -340,14 +341,15 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<Label className="text-[9px] uppercase tracking-wider text-white/40">
Tooltip (optional)
</Label>
<Textarea
<MarkupEditor
value={choice.tooltip ?? ""}
onChange={(e) =>
setChoice(index, { ...choice, tooltip: e.target.value || undefined })
onChange={(next) =>
setChoice(index, { ...choice, tooltip: next || undefined })
}
placeholder="Hover card. Supports markup, {{flags}} and ![alt](url) images."
rows={2}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
preview={false}
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
</div>
<div className="flex flex-col gap-1.5">
@ -397,14 +399,15 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Lock message (optional)
</Label>
<Textarea
<MarkupEditor
value={choice.lockedHint ?? ""}
onChange={(e) =>
setChoice(index, { ...choice, lockedHint: e.target.value || undefined })
onChange={(next) =>
setChoice(index, { ...choice, lockedHint: next || undefined })
}
placeholder='Shown on the disabled choice, e.g. "Needs {amber}trusted{/} standing."'
rows={2}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
preview={false}
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
<p className="text-[10px] text-white/40">
Player-specific flag takes priority; falls back to global (no user).
@ -438,12 +441,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Narration
</Label>
<Textarea
<MarkupEditor
value={draft.body ?? ""}
onChange={(e) => patch({ body: e.target.value || undefined })}
onChange={(next) => patch({ body: next || undefined })}
placeholder="Describe what happens. Shown as a speaker-less narrative line."
rows={3}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
<p className="text-[10px] text-white/40">
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
@ -624,12 +627,13 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
{draft.effect && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Message</Label>
<Textarea
<MarkupEditor
value={draft.effect.message ?? ""}
onChange={(e) => patchEffect({ message: e.target.value || undefined })}
onChange={(next) => patchEffect({ message: next || undefined })}
placeholder="What happens when the player reaches this node?"
rows={3}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
preview={false}
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
</div>
)}
@ -723,12 +727,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
{node.type === "end" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Closing line</Label>
<Textarea
<MarkupEditor
value={draft.closing ?? ""}
onChange={(e) => patch({ closing: e.target.value || undefined })}
onChange={(next) => patch({ closing: next || undefined })}
placeholder="The conversation ends."
rows={3}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
<p className="text-[10px] text-white/40">
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.

View file

@ -16,17 +16,85 @@ import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
* stay put; no navigation, so conversation progress survives)
* {cd|<iso|done>} countdown leaf produced by `{{countdown:key}}` resolution
*
* Block level: consecutive lines starting with `- `/`* ` render as a bullet
* list, consecutive lines starting with `1.`/`2)` as an ordered list; item
* content runs through the inline parser like any other text. A line whose
* prose merely starts with "- " also becomes a bullet, so start list items
* deliberately.
*
* Shared by the admin flow editor previews and the frontend conversation
* dialog, so it must stay client-safe (no Payload imports).
*/
export function DialogueText({ text, className }: { text: string; className?: string }) {
return (
<span className={`whitespace-pre-wrap ${className ?? ""}`}>
{parseSegment(text, 0, { i: 0 }, false).nodes}
{renderBlocks(text, { i: 0 })}
</span>
);
}
const BULLET_RE = /^[-*]\s+/;
const ORDERED_RE = /^\d+[.)]\s+/;
/**
* Line-based block pass over `text`: runs of bullet / ordered lines collapse
* into list groups (spans with list roles, so they stay valid inside the
* inline wrapper), everything else flushes as a paragraph rendered by the
* inline parser. A blank line or a kind change splits adjacent lists.
*/
function renderBlocks(text: string, keys: { i: number }): ReactNode[] {
if (!text) return [];
const out: ReactNode[] = [];
let paragraph: string[] = [];
let listKind: "ul" | "ol" | null = null;
let items: string[] = [];
const flushParagraph = () => {
if (paragraph.length === 0) return;
const chunk = paragraph.join("\n");
paragraph = [];
out.push(<span key={`p${keys.i++}`}>{parseSegment(chunk, 0, keys, false).nodes}</span>);
};
const flushList = () => {
if (!listKind) return;
const kind = listKind;
out.push(
<span key={`l${keys.i++}`} role="list" className="my-0.5 flex flex-col gap-0.5 pl-2">
{items.map((item, index) => (
<span key={index} role="listitem" className="flex gap-2">
<span aria-hidden className="shrink-0 text-white/40">
{kind === "ul" ? "\u2022" : `${index + 1}.`}
</span>
<span>{parseSegment(item, 0, keys, false).nodes}</span>
</span>
))}
</span>,
);
items = [];
listKind = null;
};
for (const line of text.split("\n")) {
const kind: "ul" | "ol" | null = BULLET_RE.test(line)
? "ul"
: ORDERED_RE.test(line)
? "ol"
: null;
if (kind) {
if (listKind && listKind !== kind) flushList();
flushParagraph();
listKind = kind;
items.push(line.replace(kind === "ul" ? BULLET_RE : ORDERED_RE, ""));
continue;
}
if (listKind) flushList();
paragraph.push(line);
}
flushList();
flushParagraph();
return out;
}
/** Friendly color names mapped to Tailwind text classes (400 shades read well
* on the dark conversation surface). Keys are lowercase. */
const FRIENDLY_COLORS: Record<string, string> = {

View file

@ -521,3 +521,35 @@ describe("ternary tokens ({{ cond ? yes : no }})", () => {
expect(collectNodeTokens(node)).toEqual(expect.arrayContaining(["trust", "rep", "exfil"]));
});
});
describe("block lists in dialogue markup", () => {
const render = (text: string) => renderToStaticMarkup(createElement(DialogueText, { text }));
it("renders consecutive dash lines as one bullet list with markers", () => {
const html = render("- first\n- second");
expect(html).toContain('role="list"');
expect(html.match(/role="listitem"/g)?.length).toBe(2);
expect(html).toContain("first");
expect(html).toContain("\u2022");
});
it("renders numbered lines as an ordered list and keeps inline markup inside items", () => {
const html = render("1. **one**\n2. *two*");
expect(html).toContain("one</strong>");
expect(html).toContain("<em>two</em>");
expect(html).toContain("1.");
expect(html).toContain("2.");
});
it("splits paragraphs from lists and adjacent kinds into separate lists", () => {
const html = render("intro line\n- a\n- b\n\n1. x\n1. y");
expect(html.match(/role="list"/g)?.length).toBe(2);
expect(html).toContain("intro line");
});
it("does not treat leading emphasis or prose asterisks as bullets", () => {
const html = render("*emphasis start* is fine");
expect(html).toContain("<em>emphasis start</em>");
expect(html).not.toContain('role="list"');
});
});