1
0
Fork 0
polaris-task-force/src/components/admin/npc-dialogue/NodeEditDialog.tsx
Z8MB1E 4264431e4d feat(npc-dialogue): AI-assisted conversation drafting behind the review gate
Add a Generate button to the flow editor that drafts a whole conversation
from a form brief, and per-line Rewrite/Shorten/Sharpen controls in the node
dialog. Both land in unsaved field state, so a draft only reaches players when
an author saves the document: neither server action writes to npc-dialogues.

- src/lib/ai/generate.ts: extract the Unsloth client out of payload.config so
  Compose and dialogue drafting share one path; add generateStructured and
  resolveModel, with an optional UNSLOTH_MODEL_STRUCTURED override
- generationSchema.ts (pure): strict-safe JSON schema, normalizer with
  breadth layout, validator that rejects unknown flag keys, unauthorised
  effects, dangling hops and missing keys
- generation.ts: context loading, one validate-and-retry, then give up rather
  than hand back a broken graph; dash normalization keeps shipped copy clean
- effect vocabulary limited to notify and flag; emit, reward and discord stay
  author-only
- provenance group on npc-dialogues (migration 20261112_171955) records model,
  prompt version, attempts and the brief the draft was accepted from
- tests: 21 cases covering the normalizer, validator, retry paths and the
  rewrite parser, with the model call injected
- docs/npc-dialogue-ai.md and src/lib/npc-dialogue/AGENTS.md
2026-11-12 12:26:35 -05:00

1094 lines
46 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ChevronDownIcon, ChevronUpIcon, 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 { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import type {
DialogueAttachment,
DialogueCondition,
DialogueConditionGroup,
DialogueFlagCondition,
DialogueFlagOp,
DialogueNext,
DialogueNode,
DialogueNodeData,
NpcDialogueEffect,
NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue";
import { conditionSummary, EFFECT_TYPES, outgoingHops } from "@/lib/npc-dialogue/dialogue";
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
import { MarkupEditor } from "./MarkupEditor";
import { LineAssist } from "./LineAssist";
import { uploadNpcDialogueAttachment } from "@/app/(frontend)/personnel/contacts/[id]/actions";
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;
/** The contact this flow belongs to, for the per-line AI controls. */
readonly npcId: number | null;
}
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",
set_text: "Set text to",
add: "Add to number",
};
const CONDITION_OP_LABELS: Record<DialogueFlagCondition["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",
};
/** Group combinators, in UI order. Groups are single-level over leaves. */
const GROUP_OP_LABELS: Record<DialogueConditionGroup["op"], string> = {
and: "All conditions match (AND)",
or: "Any condition matches (OR)",
nor: "No condition matches (NOR)",
};
/** Ops that compare against a number (everything except is_true/is_false). */
const NUMERIC_OPS: DialogueFlagCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"];
/** A blank leaf used when switching into single mode or adding a group row. */
const EMPTY_LEAF: DialogueFlagCondition = { kind: "flag", key: "", op: "is_true" };
/** Max height (px) the dialogue Line box auto-grows to. Longer content scrolls
* inside the box from here; the user can still drag-resize it taller. */
const MAX_LINE_HEIGHT_PX = 200;
/** 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 ? conditionSummary(c) : "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,
npcId,
}: NodeEditDialogProps) {
const [draft, setDraft] = useState<DialogueNodeData | null>(null);
// The line immediately before this node, so a rewrite does not restate it.
// Reads the incoming hop's source rather than a separate "previous" prop,
// because the graph already knows and nothing else does.
const previousLine = useMemo(() => {
if (!node) return null;
const source = allNodes.find((candidate) =>
outgoingHops(candidate).some((hop) => hop?.target === node.id),
);
return source?.data.body?.trim() || source?.data.leadIn?.trim() || null;
}, [node, allNodes]);
// Users for the "Specific user" flag target. Fetched once per open; the
// admin context is already authenticated, so cookie auth is enough.
const [users, setUsers] = useState<{ id: number; username: string }[]>([]);
useEffect(() => {
let active = true;
if (!open) return;
fetch("/api/users?limit=1000&depth=0")
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (!active) return;
const list = Array.isArray(data?.docs) ? data.docs : [];
setUsers(
list
.filter((u: { username?: unknown }) => Boolean(u?.username))
.map((u: { id: number; username: string }) => ({
id: u.id,
username: `${u.username} (id ${u.id})`,
})),
);
})
.catch(() => {
if (active) setUsers([]);
});
return () => {
active = false;
};
}, [open]);
useEffect(() => {
setDraft(node?.data ?? null);
}, [node?.id, open]);
const patch = (partial: Partial<DialogueNodeData>) =>
setDraft((prev) => (prev ? { ...prev, ...partial } : prev));
const lineRef = useRef<HTMLTextAreaElement>(null);
/** Auto-grow the line box to its content up to MAX_LINE_HEIGHT_PX so long
* lines do not scroll in a fixed-height box. The user can still drag-resize
* it taller; typing re-sizes it to fit. */
const autoSizeLine = useCallback(() => {
const el = lineRef.current;
if (!el) return;
el.style.height = "auto";
el.style.height = `${Math.min(el.scrollHeight, MAX_LINE_HEIGHT_PX)}px`;
}, []);
useEffect(() => {
autoSizeLine();
}, [draft?.body, autoSizeLine]);
// Guard lives below every hook so their call order never changes: on the
// first render draft is still null, and returning early here would skip the
// hooks defined above it on later renders (a Rules of Hooks violation).
if (!node || !draft) return null;
const patchEffect = (partial: Partial<NpcDialogueEffect>) =>
patch({ effect: { type: "notify", ...draft.effect, ...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) });
/** Swap a choice with its neighbour so choices can be reordered. No-op at
* the ends, so the buttons can be disabled there. */
const moveChoice = (index: number, direction: -1 | 1) => {
const ordered = reorderChoice(draft.choices ?? [], index, direction);
if (ordered) patch({ choices: ordered });
};
/** Toggle/replace a choice's visibility gate; null removes the gate. */
const setChoiceCondition = (index: number, next: DialogueCondition | null) =>
patch({
choices: (draft.choices ?? []).map((c, i) =>
i === index ? { ...c, condition: next ?? undefined } : c,
),
});
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>
<MarkupEditor
value={draft.body ?? ""}
onChange={(next) => {
patch({ body: next || undefined });
autoSizeLine();
}}
placeholder="The NPC says…"
rows={4}
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"
/>
<LineAssist
npcId={npcId}
nodeType={node.type}
value={draft.body ?? ""}
previousLine={previousLine}
onChange={(next) => {
patch({ body: next || undefined });
autoSizeLine();
}}
/>
<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}`}. Insert flag values
with {'{{flag_key}}'}; text flags may carry their own color markup. Pick a branch
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. Lines starting with "- " or "1. " become lists.
Right-click the box for a markup menu.
</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>
<MarkupEditor
value={draft.leadIn ?? ""}
onChange={(next) => patch({ leadIn: next || undefined })}
placeholder="Optional line before the choices."
rows={2}
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
<LineAssist
npcId={npcId}
nodeType={node.type}
value={draft.leadIn ?? ""}
previousLine={previousLine}
onChange={(next) => patch({ leadIn: next || undefined })}
/>
</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 items-center justify-end gap-1">
<Button
type="button"
variant="outline"
size="icon"
aria-label="Move choice up"
disabled={index === 0}
onClick={() => moveChoice(index, -1)}
className="h-6 w-6 border-white/20 text-white/70 hover:bg-zinc-800 disabled:opacity-30"
>
<ChevronUpIcon className="size-3.5" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
aria-label="Move choice down"
disabled={index === (draft.choices?.length ?? 0) - 1}
onClick={() => moveChoice(index, 1)}
className="h-6 w-6 border-white/20 text-white/70 hover:bg-zinc-800 disabled:opacity-30"
>
<ChevronDownIcon className="size-3.5" />
</Button>
</div>
<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"
/>
<LineAssist
npcId={npcId}
nodeType="choice"
value={choice.label ?? ""}
previousLine={previousLine}
onChange={(next) =>
setChoice(index, { ...choice, label: next || undefined })
}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-white/40">
Tooltip (optional)
</Label>
<MarkupEditor
value={choice.tooltip ?? ""}
onChange={(next) =>
setChoice(index, { ...choice, tooltip: next || undefined })
}
placeholder="Hover card. Supports markup, {{flags}} and ![alt](url) images."
rows={2}
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">
<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 ? EMPTY_LEAF : 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">
<ConditionFields
value={choice.condition}
onChange={(next) => setChoiceCondition(index, next)}
/>
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Lock message (optional)
</Label>
<MarkupEditor
value={choice.lockedHint ?? ""}
onChange={(next) =>
setChoice(index, { ...choice, lockedHint: next || undefined })
}
placeholder='Shown on the disabled choice, e.g. "Needs {amber}trusted{/} standing."'
rows={2}
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).
Missing = false / 0. With a lock message the choice stays visible but
disabled (tooltip explains why) while the condition fails; without one
it is hidden entirely.
</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>
<MarkupEditor
value={draft.body ?? ""}
onChange={(next) => patch({ body: next || undefined })}
placeholder="Describe what happens. Shown as a speaker-less narrative line."
rows={3}
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.
</p>
</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"
/>
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Target
</Label>
<select
value={draft.effect.flagTarget ?? "self"}
onChange={(e) =>
patchEffect({
flagTarget: e.target.value as "self" | "global" | "user",
// Leave the target user id set only in the "user" scope so
// switching away never leaves a dangling owner behind.
flagTargetUserId:
e.target.value === "user"
? draft.effect?.flagTargetUserId ?? users[0]?.id ?? undefined
: undefined,
})
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="self">Self (this player)</option>
<option value="global">Global (everyone, same key)</option>
<option value="user">Specific user</option>
</select>
{draft.effect.flagTarget === "user" && (
<select
value={draft.effect.flagTargetUserId ?? ""}
onChange={(e) =>
patchEffect({
flagTargetUserId: e.target.value
? Number(e.target.value)
: undefined,
})
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="">No player</option>
{users.map((user) => (
<option key={user.id} value={user.id}>
{user.username}
</option>
))}
</select>
)}
<p className="text-[10px] text-white/40">
A flag's identity is (owner, key): the same key holds independent
values for each target. Defaults to this player.
</p>
</div>
<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>
)}
{draft.effect.flagOp === "set_text" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Text value
</Label>
<Input
value={draft.effect.flagText ?? ""}
onChange={(e) => patchEffect({ flagText: e.target.value || undefined })}
placeholder="{green}NOMINAL{/}"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<p className="text-[10px] text-white/40">
Conversations insert this value wherever {'{{key}}'} appears. Colors like
{` {green}...{/}`} render in dialogue lines.
</p>
</div>
)}
{(draft.effect.flagOp === "set_true" ||
draft.effect.flagOp === "set_false" ||
draft.effect.flagOp === "set_number" ||
draft.effect.flagOp === "set_text") && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Delay activation (minutes, optional)
</Label>
<Input
type="number"
min={0}
value={draft.effect.flagDelayMinutes ?? ""}
onChange={(e) =>
patchEffect({
flagDelayMinutes:
Number(e.target.value) > 0 ? Number(e.target.value) : undefined,
})
}
placeholder="0 = immediate"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<p className="text-[10px] text-white/40">
For slow-burn narrative: the flag reads as false / 0 until this many
minutes have passed, so conditions fail and {"{{countdown:key}}"} tokens
tick down to it. Leave empty for an immediate write.
</p>
</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; "Set text to" converts the flag to a text flag.
</p>
</div>
)}
{draft.effect && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Message</Label>
<MarkupEditor
value={draft.effect.message ?? ""}
onChange={(next) => patchEffect({ message: next || undefined })}
placeholder="What happens when the player reaches this node?"
rows={3}
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>
)}
{draft.effect && draft.effect.type !== "notify" && (
<label className="flex items-center gap-2 text-xs text-white/60">
<Checkbox
checked={draft.effect.eventVisibility === "public"}
onCheckedChange={(checked) =>
// Unset, not "restricted": leaving the key absent keeps the
// event on the restricted narrative default in visibility.ts.
patchEffect({ eventVisibility: checked === true ? "public" : undefined })
}
className="border-white/30 data-[state=checked]:border-emerald-500 data-[state=checked]:bg-emerald-500"
/>
Show this event to everyone (normally staff only)
</label>
)}
{draft.effect && draft.effect.type !== "notify" && (
<label className="flex items-center gap-2 text-xs text-white/60">
<Checkbox
checked={draft.effect.discord === true}
onCheckedChange={(checked) =>
patchEffect({ discord: checked === true ? true : undefined })
}
className="border-white/30 data-[state=checked]:border-indigo-500 data-[state=checked]:bg-indigo-500"
/>
Post this event to the Discord NPC dispatch channel
</label>
)}
</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">
<ConditionFields
value={draft.condition ?? EMPTY_LEAF}
onChange={(condition) => patch({ condition })}
/>
<p className="-mt-2 text-[10px] text-zinc-400">
Player-specific flag takes priority; falls back to global (no user). Missing =
false / 0.
</p>
<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>
<MarkupEditor
value={draft.closing ?? ""}
onChange={(next) => patch({ closing: next || undefined })}
placeholder="The conversation ends."
rows={3}
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
<LineAssist
npcId={npcId}
nodeType={node.type}
value={draft.closing ?? ""}
previousLine={previousLine}
onChange={(next) => patch({ closing: next || undefined })}
/>
<p className="text-[10px] text-white/40">
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
</p>
</div>
)}
{(node.type === "dialogue" || node.type === "event") && (
<AttachmentEditor
attachments={draft.attachments ?? []}
onChange={(attachments) =>
patch({ attachments: attachments.length > 0 ? attachments : undefined })
}
/>
)}
{(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>
);
}
/**
* Attachment list for a dialogue/event node. Uploads go to the `media`
* collection through the conversation upload action (which gates on
* npc-dialogues:update); flowData only keeps the returned pointer plus an
* editable chip label. Removing here only drops the pointer, never the file.
*/
function AttachmentEditor({
attachments,
onChange,
}: {
attachments: DialogueAttachment[];
onChange: (next: DialogueAttachment[]) => void;
}) {
const inputRef = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const upload = async (file: File) => {
setBusy(true);
setError(null);
try {
const formData = new FormData();
formData.append("file", file);
const result = await uploadNpcDialogueAttachment(formData);
if (result.success && result.data) {
onChange([
...attachments,
{ mediaId: result.data.mediaId, label: result.data.filename },
]);
} else {
setError(result.error ?? "Upload failed.");
}
} finally {
setBusy(false);
}
};
return (
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Attachments</Label>
<Button
type="button"
variant="outline"
size="sm"
disabled={busy}
onClick={() => inputRef.current?.click()}
className="h-6 border-white/20 text-xs text-white"
>
{busy ? "Uploading…" : "Upload file"}
</Button>
</div>
<input
ref={inputRef}
type="file"
className="hidden"
accept="text/*,application/pdf,image/*"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) void upload(file);
e.target.value = "";
}}
/>
{attachments.map((attachment, index) => (
<div key={`${attachment.mediaId}-${index}`} className="flex items-center gap-1.5">
<Input
value={attachment.label ?? ""}
placeholder="Chip label"
onChange={(e) =>
onChange(
attachments.map((a, i) =>
i === index ? { ...a, label: e.target.value || undefined } : a,
),
)
}
className="h-7 bg-zinc-800 border-white/20 text-xs text-white placeholder:text-white/30"
/>
<span className="w-16 shrink-0 truncate font-mono text-[10px] text-white/30">
#{attachment.mediaId}
</span>
<Button
type="button"
variant="outline"
size="sm"
aria-label="Remove attachment"
onClick={() => onChange(attachments.filter((_, i) => i !== index))}
className="h-7 shrink-0 border-red-900/50 px-2 text-xs text-red-400 hover:bg-red-950/40"
>
Remove
</Button>
</div>
))}
{attachments.length === 0 && (
<p className="text-xs text-white/30">No attachments on this line.</p>
)}
{error && <p className="text-[10px] text-red-400">{error}</p>}
<p className="text-[10px] text-white/40">
Players see these as chips under the line that open a file viewer. Text, PDF or image,
up to 8 MB. Files live in the media library; removing a chip never deletes the file.
</p>
</div>
);
}
/**
* Single-level condition builder: a combinator dropdown (one flag, or an
* AND / OR / NOR group) plus one editable row per leaf. Groups never nest,
* which keeps authored JSON shallow and the runtime evaluator single-pass.
*/
function ConditionFields({
value,
onChange,
}: {
value: DialogueCondition;
onChange: (next: DialogueCondition) => void;
}) {
const mode = value.kind === "group" ? `group:${value.op}` : "leaf";
const setMode = (next: string) => {
if (next === mode) return;
if (next === "leaf") {
onChange(value.kind === "group" ? (value.children[0] ?? EMPTY_LEAF) : value);
return;
}
const op = next.slice("group:".length) as DialogueConditionGroup["op"];
if (value.kind === "group") onChange({ ...value, op });
else onChange({ kind: "group", op, children: [value] });
};
const patchLeaf = (index: number, partial: Partial<DialogueFlagCondition>) => {
if (value.kind === "flag" && index === 0) onChange({ ...value, ...partial });
else if (value.kind === "group")
onChange({
...value,
children: value.children.map((c, i) => (i === index ? { ...c, ...partial } : c)),
});
};
const leaves = value.kind === "group" ? value.children : [value];
return (
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-white/40">Condition</Label>
<select
value={mode}
onChange={(e) => setMode(e.target.value)}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="leaf">Single flag condition</option>
{(Object.keys(GROUP_OP_LABELS) as DialogueConditionGroup["op"][]).map((op) => (
<option key={op} value={`group:${op}`}>
{GROUP_OP_LABELS[op]}
</option>
))}
</select>
{leaves.map((leaf, index) => (
<div key={index} className="flex flex-col gap-1.5 border-t border-white/10 pt-1.5">
<div className="flex items-center justify-between">
<Label className="text-[9px] uppercase tracking-wider text-white/40">
{value.kind === "group" ? `Condition ${index + 1}` : "Flag key"}
</Label>
{value.kind === "group" && leaves.length > 1 && (
<Button
type="button"
variant="outline"
size="sm"
aria-label="Remove condition"
onClick={() =>
onChange({ ...value, children: value.children.filter((_, i) => i !== index) })
}
className="h-5 border-red-900/50 px-1.5 text-[10px] text-red-400 hover:bg-red-950/40"
>
Remove
</Button>
)}
</div>
<Input
value={leaf.key}
onChange={(e) => patchLeaf(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-white/40">When the flag</Label>
<select
value={leaf.op}
onChange={(e) => patchLeaf(index, { op: e.target.value as DialogueFlagCondition["op"] })}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(CONDITION_OP_LABELS) as DialogueFlagCondition["op"][]).map((op) => (
<option key={op} value={op}>
{CONDITION_OP_LABELS[op]}
</option>
))}
</select>
{NUMERIC_OPS.includes(leaf.op) && (
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-white/40">Amount</Label>
<Input
type="number"
value={leaf.amount ?? 0}
onChange={(e) => patchLeaf(index, { amount: Number(e.target.value) || 0 })}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
</div>
))}
{value.kind === "group" && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onChange({ ...value, children: [...value.children, EMPTY_LEAF] })}
className="h-6 self-end border-white/20 text-xs text-white"
>
Add condition
</Button>
)}
</div>
);
}