1
0
Fork 0

feat(npc-dialogue): attach files to conversation lines

Nodes can carry pointers to media docs (transcripts, sealed orders,
images). Authors upload from the node editor (gated on
npc-dialogues:update); the runtime resolves ids to file URLs server-side
and players open them in a dossier-styled viewer modal with download
and new-tab escape hatches. Deleted media resolve to nothing instead of
dead chips.
This commit is contained in:
Jason Fraley 2026-10-14 16:05:15 -04:00
parent 799c3216d2
commit a1aaed913d
8 changed files with 481 additions and 6 deletions

View file

@ -11,6 +11,8 @@ import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpol
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
import { markNodeRead } from "@/lib/npc-dialogue/states";
import { resolveAttachments } from "@/lib/npc-dialogue/attachments";
import { hasPermission } from "@/utils/access-control/hasPermission";
import type {
ChoiceGate,
DialogueFlagOp,
@ -280,7 +282,13 @@ export async function resolveNpcDialogueTexts(
// "done", missing ones render nothing.
countdowns[key] = flag.activatesAt ?? (flag.exists ? "done" : "");
}
return { success: true, data: resolveNodeTexts(node, values, countdowns) };
const resolved = resolveNodeTexts(node, values, countdowns);
// Attachments ride the same round trip: ids become renderable file
// references here, so the client never guesses media URLs and deleted
// files simply drop off instead of rendering dead chips.
const attachments = await resolveAttachments(payload, node.data.attachments);
if (attachments.length > 0) resolved.attachments = attachments;
return { success: true, data: resolved };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
@ -315,3 +323,69 @@ export async function markNpcDialogueNodeRead(
}
}
/** File types authors may attach to a conversation node. */
const ATTACHMENT_TYPES = new Set([
"text/plain",
"application/pdf",
"image/png",
"image/jpeg",
"image/webp",
"image/gif",
]);
/**
* Upload a file to attach to a conversation node (intercept transcripts,
* sealed orders, reference images). The bytes land in `media`; flowData only
* keeps the returned pointer, and resolveNpcDialogueTexts turns it back into
* a URL per read. Gated like dialogue authoring (npc-dialogues:update) since
* this stores files the whole unit will be served.
*/
export async function uploadNpcDialogueAttachment(
formData: FormData,
): Promise<ActionResult<{ mediaId: number; filename: string; mimeType: string }>> {
try {
const { payload, user } = await authenticate();
const allowed = await hasPermission(payload, user, "npc-dialogues:update");
if (!allowed) {
return { success: false, error: "You are not allowed to edit conversations." };
}
const file = formData.get("file");
if (!(file instanceof File)) {
return { success: false, error: "No file was provided." };
}
if (!ATTACHMENT_TYPES.has(file.type)) {
return { success: false, error: "Attachments must be text, PDF, or image files." };
}
if (file.size > 8 * 1024 * 1024) {
return { success: false, error: "Attachments must be 8 MB or smaller." };
}
const doc = await payload.create({
collection: "media",
data: {
alt: file.name.replace(/\.[^/.]+$/, "").replace(/[^a-zA-Z0-9 _-]/g, "").trim() || "Attachment",
},
file: {
data: Buffer.from(await file.arrayBuffer()),
mimetype: file.type,
name: file.name,
size: file.size,
},
overrideAccess: true,
});
if (!doc.filename) {
return { success: false, error: "Upload failed: no file was stored." };
}
return {
success: true,
data: { mediaId: doc.id, filename: doc.filename, mimeType: file.type },
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };
}
return { success: false, error: message };
}
}

View file

