Compare commits
No commits in common. "88e89c9e55bd9243d260335bd91c63bbcca3756a" and "35a88ccd8f74f1fcd91b9ccfa634b20c29938184" have entirely different histories.
88e89c9e55
...
35a88ccd8f
37 changed files with 380 additions and 84121 deletions
|
|
@ -73,11 +73,6 @@ APP_PORT=3000
|
|||
# DISCORD_STAFF_ROLE_IDS=
|
||||
# DISCORD_ATTENDANCE_POLL_MS=
|
||||
# DISCORD_NOTIFICATION_POLL_MS=
|
||||
# NPC dispatch: dialogue event effects flagged "Post to Discord" are posted as
|
||||
# amber embeds to this channel by the bot poll service (queued on the game
|
||||
# event log entry until posted). Unset disables posting.
|
||||
# DISCORD_NPC_EVENT_CHANNEL_ID=
|
||||
# DISCORD_NPC_EVENT_POLL_MS=
|
||||
|
||||
# --- Usage analytics (Microsoft Clarity) ---
|
||||
# Project ID from clarity.microsoft.com (Settings > Project ID). Optional;
|
||||
|
|
|
|||
|
|
@ -145,13 +145,6 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
|
|||
- **Dedup**: no DB state. The notice embeds a stable per-Friday `<t:epoch:D>` token; before posting, the service scans the last 100 channel messages for it, so restarts never double-post.
|
||||
- **Claim credit**: when a non-cancelled mission later appears on that Friday whose creator is not a superuser (`getFridayClaimant` in `src/lib/intelligence/fridayOpsNotice.ts`, earliest `createdAt` wins; superuser- or staff-created missions never claim), the service edits the notice in place, appending "This slot was claimed by \<user\>. Thank you for hosting for our community!". If the claiming op is later cancelled or deleted, the claim line is stripped and the notice reverts to the open-slot state (a claim swap between polls re-credits the new claimant). Idempotent via a claim-line check on the message content; the edit half runs whenever the notice is still in the recent-messages window, regardless of day, so a Thursday claim still lands.
|
||||
|
||||
### G. NPC dispatch announcements (dialogue events → channel)
|
||||
|
||||
- **Trigger**: a dialogue event node with an emit/reward/flag effect authored with `discord: true`. `runEffect` passes `discordRequested` into `emitGameEvent`, which persists it on the `game-event-logs` entry; nothing talks to Discord at emit time.
|
||||
- **Poll loop** (`src/bot/services/npcEventAnnouncements.ts`, every `DISCORD_NPC_EVENT_POLL_MS`, default 60s): query entries with `discordRequested = true` and no `discordAnnouncedAt`, oldest first, cap 5 posts/tick. Channel from `DISCORD_NPC_EVENT_CHANNEL_ID`; unset disables the service.
|
||||
- **Embed**: amber "NPC Dispatch" with the event message, a `<t:epoch:R>` reported field, and a Source link to the speaking NPC's contact page when the event targets `game-npcs`.
|
||||
- **Idempotency**: one-shot markers on the log entry (`discordAnnouncedAt` + `discordMessageId`), stamped only after a successful send; failures stay queued and retry next tick.
|
||||
|
||||
### Authz (`src/bot/lib/roles.ts`)
|
||||
|
||||
`isStaff(member)`: caller has any `DISCORD_STAFF_ROLE_IDS`, **or** their linked Payload user has roles `admin`/`developer`. RSVP/signup/link are open to all members. The bot performs Payload writes with `overrideAccess` and relies on these checks + its own validations.
|
||||
|
|
@ -174,8 +167,6 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
|
|||
| `DISCORD_ANNOUNCE_MENTION_ROLE_ID` | no | Role auto-mentioned in `/announce` when called without a message (compose dialog). Unset disables it |
|
||||
| `DISCORD_SIDE_OPS_POLL_MS` | no | default 1800000 (30 min) |
|
||||
| `DISCORD_PRESENCE_POLL_MS` | no | default 30000 (30s); reconcile loop for the bot's Rich Presence from the `discord-presence` Global |
|
||||
| `DISCORD_NPC_EVENT_CHANNEL_ID` | no | NPC dispatch channel for dialogue events flagged "Post to Discord"; unset disables posting |
|
||||
| `DISCORD_NPC_EVENT_POLL_MS` | no | default 60000 (60s) |
|
||||
|
||||
`APP_URL` already exists — used for login links in DMs.
|
||||
|
||||
|
|
|
|||
|
|
@ -10,16 +10,12 @@ import { notifyUser } from "@/lib/notifications";
|
|||
import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
|
||||
import { markNodeRead } from "@/lib/npc-dialogue/states";
|
||||
import { resolveAttachments } from "@/lib/npc-dialogue/attachments";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import type {
|
||||
ChoiceGate,
|
||||
DialogueFlagOp,
|
||||
FlowData,
|
||||
NpcDialogueEffect,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
import { hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
|
||||
|
||||
interface ActionResult<T = undefined> {
|
||||
success: boolean;
|
||||
|
|
@ -111,10 +107,6 @@ async function runEffect(
|
|||
targetCollection: "game-npcs",
|
||||
targetId: npcId,
|
||||
data: { effect: "emit" },
|
||||
// Author override: "public" puts the entry in every member's feed;
|
||||
// undefined keeps the restricted narrative default (see visibility.ts).
|
||||
visibility: effect.eventVisibility,
|
||||
discordRequested: effect.discord,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
|
@ -127,8 +119,6 @@ async function runEffect(
|
|||
targetCollection: "game-npcs",
|
||||
targetId: npcId,
|
||||
data: { effect: "reward", unconfigured: true },
|
||||
visibility: effect.eventVisibility,
|
||||
discordRequested: effect.discord,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
|
@ -156,8 +146,6 @@ async function runEffect(
|
|||
targetCollection: "game-npcs",
|
||||
targetId: npcId,
|
||||
data: { effect: "flag", key, op, amount },
|
||||
visibility: effect.eventVisibility,
|
||||
discordRequested: effect.discord,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
|
@ -234,7 +222,7 @@ export async function evaluateNpcDialogueChoices(
|
|||
const gates: ChoiceGate[] = [];
|
||||
for (const choice of node.data.choices ?? []) {
|
||||
const showLocked = Boolean(choice.lockedHint?.trim());
|
||||
if (!choice.condition || hasEmptyConditionKey(choice.condition)) {
|
||||
if (!choice.condition?.key?.trim()) {
|
||||
gates.push({ pass: true, showLocked });
|
||||
continue;
|
||||
}
|
||||
|
|
@ -279,23 +267,14 @@ export async function resolveNpcDialogueTexts(
|
|||
const keys = collectNodeTokens(node);
|
||||
const values: Record<string, string> = {};
|
||||
const countdowns: Record<string, string> = {};
|
||||
const truths: Record<string, { bool: boolean; num: number }> = {};
|
||||
for (const key of keys) {
|
||||
const flag = await readFlag(payload, user.id as number, key);
|
||||
values[key] = flag.text;
|
||||
// Countdown leaf: pending flags tick toward activation, active ones read
|
||||
// "done", missing ones render nothing.
|
||||
countdowns[key] = flag.activatesAt ?? (flag.exists ? "done" : "");
|
||||
// Truth inputs for ternary conditions (`{{ key ? .. : .. }}`).
|
||||
truths[key] = { bool: flag.bool, num: flag.num };
|
||||
}
|
||||
const resolved = resolveNodeTexts(node, values, countdowns, truths);
|
||||
// Attachments ride the same round trip: ids become renderable file
|
||||
// references here, so the client never guesses media URLs and deleted
|
||||
// files simply drop off instead of rendering dead chips.
|
||||
const attachments = await resolveAttachments(payload, node.data.attachments);
|
||||
if (attachments.length > 0) resolved.attachments = attachments;
|
||||
return { success: true, data: resolved };
|
||||
return { success: true, data: resolveNodeTexts(node, values, countdowns) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") {
|
||||
|
|
@ -305,94 +284,3 @@ export async function resolveNpcDialogueTexts(
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that the reading user has seen one conversation node, so its NEW
|
||||
* badge clears on every device. Idempotent; the client fires this off
|
||||
* fire-and-forget as lines land in the log.
|
||||
*/
|
||||
export async function markNpcDialogueNodeRead(
|
||||
dialogueId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!Number.isInteger(dialogueId) || dialogueId <= 0 || !nodeId.trim()) {
|
||||
return { success: false, error: "Invalid conversation node reference." };
|
||||
}
|
||||
await markNodeRead(payload, user.id as number, dialogueId, nodeId.trim());
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
/** File types authors may attach to a conversation node. */
|
||||
const ATTACHMENT_TYPES = new Set([
|
||||
"text/plain",
|
||||
"application/pdf",
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/webp",
|
||||
"image/gif",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Upload a file to attach to a conversation node (intercept transcripts,
|
||||
* sealed orders, reference images). The bytes land in `media`; flowData only
|
||||
* keeps the returned pointer, and resolveNpcDialogueTexts turns it back into
|
||||
* a URL per read. Gated like dialogue authoring (npc-dialogues:update) since
|
||||
* this stores files the whole unit will be served.
|
||||
*/
|
||||
export async function uploadNpcDialogueAttachment(
|
||||
formData: FormData,
|
||||
): Promise<ActionResult<{ mediaId: number; filename: string; mimeType: string }>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
const allowed = await hasPermission(payload, user, "npc-dialogues:update");
|
||||
if (!allowed) {
|
||||
return { success: false, error: "You are not allowed to edit conversations." };
|
||||
}
|
||||
|
||||
const file = formData.get("file");
|
||||
if (!(file instanceof File)) {
|
||||
return { success: false, error: "No file was provided." };
|
||||
}
|
||||
if (!ATTACHMENT_TYPES.has(file.type)) {
|
||||
return { success: false, error: "Attachments must be text, PDF, or image files." };
|
||||
}
|
||||
if (file.size > 8 * 1024 * 1024) {
|
||||
return { success: false, error: "Attachments must be 8 MB or smaller." };
|
||||
}
|
||||
|
||||
const doc = await payload.create({
|
||||
collection: "media",
|
||||
data: {
|
||||
alt: file.name.replace(/\.[^/.]+$/, "").replace(/[^a-zA-Z0-9 _-]/g, "").trim() || "Attachment",
|
||||
},
|
||||
file: {
|
||||
data: Buffer.from(await file.arrayBuffer()),
|
||||
mimetype: file.type,
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
},
|
||||
overrideAccess: true,
|
||||
});
|
||||
if (!doc.filename) {
|
||||
return { success: false, error: "Upload failed: no file was stored." };
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
data: { mediaId: doc.id, filename: doc.filename, mimeType: file.type },
|
||||
};
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") {
|
||||
return { success: false, error: "You must be logged in." };
|
||||
}
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import type { GameNpc, MarketListing, NpcStaffing } from "@/payload-types";
|
|||
import type { FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
import { selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
||||
import { evaluateCondition } from "@/lib/npc-dialogue/flags";
|
||||
import { listSeenNodeIds } from "@/lib/npc-dialogue/states";
|
||||
import { NpcProfile } from "@/components/frontend/personnel/NpcProfile";
|
||||
import { NpcConversation } from "@/components/frontend/personnel/NpcConversation";
|
||||
import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard";
|
||||
|
|
@ -159,22 +158,12 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
? await pickDialogue(payload, id, user?.id as number | undefined)
|
||||
: null;
|
||||
|
||||
// Server-side NEW badges: which nodes has this player already read? Empty
|
||||
// when signed out or there's no conversation. Sourced from npc-dialogue-
|
||||
// states so progress follows the account across devices.
|
||||
const seenNodeIds =
|
||||
dialogue && user
|
||||
? await listSeenNodeIds(payload, user.id as number, dialogue.id)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="p-5 flex flex-col gap-6">
|
||||
<NpcProfile
|
||||
npc={npc}
|
||||
listings={listings}
|
||||
conversationSlot={
|
||||
<NpcConversation npc={npc} dialogue={dialogue} initialSeenNodeIds={seenNodeIds} />
|
||||
}
|
||||
conversationSlot={<NpcConversation npc={npc} dialogue={dialogue} />}
|
||||
employmentSlot={
|
||||
<EmploymentCard
|
||||
employment={employment}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ Standalone long-running process (`bun run bot`). Imports `@payload-config` direc
|
|||
|
||||
## Env
|
||||
|
||||
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `DISCORD_NPC_EVENT_CHANNEL_ID` (NPC dispatch channel for dialogue events; unset disables posting), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s), `DISCORD_NPC_EVENT_POLL_MS` (default 60s). Logs through `payload.logger`.
|
||||
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s). Logs through `payload.logger`.
|
||||
|
||||
## Structure
|
||||
|
||||
|
|
@ -39,7 +39,6 @@ bot/
|
|||
evaluationReminders.ts # Post-mission evaluation reminder DMs (one-shot marker on Missions)
|
||||
imminentReminders.ts # Pre-op reminder: thread on the roll-call message + attendee pings (one-shot marker on Missions)
|
||||
fridayOpsNotice.ts # Weekly notice: pings Community Zeus in #side-ops when the upcoming Friday has no op
|
||||
npcEventAnnouncements.ts # Poll game-event-logs flagged discordRequested → post amber "NPC Dispatch" embeds, stamp discordAnnouncedAt + discordMessageId
|
||||
signup.ts # Signup service logic
|
||||
transferRequests.ts # Polls assignment transfer requests awaiting leader decision
|
||||
transferDelivery.ts # Transfer leader-request / rejection / info delivery DMs
|
||||
|
|
@ -111,7 +110,6 @@ A poll loop (`services/discordPresence.ts`, `DISCORD_PRESENCE_POLL_MS`, default
|
|||
| Evaluation reminder logic | `bot/services/evaluationReminders.ts` + `src/lib/evaluations/reminders.ts` |
|
||||
| Imminent-op reminder logic | `bot/services/imminentReminders.ts` + `src/lib/intelligence/imminentReminders.ts` |
|
||||
| Friday open-slot notice | `bot/services/fridayOpsNotice.ts` + `src/lib/intelligence/fridayOpsNotice.ts` |
|
||||
| NPC dispatch posting (dialogue events) | `bot/services/npcEventAnnouncements.ts` + `discordRequested`/`discordAnnouncedAt` on game-event-logs |
|
||||
| Transfer workflow | `bot/services/transferRequests.ts` + `lib/transferMessaging.ts` |
|
||||
| User lookup patterns | `bot/lib/resolve.ts` |
|
||||
| Edit bot Rich Presence (command) | `bot/commands/discordPresence.ts` (+ Global `src/collections/discord/DiscordPresence.ts`) |
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ export interface BotConfig {
|
|||
communityZeusRoleId: string | null;
|
||||
changelogChannelId: string | null;
|
||||
announceMentionRoleId: string | null;
|
||||
npcEventChannelId: string | null;
|
||||
attendancePollMs: number;
|
||||
notificationPollMs: number;
|
||||
evaluationPollMs: number;
|
||||
|
|
@ -18,7 +17,6 @@ export interface BotConfig {
|
|||
sideOpsNoticePollMs: number;
|
||||
achievementPollMs: number;
|
||||
presencePollMs: number;
|
||||
npcEventPollMs: number;
|
||||
}
|
||||
|
||||
const required = (name: string): string => {
|
||||
|
|
@ -60,7 +58,6 @@ export const botConfig: BotConfig = {
|
|||
communityZeusRoleId: optional("DISCORD_COMMUNITY_ZEUS_ROLE_ID"),
|
||||
changelogChannelId: optional("DISCORD_CHANGELOG_CHANNEL_ID"),
|
||||
announceMentionRoleId: optional("DISCORD_ANNOUNCE_MENTION_ROLE_ID"),
|
||||
npcEventChannelId: optional("DISCORD_NPC_EVENT_CHANNEL_ID"),
|
||||
attendancePollMs: pollMs("DISCORD_ATTENDANCE_POLL_MS", 60_000),
|
||||
notificationPollMs: pollMs("DISCORD_NOTIFICATION_POLL_MS", 20_000),
|
||||
evaluationPollMs: pollMs("DISCORD_EVALUATION_POLL_MS", 60_000),
|
||||
|
|
@ -69,5 +66,4 @@ export const botConfig: BotConfig = {
|
|||
sideOpsNoticePollMs: pollMs("DISCORD_SIDE_OPS_POLL_MS", 1_800_000),
|
||||
achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000),
|
||||
presencePollMs: pollMs("DISCORD_PRESENCE_POLL_MS", 30_000),
|
||||
npcEventPollMs: pollMs("DISCORD_NPC_EVENT_POLL_MS", 60_000),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import { start as startReadyReminders } from "./readyReminders";
|
|||
import { start as startImminentReminders } from "./imminentReminders";
|
||||
import { start as startFridayOpsNotice } from "./fridayOpsNotice";
|
||||
import { start as startAchievementAnnouncements } from "./achievementAnnouncements";
|
||||
import { start as startNpcEventAnnouncements } from "./npcEventAnnouncements";
|
||||
import { start as startDiscordPresence } from "./discordPresence";
|
||||
|
||||
export type ServiceStarter = (client: Client, payload: Payload) => Promise<void> | void;
|
||||
|
|
@ -22,6 +21,5 @@ export const services: ServiceStarter[] = [
|
|||
startImminentReminders,
|
||||
startFridayOpsNotice,
|
||||
startAchievementAnnouncements,
|
||||
startNpcEventAnnouncements,
|
||||
startDiscordPresence,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,114 +0,0 @@
|
|||
import { type Client, EmbedBuilder } from "discord.js";
|
||||
import type { Payload } from "payload";
|
||||
|
||||
import { botConfig } from "@/bot/config";
|
||||
import type { GameEventLog } from "@/payload-types";
|
||||
|
||||
/**
|
||||
* NPC dispatch announcements: poll game-event-log entries that a dialogue
|
||||
* event effect flagged with `discordRequested` but that were never posted,
|
||||
* send one embed per event to the NPC dispatch channel, then stamp
|
||||
* `discordAnnouncedAt` + `discordMessageId` on the log entry.
|
||||
*
|
||||
* The stamp happens only after a successful send, so a failed or missing
|
||||
* post stays queued and retries on the next tick. Per-tick cap keeps the
|
||||
* channel (and Discord rate limits) calm when a session replays many beats.
|
||||
*
|
||||
* The Next app never talks to Discord; this service owns the bot side.
|
||||
*/
|
||||
|
||||
const MAX_POSTS_PER_TICK = 5;
|
||||
const BATCH_LIMIT = 20;
|
||||
|
||||
/** Minimal text-channel shape we rely on (mirrors achievementAnnouncements). */
|
||||
type DispatchChannel = {
|
||||
send(payload: { embeds: EmbedBuilder[] }): Promise<{ id: string }>;
|
||||
};
|
||||
|
||||
let running = false;
|
||||
|
||||
const errorMessage = (error: unknown): string =>
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
|
||||
const buildEmbed = (doc: GameEventLog): EmbedBuilder => {
|
||||
const epoch = Math.floor(new Date(doc.timestamp).getTime() / 1000);
|
||||
const embed = new EmbedBuilder()
|
||||
.setTitle("NPC Dispatch")
|
||||
.setDescription(doc.message.slice(0, 1000))
|
||||
.setColor(0xf59e0b)
|
||||
.addFields({ name: "Reported", value: `<t:${epoch}:R>`, inline: true });
|
||||
// Dialogue events target the NPC that spoke; link its contact page so the
|
||||
// reader can find who said it.
|
||||
if (doc.targetCollection === "game-npcs" && doc.targetId) {
|
||||
embed.addFields({
|
||||
name: "Source",
|
||||
value: `[Contact file](${botConfig.appUrl}/personnel/contacts/${doc.targetId})`,
|
||||
inline: true,
|
||||
});
|
||||
}
|
||||
return embed;
|
||||
};
|
||||
|
||||
const poll = async (client: Client, payload: Payload): Promise<void> => {
|
||||
if (running) return;
|
||||
running = true;
|
||||
try {
|
||||
const channelId = botConfig.npcEventChannelId;
|
||||
if (!channelId) return;
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: {
|
||||
discordRequested: { equals: true },
|
||||
discordAnnouncedAt: { exists: false },
|
||||
},
|
||||
sort: "timestamp",
|
||||
limit: BATCH_LIMIT,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
if (res.docs.length === 0) return;
|
||||
|
||||
const channel = await client.channels.fetch(channelId);
|
||||
if (!channel || !("send" in channel)) {
|
||||
throw new Error(`[Bot] NPC dispatch channel ${channelId} is not a text channel.`);
|
||||
}
|
||||
const textChannel = channel as unknown as DispatchChannel;
|
||||
|
||||
let posted = 0;
|
||||
for (const doc of res.docs.slice(0, MAX_POSTS_PER_TICK)) {
|
||||
try {
|
||||
const message = await textChannel.send({ embeds: [buildEmbed(doc)] });
|
||||
await payload.update({
|
||||
collection: "game-event-logs",
|
||||
id: doc.id,
|
||||
data: { discordAnnouncedAt: new Date().toISOString(), discordMessageId: message.id },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
posted += 1;
|
||||
} catch (error) {
|
||||
// Leave this entry queued so the next tick retries it.
|
||||
payload.logger.error(
|
||||
`[Bot] NPC dispatch post for event ${doc.id} failed: ${errorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (posted > 0) {
|
||||
payload.logger.info(`[Bot] NPC dispatch announcements posted: ${posted}`);
|
||||
}
|
||||
} catch (error) {
|
||||
payload.logger.error(`[Bot] NPC dispatch poll failed: ${errorMessage(error)}`);
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
|
||||
export const start = (client: Client, payload: Payload): void => {
|
||||
payload.logger.info("[Bot] NPC dispatch announcement service started");
|
||||
void poll(client, payload);
|
||||
setInterval(() => {
|
||||
void poll(client, payload);
|
||||
}, botConfig.npcEventPollMs);
|
||||
};
|
||||
|
|
@ -173,28 +173,5 @@ export const GameEventLogs: CollectionConfig = {
|
|||
name: "data",
|
||||
type: "json",
|
||||
},
|
||||
{
|
||||
name: "discordRequested",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
index: true,
|
||||
admin: {
|
||||
description:
|
||||
"Queued for the bot's NPC dispatch channel. Set at emit time by dialogue event effects; the poll service stamps the announcement columns once posted.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "discordAnnouncedAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: "Set by the bot when the dispatch posts. Empty with a request above means queued or retrying.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "discordMessageId",
|
||||
type: "text",
|
||||
admin: { readOnly: true, description: "Discord message id of the posted dispatch." },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,90 +0,0 @@
|
|||
import type { CollectionConfig } from "payload";
|
||||
import hasRoles from "@/utils/access-control/hasRoles";
|
||||
|
||||
const STAFF_ROLES = ["admin", "developer"] as const;
|
||||
|
||||
function isStaff(user: Parameters<typeof hasRoles>[1]): boolean {
|
||||
return hasRoles(["admin", "developer"], user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-user read markers for conversation nodes, powering the "NEW" badges in
|
||||
* the NPC conversation UI. One row per (user, dialogue, node): a node badges
|
||||
* NEW until this player has read it at least once, and GM edits never
|
||||
* re-flag already-read content. Replaces the old per-browser localStorage
|
||||
* tracking, which reset across devices.
|
||||
*/
|
||||
export const NpcDialogueStates: CollectionConfig = {
|
||||
slug: "npc-dialogue-states",
|
||||
labels: {
|
||||
singular: "Conversation Read Marker",
|
||||
plural: "Conversation Read Markers",
|
||||
},
|
||||
admin: {
|
||||
group: "Game",
|
||||
useAsTitle: "nodeId",
|
||||
defaultColumns: ["user", "dialogue", "nodeId", "readAt"],
|
||||
description: "Per-user read markers for NPC conversation nodes (NEW badges).",
|
||||
// The admin-panel `user` is a client-side user type, so check its roles
|
||||
// structurally rather than through hasRoles.
|
||||
hidden: ({ user }) =>
|
||||
user?.collection !== "users" ||
|
||||
!STAFF_ROLES.some((role) => (user.roles ?? []).includes(role)),
|
||||
},
|
||||
access: {
|
||||
// Users can read/create their own markers; staff see everything.
|
||||
read: ({ req }) => {
|
||||
if (!req.user) return false;
|
||||
if (isStaff(req.user)) return true;
|
||||
return { user: { equals: req.user.id } };
|
||||
},
|
||||
create: ({ req }) => !!req.user,
|
||||
update: ({ req }) => {
|
||||
if (!req.user) return false;
|
||||
if (isStaff(req.user)) return true;
|
||||
return { user: { equals: req.user.id } };
|
||||
},
|
||||
delete: ({ req }) => isStaff(req.user),
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "user",
|
||||
type: "relationship",
|
||||
relationTo: "users",
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: "dialogue",
|
||||
type: "relationship",
|
||||
relationTo: "npc-dialogues",
|
||||
required: true,
|
||||
index: true,
|
||||
admin: {
|
||||
description: "The conversation this marker belongs to.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "nodeId",
|
||||
type: "text",
|
||||
required: true,
|
||||
admin: {
|
||||
description: "Flowchart node id the player has read.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "readAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
description: "When the user first read the node.",
|
||||
},
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
// One marker per (user, dialogue, node); the mark-read action upserts on it.
|
||||
fields: ["user", "dialogue", "nodeId"],
|
||||
unique: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
@ -1,205 +0,0 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||
|
||||
/** Friendly color names offered by the color picker (mirrors DialogueText). */
|
||||
const COLOR_CHOICES = [
|
||||
"red",
|
||||
"amber",
|
||||
"cyan",
|
||||
"emerald",
|
||||
"green",
|
||||
"sky",
|
||||
"violet",
|
||||
"purple",
|
||||
"pink",
|
||||
"slate",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Textarea for authored dialogue strings with a formatting toolbar, a
|
||||
* right-click markup menu, and a live `DialogueText` preview. Storage stays
|
||||
* the plain custom-markup string (this only wraps the selection in tokens);
|
||||
* one component serves every interpolatable field (line, narration, lead-in,
|
||||
* closing, tooltip, lock message) so authoring affordances are consistent.
|
||||
*/
|
||||
export function MarkupEditor({
|
||||
value,
|
||||
onChange,
|
||||
rows = 4,
|
||||
placeholder,
|
||||
className,
|
||||
textareaRef,
|
||||
preview = true,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (next: string) => void;
|
||||
rows?: number;
|
||||
placeholder?: string;
|
||||
/** Extra classes for the textarea itself (sizing/colors per surface). */
|
||||
className?: string;
|
||||
/** Optional external ref, e.g. the line box's auto-grow logic. */
|
||||
textareaRef?: React.RefObject<HTMLTextAreaElement | null>;
|
||||
/** Show the rendered preview under the box (default true). */
|
||||
preview?: boolean;
|
||||
}) {
|
||||
const innerRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const el = () => textareaRef?.current ?? innerRef.current;
|
||||
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);
|
||||
|
||||
// Close the context menu on any outside click or Escape.
|
||||
useEffect(() => {
|
||||
if (!menu) return;
|
||||
const close = () => setMenu(null);
|
||||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setMenu(null);
|
||||
window.addEventListener("mousedown", close);
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
window.removeEventListener("mousedown", close);
|
||||
window.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, [menu]);
|
||||
|
||||
/** Replace the selection with `before + sel + after`, keeping it selected. */
|
||||
const wrap = (before: string, after: string) => {
|
||||
const node = el();
|
||||
if (!node) return;
|
||||
const start = node.selectionStart;
|
||||
const end = node.selectionEnd;
|
||||
const selected = value.slice(start, end);
|
||||
onChange(value.slice(0, start) + before + selected + after + value.slice(end));
|
||||
requestAnimationFrame(() => {
|
||||
node.focus();
|
||||
node.setSelectionRange(start + before.length, start + before.length + selected.length);
|
||||
});
|
||||
};
|
||||
|
||||
/** Toggle a line prefix (`- `, `1. `) across the selected lines. */
|
||||
const toggleLines = (kind: "ul" | "ol") => {
|
||||
const node = el();
|
||||
if (!node) return;
|
||||
const lineStart = value.lastIndexOf("\n", node.selectionStart - 1) + 1;
|
||||
const nextBreak = value.indexOf("\n", node.selectionEnd);
|
||||
const lineEnd = nextBreak === -1 ? value.length : nextBreak;
|
||||
const lines = value.slice(lineStart, lineEnd).split("\n");
|
||||
const marker = kind === "ul" ? /^(\s*)[-*]\s/ : /^(\s*)\d+[.)]\s/;
|
||||
const allMarked = lines.every((line) => marker.test(line));
|
||||
const nextLines = lines.map((line, index) => {
|
||||
if (allMarked) return line.replace(marker, "$1");
|
||||
const stripped = line.replace(marker, "$1");
|
||||
return kind === "ul" ? `- ${stripped}` : `${index + 1}. ${stripped}`;
|
||||
});
|
||||
onChange(value.slice(0, lineStart) + nextLines.join("\n") + value.slice(lineEnd));
|
||||
requestAnimationFrame(() => node.focus());
|
||||
};
|
||||
|
||||
const insertLink = () => {
|
||||
const node = el();
|
||||
if (!node) return;
|
||||
const start = node.selectionStart;
|
||||
const end = node.selectionEnd;
|
||||
const selected = value.slice(start, end) || "label";
|
||||
onChange(`${value.slice(0, start)}[${selected}](${value.slice(end)})`);
|
||||
requestAnimationFrame(() => {
|
||||
node.focus();
|
||||
const urlAt = start + selected.length + 3;
|
||||
node.setSelectionRange(urlAt, urlAt);
|
||||
});
|
||||
};
|
||||
|
||||
const toolbarButton =
|
||||
"h-6 min-w-6 rounded-sm border border-white/15 bg-black/40 px-1.5 font-mono text-[11px] text-white/70 transition-colors hover:border-cyan-400/50 hover:text-cyan-300";
|
||||
|
||||
const menuItems: { label: string; run: () => void }[] = [
|
||||
{ label: "** bold **", run: () => wrap("**", "**") },
|
||||
{ label: "* italic *", run: () => wrap("*", "*") },
|
||||
{ label: "` code `", run: () => wrap("`", "`") },
|
||||
{ label: "[ link ]", run: insertLink },
|
||||
{ label: "- bullet list", run: () => toggleLines("ul") },
|
||||
{ label: "1. numbered list", run: () => toggleLines("ol") },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
<button type="button" title="Bold" onClick={() => wrap("**", "**")} className={`${toolbarButton} font-bold`}>
|
||||
B
|
||||
</button>
|
||||
<button type="button" title="Italic" onClick={() => wrap("*", "*")} className={`${toolbarButton} italic`}>
|
||||
I
|
||||
</button>
|
||||
<button type="button" title="Code" onClick={() => wrap("`", "`")} className={toolbarButton}>
|
||||
{"<>"}
|
||||
</button>
|
||||
<select
|
||||
value=""
|
||||
title="Wrap in a color"
|
||||
onChange={(e) => e.target.value && wrap(`{${e.target.value}}`, "{/}")}
|
||||
className="h-6 rounded-sm border border-white/15 bg-zinc-800 px-1 text-[11px] text-white/70"
|
||||
>
|
||||
<option value="">color</option>
|
||||
{COLOR_CHOICES.map((color) => (
|
||||
<option key={color} value={color}>
|
||||
{color}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button type="button" title="Link (opens in a popup)" onClick={insertLink} className={toolbarButton}>
|
||||
link
|
||||
</button>
|
||||
<button type="button" title="Bullet list" onClick={() => toggleLines("ul")} className={toolbarButton}>
|
||||
• list
|
||||
</button>
|
||||
<button type="button" title="Numbered list" onClick={() => toggleLines("ol")} className={toolbarButton}>
|
||||
1. list
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
ref={textareaRef ?? innerRef}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
setMenu({ x: e.clientX, y: e.clientY });
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
rows={rows}
|
||||
className={
|
||||
className ??
|
||||
"bg-zinc-800 border border-white/20 rounded px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
}
|
||||
/>
|
||||
{preview && value.trim() !== "" && (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-[9px] uppercase tracking-wider text-white/30">Preview</span>
|
||||
<div className="min-w-0 break-words rounded border border-white/10 bg-black/40 px-2 py-1.5 text-sm text-white/80">
|
||||
<DialogueText text={value} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{menu && (
|
||||
<div
|
||||
className="fixed z-[120] flex min-w-40 flex-col rounded border border-zinc-700 bg-zinc-900 py-1 shadow-xl"
|
||||
style={{ left: menu.x, top: menu.y }}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
{menuItems.map((item) => (
|
||||
<button
|
||||
key={item.label}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
item.run();
|
||||
setMenu(null);
|
||||
}}
|
||||
className="px-3 py-1 text-left font-mono text-xs text-white/70 hover:bg-zinc-800 hover:text-cyan-300"
|
||||
>
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -12,14 +12,12 @@ import {
|
|||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
|
||||
import type {
|
||||
DialogueAttachment,
|
||||
DialogueCondition,
|
||||
DialogueConditionGroup,
|
||||
DialogueFlagCondition,
|
||||
DialogueFlagOp,
|
||||
DialogueNext,
|
||||
DialogueNode,
|
||||
|
|
@ -27,10 +25,8 @@ import type {
|
|||
NpcDialogueEffect,
|
||||
NpcDialogueNodeType,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
import { conditionSummary, EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
|
||||
import { EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
|
||||
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
|
||||
import { MarkupEditor } from "./MarkupEditor";
|
||||
import { uploadNpcDialogueAttachment } from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
||||
|
||||
interface NodeEditDialogProps {
|
||||
readonly node: DialogueNode | null;
|
||||
|
|
@ -56,7 +52,7 @@ const FLAG_OP_LABELS: Record<DialogueFlagOp, string> = {
|
|||
add: "Add to number",
|
||||
};
|
||||
|
||||
const CONDITION_OP_LABELS: Record<DialogueFlagCondition["op"], string> = {
|
||||
const CONDITION_OP_LABELS: Record<DialogueCondition["op"], string> = {
|
||||
is_true: "is true",
|
||||
is_false: "is false",
|
||||
gte: "is at least",
|
||||
|
|
@ -66,18 +62,8 @@ const CONDITION_OP_LABELS: Record<DialogueFlagCondition["op"], string> = {
|
|||
eq: "equals",
|
||||
};
|
||||
|
||||
/** Group combinators, in UI order. Groups are single-level over leaves. */
|
||||
const GROUP_OP_LABELS: Record<DialogueConditionGroup["op"], string> = {
|
||||
and: "All conditions match (AND)",
|
||||
or: "Any condition matches (OR)",
|
||||
nor: "No condition matches (NOR)",
|
||||
};
|
||||
|
||||
/** Ops that compare against a number (everything except is_true/is_false). */
|
||||
const NUMERIC_OPS: DialogueFlagCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"];
|
||||
|
||||
/** A blank leaf used when switching into single mode or adding a group row. */
|
||||
const EMPTY_LEAF: DialogueFlagCondition = { kind: "flag", key: "", op: "is_true" };
|
||||
const NUMERIC_OPS: DialogueCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"];
|
||||
|
||||
/** Max height (px) the dialogue Line box auto-grows to. Longer content scrolls
|
||||
* inside the box from here; the user can still drag-resize it taller. */
|
||||
|
|
@ -112,7 +98,7 @@ function nodeLabel(node: DialogueNode): string {
|
|||
break;
|
||||
case "condition": {
|
||||
const c = d.condition;
|
||||
preview = c ? conditionSummary(c) : "Condition";
|
||||
preview = c ? `flag "${c.key || "?"}" ${CONDITION_OP_LABELS[c.op]}` : "Condition";
|
||||
break;
|
||||
}
|
||||
default:
|
||||
|
|
@ -185,7 +171,10 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
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)) });
|
||||
|
|
@ -203,12 +192,15 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
if (ordered) patch({ choices: ordered });
|
||||
};
|
||||
|
||||
/** Toggle/replace a choice's visibility gate; null removes the gate. */
|
||||
const setChoiceCondition = (index: number, next: DialogueCondition | null) =>
|
||||
/** Toggle/update a choice's visibility gate; null removes the gate. */
|
||||
const setChoiceCondition = (index: number, partial: Partial<DialogueCondition> | null) =>
|
||||
patch({
|
||||
choices: (draft.choices ?? []).map((c, i) =>
|
||||
i === index ? { ...c, condition: next ?? undefined } : c,
|
||||
),
|
||||
choices: (draft.choices ?? []).map((c, i) => {
|
||||
if (i !== index) return c;
|
||||
if (partial === null) return { ...c, condition: undefined };
|
||||
const base: DialogueCondition = c.condition ?? { kind: "flag", key: "", op: "is_true" };
|
||||
return { ...c, condition: { ...base, ...partial } };
|
||||
}),
|
||||
});
|
||||
|
||||
const targetOptions = allNodes.filter((n) => n.id !== node.id);
|
||||
|
|
@ -249,27 +241,24 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
{node.type === "dialogue" && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">Line</Label>
|
||||
<MarkupEditor
|
||||
<Textarea
|
||||
ref={lineRef}
|
||||
value={draft.body ?? ""}
|
||||
onChange={(next) => {
|
||||
patch({ body: next || undefined });
|
||||
onChange={(e) => {
|
||||
patch({ body: e.target.value || undefined });
|
||||
autoSizeLine();
|
||||
}}
|
||||
placeholder="The NPC says…"
|
||||
rows={4}
|
||||
textareaRef={lineRef}
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30 resize-y"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Line breaks are kept. **bold**, *italic*, {`{red}color{/}`} and {'`code`'} render
|
||||
in the conversation. Colors take a friendly name (red, amber, cyan, emerald,
|
||||
violet, pink, slate, ...) or a hex code like {`{#ff00ff}`}. Insert flag values
|
||||
with {'{{flag_key}}'}; text flags may carry their own color markup. Pick a branch
|
||||
with a ternary: {'{{ trust ? friend : hostile }}'}, also {'{{ !key }}'} and
|
||||
{'{{ rep >= 5 ? elite : rookie }}'}. Branches may nest tokens. Inline
|
||||
with {'{{flag_key}}'}; text flags may carry their own color markup. Inline
|
||||
images use {''} (e.g. {``}) and
|
||||
render at text height. Lines starting with "- " or "1. " become lists.
|
||||
Right-click the box for a markup menu.
|
||||
render at text height.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -278,12 +267,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">Lead-in</Label>
|
||||
<MarkupEditor
|
||||
<Textarea
|
||||
value={draft.leadIn ?? ""}
|
||||
onChange={(next) => patch({ leadIn: next || undefined })}
|
||||
onChange={(e) => patch({ leadIn: e.target.value || undefined })}
|
||||
placeholder="Optional line before the choices."
|
||||
rows={2}
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
|
@ -341,15 +330,14 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
<Label className="text-[9px] uppercase tracking-wider text-white/40">
|
||||
Tooltip (optional)
|
||||
</Label>
|
||||
<MarkupEditor
|
||||
<Textarea
|
||||
value={choice.tooltip ?? ""}
|
||||
onChange={(next) =>
|
||||
setChoice(index, { ...choice, tooltip: next || undefined })
|
||||
onChange={(e) =>
|
||||
setChoice(index, { ...choice, tooltip: e.target.value || undefined })
|
||||
}
|
||||
placeholder="Hover card. Supports markup, {{flags}} and  images."
|
||||
rows={2}
|
||||
preview={false}
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
|
|
@ -384,7 +372,7 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
<Checkbox
|
||||
checked={choice.condition !== undefined}
|
||||
onCheckedChange={(checked) =>
|
||||
setChoiceCondition(index, checked === true ? EMPTY_LEAF : null)
|
||||
setChoiceCondition(index, checked === true ? {} : null)
|
||||
}
|
||||
className="border-white/30 data-[state=checked]:border-sky-500 data-[state=checked]:bg-sky-500"
|
||||
/>
|
||||
|
|
@ -392,22 +380,61 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
</label>
|
||||
{choice.condition && (
|
||||
<div className="flex flex-col gap-1.5 rounded border border-sky-500/25 bg-sky-950/20 p-2">
|
||||
<ConditionFields
|
||||
value={choice.condition}
|
||||
onChange={(next) => setChoiceCondition(index, next)}
|
||||
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
|
||||
Flag key
|
||||
</Label>
|
||||
<Input
|
||||
value={choice.condition.key}
|
||||
onChange={(e) => setChoiceCondition(index, { key: e.target.value })}
|
||||
placeholder="met_informant"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
|
||||
When the flag
|
||||
</Label>
|
||||
<select
|
||||
value={choice.condition.op}
|
||||
onChange={(e) =>
|
||||
setChoiceCondition(index, {
|
||||
op: e.target.value as DialogueCondition["op"],
|
||||
})
|
||||
}
|
||||
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
|
||||
>
|
||||
{(Object.keys(CONDITION_OP_LABELS) as DialogueCondition["op"][]).map(
|
||||
(op) => (
|
||||
<option key={op} value={op}>
|
||||
{CONDITION_OP_LABELS[op]}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
{NUMERIC_OPS.includes(choice.condition.op) && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
|
||||
Amount
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={choice.condition.amount ?? 0}
|
||||
onChange={(e) =>
|
||||
setChoiceCondition(index, { amount: Number(e.target.value) || 0 })
|
||||
}
|
||||
className="bg-zinc-800 border-white/20 text-white"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
|
||||
Lock message (optional)
|
||||
</Label>
|
||||
<MarkupEditor
|
||||
<Textarea
|
||||
value={choice.lockedHint ?? ""}
|
||||
onChange={(next) =>
|
||||
setChoice(index, { ...choice, lockedHint: next || undefined })
|
||||
onChange={(e) =>
|
||||
setChoice(index, { ...choice, lockedHint: e.target.value || undefined })
|
||||
}
|
||||
placeholder='Shown on the disabled choice, e.g. "Needs {amber}trusted{/} standing."'
|
||||
rows={2}
|
||||
preview={false}
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Player-specific flag takes priority; falls back to global (no user).
|
||||
|
|
@ -441,12 +468,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Narration
|
||||
</Label>
|
||||
<MarkupEditor
|
||||
<Textarea
|
||||
value={draft.body ?? ""}
|
||||
onChange={(next) => patch({ body: next || undefined })}
|
||||
onChange={(e) => patch({ body: e.target.value || undefined })}
|
||||
placeholder="Describe what happens. Shown as a speaker-less narrative line."
|
||||
rows={3}
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
|
||||
|
|
@ -627,42 +654,15 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
{draft.effect && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">Message</Label>
|
||||
<MarkupEditor
|
||||
<Textarea
|
||||
value={draft.effect.message ?? ""}
|
||||
onChange={(next) => patchEffect({ message: next || undefined })}
|
||||
onChange={(e) => patchEffect({ message: e.target.value || undefined })}
|
||||
placeholder="What happens when the player reaches this node?"
|
||||
rows={3}
|
||||
preview={false}
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{draft.effect && draft.effect.type !== "notify" && (
|
||||
<label className="flex items-center gap-2 text-xs text-white/60">
|
||||
<Checkbox
|
||||
checked={draft.effect.eventVisibility === "public"}
|
||||
onCheckedChange={(checked) =>
|
||||
// Unset, not "restricted": leaving the key absent keeps the
|
||||
// event on the restricted narrative default in visibility.ts.
|
||||
patchEffect({ eventVisibility: checked === true ? "public" : undefined })
|
||||
}
|
||||
className="border-white/30 data-[state=checked]:border-emerald-500 data-[state=checked]:bg-emerald-500"
|
||||
/>
|
||||
Show this event to everyone (normally staff only)
|
||||
</label>
|
||||
)}
|
||||
{draft.effect && draft.effect.type !== "notify" && (
|
||||
<label className="flex items-center gap-2 text-xs text-white/60">
|
||||
<Checkbox
|
||||
checked={draft.effect.discord === true}
|
||||
onCheckedChange={(checked) =>
|
||||
patchEffect({ discord: checked === true ? true : undefined })
|
||||
}
|
||||
className="border-white/30 data-[state=checked]:border-indigo-500 data-[state=checked]:bg-indigo-500"
|
||||
/>
|
||||
Post this event to the Discord NPC dispatch channel
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
@ -689,14 +689,51 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
|
||||
{node.type === "condition" && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<ConditionFields
|
||||
value={draft.condition ?? EMPTY_LEAF}
|
||||
onChange={(condition) => patch({ condition })}
|
||||
/>
|
||||
<p className="-mt-2 text-[10px] text-zinc-400">
|
||||
Player-specific flag takes priority; falls back to global (no user). Missing =
|
||||
false / 0.
|
||||
</p>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Flag key
|
||||
</Label>
|
||||
<Input
|
||||
value={draft.condition?.key ?? ""}
|
||||
onChange={(e) => patchCondition({ key: e.target.value })}
|
||||
placeholder="met_informant"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-zinc-400">
|
||||
Player-specific flag takes priority; falls back to global (no user). Missing = false / 0.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
When the flag
|
||||
</Label>
|
||||
<select
|
||||
value={draft.condition?.op ?? "is_true"}
|
||||
onChange={(e) => patchCondition({ op: e.target.value as DialogueCondition["op"] })}
|
||||
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
|
||||
>
|
||||
{(Object.keys(CONDITION_OP_LABELS) as DialogueCondition["op"][]).map((op) => (
|
||||
<option key={op} value={op}>
|
||||
{CONDITION_OP_LABELS[op]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{NUMERIC_OPS.includes(draft.condition?.op ?? "is_true") && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Amount
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={draft.condition?.amount ?? 0}
|
||||
onChange={(e) => patchCondition({ amount: Number(e.target.value) || 0 })}
|
||||
className="bg-zinc-800 border-white/20 text-white"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
|
|
@ -739,12 +776,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
{node.type === "end" && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">Closing line</Label>
|
||||
<MarkupEditor
|
||||
<Textarea
|
||||
value={draft.closing ?? ""}
|
||||
onChange={(next) => patch({ closing: next || undefined })}
|
||||
onChange={(e) => patch({ closing: e.target.value || undefined })}
|
||||
placeholder="The conversation ends."
|
||||
rows={3}
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
|
||||
|
|
@ -752,15 +789,6 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
</div>
|
||||
)}
|
||||
|
||||
{(node.type === "dialogue" || node.type === "event") && (
|
||||
<AttachmentEditor
|
||||
attachments={draft.attachments ?? []}
|
||||
onChange={(attachments) =>
|
||||
patch({ attachments: attachments.length > 0 ? attachments : undefined })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{(node.type === "dialogue" || node.type === "event" || node.type === "delay") && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
|
|
@ -816,225 +844,3 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attachment list for a dialogue/event node. Uploads go to the `media`
|
||||
* collection through the conversation upload action (which gates on
|
||||
* npc-dialogues:update); flowData only keeps the returned pointer plus an
|
||||
* editable chip label. Removing here only drops the pointer, never the file.
|
||||
*/
|
||||
function AttachmentEditor({
|
||||
attachments,
|
||||
onChange,
|
||||
}: {
|
||||
attachments: DialogueAttachment[];
|
||||
onChange: (next: DialogueAttachment[]) => void;
|
||||
}) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const upload = async (file: File) => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
const result = await uploadNpcDialogueAttachment(formData);
|
||||
if (result.success && result.data) {
|
||||
onChange([
|
||||
...attachments,
|
||||
{ mediaId: result.data.mediaId, label: result.data.filename },
|
||||
]);
|
||||
} else {
|
||||
setError(result.error ?? "Upload failed.");
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">Attachments</Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
className="h-6 border-white/20 text-xs text-white"
|
||||
>
|
||||
{busy ? "Uploading…" : "Upload file"}
|
||||
</Button>
|
||||
</div>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
accept="text/*,application/pdf,image/*"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) void upload(file);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
{attachments.map((attachment, index) => (
|
||||
<div key={`${attachment.mediaId}-${index}`} className="flex items-center gap-1.5">
|
||||
<Input
|
||||
value={attachment.label ?? ""}
|
||||
placeholder="Chip label"
|
||||
onChange={(e) =>
|
||||
onChange(
|
||||
attachments.map((a, i) =>
|
||||
i === index ? { ...a, label: e.target.value || undefined } : a,
|
||||
),
|
||||
)
|
||||
}
|
||||
className="h-7 bg-zinc-800 border-white/20 text-xs text-white placeholder:text-white/30"
|
||||
/>
|
||||
<span className="w-16 shrink-0 truncate font-mono text-[10px] text-white/30">
|
||||
#{attachment.mediaId}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label="Remove attachment"
|
||||
onClick={() => onChange(attachments.filter((_, i) => i !== index))}
|
||||
className="h-7 shrink-0 border-red-900/50 px-2 text-xs text-red-400 hover:bg-red-950/40"
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{attachments.length === 0 && (
|
||||
<p className="text-xs text-white/30">No attachments on this line.</p>
|
||||
)}
|
||||
{error && <p className="text-[10px] text-red-400">{error}</p>}
|
||||
<p className="text-[10px] text-white/40">
|
||||
Players see these as chips under the line that open a file viewer. Text, PDF or image,
|
||||
up to 8 MB. Files live in the media library; removing a chip never deletes the file.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-level condition builder: a combinator dropdown (one flag, or an
|
||||
* AND / OR / NOR group) plus one editable row per leaf. Groups never nest,
|
||||
* which keeps authored JSON shallow and the runtime evaluator single-pass.
|
||||
*/
|
||||
function ConditionFields({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: DialogueCondition;
|
||||
onChange: (next: DialogueCondition) => void;
|
||||
}) {
|
||||
const mode = value.kind === "group" ? `group:${value.op}` : "leaf";
|
||||
|
||||
const setMode = (next: string) => {
|
||||
if (next === mode) return;
|
||||
if (next === "leaf") {
|
||||
onChange(value.kind === "group" ? (value.children[0] ?? EMPTY_LEAF) : value);
|
||||
return;
|
||||
}
|
||||
const op = next.slice("group:".length) as DialogueConditionGroup["op"];
|
||||
if (value.kind === "group") onChange({ ...value, op });
|
||||
else onChange({ kind: "group", op, children: [value] });
|
||||
};
|
||||
|
||||
const patchLeaf = (index: number, partial: Partial<DialogueFlagCondition>) => {
|
||||
if (value.kind === "flag" && index === 0) onChange({ ...value, ...partial });
|
||||
else if (value.kind === "group")
|
||||
onChange({
|
||||
...value,
|
||||
children: value.children.map((c, i) => (i === index ? { ...c, ...partial } : c)),
|
||||
});
|
||||
};
|
||||
|
||||
const leaves = value.kind === "group" ? value.children : [value];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[9px] uppercase tracking-wider text-white/40">Condition</Label>
|
||||
<select
|
||||
value={mode}
|
||||
onChange={(e) => setMode(e.target.value)}
|
||||
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
|
||||
>
|
||||
<option value="leaf">Single flag condition</option>
|
||||
{(Object.keys(GROUP_OP_LABELS) as DialogueConditionGroup["op"][]).map((op) => (
|
||||
<option key={op} value={`group:${op}`}>
|
||||
{GROUP_OP_LABELS[op]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{leaves.map((leaf, index) => (
|
||||
<div key={index} className="flex flex-col gap-1.5 border-t border-white/10 pt-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-[9px] uppercase tracking-wider text-white/40">
|
||||
{value.kind === "group" ? `Condition ${index + 1}` : "Flag key"}
|
||||
</Label>
|
||||
{value.kind === "group" && leaves.length > 1 && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label="Remove condition"
|
||||
onClick={() =>
|
||||
onChange({ ...value, children: value.children.filter((_, i) => i !== index) })
|
||||
}
|
||||
className="h-5 border-red-900/50 px-1.5 text-[10px] text-red-400 hover:bg-red-950/40"
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
value={leaf.key}
|
||||
onChange={(e) => patchLeaf(index, { key: e.target.value })}
|
||||
placeholder="met_informant"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<Label className="text-[9px] uppercase tracking-wider text-white/40">When the flag</Label>
|
||||
<select
|
||||
value={leaf.op}
|
||||
onChange={(e) => patchLeaf(index, { op: e.target.value as DialogueFlagCondition["op"] })}
|
||||
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
|
||||
>
|
||||
{(Object.keys(CONDITION_OP_LABELS) as DialogueFlagCondition["op"][]).map((op) => (
|
||||
<option key={op} value={op}>
|
||||
{CONDITION_OP_LABELS[op]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{NUMERIC_OPS.includes(leaf.op) && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[9px] uppercase tracking-wider text-white/40">Amount</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={leaf.amount ?? 0}
|
||||
onChange={(e) => patchLeaf(index, { amount: Number(e.target.value) || 0 })}
|
||||
className="bg-zinc-800 border-white/20 text-white"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{value.kind === "group" && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onChange({ ...value, children: [...value.children, EMPTY_LEAF] })}
|
||||
className="h-6 self-end border-white/20 text-xs text-white"
|
||||
>
|
||||
Add condition
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,7 +34,6 @@ import type {
|
|||
NpcDialogueNodeType,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
import { deriveEdges, removeHopFromNode, validateGraph } from "@/lib/npc-dialogue/dialogue";
|
||||
import type { RouteRect } from "@/lib/flow-edge-routing";
|
||||
import { NpcDialogueNode } from "./NpcDialogueNode";
|
||||
import { NodeEditDialog } from "./NodeEditDialog";
|
||||
import { RoutedFlowEdge } from "./RoutedFlowEdge";
|
||||
|
|
@ -132,30 +131,19 @@ function FlowEditor() {
|
|||
|
||||
// Edges are a derived projection of the node data, never edited directly.
|
||||
// Every edge renders through the routed edge type so lines bend around
|
||||
// unrelated cards instead of slicing through them. The card rectangles used
|
||||
// for obstacle avoidance are computed here from the live `nodes` state and
|
||||
// handed to each edge via `data`: React Flow mutates its store's nodeLookup
|
||||
// Map in place, so reading it inside the edge yields a stale snapshot that
|
||||
// only refreshes on remount (edges kept bending around where cards used to
|
||||
// be until save+refresh). Deriving from `nodes` re-routes edges as you drag.
|
||||
const syncedEdges = useMemo<Edge[]>(() => {
|
||||
const obstacles: RouteRect[] = [];
|
||||
for (const n of nodes) {
|
||||
const width = n.measured?.width ?? 0;
|
||||
const height = n.measured?.height ?? 0;
|
||||
if (!width || !height) continue;
|
||||
obstacles.push({ id: n.id, x: n.position.x, y: n.position.y, width, height });
|
||||
}
|
||||
return deriveEdges(nodes as DialogueNode[])
|
||||
.map((edge) => ({
|
||||
...edge,
|
||||
type: "routed",
|
||||
animated: true,
|
||||
markerEnd: EDGE_MARKER,
|
||||
selected: edge.id === selectedEdgeId,
|
||||
data: { obstacles },
|
||||
}));
|
||||
}, [nodes, selectedEdgeId]);
|
||||
// unrelated cards instead of slicing through them.
|
||||
const syncedEdges = useMemo<Edge[]>(
|
||||
() =>
|
||||
deriveEdges(nodes as DialogueNode[])
|
||||
.map((edge) => ({
|
||||
...edge,
|
||||
type: "routed",
|
||||
animated: true,
|
||||
markerEnd: EDGE_MARKER,
|
||||
selected: edge.id === selectedEdgeId,
|
||||
})),
|
||||
[nodes, selectedEdgeId],
|
||||
);
|
||||
|
||||
const serialize = useCallback((nds: Node[]) => {
|
||||
// Volatile interaction flags (selection, in-progress drags) are not part
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ import {
|
|||
} from "lucide-react";
|
||||
|
||||
import type { DialogueNodeData, NpcDialogueNodeType } from "@/lib/npc-dialogue/dialogue";
|
||||
import { conditionSummary, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
|
||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { DIALOGUE_NODES } from "./types";
|
||||
|
||||
|
|
@ -96,7 +95,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
|
|||
{choice.condition && (
|
||||
<span
|
||||
className="shrink-0 rounded-sm border border-sky-500/40 bg-sky-500/10 px-1 font-mono text-[8px] uppercase tracking-wider text-sky-300"
|
||||
title={`Only shown when ${conditionSummary(choice.condition)}`}
|
||||
title={`Only shown when flag "${choice.condition.key}" ${choice.condition.op.replace(/_/g, " ")}`}
|
||||
>
|
||||
gated
|
||||
</span>
|
||||
|
|
@ -163,9 +162,13 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
|
|||
{nodeType === "condition" && (
|
||||
<div className="flex flex-col gap-1.5 text-sm text-white/70">
|
||||
<div>
|
||||
{d.condition && !hasEmptyConditionKey(d.condition) ? (
|
||||
{d.condition?.key ? (
|
||||
<span>
|
||||
Flag <span className="font-mono text-sky-300">{conditionSummary(d.condition)}</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>
|
||||
|
|
|
|||
|
|
@ -7,17 +7,13 @@
|
|||
* line), and plain Bezier connectors sliced straight through unrelated
|
||||
* cards, which made return paths impossible to trace. All shape logic lives
|
||||
* in the shared `routeEdge` (`@/lib/flow-edge-routing`, also used by the
|
||||
* tech tree); the editor passes the current card rectangles in through edge
|
||||
* `data` (same pattern as the tech tree's RoutedEdge). This component renders
|
||||
* the result with rounded corners, an arrowhead, and the condition label as a
|
||||
* chip at the path midpoint so text stays readable over other geometry.
|
||||
*
|
||||
* Obstacles arrive via props rather than being read from the React Flow
|
||||
* store: the store's `nodeLookup` Map is mutated in place, so a memo keyed on
|
||||
* it never recomputes and edges would keep bending around where cards *used
|
||||
* to be* until the editor remounted.
|
||||
* tech tree); this component gathers the card rectangles from the React Flow
|
||||
* store and renders the result with rounded corners, an arrowhead, and the
|
||||
* condition label as a chip at the path midpoint so text stays readable
|
||||
* over other geometry.
|
||||
*/
|
||||
import { BaseEdge, EdgeLabelRenderer, type EdgeProps } from "@xyflow/react";
|
||||
import { useMemo } from "react";
|
||||
import { BaseEdge, EdgeLabelRenderer, useStore, type EdgeProps } from "@xyflow/react";
|
||||
|
||||
import {
|
||||
buildRoutePath,
|
||||
|
|
@ -41,11 +37,20 @@ export function RoutedFlowEdge({
|
|||
markerEnd,
|
||||
label,
|
||||
selected,
|
||||
data,
|
||||
}: EdgeProps) {
|
||||
// Card rectangles computed by the editor from its live node state, so a
|
||||
// drag re-renders this edge with fresh obstacles instead of a stale cache.
|
||||
const nodes = (data?.obstacles as RouteRect[] | undefined) ?? [];
|
||||
const nodeLookup = useStore((s) => s.nodeLookup);
|
||||
|
||||
const nodes = useMemo(() => {
|
||||
const rects: RouteRect[] = [];
|
||||
nodeLookup.forEach((node) => {
|
||||
const width = node.measured?.width ?? 0;
|
||||
const height = node.measured?.height ?? 0;
|
||||
if (!width || !height) return;
|
||||
const { x, y } = node.internals.positionAbsolute;
|
||||
rects.push({ id: node.id, x, y, width, height });
|
||||
});
|
||||
return rects;
|
||||
}, [nodeLookup]);
|
||||
|
||||
const start: RoutePoint = { x: sourceX, y: sourceY };
|
||||
const end: RoutePoint = { x: targetX, y: targetY };
|
||||
|
|
|
|||
|
|
@ -1,111 +0,0 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import {
|
||||
DownloadIcon,
|
||||
ExternalLinkIcon,
|
||||
PaperclipIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import type { ResolvedAttachment } from "@/lib/npc-dialogue/dialogue";
|
||||
|
||||
/**
|
||||
* Attachment chips for a conversation line. Each chip opens the file in a
|
||||
* dossier-styled modal (images render directly, everything else through an
|
||||
* iframe, which gives PDFs and plain text their native browser viewer) with
|
||||
* download and new-tab escape hatches. Mirrors how DialogueLink presents
|
||||
* linked pages, so attachments and links feel like one system.
|
||||
*/
|
||||
export function DialogueAttachments({
|
||||
attachments,
|
||||
}: {
|
||||
attachments: ResolvedAttachment[] | undefined;
|
||||
}) {
|
||||
const [active, setActive] = useState<ResolvedAttachment | null>(null);
|
||||
if (!attachments || attachments.length === 0) return null;
|
||||
|
||||
const isImage = (a: ResolvedAttachment) => a.mimeType.startsWith("image/");
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-wrap gap-1.5 pt-0.5">
|
||||
{attachments.map((attachment) => (
|
||||
<button
|
||||
key={attachment.url}
|
||||
type="button"
|
||||
onClick={() => setActive(attachment)}
|
||||
title={`Open ${attachment.label}`}
|
||||
className="inline-flex max-w-full items-center gap-1.5 rounded-none border border-cyan-500/30 bg-cyan-500/10 px-2 py-0.5 font-mono text-[10px] uppercase tracking-widest text-cyan-200 transition-colors hover:border-cyan-400/60 hover:text-cyan-100"
|
||||
>
|
||||
<PaperclipIcon className="size-3 shrink-0" />
|
||||
<span className="truncate">{attachment.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Dialog open={active !== null} onOpenChange={(next) => !next && setActive(null)}>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
className="flex h-[85vh] w-[92vw] max-w-4xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-4 border-b border-white/15 bg-black/50 px-4 py-2 backdrop-blur-sm">
|
||||
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
|
||||
Attachment // {active?.label}
|
||||
</DialogTitle>
|
||||
<div className="flex shrink-0 items-center gap-3">
|
||||
{active && (
|
||||
<>
|
||||
<a
|
||||
href={active.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-widest text-white/40 transition-colors hover:text-cyan-400"
|
||||
>
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
New tab
|
||||
</a>
|
||||
<a
|
||||
href={active.url}
|
||||
download={active.filename}
|
||||
className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-widest text-white/40 transition-colors hover:text-cyan-400"
|
||||
>
|
||||
<DownloadIcon className="size-3" />
|
||||
Download
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setActive(null)}
|
||||
aria-label="Close attachment"
|
||||
className="text-white/40 transition-colors hover:text-white/90"
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{active && isImage(active) ? (
|
||||
<div className="min-h-0 flex-1 overflow-auto bg-zinc-900 p-4">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={active.url}
|
||||
alt={active.label}
|
||||
className="mx-auto max-h-full max-w-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
active && (
|
||||
<iframe
|
||||
src={active.url}
|
||||
title={active.label}
|
||||
className="min-h-0 flex-1 bg-zinc-900"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -8,8 +8,9 @@ import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc
|
|||
import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate";
|
||||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments";
|
||||
import { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
|
||||
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
|
||||
import { flowHash, loadSeenMap, mergeSeenNodes, saveSeenMap, unseenNodeIds } from "@/lib/npc-dialogue/seen";
|
||||
import type { SeenMap } from "@/lib/npc-dialogue/seen";
|
||||
import { DOSSIER } from "@/components/frontend/operations";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
|
@ -26,7 +27,6 @@ import {
|
|||
import {
|
||||
evaluateNpcDialogueChoices,
|
||||
evaluateNpcDialogueCondition,
|
||||
markNpcDialogueNodeRead,
|
||||
resolveNpcDialogueTexts,
|
||||
triggerNpcDialogueEvent,
|
||||
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
||||
|
|
@ -34,10 +34,6 @@ import {
|
|||
interface NpcConversationProps {
|
||||
readonly npc: GameNpc;
|
||||
readonly dialogue: { id: number; flowData?: FlowData } | null | undefined;
|
||||
/** Node ids this user has already read (server-side NEW badges). Seeds the
|
||||
* local seen set; reads during the session are sent to the server and
|
||||
* merged optimistically. */
|
||||
readonly initialSeenNodeIds?: readonly string[];
|
||||
}
|
||||
|
||||
interface ResolvedFlow {
|
||||
|
|
@ -74,7 +70,7 @@ function nodeText(node: DialogueNode): string {
|
|||
return node.data.body || node.data.effect?.message || node.data.closing || node.data.leadIn || "";
|
||||
}
|
||||
|
||||
export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConversationProps) {
|
||||
export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
||||
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [log, setLog] = useState<LogEntry[]>([]);
|
||||
|
|
@ -91,12 +87,12 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
* the server when the conversation lands on a choice node. Cleared on
|
||||
* every `begin()` so flags gained mid-conversation are re-checked. */
|
||||
const [choiceGates, setChoiceGates] = useState<Record<string, ChoiceGate[]>>({});
|
||||
/** Node ids this player has read, powering the NEW badges. Seeded from the
|
||||
* server (npc-dialogue-states); nodes read in this session are added here
|
||||
* optimistically and persisted via `markNpcDialogueNodeRead`. */
|
||||
const [seenNodes, setSeenNodes] = useState<Set<string>>(
|
||||
() => new Set(initialSeenNodeIds ?? []),
|
||||
);
|
||||
/** Per-browser read progress powering the NEW badges. Loaded after mount so
|
||||
* server and client markup agree (localStorage is invisible to SSR). */
|
||||
const [seenMap, setSeenMap] = useState<SeenMap>({});
|
||||
useEffect(() => {
|
||||
setSeenMap(loadSeenMap());
|
||||
}, []);
|
||||
const seq = useRef(0);
|
||||
const sessionRef = useRef(0);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
|
@ -130,9 +126,7 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
if (!open || !flow || !activeChoiceNodeId) return;
|
||||
if (choiceGates[activeChoiceNodeId]) return;
|
||||
const node = flow.nodes.find((n) => n.id === activeChoiceNodeId);
|
||||
const hasGated = (node?.data.choices ?? []).some(
|
||||
(c) => c.condition && !hasEmptyConditionKey(c.condition),
|
||||
);
|
||||
const hasGated = (node?.data.choices ?? []).some((c) => c.condition?.key?.trim());
|
||||
if (!hasGated) return;
|
||||
let cancelled = false;
|
||||
void evaluateNpcDialogueChoices(Number(npc.id), activeChoiceNodeId).then((res) => {
|
||||
|
|
@ -146,24 +140,30 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
};
|
||||
}, [open, flow, activeChoiceNodeId, choiceGates, npc.id]);
|
||||
|
||||
// NEW badge input: nodes in this flow the player has never read. Server-
|
||||
// sourced, so badges follow the account across devices; GM edits no longer
|
||||
// re-flag content the player already saw.
|
||||
// NEW badge inputs: current flowchart signature + the nodes this browser
|
||||
// has not read yet (a GM edit changes the hash and re-flags everything).
|
||||
const seenKey = dialogue ? String(dialogue.id) : "";
|
||||
const flowSignature = useMemo(() => flowHash(dialogue?.flowData), [dialogue]);
|
||||
const allNodeIds = useMemo(() => (flow ? flow.nodes.map((n) => n.id) : []), [flow]);
|
||||
const unseenTargets = useMemo(
|
||||
() => new Set(allNodeIds.filter((id) => !seenNodes.has(id))),
|
||||
[seenNodes, allNodeIds],
|
||||
() => new Set(unseenNodeIds(seenMap[seenKey], flowSignature, allNodeIds)),
|
||||
[seenMap, seenKey, flowSignature, allNodeIds],
|
||||
);
|
||||
|
||||
if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null;
|
||||
|
||||
/** Marks a node read: clears its badge locally right away and persists the
|
||||
* marker server-side fire-and-forget (a failed write just re-badges on the
|
||||
* next load; the action itself is idempotent). */
|
||||
/** Records that this browser has read a node (persisted, idempotent). */
|
||||
const markSeen = (nodeId: string) => {
|
||||
if (!dialogue || seenNodes.has(nodeId)) return;
|
||||
setSeenNodes((prev) => new Set(prev).add(nodeId));
|
||||
void markNpcDialogueNodeRead(dialogue.id, nodeId).catch(() => undefined);
|
||||
setSeenMap((prev) => {
|
||||
const entry = prev[seenKey];
|
||||
if (entry && entry.hash === flowSignature && entry.nodes.includes(nodeId)) return prev;
|
||||
const next: SeenMap = {
|
||||
...prev,
|
||||
[seenKey]: { hash: flowSignature, nodes: mergeSeenNodes(entry, flowSignature, nodeId) },
|
||||
};
|
||||
saveSeenMap(next);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
/** Resolves the node's display strings server-side (flag tokens), then
|
||||
|
|
@ -171,7 +171,7 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
* tokens skip the round trip and render their raw authored text. */
|
||||
const typeIn = async (node: DialogueNode, token: number) => {
|
||||
let resolved: ResolvedNodeTexts | undefined;
|
||||
if (collectNodeTokens(node).length > 0 || (node.data.attachments?.length ?? 0) > 0) {
|
||||
if (collectNodeTokens(node).length > 0) {
|
||||
const res = await resolveNpcDialogueTexts(Number(npc.id), node.id);
|
||||
if (sessionRef.current !== token) return;
|
||||
if (res.success && res.data) resolved = res.data;
|
||||
|
|
@ -292,7 +292,7 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
{ hop: DialogueNext; index: number; locked: boolean }[]
|
||||
>((acc, hop, index) => {
|
||||
if (hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) return acc;
|
||||
if (!hop.condition || hasEmptyConditionKey(hop.condition)) {
|
||||
if (!hop.condition?.key?.trim()) {
|
||||
acc.push({ hop, index, locked: false });
|
||||
return acc;
|
||||
}
|
||||
|
|
@ -486,12 +486,9 @@ function TimelineEntry({
|
|||
const message = resolved?.message ?? node.data.effect?.message;
|
||||
const text = body || message || "An event unfolds…";
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
|
||||
<DialogueText text={text} />
|
||||
</p>
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
|
||||
<DialogueText text={text} />
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -527,7 +524,6 @@ function TimelineEntry({
|
|||
<span className="italic text-white/30">…</span>
|
||||
)}
|
||||
</p>
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,85 +16,17 @@ import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
|||
* stay put; no navigation, so conversation progress survives)
|
||||
* {cd|<iso|done>} countdown leaf produced by `{{countdown:key}}` resolution
|
||||
*
|
||||
* Block level: consecutive lines starting with `- `/`* ` render as a bullet
|
||||
* list, consecutive lines starting with `1.`/`2)` as an ordered list; item
|
||||
* content runs through the inline parser like any other text. A line whose
|
||||
* prose merely starts with "- " also becomes a bullet, so start list items
|
||||
* deliberately.
|
||||
*
|
||||
* Shared by the admin flow editor previews and the frontend conversation
|
||||
* dialog, so it must stay client-safe (no Payload imports).
|
||||
*/
|
||||
export function DialogueText({ text, className }: { text: string; className?: string }) {
|
||||
return (
|
||||
<span className={`whitespace-pre-wrap ${className ?? ""}`}>
|
||||
{renderBlocks(text, { i: 0 })}
|
||||
{parseSegment(text, 0, { i: 0 }, false).nodes}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const BULLET_RE = /^[-*]\s+/;
|
||||
const ORDERED_RE = /^\d+[.)]\s+/;
|
||||
|
||||
/**
|
||||
* Line-based block pass over `text`: runs of bullet / ordered lines collapse
|
||||
* into list groups (spans with list roles, so they stay valid inside the
|
||||
* inline wrapper), everything else flushes as a paragraph rendered by the
|
||||
* inline parser. A blank line or a kind change splits adjacent lists.
|
||||
*/
|
||||
function renderBlocks(text: string, keys: { i: number }): ReactNode[] {
|
||||
if (!text) return [];
|
||||
const out: ReactNode[] = [];
|
||||
let paragraph: string[] = [];
|
||||
let listKind: "ul" | "ol" | null = null;
|
||||
let items: string[] = [];
|
||||
|
||||
const flushParagraph = () => {
|
||||
if (paragraph.length === 0) return;
|
||||
const chunk = paragraph.join("\n");
|
||||
paragraph = [];
|
||||
out.push(<span key={`p${keys.i++}`}>{parseSegment(chunk, 0, keys, false).nodes}</span>);
|
||||
};
|
||||
const flushList = () => {
|
||||
if (!listKind) return;
|
||||
const kind = listKind;
|
||||
out.push(
|
||||
<span key={`l${keys.i++}`} role="list" className="my-0.5 flex flex-col gap-0.5 pl-2">
|
||||
{items.map((item, index) => (
|
||||
<span key={index} role="listitem" className="flex gap-2">
|
||||
<span aria-hidden className="shrink-0 text-white/40">
|
||||
{kind === "ul" ? "\u2022" : `${index + 1}.`}
|
||||
</span>
|
||||
<span>{parseSegment(item, 0, keys, false).nodes}</span>
|
||||
</span>
|
||||
))}
|
||||
</span>,
|
||||
);
|
||||
items = [];
|
||||
listKind = null;
|
||||
};
|
||||
|
||||
for (const line of text.split("\n")) {
|
||||
const kind: "ul" | "ol" | null = BULLET_RE.test(line)
|
||||
? "ul"
|
||||
: ORDERED_RE.test(line)
|
||||
? "ol"
|
||||
: null;
|
||||
if (kind) {
|
||||
if (listKind && listKind !== kind) flushList();
|
||||
flushParagraph();
|
||||
listKind = kind;
|
||||
items.push(line.replace(kind === "ul" ? BULLET_RE : ORDERED_RE, ""));
|
||||
continue;
|
||||
}
|
||||
if (listKind) flushList();
|
||||
paragraph.push(line);
|
||||
}
|
||||
flushList();
|
||||
flushParagraph();
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Friendly color names mapped to Tailwind text classes (400 shades read well
|
||||
* on the dark conversation surface). Keys are lowercase. */
|
||||
const FRIENDLY_COLORS: Record<string, string> = {
|
||||
|
|
|
|||
|
|
@ -1,43 +0,0 @@
|
|||
import type { Payload } from "payload";
|
||||
import type { DialogueAttachment, ResolvedAttachment } from "./dialogue";
|
||||
|
||||
/**
|
||||
* Resolve flowData attachment pointers into renderable file references.
|
||||
*
|
||||
* `flowData` is a plain JSON field, so its nested media ids are never
|
||||
* populated by Payload; the conversation runtime calls this before sending a
|
||||
* node to the client. Deleted media documents resolve to nothing (the chip
|
||||
* disappears instead of rendering a dead link). Payload-dependent, server
|
||||
* only.
|
||||
*/
|
||||
export async function resolveAttachments(
|
||||
payload: Payload,
|
||||
attachments: DialogueAttachment[] | undefined,
|
||||
): Promise<ResolvedAttachment[]> {
|
||||
if (!attachments || attachments.length === 0) return [];
|
||||
const out: ResolvedAttachment[] = [];
|
||||
for (const attachment of attachments) {
|
||||
const id = Number(attachment.mediaId);
|
||||
if (!Number.isFinite(id) || id <= 0) continue;
|
||||
try {
|
||||
const doc = await payload.findByID({
|
||||
collection: "media",
|
||||
id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
select: { filename: true, mimeType: true, alt: true, filesize: true },
|
||||
});
|
||||
if (!doc?.filename) continue;
|
||||
out.push({
|
||||
label: attachment.label?.trim() || doc.filename,
|
||||
url: `/api/media/file/${doc.filename}`,
|
||||
filename: doc.filename,
|
||||
mimeType: doc.mimeType ?? "application/octet-stream",
|
||||
sizeBytes: doc.filesize ?? undefined,
|
||||
});
|
||||
} catch {
|
||||
// Media document no longer exists: skip the attachment.
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
@ -61,7 +61,7 @@ export interface ChoiceGate {
|
|||
* true/false; numeric flags compare against `amount` (a missing flag counts
|
||||
* as false / zero).
|
||||
*/
|
||||
export interface DialogueFlagCondition {
|
||||
export interface DialogueCondition {
|
||||
/** Currently only generic player flags; more kinds can join later. */
|
||||
kind: "flag";
|
||||
/** `player-flags` key checked for the reading user. */
|
||||
|
|
@ -72,22 +72,8 @@ export interface DialogueFlagCondition {
|
|||
amount?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-level group over leaf conditions (children are always leaves, so
|
||||
* authored JSON stays shallow and the editor builder stays simple).
|
||||
* `and` passes when every child passes, `or` when any does, `nor` when none
|
||||
* does. An empty group passes for `and`/`nor` and fails for `or`.
|
||||
*/
|
||||
export interface DialogueConditionGroup {
|
||||
kind: "group";
|
||||
op: "and" | "or" | "nor";
|
||||
children: DialogueFlagCondition[];
|
||||
}
|
||||
|
||||
export type DialogueCondition = DialogueFlagCondition | DialogueConditionGroup;
|
||||
|
||||
/** All leaf condition operators, in UI order. */
|
||||
export const CONDITION_OPS: DialogueFlagCondition["op"][] = [
|
||||
/** All condition operators, in UI order. */
|
||||
export const CONDITION_OPS: DialogueCondition["op"][] = [
|
||||
"is_true",
|
||||
"is_false",
|
||||
"gte",
|
||||
|
|
@ -107,19 +93,6 @@ export interface NpcDialogueEffect {
|
|||
title?: string;
|
||||
/** Notification / event-log body (notify, emit). */
|
||||
message?: string;
|
||||
/**
|
||||
* Visibility of the game-event-log entry this effect writes (emit, reward,
|
||||
* flag). Dialogue events default to restricted (narrative spoilers), gated
|
||||
* to dialogue/flag staff; set "public" for announcements that should appear
|
||||
* in every member's event feed. Omitted means "use the default policy".
|
||||
*/
|
||||
eventVisibility?: "public" | "restricted";
|
||||
/**
|
||||
* Queue the emitted game-event entry for the bot's Discord NPC dispatch
|
||||
* channel (emit, reward, flag). Reserve for milestone beats; the poll
|
||||
* service posts the message once and stamps the log entry.
|
||||
*/
|
||||
discord?: boolean;
|
||||
/** Flag key to write (flag). */
|
||||
flagKey?: string;
|
||||
/** Write mode (flag). */
|
||||
|
|
@ -146,29 +119,6 @@ export interface NpcDialogueEffect {
|
|||
flagTargetUserId?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A file attached to a conversation node (transcripts, orders, images). The
|
||||
* bytes live in the `media` collection; flowData only stores the pointer, so
|
||||
* the runtime resolves ids to URLs server-side before the client renders
|
||||
* chips (JSON relationships are never auto-populated).
|
||||
*/
|
||||
export interface DialogueAttachment {
|
||||
/** `media` document id holding the file. */
|
||||
mediaId: number | string;
|
||||
/** Chip label; falls back to the stored filename. */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
/** An attachment resolved for rendering (server-side). */
|
||||
export interface ResolvedAttachment {
|
||||
label: string;
|
||||
/** Site-relative file URL (`/api/media/file/<filename>`). */
|
||||
url: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes?: number;
|
||||
}
|
||||
|
||||
export type DialogueNodeData = {
|
||||
/** Speaker label shown above the line. Defaults to the NPC's name at runtime. */
|
||||
speaker?: string;
|
||||
|
|
@ -182,8 +132,6 @@ export type DialogueNodeData = {
|
|||
effect?: NpcDialogueEffect;
|
||||
/** Closing text shown when the conversation ends. */
|
||||
closing?: string;
|
||||
/** Files attached to this node's message (dialogue/event/end nodes). */
|
||||
attachments?: DialogueAttachment[];
|
||||
/** Marks this node as the conversation start. */
|
||||
isStart?: boolean;
|
||||
/** Single continuation (dialogue / event / end nodes). */
|
||||
|
|
@ -319,28 +267,6 @@ export interface GraphValidation {
|
|||
errors: string[];
|
||||
}
|
||||
|
||||
/** One-line human summary of a condition for editor previews. */
|
||||
export function conditionSummary(condition: DialogueCondition): string {
|
||||
const leaf = (c: DialogueFlagCondition): string =>
|
||||
`"${c.key || "?"}" ${c.op.replace(/_/g, " ")}${
|
||||
c.amount !== undefined && !["is_true", "is_false"].includes(c.op) ? ` ${c.amount}` : ""
|
||||
}`;
|
||||
if (condition.kind === "group") {
|
||||
const joiner = condition.op === "and" ? " and " : condition.op === "or" ? " or " : " and ";
|
||||
const body = condition.children.map(leaf).join(joiner);
|
||||
return condition.op === "nor" ? `none of: ${body}` : body;
|
||||
}
|
||||
return leaf(condition);
|
||||
}
|
||||
|
||||
/** True when any leaf of the condition (including inside a group) lacks a key. */
|
||||
export function hasEmptyConditionKey(condition: DialogueCondition): boolean {
|
||||
if (condition.kind === "group") {
|
||||
return condition.children.length === 0 || condition.children.some((child) => !child.key.trim());
|
||||
}
|
||||
return !condition.key.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
|
@ -358,9 +284,6 @@ export function validateGraph(nodes: DialogueNode[]): GraphValidation {
|
|||
}
|
||||
|
||||
for (const node of nodes) {
|
||||
if (node.type === "condition" && node.data.condition && hasEmptyConditionKey(node.data.condition)) {
|
||||
errors.push(`The branch condition on "${node.id}" needs a flag key.`);
|
||||
}
|
||||
const hops = outgoingHops(node);
|
||||
for (const hop of hops) {
|
||||
if (!hop) continue;
|
||||
|
|
@ -370,7 +293,7 @@ export function validateGraph(nodes: DialogueNode[]): GraphValidation {
|
|||
if (node.type === "choice" && !hop.label?.trim()) {
|
||||
errors.push(`A choice on "${node.id}" needs button text.`);
|
||||
}
|
||||
if (node.type === "choice" && hop.condition && hasEmptyConditionKey(hop.condition)) {
|
||||
if (node.type === "choice" && hop.condition && !hop.condition.key.trim()) {
|
||||
errors.push(`A gated choice on "${node.id}" needs a flag key.`);
|
||||
}
|
||||
if (
|
||||
|
|
|
|||
|
|
@ -144,29 +144,12 @@ export function flagValues(doc: {
|
|||
return { bool, num: bool ? 1 : 0, text: bool ? "true" : "false", exists: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates one authored condition against the user's live flags. Leaves
|
||||
* compare a single flag; groups combine leaves with and / or / nor (groups
|
||||
* are single-level by construction, so recursion stops at the children).
|
||||
*/
|
||||
/** Evaluates one authored condition against the user's live flags. */
|
||||
export async function evaluateCondition(
|
||||
payload: Payload,
|
||||
userId: number,
|
||||
condition: DialogueCondition,
|
||||
): Promise<boolean> {
|
||||
if (condition.kind === "group") {
|
||||
const results = await Promise.all(
|
||||
(condition.children ?? []).map((child) => evaluateCondition(payload, userId, child)),
|
||||
);
|
||||
switch (condition.op) {
|
||||
case "and":
|
||||
return results.every(Boolean);
|
||||
case "or":
|
||||
return results.some(Boolean);
|
||||
default:
|
||||
return results.every((pass) => !pass);
|
||||
}
|
||||
}
|
||||
const flag = await readFlag(payload, userId, condition.key);
|
||||
const amount = condition.amount ?? 0;
|
||||
switch (condition.op) {
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
* Pure module: client-safe (no Payload imports).
|
||||
*/
|
||||
|
||||
import type { DialogueNode, ResolvedAttachment } from "./dialogue";
|
||||
import type { DialogueNode } from "./dialogue";
|
||||
|
||||
/** One `{{key}}` token. Keys are matched leniently and lowercased; flag keys
|
||||
* are documented as lowercase-with-underscores. */
|
||||
|
|
@ -47,173 +47,6 @@ export function replaceCountdowns(
|
|||
return text.replace(COUNTDOWN_TOKEN, (_match, key: string) => `{cd|${countdowns[key.toLowerCase()] ?? ""}}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ternary token: `{{ cond ? 'yes' : 'no' }}`, where `cond` is an optional
|
||||
* `!` plus a flag key plus an optional numeric comparison (`>= 5`, `< 2`,
|
||||
* `= 0`, `> 1`, `<= 10`). Branches are free text and may themselves contain
|
||||
* `{{flag}}` tokens, color markup, or nested ternaries; those resolve on
|
||||
* later passes (bounded) before `interpolateFlags` runs its single pass.
|
||||
*/
|
||||
const TERNARY_CONDITION = /^(!?)\s*([a-zA-Z0-9_]+)\s*(?:(>=|<=|>|<|=)\s*(-?\d+(?:\.\d+)?))?$/;
|
||||
|
||||
/** How many rewrite passes `resolveTernaries` makes over one string. Nested
|
||||
* ternaries deeper than this stay literal, which beats any unbounded loop. */
|
||||
const MAX_TERNARY_PASSES = 4;
|
||||
|
||||
/** The truth inputs a ternary condition reads for one flag key. */
|
||||
export interface TernaryTruth {
|
||||
bool: boolean;
|
||||
num: number;
|
||||
}
|
||||
|
||||
/** Evaluates one parsed ternary condition against live flag truths. Missing
|
||||
* flags read falsy (false / 0), matching condition-node semantics. */
|
||||
function ternaryConditionPasses(condition: string, truths: Record<string, TernaryTruth>): boolean {
|
||||
const match = TERNARY_CONDITION.exec(condition.trim());
|
||||
if (!match) return false;
|
||||
const [, negate, key, cmp, amount] = match;
|
||||
const flag = truths[key.toLowerCase()];
|
||||
let pass: boolean;
|
||||
if (cmp) {
|
||||
pass = compareNumeric(flag?.num ?? 0, cmp, Number(amount));
|
||||
} else {
|
||||
pass = flag?.bool === true;
|
||||
}
|
||||
return negate === "!" ? !pass : pass;
|
||||
}
|
||||
|
||||
function compareNumeric(left: number, op: string, right: number): boolean {
|
||||
switch (op) {
|
||||
case ">=":
|
||||
return left >= right;
|
||||
case "<=":
|
||||
return left <= right;
|
||||
case ">":
|
||||
return left > right;
|
||||
case "<":
|
||||
return left < right;
|
||||
default:
|
||||
return left === right;
|
||||
}
|
||||
}
|
||||
|
||||
interface FoundTernary {
|
||||
/** Index of the opening `{{`. */
|
||||
start: number;
|
||||
/** Index just past the closing `}}`. */
|
||||
end: number;
|
||||
condition: string;
|
||||
whenTrue: string;
|
||||
whenFalse: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the next ternary token at or after `from` with a brace-depth scan:
|
||||
* nested `{{ }}` raise the depth so their `?`/`:` never split the outer
|
||||
* token, and the token ends at the `}}` that returns depth to zero. The
|
||||
* boundaries are the first top-level `?` and the first top-level `:` after
|
||||
* it, so authors separate parts with spaces around `?` and `:` (a literal
|
||||
* colon in branch text is not supported). Tokens without both boundaries
|
||||
* (plain flags, countdowns) are skipped, not treated as ternaries.
|
||||
*/
|
||||
function findTernary(text: string, from: number): FoundTernary | null {
|
||||
let cursor = from;
|
||||
while (cursor < text.length) {
|
||||
const open = text.indexOf("{{", cursor);
|
||||
if (open === -1) return null;
|
||||
let depth = 1;
|
||||
let i = open + 2;
|
||||
let questionAt = -1;
|
||||
let colonAt = -1;
|
||||
let end = -1;
|
||||
while (i < text.length) {
|
||||
const ch = text[i];
|
||||
if (ch === "{" && text[i + 1] === "{") {
|
||||
depth += 1;
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === "}" && text[i + 1] === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
end = i + 2;
|
||||
break;
|
||||
}
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (depth === 1) {
|
||||
if (ch === "?" && questionAt === -1) questionAt = i;
|
||||
else if (ch === ":" && questionAt !== -1 && colonAt === -1) colonAt = i;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if (end === -1) return null;
|
||||
if (questionAt !== -1 && colonAt !== -1) {
|
||||
return {
|
||||
start: open,
|
||||
end,
|
||||
condition: text.slice(open + 2, questionAt),
|
||||
whenTrue: text.slice(questionAt + 1, colonAt).trim(),
|
||||
whenFalse: text.slice(colonAt + 1, end - 2).trim(),
|
||||
};
|
||||
}
|
||||
cursor = open + 2;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Every flag key referenced by ternary conditions in `text`, lowercased. */
|
||||
export function extractTernaryKeys(text: string | undefined): string[] {
|
||||
if (!text) return [];
|
||||
const keys = new Set<string>();
|
||||
for (const token of iterTernaries(text)) {
|
||||
const match = TERNARY_CONDITION.exec(token.condition.trim());
|
||||
if (match) keys.add(match[2].toLowerCase());
|
||||
}
|
||||
return [...keys];
|
||||
}
|
||||
|
||||
/** Iterates every well-formed ternary token in `text` (top level per scan). */
|
||||
function* iterTernaries(text: string): Generator<FoundTernary> {
|
||||
let cursor = 0;
|
||||
for (;;) {
|
||||
const found = findTernary(text, cursor);
|
||||
if (!found) return;
|
||||
yield found;
|
||||
cursor = found.end;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites ternary tokens to their taken branch over a bounded number of
|
||||
* passes, so branches containing nested tokens resolve on later passes. The
|
||||
* chosen branch is inserted verbatim; `interpolateFlags` then substitutes
|
||||
* plain `{{flag}}` tokens in a final single pass that never re-scans values.
|
||||
*/
|
||||
export function resolveTernaries(
|
||||
text: string | undefined,
|
||||
truths: Record<string, TernaryTruth>,
|
||||
): string {
|
||||
if (!text || !text.includes("?")) return text ?? "";
|
||||
let current = text;
|
||||
for (let pass = 0; pass < MAX_TERNARY_PASSES; pass++) {
|
||||
let out = "";
|
||||
let cursor = 0;
|
||||
let replaced = false;
|
||||
for (const token of iterTernaries(current)) {
|
||||
out += current.slice(cursor, token.start);
|
||||
out += ternaryConditionPasses(token.condition, truths) ? token.whenTrue : token.whenFalse;
|
||||
cursor = token.end;
|
||||
replaced = true;
|
||||
}
|
||||
out += current.slice(cursor);
|
||||
current = out;
|
||||
if (!replaced) break;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/** The display strings of a node that support interpolation. */
|
||||
export interface ResolvedNodeTexts {
|
||||
body?: string;
|
||||
|
|
@ -227,12 +60,6 @@ export interface ResolvedNodeTexts {
|
|||
tooltips?: string[];
|
||||
/** Locked-choice hints, index-aligned with the node's choices. */
|
||||
hints?: string[];
|
||||
/**
|
||||
* Node attachments resolved to renderable file references. Only present
|
||||
* when the node has attachments (absent means "nothing to render", not
|
||||
* "unresolved").
|
||||
*/
|
||||
attachments?: ResolvedAttachment[];
|
||||
}
|
||||
|
||||
/** Every distinct flag key referenced by `text`, lowercased. */
|
||||
|
|
@ -285,8 +112,8 @@ export function formatFlagValue(flag: FlagValueLike): string {
|
|||
}
|
||||
|
||||
/** All flag keys the node's display strings reference (deduped, lowercased).
|
||||
* Countdown (`{{countdown:key}}`) and ternary condition (`{{ key ? .. : .. }}`)
|
||||
* keys join this set too: they need the same server-side flag read. */
|
||||
* Countdown (`{{countdown:key}}`) keys join this set too: they need the same
|
||||
* server-side flag read to resolve their activation time. */
|
||||
export function collectNodeTokens(node: DialogueNode): string[] {
|
||||
const keys = new Set<string>();
|
||||
const texts = [
|
||||
|
|
@ -299,27 +126,22 @@ export function collectNodeTokens(node: DialogueNode): string[] {
|
|||
for (const text of texts) {
|
||||
for (const key of extractFlagTokens(text)) keys.add(key);
|
||||
for (const key of extractCountdownKeys(text)) keys.add(key);
|
||||
for (const key of extractTernaryKeys(text)) keys.add(key);
|
||||
}
|
||||
return [...keys];
|
||||
}
|
||||
|
||||
/**
|
||||
* Interpolates every display string of a node against resolved flag values.
|
||||
* Ternaries resolve first (bounded passes, so nested tokens inside branches
|
||||
* survive into the plain-token pass), then `{{key}}` substitution runs once,
|
||||
* then countdown leaves are rewritten. Only fields the node actually defines
|
||||
* are returned, so the client can tell "resolved to empty" apart from
|
||||
* "no such field".
|
||||
* Only fields the node actually defines are returned, so the client can tell
|
||||
* "resolved to empty" apart from "no such field".
|
||||
*/
|
||||
export function resolveNodeTexts(
|
||||
node: DialogueNode,
|
||||
values: Record<string, string>,
|
||||
countdowns: Record<string, string> = {},
|
||||
truths: Record<string, TernaryTruth> = {},
|
||||
): ResolvedNodeTexts {
|
||||
const finish = (text: string | undefined): string =>
|
||||
replaceCountdowns(interpolateFlags(resolveTernaries(text, truths), values), countdowns);
|
||||
replaceCountdowns(interpolateFlags(text, values), countdowns);
|
||||
const resolved: ResolvedNodeTexts = {};
|
||||
if (node.data.body !== undefined) resolved.body = finish(node.data.body);
|
||||
if (node.data.leadIn !== undefined) resolved.leadIn = finish(node.data.leadIn);
|
||||
|
|
|
|||
106
src/lib/npc-dialogue/seen.ts
Normal file
106
src/lib/npc-dialogue/seen.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
/**
|
||||
* Per-browser conversation progress tracking that powers the "NEW" badges.
|
||||
*
|
||||
* For each conversation (npc-dialogues id) we remember a hash of its
|
||||
* flowchart plus the node ids this browser has read. The Converse button
|
||||
* shows a badge when the flow changed (GM added paths -> new hash) or when
|
||||
* nodes remain unread; choice buttons badge their unseen targets. Stored in
|
||||
* localStorage like the tour/announcement dismissals: no server state, and a
|
||||
* fresh device rediscovers every path once. Pure module, client-safe.
|
||||
*/
|
||||
|
||||
const STORAGE_KEY = "ptf:npc-dialogue-seen";
|
||||
|
||||
export interface SeenEntry {
|
||||
/** flowHash of the flowchart these node ids belong to. */
|
||||
hash: string;
|
||||
/** Node ids rendered at least once. */
|
||||
nodes: string[];
|
||||
}
|
||||
|
||||
export type SeenMap = Record<string, SeenEntry>;
|
||||
|
||||
/** Deterministic djb2 hash of the flowchart's CONTENT (base36). Node
|
||||
* positions and edge plumbing (ids, handles, styling) are excluded on
|
||||
* purpose: rearranging the canvas is not a story change and must not
|
||||
* re-badge conversations as NEW. Object keys are sorted so an equivalent
|
||||
* document serialized with a different key order hashes the same. */
|
||||
export function flowHash(flowData: unknown): string {
|
||||
const json = stableStringify(contentOnly(flowData));
|
||||
let h = 5381;
|
||||
for (let i = 0; i < json.length; i += 1) {
|
||||
h = ((h << 5) + h + json.charCodeAt(i)) | 0;
|
||||
}
|
||||
return (h >>> 0).toString(36);
|
||||
}
|
||||
|
||||
/** Strips layout from a flowchart, keeping node identity/branching/text. */
|
||||
function contentOnly(flowData: unknown): unknown {
|
||||
const doc = (flowData ?? {}) as { nodes?: unknown; edges?: unknown };
|
||||
const nodes = Array.isArray(doc.nodes) ? doc.nodes : [];
|
||||
const edges = Array.isArray(doc.edges) ? doc.edges : [];
|
||||
return {
|
||||
nodes: nodes.map((node) => {
|
||||
const n = (node ?? {}) as { id?: unknown; type?: unknown; data?: unknown };
|
||||
return { id: n.id, type: n.type, data: n.data };
|
||||
}),
|
||||
edges: edges.map((edge) => {
|
||||
const e = (edge ?? {}) as { source?: unknown; target?: unknown };
|
||||
return { source: e.source, target: e.target };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** JSON.stringify with sorted object keys for order-independent hashing. */
|
||||
function stableStringify(value: unknown): string {
|
||||
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
||||
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
||||
const entries = Object.entries(value as Record<string, unknown>)
|
||||
.filter(([, v]) => v !== undefined)
|
||||
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
|
||||
}
|
||||
|
||||
/** Reads the seen map; corrupt or absent storage reads empty. */
|
||||
export function loadSeenMap(): SeenMap {
|
||||
if (typeof window === "undefined") return {};
|
||||
try {
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return {};
|
||||
const parsed = JSON.parse(raw) as SeenMap;
|
||||
return parsed && typeof parsed === "object" ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** Persists the seen map; storage failures (private mode) are ignored. */
|
||||
export function saveSeenMap(map: SeenMap): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(map));
|
||||
} catch {
|
||||
// Best effort only.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Node ids from `nodeIds` this browser has not read yet. A missing entry or a
|
||||
* hash mismatch (the GM edited the flowchart) counts everything as unseen.
|
||||
*/
|
||||
export function unseenNodeIds(
|
||||
entry: SeenEntry | undefined,
|
||||
hash: string,
|
||||
nodeIds: readonly string[],
|
||||
): string[] {
|
||||
if (!entry || entry.hash !== hash) return [...nodeIds];
|
||||
const seen = new Set(entry.nodes);
|
||||
return nodeIds.filter((id) => !seen.has(id));
|
||||
}
|
||||
|
||||
/** Returns the updated node list for one conversation (deduped, sorted-free). */
|
||||
export function mergeSeenNodes(entry: SeenEntry | undefined, hash: string, nodeId: string): string[] {
|
||||
const nodes = entry && entry.hash === hash ? [...entry.nodes] : [];
|
||||
if (!nodes.includes(nodeId)) nodes.push(nodeId);
|
||||
return nodes;
|
||||
}
|
||||
|
|
@ -9,16 +9,12 @@
|
|||
* so this stays testable and client-safe.
|
||||
*/
|
||||
|
||||
import type { DialogueFlagCondition } from "./dialogue";
|
||||
import type { DialogueCondition } from "./dialogue";
|
||||
|
||||
/**
|
||||
* The stored entry gate shape on an npc-dialogues document. Entry gates stay
|
||||
* flat leaves by design (the DB column shape predates condition groups and
|
||||
* gating a whole conversation with one flag is the intended use).
|
||||
*/
|
||||
/** The stored entry gate shape on an npc-dialogues document. */
|
||||
export interface DialogueEntryGate {
|
||||
key?: string | null;
|
||||
op?: DialogueFlagCondition["op"] | null;
|
||||
op?: DialogueCondition["op"] | null;
|
||||
amount?: number | null;
|
||||
}
|
||||
|
||||
|
|
@ -30,9 +26,7 @@ export interface GateCandidate {
|
|||
}
|
||||
|
||||
/** Turns a stored gate into a runtime condition; null when ungated. */
|
||||
export function gateCondition(
|
||||
gate: DialogueEntryGate | null | undefined,
|
||||
): DialogueFlagCondition | null {
|
||||
export function gateCondition(gate: DialogueEntryGate | null | undefined): DialogueCondition | null {
|
||||
const key = gate?.key?.trim();
|
||||
if (!key || !gate) return null;
|
||||
return { kind: "flag", key, op: gate.op ?? "is_true", amount: gate.amount ?? 0 };
|
||||
|
|
@ -45,7 +39,7 @@ export function gateCondition(
|
|||
*/
|
||||
export async function selectDialogueForUser<T extends GateCandidate>(
|
||||
docs: readonly T[],
|
||||
evaluate: (condition: DialogueFlagCondition) => Promise<boolean>,
|
||||
evaluate: (condition: DialogueCondition) => Promise<boolean>,
|
||||
): Promise<T | null> {
|
||||
const ordered = [...docs].sort(
|
||||
(a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id - b.id,
|
||||
|
|
|
|||
|
|
@ -1,73 +0,0 @@
|
|||
import type { Payload } from "payload";
|
||||
|
||||
/**
|
||||
* Read markers powering the conversation NEW badges (npc-dialogue-states).
|
||||
* One row per (user, dialogue, nodeId): a node badges NEW until the player
|
||||
* has read it at least once. Server-side so progress follows the account
|
||||
* across devices, and GM edits never re-flag already-read content.
|
||||
*/
|
||||
|
||||
/** Node ids of `dialogueId` this user has already read. */
|
||||
export async function listSeenNodeIds(
|
||||
payload: Payload,
|
||||
userId: number,
|
||||
dialogueId: number,
|
||||
): Promise<string[]> {
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogue-states",
|
||||
where: {
|
||||
and: [{ user: { equals: userId } }, { dialogue: { equals: dialogueId } }],
|
||||
},
|
||||
limit: 500,
|
||||
depth: 0,
|
||||
select: { nodeId: true },
|
||||
overrideAccess: true,
|
||||
});
|
||||
return res.docs.map((doc) => doc.nodeId).filter((id): id is string => Boolean(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that the user read one conversation node. Idempotent: repeated
|
||||
* calls for the same node are no-ops (the unique index makes racing writes
|
||||
* safe too - a duplicate just resolves to the existing row).
|
||||
*/
|
||||
export async function markNodeRead(
|
||||
payload: Payload,
|
||||
userId: number,
|
||||
dialogueId: number,
|
||||
nodeId: string,
|
||||
): Promise<void> {
|
||||
const existing = await payload.find({
|
||||
collection: "npc-dialogue-states",
|
||||
where: {
|
||||
and: [
|
||||
{ user: { equals: userId } },
|
||||
{ dialogue: { equals: dialogueId } },
|
||||
{ nodeId: { equals: nodeId } },
|
||||
],
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
if (existing.docs.length > 0) return;
|
||||
|
||||
try {
|
||||
await payload.create({
|
||||
collection: "npc-dialogue-states",
|
||||
data: {
|
||||
user: userId,
|
||||
dialogue: dialogueId,
|
||||
nodeId,
|
||||
readAt: new Date().toISOString(),
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
} catch (error) {
|
||||
// A concurrent write won the race against the unique index: the marker
|
||||
// exists either way, which is all this call promises.
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
if (!/duplicate key|violates unique constraint/i.test(message)) throw error;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,43 +0,0 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
CREATE TABLE "npc_dialogue_states" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" integer NOT NULL,
|
||||
"dialogue_id" integer NOT NULL,
|
||||
"node_id" varchar NOT NULL,
|
||||
"read_at" timestamp(3) with time zone,
|
||||
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_find" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_create" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_update" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_delete" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "npc_dialogue_states_id" integer;
|
||||
ALTER TABLE "npc_dialogue_states" ADD CONSTRAINT "npc_dialogue_states_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "npc_dialogue_states" ADD CONSTRAINT "npc_dialogue_states_dialogue_id_npc_dialogues_id_fk" FOREIGN KEY ("dialogue_id") REFERENCES "public"."npc_dialogues"("id") ON DELETE set null ON UPDATE no action;
|
||||
CREATE INDEX "npc_dialogue_states_user_idx" ON "npc_dialogue_states" USING btree ("user_id");
|
||||
CREATE INDEX "npc_dialogue_states_dialogue_idx" ON "npc_dialogue_states" USING btree ("dialogue_id");
|
||||
CREATE INDEX "npc_dialogue_states_updated_at_idx" ON "npc_dialogue_states" USING btree ("updated_at");
|
||||
CREATE INDEX "npc_dialogue_states_created_at_idx" ON "npc_dialogue_states" USING btree ("created_at");
|
||||
CREATE UNIQUE INDEX "user_dialogue_nodeId_idx" ON "npc_dialogue_states" USING btree ("user_id","dialogue_id","node_id");
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_npc_dialogue_states_fk" FOREIGN KEY ("npc_dialogue_states_id") REFERENCES "public"."npc_dialogue_states"("id") ON DELETE cascade ON UPDATE no action;
|
||||
CREATE INDEX "payload_locked_documents_rels_npc_dialogue_states_id_idx" ON "payload_locked_documents_rels" USING btree ("npc_dialogue_states_id");`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "npc_dialogue_states" DISABLE ROW LEVEL SECURITY;
|
||||
DROP TABLE "npc_dialogue_states" CASCADE;
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_npc_dialogue_states_fk";
|
||||
|
||||
DROP INDEX "payload_locked_documents_rels_npc_dialogue_states_id_idx";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_find";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_create";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_update";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_delete";
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "npc_dialogue_states_id";`)
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,17 +0,0 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "game_event_logs" ADD COLUMN "discord_requested" boolean DEFAULT false;
|
||||
ALTER TABLE "game_event_logs" ADD COLUMN "discord_announced_at" timestamp(3) with time zone;
|
||||
ALTER TABLE "game_event_logs" ADD COLUMN "discord_message_id" varchar;
|
||||
CREATE INDEX "game_event_logs_discord_requested_idx" ON "game_event_logs" USING btree ("discord_requested");`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
DROP INDEX "game_event_logs_discord_requested_idx";
|
||||
ALTER TABLE "game_event_logs" DROP COLUMN "discord_requested";
|
||||
ALTER TABLE "game_event_logs" DROP COLUMN "discord_announced_at";
|
||||
ALTER TABLE "game_event_logs" DROP COLUMN "discord_message_id";`)
|
||||
}
|
||||
|
|
@ -134,8 +134,6 @@ import * as migration_20261012_182016_add_journals_event_target from './20261012
|
|||
import * as migration_20261012_185409_add_award_rules_automation from './20261012_185409_add_award_rules_automation';
|
||||
import * as migration_20261013_183041_add_journal_contribution_type from './20261013_183041_add_journal_contribution_type';
|
||||
import * as migration_20261013_184745_add_garage_fields from './20261013_184745_add_garage_fields';
|
||||
import * as migration_20261014_192950_add_npc_dialogue_states from './20261014_192950_add_npc_dialogue_states';
|
||||
import * as migration_20261014_203529_add_event_log_discord_fields from './20261014_203529_add_event_log_discord_fields';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -816,16 +814,6 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261013_184745_add_garage_fields.up,
|
||||
down: migration_20261013_184745_add_garage_fields.down,
|
||||
name: '20261013_184745_add_garage_fields',
|
||||
},
|
||||
{
|
||||
up: migration_20261014_192950_add_npc_dialogue_states.up,
|
||||
down: migration_20261014_192950_add_npc_dialogue_states.down,
|
||||
name: '20261014_192950_add_npc_dialogue_states',
|
||||
},
|
||||
{
|
||||
up: migration_20261014_203529_add_event_log_discord_fields.up,
|
||||
down: migration_20261014_203529_add_event_log_discord_fields.down,
|
||||
name: '20261014_203529_add_event_log_discord_fields'
|
||||
name: '20261013_184745_add_garage_fields'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -76,7 +76,6 @@ export interface Config {
|
|||
'game-npcs': GameNpc;
|
||||
'npc-staffing': NpcStaffing;
|
||||
'npc-dialogues': NpcDialogue;
|
||||
'npc-dialogue-states': NpcDialogueState;
|
||||
'player-flags': PlayerFlag;
|
||||
'reinforcement-pools': ReinforcementPool;
|
||||
'labor-classifications': LaborClassification;
|
||||
|
|
@ -184,7 +183,6 @@ export interface Config {
|
|||
'game-npcs': GameNpcsSelect<false> | GameNpcsSelect<true>;
|
||||
'npc-staffing': NpcStaffingSelect<false> | NpcStaffingSelect<true>;
|
||||
'npc-dialogues': NpcDialoguesSelect<false> | NpcDialoguesSelect<true>;
|
||||
'npc-dialogue-states': NpcDialogueStatesSelect<false> | NpcDialogueStatesSelect<true>;
|
||||
'player-flags': PlayerFlagsSelect<false> | PlayerFlagsSelect<true>;
|
||||
'reinforcement-pools': ReinforcementPoolsSelect<false> | ReinforcementPoolsSelect<true>;
|
||||
'labor-classifications': LaborClassificationsSelect<false> | LaborClassificationsSelect<true>;
|
||||
|
|
@ -2670,30 +2668,6 @@ export interface NpcDialogue {
|
|||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* Per-user read markers for NPC conversation nodes (NEW badges).
|
||||
*
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "npc-dialogue-states".
|
||||
*/
|
||||
export interface NpcDialogueState {
|
||||
id: number;
|
||||
user: number | User;
|
||||
/**
|
||||
* The conversation this marker belongs to.
|
||||
*/
|
||||
dialogue: number | NpcDialogue;
|
||||
/**
|
||||
* Flowchart node id the player has read.
|
||||
*/
|
||||
nodeId: string;
|
||||
/**
|
||||
* When the user first read the node.
|
||||
*/
|
||||
readAt?: string | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "player-flags".
|
||||
|
|
@ -3241,18 +3215,6 @@ export interface GameEventLog {
|
|||
| number
|
||||
| boolean
|
||||
| null;
|
||||
/**
|
||||
* Queued for the bot's NPC dispatch channel. Set at emit time by dialogue event effects; the poll service stamps the announcement columns once posted.
|
||||
*/
|
||||
discordRequested?: boolean | null;
|
||||
/**
|
||||
* Set by the bot when the dispatch posts. Empty with a request above means queued or retrying.
|
||||
*/
|
||||
discordAnnouncedAt?: string | null;
|
||||
/**
|
||||
* Discord message id of the posted dispatch.
|
||||
*/
|
||||
discordMessageId?: string | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
|
@ -6753,24 +6715,6 @@ export interface PayloadMcpApiKey {
|
|||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
npcDialogueStates?: {
|
||||
/**
|
||||
* Allow clients to find npc-dialogue-states.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create npc-dialogue-states.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update npc-dialogue-states.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete npc-dialogue-states.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
playerFlags?: {
|
||||
/**
|
||||
* Allow clients to find player-flags.
|
||||
|
|
@ -8292,10 +8236,6 @@ export interface PayloadLockedDocument {
|
|||
relationTo: 'npc-dialogues';
|
||||
value: number | NpcDialogue;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'npc-dialogue-states';
|
||||
value: number | NpcDialogueState;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'player-flags';
|
||||
value: number | PlayerFlag;
|
||||
|
|
@ -8983,18 +8923,6 @@ export interface NpcDialoguesSelect<T extends boolean = true> {
|
|||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "npc-dialogue-states_select".
|
||||
*/
|
||||
export interface NpcDialogueStatesSelect<T extends boolean = true> {
|
||||
user?: T;
|
||||
dialogue?: T;
|
||||
nodeId?: T;
|
||||
readAt?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "player-flags_select".
|
||||
|
|
@ -9054,9 +8982,6 @@ export interface GameEventLogsSelect<T extends boolean = true> {
|
|||
targetCollection?: T;
|
||||
targetId?: T;
|
||||
data?: T;
|
||||
discordRequested?: T;
|
||||
discordAnnouncedAt?: T;
|
||||
discordMessageId?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
|
|
@ -11431,14 +11356,6 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
|||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
npcDialogueStates?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
playerFlags?:
|
||||
| T
|
||||
| {
|
||||
|
|
|
|||
|
|
@ -57,7 +57,6 @@ 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 { NpcDialogueStates } from "@/collections/game/NpcDialogueStates";
|
||||
import { PlayerFlags } from "@/collections/game/PlayerFlags";
|
||||
import { ReinforcementPools } from "@/collections/game/ReinforcementPools";
|
||||
import { LaborClassifications } from "@/collections/game/LaborClassifications";
|
||||
|
|
@ -281,7 +280,6 @@ const collections = [
|
|||
GameNpcs,
|
||||
NpcStaffing,
|
||||
NpcDialogues,
|
||||
NpcDialogueStates,
|
||||
PlayerFlags,
|
||||
ReinforcementPools,
|
||||
LaborClassifications,
|
||||
|
|
|
|||
|
|
@ -67,12 +67,6 @@ interface GameEventInput {
|
|||
visibility?: EventVisibility;
|
||||
/** Any-of permission gate for restricted events. See `visibility`. */
|
||||
requiredPermissions?: Permission[];
|
||||
/**
|
||||
* Queue this entry for the bot's NPC dispatch channel (the poll service
|
||||
* posts it and stamps `discordAnnouncedAt`). Only meaningful for events
|
||||
* worth broadcasting unit-wide; dialogue event effects set it per authoring.
|
||||
*/
|
||||
discordRequested?: boolean;
|
||||
}
|
||||
|
||||
export async function emitGameEvent(
|
||||
|
|
@ -98,7 +92,6 @@ export async function emitGameEvent(
|
|||
structure: event.structure,
|
||||
visibility: policy.visibility,
|
||||
requiredPermissions: policy.requiredPermissions,
|
||||
discordRequested: event.discordRequested === true,
|
||||
},
|
||||
depth: 0,
|
||||
// Bins and tests run without an authenticated user; create access on
|
||||
|
|
|
|||
|
|
@ -1,79 +0,0 @@
|
|||
import { getPayload, Payload } from "payload";
|
||||
import config from "@/payload.config";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const RUN = `evdisc-${Date.now().toString(36)}`;
|
||||
const TIMEOUT = 30_000;
|
||||
const eventIds: number[] = [];
|
||||
|
||||
/** Emit an event and return its persisted document. */
|
||||
async function emit(input: Parameters<typeof emitGameEvent>[1]) {
|
||||
await emitGameEvent(payload, input);
|
||||
const res = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: { message: { equals: input.message } },
|
||||
sort: "-id",
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
const doc = res.docs[0];
|
||||
expect(doc).toBeDefined();
|
||||
eventIds.push(doc.id);
|
||||
return doc;
|
||||
}
|
||||
|
||||
describe("discordRequested flag on game events", () => {
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config });
|
||||
}, TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
for (const id of eventIds) {
|
||||
await payload
|
||||
.delete({ collection: "game-event-logs", id, overrideAccess: true })
|
||||
.catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
it(
|
||||
"persists discordRequested when the emitter opts in",
|
||||
async () => {
|
||||
const doc = await emit({
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `${RUN} opted in`,
|
||||
discordRequested: true,
|
||||
});
|
||||
expect(doc.discordRequested).toBe(true);
|
||||
// The bot stamps these only after posting; emitting must leave them clear.
|
||||
expect(doc.discordAnnouncedAt).toBeFalsy();
|
||||
expect(doc.discordMessageId).toBeFalsy();
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"defaults to false when omitted or explicitly false",
|
||||
async () => {
|
||||
const omitted = await emit({
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `${RUN} omitted`,
|
||||
});
|
||||
expect(omitted.discordRequested).toBe(false);
|
||||
|
||||
const explicitFalse = await emit({
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `${RUN} explicit false`,
|
||||
discordRequested: false,
|
||||
});
|
||||
expect(explicitFalse.discordRequested).toBe(false);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
});
|
||||
|
|
@ -1,96 +0,0 @@
|
|||
import { getPayload, Payload } from "payload";
|
||||
import config from "@/payload.config";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveAttachments } from "@/lib/npc-dialogue/attachments";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
/** Create a tiny media doc and return its id. */
|
||||
async function createMedia(name: string): Promise<number> {
|
||||
const doc = await payload.create({
|
||||
collection: "media",
|
||||
data: { alt: name },
|
||||
file: {
|
||||
data: Buffer.from(`attachment fixture: ${name}`),
|
||||
mimetype: "text/plain",
|
||||
name,
|
||||
size: 24,
|
||||
},
|
||||
overrideAccess: true,
|
||||
});
|
||||
return doc.id;
|
||||
}
|
||||
|
||||
describe("resolveAttachments", () => {
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config });
|
||||
}, TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
// Nothing persists: each test cleans up its own docs below.
|
||||
});
|
||||
|
||||
it(
|
||||
"returns nothing for missing or empty input",
|
||||
async () => {
|
||||
expect(await resolveAttachments(payload, undefined)).toEqual([]);
|
||||
expect(await resolveAttachments(payload, [])).toEqual([]);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"resolves pointers to renderable references, honouring custom labels",
|
||||
async () => {
|
||||
const id = await createMedia("b2-int-transcript.txt");
|
||||
try {
|
||||
const [resolved] = await resolveAttachments(payload, [
|
||||
{ mediaId: id, label: "Intercept transcript" },
|
||||
]);
|
||||
expect(resolved).toMatchObject({
|
||||
label: "Intercept transcript",
|
||||
url: "/api/media/file/b2-int-transcript.txt",
|
||||
filename: "b2-int-transcript.txt",
|
||||
mimeType: "text/plain",
|
||||
});
|
||||
} finally {
|
||||
await payload.delete({ collection: "media", id, overrideAccess: true });
|
||||
}
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"falls back to the stored filename when no label is authored",
|
||||
async () => {
|
||||
const id = await createMedia("b2-int-order.txt");
|
||||
try {
|
||||
const [resolved] = await resolveAttachments(payload, [{ mediaId: id }]);
|
||||
expect(resolved?.label).toBe("b2-int-order.txt");
|
||||
} finally {
|
||||
await payload.delete({ collection: "media", id, overrideAccess: true });
|
||||
}
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"skips deleted media and malformed pointers instead of rendering dead chips",
|
||||
async () => {
|
||||
const doomed = await createMedia("b2-int-doomed.txt");
|
||||
await payload.delete({ collection: "media", id: doomed, overrideAccess: true });
|
||||
const resolved = await resolveAttachments(payload, [
|
||||
{ mediaId: doomed },
|
||||
{ mediaId: 0 },
|
||||
{ mediaId: "not-a-number" },
|
||||
{ mediaId: -3 },
|
||||
]);
|
||||
expect(resolved).toEqual([]);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
});
|
||||
|
|
@ -1,160 +0,0 @@
|
|||
import { getPayload, Payload } from "payload";
|
||||
import config from "@/payload.config";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import type { DialogueCondition, DialogueFlagCondition } from "@/lib/npc-dialogue/dialogue";
|
||||
import { applyFlagEffect, evaluateCondition } from "@/lib/npc-dialogue/flags";
|
||||
import { conditionSummary, hasEmptyConditionKey, validateGraph } from "@/lib/npc-dialogue/dialogue";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const RUN = `grp_${Date.now().toString(36)}`;
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
const userIds: number[] = [];
|
||||
|
||||
async function createUser(username: string): Promise<number> {
|
||||
const user = (await payload.create({
|
||||
collection: "users",
|
||||
data: {
|
||||
username,
|
||||
discordUsername: username,
|
||||
displayName: `GRP ${username}`,
|
||||
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||
password: "Test123",
|
||||
roles: ["user"],
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as { id: number };
|
||||
userIds.push(user.id);
|
||||
return user.id;
|
||||
}
|
||||
|
||||
describe("condition groups (and / or / nor over leaf conditions)", () => {
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config });
|
||||
}, TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
const flags = await payload.find({
|
||||
collection: "player-flags",
|
||||
where: { key: { like: `${RUN}_%` } },
|
||||
limit: 200,
|
||||
overrideAccess: true,
|
||||
});
|
||||
for (const doc of flags.docs) {
|
||||
await payload.delete({ collection: "player-flags", id: doc.id, overrideAccess: true });
|
||||
}
|
||||
for (const id of userIds) {
|
||||
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
it(
|
||||
"combines leaves with and / or / nor against live flags",
|
||||
async () => {
|
||||
const user = await createUser(`${RUN}_combo`);
|
||||
await applyFlagEffect(payload, user, `${RUN}_a`, "set_true", 0);
|
||||
await applyFlagEffect(payload, user, `${RUN}_rep`, "set_number", 7);
|
||||
|
||||
const leafA: DialogueFlagCondition = { kind: "flag", key: `${RUN}_a`, op: "is_true" };
|
||||
const leafMissing: DialogueFlagCondition = {
|
||||
kind: "flag",
|
||||
key: `${RUN}_nope`,
|
||||
op: "is_true",
|
||||
};
|
||||
const leafRep: DialogueFlagCondition = { kind: "flag", key: `${RUN}_rep`, op: "gte", amount: 5 };
|
||||
const leafRepFail: DialogueFlagCondition = {
|
||||
kind: "flag",
|
||||
key: `${RUN}_rep`,
|
||||
op: "gte",
|
||||
amount: 99,
|
||||
};
|
||||
|
||||
const evalGroup = (op: "and" | "or" | "nor", children: DialogueFlagCondition[]) =>
|
||||
evaluateCondition(payload, user, { kind: "group", op, children });
|
||||
|
||||
expect(await evalGroup("and", [leafA, leafRep])).toBe(true);
|
||||
expect(await evalGroup("and", [leafA, leafMissing])).toBe(false);
|
||||
expect(await evalGroup("or", [leafMissing, leafRep])).toBe(true);
|
||||
expect(await evalGroup("or", [leafMissing, leafRepFail])).toBe(false);
|
||||
expect(await evalGroup("nor", [leafMissing, leafRepFail])).toBe(true);
|
||||
expect(await evalGroup("nor", [leafA, leafRepFail])).toBe(false);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"treats empty groups as vacuous (and/nor pass, or fails) and leaves still work",
|
||||
async () => {
|
||||
const user = await createUser(`${RUN}_empty`);
|
||||
expect(await evaluateCondition(payload, user, { kind: "group", op: "and", children: [] })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(await evaluateCondition(payload, user, { kind: "group", op: "nor", children: [] })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(await evaluateCondition(payload, user, { kind: "group", op: "or", children: [] })).toBe(
|
||||
false,
|
||||
);
|
||||
// A plain leaf keeps its old semantics.
|
||||
expect(
|
||||
await evaluateCondition(payload, user, { kind: "flag", key: `${RUN}_x`, op: "is_false" }),
|
||||
).toBe(true);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it("summarises and validates groups for the editor", () => {
|
||||
const group: DialogueCondition = {
|
||||
kind: "group",
|
||||
op: "or",
|
||||
children: [
|
||||
{ kind: "flag", key: "met_informant", op: "is_true" },
|
||||
{ kind: "flag", key: "rep", op: "gte", amount: 5 },
|
||||
],
|
||||
};
|
||||
expect(conditionSummary(group)).toBe('"met_informant" is true or "rep" gte 5');
|
||||
expect(hasEmptyConditionKey(group)).toBe(false);
|
||||
expect(
|
||||
hasEmptyConditionKey({
|
||||
kind: "group",
|
||||
op: "and",
|
||||
children: [{ kind: "flag", key: " ", op: "is_true" }],
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(hasEmptyConditionKey({ kind: "group", op: "and", children: [] })).toBe(true);
|
||||
|
||||
const nodes = [
|
||||
{
|
||||
id: "start",
|
||||
type: "dialogue" as const,
|
||||
position: { x: 0, y: 0 },
|
||||
data: { isStart: true, body: "hi", next: { target: "c1" } },
|
||||
},
|
||||
{
|
||||
id: "c1",
|
||||
type: "choice" as const,
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
choices: [
|
||||
{
|
||||
label: "Ask",
|
||||
target: "",
|
||||
condition: {
|
||||
kind: "group" as const,
|
||||
op: "and" as const,
|
||||
children: [{ kind: "flag" as const, key: " ", op: "is_true" as const }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
const validation = validateGraph(nodes);
|
||||
expect(validation.valid).toBe(false);
|
||||
expect(validation.errors.join(" ")).toContain("needs a flag key");
|
||||
});
|
||||
});
|
||||
|
|
@ -9,17 +9,16 @@ import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
|
|||
import { DialogueText, formatRemaining } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { gateCondition, selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
||||
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
|
||||
import { flowHash, mergeSeenNodes, unseenNodeIds } from "@/lib/npc-dialogue/seen";
|
||||
import {
|
||||
collectNodeTokens,
|
||||
extractCountdownKeys,
|
||||
extractFlagTokens,
|
||||
extractTernaryKeys,
|
||||
formatFlagValue,
|
||||
hasFlagTokens,
|
||||
interpolateFlags,
|
||||
replaceCountdowns,
|
||||
resolveNodeTexts,
|
||||
resolveTernaries,
|
||||
} from "@/lib/npc-dialogue/interpolate";
|
||||
|
||||
let payload: Payload;
|
||||
|
|
@ -457,99 +456,54 @@ describe("countdown token resolution (pure)", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("ternary tokens ({{ cond ? yes : no }})", () => {
|
||||
const truths = {
|
||||
trust: { bool: true, num: 1 },
|
||||
met: { bool: false, num: 0 },
|
||||
rep: { bool: true, num: 7 },
|
||||
};
|
||||
|
||||
it("picks branches by boolean truth, negation and numeric comparison", () => {
|
||||
expect(resolveTernaries("He is {{ trust ? friend : hostile }}.", truths)).toBe(
|
||||
"He is friend.",
|
||||
);
|
||||
expect(resolveTernaries("He is {{ met ? friend : hostile }}.", truths)).toBe(
|
||||
"He is hostile.",
|
||||
);
|
||||
expect(resolveTernaries("{{ !met ? who_are_you : welcome_back }}", truths)).toBe(
|
||||
"who_are_you",
|
||||
);
|
||||
expect(resolveTernaries("{{ rep >= 5 ? elite : rookie }}", truths)).toBe("elite");
|
||||
expect(resolveTernaries("{{ rep > 10 ? elite : rookie }}", truths)).toBe("rookie");
|
||||
expect(resolveTernaries("{{ rep = 7 ? exact : off }}", truths)).toBe("exact");
|
||||
describe("seen tracking (NEW badges)", () => {
|
||||
it("hashes flowcharts deterministically and differently on change", () => {
|
||||
expect(flowHash({ nodes: [{ id: "a" }] })).toBe(flowHash({ nodes: [{ id: "a" }] }));
|
||||
expect(flowHash({ nodes: [{ id: "a" }] })).not.toBe(flowHash({ nodes: [{ id: "b" }] }));
|
||||
});
|
||||
|
||||
it("treats missing flags as falsy and keeps malformed tokens literal", () => {
|
||||
expect(resolveTernaries("{{ ghost ? a : b }}", truths)).toBe("b");
|
||||
expect(resolveTernaries("{{ !ghost ? a : b }}", truths)).toBe("a");
|
||||
// Not ternaries: plain flag, countdown, and a token without a colon.
|
||||
const plain = "Status {{network_status}} at {{countdown:exfil}} maybe {{ broken";
|
||||
expect(resolveTernaries(plain, truths)).toBe(plain);
|
||||
});
|
||||
|
||||
it("leaves nested tokens for the later passes and resolves nested ternaries", () => {
|
||||
// Branch tokens survive resolveTernaries; interpolateFlags fills them next.
|
||||
const once = resolveTernaries("{{ trust ? {{ rep }} pts : none }}", truths);
|
||||
expect(once).toBe("{{ rep }} pts");
|
||||
expect(interpolateFlags(once, { rep: "7" })).toBe("7 pts");
|
||||
// A ternary inside a branch resolves on the second bounded pass.
|
||||
expect(
|
||||
resolveTernaries("{{ trust ? {{ met ? seen : new }} : dark }}", truths),
|
||||
).toBe("new");
|
||||
});
|
||||
|
||||
it("extracts condition keys (negated and numeric) for the flag read", () => {
|
||||
// The third token has no `?`, so it is not a ternary and contributes nothing.
|
||||
expect(extractTernaryKeys("{{ trust ? a : b }} {{ !met ? c : d }} {{ rep >= 2 : e : f }}")).toEqual([
|
||||
"trust",
|
||||
"met",
|
||||
]);
|
||||
expect(extractTernaryKeys("{{ rep >= 2 ? e : f }}")).toEqual(["rep"]);
|
||||
expect(extractTernaryKeys("no tokens {{plain}} {{countdown:x}}")).toEqual([]);
|
||||
});
|
||||
|
||||
it("resolves through resolveNodeTexts with values, countdowns and truths", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "t1",
|
||||
type: "dialogue",
|
||||
position: { x: 0, y: 0 },
|
||||
data: { body: "{{ trust ? Status {{ rep }} : silent }} {{countdown:exfil}}" },
|
||||
it("ignores layout (positions, edge ids/styling) and key order", () => {
|
||||
const base = {
|
||||
nodes: [{ id: "a", type: "dialogue", position: { x: 0, y: 0 }, data: { body: "hi" } }],
|
||||
edges: [{ id: "e1", source: "a", target: "b", style: {} }],
|
||||
};
|
||||
const resolved = resolveNodeTexts(node, { rep: "7" }, { exfil: "done" }, truths);
|
||||
expect(resolved.body).toBe("Status 7 {cd|done}");
|
||||
// collectNodeTokens must see ternary keys so the server reads those flags.
|
||||
expect(collectNodeTokens(node)).toEqual(expect.arrayContaining(["trust", "rep", "exfil"]));
|
||||
});
|
||||
});
|
||||
|
||||
describe("block lists in dialogue markup", () => {
|
||||
const render = (text: string) => renderToStaticMarkup(createElement(DialogueText, { text }));
|
||||
|
||||
it("renders consecutive dash lines as one bullet list with markers", () => {
|
||||
const html = render("- first\n- second");
|
||||
expect(html).toContain('role="list"');
|
||||
expect(html.match(/role="listitem"/g)?.length).toBe(2);
|
||||
expect(html).toContain("first");
|
||||
expect(html).toContain("\u2022");
|
||||
});
|
||||
|
||||
it("renders numbered lines as an ordered list and keeps inline markup inside items", () => {
|
||||
const html = render("1. **one**\n2. *two*");
|
||||
expect(html).toContain("one</strong>");
|
||||
expect(html).toContain("<em>two</em>");
|
||||
expect(html).toContain("1.");
|
||||
expect(html).toContain("2.");
|
||||
});
|
||||
|
||||
it("splits paragraphs from lists and adjacent kinds into separate lists", () => {
|
||||
const html = render("intro line\n- a\n- b\n\n1. x\n1. y");
|
||||
expect(html.match(/role="list"/g)?.length).toBe(2);
|
||||
expect(html).toContain("intro line");
|
||||
});
|
||||
|
||||
it("does not treat leading emphasis or prose asterisks as bullets", () => {
|
||||
const html = render("*emphasis start* is fine");
|
||||
expect(html).toContain("<em>emphasis start</em>");
|
||||
expect(html).not.toContain('role="list"');
|
||||
const rearranged = {
|
||||
nodes: [{ id: "a", type: "dialogue", position: { x: 900, y: 400 }, data: { body: "hi" } }],
|
||||
edges: [{ id: "zzz", source: "a", target: "b", style: { stroke: "red" } }],
|
||||
};
|
||||
expect(flowHash(rearranged)).toBe(flowHash(base));
|
||||
const reordered = {
|
||||
nodes: [{ data: { body: "hi" }, type: "dialogue", id: "a" }],
|
||||
edges: [{ target: "b", source: "a" }],
|
||||
};
|
||||
expect(flowHash(reordered)).toBe(flowHash(base));
|
||||
});
|
||||
|
||||
it("re-flags when node content changes", () => {
|
||||
const base = { nodes: [{ id: "a", type: "dialogue", data: { body: "hi" } }] };
|
||||
const edited = { nodes: [{ id: "a", type: "dialogue", data: { body: "changed" } }] };
|
||||
expect(flowHash(edited)).not.toBe(flowHash(base));
|
||||
const addedChoice = {
|
||||
nodes: [
|
||||
{ id: "a", type: "dialogue", data: { body: "hi" } },
|
||||
{ id: "b", type: "choice", data: { choices: [{ label: "New path", target: "a" }] } },
|
||||
],
|
||||
};
|
||||
expect(flowHash(addedChoice)).not.toBe(flowHash(base));
|
||||
});
|
||||
|
||||
it("treats a hash mismatch as everything unseen", () => {
|
||||
expect(unseenNodeIds({ hash: "old", nodes: ["a", "b"] }, "new", ["a", "b"])).toEqual([
|
||||
"a",
|
||||
"b",
|
||||
]);
|
||||
expect(unseenNodeIds({ hash: "x", nodes: ["a"] }, "x", ["a", "b"])).toEqual(["b"]);
|
||||
expect(unseenNodeIds(undefined, "x", ["a"])).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("merges seen nodes without duplicates and resets on new hash", () => {
|
||||
expect(mergeSeenNodes({ hash: "x", nodes: ["a"] }, "x", "a")).toEqual(["a"]);
|
||||
expect(mergeSeenNodes({ hash: "x", nodes: ["a"] }, "x", "b")).toEqual(["a", "b"]);
|
||||
expect(mergeSeenNodes({ hash: "old", nodes: ["a"] }, "new", "b")).toEqual(["b"]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue