1
0
Fork 0
polaris-task-force/src/components/admin/npc-dialogue/NodeEditDialog.tsx
Z8MB1E 089246def8 feat(npc-dialogue): flow editor UX pass for authoring dialogue flows
- Delete selected nodes with Del/Backspace (guarded against open dialogs,
  menus, and focused form fields)
- Double-click the canvas to drop a dialogue node at the cursor; right-click
  empty canvas for a New node menu with all six types; toolbar buttons now
  place nodes at the viewport center instead of blind grid coordinates
- Choices support optional flag conditions evaluated server-side per player
  (player flag first, global fallback); gated choices stay hidden until the
  server confirms them, so forbidden options never flash on screen
- Litegraph-style per-output handles: one source handle per choice row plus
  dedicated true/false handles on condition nodes, wired through derived
  edges and handle-aware connections
- Brighten passive edge lines and edge labels on the dark canvas
- New dialogue nodes default to an empty speaker, rendering the NPC's name
2026-10-06 13:44:01 -04:00

628 lines
26 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import { XIcon } from "lucide-react";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} 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";
import type {
DialogueCondition,
DialogueFlagOp,
DialogueNext,
DialogueNode,
DialogueNodeData,
NpcDialogueEffect,
NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue";
import { EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
interface NodeEditDialogProps {
readonly node: DialogueNode | null;
/** Every node in the flow, used to build the "goes to" target lists. */
readonly allNodes: DialogueNode[];
readonly open: boolean;
readonly onOpenChange: (open: boolean) => void;
readonly onSave: (nodeId: string, data: DialogueNodeData) => void;
}
const EFFECT_LABELS: Record<NpcDialogueEffect["type"], string> = {
notify: "Notify user (in-app)",
emit: "Log game event",
reward: "Reward (unconfigured)",
flag: "Set player flag",
};
const FLAG_OP_LABELS: Record<DialogueFlagOp, string> = {
set_true: "Set to true",
set_false: "Set to false",
set_number: "Set number to",
add: "Add to number",
};
const CONDITION_OP_LABELS: Record<DialogueCondition["op"], string> = {
is_true: "is true",
is_false: "is false",
gte: "is at least",
lte: "is at most",
gt: "is greater than",
lt: "is less than",
eq: "equals",
};
/** Ops that compare against a number (everything except is_true/is_false). */
const NUMERIC_OPS: DialogueCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"];
/** Short readable label for a node in the target pickers, with a text snippet. */
function nodeLabel(node: DialogueNode): string {
const d = node.data;
let preview: string;
switch (node.type) {
case "dialogue": {
const speaker = d.speaker?.trim();
const body = d.body?.trim();
preview = speaker && body ? `${speaker}: ${body}` : speaker || body || "Empty line";
break;
}
case "choice": {
const lead = d.leadIn?.trim();
const count = d.choices?.length ?? 0;
const tail = `${count} choice${count === 1 ? "" : "s"}`;
preview = lead ? `${lead} (${tail})` : tail;
break;
}
case "event":
preview =
d.body?.trim() ||
d.effect?.message?.trim() ||
(d.effect ? EFFECT_LABELS[d.effect.type] : "Narration");
break;
case "delay":
preview = d.delaySeconds ? `${d.delaySeconds}s pause` : "Pause";
break;
case "condition": {
const c = d.condition;
preview = c ? `flag "${c.key || "?"}" ${CONDITION_OP_LABELS[c.op]}` : "Condition";
break;
}
default:
preview = d.closing?.trim() || "Conversation ends";
}
const trimmed = preview.length > 48 ? `${preview.slice(0, 48)}…` : preview;
return `${node.type} · ${trimmed}`;
}
/** Inline editor for a single dialogue node's data. */
export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: NodeEditDialogProps) {
const [draft, setDraft] = useState<DialogueNodeData | null>(null);
useEffect(() => {
setDraft(node?.data ?? null);
}, [node?.id, open]);
if (!node || !draft) return null;
const patch = (partial: Partial<DialogueNodeData>) =>
setDraft((prev) => (prev ? { ...prev, ...partial } : prev));
const patchEffect = (partial: Partial<NpcDialogueEffect>) =>
patch({ effect: { type: "notify", ...draft.effect, ...partial } });
const patchCondition = (partial: Partial<DialogueCondition>) =>
patch({
condition: { kind: "flag", key: "", op: "is_true", ...draft.condition, ...partial },
});
const setChoice = (index: number, next: DialogueNext) =>
patch({ choices: (draft.choices ?? []).map((choice, i) => (i === index ? next : choice)) });
const addChoice = () =>
patch({ choices: [...(draft.choices ?? []), { label: "", target: "" }] });
const removeChoice = (index: number) =>
patch({ choices: (draft.choices ?? []).filter((_, i) => i !== index) });
/** Toggle/update a choice's visibility gate; null removes the gate. */
const setChoiceCondition = (index: number, partial: Partial<DialogueCondition> | null) =>
patch({
choices: (draft.choices ?? []).map((c, i) => {
if (i !== index) return c;
if (partial === null) return { ...c, condition: undefined };
const base: DialogueCondition = c.condition ?? { kind: "flag", key: "", op: "is_true" };
return { ...c, condition: { ...base, ...partial } };
}),
});
const targetOptions = allNodes.filter((n) => n.id !== node.id);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
className="max-w-lg max-h-[80vh] overflow-y-auto dark:bg-zinc-900 dark:text-zinc-100 dark:border-zinc-700 bg-white text-zinc-900"
showCloseButton={false}
onClick={(e) => e.stopPropagation()}
>
<DialogHeader>
<DialogTitle className="flex items-center justify-between">
<span>Edit {node.type}</span>
<span
onClick={() => onOpenChange(false)}
className="p-2 -m-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 rounded-full"
aria-label="Close"
>
<XIcon className="size-4 text-zinc-500" />
</span>
</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4 pt-2">
{node.type === "dialogue" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Speaker</Label>
<Input
value={draft.speaker ?? ""}
onChange={(e) => patch({ speaker: e.target.value || undefined })}
placeholder="Defaults to the NPC's name"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
</div>
)}
{node.type === "dialogue" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Line</Label>
<Textarea
value={draft.body ?? ""}
onChange={(e) => patch({ body: e.target.value || undefined })}
placeholder="The NPC says…"
rows={4}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<p className="text-[10px] text-white/40">
Line breaks are kept. **bold**, *italic*, {`{red}color{/}`} and {'`code`'} render
in the conversation. Colors take a friendly name (red, amber, cyan, emerald,
violet, pink, slate, ...) or a hex code like {`{#ff00ff}`}.
</p>
</div>
)}
{node.type === "choice" && (
<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
value={draft.leadIn ?? ""}
onChange={(e) => patch({ leadIn: e.target.value || undefined })}
placeholder="Optional line before the choices."
rows={2}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
</div>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Choices
</Label>
<Button
type="button"
variant="outline"
size="sm"
onClick={addChoice}
className="h-6 border-white/20 text-xs text-white"
>
Add choice
</Button>
</div>
{(draft.choices ?? []).map((choice, index) => (
<div key={index} className="flex flex-col gap-1.5 border-t border-white/10 pt-2">
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-white/40">Button text</Label>
<Input
value={choice.label ?? ""}
onChange={(e) => setChoice(index, { ...choice, label: e.target.value })}
placeholder="How do you respond?"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-white/40">Goes to</Label>
<select
value={choice.target ?? ""}
onChange={(e) => setChoice(index, { ...choice, target: e.target.value })}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="">None</option>
{targetOptions.map((target) => (
<option key={target.id} value={target.id}>
{nodeLabel(target)}
</option>
))}
</select>
</div>
<label className="flex items-center gap-2 text-xs text-white/60">
<Checkbox
checked={choice.once === true}
onCheckedChange={(checked) =>
setChoice(index, {
...choice,
once: checked === true ? true : undefined,
})
}
className="border-white/30 data-[state=checked]:border-cyan-500 data-[state=checked]:bg-cyan-500"
/>
Hide after picked (one-time choice)
</label>
<label className="flex items-center gap-2 text-xs text-white/60">
<Checkbox
checked={choice.condition !== undefined}
onCheckedChange={(checked) =>
setChoiceCondition(index, checked === true ? {} : null)
}
className="border-white/30 data-[state=checked]:border-sky-500 data-[state=checked]:bg-sky-500"
/>
Only show when a flag condition passes
</label>
{choice.condition && (
<div className="flex flex-col gap-1.5 rounded border border-sky-500/25 bg-sky-950/20 p-2">
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Flag key
</Label>
<Input
value={choice.condition.key}
onChange={(e) => setChoiceCondition(index, { key: e.target.value })}
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
When the flag
</Label>
<select
value={choice.condition.op}
onChange={(e) =>
setChoiceCondition(index, {
op: e.target.value as DialogueCondition["op"],
})
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(CONDITION_OP_LABELS) as DialogueCondition["op"][]).map(
(op) => (
<option key={op} value={op}>
{CONDITION_OP_LABELS[op]}
</option>
),
)}
</select>
{NUMERIC_OPS.includes(choice.condition.op) && (
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Amount
</Label>
<Input
type="number"
value={choice.condition.amount ?? 0}
onChange={(e) =>
setChoiceCondition(index, { amount: Number(e.target.value) || 0 })
}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
<p className="text-[10px] text-white/40">
Player-specific flag takes priority; falls back to global (no user).
Missing = false / 0. The choice button is hidden until this passes.
</p>
</div>
)}
<Button
type="button"
variant="outline"
size="sm"
onClick={() => removeChoice(index)}
className="h-6 self-end border-red-900/50 text-red-400 hover:bg-red-950/40"
>
Remove
</Button>
</div>
))}
{(draft.choices?.length ?? 0) === 0 && (
<p className="text-xs text-white/30">No choices yet. Add one above.</p>
)}
</div>
</div>
)}
{node.type === "event" && (
<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">
Narration
</Label>
<Textarea
value={draft.body ?? ""}
onChange={(e) => patch({ body: e.target.value || 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"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Effect</Label>
<select
value={draft.effect?.type ?? "none"}
onChange={(e) => {
const type = e.target.value;
if (type === "none") patch({ effect: undefined });
else patchEffect({ type: type as NpcDialogueEffect["type"] });
}}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="none">None (narration only)</option>
{EFFECT_TYPES.map((type) => (
<option key={type} value={type}>
{EFFECT_LABELS[type]}
</option>
))}
</select>
</div>
{draft.effect?.type === "notify" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Title</Label>
<Input
value={draft.effect.title ?? ""}
onChange={(e) => patchEffect({ title: e.target.value || undefined })}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
{draft.effect?.type === "flag" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Flag key
</Label>
<Input
value={draft.effect.flagKey ?? ""}
onChange={(e) => patchEffect({ flagKey: e.target.value || undefined })}
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Write
</Label>
<select
value={draft.effect.flagOp ?? "set_true"}
onChange={(e) =>
patchEffect({ flagOp: e.target.value as DialogueFlagOp })
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(FLAG_OP_LABELS) as DialogueFlagOp[]).map((op) => (
<option key={op} value={op}>
{FLAG_OP_LABELS[op]}
</option>
))}
</select>
{(draft.effect.flagOp === "set_number" ||
draft.effect.flagOp === "add") && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Amount
</Label>
<Input
type="number"
value={draft.effect.flagAmount ?? 0}
onChange={(e) =>
patchEffect({ flagAmount: Number(e.target.value) || 0 })
}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
<p className="text-[10px] text-white/40">
Creates the flag when the player does not have it yet. "Add" keeps numeric
flags running totals.
</p>
</div>
)}
{draft.effect && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Message</Label>
<Textarea
value={draft.effect.message ?? ""}
onChange={(e) => patchEffect({ message: e.target.value || 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"
/>
</div>
)}
</div>
)}
{node.type === "delay" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Pause (seconds)
</Label>
<Input
type="number"
min={0}
step={0.5}
value={draft.delaySeconds ?? 2}
onChange={(e) =>
patch({ delaySeconds: Math.max(0, Number(e.target.value) || 0) })
}
className="bg-zinc-800 border-white/20 text-white"
/>
<p className="text-[10px] text-white/40">
The conversation shows typing dots for this long, then continues.
</p>
</div>
)}
{node.type === "condition" && (
<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">
Flag key
</Label>
<Input
value={draft.condition?.key ?? ""}
onChange={(e) => patchCondition({ key: e.target.value })}
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<p className="text-[10px] text-zinc-400">
Player-specific flag takes priority; falls back to global (no user). Missing = false / 0.
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
When the flag
</Label>
<select
value={draft.condition?.op ?? "is_true"}
onChange={(e) => patchCondition({ op: e.target.value as DialogueCondition["op"] })}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(CONDITION_OP_LABELS) as DialogueCondition["op"][]).map((op) => (
<option key={op} value={op}>
{CONDITION_OP_LABELS[op]}
</option>
))}
</select>
</div>
{NUMERIC_OPS.includes(draft.condition?.op ?? "is_true") && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Amount
</Label>
<Input
type="number"
value={draft.condition?.amount ?? 0}
onChange={(e) => patchCondition({ amount: Number(e.target.value) || 0 })}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
True branch goes to
</Label>
<select
value={draft.trueTarget ?? ""}
onChange={(e) => patch({ trueTarget: e.target.value || undefined })}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="">Nothing (ends here)</option>
{targetOptions.map((target) => (
<option key={target.id} value={target.id}>
{nodeLabel(target)}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
False branch goes to
</Label>
<select
value={draft.falseTarget ?? ""}
onChange={(e) => patch({ falseTarget: e.target.value || undefined })}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="">Nothing (ends here)</option>
{targetOptions.map((target) => (
<option key={target.id} value={target.id}>
{nodeLabel(target)}
</option>
))}
</select>
</div>
</div>
)}
{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
value={draft.closing ?? ""}
onChange={(e) => patch({ closing: e.target.value || undefined })}
placeholder="The conversation ends."
rows={3}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
</div>
)}
{(node.type === "dialogue" || node.type === "event" || node.type === "delay") && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Continues to
</Label>
<select
value={draft.next?.target ?? ""}
onChange={(e) => {
const target = e.target.value;
patch({
next: target ? { ...(draft.next ?? { target: "" }), target } : undefined,
});
}}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="">Ends the conversation</option>
{targetOptions.map((target) => (
<option key={target.id} value={target.id}>
{nodeLabel(target)}
</option>
))}
</select>
</div>
)}
<label className="flex items-center gap-2 pt-2 text-sm text-white/70 cursor-pointer">
<Checkbox
checked={draft.isStart === true}
onCheckedChange={(checked) => patch({ isStart: checked === true })}
/>
Mark as conversation start
</label>
<DialogFooter className="gap-2 -mt-2">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
className="border-white/20 text-white"
>
Cancel
</Button>
<Button
type="button"
onClick={() => onSave(node.id, draft)}
className="bg-cyan-600 text-white hover:bg-cyan-500"
>
Save
</Button>
</DialogFooter>
</div>
</DialogContent>
</Dialog>
);
}