@ -17,6 +17,7 @@ import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import type {
DialogueAttachment,
DialogueCondition,
DialogueFlagOp,
DialogueNext,
@ -27,6 +28,7 @@ import type {
} from "@/lib/npc-dialogue/dialogue";
import { EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
import { uploadNpcDialogueAttachment } from "@/app/(frontend)/personnel/contacts/[id]/actions";
interface NodeEditDialogProps {
readonly node: DialogueNode | null;
@ -803,6 +805,15 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
</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">
@ -858,3 +869,107 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
</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>
);
}

View file

@ -0,0 +1,111 @@
"use client";
import { useState } from "react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import {
DownloadIcon,
ExternalLinkIcon,
PaperclipIcon,
XIcon,
} from "lucide-react";
import type { ResolvedAttachment } from "@/lib/npc-dialogue/dialogue";
/**
* Attachment chips for a conversation line. Each chip opens the file in a
* dossier-styled modal (images render directly, everything else through an
* iframe, which gives PDFs and plain text their native browser viewer) with
* download and new-tab escape hatches. Mirrors how DialogueLink presents
* linked pages, so attachments and links feel like one system.
*/
export function DialogueAttachments({
attachments,
}: {
attachments: ResolvedAttachment[] | undefined;
}) {
const [active, setActive] = useState<ResolvedAttachment | null>(null);
if (!attachments || attachments.length === 0) return null;
const isImage = (a: ResolvedAttachment) => a.mimeType.startsWith("image/");
return (
<>
<div className="flex flex-wrap gap-1.5 pt-0.5">
{attachments.map((attachment) => (
<button
key={attachment.url}
type="button"
onClick={() => setActive(attachment)}
title={`Open ${attachment.label}`}
className="inline-flex max-w-full items-center gap-1.5 rounded-none border border-cyan-500/30 bg-cyan-500/10 px-2 py-0.5 font-mono text-[10px] uppercase tracking-widest text-cyan-200 transition-colors hover:border-cyan-400/60 hover:text-cyan-100"
>
<PaperclipIcon className="size-3 shrink-0" />
<span className="truncate">{attachment.label}</span>
</button>
))}
</div>
<Dialog open={active !== null} onOpenChange={(next) => !next && setActive(null)}>
<DialogContent
showCloseButton={false}
className="flex h-[85vh] w-[92vw] max-w-4xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white"
>
<div className="flex items-center justify-between gap-4 border-b border-white/15 bg-black/50 px-4 py-2 backdrop-blur-sm">
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
Attachment // {active?.label}
</DialogTitle>
<div className="flex shrink-0 items-center gap-3">
{active && (
<>
<a
href={active.url}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-widest text-white/40 transition-colors hover:text-cyan-400"
>
<ExternalLinkIcon className="size-3" />
New tab
</a>
<a
href={active.url}
download={active.filename}
className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-widest text-white/40 transition-colors hover:text-cyan-400"
>
<DownloadIcon className="size-3" />
Download
</a>
</>
)}
<button
type="button"
onClick={() => setActive(null)}
aria-label="Close attachment"
className="text-white/40 transition-colors hover:text-white/90"
>
<XIcon className="size-4" />
</button>
</div>
</div>
{active && isImage(active) ? (
<div className="min-h-0 flex-1 overflow-auto bg-zinc-900 p-4">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={active.url}
alt={active.label}
className="mx-auto max-h-full max-w-full object-contain"
/>
</div>
) : (
active && (
<iframe
src={active.url}
title={active.label}
className="min-h-0 flex-1 bg-zinc-900"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
/>
)
)}
</DialogContent>
</Dialog>
</>
);
}

View file

@ -8,6 +8,7 @@ import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc
import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate";
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments";
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
import { DOSSIER } from "@/components/frontend/operations";
import { Button } from "@/components/ui/button";
@ -168,7 +169,7 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
* tokens skip the round trip and render their raw authored text. */
const typeIn = async (node: DialogueNode, token: number) => {
let resolved: ResolvedNodeTexts | undefined;
if (collectNodeTokens(node).length > 0) {
if (collectNodeTokens(node).length > 0 || (node.data.attachments?.length ?? 0) > 0) {
const res = await resolveNpcDialogueTexts(Number(npc.id), node.id);
if (sessionRef.current !== token) return;
if (res.success && res.data) resolved = res.data;
@ -483,9 +484,12 @@ function TimelineEntry({
const message = resolved?.message ?? node.data.effect?.message;
const text = body || message || "An event unfolds…";
return (
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
<DialogueText text={text} />
</p>
<div className="flex flex-col gap-1">
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
<DialogueText text={text} />
</p>
<DialogueAttachments attachments={resolved?.attachments} />
</div>
);
}
@ -521,6 +525,7 @@ function TimelineEntry({
<span className="italic text-white/30">…</span>
)}
</p>
<DialogueAttachments attachments={resolved?.attachments} />
</div>
);
}

View file

@ -0,0 +1,43 @@
import type { Payload } from "payload";
import type { DialogueAttachment, ResolvedAttachment } from "./dialogue";
/**
* Resolve flowData attachment pointers into renderable file references.
*
* `flowData` is a plain JSON field, so its nested media ids are never
* populated by Payload; the conversation runtime calls this before sending a
* node to the client. Deleted media documents resolve to nothing (the chip
* disappears instead of rendering a dead link). Payload-dependent, server
* only.
*/
export async function resolveAttachments(
payload: Payload,
attachments: DialogueAttachment[] | undefined,
): Promise<ResolvedAttachment[]> {
if (!attachments || attachments.length === 0) return [];
const out: ResolvedAttachment[] = [];
for (const attachment of attachments) {
const id = Number(attachment.mediaId);
if (!Number.isFinite(id) || id <= 0) continue;
try {
const doc = await payload.findByID({
collection: "media",
id,
depth: 0,
overrideAccess: true,
select: { filename: true, mimeType: true, alt: true, filesize: true },
});
if (!doc?.filename) continue;
out.push({
label: attachment.label?.trim() || doc.filename,
url: `/api/media/file/${doc.filename}`,
filename: doc.filename,
mimeType: doc.mimeType ?? "application/octet-stream",
sizeBytes: doc.filesize ?? undefined,
});
} catch {
// Media document no longer exists: skip the attachment.
}
}
return out;
}

View file

@ -126,6 +126,29 @@ export interface NpcDialogueEffect {
flagTargetUserId?: number | null;
}
/**
* A file attached to a conversation node (transcripts, orders, images). The
* bytes live in the `media` collection; flowData only stores the pointer, so
* the runtime resolves ids to URLs server-side before the client renders
* chips (JSON relationships are never auto-populated).
*/
export interface DialogueAttachment {
/** `media` document id holding the file. */
mediaId: number | string;
/** Chip label; falls back to the stored filename. */
label?: string;
}
/** An attachment resolved for rendering (server-side). */
export interface ResolvedAttachment {
label: string;
/** Site-relative file URL (`/api/media/file/<filename>`). */
url: string;
filename: string;
mimeType: string;
sizeBytes?: number;
}
export type DialogueNodeData = {
/** Speaker label shown above the line. Defaults to the NPC's name at runtime. */
speaker?: string;
@ -139,6 +162,8 @@ export type DialogueNodeData = {
effect?: NpcDialogueEffect;
/** Closing text shown when the conversation ends. */
closing?: string;
/** Files attached to this node's message (dialogue/event/end nodes). */
attachments?: DialogueAttachment[];
/** Marks this node as the conversation start. */
isStart?: boolean;
/** Single continuation (dialogue / event / end nodes). */

View file

@ -11,7 +11,7 @@
* Pure module: client-safe (no Payload imports).
*/
import type { DialogueNode } from "./dialogue";
import type { DialogueNode, ResolvedAttachment } from "./dialogue";
/** One `{{key}}` token. Keys are matched leniently and lowercased; flag keys
* are documented as lowercase-with-underscores. */
@ -60,6 +60,12 @@ export interface ResolvedNodeTexts {
tooltips?: string[];
/** Locked-choice hints, index-aligned with the node's choices. */
hints?: string[];
/**
* Node attachments resolved to renderable file references. Only present
* when the node has attachments (absent means "nothing to render", not
* "unresolved").
*/
attachments?: ResolvedAttachment[];
}
/** Every distinct flag key referenced by `text`, lowercased. */

View file

@ -0,0 +1,96 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { resolveAttachments } from "@/lib/npc-dialogue/attachments";
let payload: Payload;
const TIMEOUT = 30_000;
/** Create a tiny media doc and return its id. */
async function createMedia(name: string): Promise<number> {
const doc = await payload.create({
collection: "media",
data: { alt: name },
file: {
data: Buffer.from(`attachment fixture: ${name}`),
mimetype: "text/plain",
name,
size: 24,
},
overrideAccess: true,
});
return doc.id;
}
describe("resolveAttachments", () => {
beforeAll(async () => {
payload = await getPayload({ config });
}, TIMEOUT);
afterAll(async () => {
// Nothing persists: each test cleans up its own docs below.
});
it(
"returns nothing for missing or empty input",
async () => {
expect(await resolveAttachments(payload, undefined)).toEqual([]);
expect(await resolveAttachments(payload, [])).toEqual([]);
},
TIMEOUT,
);
it(
"resolves pointers to renderable references, honouring custom labels",
async () => {
const id = await createMedia("b2-int-transcript.txt");
try {
const [resolved] = await resolveAttachments(payload, [
{ mediaId: id, label: "Intercept transcript" },
]);
expect(resolved).toMatchObject({
label: "Intercept transcript",
url: "/api/media/file/b2-int-transcript.txt",
filename: "b2-int-transcript.txt",
mimeType: "text/plain",
});
} finally {
await payload.delete({ collection: "media", id, overrideAccess: true });
}
},
TIMEOUT,
);
it(
"falls back to the stored filename when no label is authored",
async () => {
const id = await createMedia("b2-int-order.txt");
try {
const [resolved] = await resolveAttachments(payload, [{ mediaId: id }]);
expect(resolved?.label).toBe("b2-int-order.txt");
} finally {
await payload.delete({ collection: "media", id, overrideAccess: true });
}
},
TIMEOUT,
);
it(
"skips deleted media and malformed pointers instead of rendering dead chips",
async () => {
const doomed = await createMedia("b2-int-doomed.txt");
await payload.delete({ collection: "media", id: doomed, overrideAccess: true });
const resolved = await resolveAttachments(payload, [
{ mediaId: doomed },
{ mediaId: 0 },
{ mediaId: "not-a-number" },
{ mediaId: -3 },
]);
expect(resolved).toEqual([]);
},
TIMEOUT,
);
});