Compare commits
4 commits
d21b36612f
...
4c2fc86ecb
| Author | SHA1 | Date | |
|---|---|---|---|
| 4c2fc86ecb | |||
| ac6415d034 | |||
| 2a3ad57bce | |||
| 76ca0e1d72 |
31 changed files with 77875 additions and 15 deletions
|
|
@ -56,6 +56,8 @@ Known pre-existing errors (not yours, don't widen scope to fix them): `src/colle
|
|||
- If the user says **no**, do **not** start a dev server and do **not** attempt to verify via E2E or Playwright — the user will run the app and test themselves, then report back.
|
||||
- Stale dev processes: killing the process is not always enough; remove `.next/dev/devserver.lock` before restarting.
|
||||
- For browser/UI verification, make a reasonable attempt with Playwright. If the browser tooling is unavailable or repeatedly unreliable, stop rather than spending excessive effort on it and defer the manual UI check to the user.
|
||||
- **Browser tool tab hygiene (OpenChamber)**: when driving the in-app browser, reuse a SINGLE tab. Call `browser.open` once to obtain a `tabId`, then pass that same `tabId` to every subsequent `browser.open` / `browser.snapshot` / `browser.click` / `browser.type` / `browser.capture` / `browser.inspect` call. Calling `browser.open` without a `tabId` opens a NEW tab every time and litters the panel; the tool has no close-tab action, so minimize new tabs by reusing one (re-read the tab list from a snapshot when a `tabId` goes stale, and reuse the matching existing tab rather than opening another).
|
||||
- **Capture verification (OpenChamber)**: `browser.capture` returning `ok` only means a file was written, NOT that the page looks right. `read` the captured image and confirm it shows your change before reporting success. Next dev error overlays persist after the code is fixed (the devtools badge reads "stale"): reload the page, re-capture, and inspect again before concluding anything. After swapping a symbol (e.g. a lucide icon import), grep the file for the old name to catch missed usages like JSX elements.
|
||||
|
||||
## Agent debugging SOP (read before fixing any bug)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "polaris-task-force",
|
||||
"version": "0.4.1",
|
||||
"version": "0.5.0",
|
||||
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
|
|
|||
311
src/app/(frontend)/personnel/contacts/[id]/actions.ts
Normal file
311
src/app/(frontend)/personnel/contacts/[id]/actions.ts
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
"use server";
|
||||
|
||||
import config from "@payload-config";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { getPayload } from "payload";
|
||||
import type { User } from "@/payload-types";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import { notifyUser } from "@/lib/notifications";
|
||||
import type {
|
||||
DialogueCondition,
|
||||
DialogueFlagOp,
|
||||
FlowData,
|
||||
NpcDialogueEffect,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
|
||||
interface ActionResult<T = undefined> {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
data?: T;
|
||||
}
|
||||
|
||||
async function authenticate() {
|
||||
const payloadConfig = await config;
|
||||
const payload = await getPayload({ config: payloadConfig });
|
||||
const { headers } = await import("next/headers");
|
||||
const hdrs = await headers();
|
||||
const { user } = await payload.auth({
|
||||
headers: hdrs,
|
||||
canSetHeaders: false,
|
||||
});
|
||||
|
||||
if (!isPayloadUser(user)) {
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
|
||||
return { payload, user };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the effect configured on a dialogue `event` node and run it. The
|
||||
* node is looked up server-side from the stored flowchart, so the client can
|
||||
* only trigger effects an admin has authored for this conversation.
|
||||
*/
|
||||
export async function triggerNpcDialogueEvent(
|
||||
npcId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
||||
if (!flowData || !Array.isArray(flowData.nodes)) {
|
||||
return { success: false, error: "This contact has no conversation configured." };
|
||||
}
|
||||
|
||||
const node = flowData.nodes.find((n) => n.id === nodeId);
|
||||
if (!node || node.type !== "event" || !node.data.effect) {
|
||||
// Nothing to trigger (or the node isn't an event): treated as a no-op.
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
const effect: NpcDialogueEffect = node.data.effect;
|
||||
await runEffect(payload, user.id as number, npcId, effect);
|
||||
|
||||
return { success: true };
|
||||
} 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 };
|
||||
}
|
||||
}
|
||||
|
||||
async function runEffect(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
userId: number,
|
||||
npcId: number,
|
||||
effect: NpcDialogueEffect,
|
||||
): Promise<void> {
|
||||
switch (effect.type) {
|
||||
case "notify": {
|
||||
await notifyUser(payload, {
|
||||
userId,
|
||||
type: "npc:dialogue",
|
||||
title: effect.title ?? "Conversation",
|
||||
message: effect.message,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "emit": {
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: effect.message ?? "NPC dialogue event",
|
||||
actor: userId,
|
||||
targetCollection: "game-npcs",
|
||||
targetId: npcId,
|
||||
data: { effect: "emit" },
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "reward": {
|
||||
// LLM/reward seam intentionally left unconfigured (see Phase 5).
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: effect.message ?? "NPC dialogue reward (unconfigured)",
|
||||
actor: userId,
|
||||
targetCollection: "game-npcs",
|
||||
targetId: npcId,
|
||||
data: { effect: "reward", unconfigured: true },
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "flag": {
|
||||
const key = effect.flagKey?.trim();
|
||||
if (!key) break;
|
||||
const op: DialogueFlagOp = effect.flagOp ?? "set_true";
|
||||
const amount = effect.flagAmount ?? 0;
|
||||
await applyFlagEffect(payload, userId, key, op, amount);
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `Conversation set flag "${key}" (${op}).`,
|
||||
actor: userId,
|
||||
targetCollection: "game-npcs",
|
||||
targetId: npcId,
|
||||
data: { effect: "flag", key, op, amount },
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Effective value of a player flag: missing flags read false / 0. */
|
||||
async function readFlag(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
userId: number,
|
||||
key: string,
|
||||
): Promise<{ bool: boolean; num: number }> {
|
||||
const res = await payload.find({
|
||||
collection: "player-flags",
|
||||
where: {
|
||||
user: { equals: userId },
|
||||
key: { equals: key },
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const doc = res.docs[0];
|
||||
if (!doc) return { bool: false, num: 0 };
|
||||
if (doc.flagType === "number") {
|
||||
const num = doc.numberValue ?? 0;
|
||||
return { bool: num !== 0, num };
|
||||
}
|
||||
const bool = doc.boolValue === true;
|
||||
return { bool, num: bool ? 1 : 0 };
|
||||
}
|
||||
|
||||
/** Create-or-update a player flag according to the effect's write mode. */
|
||||
async function applyFlagEffect(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
userId: number,
|
||||
key: string,
|
||||
op: DialogueFlagOp,
|
||||
amount: number,
|
||||
): Promise<void> {
|
||||
const existing = await payload.find({
|
||||
collection: "player-flags",
|
||||
where: {
|
||||
user: { equals: userId },
|
||||
key: { equals: key },
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const doc = existing.docs[0];
|
||||
|
||||
if (op === "set_true" || op === "set_false") {
|
||||
const boolValue = op === "set_true";
|
||||
if (doc) {
|
||||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "boolean", boolValue },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "boolean", boolValue },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (op === "set_number") {
|
||||
if (doc) {
|
||||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "number", numberValue: amount },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "number", numberValue: amount },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// add: numeric flags accumulate; boolean flags convert (true = 1).
|
||||
const current = doc
|
||||
? doc.flagType === "number"
|
||||
? doc.numberValue ?? 0
|
||||
: doc.boolValue
|
||||
? 1
|
||||
: 0
|
||||
: 0;
|
||||
const numberValue = current + amount;
|
||||
if (doc) {
|
||||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "number", numberValue },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "number", numberValue },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a dialogue `condition` node against the reading user's live
|
||||
* web-app state (player flags). The node is looked up server-side from the
|
||||
* stored flowchart, so the client can only evaluate conditions an admin
|
||||
* authored for this conversation.
|
||||
*/
|
||||
export async function evaluateNpcDialogueCondition(
|
||||
npcId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult<boolean>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
||||
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
||||
if (!node || node.type !== "condition" || !node.data.condition) {
|
||||
// Not a condition node: nothing to branch on.
|
||||
return { success: true, data: false };
|
||||
}
|
||||
|
||||
const value = await evaluateCondition(payload, user.id as number, node.data.condition);
|
||||
return { success: true, data: value };
|
||||
} 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 };
|
||||
}
|
||||
}
|
||||
|
||||
async function evaluateCondition(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
userId: number,
|
||||
condition: DialogueCondition,
|
||||
): Promise<boolean> {
|
||||
const flag = await readFlag(payload, userId, condition.key);
|
||||
const amount = condition.amount ?? 0;
|
||||
switch (condition.op) {
|
||||
case "is_true":
|
||||
return flag.bool;
|
||||
case "is_false":
|
||||
return !flag.bool;
|
||||
case "gte":
|
||||
return flag.num >= amount;
|
||||
case "lte":
|
||||
return flag.num <= amount;
|
||||
case "gt":
|
||||
return flag.num > amount;
|
||||
case "lt":
|
||||
return flag.num < amount;
|
||||
case "eq":
|
||||
return flag.num === amount;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -3,7 +3,9 @@ import { getPayload } from "payload";
|
|||
import { notFound } from "next/navigation";
|
||||
import { headers as nextHeaders } from "next/headers";
|
||||
import type { GameNpc, MarketListing, NpcStaffing } from "@/payload-types";
|
||||
import type { FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
import { NpcProfile } from "@/components/frontend/personnel/NpcProfile";
|
||||
import { NpcConversation } from "@/components/frontend/personnel/NpcConversation";
|
||||
import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard";
|
||||
import { hasLogisticsQualification } from "@/utils/access-control/hasLogisticsQualification";
|
||||
import type { LaborClassificationOption, StructureStaffingOption } from "@/lib/base";
|
||||
|
|
@ -149,11 +151,17 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
});
|
||||
const listings = listingsRes.docs as unknown as MarketListing[];
|
||||
|
||||
const dialogue =
|
||||
npc.canMessage === true
|
||||
? await firstDialogue(payload, id)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="p-5">
|
||||
<div className="p-5 flex flex-col gap-6">
|
||||
<NpcProfile
|
||||
npc={npc}
|
||||
listings={listings}
|
||||
conversationSlot={<NpcConversation npc={npc} dialogue={dialogue} />}
|
||||
employmentSlot={
|
||||
<EmploymentCard
|
||||
employment={employment}
|
||||
|
|
@ -171,3 +179,17 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Fetches the single dialogue flowchart for an NPC, if one exists. */
|
||||
async function firstDialogue(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
npcId: number,
|
||||
) {
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
});
|
||||
return res.docs[0] as unknown as { id: number; flowData?: FlowData } | null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997e
|
|||
import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
|
||||
import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
|
||||
import { ComposeField as ComposeField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
|
||||
import { default as default_163cd5fa19b83af73532cccaf34704fb } from '@/components/admin/npc-dialogue/NpcDialogueEditor'
|
||||
import { default as default_513af5ed43d616d133e530d8c94232f8 } from '@/components/admin/groups/CollapsibleGroupField'
|
||||
import { default as default_d9c22b951ac6762f436db59b889da382 } from '@/components/admin/awards/CommendationColorField'
|
||||
import { default as default_c3ea68702b5e5f8f2f98055e01c43c8d } from '@/components/admin/awards/RibbonDesigner'
|
||||
|
|
@ -74,6 +75,7 @@ export const importMap = {
|
|||
"@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
|
||||
"@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
|
||||
"@ai-stack/payloadcms/client#ComposeField": ComposeField_4490b89d4413c1ffaecdacfe72efaf73,
|
||||
"@/components/admin/npc-dialogue/NpcDialogueEditor#default": default_163cd5fa19b83af73532cccaf34704fb,
|
||||
"@/components/admin/groups/CollapsibleGroupField#default": default_513af5ed43d616d133e530d8c94232f8,
|
||||
"@/components/admin/awards/CommendationColorField#default": default_d9c22b951ac6762f436db59b889da382,
|
||||
"@/components/admin/awards/RibbonDesigner#default": default_c3ea68702b5e5f8f2f98055e01c43c8d,
|
||||
|
|
|
|||
|
|
@ -43,6 +43,24 @@
|
|||
a { color: rgba(255, 255, 255, 0.35); }
|
||||
}
|
||||
|
||||
/* NPC dialogue canvas: the default 1px grey drag line vanishes on the dark
|
||||
canvas, so make the in-progress connection a bright cyan laser. */
|
||||
.npc-dialogue-flow {
|
||||
.react-flow__connection-path {
|
||||
stroke: #22d3ee;
|
||||
stroke-width: 2.5;
|
||||
stroke-dasharray: 6 4;
|
||||
filter: drop-shadow(0 0 4px rgba(34, 211, 238, 0.7));
|
||||
}
|
||||
|
||||
/* Make drop-target handles obvious on hover. */
|
||||
.react-flow__handle.connectionindicator:hover {
|
||||
background: #22d3ee;
|
||||
border-color: #22d3ee;
|
||||
box-shadow: 0 0 6px rgba(34, 211, 238, 0.9);
|
||||
}
|
||||
}
|
||||
|
||||
/* Tech Tree: dark thin scrollbars for the panel and its dropdowns. */
|
||||
.tech-tree-scroll {
|
||||
scrollbar-width: thin;
|
||||
|
|
|
|||
|
|
@ -119,5 +119,83 @@ export const GameNpcs: CollectionConfig = {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "activity",
|
||||
label: "Narrative Activity",
|
||||
type: "group",
|
||||
fields: [
|
||||
{
|
||||
name: "intervalMinutes",
|
||||
type: "number",
|
||||
min: 1,
|
||||
defaultValue: 30,
|
||||
admin: {
|
||||
description:
|
||||
"How often (in minutes) the current activity reshuffles automatically. Ignored while a forced activity is active.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "activityOptions",
|
||||
type: "array",
|
||||
admin: {
|
||||
description:
|
||||
"Possible activities this contact can be doing. 'Forced' activities stay active until turned off; otherwise the most likely option (by 'Chance') is picked on each interval.",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "label",
|
||||
type: "text",
|
||||
required: true,
|
||||
admin: {
|
||||
description: "What the contact is doing (e.g. 'Coordinating combat androids').",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "weight",
|
||||
type: "number",
|
||||
min: 1,
|
||||
defaultValue: 1,
|
||||
admin: {
|
||||
description: "Relative chance this activity is picked when reshuffling.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "forced",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"Keep this activity active until turned off (overrides the interval reshuffle).",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "level",
|
||||
type: "number",
|
||||
min: 1,
|
||||
admin: {
|
||||
description: "This contact's level. Shown on their profile alongside its description.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "levelDescription",
|
||||
type: "richText",
|
||||
admin: {
|
||||
description: "Capabilities / notes for this contact's level (e.g. a bullet list).",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "canMessage",
|
||||
label: "Messaging",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"Enable conversing with this contact on their profile page. Requires a configured NPC Dialogue flow.",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
|
|||
68
src/collections/game/NpcDialogues.ts
Normal file
68
src/collections/game/NpcDialogues.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
|
||||
export const NpcDialogues: CollectionConfig = {
|
||||
slug: "npc-dialogues",
|
||||
admin: {
|
||||
group: "Game",
|
||||
useAsTitle: "name",
|
||||
listSearchableFields: ["name"],
|
||||
defaultColumns: ["name", "npc"],
|
||||
pagination: { defaultLimit: 50 },
|
||||
},
|
||||
access: {
|
||||
read: requirePermission("npc-dialogues:read"),
|
||||
create: requirePermission("npc-dialogues:create"),
|
||||
update: requirePermission("npc-dialogues:update"),
|
||||
delete: requirePermission("npc-dialogues:delete"),
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "name",
|
||||
type: "text",
|
||||
required: true,
|
||||
admin: {
|
||||
description: "A short label for this conversation (e.g. 'Merchant greeting').",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "npc",
|
||||
type: "relationship",
|
||||
relationTo: "game-npcs",
|
||||
required: true,
|
||||
hasMany: false,
|
||||
admin: {
|
||||
description: "The contact this conversation belongs to.",
|
||||
},
|
||||
filterOptions: {
|
||||
canMessage: { equals: true },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "tabs",
|
||||
tabs: [
|
||||
{
|
||||
label: "Flow Editor",
|
||||
description:
|
||||
"Build the conversation: dialogue lines, branching choices, and trigger events. Mark one node as the start.",
|
||||
fields: [
|
||||
{
|
||||
name: "flowData",
|
||||
type: "json",
|
||||
required: true,
|
||||
defaultValue: () => ({
|
||||
nodes: [],
|
||||
edges: [],
|
||||
}),
|
||||
admin: {
|
||||
components: {
|
||||
Field: "@/components/admin/npc-dialogue/NpcDialogueEditor",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
74
src/collections/game/PlayerFlags.ts
Normal file
74
src/collections/game/PlayerFlags.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
|
||||
/**
|
||||
* Generic per-player flags: the lightweight state layer conversations branch
|
||||
* on. Event nodes write them (set / add), condition nodes read them. GMs can
|
||||
* also seed or correct them here in the admin panel.
|
||||
*/
|
||||
export const PlayerFlags: CollectionConfig = {
|
||||
slug: "player-flags",
|
||||
admin: {
|
||||
group: "Game",
|
||||
useAsTitle: "key",
|
||||
listSearchableFields: ["key"],
|
||||
defaultColumns: ["user", "key", "flagType"],
|
||||
pagination: { defaultLimit: 50 },
|
||||
},
|
||||
access: {
|
||||
read: requirePermission("player-flags:read"),
|
||||
create: requirePermission("player-flags:create"),
|
||||
update: requirePermission("player-flags:update"),
|
||||
delete: requirePermission("player-flags:delete"),
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "user",
|
||||
type: "relationship",
|
||||
relationTo: "users",
|
||||
required: true,
|
||||
admin: {
|
||||
description: "The player this flag belongs to.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "key",
|
||||
type: "text",
|
||||
required: true,
|
||||
admin: {
|
||||
description:
|
||||
"Stable key referenced by conversation nodes (e.g. 'met_informant', 'rep_merchants'). Lowercase with underscores.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "flagType",
|
||||
type: "select",
|
||||
required: true,
|
||||
defaultValue: "boolean",
|
||||
options: ["boolean", "number"],
|
||||
admin: {
|
||||
description: "Boolean flags read as true/false; numeric flags track statistics.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "boolValue",
|
||||
type: "checkbox",
|
||||
defaultValue: true,
|
||||
admin: {
|
||||
condition: (_data, blockData) => blockData?.flagType === "boolean",
|
||||
description: "A missing boolean flag counts as false.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "numberValue",
|
||||
type: "number",
|
||||
defaultValue: 0,
|
||||
admin: {
|
||||
condition: (_data, blockData) => blockData?.flagType === "number",
|
||||
description: "A missing numeric flag counts as 0.",
|
||||
},
|
||||
},
|
||||
],
|
||||
timestamps: true,
|
||||
indexes: [{ fields: ["user", "key"], unique: true }],
|
||||
};
|
||||
555
src/components/admin/npc-dialogue/NodeEditDialog.tsx
Normal file
555
src/components/admin/npc-dialogue/NodeEditDialog.tsx
Normal file
|
|
@ -0,0 +1,555 @@
|
|||
"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) });
|
||||
|
||||
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>
|
||||
<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-white/40">
|
||||
Checked against the player's flags. A missing flag counts as 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>
|
||||
);
|
||||
}
|
||||
361
src/components/admin/npc-dialogue/NpcDialogueEditor.tsx
Normal file
361
src/components/admin/npc-dialogue/NpcDialogueEditor.tsx
Normal file
|
|
@ -0,0 +1,361 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from "react";
|
||||
import {
|
||||
Background,
|
||||
type Connection,
|
||||
type Edge,
|
||||
type Node,
|
||||
ReactFlow,
|
||||
useNodesState,
|
||||
} from "@xyflow/react";
|
||||
import "@xyflow/react/dist/style.css";
|
||||
|
||||
import { useField } from "@payloadcms/ui";
|
||||
|
||||
import type {
|
||||
DialogueEdge,
|
||||
DialogueNode,
|
||||
DialogueNodeData,
|
||||
FlowData,
|
||||
NpcDialogueNodeType,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
import { deriveEdges, validateGraph } from "@/lib/npc-dialogue/dialogue";
|
||||
import { NpcDialogueNode } from "./NpcDialogueNode";
|
||||
import { NodeEditDialog } from "./NodeEditDialog";
|
||||
|
||||
const nodeTypes = {
|
||||
dialogue: NpcDialogueNode,
|
||||
choice: NpcDialogueNode,
|
||||
event: NpcDialogueNode,
|
||||
delay: NpcDialogueNode,
|
||||
condition: NpcDialogueNode,
|
||||
end: NpcDialogueNode,
|
||||
};
|
||||
|
||||
const defaultFlow: FlowData = { nodes: [], edges: [] };
|
||||
|
||||
type ContextMenu = { x: number; y: number; nodeId: string } | null;
|
||||
|
||||
const NODE_LABELS: Record<NpcDialogueNodeType, string> = {
|
||||
dialogue: "Dialogue",
|
||||
choice: "Choice",
|
||||
event: "Event",
|
||||
delay: "Delay",
|
||||
condition: "Condition",
|
||||
end: "End",
|
||||
};
|
||||
|
||||
const DEFAULT_DATA: Record<string, DialogueNodeData> = {
|
||||
dialogue: { speaker: "NPC", body: "" },
|
||||
choice: { choices: [] },
|
||||
event: { effect: { type: "notify", message: "" } },
|
||||
delay: { delaySeconds: 2 },
|
||||
condition: { condition: { kind: "flag", key: "", op: "is_true" } },
|
||||
end: {},
|
||||
};
|
||||
|
||||
export function NpcDialogueEditor() {
|
||||
const { value, setValue } = useField<FlowData>();
|
||||
|
||||
const initial: FlowData =
|
||||
value && typeof value === "object" && Array.isArray((value as FlowData).nodes)
|
||||
? (value as FlowData)
|
||||
: defaultFlow;
|
||||
|
||||
const [nodes, setNodes, onNodesChange] = useNodesState(initial.nodes as Node[]);
|
||||
const [editingNodeId, setEditingNodeId] = useState<string | null>(null);
|
||||
const [contextMenu, setContextMenu] = useState<ContextMenu>(null);
|
||||
|
||||
const lastSerialized = useRef<string>("");
|
||||
const menuRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
// Edges are a derived projection of the node data, never edited directly.
|
||||
const syncedEdges = useMemo<Edge[]>(
|
||||
() => deriveEdges(nodes as DialogueNode[]),
|
||||
[nodes],
|
||||
);
|
||||
|
||||
const serialize = useCallback((nds: Node[]) => {
|
||||
const payload: FlowData = {
|
||||
nodes: nds as DialogueNode[],
|
||||
edges: deriveEdges(nds as DialogueNode[]),
|
||||
};
|
||||
const serialized = JSON.stringify(payload);
|
||||
if (serialized !== lastSerialized.current) {
|
||||
lastSerialized.current = serialized;
|
||||
setValue(payload);
|
||||
}
|
||||
}, [setValue]);
|
||||
|
||||
const addNode = useCallback(
|
||||
(type: NpcDialogueNodeType) => {
|
||||
const count = nodes.length;
|
||||
const node: DialogueNode = {
|
||||
id: crypto.randomUUID(),
|
||||
type,
|
||||
position: {
|
||||
x: 120 + (count % 4) * 240,
|
||||
y: 80 + Math.floor(count / 4) * 140,
|
||||
},
|
||||
data: { ...DEFAULT_DATA[type] },
|
||||
};
|
||||
const next = [...nodes, node];
|
||||
setNodes(next);
|
||||
serialize(next);
|
||||
setEditingNodeId(node.id);
|
||||
},
|
||||
[nodes, setNodes, serialize],
|
||||
);
|
||||
|
||||
const handleNodeSave = useCallback(
|
||||
(nodeId: string, data: DialogueNodeData) => {
|
||||
const next = nodes.map((n) => (n.id === nodeId ? { ...n, data } : n));
|
||||
setNodes(next);
|
||||
serialize(next);
|
||||
setEditingNodeId(null);
|
||||
},
|
||||
[nodes, setNodes, serialize],
|
||||
);
|
||||
|
||||
const deleteNode = useCallback(
|
||||
(nodeId: string) => {
|
||||
const next = (nodes as DialogueNode[])
|
||||
.filter((n) => n.id !== nodeId)
|
||||
.map((n) => ({
|
||||
...n,
|
||||
data: {
|
||||
...n.data,
|
||||
next: n.data.next && n.data.next.target !== nodeId ? n.data.next : undefined,
|
||||
choices: (n.data.choices ?? []).filter((c) => c.target !== nodeId),
|
||||
trueTarget: n.data.trueTarget !== nodeId ? n.data.trueTarget : undefined,
|
||||
falseTarget: n.data.falseTarget !== nodeId ? n.data.falseTarget : undefined,
|
||||
},
|
||||
}));
|
||||
setNodes(next);
|
||||
serialize(next);
|
||||
setContextMenu(null);
|
||||
if (editingNodeId === nodeId) setEditingNodeId(null);
|
||||
},
|
||||
[nodes, setNodes, serialize, editingNodeId],
|
||||
);
|
||||
|
||||
const onNodeContextMenu = useCallback(
|
||||
(e: ReactMouseEvent, node: Node) => {
|
||||
e.preventDefault();
|
||||
setContextMenu({ x: e.clientX, y: e.clientY, nodeId: node.id });
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Drag-to-connect writes into the node data (the graph's source of truth);
|
||||
// edges stay a derived projection.
|
||||
const applyConnection = useCallback(
|
||||
(sourceId: string, targetId: string) => {
|
||||
if (sourceId === targetId) return;
|
||||
const all = nodes as DialogueNode[];
|
||||
const source = all.find((n) => n.id === sourceId);
|
||||
const target = all.find((n) => n.id === targetId);
|
||||
if (!source || !target) return;
|
||||
if (source.type === "end" || target.data.isStart) return;
|
||||
const next = all.map((n) => {
|
||||
if (n.id !== sourceId) return n;
|
||||
if (n.type === "choice") {
|
||||
return {
|
||||
...n,
|
||||
data: { ...n.data, choices: [...(n.data.choices ?? []), { label: "", target: targetId }] },
|
||||
};
|
||||
}
|
||||
if (n.type === "condition") {
|
||||
// First connection wires the true branch, the second the false one.
|
||||
if (n.data.trueTarget && n.data.falseTarget) return n;
|
||||
return {
|
||||
...n,
|
||||
data: {
|
||||
...n.data,
|
||||
trueTarget: n.data.trueTarget ?? targetId,
|
||||
falseTarget: n.data.trueTarget ? n.data.falseTarget : targetId,
|
||||
},
|
||||
};
|
||||
}
|
||||
return { ...n, data: { ...n.data, next: { target: targetId } } };
|
||||
});
|
||||
setNodes(next);
|
||||
serialize(next);
|
||||
// A fresh choice has no button text yet: pop the editor so it can be
|
||||
// typed immediately (validateGraph flags empty labels).
|
||||
if (source.type === "choice") setEditingNodeId(sourceId);
|
||||
},
|
||||
[nodes, setNodes, serialize],
|
||||
);
|
||||
|
||||
const isValidConnection = useCallback(
|
||||
(c: Connection | Edge) => {
|
||||
if (!c.source || !c.target || c.source === c.target) return false;
|
||||
const target = (nodes as DialogueNode[]).find((n) => n.id === c.target);
|
||||
return !!target && !target.data.isStart;
|
||||
},
|
||||
[nodes],
|
||||
);
|
||||
|
||||
const onPaneClick = useCallback(() => setContextMenu(null), []);
|
||||
|
||||
const validation = useMemo(() => validateGraph(nodes as DialogueNode[]), [nodes]);
|
||||
|
||||
// Close the context menu on escape / pointer outside.
|
||||
const closeMenu = useCallback(() => setContextMenu(null), []);
|
||||
useEffect(() => {
|
||||
if (!contextMenu) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") closeMenu();
|
||||
};
|
||||
// Ignore pointerdowns inside the menu itself: pointerdown fires before
|
||||
// click, so closing here would unmount the menu before its buttons can
|
||||
// ever receive the click.
|
||||
const onPtr = (e: PointerEvent) => {
|
||||
if (menuRef.current?.contains(e.target as globalThis.Node)) return;
|
||||
closeMenu();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
document.addEventListener("pointerdown", onPtr);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey);
|
||||
document.removeEventListener("pointerdown", onPtr);
|
||||
};
|
||||
}, [contextMenu, closeMenu]);
|
||||
|
||||
const buttonClass =
|
||||
"px-2 py-1 text-[10px] font-medium rounded border transition-colors cursor-pointer";
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<div className="flex flex-wrap items-center gap-1 px-2 py-1.5 bg-zinc-900 rounded-t-md border border-zinc-700">
|
||||
<span className="text-[9px] uppercase tracking-wider text-zinc-500 font-semibold mr-1">
|
||||
Nodes
|
||||
</span>
|
||||
<button
|
||||
className={`${buttonClass} bg-blue-950 border-blue-700 text-blue-200 hover:bg-blue-900`}
|
||||
onClick={() => addNode("dialogue")}
|
||||
>
|
||||
{NODE_LABELS.dialogue}
|
||||
</button>
|
||||
<button
|
||||
className={`${buttonClass} bg-amber-950 border-amber-700 text-amber-200 hover:bg-amber-900`}
|
||||
onClick={() => addNode("choice")}
|
||||
>
|
||||
{NODE_LABELS.choice}
|
||||
</button>
|
||||
<button
|
||||
className={`${buttonClass} bg-emerald-950 border-emerald-700 text-emerald-200 hover:bg-emerald-900`}
|
||||
onClick={() => addNode("event")}
|
||||
>
|
||||
{NODE_LABELS.event}
|
||||
</button>
|
||||
<button
|
||||
className={`${buttonClass} bg-violet-950 border-violet-700 text-violet-200 hover:bg-violet-900`}
|
||||
onClick={() => addNode("delay")}
|
||||
>
|
||||
{NODE_LABELS.delay}
|
||||
</button>
|
||||
<button
|
||||
className={`${buttonClass} bg-sky-950 border-sky-700 text-sky-200 hover:bg-sky-900`}
|
||||
onClick={() => addNode("condition")}
|
||||
>
|
||||
{NODE_LABELS.condition}
|
||||
</button>
|
||||
<button
|
||||
className={`${buttonClass} bg-slate-950 border-slate-700 text-slate-200 hover:bg-slate-900`}
|
||||
onClick={() => addNode("end")}
|
||||
>
|
||||
{NODE_LABELS.end}
|
||||
</button>
|
||||
|
||||
<span className="ml-auto text-[10px] text-zinc-500">
|
||||
{nodes.length} node{nodes.length !== 1 ? "s" : ""}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{!validation.valid && (
|
||||
<div className="px-2 py-1 bg-red-950/60 border-b border-red-900/50 text-xs text-red-300">
|
||||
{validation.errors.slice(0, 3).join(" ")}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="npc-dialogue-flow h-96 border border-zinc-700 rounded-b-md overflow-hidden bg-zinc-950">
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={syncedEdges}
|
||||
onNodesChange={onNodesChange}
|
||||
onConnect={(c: Connection) => {
|
||||
if (c.source && c.target) applyConnection(c.source, c.target);
|
||||
}}
|
||||
onConnectEnd={(event, connectionState) => {
|
||||
// React Flow only resolves drops onto a handle. If the pointer
|
||||
// was released over a node card instead, resolve that card
|
||||
// ourselves so "drag onto the node" works as people expect.
|
||||
if (!("fromNode" in connectionState)) return;
|
||||
if (connectionState.toHandle) return; // dropped on a handle: onConnect leads
|
||||
const sourceId = connectionState.fromNode?.id;
|
||||
if (!sourceId) return;
|
||||
const point = event as MouseEvent;
|
||||
const element = document.elementFromPoint(point.clientX ?? 0, point.clientY ?? 0);
|
||||
const nodeElement = element?.closest?.(".react-flow__node") as HTMLElement | null;
|
||||
const targetId = nodeElement?.getAttribute("data-id");
|
||||
if (!targetId || targetId === sourceId) return;
|
||||
applyConnection(sourceId, targetId);
|
||||
}}
|
||||
isValidConnection={isValidConnection}
|
||||
onNodeClick={(_e, node) => setEditingNodeId(node.id)}
|
||||
onNodeContextMenu={onNodeContextMenu}
|
||||
onPaneClick={onPaneClick}
|
||||
nodeTypes={nodeTypes}
|
||||
fitView
|
||||
colorMode="dark"
|
||||
defaultEdgeOptions={{ animated: true }}
|
||||
proOptions={{ hideAttribution: true }}
|
||||
>
|
||||
<Background color="#27272a" gap={20} />
|
||||
{nodes.length === 0 && (
|
||||
<div className="absolute inset-0 pointer-events-none flex items-center justify-center text-zinc-600 text-sm">
|
||||
Add a node to start building the conversation.
|
||||
</div>
|
||||
)}
|
||||
</ReactFlow>
|
||||
</div>
|
||||
|
||||
<p className="text-[10px] text-zinc-500">
|
||||
Click a node to edit. Right-click to delete. Drag from a node's right handle onto
|
||||
another node to connect them (a choice node gains a new choice; dialogue and event nodes
|
||||
re-point their continuation).
|
||||
</p>
|
||||
|
||||
{contextMenu && (
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="fixed z-50 min-w-[7rem] overflow-hidden rounded-md border border-zinc-700 bg-zinc-900 p-1 shadow-lg"
|
||||
style={{ left: contextMenu.x, top: contextMenu.y }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => deleteNode(contextMenu.nodeId)}
|
||||
className="flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm text-red-400 outline-none select-none hover:bg-red-950/40"
|
||||
>
|
||||
Delete node
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<NodeEditDialog
|
||||
node={(nodes as DialogueNode[]).find((n) => n.id === editingNodeId) ?? null}
|
||||
allNodes={nodes as DialogueNode[]}
|
||||
open={editingNodeId !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setEditingNodeId(null);
|
||||
}}
|
||||
onSave={handleNodeSave}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default NpcDialogueEditor;
|
||||
184
src/components/admin/npc-dialogue/NpcDialogueNode.tsx
Normal file
184
src/components/admin/npc-dialogue/NpcDialogueNode.tsx
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
"use client";
|
||||
|
||||
import { Handle, NodeProps, Position } from "@xyflow/react";
|
||||
import {
|
||||
FileTextIcon,
|
||||
GitBranchIcon,
|
||||
GitCompareIcon,
|
||||
SparklesIcon,
|
||||
CircleStopIcon,
|
||||
TimerIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
import type { DialogueNodeData, NpcDialogueNodeType } from "@/lib/npc-dialogue/dialogue";
|
||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { DIALOGUE_NODES } from "./types";
|
||||
|
||||
const position: Position = Position.Right;
|
||||
const inputPosition: Position = Position.Left;
|
||||
|
||||
/** Single reusable canvas node for every dialogue node type. */
|
||||
export function NpcDialogueNode({ data, type }: NodeProps) {
|
||||
const d = data as DialogueNodeData;
|
||||
const nodeType = type as NpcDialogueNodeType;
|
||||
const meta = DIALOGUE_NODES[nodeType];
|
||||
// Only end nodes are truly terminal. A choice node keeps its source handle
|
||||
// even with zero choices, otherwise there would be no way to drag the
|
||||
// first choice out of it.
|
||||
const terminal = nodeType === "end";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`w-[20rem] max-w-[20rem] rounded border bg-zinc-900 shadow-lg ${meta.border}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 border-b border-white/10 px-3 py-1.5">
|
||||
<NodeIcon type={nodeType} />
|
||||
<span className="font-mono text-[10px] uppercase tracking-widest text-white/70">
|
||||
{meta.label}
|
||||
</span>
|
||||
{d.isStart && (
|
||||
<span className="ml-auto font-mono text-[8px] uppercase tracking-widest text-emerald-400">
|
||||
start
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="max-h-32 min-h-20 overflow-y-auto px-3 py-2">
|
||||
{nodeType === "dialogue" && (
|
||||
<div>
|
||||
{d.speaker && (
|
||||
<p className="text-[10px] uppercase tracking-wider text-white/40">{d.speaker}</p>
|
||||
)}
|
||||
<p className="line-clamp-3 text-sm text-white/90">
|
||||
{d.body ? (
|
||||
<DialogueText text={d.body} />
|
||||
) : (
|
||||
<span className="italic text-white/30">Empty line</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{nodeType === "choice" && (
|
||||
<div>
|
||||
{d.leadIn && (
|
||||
<p className="mb-1.5 line-clamp-2 text-sm text-white/70">
|
||||
<DialogueText text={d.leadIn} />
|
||||
</p>
|
||||
)}
|
||||
<ul className="flex flex-col gap-1">
|
||||
{(d.choices ?? []).map((choice, index) => (
|
||||
<li key={index} className="flex items-center gap-1.5 text-xs text-white/70">
|
||||
<span className="size-3 shrink-0 rounded border border-amber-500/50" />
|
||||
<span className="truncate">{choice.label || "Unlabeled choice"}</span>
|
||||
{choice.once && (
|
||||
<span className="shrink-0 rounded-sm border border-amber-500/40 bg-amber-500/10 px-1 font-mono text-[8px] uppercase tracking-wider text-amber-300">
|
||||
once
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
{(d.choices?.length ?? 0) === 0 && (
|
||||
<li className="text-white/30">Add a choice below.</li>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{nodeType === "event" && (
|
||||
<div className="text-sm">
|
||||
{d.body && (
|
||||
<p className="line-clamp-3 italic text-amber-100/80">
|
||||
<DialogueText text={d.body} />
|
||||
</p>
|
||||
)}
|
||||
{d.effect ? (
|
||||
<span className={d.body ? "text-xs text-white/50" : "text-white/80"}>
|
||||
{d.effect.type === "notify"
|
||||
? "Notify user"
|
||||
: d.effect.type === "emit"
|
||||
? "Log game event"
|
||||
: d.effect.type === "flag"
|
||||
? `Set flag "${d.effect.flagKey || "?"}"`
|
||||
: "Reward (unconfigured)"}
|
||||
{d.effect.message ? `: "${d.effect.message}"` : ""}
|
||||
</span>
|
||||
) : (
|
||||
!d.body && (
|
||||
<span className="italic text-white/30">
|
||||
No narration or effect. Leave the effect on “None” for pure narration.
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{nodeType === "delay" && (
|
||||
<div className="text-sm text-white/70">
|
||||
{d.delaySeconds ? (
|
||||
<span>
|
||||
Pause <span className="font-mono text-violet-300">{d.delaySeconds}s</span> before
|
||||
continuing.
|
||||
</span>
|
||||
) : (
|
||||
<span className="italic text-white/30">Set a pause length.</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{nodeType === "condition" && (
|
||||
<div className="text-sm text-white/70">
|
||||
{d.condition?.key ? (
|
||||
<span>
|
||||
Flag <span className="font-mono text-sky-300">{d.condition.key}</span>{" "}
|
||||
<span className="text-white/50">{d.condition.op}</span>
|
||||
{typeof d.condition.amount === "number" && (
|
||||
<span className="font-mono text-sky-300"> {d.condition.amount}</span>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="italic text-white/30">Set a flag key to branch on.</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{nodeType === "end" && (
|
||||
<div className="text-sm text-white/70">
|
||||
{d.closing ? (
|
||||
<span className="line-clamp-3">
|
||||
<DialogueText text={d.closing} />
|
||||
</span>
|
||||
) : (
|
||||
<span className="italic text-white/30">No closing line</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!terminal && (
|
||||
<Handle type="source" position={position} className="!size-2 !bg-white/60" />
|
||||
)}
|
||||
{!d.isStart && (
|
||||
<Handle type="target" position={inputPosition} className="!size-2 !bg-white/60" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NodeIcon({ type }: { type: NpcDialogueNodeType }) {
|
||||
const className = "size-3.5 text-white/50";
|
||||
switch (type) {
|
||||
case "choice":
|
||||
return <GitBranchIcon className={className} />;
|
||||
case "event":
|
||||
return <SparklesIcon className={className} />;
|
||||
case "delay":
|
||||
return <TimerIcon className={className} />;
|
||||
case "condition":
|
||||
return <GitCompareIcon className={className} />;
|
||||
case "end":
|
||||
return <CircleStopIcon className={className} />;
|
||||
default:
|
||||
return <FileTextIcon className={className} />;
|
||||
}
|
||||
}
|
||||
57
src/components/admin/npc-dialogue/types.ts
Normal file
57
src/components/admin/npc-dialogue/types.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import type { NpcDialogueNodeType } from "@/lib/npc-dialogue/dialogue";
|
||||
|
||||
export interface NodeMeta {
|
||||
type: NpcDialogueNodeType;
|
||||
label: string;
|
||||
/** Tailwind border accent class. */
|
||||
border: string;
|
||||
/** Canvas / minimap node color. */
|
||||
node: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
/** Authoring metadata for each dialogue node type. */
|
||||
export const DIALOGUE_NODES: Record<NpcDialogueNodeType, NodeMeta> = {
|
||||
dialogue: {
|
||||
type: "dialogue",
|
||||
label: "Dialogue",
|
||||
border: "border-blue-500/60",
|
||||
node: "#3b82f6",
|
||||
description: "The NPC speaks a line.",
|
||||
},
|
||||
choice: {
|
||||
type: "choice",
|
||||
label: "Choice",
|
||||
border: "border-amber-500/60",
|
||||
node: "#d97706",
|
||||
description: "Player branches the conversation.",
|
||||
},
|
||||
event: {
|
||||
type: "event",
|
||||
label: "Event",
|
||||
border: "border-emerald-500/60",
|
||||
node: "#10b981",
|
||||
description: "Trigger a notification or game event.",
|
||||
},
|
||||
delay: {
|
||||
type: "delay",
|
||||
label: "Delay",
|
||||
border: "border-violet-500/60",
|
||||
node: "#8b5cf6",
|
||||
description: "Pause the conversation for a beat.",
|
||||
},
|
||||
condition: {
|
||||
type: "condition",
|
||||
label: "Condition",
|
||||
border: "border-sky-500/60",
|
||||
node: "#0ea5e9",
|
||||
description: "Branch on live web-app state (player flags).",
|
||||
},
|
||||
end: {
|
||||
type: "end",
|
||||
label: "End",
|
||||
border: "border-slate-500/60",
|
||||
node: "#64748b",
|
||||
description: "End the conversation.",
|
||||
},
|
||||
};
|
||||
42
src/components/frontend/personnel/NpcActivityLine.tsx
Normal file
42
src/components/frontend/personnel/NpcActivityLine.tsx
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { DOSSIER } from "@/components/frontend/operations";
|
||||
import {
|
||||
formatActivityLine,
|
||||
resolveCurrentActivity,
|
||||
type NpcActivityOption,
|
||||
} from "@/lib/npcs/activity";
|
||||
|
||||
interface NpcActivityLineProps {
|
||||
/** How often (minutes) the activity reshuffles when nothing is forced. */
|
||||
readonly intervalMinutes: number;
|
||||
/** The contact's possible activities. */
|
||||
readonly activityOptions: NpcActivityOption[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the contact's "current activity" and reshuffles it on the configured
|
||||
* interval. A forced activity stays put until the flag is turned off.
|
||||
*/
|
||||
export function NpcActivityLine({ intervalMinutes, activityOptions }: NpcActivityLineProps) {
|
||||
const [tick, setTick] = useState(0);
|
||||
const reshuffle = intervalMinutes > 0 && activityOptions.length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (!reshuffle) return;
|
||||
const interval = setInterval(() => setTick((prev) => prev + 1), intervalMinutes * 60_000);
|
||||
return () => clearInterval(interval);
|
||||
}, [intervalMinutes, reshuffle]);
|
||||
|
||||
const activity = resolveCurrentActivity(activityOptions, reshuffle ? `tick-${tick}` : undefined);
|
||||
|
||||
return (
|
||||
// leading-none keeps the label and chip off the inherited (tall) line-height,
|
||||
// so the chip matches the NpcStatusChips tags below it.
|
||||
<div className="flex items-center gap-3 leading-none">
|
||||
<span className={DOSSIER.readoutLabel}>Activity</span>
|
||||
<span className={DOSSIER.chip}>{formatActivityLine(activity)}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -61,7 +61,7 @@ export function NpcCard({ npc }: NpcCardProps) {
|
|||
/>
|
||||
|
||||
<div className="relative z-10 flex h-full items-center justify-center px-3 text-center">
|
||||
<div className="flex max-w-full flex-col items-center gap-1.5">
|
||||
<div className="flex max-w-full flex-col items-center gap-1">
|
||||
<h2
|
||||
data-text={npc.name}
|
||||
className="glitch-hover text-balance text-center text-sm font-bold leading-tight text-white drop-shadow-lg"
|
||||
|
|
@ -80,7 +80,7 @@ export function NpcCard({ npc }: NpcCardProps) {
|
|||
<p className="glitch-soft line-clamp-1 max-w-full text-pretty text-[10px] text-white/60 drop-shadow">
|
||||
{npc.occupation ?? "Occupation not recorded"}
|
||||
</p>
|
||||
<NpcStatusChips npc={npc} size="compact" className="mt-0.5 justify-center" />
|
||||
<NpcStatusChips npc={npc} size="compact" className="justify-center" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
388
src/components/frontend/personnel/NpcConversation.tsx
Normal file
388
src/components/frontend/personnel/NpcConversation.tsx
Normal file
|
|
@ -0,0 +1,388 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { MessageCircleIcon, XIcon } from "lucide-react";
|
||||
|
||||
import type { GameNpc } from "@/payload-types";
|
||||
import type { DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
|
||||
import { DOSSIER } from "@/components/frontend/operations";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
evaluateNpcDialogueCondition,
|
||||
triggerNpcDialogueEvent,
|
||||
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
||||
|
||||
interface NpcConversationProps {
|
||||
readonly npc: GameNpc;
|
||||
readonly dialogue: { id: number; flowData?: FlowData } | null | undefined;
|
||||
}
|
||||
|
||||
interface ResolvedFlow {
|
||||
nodes: DialogueNode[];
|
||||
startId: string | null;
|
||||
}
|
||||
|
||||
type LogEntry =
|
||||
| { kind: "node"; id: string; node: DialogueNode; triggered: boolean }
|
||||
| { kind: "player"; id: string; text: string };
|
||||
|
||||
/** Resolves the authored flowchart into a shape the runtime can walk. */
|
||||
function resolveFlow(dialogue: NpcConversationProps["dialogue"]): ResolvedFlow | null {
|
||||
if (!dialogue?.flowData || !Array.isArray(dialogue.flowData.nodes)) return null;
|
||||
const nodes = dialogue.flowData.nodes as DialogueNode[];
|
||||
return { nodes, startId: findStartNode(nodes)?.id ?? null };
|
||||
}
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/** Text length drives how long the NPC "types"; jitter keeps it human. */
|
||||
function typingDelayMs(text: string): number {
|
||||
return Math.min(2600, 450 + text.length * 24) * (0.85 + Math.random() * 0.3);
|
||||
}
|
||||
|
||||
function nodeText(node: DialogueNode): string {
|
||||
return node.data.body || node.data.effect?.message || node.data.closing || node.data.leadIn || "";
|
||||
}
|
||||
|
||||
export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
||||
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [log, setLog] = useState<LogEntry[]>([]);
|
||||
/** Speaker label while the NPC types; "" for speaker-less narration. */
|
||||
const [typing, setTyping] = useState<string | null>(null);
|
||||
/** True while the player's chosen line is "typing" into the log. */
|
||||
const [playerTyping, setPlayerTyping] = useState(false);
|
||||
/** `${nodeId}:${index}` keys of one-time choices picked in THIS conversation.
|
||||
* Purely local: it resets on every `begin()`, so a choice hidden here
|
||||
* reappears the next time the conversation is opened. Persist across
|
||||
* conversations with a condition + player flag instead. */
|
||||
const [takenChoices, setTakenChoices] = useState<Set<string>>(new Set());
|
||||
const seq = useRef(0);
|
||||
const sessionRef = useRef(0);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const nextId = () => `entry-${seq.current++}`;
|
||||
|
||||
// Invalidate pending typing timers when the component unmounts.
|
||||
useEffect(
|
||||
() => () => {
|
||||
sessionRef.current += 1;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Trigger every arrived event node's effect exactly once, in order (the
|
||||
// opening cascade can land on several events at once).
|
||||
useEffect(() => {
|
||||
const pending = log.find(
|
||||
(entry) =>
|
||||
entry.kind === "node" &&
|
||||
entry.node.type === "event" &&
|
||||
!!entry.node.data.effect &&
|
||||
!entry.triggered,
|
||||
);
|
||||
if (!pending || pending.kind !== "node") return;
|
||||
void triggerNpcDialogueEvent(Number(npc.id), pending.node.id).catch(() => undefined);
|
||||
setLog((prev) =>
|
||||
prev.map((entry) => (entry.id === pending.id ? { ...entry, triggered: true } : entry)),
|
||||
);
|
||||
}, [log, npc.id]);
|
||||
|
||||
// Keep the newest line in view.
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
}, [log, typing, playerTyping, open]);
|
||||
|
||||
if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null;
|
||||
|
||||
/** Appends a node to the log after a length-based "typing" delay. */
|
||||
const typeIn = async (node: DialogueNode, token: number) => {
|
||||
setTyping(node.type === "event" ? "" : node.data.speaker?.trim() || npc.name);
|
||||
await sleep(typingDelayMs(nodeText(node)));
|
||||
if (sessionRef.current !== token) return;
|
||||
setTyping(null);
|
||||
setLog((prev) => [...prev, { kind: "node", id: nextId(), node, triggered: false }]);
|
||||
};
|
||||
|
||||
// Opening the conversation walks the start node and auto-advances through
|
||||
// linear dialogue/event nodes, so the player lands on the first interactive
|
||||
// node (a choice, an end, or a dead end) without clicking Continue. Each
|
||||
// line arrives after its own typing delay.
|
||||
const begin = () => {
|
||||
const token = ++sessionRef.current;
|
||||
setLog([]);
|
||||
setTyping(null);
|
||||
setPlayerTyping(false);
|
||||
setTakenChoices(new Set());
|
||||
setOpen(true);
|
||||
if (!flow.startId) return;
|
||||
void (async () => {
|
||||
const start = flow.nodes.find((n) => n.id === flow.startId) ?? null;
|
||||
if (start) await cascadeFrom(start, token);
|
||||
})();
|
||||
};
|
||||
|
||||
/** Types `start`, then auto-advances through linear dialogue/event/delay/
|
||||
* condition nodes so the player always lands on the next interactive node
|
||||
* (a choice or an end). Delay nodes pause the conversation; condition nodes
|
||||
* branch on the player's flags, evaluated server-side. Neither is logged. */
|
||||
const cascadeFrom = async (start: DialogueNode, token: number) => {
|
||||
let current: DialogueNode | null = start;
|
||||
const seen = new Set<string>();
|
||||
while (current && !seen.has(current.id) && sessionRef.current === token) {
|
||||
seen.add(current.id);
|
||||
|
||||
if (current.type === "delay") {
|
||||
const seconds = Math.min(30, Math.max(0.5, current.data.delaySeconds ?? 2));
|
||||
setTyping("");
|
||||
await sleep(seconds * 1000);
|
||||
if (sessionRef.current !== token) return;
|
||||
setTyping(null);
|
||||
const target: string | undefined = current.data.next?.target;
|
||||
current = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current.type === "condition") {
|
||||
const result = await evaluateNpcDialogueCondition(Number(npc.id), current.id);
|
||||
if (sessionRef.current !== token) return;
|
||||
const branch =
|
||||
result.success && result.data ? current.data.trueTarget : current.data.falseTarget;
|
||||
current = branch ? (flow.nodes.find((n) => n.id === branch) ?? null) : null;
|
||||
continue;
|
||||
}
|
||||
|
||||
await typeIn(current, token);
|
||||
if (sessionRef.current !== token) return;
|
||||
if (current.type === "dialogue" || current.type === "event") {
|
||||
const target: string | undefined = current.data.next?.target;
|
||||
current = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null;
|
||||
} else {
|
||||
current = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
sessionRef.current += 1;
|
||||
setTyping(null);
|
||||
setPlayerTyping(false);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const lastNode = [...log].reverse().find((entry) => entry.kind === "node");
|
||||
|
||||
// The player's line types out (shorter than NPC pacing), lands, and then
|
||||
// the NPC starts typing its reply.
|
||||
const pick = (hop: DialogueNext, choiceIndex: number) => {
|
||||
const token = sessionRef.current;
|
||||
const text = hop.label || "…";
|
||||
if (hop.once && lastNode && lastNode.kind === "node") {
|
||||
const key = `${lastNode.node.id}:${choiceIndex}`;
|
||||
setTakenChoices((prev) => (prev.has(key) ? prev : new Set(prev).add(key)));
|
||||
}
|
||||
void (async () => {
|
||||
setPlayerTyping(true);
|
||||
await sleep(Math.min(1100, 300 + text.length * 16) * (0.85 + Math.random() * 0.3));
|
||||
if (sessionRef.current !== token) return;
|
||||
setPlayerTyping(false);
|
||||
setLog((prev) => [...prev, { kind: "player", id: nextId(), text }]);
|
||||
const target = flow.nodes.find((n) => n.id === hop.target);
|
||||
if (target) await cascadeFrom(target, token);
|
||||
})();
|
||||
};
|
||||
|
||||
// The choices offered by the node the log currently rests on. One-time
|
||||
// choices the player already took are hidden; if that empties the list the
|
||||
// footer falls back to the End conversation button so nobody gets stuck.
|
||||
const choiceNode =
|
||||
lastNode && lastNode.kind === "node" && lastNode.node.type === "choice"
|
||||
? lastNode.node
|
||||
: null;
|
||||
const visibleChoices = choiceNode
|
||||
? (choiceNode.data.choices ?? [])
|
||||
.map((hop, index) => ({ hop, index }))
|
||||
.filter(({ hop, index }) => !(hop.once && takenChoices.has(`${choiceNode.id}:${index}`)))
|
||||
: [];
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
onClick={begin}
|
||||
className="group/converse relative overflow-hidden rounded-none border border-white/20 bg-black/40 text-white hover:border-cyan-400/60 hover:bg-zinc-800 hover:text-cyan-400"
|
||||
>
|
||||
<span className="absolute -left-8 h-full w-8 bg-gradient-to-r from-cyan-500/40 via-cyan-500/15 to-transparent transition-transform group-hover/converse:translate-x-8" />
|
||||
<MessageCircleIcon className="relative z-10 size-3.5 text-cyan-400" />
|
||||
<span className="relative z-10 ml-2 text-xs uppercase tracking-widest">Converse</span>
|
||||
</Button>
|
||||
|
||||
<Dialog open={open} onOpenChange={(next) => !next && close()}>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
className="flex max-w-2xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white sm:rounded-none"
|
||||
>
|
||||
<div className={`relative flex items-center justify-between ${DOSSIER.strip}`}>
|
||||
<DialogTitle className="font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
|
||||
Conversation // {npc.name}
|
||||
</DialogTitle>
|
||||
<button
|
||||
type="button"
|
||||
onClick={close}
|
||||
aria-label="Close conversation"
|
||||
className="text-white/40 transition-colors hover:text-white/90"
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</button>
|
||||
<span
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-0 opacity-[0.04]"
|
||||
style={DOSSIER.gridTexture}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{flow.startId === null ? (
|
||||
<div className="p-5 text-sm text-white/50">
|
||||
This conversation has no start node. Ask staff to configure it.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={scrollRef} className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5">
|
||||
{log.map((entry) => (
|
||||
<TimelineEntry key={entry.id} entry={entry} speakerDefault={npc.name} />
|
||||
))}
|
||||
{typing !== null && <TypingIndicator speaker={typing} />}
|
||||
{playerTyping && <TypingIndicator player />}
|
||||
</div>
|
||||
|
||||
{!typing &&
|
||||
!playerTyping &&
|
||||
lastNode &&
|
||||
lastNode.kind === "node" &&
|
||||
(lastNode.node.type === "choice" || lastNode.node.type === "end") && (
|
||||
<div className="flex flex-col gap-2 border-t border-white/15 bg-black/50 p-4">
|
||||
{lastNode.node.type === "choice" && visibleChoices.length > 0 ? (
|
||||
visibleChoices.map(({ hop, index }) => (
|
||||
<button
|
||||
key={index}
|
||||
type="button"
|
||||
onClick={() => pick(hop, index)}
|
||||
className="w-full rounded-none border border-white/20 bg-black/40 px-3 py-2 text-left text-sm text-white/80 transition-colors hover:border-cyan-500/60 hover:text-white"
|
||||
>
|
||||
{hop.label || "…"}
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<Button
|
||||
onClick={close}
|
||||
className="w-full rounded-none border border-white/20 bg-black/40 text-xs uppercase tracking-widest text-white/80 hover:border-cyan-500/60 hover:bg-black/40 hover:text-white"
|
||||
>
|
||||
End conversation
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function TimelineEntry({
|
||||
entry,
|
||||
speakerDefault,
|
||||
}: {
|
||||
entry: LogEntry;
|
||||
speakerDefault: string;
|
||||
}) {
|
||||
if (entry.kind === "player") {
|
||||
return (
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<span className={`${DOSSIER.readoutLabel} text-cyan-400/70`}>You</span>
|
||||
<p className="max-w-[85%] rounded-none border border-cyan-500/30 bg-cyan-500/10 px-3 py-1.5 text-sm text-cyan-50">
|
||||
{entry.text}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { node } = entry;
|
||||
|
||||
if (node.type === "event") {
|
||||
// Narration: no speaker, styled like a mission briefing line.
|
||||
const text = node.data.body || node.data.effect?.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>
|
||||
);
|
||||
}
|
||||
|
||||
if (node.type === "end") {
|
||||
return (
|
||||
<p className="text-sm italic text-white/50">
|
||||
<DialogueText text={node.data.closing || "The conversation ends."} />
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
if (node.type === "choice") {
|
||||
// The choice buttons live in the footer; only the lead-in joins the log.
|
||||
if (!node.data.leadIn) return null;
|
||||
return (
|
||||
<p className="text-sm italic text-white/60">
|
||||
<DialogueText text={node.data.leadIn} />
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
const speaker = node.data.speaker?.trim() || speakerDefault;
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className={DOSSIER.readoutLabel}>{speaker}</span>
|
||||
<p className="text-sm text-white/90">
|
||||
{node.data.body ? (
|
||||
<DialogueText text={node.data.body} />
|
||||
) : (
|
||||
<span className="italic text-white/30">…</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Three bouncing dots while a line is "typing". `player` renders the
|
||||
* right-aligned cyan variant for the player's incoming response. */
|
||||
function TypingIndicator({ speaker, player }: { speaker?: string; player?: boolean }) {
|
||||
return (
|
||||
<div className={`flex flex-col gap-1 ${player ? "items-end" : ""}`}>
|
||||
{player ? (
|
||||
<span className={`${DOSSIER.readoutLabel} text-cyan-400/70`}>You</span>
|
||||
) : speaker ? (
|
||||
<span className={DOSSIER.readoutLabel}>{speaker}</span>
|
||||
) : null}
|
||||
<span
|
||||
className={`flex items-center gap-1 py-1 ${player ? "justify-end" : ""}`}
|
||||
role="status"
|
||||
aria-label={player ? "You are typing" : "typing"}
|
||||
>
|
||||
{[0, 150, 300].map((delay) => (
|
||||
<span
|
||||
key={delay}
|
||||
className={`size-1.5 animate-bounce rounded-full ${player ? "bg-cyan-300/80" : "bg-cyan-400/70"}`}
|
||||
style={{ animationDelay: `${delay}ms` }}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -16,6 +16,8 @@ import {
|
|||
type ReadoutCell,
|
||||
} from "@/components/frontend/operations";
|
||||
import { CurrencyAmount } from "@/components/frontend/banking/CurrencyAmount";
|
||||
import { NpcActivityLine } from "@/components/frontend/personnel/NpcActivityLine";
|
||||
import type { NpcActivityOption } from "@/lib/npcs/activity";
|
||||
import { NpcStatusChips } from "@/components/frontend/personnel/NpcStatusChips";
|
||||
import { initialsOf } from "@/components/frontend/personnel/initials";
|
||||
|
||||
|
|
@ -24,6 +26,8 @@ interface NpcProfileProps {
|
|||
readonly listings: MarketListing[];
|
||||
/** Interactive employment controls, rendered in the dossier's right column. */
|
||||
readonly employmentSlot?: ReactNode;
|
||||
/** Conversation trigger, anchored to the right side of the hero card. */
|
||||
readonly conversationSlot?: ReactNode;
|
||||
}
|
||||
|
||||
function assetName(asset: number | Asset): string {
|
||||
|
|
@ -65,7 +69,17 @@ function NpcBio({ bio }: { bio: GameNpc["bio"] }) {
|
|||
);
|
||||
}
|
||||
|
||||
export function NpcProfile({ npc, listings, employmentSlot }: NpcProfileProps) {
|
||||
/** Renders an NPC's level description (Lexical richText), falling back when empty. */
|
||||
function LevelDescription({ data }: { data: GameNpc["levelDescription"] }) {
|
||||
const children = (data as { root?: { children?: unknown[] } } | null | undefined)?.root
|
||||
?.children;
|
||||
if (!data || !Array.isArray(children) || children.length === 0) {
|
||||
return <p className="text-sm text-white/60">No capabilities on file.</p>;
|
||||
}
|
||||
return <div className="lexical-content"><RichText data={data as LexicalData} /></div>;
|
||||
}
|
||||
|
||||
export function NpcProfile({ npc, listings, employmentSlot, conversationSlot }: NpcProfileProps) {
|
||||
const faction = typeof npc.faction === "object" && npc.faction !== null ? npc.faction : null;
|
||||
const location =
|
||||
typeof npc.location === "object" && npc.location !== null ? npc.location : null;
|
||||
|
|
@ -79,6 +93,15 @@ export function NpcProfile({ npc, listings, employmentSlot }: NpcProfileProps) {
|
|||
|
||||
const refCode = String(npc.id).padStart(3, "0");
|
||||
const monogram = initialsOf(npc.name);
|
||||
const activityInterval = npc.activity?.intervalMinutes ?? 30;
|
||||
const activityOptions: NpcActivityOption[] = (npc.activity?.activityOptions ?? []).map(
|
||||
(option) => ({
|
||||
label: option.label,
|
||||
weight: option.weight ?? 1,
|
||||
forced: option.forced ?? false,
|
||||
}),
|
||||
);
|
||||
const hasLevel = typeof npc.level === "number";
|
||||
|
||||
const heroCells: ReadoutCell[] = [
|
||||
{ label: "Faction", value: faction?.name ?? "Unaffiliated" },
|
||||
|
|
@ -131,6 +154,12 @@ export function NpcProfile({ npc, listings, employmentSlot }: NpcProfileProps) {
|
|||
<ClassificationStrip left="Personnel File // Theater Contacts" right={`REF ${refCode}`} />
|
||||
<CornerBrackets />
|
||||
|
||||
{conversationSlot ? (
|
||||
<div className="absolute right-6 top-1/2 z-20 -translate-y-1/2 md:right-12">
|
||||
{conversationSlot}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="relative z-10 flex flex-col gap-3 px-6 py-10 md:py-14">
|
||||
<h1
|
||||
data-text={npc.name}
|
||||
|
|
@ -150,6 +179,10 @@ export function NpcProfile({ npc, listings, employmentSlot }: NpcProfileProps) {
|
|||
<p className="glitch-soft max-w-prose text-pretty text-sm uppercase tracking-wider text-white/60 drop-shadow">
|
||||
{npc.occupation ?? "Occupation not recorded"}
|
||||
</p>
|
||||
<NpcActivityLine
|
||||
intervalMinutes={activityInterval}
|
||||
activityOptions={activityOptions}
|
||||
/>
|
||||
<NpcStatusChips npc={npc} className="mt-1" />
|
||||
</div>
|
||||
|
||||
|
|
@ -178,6 +211,15 @@ export function NpcProfile({ npc, listings, employmentSlot }: NpcProfileProps) {
|
|||
/>
|
||||
</div>
|
||||
</StrategicSummary>
|
||||
|
||||
{hasLevel && (
|
||||
<StrategicSummary
|
||||
classificationLeft="Capabilities"
|
||||
classificationRight={`Level ${npc.level}`}
|
||||
>
|
||||
<LevelDescription data={npc.levelDescription} />
|
||||
</StrategicSummary>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-6">
|
||||
|
|
@ -215,15 +257,20 @@ export function NpcProfile({ npc, listings, employmentSlot }: NpcProfileProps) {
|
|||
classificationLeft="Active Market Stock"
|
||||
classificationRight={`${listings.length} Listing(s)`}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex justify-end">
|
||||
{listings.length === 0 ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<p className="text-sm italic text-white/50">No active stock.</p>
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<Link href="/logistics/market">View market</Link>
|
||||
</Button>
|
||||
</div>
|
||||
{listings.length === 0 ? (
|
||||
<p className="text-sm italic text-white/50">No active stock.</p>
|
||||
) : (
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex justify-end">
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<Link href="/logistics/market">View market</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
{listings.map((listing, index) => (
|
||||
<Fragment key={listing.id}>
|
||||
|
|
@ -244,8 +291,8 @@ export function NpcProfile({ npc, listings, employmentSlot }: NpcProfileProps) {
|
|||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</StrategicSummary>
|
||||
|
||||
{employmentSlot ? (
|
||||
|
|
|
|||
|
|
@ -21,8 +21,13 @@ function Chip({
|
|||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center border font-mono uppercase leading-none tracking-widest",
|
||||
size === "compact" ? "px-1 py-px text-[8px]" : "px-1.5 py-0.5 text-[9px]",
|
||||
"inline-flex items-center border font-mono uppercase tracking-widest",
|
||||
// Keep `leading-none` AFTER the font-size: tailwind-merge drops it when a
|
||||
// later `text-[Npx]` is in the same class list, which leaves the chip at
|
||||
// the inherited line-height (very tall).
|
||||
size === "compact"
|
||||
? "px-1 py-px text-[8px] leading-none"
|
||||
: "px-1.5 py-0.5 text-[9px] leading-none",
|
||||
STATUS_CHIP[tone],
|
||||
)}
|
||||
>
|
||||
|
|
|
|||
91
src/lib/npc-dialogue/DialogueText.tsx
Normal file
91
src/lib/npc-dialogue/DialogueText.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import type { ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* Renders a dialogue string for display: newlines are preserved and a tiny
|
||||
* inline markup subset is honoured (**bold**, *italic*, `code`, and
|
||||
* {color}text{/}). Colors take a friendly name ({red}, {cyan}, ...) or a hex
|
||||
* code ({#ff00ff}). 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 ?? ""}`}>{renderInline(text)}</span>;
|
||||
}
|
||||
|
||||
/** 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> = {
|
||||
red: "text-red-400",
|
||||
rose: "text-rose-400",
|
||||
orange: "text-orange-400",
|
||||
amber: "text-amber-400",
|
||||
yellow: "text-yellow-400",
|
||||
green: "text-green-400",
|
||||
emerald: "text-emerald-400",
|
||||
cyan: "text-cyan-400",
|
||||
sky: "text-sky-400",
|
||||
blue: "text-blue-400",
|
||||
violet: "text-violet-400",
|
||||
purple: "text-purple-400",
|
||||
pink: "text-pink-400",
|
||||
slate: "text-slate-300",
|
||||
};
|
||||
|
||||
const HEX_COLOR = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
|
||||
|
||||
const INLINE_PATTERN =
|
||||
/(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\{(?:#[0-9a-fA-F]{3,6}|[a-zA-Z]+)\}[^{}]*\{\/\})/g;
|
||||
|
||||
/** Matches one colour token produced by INLINE_PATTERN. */
|
||||
const COLOR_TOKEN = /^\{(#?[a-zA-Z0-9#]+)\}([^{}]*)\{\/\}$/;
|
||||
|
||||
function renderInline(text: string): ReactNode {
|
||||
const parts = text.split(INLINE_PATTERN);
|
||||
return parts.map((part, index) => {
|
||||
if (part.length > 4 && part.startsWith("**") && part.endsWith("**")) {
|
||||
return (
|
||||
<strong key={index} className="font-semibold">
|
||||
{part.slice(2, -2)}
|
||||
</strong>
|
||||
);
|
||||
}
|
||||
if (part.length > 2 && part.startsWith("*") && part.endsWith("*")) {
|
||||
return <em key={index}>{part.slice(1, -1)}</em>;
|
||||
}
|
||||
if (part.length > 2 && part.startsWith("`") && part.endsWith("`")) {
|
||||
return (
|
||||
<code
|
||||
key={index}
|
||||
className="rounded-sm bg-white/10 px-1 py-0.5 font-mono text-[0.85em] text-cyan-300"
|
||||
>
|
||||
{part.slice(1, -1)}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
const colorMatch = part.match(COLOR_TOKEN);
|
||||
if (colorMatch) {
|
||||
const token = colorMatch[1];
|
||||
const inner = colorMatch[2];
|
||||
if (token.startsWith("#")) {
|
||||
// Only well-formed hex codes reach the style attribute; anything else
|
||||
// (e.g. {#12345}) renders as literal text.
|
||||
if (HEX_COLOR.test(token)) {
|
||||
return (
|
||||
<span key={index} style={{ color: token }}>
|
||||
{inner}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return <span key={index}>{part}</span>;
|
||||
}
|
||||
const cls = FRIENDLY_COLORS[token.toLowerCase()];
|
||||
if (cls) {
|
||||
return (
|
||||
<span key={index} className={cls}>
|
||||
{inner}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
return <span key={index}>{part}</span>;
|
||||
});
|
||||
}
|
||||
205
src/lib/npc-dialogue/dialogue.ts
Normal file
205
src/lib/npc-dialogue/dialogue.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
/**
|
||||
* Canonical model + pure helpers for NPC conversation flowcharts.
|
||||
*
|
||||
* The graph is authoritative in node data: every node lists where the
|
||||
* conversation can go next (`next` for a single continuation, `choices` for
|
||||
* branching). Edges are a derived projection of that data, so the admin
|
||||
* canvas and the runtime walker always agree.
|
||||
*/
|
||||
|
||||
export type NpcDialogueNodeType =
|
||||
| "dialogue"
|
||||
| "choice"
|
||||
| "event"
|
||||
| "end"
|
||||
| "delay"
|
||||
| "condition";
|
||||
|
||||
/** A directed hop to another node. `label` is the choice button text. */
|
||||
export interface DialogueNext {
|
||||
/** Button text shown to the player (required on choice hops). */
|
||||
label?: string;
|
||||
/** Target node id. */
|
||||
target: string;
|
||||
/**
|
||||
* Choice hops only: once the player picks this choice it is hidden from
|
||||
* them in every later conversation turn (tracked per player as a reserved
|
||||
* `dlg-once:` player flag).
|
||||
*/
|
||||
once?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Branch condition evaluated server-side against live web-app state when the
|
||||
* conversation arrives at a `condition` node. Boolean flags compare against
|
||||
* true/false; numeric flags compare against `amount` (a missing flag counts
|
||||
* as false / zero).
|
||||
*/
|
||||
export interface DialogueCondition {
|
||||
/** Currently only generic player flags; more kinds can join later. */
|
||||
kind: "flag";
|
||||
/** `player-flags` key checked for the reading user. */
|
||||
key: string;
|
||||
/** Comparison applied to the flag's effective value. */
|
||||
op: "is_true" | "is_false" | "gte" | "lte" | "gt" | "lt" | "eq";
|
||||
/** Right-hand side for the numeric comparisons. */
|
||||
amount?: number;
|
||||
}
|
||||
|
||||
/** How a flag effect writes the flag. */
|
||||
export type DialogueFlagOp = "set_true" | "set_false" | "set_number" | "add";
|
||||
|
||||
/** Configured effect for an `event` node. */
|
||||
export interface NpcDialogueEffect {
|
||||
type: "notify" | "emit" | "reward" | "flag";
|
||||
/** In-app notification title (notify). */
|
||||
title?: string;
|
||||
/** Notification / event-log body (notify, emit). */
|
||||
message?: string;
|
||||
/** Flag key to write (flag). */
|
||||
flagKey?: string;
|
||||
/** Write mode (flag). */
|
||||
flagOp?: DialogueFlagOp;
|
||||
/** Value for set_number / addend for add (flag). */
|
||||
flagAmount?: number;
|
||||
}
|
||||
|
||||
export type DialogueNodeData = {
|
||||
/** Speaker label shown above the line. Defaults to the NPC's name at runtime. */
|
||||
speaker?: string;
|
||||
/** The spoken line (dialogue) or narrative description (event nodes). */
|
||||
body?: string;
|
||||
/** Branching options (choice nodes). */
|
||||
choices?: DialogueNext[];
|
||||
/** Optional lead-in text before the choices. */
|
||||
leadIn?: string;
|
||||
/** Triggered when the conversation arrives at this node. */
|
||||
effect?: NpcDialogueEffect;
|
||||
/** Closing text shown when the conversation ends. */
|
||||
closing?: string;
|
||||
/** Marks this node as the conversation start. */
|
||||
isStart?: boolean;
|
||||
/** Single continuation (dialogue / event / end nodes). */
|
||||
next?: DialogueNext;
|
||||
/** Pause in seconds before the conversation continues (delay nodes). */
|
||||
delaySeconds?: number;
|
||||
/** Branch condition evaluated when the conversation arrives (condition nodes). */
|
||||
condition?: DialogueCondition;
|
||||
/** Continuation when the condition passes (condition nodes). */
|
||||
trueTarget?: string;
|
||||
/** Continuation when the condition fails (condition nodes). */
|
||||
falseTarget?: string;
|
||||
} & Record<string, unknown>;
|
||||
|
||||
export interface DialogueNode {
|
||||
id: string;
|
||||
type: NpcDialogueNodeType;
|
||||
position: { x: number; y: number };
|
||||
data: DialogueNodeData;
|
||||
}
|
||||
|
||||
export interface DialogueEdge {
|
||||
id: string;
|
||||
source: string;
|
||||
target: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export interface FlowData {
|
||||
nodes: DialogueNode[];
|
||||
edges: DialogueEdge[];
|
||||
}
|
||||
|
||||
/** All effect types the runtime can actually trigger. */
|
||||
export const EFFECT_TYPES: NpcDialogueEffect["type"][] = [
|
||||
"notify",
|
||||
"emit",
|
||||
"reward",
|
||||
"flag",
|
||||
];
|
||||
|
||||
/**
|
||||
* Every outgoing hop of a node, in canvas order: choice buttons, the single
|
||||
* continuation, or the condition's true/false branches. The edge projection,
|
||||
* validation, and the runtime walker all share this so they never disagree.
|
||||
*/
|
||||
export function outgoingHops(node: DialogueNode): DialogueNext[] {
|
||||
if (node.type === "choice") return node.data.choices ?? [];
|
||||
if (node.type === "condition") {
|
||||
const hops: DialogueNext[] = [];
|
||||
if (node.data.trueTarget) hops.push({ label: "true", target: node.data.trueTarget });
|
||||
if (node.data.falseTarget) hops.push({ label: "false", target: node.data.falseTarget });
|
||||
return hops;
|
||||
}
|
||||
return node.data.next ? [node.data.next] : [];
|
||||
}
|
||||
|
||||
/** True when a node has no outgoing hops (conversation ends here). */
|
||||
export function isTerminalNode(node: DialogueNode): boolean {
|
||||
return outgoingHops(node).length === 0;
|
||||
}
|
||||
|
||||
/** Resolves the node the conversation should start at. */
|
||||
export function findStartNode(nodes: DialogueNode[]): DialogueNode | null {
|
||||
if (nodes.length === 0) return null;
|
||||
const marked = nodes.find((node) => node.data.isStart === true);
|
||||
if (marked) return marked;
|
||||
// Fall back to the first node with no incoming edges.
|
||||
const targets = new Set(nodes.flatMap((n) => outgoingHops(n).map((h) => h.target)));
|
||||
const roots = nodes.filter((n) => !targets.has(n.id));
|
||||
return (roots.length ? roots[0] : nodes[0]) ?? null;
|
||||
}
|
||||
|
||||
/** Builds the edge projection that mirrors the node graph. */
|
||||
export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] {
|
||||
const edges: DialogueEdge[] = [];
|
||||
for (const node of nodes) {
|
||||
outgoingHops(node).forEach((hop, index) => {
|
||||
if (!hop || !hop.target) return;
|
||||
edges.push({
|
||||
id: `${node.id}->${index}`,
|
||||
source: node.id,
|
||||
target: hop.target,
|
||||
label: hop.label,
|
||||
});
|
||||
});
|
||||
}
|
||||
return edges;
|
||||
}
|
||||
|
||||
export interface GraphValidation {
|
||||
valid: boolean;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a flowchart: a start node exists, every hop target resolves, and
|
||||
* choice hops carry a label. Does not hard-fail on cycles (branching can be
|
||||
* intentionally re-entrant) but reports them.
|
||||
*/
|
||||
export function validateGraph(nodes: DialogueNode[]): GraphValidation {
|
||||
const errors: string[] = [];
|
||||
const ids = new Set(nodes.map((n) => n.id));
|
||||
|
||||
if (nodes.length === 0) {
|
||||
return { valid: false, errors: ["Add at least one node to start building the conversation."] };
|
||||
}
|
||||
if (!findStartNode(nodes)) {
|
||||
errors.push("Mark a node as the conversation start.");
|
||||
}
|
||||
|
||||
for (const node of nodes) {
|
||||
const hops = outgoingHops(node);
|
||||
for (const hop of hops) {
|
||||
if (!hop) continue;
|
||||
if (hop.target && !ids.has(hop.target)) {
|
||||
errors.push(`"${node.id}" points to missing node "${hop.target}".`);
|
||||
}
|
||||
if (node.type === "choice" && !hop.label?.trim()) {
|
||||
errors.push(`A choice on "${node.id}" needs button text.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: errors.length === 0, errors };
|
||||
}
|
||||
85
src/lib/npcs/activity.ts
Normal file
85
src/lib/npcs/activity.ts
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
/**
|
||||
* Pure, client-safe helpers for an NPC's "current activity" flavor.
|
||||
*
|
||||
* An NPC has a list of possible activities, each with a relative "chance"
|
||||
* (weight) and an optional "forced" flag. If any activity is forced, it is
|
||||
* shown stably (it ignores the reshuffle interval). Otherwise the most likely
|
||||
* activity is picked at random, weighted by each option's chance.
|
||||
*/
|
||||
|
||||
export interface NpcActivityOption {
|
||||
label: string;
|
||||
/** Relative chance this activity is picked when reshuffling (min 1). */
|
||||
weight: number;
|
||||
/** When true, this activity stays active until the flag is turned off. */
|
||||
forced?: boolean;
|
||||
}
|
||||
|
||||
/** Deterministic 32-bit PRNG (mulberry32) so reshuffles are reproducible in tests. */
|
||||
export function seededRng(seed: number | string): () => number {
|
||||
let a = typeof seed === "string" ? stringToSeed(seed) : seed;
|
||||
return function next(): number {
|
||||
a |= 0;
|
||||
a = (a + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function stringToSeed(input: string): number {
|
||||
let hash = 0;
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
hash = (mathHash(hash + input.charCodeAt(i), 0x1000193) + mathHash(hash, 0x287c47fd)) | 0;
|
||||
}
|
||||
return hash >>> 0;
|
||||
}
|
||||
|
||||
function mathHash(value: number, prime: number): number {
|
||||
return (Math.imul(value ^ (value >>> 16), prime) >>> 0) | 0;
|
||||
}
|
||||
|
||||
/** Returns true when at least one activity is flagged forced. */
|
||||
export function hasForcedActivity(options: NpcActivityOption[]): boolean {
|
||||
return options.some((option) => option.forced === true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the activity an NPC is "currently" doing.
|
||||
*
|
||||
* - If any activity is forced, the first forced option is returned (stable,
|
||||
* ignores the reshuffle interval).
|
||||
* - Otherwise a weighted-random pick is made. Pass `seed`/`rng` to reshuffle
|
||||
* deterministically (e.g. a new seed each interval tick on the frontend).
|
||||
*/
|
||||
export function resolveCurrentActivity(
|
||||
options: NpcActivityOption[],
|
||||
seed?: number | string,
|
||||
rng: () => number = Math.random,
|
||||
): string | null {
|
||||
const forced = options.filter((option) => option.forced === true);
|
||||
if (forced.length > 0) {
|
||||
return forced[0].label;
|
||||
}
|
||||
|
||||
const totalWeight = options.reduce((sum, option) => sum + Math.max(0, option.weight ?? 1), 0);
|
||||
if (totalWeight <= 0) {
|
||||
return options.length > 0 ? options[0].label : null;
|
||||
}
|
||||
|
||||
const pickRng = seed !== undefined ? seededRng(seed) : rng;
|
||||
let roll = pickRng() * totalWeight;
|
||||
for (const option of options) {
|
||||
const weight = Math.max(0, option.weight ?? 1);
|
||||
if (roll < weight) {
|
||||
return option.label;
|
||||
}
|
||||
roll -= weight;
|
||||
}
|
||||
return options[options.length - 1]?.label ?? null;
|
||||
}
|
||||
|
||||
/** Formats an activity for the "Currently: …" readout. */
|
||||
export function formatActivityLine(activity: string | null | undefined): string {
|
||||
return activity ? `Currently: ${activity}` : "Currently: undetermined";
|
||||
}
|
||||
37379
src/migrations/20261005_185014_add_player_flags.json
Normal file
37379
src/migrations/20261005_185014_add_player_flags.json
Normal file
File diff suppressed because it is too large
Load diff
53
src/migrations/20261005_185014_add_player_flags.ts
Normal file
53
src/migrations/20261005_185014_add_player_flags.ts
Normal file
File diff suppressed because one or more lines are too long
37379
src/migrations/20261006_000000_add_npc_dialogue_and_activity_fields.json
Normal file
37379
src/migrations/20261006_000000_add_npc_dialogue_and_activity_fields.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,91 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
/**
|
||||
* NPC contacts: the "Narrative Activity" group + `level`/`levelDescription`/
|
||||
* `canMessage` fields on `game_npcs`, the `npc-dialogues` collection (branching
|
||||
* conversation flowcharts), and the collection's RBAC permission values.
|
||||
* Hand-written in the add_mission_role_signups / add_mission_map_markers style
|
||||
* (isolated to this feature's footprint).
|
||||
*/
|
||||
export async function up({ db }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE IF NOT EXISTS 'npc-dialogues:create' BEFORE 'campaigns:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE IF NOT EXISTS 'npc-dialogues:read' BEFORE 'campaigns:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE IF NOT EXISTS 'npc-dialogues:update' BEFORE 'campaigns:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE IF NOT EXISTS 'npc-dialogues:delete' BEFORE 'campaigns:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE IF NOT EXISTS 'admin:npc-dialogues:manage' BEFORE 'campaigns:create';
|
||||
CREATE TABLE "npc_dialogues" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"name" varchar NOT NULL,
|
||||
"npc_id" integer NOT NULL,
|
||||
"flow_data" jsonb DEFAULT '{"nodes":[],"edges":[]}' NOT NULL,
|
||||
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
|
||||
-- game_npcs: narrative activity group. intervalMinutes is a direct column
|
||||
-- (default 30); activityOptions is an array, which Payload stores in its own
|
||||
-- sub-table rather than as a jsonb column on the parent.
|
||||
ALTER TABLE "game_npcs" ADD COLUMN "activity_interval_minutes" numeric DEFAULT 30;
|
||||
ALTER TABLE "game_npcs" ADD COLUMN "level" numeric;
|
||||
ALTER TABLE "game_npcs" ADD COLUMN "level_description" jsonb;
|
||||
ALTER TABLE "game_npcs" ADD COLUMN "can_message" boolean DEFAULT false;
|
||||
|
||||
-- array sub-table for activity.activityOptions (Payload-managed _order/_parent_id/id)
|
||||
CREATE TABLE "game_npcs_activity_activity_options" (
|
||||
"id" varchar PRIMARY KEY NOT NULL,
|
||||
"_order" integer NOT NULL,
|
||||
"_parent_id" integer NOT NULL,
|
||||
"label" varchar NOT NULL,
|
||||
"weight" numeric DEFAULT 1,
|
||||
"forced" boolean DEFAULT false
|
||||
);
|
||||
CREATE INDEX "game_npcs_activity_activity_options_order_idx" ON "game_npcs_activity_activity_options" USING btree ("_order");
|
||||
CREATE INDEX "game_npcs_activity_activity_options_parent_id_idx" ON "game_npcs_activity_activity_options" USING btree ("_parent_id");
|
||||
ALTER TABLE "game_npcs_activity_activity_options" ADD CONSTRAINT "game_npcs_activity_activity_options_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."game_npcs"("id") ON DELETE cascade ON UPDATE no action;
|
||||
|
||||
-- MCP exposure (the mcp plugin is enabled for every scoped collection)
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogues_find" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogues_create" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogues_update" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogues_delete" boolean DEFAULT false;
|
||||
|
||||
-- document locking bookkeeping for the new collection
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "npc_dialogues_id" integer;
|
||||
ALTER TABLE "npc_dialogues" ADD CONSTRAINT "npc_dialogues_npc_id_game_npcs_id_fk" FOREIGN KEY ("npc_id") REFERENCES "public"."game_npcs"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_npc_dialogues_fk" FOREIGN KEY ("npc_dialogues_id") REFERENCES "public"."npc_dialogues"("id") ON DELETE cascade ON UPDATE no action;
|
||||
CREATE INDEX "npc_dialogues_npc_idx" ON "npc_dialogues" USING btree ("npc_id");
|
||||
CREATE INDEX "npc_dialogues_updated_at_idx" ON "npc_dialogues" USING btree ("updated_at");
|
||||
CREATE INDEX "npc_dialogues_created_at_idx" ON "npc_dialogues" USING btree ("created_at");
|
||||
CREATE INDEX "payload_locked_documents_rels_npc_dialogues_id_idx" ON "payload_locked_documents_rels" USING btree ("npc_dialogues_id");`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the table, columns and FKs. The enum values are left in place (Postgres
|
||||
* cannot drop enum values without rebuilding the type, and an unused value is
|
||||
* harmless); role rows holding them are removed.
|
||||
*/
|
||||
export async function down({ db }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
DELETE FROM "roles_permissions" WHERE "value"::text LIKE '%npc-dialogues%';
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT IF EXISTS "payload_locked_documents_rels_npc_dialogues_fk";
|
||||
DROP INDEX IF EXISTS "payload_locked_documents_rels_npc_dialogues_id_idx";
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN IF EXISTS "npc_dialogues_id";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "npc_dialogues_find";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "npc_dialogues_create";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "npc_dialogues_update";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "npc_dialogues_delete";
|
||||
ALTER TABLE "game_npcs_activity_activity_options" DROP CONSTRAINT IF EXISTS "game_npcs_activity_activity_options_parent_id_fk";
|
||||
DROP INDEX IF EXISTS "game_npcs_activity_activity_options_order_idx";
|
||||
DROP INDEX IF EXISTS "game_npcs_activity_activity_options_parent_id_idx";
|
||||
DROP TABLE IF EXISTS "game_npcs_activity_activity_options" CASCADE;
|
||||
DROP INDEX IF EXISTS "npc_dialogues_npc_idx";
|
||||
DROP INDEX IF EXISTS "npc_dialogues_updated_at_idx";
|
||||
DROP INDEX IF EXISTS "npc_dialogues_created_at_idx";
|
||||
ALTER TABLE "npc_dialogues" DROP CONSTRAINT IF EXISTS "npc_dialogues_npc_id_game_npcs_id_fk";
|
||||
DROP TABLE IF EXISTS "npc_dialogues" CASCADE;
|
||||
ALTER TABLE "game_npcs" DROP COLUMN IF EXISTS "activity_interval_minutes";
|
||||
ALTER TABLE "game_npcs" DROP COLUMN IF EXISTS "level";
|
||||
ALTER TABLE "game_npcs" DROP COLUMN IF EXISTS "level_description";
|
||||
ALTER TABLE "game_npcs" DROP COLUMN IF EXISTS "can_message";`)
|
||||
}
|
||||
|
|
@ -106,6 +106,8 @@ import * as migration_20261005_001212_add_map_grid_config from './20261005_00121
|
|||
import * as migration_20261005_051452_add_game_structure_item_storage from './20261005_051452_add_game_structure_item_storage';
|
||||
import * as migration_20261005_054132_add_game_npc_bio_richtext from './20261005_054132_add_game_npc_bio_richtext';
|
||||
import * as migration_20261005_063613_add_game_npc_image from './20261005_063613_add_game_npc_image';
|
||||
import * as migration_20261005_185014_add_player_flags from './20261005_185014_add_player_flags';
|
||||
import * as migration_20261006_000000_add_npc_dialogue_and_activity_fields from './20261006_000000_add_npc_dialogue_and_activity_fields';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -646,6 +648,16 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261005_063613_add_game_npc_image.up,
|
||||
down: migration_20261005_063613_add_game_npc_image.down,
|
||||
name: '20261005_063613_add_game_npc_image'
|
||||
name: '20261005_063613_add_game_npc_image',
|
||||
},
|
||||
{
|
||||
up: migration_20261005_185014_add_player_flags.up,
|
||||
down: migration_20261005_185014_add_player_flags.down,
|
||||
name: '20261005_185014_add_player_flags',
|
||||
},
|
||||
{
|
||||
up: migration_20261006_000000_add_npc_dialogue_and_activity_fields.up,
|
||||
down: migration_20261006_000000_add_npc_dialogue_and_activity_fields.down,
|
||||
name: '20261006_000000_add_npc_dialogue_and_activity_fields'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -439,6 +439,11 @@ export const enum_roles_permissions = pgEnum("enum_roles_permissions", [
|
|||
"narrative-events:update",
|
||||
"narrative-events:delete",
|
||||
"admin:narrative-events:manage",
|
||||
"npc-dialogues:create",
|
||||
"npc-dialogues:read",
|
||||
"npc-dialogues:update",
|
||||
"npc-dialogues:delete",
|
||||
"admin:npc-dialogues:manage",
|
||||
"mission-files:create",
|
||||
"mission-files:read",
|
||||
"mission-files:update",
|
||||
|
|
@ -1668,6 +1673,27 @@ export const game_vehicles = pgTable(
|
|||
],
|
||||
);
|
||||
|
||||
export const game_npcs_activity_activity_options = pgTable(
|
||||
"game_npcs_activity_activity_options",
|
||||
{
|
||||
_order: integer("_order").notNull(),
|
||||
_parentID: integer("_parent_id").notNull(),
|
||||
id: varchar("id").primaryKey(),
|
||||
label: varchar("label").notNull(),
|
||||
weight: numeric("weight", { mode: "number" }).default(1),
|
||||
forced: boolean("forced").default(false),
|
||||
},
|
||||
(columns) => [
|
||||
index("game_npcs_activity_activity_options_order_idx").on(columns._order),
|
||||
index("game_npcs_activity_activity_options_parent_id_idx").on(columns._parentID),
|
||||
foreignKey({
|
||||
columns: [columns["_parentID"]],
|
||||
foreignColumns: [game_npcs.id],
|
||||
name: "game_npcs_activity_activity_options_parent_id_fk",
|
||||
}).onDelete("cascade"),
|
||||
],
|
||||
);
|
||||
|
||||
export const game_npcs = pgTable(
|
||||
"game_npcs",
|
||||
{
|
||||
|
|
@ -1688,6 +1714,10 @@ export const game_npcs = pgTable(
|
|||
isInGame: boolean("is_in_game").default(true),
|
||||
vendor_enabled: boolean("vendor_enabled").default(false),
|
||||
vendor_priceModifier: numeric("vendor_price_modifier", { mode: "number" }).default(1),
|
||||
activity_intervalMinutes: numeric("activity_interval_minutes", { mode: "number" }).default(30),
|
||||
level: numeric("level", { mode: "number" }),
|
||||
levelDescription: jsonb("level_description"),
|
||||
canMessage: boolean("can_message").default(false),
|
||||
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
|
||||
.defaultNow()
|
||||
.notNull(),
|
||||
|
|
@ -1773,6 +1803,31 @@ export const npc_staffing = pgTable(
|
|||
],
|
||||
);
|
||||
|
||||
export const npc_dialogues = pgTable(
|
||||
"npc_dialogues",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
name: varchar("name").notNull(),
|
||||
npc: integer("npc_id")
|
||||
.notNull()
|
||||
.references(() => game_npcs.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
flowData: jsonb("flow_data").notNull(),
|
||||
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
|
||||
.defaultNow()
|
||||
.notNull(),
|
||||
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 })
|
||||
.defaultNow()
|
||||
.notNull(),
|
||||
},
|
||||
(columns) => [
|
||||
index("npc_dialogues_npc_idx").on(columns.npc),
|
||||
index("npc_dialogues_updated_at_idx").on(columns.updatedAt),
|
||||
index("npc_dialogues_created_at_idx").on(columns.createdAt),
|
||||
],
|
||||
);
|
||||
|
||||
export const labor_classifications = pgTable(
|
||||
"labor_classifications",
|
||||
{
|
||||
|
|
@ -7092,6 +7147,10 @@ export const payload_mcp_api_keys = pgTable(
|
|||
npcStaffing_create: boolean("npc_staffing_create").default(false),
|
||||
npcStaffing_update: boolean("npc_staffing_update").default(false),
|
||||
npcStaffing_delete: boolean("npc_staffing_delete").default(false),
|
||||
npcDialogues_find: boolean("npc_dialogues_find").default(false),
|
||||
npcDialogues_create: boolean("npc_dialogues_create").default(false),
|
||||
npcDialogues_update: boolean("npc_dialogues_update").default(false),
|
||||
npcDialogues_delete: boolean("npc_dialogues_delete").default(false),
|
||||
laborClassifications_find: boolean("labor_classifications_find").default(false),
|
||||
laborClassifications_create: boolean("labor_classifications_create").default(false),
|
||||
laborClassifications_update: boolean("labor_classifications_update").default(false),
|
||||
|
|
@ -7440,6 +7499,7 @@ export const payload_locked_documents_rels = pgTable(
|
|||
"game-vehiclesID": integer("game_vehicles_id"),
|
||||
"game-npcsID": integer("game_npcs_id"),
|
||||
"npc-staffingID": integer("npc_staffing_id"),
|
||||
"npc-dialoguesID": integer("npc_dialogues_id"),
|
||||
"labor-classificationsID": integer("labor_classifications_id"),
|
||||
"game-event-logsID": integer("game_event_logs_id"),
|
||||
usersID: integer("users_id"),
|
||||
|
|
@ -7530,6 +7590,7 @@ export const payload_locked_documents_rels = pgTable(
|
|||
index("payload_locked_documents_rels_game_vehicles_id_idx").on(columns["game-vehiclesID"]),
|
||||
index("payload_locked_documents_rels_game_npcs_id_idx").on(columns["game-npcsID"]),
|
||||
index("payload_locked_documents_rels_npc_staffing_id_idx").on(columns["npc-staffingID"]),
|
||||
index("payload_locked_documents_rels_npc_dialogues_id_idx").on(columns["npc-dialoguesID"]),
|
||||
index("payload_locked_documents_rels_labor_classifications_id_idx").on(
|
||||
columns["labor-classificationsID"],
|
||||
),
|
||||
|
|
@ -7700,6 +7761,11 @@ export const payload_locked_documents_rels = pgTable(
|
|||
foreignColumns: [npc_staffing.id],
|
||||
name: "payload_locked_documents_rels_npc_staffing_fk",
|
||||
}).onDelete("cascade"),
|
||||
foreignKey({
|
||||
columns: [columns["npc-dialoguesID"]],
|
||||
foreignColumns: [npc_dialogues.id],
|
||||
name: "payload_locked_documents_rels_npc_dialogues_fk",
|
||||
}).onDelete("cascade"),
|
||||
foreignKey({
|
||||
columns: [columns["labor-classificationsID"]],
|
||||
foreignColumns: [labor_classifications.id],
|
||||
|
|
@ -8636,6 +8702,16 @@ export const relations_game_vehicles = relations(game_vehicles, ({ one, many })
|
|||
relationName: "voidStorage",
|
||||
}),
|
||||
}));
|
||||
export const relations_game_npcs_activity_activity_options = relations(
|
||||
game_npcs_activity_activity_options,
|
||||
({ one }) => ({
|
||||
_parentID: one(game_npcs, {
|
||||
fields: [game_npcs_activity_activity_options._parentID],
|
||||
references: [game_npcs.id],
|
||||
relationName: "activity_activityOptions",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
export const relations_game_npcs_rels = relations(game_npcs_rels, ({ one }) => ({
|
||||
parent: one(game_npcs, {
|
||||
fields: [game_npcs_rels.parent],
|
||||
|
|
@ -8664,6 +8740,9 @@ export const relations_game_npcs = relations(game_npcs, ({ one, many }) => ({
|
|||
references: [factions.id],
|
||||
relationName: "faction",
|
||||
}),
|
||||
activity_activityOptions: many(game_npcs_activity_activity_options, {
|
||||
relationName: "activity_activityOptions",
|
||||
}),
|
||||
_rels: many(game_npcs_rels, {
|
||||
relationName: "_rels",
|
||||
}),
|
||||
|
|
@ -8685,6 +8764,13 @@ export const relations_npc_staffing = relations(npc_staffing, ({ one }) => ({
|
|||
relationName: "laborClassification",
|
||||
}),
|
||||
}));
|
||||
export const relations_npc_dialogues = relations(npc_dialogues, ({ one }) => ({
|
||||
npc: one(game_npcs, {
|
||||
fields: [npc_dialogues.npc],
|
||||
references: [game_npcs.id],
|
||||
relationName: "npc",
|
||||
}),
|
||||
}));
|
||||
export const relations_labor_classifications = relations(labor_classifications, () => ({}));
|
||||
export const relations_game_event_logs = relations(game_event_logs, ({ one }) => ({
|
||||
actor: one(users, {
|
||||
|
|
@ -10919,6 +11005,11 @@ export const relations_payload_locked_documents_rels = relations(
|
|||
references: [npc_staffing.id],
|
||||
relationName: "npc-staffing",
|
||||
}),
|
||||
"npc-dialoguesID": one(npc_dialogues, {
|
||||
fields: [payload_locked_documents_rels["npc-dialoguesID"]],
|
||||
references: [npc_dialogues.id],
|
||||
relationName: "npc-dialogues",
|
||||
}),
|
||||
"labor-classificationsID": one(labor_classifications, {
|
||||
fields: [payload_locked_documents_rels["labor-classificationsID"]],
|
||||
references: [labor_classifications.id],
|
||||
|
|
@ -11561,9 +11652,11 @@ type DatabaseSchema = {
|
|||
game_vehicles_stored_resources: typeof game_vehicles_stored_resources;
|
||||
game_vehicles_void_storage: typeof game_vehicles_void_storage;
|
||||
game_vehicles: typeof game_vehicles;
|
||||
game_npcs_activity_activity_options: typeof game_npcs_activity_activity_options;
|
||||
game_npcs: typeof game_npcs;
|
||||
game_npcs_rels: typeof game_npcs_rels;
|
||||
npc_staffing: typeof npc_staffing;
|
||||
npc_dialogues: typeof npc_dialogues;
|
||||
labor_classifications: typeof labor_classifications;
|
||||
game_event_logs: typeof game_event_logs;
|
||||
users_roles: typeof users_roles;
|
||||
|
|
@ -11757,9 +11850,11 @@ type DatabaseSchema = {
|
|||
relations_game_vehicles_stored_resources: typeof relations_game_vehicles_stored_resources;
|
||||
relations_game_vehicles_void_storage: typeof relations_game_vehicles_void_storage;
|
||||
relations_game_vehicles: typeof relations_game_vehicles;
|
||||
relations_game_npcs_activity_activity_options: typeof relations_game_npcs_activity_activity_options;
|
||||
relations_game_npcs_rels: typeof relations_game_npcs_rels;
|
||||
relations_game_npcs: typeof relations_game_npcs;
|
||||
relations_npc_staffing: typeof relations_npc_staffing;
|
||||
relations_npc_dialogues: typeof relations_npc_dialogues;
|
||||
relations_labor_classifications: typeof relations_labor_classifications;
|
||||
relations_game_event_logs: typeof relations_game_event_logs;
|
||||
relations_users_roles: typeof relations_users_roles;
|
||||
|
|
|
|||
|
|
@ -75,6 +75,8 @@ export interface Config {
|
|||
'game-vehicles': GameVehicle;
|
||||
'game-npcs': GameNpc;
|
||||
'npc-staffing': NpcStaffing;
|
||||
'npc-dialogues': NpcDialogue;
|
||||
'player-flags': PlayerFlag;
|
||||
'labor-classifications': LaborClassification;
|
||||
'game-event-logs': GameEventLog;
|
||||
users: User;
|
||||
|
|
@ -172,6 +174,8 @@ export interface Config {
|
|||
'game-vehicles': GameVehiclesSelect<false> | GameVehiclesSelect<true>;
|
||||
'game-npcs': GameNpcsSelect<false> | GameNpcsSelect<true>;
|
||||
'npc-staffing': NpcStaffingSelect<false> | NpcStaffingSelect<true>;
|
||||
'npc-dialogues': NpcDialoguesSelect<false> | NpcDialoguesSelect<true>;
|
||||
'player-flags': PlayerFlagsSelect<false> | PlayerFlagsSelect<true>;
|
||||
'labor-classifications': LaborClassificationsSelect<false> | LaborClassificationsSelect<true>;
|
||||
'game-event-logs': GameEventLogsSelect<false> | GameEventLogsSelect<true>;
|
||||
users: UsersSelect<false> | UsersSelect<true>;
|
||||
|
|
@ -814,6 +818,16 @@ export interface Role {
|
|||
| 'narrative-events:update'
|
||||
| 'narrative-events:delete'
|
||||
| 'admin:narrative-events:manage'
|
||||
| 'npc-dialogues:create'
|
||||
| 'npc-dialogues:read'
|
||||
| 'npc-dialogues:update'
|
||||
| 'npc-dialogues:delete'
|
||||
| 'admin:npc-dialogues:manage'
|
||||
| 'player-flags:create'
|
||||
| 'player-flags:read'
|
||||
| 'player-flags:update'
|
||||
| 'player-flags:delete'
|
||||
| 'admin:player-flags:manage'
|
||||
| 'mission-files:create'
|
||||
| 'mission-files:read'
|
||||
| 'mission-files:update'
|
||||
|
|
@ -2420,6 +2434,58 @@ export interface GameNpc {
|
|||
*/
|
||||
sells?: (number | Asset)[] | null;
|
||||
};
|
||||
activity?: {
|
||||
/**
|
||||
* How often (in minutes) the current activity reshuffles automatically. Ignored while a forced activity is active.
|
||||
*/
|
||||
intervalMinutes?: number | null;
|
||||
/**
|
||||
* Possible activities this contact can be doing. 'Forced' activities stay active until turned off; otherwise the most likely option (by 'Chance') is picked on each interval.
|
||||
*/
|
||||
activityOptions?:
|
||||
| {
|
||||
/**
|
||||
* What the contact is doing (e.g. 'Coordinating combat androids').
|
||||
*/
|
||||
label: string;
|
||||
/**
|
||||
* Relative chance this activity is picked when reshuffling.
|
||||
*/
|
||||
weight?: number | null;
|
||||
/**
|
||||
* Keep this activity active until turned off (overrides the interval reshuffle).
|
||||
*/
|
||||
forced?: boolean | null;
|
||||
id?: string | null;
|
||||
}[]
|
||||
| null;
|
||||
};
|
||||
/**
|
||||
* This contact's level. Shown on their profile alongside its description.
|
||||
*/
|
||||
level?: number | null;
|
||||
/**
|
||||
* Capabilities / notes for this contact's level (e.g. a bullet list).
|
||||
*/
|
||||
levelDescription?: {
|
||||
root: {
|
||||
type: string;
|
||||
children: {
|
||||
type: any;
|
||||
version: number;
|
||||
[k: string]: unknown;
|
||||
}[];
|
||||
direction: ('ltr' | 'rtl') | null;
|
||||
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
|
||||
indent: number;
|
||||
version: number;
|
||||
};
|
||||
[k: string]: unknown;
|
||||
} | null;
|
||||
/**
|
||||
* Enable conversing with this contact on their profile page. Requires a configured NPC Dialogue flow.
|
||||
*/
|
||||
canMessage?: boolean | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
|
@ -2446,6 +2512,61 @@ export interface NpcStaffing {
|
|||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "npc-dialogues".
|
||||
*/
|
||||
export interface NpcDialogue {
|
||||
id: number;
|
||||
/**
|
||||
* A short label for this conversation (e.g. 'Merchant greeting').
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The contact this conversation belongs to.
|
||||
*/
|
||||
npc: number | GameNpc;
|
||||
flowData:
|
||||
| {
|
||||
[k: string]: unknown;
|
||||
}
|
||||
| unknown[]
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "player-flags".
|
||||
*/
|
||||
export interface PlayerFlag {
|
||||
id: number;
|
||||
/**
|
||||
* The player this flag belongs to.
|
||||
*/
|
||||
user: number | User;
|
||||
/**
|
||||
* Stable key referenced by conversation nodes (e.g. 'met_informant', 'rep_merchants'). Lowercase with underscores.
|
||||
*/
|
||||
key: string;
|
||||
/**
|
||||
* Boolean flags read as true/false; numeric flags track statistics.
|
||||
*/
|
||||
flagType: 'boolean' | 'number';
|
||||
/**
|
||||
* A missing boolean flag counts as false.
|
||||
*/
|
||||
boolValue?: boolean | null;
|
||||
/**
|
||||
* A missing numeric flag counts as 0.
|
||||
*/
|
||||
numberValue?: number | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "game-event-logs".
|
||||
|
|
@ -5677,6 +5798,42 @@ export interface PayloadMcpApiKey {
|
|||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
npcDialogues?: {
|
||||
/**
|
||||
* Allow clients to find npc-dialogues.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create npc-dialogues.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update npc-dialogues.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete npc-dialogues.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
playerFlags?: {
|
||||
/**
|
||||
* Allow clients to find player-flags.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create player-flags.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update player-flags.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete player-flags.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
laborClassifications?: {
|
||||
/**
|
||||
* Allow clients to find labor-classifications.
|
||||
|
|
@ -7032,6 +7189,14 @@ export interface PayloadLockedDocument {
|
|||
relationTo: 'npc-staffing';
|
||||
value: number | NpcStaffing;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'npc-dialogues';
|
||||
value: number | NpcDialogue;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'player-flags';
|
||||
value: number | PlayerFlag;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'labor-classifications';
|
||||
value: number | LaborClassification;
|
||||
|
|
@ -7622,6 +7787,22 @@ export interface GameNpcsSelect<T extends boolean = true> {
|
|||
priceModifier?: T;
|
||||
sells?: T;
|
||||
};
|
||||
activity?:
|
||||
| T
|
||||
| {
|
||||
intervalMinutes?: T;
|
||||
activityOptions?:
|
||||
| T
|
||||
| {
|
||||
label?: T;
|
||||
weight?: T;
|
||||
forced?: T;
|
||||
id?: T;
|
||||
};
|
||||
};
|
||||
level?: T;
|
||||
levelDescription?: T;
|
||||
canMessage?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
|
|
@ -7644,6 +7825,30 @@ export interface NpcStaffingSelect<T extends boolean = true> {
|
|||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "npc-dialogues_select".
|
||||
*/
|
||||
export interface NpcDialoguesSelect<T extends boolean = true> {
|
||||
name?: T;
|
||||
npc?: T;
|
||||
flowData?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "player-flags_select".
|
||||
*/
|
||||
export interface PlayerFlagsSelect<T extends boolean = true> {
|
||||
user?: T;
|
||||
key?: T;
|
||||
flagType?: T;
|
||||
boolValue?: T;
|
||||
numberValue?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "labor-classifications_select".
|
||||
|
|
@ -9862,6 +10067,22 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
|||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
npcDialogues?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
playerFlags?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
laborClassifications?:
|
||||
| T
|
||||
| {
|
||||
|
|
|
|||
|
|
@ -54,6 +54,8 @@ import { GameEventLogs } from "@/collections/game/GameEventLogs";
|
|||
import { GameVehicles } from "@/collections/game/GameVehicles";
|
||||
import { GameNpcs } from "@/collections/game/GameNpcs";
|
||||
import { NpcStaffing } from "@/collections/game/NpcStaffing";
|
||||
import { NpcDialogues } from "@/collections/game/NpcDialogues";
|
||||
import { PlayerFlags } from "@/collections/game/PlayerFlags";
|
||||
import { LaborClassifications } from "@/collections/game/LaborClassifications";
|
||||
import { Experience } from "@/collections/users/Experience";
|
||||
import { BankAccounts } from "@/collections/banking/BankAccounts";
|
||||
|
|
@ -268,6 +270,8 @@ const collections = [
|
|||
GameVehicles,
|
||||
GameNpcs,
|
||||
NpcStaffing,
|
||||
NpcDialogues,
|
||||
PlayerFlags,
|
||||
LaborClassifications,
|
||||
GameEventLogs,
|
||||
|
||||
|
|
|
|||
|
|
@ -538,6 +538,26 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
|
|||
{ value: "admin:narrative-events:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "NPC Dialogue",
|
||||
permissions: [
|
||||
{ value: "npc-dialogues:create", label: "Create" },
|
||||
{ value: "npc-dialogues:read", label: "Read" },
|
||||
{ value: "npc-dialogues:update", label: "Update" },
|
||||
{ value: "npc-dialogues:delete", label: "Delete" },
|
||||
{ value: "admin:npc-dialogues:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Player Flags",
|
||||
permissions: [
|
||||
{ value: "player-flags:create", label: "Create" },
|
||||
{ value: "player-flags:read", label: "Read" },
|
||||
{ value: "player-flags:update", label: "Update" },
|
||||
{ value: "player-flags:delete", label: "Delete" },
|
||||
{ value: "admin:player-flags:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
|
||||
// ---- Server --------------------------------------------------------------
|
||||
{
|
||||
|
|
@ -984,6 +1004,16 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
|
|||
"narrative-events:update",
|
||||
"narrative-events:delete",
|
||||
"admin:narrative-events:manage",
|
||||
"npc-dialogues:create",
|
||||
"npc-dialogues:read",
|
||||
"npc-dialogues:update",
|
||||
"npc-dialogues:delete",
|
||||
"admin:npc-dialogues:manage",
|
||||
"player-flags:create",
|
||||
"player-flags:read",
|
||||
"player-flags:update",
|
||||
"player-flags:delete",
|
||||
"admin:player-flags:manage",
|
||||
"mission-files:create",
|
||||
"mission-files:read",
|
||||
"mission-files:update",
|
||||
|
|
|
|||
|
|
@ -115,6 +115,7 @@ export const EventTypes = {
|
|||
|
||||
// NPCs
|
||||
NpcGenerate: "npc:generate",
|
||||
NpcDialogue: "npc:dialogue",
|
||||
|
||||
// Account
|
||||
AccountPasswordChange: "account:password-change",
|
||||
|
|
|
|||
Loading…
Reference in a new issue