Compare commits
8 commits
9f8a0d87ea
...
4ce82a1f87
| Author | SHA1 | Date | |
|---|---|---|---|
| 4ce82a1f87 | |||
| 9c27d48649 | |||
| 1110315214 | |||
| 36f4bf5e1a | |||
| 18ea696d1b | |||
| 66a4337ba5 | |||
| b0457a17b3 | |||
| 04bbc66edc |
42 changed files with 190542 additions and 183 deletions
17
CHANGELOG.md
17
CHANGELOG.md
|
|
@ -1,5 +1,22 @@
|
|||
# Changelog
|
||||
|
||||
# v0.18.0
|
||||
|
||||
Conversations can be spoken aloud and type themselves out, and you decide whether either happens.
|
||||
|
||||
### Features
|
||||
|
||||
- **Spoken lines.** A conversation can now play a voice recording as each line appears, with the text keeping pace with the read. A speaker button in the conversation header mutes the audio for that conversation, and your account preferences hold a permanent on/off switch.
|
||||
- **Typing lines.** Conversation text arrives a character at a time instead of all at once, and clicking a line finishes it immediately. You can turn this off in your account preferences; devices that ask for reduced motion never animate.
|
||||
- **Narrator passages.** A contact's descriptive passages now read as centered, quiet text, set apart from the lines the contact speaks.
|
||||
|
||||
### Fixes
|
||||
|
||||
- A conversation's opening choices now appear with its lead-in line instead of after it.
|
||||
- Various bug fixes and improvements.
|
||||
|
||||
---
|
||||
|
||||
# v0.17.0
|
||||
|
||||
### Fixes
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "polaris-task-force",
|
||||
"version": "0.17.0",
|
||||
"version": "0.18.0",
|
||||
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -210,6 +210,8 @@ export async function updatePreferences(input: {
|
|||
discordEnabled: boolean;
|
||||
discordMutedTypes: string[];
|
||||
xpDisplayMini: boolean;
|
||||
conversationTypewriter: "default" | "on" | "off";
|
||||
conversationVoice: boolean;
|
||||
}): Promise<ActionResult> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
|
@ -246,6 +248,10 @@ export async function updatePreferences(input: {
|
|||
xpDisplayMini: input.xpDisplayMini,
|
||||
sidebarOrder: stored.display?.sidebarOrder ?? null,
|
||||
},
|
||||
dialogue: {
|
||||
typewriter: input.conversationTypewriter,
|
||||
voice: input.conversationVoice,
|
||||
},
|
||||
discord: {
|
||||
enabled: input.discordEnabled,
|
||||
mutedTypes: discordMutedTypes,
|
||||
|
|
|
|||
|
|
@ -181,6 +181,8 @@ export default async function AccountPage() {
|
|||
mutedTypes={notifications?.mutedTypes ?? []}
|
||||
showCallsign={fullUser.preferences?.display?.showCallsign ?? false}
|
||||
showVersionOverlay={fullUser.preferences?.display?.showVersionOverlay ?? true}
|
||||
conversationTypewriter={fullUser.preferences?.dialogue?.typewriter ?? "default"}
|
||||
conversationVoice={fullUser.preferences?.dialogue?.voice !== false}
|
||||
showBackgroundTexture={fullUser.preferences?.display?.showBackgroundTexture ?? true}
|
||||
leadOrActual={fullUser.preferences?.display?.leadOrActual ?? "lead"}
|
||||
discordEnabled={discord?.enabled ?? false}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,9 @@ import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpol
|
|||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
|
||||
import { markNodeRead } from "@/lib/npc-dialogue/states";
|
||||
import { resolveAttachments } from "@/lib/npc-dialogue/attachments";
|
||||
import { canSeeTestingDialogues, loadPlayerDialogue } from "@/lib/npc-dialogue/visibility";
|
||||
import { resolveAttachments, resolveVoiceClip } from "@/lib/npc-dialogue/attachments";
|
||||
import { transcodeToMp3, MP3_MIMETYPE } from "@/lib/voiceover/transcode";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { generateDialogueDraft, rewriteDialogueLine } from "@/lib/npc-dialogue/generation";
|
||||
import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings";
|
||||
|
|
@ -67,20 +69,23 @@ async function authenticate() {
|
|||
* only trigger effects an admin has authored for this conversation.
|
||||
*/
|
||||
export async function triggerNpcDialogueEvent(
|
||||
dialogueId: number,
|
||||
npcId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
// The client names the conversation it is in; the id is verified (right
|
||||
// NPC, and visible to this reader) instead of trusted, so an unreleased
|
||||
// testing conversation cannot be read by guessing a node id.
|
||||
const dialogue = await loadPlayerDialogue(payload, {
|
||||
npcId,
|
||||
dialogueId,
|
||||
userId: user.id as number,
|
||||
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||
});
|
||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
||||
const flowData = dialogue?.flowData;
|
||||
if (!flowData || !Array.isArray(flowData.nodes)) {
|
||||
return { success: false, error: "This contact has no conversation configured." };
|
||||
}
|
||||
|
|
@ -188,20 +193,23 @@ async function runEffect(
|
|||
* authored for this conversation.
|
||||
*/
|
||||
export async function evaluateNpcDialogueCondition(
|
||||
dialogueId: number,
|
||||
npcId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult<boolean>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
// The client names the conversation it is in; the id is verified (right
|
||||
// NPC, and visible to this reader) instead of trusted, so an unreleased
|
||||
// testing conversation cannot be read by guessing a node id.
|
||||
const dialogue = await loadPlayerDialogue(payload, {
|
||||
npcId,
|
||||
dialogueId,
|
||||
userId: user.id as number,
|
||||
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||
});
|
||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
||||
const flowData = dialogue?.flowData;
|
||||
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
||||
if (!node || node.type !== "condition" || !node.data.condition) {
|
||||
// Not a condition node: nothing to branch on.
|
||||
|
|
@ -228,20 +236,23 @@ export async function evaluateNpcDialogueCondition(
|
|||
* config for conversations an admin has not authored.
|
||||
*/
|
||||
export async function evaluateNpcDialogueChoices(
|
||||
dialogueId: number,
|
||||
npcId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult<ChoiceGate[]>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
// The client names the conversation it is in; the id is verified (right
|
||||
// NPC, and visible to this reader) instead of trusted, so an unreleased
|
||||
// testing conversation cannot be read by guessing a node id.
|
||||
const dialogue = await loadPlayerDialogue(payload, {
|
||||
npcId,
|
||||
dialogueId,
|
||||
userId: user.id as number,
|
||||
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||
});
|
||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
||||
const flowData = dialogue?.flowData;
|
||||
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
||||
if (!node || node.type !== "choice") {
|
||||
// Not a choice node: nothing to gate.
|
||||
|
|
@ -276,20 +287,23 @@ export async function evaluateNpcDialogueChoices(
|
|||
* references are read; substituted values are never re-scanned for tokens.
|
||||
*/
|
||||
export async function resolveNpcDialogueTexts(
|
||||
dialogueId: number,
|
||||
npcId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult<ResolvedNodeTexts>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
// The client names the conversation it is in; the id is verified (right
|
||||
// NPC, and visible to this reader) instead of trusted, so an unreleased
|
||||
// testing conversation cannot be read by guessing a node id.
|
||||
const dialogue = await loadPlayerDialogue(payload, {
|
||||
npcId,
|
||||
dialogueId,
|
||||
userId: user.id as number,
|
||||
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||
});
|
||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
||||
const flowData = dialogue?.flowData;
|
||||
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
||||
if (!node) return { success: true, data: {} };
|
||||
|
||||
|
|
@ -312,6 +326,9 @@ export async function resolveNpcDialogueTexts(
|
|||
// files simply drop off instead of rendering dead chips.
|
||||
const attachments = await resolveAttachments(payload, node.data.attachments);
|
||||
if (attachments.length > 0) resolved.attachments = attachments;
|
||||
// Voice clips resolve the same way: a pointer in flowData, a URL per read.
|
||||
const voice = await resolveVoiceClip(payload, node.data.voice);
|
||||
if (voice) resolved.voice = voice;
|
||||
return { success: true, data: resolved };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
|
|
@ -414,6 +431,189 @@ export async function uploadNpcDialogueAttachment(
|
|||
}
|
||||
}
|
||||
|
||||
/** Audio container types a browser recording or an audio editor produces. */
|
||||
const VOICE_INPUT_TYPES = new Set([
|
||||
"audio/mpeg",
|
||||
"audio/mp3",
|
||||
"audio/wav",
|
||||
"audio/x-wav",
|
||||
"audio/webm",
|
||||
"audio/ogg",
|
||||
"audio/mp4",
|
||||
"audio/aac",
|
||||
"audio/flac",
|
||||
"video/webm", // Chrome reports MediaRecorder output as video/webm.
|
||||
]);
|
||||
|
||||
/** Hard cap on a raw upload; a line read is seconds, not minutes. */
|
||||
const VOICE_MAX_BYTES = 12 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Store an audio file in `media` for a conversation line.
|
||||
*
|
||||
* Recordings arrive as WebM/Opus (or AAC in Safari), which iOS will not always
|
||||
* play and which bloats the page, so anything that is not already MP3 goes
|
||||
* through ffmpeg first. If transcoding fails the original is stored as-is
|
||||
* rather than losing the take, and the browser falls back to its own decoder.
|
||||
*
|
||||
* Gated like dialogue authoring: this stores a file the whole unit will hear.
|
||||
*/
|
||||
export async function uploadNpcDialogueVoice(
|
||||
formData: FormData,
|
||||
): Promise<ActionResult<{ mediaId: number; filename: string; mimeType: string }>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!(await hasPermission(payload, user, "npc-dialogues:update"))) {
|
||||
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 (!VOICE_INPUT_TYPES.has(file.type)) {
|
||||
return { success: false, error: "Voice clips must be audio files." };
|
||||
}
|
||||
if (file.size > VOICE_MAX_BYTES) {
|
||||
return { success: false, error: "Voice clips must be 12 MB or smaller." };
|
||||
}
|
||||
|
||||
const original = Buffer.from(await file.arrayBuffer());
|
||||
const isMp3 = file.type === "audio/mpeg" || file.type === "audio/mp3";
|
||||
const mp3 = isMp3 ? null : await transcodeToMp3(original, file.name);
|
||||
|
||||
const bytes = mp3?.buffer ?? original;
|
||||
const mimetype = mp3?.mimetype ?? file.type;
|
||||
const name = mp3?.name ?? file.name;
|
||||
|
||||
const doc = await payload.create({
|
||||
collection: "media",
|
||||
data: { alt: file.name.replace(/\.[^/.]+$/, "").slice(0, 80) || "Voice clip" },
|
||||
file: { data: bytes, mimetype, name, size: bytes.length },
|
||||
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: mimetype } };
|
||||
} 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 };
|
||||
}
|
||||
}
|
||||
|
||||
/** One accepted recording a line can borrow. */
|
||||
export interface AcceptedVoiceTake {
|
||||
id: number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepted voiceover submissions, for the "import an accepted take" picker.
|
||||
* Recruiting is the existing flow: staff write a VoiceScript, players record
|
||||
* it, staff accept it, and the accepted audio becomes a candidate here.
|
||||
*/
|
||||
export async function listAcceptedVoiceTakes(): Promise<ActionResult<AcceptedVoiceTake[]>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!(await hasPermission(payload, user, "npc-dialogues:update"))) {
|
||||
return { success: false, error: "You are not allowed to edit conversations." };
|
||||
}
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "voice-submissions",
|
||||
where: { status: { equals: "accepted" } },
|
||||
limit: 100,
|
||||
depth: 1,
|
||||
sort: "-createdAt",
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: res.docs.map((doc) => {
|
||||
const script = doc.script as unknown as { title?: string } | number | null;
|
||||
const title = typeof script === "object" && script ? (script.title ?? "Script") : "Script";
|
||||
const submitter = doc.user as unknown as { username?: string } | number | null;
|
||||
const who =
|
||||
typeof submitter === "object" && submitter ? submitter.username ?? "unknown" : "unknown";
|
||||
return { id: doc.id, label: `${title} - @${who} (#${doc.id})` };
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy an accepted voiceover take into `media` so a line can play it.
|
||||
*
|
||||
* The copy (rather than pointing at the submission) keeps one playback path and
|
||||
* one permission story: `media` is publicly readable, while `voice-submissions`
|
||||
* access is owner-scoped. Reviewer replays of the original keep working because
|
||||
* the submission itself is untouched.
|
||||
*/
|
||||
export async function importNpcDialogueVoice(
|
||||
submissionId: number,
|
||||
): Promise<ActionResult<{ mediaId: number; filename: string; mimeType: string }>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!(await hasPermission(payload, user, "npc-dialogues:update"))) {
|
||||
return { success: false, error: "You are not allowed to edit conversations." };
|
||||
}
|
||||
|
||||
const submission = await payload.findByID({
|
||||
collection: "voice-submissions",
|
||||
id: submissionId,
|
||||
depth: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
if (!submission) return { success: false, error: "That take no longer exists." };
|
||||
if (submission.status !== "accepted") {
|
||||
return { success: false, error: "Only accepted takes can be imported." };
|
||||
}
|
||||
const filename = submission.filename;
|
||||
if (!filename) return { success: false, error: "That take has no audio file." };
|
||||
|
||||
const { readFile } = await import("node:fs/promises");
|
||||
const path = await import("node:path");
|
||||
const filePath = path.resolve(process.cwd(), "media", "voice-submissions", filename);
|
||||
let bytes: Buffer;
|
||||
try {
|
||||
bytes = await readFile(filePath);
|
||||
} catch {
|
||||
return { success: false, error: "That take's audio file is missing on disk." };
|
||||
}
|
||||
|
||||
// Normalise to MP3 so every line plays the same way on every device.
|
||||
const mp3 = submission.mimeType === MP3_MIMETYPE ? null : await transcodeToMp3(bytes, filename);
|
||||
const stored = mp3?.buffer ?? bytes;
|
||||
const mimetype = mp3?.mimetype ?? submission.mimeType ?? MP3_MIMETYPE;
|
||||
const name = mp3?.name ?? filename;
|
||||
|
||||
const doc = await payload.create({
|
||||
collection: "media",
|
||||
data: { alt: `Voice take #${submissionId}` },
|
||||
file: { data: stored, mimetype, name, size: stored.length },
|
||||
overrideAccess: true,
|
||||
});
|
||||
if (!doc.filename) {
|
||||
return { success: false, error: "Import failed: no file was stored." };
|
||||
}
|
||||
return { success: true, data: { mediaId: doc.id, filename: doc.filename, mimeType: mimetype } };
|
||||
} 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 };
|
||||
}
|
||||
}
|
||||
|
||||
/** What a successful draft hands back to the editor. */
|
||||
export interface GeneratedDialogueDraft {
|
||||
/** The graph to drop into the canvas. Never persisted by the server action. */
|
||||
|
|
|
|||
|
|
@ -3,10 +3,14 @@ import { getPayload } from "payload";
|
|||
import { notFound } from "next/navigation";
|
||||
import { headers as nextHeaders } from "next/headers";
|
||||
import type { GameNpc, MarketListing, NpcStaffing } from "@/payload-types";
|
||||
import type { FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
import { selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
||||
import { evaluateCondition } from "@/lib/npc-dialogue/flags";
|
||||
import {
|
||||
canSeeTestingDialogues,
|
||||
loadPlayerDialogue,
|
||||
} from "@/lib/npc-dialogue/visibility";
|
||||
import { listSeenNodeIds } from "@/lib/npc-dialogue/states";
|
||||
import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings";
|
||||
import { resolveTypewriter } from "@/lib/npc-dialogue/presentation";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { NpcProfile } from "@/components/frontend/personnel/NpcProfile";
|
||||
import { NpcConversation } from "@/components/frontend/personnel/NpcConversation";
|
||||
import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard";
|
||||
|
|
@ -157,7 +161,11 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
|
||||
const dialogue =
|
||||
npc.canMessage === true
|
||||
? await pickDialogue(payload, id, user?.id as number | undefined)
|
||||
? await loadPlayerDialogue(payload, {
|
||||
npcId: id,
|
||||
userId: user?.id as number | undefined,
|
||||
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||
})
|
||||
: null;
|
||||
|
||||
// Server-side NEW badges: which nodes has this player already read? Empty
|
||||
|
|
@ -168,13 +176,32 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
? await listSeenNodeIds(payload, user.id as number, dialogue.id)
|
||||
: [];
|
||||
|
||||
// Typing animation: the unit default from the settings global, overridden by
|
||||
// this player's own preference. Read here so the dialog needs no round trip.
|
||||
const typewriterEnabled = dialogue
|
||||
? resolveTypewriter(
|
||||
isPayloadUser(user) ? user.preferences?.dialogue?.typewriter : undefined,
|
||||
(await loadDialogueSettings(payload)).typewriterDefault,
|
||||
)
|
||||
: false;
|
||||
// Sound is on unless the player turned voice clips off in their account.
|
||||
const voiceEnabled = dialogue
|
||||
? (isPayloadUser(user) ? user.preferences?.dialogue?.voice : undefined) !== false
|
||||
: false;
|
||||
|
||||
return (
|
||||
<div className="p-5 flex flex-col gap-6">
|
||||
<NpcProfile
|
||||
npc={npc}
|
||||
listings={listings}
|
||||
conversationSlot={
|
||||
<NpcConversation npc={npc} dialogue={dialogue} initialSeenNodeIds={seenNodeIds} />
|
||||
<NpcConversation
|
||||
npc={npc}
|
||||
dialogue={dialogue}
|
||||
initialSeenNodeIds={seenNodeIds}
|
||||
typewriter={typewriterEnabled}
|
||||
voice={voiceEnabled}
|
||||
/>
|
||||
}
|
||||
employmentSlot={
|
||||
<EmploymentCard
|
||||
|
|
@ -194,29 +221,3 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the conversation to offer this player: among all of the NPC's
|
||||
* conversations, the highest-priority one whose entry gate passes (ungated
|
||||
* always passes). Only the winner's flowchart leaves the server, so gated
|
||||
* story content never reaches a client that has not unlocked it.
|
||||
*/
|
||||
async function pickDialogue(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
npcId: number,
|
||||
userId: number | undefined,
|
||||
) {
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 25,
|
||||
depth: 0,
|
||||
});
|
||||
if (res.docs.length === 0) return null;
|
||||
|
||||
const chosen = await selectDialogueForUser(res.docs, async (condition) => {
|
||||
if (!userId) return false;
|
||||
return evaluateCondition(payload, userId, condition);
|
||||
});
|
||||
if (!chosen) return null;
|
||||
return { id: chosen.id, flowData: chosen.flowData as unknown as FlowData | undefined };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,6 +80,23 @@ export const NpcDialogueSettings: GlobalConfig = {
|
|||
"House conventions appended after the voice, for every conversation including ones with their own voice. Keep it short and concrete, e.g. how the unit refers to itself or which slang is banned.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "presentation",
|
||||
label: "Presentation",
|
||||
type: "group",
|
||||
fields: [
|
||||
{
|
||||
name: "typewriterDefault",
|
||||
label: "Type conversation lines out character by character",
|
||||
type: "checkbox",
|
||||
defaultValue: true,
|
||||
admin: {
|
||||
description:
|
||||
"The default for everyone. Players can override it in their account preferences, and a player whose device asks for reduced motion never sees the animation.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "revision",
|
||||
type: "number",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { CONDITION_OPS } from "@/lib/npc-dialogue/dialogue";
|
||||
import { CONDITION_OPS, NUMERIC_CONDITION_OPS } from "@/lib/npc-dialogue/dialogue";
|
||||
import { cleanPromptText, MAX_VOICE_CHARS } from "@/lib/npc-dialogue/normalize";
|
||||
|
||||
export const NpcDialogues: CollectionConfig = {
|
||||
|
|
@ -9,7 +9,7 @@ export const NpcDialogues: CollectionConfig = {
|
|||
group: "Game",
|
||||
useAsTitle: "name",
|
||||
listSearchableFields: ["name"],
|
||||
defaultColumns: ["name", "npc", "priority"],
|
||||
defaultColumns: ["name", "npc", "priority", "testing"],
|
||||
pagination: { defaultLimit: 50 },
|
||||
},
|
||||
access: {
|
||||
|
|
@ -49,6 +49,16 @@ export const NpcDialogues: CollectionConfig = {
|
|||
"When a contact has several conversations, the highest-priority one whose entry gate passes is the one offered. Ties break by oldest first.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "testing",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
label: "Testing: superusers only",
|
||||
admin: {
|
||||
description:
|
||||
"Walk this conversation on the live site without releasing it. Only the superuser tier is offered it: players never see it or its new-message badge, and it cannot be resolved by guessing its id. Untick to publish.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "entryGate",
|
||||
type: "group",
|
||||
|
|
@ -79,7 +89,7 @@ export const NpcDialogues: CollectionConfig = {
|
|||
type: "number",
|
||||
admin: {
|
||||
condition: (_data, blockData) =>
|
||||
["gte", "lte", "gt", "lt", "eq"].includes(String(blockData?.op)),
|
||||
NUMERIC_CONDITION_OPS.includes(String(blockData?.op) as never),
|
||||
description: "Right-hand side for the numeric comparisons.",
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -322,6 +322,38 @@ export const Users: CollectionConfig = {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "dialogue",
|
||||
label: "Conversations",
|
||||
type: "group",
|
||||
fields: [
|
||||
{
|
||||
name: "typewriter",
|
||||
label: "Typing animation in conversations",
|
||||
type: "select",
|
||||
defaultValue: "default",
|
||||
options: [
|
||||
{ label: "Use the unit default", value: "default" },
|
||||
{ label: "Always type lines out", value: "on" },
|
||||
{ label: "Show lines instantly", value: "off" },
|
||||
],
|
||||
admin: {
|
||||
description:
|
||||
"NPC dialogue lines type out letter by letter. Click a line to finish it immediately. Reduced-motion devices always show lines instantly.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "voice",
|
||||
label: "Play voice clips in conversations",
|
||||
type: "checkbox",
|
||||
defaultValue: true,
|
||||
admin: {
|
||||
description:
|
||||
"Recorded lines play as they arrive. You can also mute for the rest of a conversation with the speaker button in its header.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "discord",
|
||||
label: "Discord",
|
||||
|
|
|
|||
|
|
@ -24,14 +24,26 @@ import type {
|
|||
DialogueNext,
|
||||
DialogueNode,
|
||||
DialogueNodeData,
|
||||
DialogueVoiceClip,
|
||||
NpcDialogueEffect,
|
||||
NpcDialogueNodeType,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
import { conditionSummary, EFFECT_TYPES, outgoingHops } from "@/lib/npc-dialogue/dialogue";
|
||||
import {
|
||||
conditionSummary,
|
||||
EFFECT_TYPES,
|
||||
NUMERIC_CONDITION_OPS,
|
||||
outgoingHops,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
|
||||
import { MarkupEditor } from "./MarkupEditor";
|
||||
import { LineAssist } from "./LineAssist";
|
||||
import { uploadNpcDialogueAttachment } from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
||||
import {
|
||||
importNpcDialogueVoice,
|
||||
listAcceptedVoiceTakes,
|
||||
uploadNpcDialogueAttachment,
|
||||
uploadNpcDialogueVoice,
|
||||
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
||||
import type { AcceptedVoiceTake } from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
||||
|
||||
interface NodeEditDialogProps {
|
||||
readonly node: DialogueNode | null;
|
||||
|
|
@ -64,6 +76,8 @@ const FLAG_OP_LABELS: Record<DialogueFlagOp, string> = {
|
|||
const CONDITION_OP_LABELS: Record<DialogueFlagCondition["op"], string> = {
|
||||
is_true: "is true",
|
||||
is_false: "is false",
|
||||
is_defined: "is defined",
|
||||
is_undefined: "is not defined",
|
||||
gte: "is at least",
|
||||
lte: "is at most",
|
||||
gt: "is greater than",
|
||||
|
|
@ -78,8 +92,9 @@ const GROUP_OP_LABELS: Record<DialogueConditionGroup["op"], string> = {
|
|||
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"];
|
||||
/** Ops that compare against a number: the shared list, so the canvas summary,
|
||||
* the entry-gate field and this dialog never disagree. */
|
||||
const NUMERIC_OPS = NUMERIC_CONDITION_OPS;
|
||||
|
||||
/** A blank leaf used when switching into single mode or adding a group row. */
|
||||
const EMPTY_LEAF: DialogueFlagCondition = { kind: "flag", key: "", op: "is_true" };
|
||||
|
|
@ -491,13 +506,11 @@ export function NodeEditDialog({
|
|||
{node.type === "event" && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Narration
|
||||
</Label>
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">Text</Label>
|
||||
<MarkupEditor
|
||||
value={draft.body ?? ""}
|
||||
onChange={(next) => patch({ body: next || undefined })}
|
||||
placeholder="Describe what happens. Shown as a speaker-less narrative line."
|
||||
placeholder="Describe what happens, or what the contact says."
|
||||
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"
|
||||
/>
|
||||
|
|
@ -506,6 +519,29 @@ export function NodeEditDialog({
|
|||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Presentation
|
||||
</Label>
|
||||
<select
|
||||
value={draft.presentation ?? "event"}
|
||||
onChange={(e) =>
|
||||
patch({
|
||||
presentation:
|
||||
e.target.value === "narration" ? "narration" : undefined,
|
||||
})
|
||||
}
|
||||
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
|
||||
>
|
||||
<option value="event">Event line (amber, left aligned)</option>
|
||||
<option value="narration">Descriptive narrative (centered, muted)</option>
|
||||
</select>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Descriptive narrative reads as the narrator describing a scene, with no
|
||||
speaker and no accent bar.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">Effect</Label>
|
||||
<select
|
||||
|
|
@ -822,6 +858,13 @@ export function NodeEditDialog({
|
|||
/>
|
||||
)}
|
||||
|
||||
{(node.type === "dialogue" || node.type === "event" || node.type === "end") && (
|
||||
<VoiceEditor
|
||||
voice={draft.voice}
|
||||
onChange={(voice) => patch({ voice })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{(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">
|
||||
|
|
@ -878,6 +921,172 @@ export function NodeEditDialog({
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recorded voice for one line. Two sources land in the same place: a direct
|
||||
* upload (transcoded to MP3 server-side) and an accepted voiceover submission
|
||||
* (copied into `media`), so playback has a single path. Only the media pointer
|
||||
* and its filename live in flowData; removing a clip never deletes the file.
|
||||
*/
|
||||
function VoiceEditor({
|
||||
voice,
|
||||
onChange,
|
||||
}: {
|
||||
voice: DialogueVoiceClip | undefined;
|
||||
onChange: (next: DialogueVoiceClip | undefined) => void;
|
||||
}) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [takes, setTakes] = useState<AcceptedVoiceTake[] | null>(null);
|
||||
const [takeId, setTakeId] = useState<string>("");
|
||||
|
||||
const upload = async (file: File) => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
const result = await uploadNpcDialogueVoice(formData);
|
||||
if (result.success && result.data) {
|
||||
onChange({ mediaId: result.data.mediaId, filename: result.data.filename });
|
||||
} else {
|
||||
setError(result.error ?? "Upload failed.");
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const importTake = async () => {
|
||||
const id = Number(takeId);
|
||||
if (!Number.isInteger(id) || id <= 0) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await importNpcDialogueVoice(id);
|
||||
if (result.success && result.data) {
|
||||
onChange({ mediaId: result.data.mediaId, filename: result.data.filename });
|
||||
setTakeId("");
|
||||
} else {
|
||||
setError(result.error ?? "Import failed.");
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadTakes = async () => {
|
||||
setError(null);
|
||||
const result = await listAcceptedVoiceTakes();
|
||||
if (result.success && result.data) setTakes(result.data);
|
||||
else setError(result.error ?? "Could not list takes.");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5 rounded border border-zinc-700 bg-zinc-900 p-2.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-zinc-400">Voice</Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
className="h-6 border-zinc-600 text-xs text-zinc-100 hover:text-white"
|
||||
>
|
||||
{busy ? "Working…" : voice ? "Replace clip" : "Upload clip"}
|
||||
</Button>
|
||||
</div>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
accept="audio/*"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) void upload(file);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
|
||||
{voice ? (
|
||||
<div className="flex flex-col gap-1.5 rounded border border-zinc-700 bg-zinc-800 p-2">
|
||||
<audio
|
||||
controls
|
||||
preload="none"
|
||||
src={`/api/media/file/${voice.filename ?? ""}`}
|
||||
className="h-8 w-full"
|
||||
/>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="truncate font-mono text-[10px] text-zinc-400">
|
||||
#{voice.mediaId} {voice.filename ?? ""}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label="Remove voice clip"
|
||||
onClick={() => onChange(undefined)}
|
||||
className="h-6 shrink-0 border-red-900/50 px-2 text-xs text-red-400 hover:bg-red-950/40"
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-zinc-400">No voice on this line.</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => void loadTakes()}
|
||||
className="h-6 shrink-0 border-zinc-600 text-xs text-zinc-100 hover:text-white"
|
||||
>
|
||||
{takes ? "Refresh takes" : "Import accepted take"}
|
||||
</Button>
|
||||
{takes && (
|
||||
<>
|
||||
<select
|
||||
value={takeId}
|
||||
onChange={(e) => setTakeId(e.target.value)}
|
||||
className="min-w-0 flex-1 rounded border border-zinc-600 bg-zinc-800 px-2 py-1 text-xs text-white"
|
||||
>
|
||||
<option value="">
|
||||
{takes.length === 0 ? "No accepted takes yet" : "Choose a take"}
|
||||
</option>
|
||||
{takes.map((take) => (
|
||||
<option key={take.id} value={take.id}>
|
||||
{take.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={busy || !takeId}
|
||||
onClick={() => void importTake()}
|
||||
className="h-6 shrink-0 border-zinc-600 text-xs text-zinc-100 hover:text-white"
|
||||
>
|
||||
Use
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <p className="text-[10px] text-red-400">{error}</p>}
|
||||
<p className="text-[10px] text-zinc-400">
|
||||
Plays when the line lands, and the text paces itself to the clip. Uploads are converted to
|
||||
MP3 so phones play them reliably. Importing an accepted take copies the audio; the
|
||||
submission stays as it was.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attachment list for a dialogue/event node. Uploads go to the `media`
|
||||
* collection through the conversation upload action (which gates on
|
||||
|
|
|
|||
|
|
@ -140,8 +140,19 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
|
|||
|
||||
{nodeType === "event" && (
|
||||
<div className="text-sm">
|
||||
{d.presentation === "narration" && (
|
||||
<span className="mb-1 inline-block rounded-sm bg-white/10 px-1 py-px font-mono text-[9px] uppercase tracking-wider text-white/50">
|
||||
narrative
|
||||
</span>
|
||||
)}
|
||||
{d.body && (
|
||||
<p className="line-clamp-3 italic text-amber-100/80">
|
||||
<p
|
||||
className={
|
||||
d.presentation === "narration"
|
||||
? "line-clamp-3 text-center italic text-white/55"
|
||||
: "line-clamp-3 italic text-amber-100/80"
|
||||
}
|
||||
>
|
||||
<DialogueText text={d.body} />
|
||||
</p>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -117,6 +117,8 @@ export function CommandPalette({
|
|||
discordEnabled: preferences?.discord?.enabled ?? false,
|
||||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: preferences?.display?.xpDisplayMini ?? false,
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
conversationVoice: preferences?.dialogue?.voice !== false,
|
||||
});
|
||||
if (result.success) {
|
||||
toast.success("Background texture toggled");
|
||||
|
|
@ -137,6 +139,8 @@ export function CommandPalette({
|
|||
discordEnabled: preferences?.discord?.enabled ?? false,
|
||||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: preferences?.display?.xpDisplayMini ?? false,
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
conversationVoice: preferences?.dialogue?.voice !== false,
|
||||
});
|
||||
if (result.success) {
|
||||
toast.success("Callsign display toggled");
|
||||
|
|
@ -157,6 +161,8 @@ export function CommandPalette({
|
|||
discordEnabled: preferences?.discord?.enabled ?? false,
|
||||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: !(preferences?.display?.xpDisplayMini ?? false),
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
conversationVoice: preferences?.dialogue?.voice !== false,
|
||||
});
|
||||
if (result.success) {
|
||||
toast.success("XP display toggled");
|
||||
|
|
|
|||
|
|
@ -22,6 +22,10 @@ interface PreferencesFormProps {
|
|||
readonly discordEnabled: boolean;
|
||||
readonly discordMutedTypes: readonly string[];
|
||||
readonly xpDisplayMini: boolean;
|
||||
/** Stored choice for the NPC conversation typing animation. */
|
||||
readonly conversationTypewriter: "default" | "on" | "off";
|
||||
/** Whether recorded voice clips play in conversations. */
|
||||
readonly conversationVoice: boolean;
|
||||
}
|
||||
|
||||
export function PreferencesForm({
|
||||
|
|
@ -34,6 +38,8 @@ export function PreferencesForm({
|
|||
discordEnabled: initialDiscordEnabled,
|
||||
discordMutedTypes: initialDiscordMutedTypes,
|
||||
xpDisplayMini: initialXPDisplayMini,
|
||||
conversationTypewriter: initialConversationTypewriter,
|
||||
conversationVoice: initialConversationVoice,
|
||||
}: PreferencesFormProps) {
|
||||
const router = useRouter();
|
||||
const [mutedAll, setMutedAll] = useState(initialMutedAll);
|
||||
|
|
@ -47,6 +53,10 @@ export function PreferencesForm({
|
|||
...initialDiscordMutedTypes,
|
||||
]);
|
||||
const [xpDisplayMini, setXPDisplayMini] = useState(initialXPDisplayMini);
|
||||
const [conversationTypewriter, setConversationTypewriter] = useState<
|
||||
"default" | "on" | "off"
|
||||
>(initialConversationTypewriter);
|
||||
const [conversationVoice, setConversationVoice] = useState(initialConversationVoice);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
|
@ -80,6 +90,8 @@ export function PreferencesForm({
|
|||
discordEnabled,
|
||||
discordMutedTypes,
|
||||
xpDisplayMini,
|
||||
conversationTypewriter,
|
||||
conversationVoice,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
|
|
@ -191,6 +203,72 @@ export function PreferencesForm({
|
|||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Conversations</CardTitle>
|
||||
<CardDescription>
|
||||
How NPC dialogue is presented when you talk to a contact.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2">
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-sm font-medium">Typing animation</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Type lines out letter by letter. Click a line to finish it immediately.
|
||||
Devices set to reduce motion always show lines instantly.
|
||||
</span>
|
||||
</div>
|
||||
<RadioGroup
|
||||
value={conversationTypewriter}
|
||||
onValueChange={(value) => {
|
||||
if (value === "default" || value === "on" || value === "off") {
|
||||
setConversationTypewriter(value);
|
||||
}
|
||||
}}
|
||||
className="flex flex-wrap gap-4"
|
||||
aria-label="Typing animation in conversations"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem id="typewriter-default" value="default" />
|
||||
<Label htmlFor="typewriter-default" className="py-1.5">
|
||||
Unit default
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem id="typewriter-on" value="on" />
|
||||
<Label htmlFor="typewriter-on" className="py-1.5">
|
||||
Always type out
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem id="typewriter-off" value="off" />
|
||||
<Label htmlFor="typewriter-off" className="py-1.5">
|
||||
Show instantly
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
|
||||
<Label
|
||||
htmlFor="conversationVoice"
|
||||
className="mt-2 flex items-center justify-between gap-4 text-sm"
|
||||
>
|
||||
<span className="flex min-w-0 flex-col gap-1">
|
||||
<span>Play voice clips</span>
|
||||
<span className="text-sm font-normal text-muted-foreground">
|
||||
Lines with recorded voice play as they arrive. The speaker button in a
|
||||
conversation header mutes it for that conversation.
|
||||
</span>
|
||||
</span>
|
||||
<Switch
|
||||
id="conversationVoice"
|
||||
checked={conversationVoice}
|
||||
onCheckedChange={setConversationVoice}
|
||||
aria-label="Play voice clips in conversations"
|
||||
/>
|
||||
</Label>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Notifications</CardTitle>
|
||||
|
|
|
|||
|
|
@ -177,6 +177,8 @@ export function AppSidebar({
|
|||
discordEnabled: preferences?.discord?.enabled ?? false,
|
||||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: !isMiniMode,
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
conversationVoice: preferences?.dialogue?.voice !== false,
|
||||
});
|
||||
setIsMiniMode(!isMiniMode);
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState, Fragment } from "react";
|
||||
import { LockIcon, MessageCircleIcon, XIcon } from "lucide-react";
|
||||
import { LockIcon, MessageCircleIcon, Volume2Icon, VolumeXIcon, XIcon } from "lucide-react";
|
||||
|
||||
import type { GameNpc } from "@/payload-types";
|
||||
import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate";
|
||||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { DialogueText, visibleLength } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments";
|
||||
import { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
|
||||
import { DOSSIER } from "@/components/frontend/operations";
|
||||
|
|
@ -38,6 +38,11 @@ interface NpcConversationProps {
|
|||
* local seen set; reads during the session are sent to the server and
|
||||
* merged optimistically. */
|
||||
readonly initialSeenNodeIds?: readonly string[];
|
||||
/** Type lines out character by character. Resolved server-side from the
|
||||
* player's preference and the unit default; reduced-motion always wins. */
|
||||
readonly typewriter?: boolean;
|
||||
/** Play recorded voice clips. The header button mutes for the session. */
|
||||
readonly voice?: boolean;
|
||||
}
|
||||
|
||||
interface ResolvedFlow {
|
||||
|
|
@ -53,6 +58,16 @@ type LogEntry =
|
|||
/** Server-resolved display strings (flag tokens interpolated), when the
|
||||
* node had tokens. Undefined = render the raw authored strings. */
|
||||
resolved?: ResolvedNodeTexts;
|
||||
/** The line as shown, resolved text first. Stored so the reveal length and
|
||||
* the renderer can never disagree about what is being typed. */
|
||||
text: string;
|
||||
/** Visible characters revealed so far while typing; undefined = whole
|
||||
* line is showing. */
|
||||
reveal?: number;
|
||||
/** Playable voice clip for this line, when it has one. */
|
||||
voiceUrl?: string;
|
||||
/** The browser refused autoplay; the line shows a play button instead. */
|
||||
voiceBlocked?: boolean;
|
||||
}
|
||||
| { kind: "player"; id: string; text: string };
|
||||
|
||||
|
|
@ -65,16 +80,65 @@ function resolveFlow(dialogue: NpcConversationProps["dialogue"]): ResolvedFlow |
|
|||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/** Text length drives how long the NPC "types"; jitter keeps it human. */
|
||||
function typingDelayMs(text: string): number {
|
||||
return Math.min(2600, 450 + text.length * 24) * (0.85 + Math.random() * 0.3);
|
||||
/** How long a line takes to type out: brisk for short lines, capped so a long
|
||||
* paragraph does not hold the player up. `visibleLength` units, not raw
|
||||
* characters, so markup does not slow the reveal down. */
|
||||
function revealDurationMs(units: number): number {
|
||||
return Math.min(2600, 450 + units * 24);
|
||||
}
|
||||
|
||||
function nodeText(node: DialogueNode): string {
|
||||
return node.data.body || node.data.effect?.message || node.data.closing || node.data.leadIn || "";
|
||||
/** True when the device asks for reduced motion; the animation is skipped
|
||||
* entirely rather than merely shortened. */
|
||||
function prefersReducedMotion(): boolean {
|
||||
return (
|
||||
typeof window !== "undefined" &&
|
||||
typeof window.matchMedia === "function" &&
|
||||
window.matchMedia("(prefers-reduced-motion: reduce)").matches
|
||||
);
|
||||
}
|
||||
|
||||
export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConversationProps) {
|
||||
/** Seconds in a clip, or 0 when the browser has not read the metadata yet.
|
||||
* Bounded so an unreadable file cannot stall the reveal. */
|
||||
async function clipDuration(audio: HTMLAudioElement): Promise<number> {
|
||||
if (Number.isFinite(audio.duration) && audio.duration > 0) return audio.duration;
|
||||
return await new Promise<number>((resolve) => {
|
||||
const done = (value: number) => {
|
||||
audio.removeEventListener("loadedmetadata", onMeta);
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const onMeta = () => done(Number.isFinite(audio.duration) ? audio.duration : 0);
|
||||
const timer = setTimeout(() => done(0), 1200);
|
||||
audio.addEventListener("loadedmetadata", onMeta);
|
||||
});
|
||||
}
|
||||
|
||||
/** The line a node displays, resolved text first (flag tokens interpolated).
|
||||
* Single source of truth for both the reveal length and the rendered line. */
|
||||
function displayText(node: DialogueNode, resolved?: ResolvedNodeTexts): string {
|
||||
if (node.type === "event") {
|
||||
return (
|
||||
(resolved?.body ?? node.data.body) ||
|
||||
(resolved?.message ?? node.data.effect?.message) ||
|
||||
"An event unfolds…"
|
||||
);
|
||||
}
|
||||
if (node.type === "end") {
|
||||
return (resolved?.closing ?? node.data.closing) || "The conversation ends.";
|
||||
}
|
||||
if (node.type === "choice") {
|
||||
return (resolved?.leadIn ?? node.data.leadIn) || "";
|
||||
}
|
||||
return (resolved?.body ?? node.data.body) || "";
|
||||
}
|
||||
|
||||
export function NpcConversation({
|
||||
npc,
|
||||
dialogue,
|
||||
initialSeenNodeIds,
|
||||
typewriter = true,
|
||||
voice = true,
|
||||
}: NpcConversationProps) {
|
||||
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [log, setLog] = useState<LogEntry[]>([]);
|
||||
|
|
@ -82,6 +146,21 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
const [typing, setTyping] = useState<string | null>(null);
|
||||
/** True while the player's chosen line is "typing" into the log. */
|
||||
const [playerTyping, setPlayerTyping] = useState(false);
|
||||
/** Log entry currently typing itself out, if any. Gates the choice footer so
|
||||
* a player cannot answer a line they have not finished reading. */
|
||||
const [streamingId, setStreamingId] = useState<string | null>(null);
|
||||
/** Set by clicking the log: finish the line instead of waiting. */
|
||||
const skipRevealRef = useRef<string | null>(null);
|
||||
/** One element reused for every clip: a line's audio stops when the next
|
||||
* starts, and the browser keeps its autoplay permission for the session. */
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
/** This conversation's id: node lookups name it so the server can verify the
|
||||
* reader is in a conversation they are allowed to see. */
|
||||
const dialogueId = dialogue?.id ?? null;
|
||||
/** Sound is on unless the player turned it off or muted this session. */
|
||||
const [soundOn, setSoundOn] = useState(voice);
|
||||
const soundOnRef = useRef(soundOn);
|
||||
soundOnRef.current = soundOn;
|
||||
/** `${nodeId}:${index}` keys of one-time choices picked in THIS conversation.
|
||||
* Purely local: it resets on every `begin()`, so a choice hidden here
|
||||
* reappears the next time the conversation is opened. Persist across
|
||||
|
|
@ -135,7 +214,8 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
);
|
||||
if (!hasGated) return;
|
||||
let cancelled = false;
|
||||
void evaluateNpcDialogueChoices(Number(npc.id), activeChoiceNodeId).then((res) => {
|
||||
if (dialogueId === null) return;
|
||||
void evaluateNpcDialogueChoices(dialogueId, Number(npc.id), activeChoiceNodeId).then((res) => {
|
||||
if (!cancelled && res.success && Array.isArray(res.data)) {
|
||||
const gate = res.data;
|
||||
setChoiceGates((prev) => ({ ...prev, [activeChoiceNodeId]: gate }));
|
||||
|
|
@ -166,22 +246,101 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
void markNpcDialogueNodeRead(dialogue.id, nodeId).catch(() => undefined);
|
||||
};
|
||||
|
||||
/** Resolves the node's display strings server-side (flag tokens), then
|
||||
* appends it to the log after a length-based "typing" delay. Nodes without
|
||||
* tokens skip the round trip and render their raw authored text. */
|
||||
/** Resolves the node's display strings server-side (flag tokens), appends the
|
||||
* line to the log, then types it out unless the player has the animation off.
|
||||
* Nodes without tokens skip the round trip and use their authored text. */
|
||||
const typeIn = async (node: DialogueNode, token: number) => {
|
||||
let resolved: ResolvedNodeTexts | undefined;
|
||||
if (collectNodeTokens(node).length > 0 || (node.data.attachments?.length ?? 0) > 0) {
|
||||
const res = await resolveNpcDialogueTexts(Number(npc.id), node.id);
|
||||
if (
|
||||
collectNodeTokens(node).length > 0 ||
|
||||
(node.data.attachments?.length ?? 0) > 0 ||
|
||||
node.data.voice
|
||||
) {
|
||||
if (dialogueId === null) return;
|
||||
const res = await resolveNpcDialogueTexts(dialogueId, Number(npc.id), node.id);
|
||||
if (sessionRef.current !== token) return;
|
||||
if (res.success && res.data) resolved = res.data;
|
||||
}
|
||||
setTyping(node.type === "event" ? "" : node.data.speaker?.trim() || npc.name);
|
||||
await sleep(typingDelayMs(nodeText(node)));
|
||||
if (sessionRef.current !== token) return;
|
||||
setTyping(null);
|
||||
setLog((prev) => [...prev, { kind: "node", id: nextId(), node, resolved }]);
|
||||
|
||||
const text = displayText(node, resolved);
|
||||
const id = nextId();
|
||||
const total = visibleLength(text);
|
||||
|
||||
// Start the clip before the line lands so the first word is not late. A
|
||||
// rejected play() (autoplay policy) marks the entry so it can offer a
|
||||
// button instead of failing silently.
|
||||
const voiceUrl = resolved?.voice?.url;
|
||||
let voiceStarted = false;
|
||||
let clipSeconds = 0;
|
||||
if (voiceUrl && soundOnRef.current && audioRef.current) {
|
||||
const audio = audioRef.current;
|
||||
audio.src = voiceUrl;
|
||||
audio.currentTime = 0;
|
||||
try {
|
||||
await audio.play();
|
||||
voiceStarted = true;
|
||||
clipSeconds = await clipDuration(audio);
|
||||
} catch {
|
||||
voiceStarted = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing to animate for an empty line, and a reduced-motion device skips
|
||||
// the animation outright. Only the NPC's spoken lines type: choice lead-ins,
|
||||
// event lines, descriptive narration and end closings are the interface's
|
||||
// own voice, and they land whole so the footer never waits on prose the
|
||||
// player is not being spoken to by.
|
||||
const animate =
|
||||
typewriter && node.type === "dialogue" && total > 0 && !prefersReducedMotion();
|
||||
// A clip paces the reveal: the text finishes with the read, so the two do
|
||||
// not drift apart on a long line.
|
||||
const durationMs =
|
||||
voiceStarted && clipSeconds > 0.4
|
||||
? Math.min(60_000, clipSeconds * 1000)
|
||||
: revealDurationMs(total);
|
||||
|
||||
setLog((prev) => [
|
||||
...prev,
|
||||
{
|
||||
kind: "node",
|
||||
id,
|
||||
node,
|
||||
resolved,
|
||||
text,
|
||||
reveal: animate ? 0 : undefined,
|
||||
voiceUrl,
|
||||
voiceBlocked: Boolean(voiceUrl && !voiceStarted && soundOnRef.current),
|
||||
},
|
||||
]);
|
||||
markSeen(node.id);
|
||||
if (!animate) return;
|
||||
|
||||
const setReveal = (shown: number | undefined) =>
|
||||
setLog((prev) =>
|
||||
prev.map((entry) =>
|
||||
entry.kind === "node" && entry.id === id ? { ...entry, reveal: shown } : entry,
|
||||
),
|
||||
);
|
||||
|
||||
setStreamingId(id);
|
||||
skipRevealRef.current = null;
|
||||
const msPerUnit = durationMs / total;
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
for (;;) {
|
||||
if (sessionRef.current !== token) return;
|
||||
if (skipRevealRef.current === id) break;
|
||||
const shown = Math.min(total, Math.floor((performance.now() - startedAt) / msPerUnit));
|
||||
setReveal(shown);
|
||||
if (shown >= total) break;
|
||||
await sleep(32);
|
||||
}
|
||||
} finally {
|
||||
// Land on the full line whether it finished, was skipped, or the dialog
|
||||
// closed mid-reveal (the session check above returns through here).
|
||||
setReveal(undefined);
|
||||
setStreamingId((current) => (current === id ? null : current));
|
||||
}
|
||||
};
|
||||
|
||||
// Opening the conversation walks the start node and auto-advances through
|
||||
|
|
@ -190,9 +349,11 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
// line arrives after its own typing delay.
|
||||
const begin = () => {
|
||||
const token = ++sessionRef.current;
|
||||
audioRef.current?.pause();
|
||||
setLog([]);
|
||||
setTyping(null);
|
||||
setPlayerTyping(false);
|
||||
setStreamingId(null);
|
||||
setTakenChoices(new Set());
|
||||
setChoiceGates({});
|
||||
setOpen(true);
|
||||
|
|
@ -225,7 +386,12 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
}
|
||||
|
||||
if (current.type === "condition") {
|
||||
const result = await evaluateNpcDialogueCondition(Number(npc.id), current.id);
|
||||
if (dialogueId === null) return;
|
||||
const result = await evaluateNpcDialogueCondition(
|
||||
dialogueId,
|
||||
Number(npc.id),
|
||||
current.id,
|
||||
);
|
||||
if (sessionRef.current !== token) return;
|
||||
const branch =
|
||||
result.success && result.data ? current.data.trueTarget : current.data.falseTarget;
|
||||
|
|
@ -239,7 +405,11 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
if (current.type === "event" && current.data.effect) {
|
||||
// Await the effect so flags it writes are visible to the lines
|
||||
// that follow (interpolated text and later condition nodes).
|
||||
await triggerNpcDialogueEvent(Number(npc.id), current.id).catch(() => undefined);
|
||||
if (dialogueId !== null) {
|
||||
await triggerNpcDialogueEvent(dialogueId, Number(npc.id), current.id).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
if (sessionRef.current !== token) return;
|
||||
}
|
||||
const target: string | undefined = current.data.next?.target;
|
||||
|
|
@ -252,8 +422,10 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
|
||||
const close = () => {
|
||||
sessionRef.current += 1;
|
||||
audioRef.current?.pause();
|
||||
setTyping(null);
|
||||
setPlayerTyping(false);
|
||||
setStreamingId(null);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
|
|
@ -362,14 +534,34 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
|
||||
Conversation // {npc.name}
|
||||
</DialogTitle>
|
||||
<button
|
||||
type="button"
|
||||
onClick={close}
|
||||
aria-label="Close conversation"
|
||||
className="shrink-0 text-white/40 transition-colors hover:text-white/90"
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</button>
|
||||
<div className="flex shrink-0 items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const next = !soundOn;
|
||||
setSoundOn(next);
|
||||
if (!next) {
|
||||
// Muting mid-line silences the clip immediately; the reveal
|
||||
// keeps its current pace.
|
||||
audioRef.current?.pause();
|
||||
}
|
||||
}}
|
||||
aria-pressed={!soundOn}
|
||||
aria-label={soundOn ? "Mute voice clips" : "Unmute voice clips"}
|
||||
title={soundOn ? "Mute voice clips" : "Unmute voice clips"}
|
||||
className="text-white/40 transition-colors hover:text-white/90"
|
||||
>
|
||||
{soundOn ? <Volume2Icon className="size-4" /> : <VolumeXIcon className="size-4" />}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={close}
|
||||
aria-label="Close conversation"
|
||||
className="text-white/40 transition-colors hover:text-white/90"
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
<span
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-0 opacity-[0.04]"
|
||||
|
|
@ -377,15 +569,50 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
/>
|
||||
</div>
|
||||
|
||||
{/* One element for every clip: starting a line stops the previous one
|
||||
and keeps the browser's autoplay permission for the session. */}
|
||||
<audio ref={audioRef} preload="none" className="hidden" />
|
||||
|
||||
{flow.startId === null ? (
|
||||
<div className="p-5 text-sm text-white/50">
|
||||
This conversation has no start node. Ask staff to configure it.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={scrollRef} className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
onClick={() => {
|
||||
// A click anywhere in the log finishes the line that is
|
||||
// typing, rather than leaving the player to wait it out.
|
||||
if (streamingId) skipRevealRef.current = streamingId;
|
||||
}}
|
||||
className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5"
|
||||
>
|
||||
{log.map((entry) => (
|
||||
<TimelineEntry key={entry.id} entry={entry} speakerDefault={npc.name} />
|
||||
<TimelineEntry
|
||||
key={entry.id}
|
||||
entry={entry}
|
||||
speakerDefault={npc.name}
|
||||
onPlayVoice={(url) => {
|
||||
// Explicit click: always allowed, and clears the notice.
|
||||
const audio = audioRef.current;
|
||||
if (!audio) return;
|
||||
audio.src = url;
|
||||
audio.currentTime = 0;
|
||||
void audio
|
||||
.play()
|
||||
.then(() =>
|
||||
setLog((prev) =>
|
||||
prev.map((e) =>
|
||||
e.kind === "node" && e.id === entry.id
|
||||
? { ...e, voiceBlocked: false }
|
||||
: e,
|
||||
),
|
||||
),
|
||||
)
|
||||
.catch(() => undefined);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{typing !== null && <TypingIndicator speaker={typing} />}
|
||||
{playerTyping && <TypingIndicator player />}
|
||||
|
|
@ -393,6 +620,7 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
|
||||
{!typing &&
|
||||
!playerTyping &&
|
||||
streamingId === null &&
|
||||
lastNode &&
|
||||
lastNode.kind === "node" &&
|
||||
(lastNode.node.type === "choice" || lastNode.node.type === "end") && (
|
||||
|
|
@ -463,9 +691,11 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
function TimelineEntry({
|
||||
entry,
|
||||
speakerDefault,
|
||||
onPlayVoice,
|
||||
}: {
|
||||
entry: LogEntry;
|
||||
speakerDefault: string;
|
||||
onPlayVoice?: (url: string) => void;
|
||||
}) {
|
||||
if (entry.kind === "player") {
|
||||
return (
|
||||
|
|
@ -478,55 +708,80 @@ function TimelineEntry({
|
|||
);
|
||||
}
|
||||
|
||||
const { node, resolved } = entry;
|
||||
const { node, resolved, text, reveal } = entry;
|
||||
/** A clip the browser refused to autoplay gets a button rather than nothing. */
|
||||
const voiceFallback =
|
||||
entry.voiceBlocked && entry.voiceUrl && onPlayVoice ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPlayVoice(entry.voiceUrl as string)}
|
||||
className="mt-1 inline-flex items-center gap-1.5 self-start rounded-sm border border-white/20 bg-black/40 px-2 py-1 font-mono text-[10px] uppercase tracking-wider text-white/70 transition-colors hover:border-cyan-500/60 hover:text-cyan-300"
|
||||
>
|
||||
<Volume2Icon className="size-3" />
|
||||
Play voice
|
||||
</button>
|
||||
) : null;
|
||||
|
||||
if (node.type === "event") {
|
||||
if (node.data.presentation === "narration") {
|
||||
// Descriptive narrative: the narrator's voice, not the NPC's. Centered
|
||||
// and muted with no accent bar so it reads as scene-setting rather than
|
||||
// as something the contact said.
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2 py-1 text-center">
|
||||
<p className="max-w-[42rem] text-sm italic leading-relaxed text-white/55">
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
</p>
|
||||
{voiceFallback}
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// Narration: no speaker, styled like a mission briefing line.
|
||||
const body = resolved?.body ?? node.data.body;
|
||||
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} />
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
</p>
|
||||
{voiceFallback}
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (node.type === "end") {
|
||||
const text = (resolved?.closing ?? node.data.closing) || "The conversation ends.";
|
||||
return (
|
||||
<p className="text-sm italic text-white/50">
|
||||
<DialogueText text={text} />
|
||||
</p>
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-sm italic text-white/50">
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
</p>
|
||||
{voiceFallback}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (node.type === "choice") {
|
||||
// The choice buttons live in the footer; only the lead-in joins the log.
|
||||
const leadIn = resolved?.leadIn ?? node.data.leadIn;
|
||||
if (!leadIn) return null;
|
||||
if (!text) return null;
|
||||
return (
|
||||
<p className="text-sm italic text-white/60">
|
||||
<DialogueText text={leadIn} />
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
const speaker = node.data.speaker?.trim() || speakerDefault;
|
||||
const body = resolved?.body ?? node.data.body;
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className={DOSSIER.readoutLabel}>{speaker}</span>
|
||||
<p className="text-sm text-white/90">
|
||||
{body ? (
|
||||
<DialogueText text={body} />
|
||||
{text ? (
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
) : (
|
||||
<span className="italic text-white/30">…</span>
|
||||
)}
|
||||
</p>
|
||||
{voiceFallback}
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@ src/lib/npc-dialogue/
|
|||
selection.ts # Which conversation is offered to a player (Payload)
|
||||
states.ts # Per-player read markers (Payload)
|
||||
attachments.ts # media ids to URLs (Payload)
|
||||
presentation.ts # Typewriter preference resolution (pure)
|
||||
reorder.ts, DialogueText.tsx (pure)
|
||||
|
||||
src/components/admin/npc-dialogue/
|
||||
|
|
@ -74,18 +75,106 @@ Node types: `dialogue`, `choice`, `event`, `end`, `delay`, `condition`. Effects
|
|||
executed by `triggerNpcDialogueEvent`, which re-reads the stored node rather than
|
||||
trusting the client.
|
||||
|
||||
An `event` node carries `presentation`: `event` (default, the amber left-barred
|
||||
line with no speaker) or `narration` (centered, muted, for a narrator describing
|
||||
a scene rather than the contact speaking). It changes rendering only; the walker
|
||||
and the effect run identically.
|
||||
|
||||
Availability is double-gated: `game-npcs.canMessage` on the contact, and the
|
||||
`entryGate` / `priority` on the dialogue document selecting which of an NPC's
|
||||
conversations is offered.
|
||||
|
||||
`testing: true` on a conversation makes it superuser-only. The flag is enforced
|
||||
in one place, `visibility.ts`, which both the offer and every node lookup call:
|
||||
|
||||
- **Who counts as a tester**: `system:admin-access` (the built-in admin role and
|
||||
superuser roles), not every author. A division officer who can edit
|
||||
conversations still cannot reach a testing one on the player site.
|
||||
- **Absent means live**: only an explicit `true` hides a conversation. Rows
|
||||
written before the flag existed read back as null and stay visible.
|
||||
- **The claim is verified, never trusted**: the conversation client sends its
|
||||
`dialogue.id` and each node lookup re-checks that the id belongs to the NPC and
|
||||
is visible to the reader, so a player cannot read a testing conversation's
|
||||
nodes by guessing an id. Those lookups used to take `limit: 1` on the NPC's
|
||||
conversations with no ordering, which with a testing conversation present could
|
||||
read the wrong document and silently skip an event effect.
|
||||
- **Badges follow the offer**: the NEW marker comes from the offered
|
||||
conversation, so a testing conversation never advertises itself to players.
|
||||
|
||||
## Flag conditions
|
||||
|
||||
Leaves test a `player-flags` value for the reading player, falling back to the
|
||||
global entry (`user: null`). `is_true` / `is_false` test truthiness, so a flag
|
||||
explicitly set to false reads the same as a missing one; use `is_defined` /
|
||||
`is_undefined` when the branch turns on whether a value was ever recorded. A
|
||||
flag whose `activatesAt` is still in the future counts as defined (recorded, not
|
||||
yet in effect) and reads false. An expired personal entry falls through to the
|
||||
global entry rather than reading as absent.
|
||||
|
||||
`NUMERIC_CONDITION_OPS` in `dialogue.ts` is the single list of ops that take
|
||||
`amount`; the editor, the `entryGate` field visibility and `conditionSummary`
|
||||
all read it. Adding an op to `CONDITION_OPS` also changes the
|
||||
`enum_npc_dialogues_entry_gate_op` Postgres enum, so it needs a migration
|
||||
(`ALTER TYPE ... ADD VALUE`), not just a code change. `generationSchema.ts` keeps
|
||||
its own copy of the op list for the drafting schema; update both.
|
||||
|
||||
## Text markup
|
||||
|
||||
Lines support `**bold**`, `*italic*`, `{red}color{/}`, `` `code` ``, ``,
|
||||
list prefixes, `{{flag}}`, `{{countdown:key}}`, and ternaries
|
||||
`{{ cond ? a : b }}` including numeric comparisons. Interpolation is a single
|
||||
`{{ cond ? key : other }}` including numeric comparisons. Interpolation is a single
|
||||
pass server-side, so a flag value can never smuggle in another token.
|
||||
`DialogueText.tsx` is the only renderer; don't hand-roll one.
|
||||
|
||||
## Voice clips
|
||||
|
||||
A line can carry `data.voice = { mediaId, filename? }` (dialogue, event and end
|
||||
nodes). Like attachments, flowData stores only a pointer and
|
||||
`resolveVoiceClip()` turns it into a URL per read, so a deleted file goes quiet
|
||||
instead of breaking the line.
|
||||
|
||||
- **Storage is always `media`.** Two sources feed it: a direct upload
|
||||
(`uploadNpcDialogueVoice`) and an accepted voiceover take
|
||||
(`importNpcDialogueVoice`, which copies the submission's audio because
|
||||
`voice-submissions` is owner-scoped while `media` is publicly readable). Both
|
||||
normalise to mono MP3 through `src/lib/voiceover/transcode.ts`, because browser
|
||||
recordings are WebM/Opus and iOS will not always play them. Transcode failure
|
||||
stores the original rather than losing the take.
|
||||
- **Playback paces the reveal.** The clip starts before the line lands and
|
||||
`clipDuration()` supplies the reveal length, so text and speech finish
|
||||
together; with no clip (or a muted player) the default cadence applies.
|
||||
- **Autoplay is not guaranteed.** A rejected `play()` marks the entry and the
|
||||
line offers a Play voice button. One `<audio>` element serves the whole
|
||||
conversation: a new line stops the previous clip and the session keeps its
|
||||
playback permission.
|
||||
- **Controls**: `users.preferences.dialogue.voice` (default on) is the durable
|
||||
choice; the speaker button in the dialog header mutes for that conversation
|
||||
only, read through a ref so a cascade in flight sees the change.
|
||||
- **Recruiting readers is the existing voiceover flow**: staff write a
|
||||
VoiceScript, players record it, staff accept it, then the line picks it up from
|
||||
the "Import accepted take" list. There is no automatic script-to-line link.
|
||||
|
||||
## Typing animation
|
||||
|
||||
Only the NPC's spoken lines type (`node.type === "dialogue"`); choice lead-ins,
|
||||
event lines, descriptive narration and end closings land whole, so a choice
|
||||
footer never waits on a lead-in. `DialogueText` takes a `reveal` count and truncates the
|
||||
**rendered** strings, never the source, so a half-typed line can never show `{gre`
|
||||
or an unclosed `**`. `visibleLength(text)` is the matching count (markup costs
|
||||
nothing, an image or countdown costs one) and is what pacing and "is it finished"
|
||||
both use.
|
||||
|
||||
- Unit default: `npc-dialogue-settings.presentation.typewriterDefault`. Changing it
|
||||
deliberately does not bump the prompt `revision`, since it is not prompt text.
|
||||
- Per player: `users.preferences.dialogue.typewriter` (`default` / `on` / `off`),
|
||||
resolved by `resolveTypewriter()` in `presentation.ts`. An explicit choice wins
|
||||
over the unit default in both directions.
|
||||
- `prefers-reduced-motion` forces the animation off regardless of either setting.
|
||||
- The choice footer and End button are gated on the reveal finishing, so nobody
|
||||
answers a line they have not seen. Clicking the log finishes it immediately.
|
||||
- The component stores the line's resolved text on the log entry and renders that,
|
||||
so the reveal length and the rendered string cannot drift apart.
|
||||
|
||||
## AI drafting behaviour worth knowing
|
||||
|
||||
- Two attempts maximum: the second prompt carries the validator's complaints.
|
||||
|
|
|
|||
|
|
@ -25,14 +25,55 @@ import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
|||
* 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 }) {
|
||||
/**
|
||||
* Characters still allowed to appear while a line types out. Markup costs
|
||||
* nothing, a countdown or an inline image costs one, so a reveal can stop
|
||||
* anywhere without flashing raw markup or cutting a component in half.
|
||||
*/
|
||||
interface RevealBudget {
|
||||
left: number;
|
||||
}
|
||||
|
||||
/** Budget for a fully revealed line (a number, not Infinity, so the consumed
|
||||
* count stays computable). */
|
||||
const UNLIMITED_REVEAL = Number.MAX_SAFE_INTEGER;
|
||||
|
||||
/**
|
||||
* Renders dialogue markup. `reveal` limits how many visible characters appear,
|
||||
* which is how conversation lines type themselves out; leave it undefined for
|
||||
* the whole line. Truncation happens on the rendered strings, never on the
|
||||
* source, so a half-typed line can never show `{gre` or an unclosed `**`.
|
||||
*/
|
||||
export function DialogueText({
|
||||
text,
|
||||
className,
|
||||
reveal,
|
||||
}: {
|
||||
text: string;
|
||||
className?: string;
|
||||
reveal?: number;
|
||||
}) {
|
||||
const budget: RevealBudget = {
|
||||
left: reveal === undefined ? UNLIMITED_REVEAL : Math.max(0, Math.floor(reveal)),
|
||||
};
|
||||
return (
|
||||
<span className={`whitespace-pre-wrap ${className ?? ""}`}>
|
||||
{renderBlocks(text, { i: 0 })}
|
||||
{renderBlocks(text, { i: 0 }, budget)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visible characters in a line, counted the way `reveal` counts them (markup
|
||||
* costs nothing, an image or countdown costs one). Pacing a reveal and knowing
|
||||
* when it is finished both need this, and both must agree with the renderer.
|
||||
*/
|
||||
export function visibleLength(text: string): number {
|
||||
const budget: RevealBudget = { left: UNLIMITED_REVEAL };
|
||||
renderBlocks(text, { i: 0 }, budget);
|
||||
return UNLIMITED_REVEAL - budget.left;
|
||||
}
|
||||
|
||||
const BULLET_RE = /^[-*]\s+/;
|
||||
const ORDERED_RE = /^\d+[.)]\s+/;
|
||||
|
||||
|
|
@ -42,7 +83,7 @@ const ORDERED_RE = /^\d+[.)]\s+/;
|
|||
* 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[] {
|
||||
function renderBlocks(text: string, keys: { i: number }, budget: RevealBudget): ReactNode[] {
|
||||
if (!text) return [];
|
||||
const out: ReactNode[] = [];
|
||||
let paragraph: string[] = [];
|
||||
|
|
@ -53,7 +94,9 @@ function renderBlocks(text: string, keys: { i: number }): ReactNode[] {
|
|||
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>);
|
||||
out.push(
|
||||
<span key={`p${keys.i++}`}>{parseSegment(chunk, 0, keys, false, budget).nodes}</span>,
|
||||
);
|
||||
};
|
||||
const flushList = () => {
|
||||
if (!listKind) return;
|
||||
|
|
@ -65,7 +108,7 @@ function renderBlocks(text: string, keys: { i: number }): ReactNode[] {
|
|||
<span aria-hidden className="shrink-0 text-white/40">
|
||||
{kind === "ul" ? "\u2022" : `${index + 1}.`}
|
||||
</span>
|
||||
<span>{parseSegment(item, 0, keys, false).nodes}</span>
|
||||
<span>{parseSegment(item, 0, keys, false, budget).nodes}</span>
|
||||
</span>
|
||||
))}
|
||||
</span>,
|
||||
|
|
@ -145,16 +188,27 @@ interface ParseResult {
|
|||
* keeps both). When `insideColor` is set, scanning stops at the matching
|
||||
* `{/}` so nested colors close inner-first.
|
||||
*/
|
||||
function parseSegment(text: string, depth: number, keys: { i: number }, insideColor: boolean): ParseResult {
|
||||
function parseSegment(
|
||||
text: string,
|
||||
depth: number,
|
||||
keys: { i: number },
|
||||
insideColor: boolean,
|
||||
budget: RevealBudget,
|
||||
): ParseResult {
|
||||
const nodes: ReactNode[] = [];
|
||||
let plain = "";
|
||||
let i = 0;
|
||||
const key = () => `${depth}:${keys.i++}`;
|
||||
const flush = () => {
|
||||
if (plain) {
|
||||
nodes.push(plain);
|
||||
plain = "";
|
||||
if (!plain) return;
|
||||
// Only the part of the run the reveal has reached is emitted; the rest is
|
||||
// dropped this render (the prefix is rebuilt from the full source next tick).
|
||||
if (budget.left > 0) {
|
||||
const take = Math.min(plain.length, budget.left);
|
||||
nodes.push(take === plain.length ? plain : plain.slice(0, take));
|
||||
budget.left -= take;
|
||||
}
|
||||
plain = "";
|
||||
};
|
||||
|
||||
while (i < text.length) {
|
||||
|
|
@ -171,14 +225,20 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo
|
|||
const end = rest.indexOf("`", 1);
|
||||
if (end > 1) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<code
|
||||
key={key()}
|
||||
className="rounded-sm bg-white/10 px-1 py-0.5 font-mono text-[0.85em] text-cyan-300"
|
||||
>
|
||||
{rest.slice(1, end)}
|
||||
</code>,
|
||||
);
|
||||
const code = rest.slice(1, end);
|
||||
// A code run is atomic: it pops in as one unit rather than typing out,
|
||||
// since its characters are literal and often not prose.
|
||||
if (budget.left >= code.length) {
|
||||
budget.left -= code.length;
|
||||
nodes.push(
|
||||
<code
|
||||
key={key()}
|
||||
className="rounded-sm bg-white/10 px-1 py-0.5 font-mono text-[0.85em] text-cyan-300"
|
||||
>
|
||||
{code}
|
||||
</code>,
|
||||
);
|
||||
}
|
||||
i += end + 1;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -188,7 +248,10 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo
|
|||
const cd = COUNTDOWN_RE.exec(rest);
|
||||
if (cd) {
|
||||
flush();
|
||||
nodes.push(<Countdown key={key()} value={cd[1]} />);
|
||||
if (budget.left >= 1) {
|
||||
budget.left -= 1;
|
||||
nodes.push(<Countdown key={key()} value={cd[1]} />);
|
||||
}
|
||||
i += cd[0].length;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -200,14 +263,17 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo
|
|||
const src = safeUrl(img[2]);
|
||||
if (src) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<img
|
||||
key={key()}
|
||||
src={src}
|
||||
alt={img[1]}
|
||||
className="mx-0.5 inline-block h-[1.15em] w-auto align-[-0.2em] object-contain"
|
||||
/>,
|
||||
);
|
||||
if (budget.left >= 1) {
|
||||
budget.left -= 1;
|
||||
nodes.push(
|
||||
<img
|
||||
key={key()}
|
||||
src={src}
|
||||
alt={img[1]}
|
||||
className="mx-0.5 inline-block h-[1.15em] w-auto align-[-0.2em] object-contain"
|
||||
/>,
|
||||
);
|
||||
}
|
||||
i += img[0].length;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -221,11 +287,16 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo
|
|||
const href = safeUrl(link[2]);
|
||||
if (href) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<DialogueLink key={key()} href={href}>
|
||||
{parseSegment(link[1], depth + 1, keys, false).nodes}
|
||||
</DialogueLink>,
|
||||
);
|
||||
const label = parseSegment(link[1], depth + 1, keys, false, budget);
|
||||
// An unrevealed label renders nothing; the link appears as its text
|
||||
// types in, and never as an empty clickable fragment.
|
||||
if (label.nodes.length > 0) {
|
||||
nodes.push(
|
||||
<DialogueLink key={key()} href={href}>
|
||||
{label.nodes}
|
||||
</DialogueLink>,
|
||||
);
|
||||
}
|
||||
i += link[0].length;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -236,15 +307,19 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo
|
|||
if (rest[0] === "{") {
|
||||
const open = COLOR_OPEN_RE.exec(rest);
|
||||
if (open && open[1] !== "/") {
|
||||
const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true);
|
||||
flush();
|
||||
const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true, budget);
|
||||
const style = colorStyle(open[1]);
|
||||
if (inner.closed && style) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<span key={key()} className={style.className} style={style.style}>
|
||||
{inner.nodes}
|
||||
</span>,
|
||||
);
|
||||
// An unrevealed run contributes nothing; the span appears with the
|
||||
// first character inside it.
|
||||
if (inner.nodes.length > 0) {
|
||||
nodes.push(
|
||||
<span key={key()} className={style.className} style={style.style}>
|
||||
{inner.nodes}
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
i += open[0].length + inner.consumed;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -257,11 +332,14 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo
|
|||
const end = rest.indexOf("**", 2);
|
||||
if (end > 2) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<strong key={key()} className="font-semibold">
|
||||
{parseSegment(rest.slice(2, end), depth + 1, keys, false).nodes}
|
||||
</strong>,
|
||||
);
|
||||
const inner = parseSegment(rest.slice(2, end), depth + 1, keys, false, budget);
|
||||
if (inner.nodes.length > 0) {
|
||||
nodes.push(
|
||||
<strong key={key()} className="font-semibold">
|
||||
{inner.nodes}
|
||||
</strong>,
|
||||
);
|
||||
}
|
||||
i += end + 2;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -270,11 +348,10 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo
|
|||
const end = rest.indexOf("*", 1);
|
||||
if (end > 1 && rest[end + 1] !== "*") {
|
||||
flush();
|
||||
nodes.push(
|
||||
<em key={key()}>
|
||||
{parseSegment(rest.slice(1, end), depth + 1, keys, false).nodes}
|
||||
</em>,
|
||||
);
|
||||
const inner = parseSegment(rest.slice(1, end), depth + 1, keys, false, budget);
|
||||
if (inner.nodes.length > 0) {
|
||||
nodes.push(<em key={key()}>{inner.nodes}</em>);
|
||||
}
|
||||
i += end + 1;
|
||||
continue;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,10 @@
|
|||
import type { Payload } from "payload";
|
||||
import type { DialogueAttachment, ResolvedAttachment } from "./dialogue";
|
||||
import type {
|
||||
DialogueAttachment,
|
||||
DialogueVoiceClip,
|
||||
ResolvedAttachment,
|
||||
ResolvedVoiceClip,
|
||||
} from "./dialogue";
|
||||
|
||||
/**
|
||||
* Resolve flowData attachment pointers into renderable file references.
|
||||
|
|
@ -41,3 +46,34 @@ export async function resolveAttachments(
|
|||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a node's voice clip into a playable file reference. Returns null when
|
||||
* the node has no clip or the media document is gone, so the conversation
|
||||
* simply plays nothing instead of erroring on a dead pointer. Payload-dependent,
|
||||
* server only.
|
||||
*/
|
||||
export async function resolveVoiceClip(
|
||||
payload: Payload,
|
||||
voice: DialogueVoiceClip | undefined,
|
||||
): Promise<ResolvedVoiceClip | null> {
|
||||
const id = Number(voice?.mediaId);
|
||||
if (!Number.isFinite(id) || id <= 0) return null;
|
||||
try {
|
||||
const doc = await payload.findByID({
|
||||
collection: "media",
|
||||
id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
select: { filename: true, mimeType: true },
|
||||
});
|
||||
if (!doc?.filename) return null;
|
||||
return {
|
||||
url: `/api/media/file/${doc.filename}`,
|
||||
filename: doc.filename,
|
||||
mimeType: doc.mimeType ?? "audio/mpeg",
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,7 +59,9 @@ export interface ChoiceGate {
|
|||
* Branch condition evaluated server-side against live web-app state when the
|
||||
* conversation arrives at a `condition` node. Boolean flags compare against
|
||||
* true/false; numeric flags compare against `amount` (a missing flag counts
|
||||
* as false / zero).
|
||||
* as false / zero). The defined checks test whether the reading player has a
|
||||
* recorded value at all, which no truthiness test can express: a missing flag
|
||||
* and a flag explicitly set to false both read as false.
|
||||
*/
|
||||
export interface DialogueFlagCondition {
|
||||
/** Currently only generic player flags; more kinds can join later. */
|
||||
|
|
@ -67,8 +69,20 @@ export interface DialogueFlagCondition {
|
|||
/** `player-flags` key checked for the reading user. */
|
||||
key: string;
|
||||
/** Comparison applied to the flag's effective value. */
|
||||
op: "is_true" | "is_false" | "gte" | "lte" | "gt" | "lt" | "eq";
|
||||
/** Right-hand side for the numeric comparisons. */
|
||||
op:
|
||||
| "is_true"
|
||||
| "is_false"
|
||||
| "is_defined"
|
||||
| "is_undefined"
|
||||
| "gte"
|
||||
| "lte"
|
||||
| "gt"
|
||||
| "lt"
|
||||
| "eq";
|
||||
/**
|
||||
* Right-hand side for the numeric comparisons. Ignored by the state checks
|
||||
* (`is_true` / `is_false` / `is_defined` / `is_undefined`).
|
||||
*/
|
||||
amount?: number;
|
||||
}
|
||||
|
||||
|
|
@ -90,6 +104,22 @@ export type DialogueCondition = DialogueFlagCondition | DialogueConditionGroup;
|
|||
export const CONDITION_OPS: DialogueFlagCondition["op"][] = [
|
||||
"is_true",
|
||||
"is_false",
|
||||
"is_defined",
|
||||
"is_undefined",
|
||||
"gte",
|
||||
"lte",
|
||||
"gt",
|
||||
"lt",
|
||||
"eq",
|
||||
];
|
||||
|
||||
/**
|
||||
* Ops that compare the flag against `amount`. Everything else tests the flag's
|
||||
* state (truthiness or existence), so the amount is meaningless for them and
|
||||
* the UI hides it. Shared so the editor, the entry-gate field and the canvas
|
||||
* summary never disagree about which ops take a number.
|
||||
*/
|
||||
export const NUMERIC_CONDITION_OPS: DialogueFlagCondition["op"][] = [
|
||||
"gte",
|
||||
"lte",
|
||||
"gt",
|
||||
|
|
@ -169,11 +199,40 @@ export interface ResolvedAttachment {
|
|||
sizeBytes?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Voice clip recorded for one line. Only the media pointer is stored in
|
||||
* flowData; the runtime resolves it to a URL per read, the same way
|
||||
* attachments work, so a deleted file simply stops playing.
|
||||
*/
|
||||
export interface DialogueVoiceClip {
|
||||
/** `media` document holding the audio. */
|
||||
mediaId: number;
|
||||
/**
|
||||
* Stored filename, for the editor's inline preview. Playback still resolves
|
||||
* through `mediaId`, so a stale name cannot break the line.
|
||||
*/
|
||||
filename?: string;
|
||||
}
|
||||
|
||||
/** A voice clip resolved for playback. */
|
||||
export interface ResolvedVoiceClip {
|
||||
url: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
}
|
||||
|
||||
export type DialogueNodeData = {
|
||||
/** Speaker label shown above the line. Defaults to the NPC's name at runtime. */
|
||||
speaker?: string;
|
||||
/** The spoken line (dialogue) or narrative description (event nodes). */
|
||||
body?: string;
|
||||
/**
|
||||
* How an `event` node's body is presented to the player. `event` (default) is
|
||||
* the spoken-style amber line with the NPC's name above it; `narration` is a
|
||||
* centered, muted description with no speaker, for scene-setting beats the
|
||||
* NPC is not saying out loud. Ignored by every other node type.
|
||||
*/
|
||||
presentation?: "event" | "narration";
|
||||
/** Branching options (choice nodes). */
|
||||
choices?: DialogueNext[];
|
||||
/** Optional lead-in text before the choices. */
|
||||
|
|
@ -184,6 +243,12 @@ export type DialogueNodeData = {
|
|||
closing?: string;
|
||||
/** Files attached to this node's message (dialogue/event/end nodes). */
|
||||
attachments?: DialogueAttachment[];
|
||||
/**
|
||||
* Recorded voice for this line (dialogue/event/end nodes). Plays when the
|
||||
* line lands and paces the reveal to the clip, so the text finishes with the
|
||||
* read. Omitted = a silent line.
|
||||
*/
|
||||
voice?: DialogueVoiceClip;
|
||||
/** Marks this node as the conversation start. */
|
||||
isStart?: boolean;
|
||||
/** Single continuation (dialogue / event / end nodes). */
|
||||
|
|
@ -444,7 +509,7 @@ export function connectHop(
|
|||
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}` : ""
|
||||
c.amount !== undefined && NUMERIC_CONDITION_OPS.includes(c.op) ? ` ${c.amount}` : ""
|
||||
}`;
|
||||
if (condition.kind === "group") {
|
||||
const joiner = condition.op === "and" ? " and " : condition.op === "or" ? " or " : " and ";
|
||||
|
|
|
|||
|
|
@ -104,8 +104,14 @@ export async function readFlag(
|
|||
});
|
||||
const playerDoc = playerRes.docs[0];
|
||||
if (playerDoc) {
|
||||
if (!activeNow(playerDoc)) return inactiveValues(playerDoc);
|
||||
return flagValues(playerDoc);
|
||||
// Pending activation: the value is recorded but not in effect yet, so it
|
||||
// reads inactive now while still counting as defined and carrying its
|
||||
// countdown target.
|
||||
if (pendingActivation(playerDoc)) return inactiveValues(playerDoc);
|
||||
// Active: this is the value.
|
||||
if (activeNow(playerDoc)) return flagValues(playerDoc);
|
||||
// Expired: the personal entry no longer applies, so fall through to the
|
||||
// global fallback below (matching the contract in this function's doc).
|
||||
}
|
||||
|
||||
// Global fallback (user is null).
|
||||
|
|
@ -174,6 +180,13 @@ export async function evaluateCondition(
|
|||
return flag.bool;
|
||||
case "is_false":
|
||||
return !flag.bool;
|
||||
// Existence, not truthiness: a flag explicitly set to false is defined,
|
||||
// and a missing one is not. A not-yet-active flag counts as defined (its
|
||||
// value is recorded, it just has not taken effect), matching `exists`.
|
||||
case "is_defined":
|
||||
return flag.exists;
|
||||
case "is_undefined":
|
||||
return !flag.exists;
|
||||
case "gte":
|
||||
return flag.num >= amount;
|
||||
case "lte":
|
||||
|
|
|
|||
|
|
@ -37,7 +37,17 @@ export const DRAFT_NODE_TYPES = ["dialogue", "choice", "event", "end", "conditio
|
|||
export const DRAFT_EFFECT_TYPES = ["none", "flag", "notify"] as const;
|
||||
|
||||
const FLAG_OPS = ["set_true", "set_false", "set_number", "set_text", "add"] as const;
|
||||
const CONDITION_OPS = ["is_true", "is_false", "gte", "lte", "gt", "lt", "eq"] as const;
|
||||
const CONDITION_OPS = [
|
||||
"is_true",
|
||||
"is_false",
|
||||
"is_defined",
|
||||
"is_undefined",
|
||||
"gte",
|
||||
"lte",
|
||||
"gt",
|
||||
"lt",
|
||||
"eq",
|
||||
] as const;
|
||||
|
||||
export interface RawDraftChoice {
|
||||
label: string;
|
||||
|
|
|
|||
|
|
@ -25,6 +25,9 @@ type SettingsDoc = {
|
|||
voice?: string | null;
|
||||
extraRules?: string | null;
|
||||
revision?: number | null;
|
||||
presentation?: {
|
||||
typewriterDefault?: boolean | null;
|
||||
} | null;
|
||||
} | null;
|
||||
|
||||
export interface DialoguePromptSettings {
|
||||
|
|
@ -34,9 +37,16 @@ export interface DialoguePromptSettings {
|
|||
extraRules: string | null;
|
||||
/** Bumped by the global's beforeChange hook whenever the text changes. */
|
||||
revision: number | null;
|
||||
/** Unit default for typing conversation lines out character by character. */
|
||||
typewriterDefault: boolean;
|
||||
}
|
||||
|
||||
const EMPTY: DialoguePromptSettings = { voice: null, extraRules: null, revision: null };
|
||||
const EMPTY: DialoguePromptSettings = {
|
||||
voice: null,
|
||||
extraRules: null,
|
||||
revision: null,
|
||||
typewriterDefault: true,
|
||||
};
|
||||
|
||||
/** Read the prompt settings, falling back to the built-in defaults on any miss. */
|
||||
export async function loadDialogueSettings(payload: Payload): Promise<DialoguePromptSettings> {
|
||||
|
|
@ -54,6 +64,9 @@ export async function loadDialogueSettings(payload: Payload): Promise<DialoguePr
|
|||
voice: doc?.voice?.trim() || null,
|
||||
extraRules: doc?.extraRules?.trim() || null,
|
||||
revision: typeof doc?.revision === "number" ? doc.revision : null,
|
||||
// Only an explicit false turns it off, so a document written before this
|
||||
// field existed still types out (its default).
|
||||
typewriterDefault: doc?.presentation?.typewriterDefault !== false,
|
||||
};
|
||||
} catch (error) {
|
||||
// A missing global (fresh database before the migration ran) must not make
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
* Pure module: client-safe (no Payload imports).
|
||||
*/
|
||||
|
||||
import type { DialogueNode, ResolvedAttachment } from "./dialogue";
|
||||
import type { DialogueNode, ResolvedAttachment, ResolvedVoiceClip } from "./dialogue";
|
||||
|
||||
/** One `{{key}}` token. Keys are matched leniently and lowercased; flag keys
|
||||
* are documented as lowercase-with-underscores. */
|
||||
|
|
@ -233,6 +233,11 @@ export interface ResolvedNodeTexts {
|
|||
* "unresolved").
|
||||
*/
|
||||
attachments?: ResolvedAttachment[];
|
||||
/**
|
||||
* Recorded voice for this line, resolved to a playable URL. Absent means the
|
||||
* line is silent (or its file is gone).
|
||||
*/
|
||||
voice?: ResolvedVoiceClip;
|
||||
}
|
||||
|
||||
/** Every distinct flag key referenced by `text`, lowercased. */
|
||||
|
|
|
|||
36
src/lib/npc-dialogue/presentation.ts
Normal file
36
src/lib/npc-dialogue/presentation.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
/**
|
||||
* Player-facing presentation preferences for NPC conversations.
|
||||
*
|
||||
* The unit default lives on the `npc-dialogue-settings` global; a player may
|
||||
* override it in their account preferences. Resolution is pure so the contact
|
||||
* page, the account form and the tests all agree, and so the component never has
|
||||
* to guess what a missing value means.
|
||||
*/
|
||||
|
||||
/** Stored per-user choice. `default` defers to the unit setting. */
|
||||
export type TypewriterPreference = "default" | "on" | "off";
|
||||
|
||||
/** The three stored values, in the order the account form shows them. */
|
||||
export const TYPEWRITER_PREFERENCE_VALUES: TypewriterPreference[] = ["default", "on", "off"];
|
||||
|
||||
/**
|
||||
* Whether conversation lines type out for this player.
|
||||
*
|
||||
* An explicit player choice always wins, in either direction: a player who
|
||||
* dislikes the animation can turn it off even when the unit default is on, and a
|
||||
* player who wants it can keep it when the unit default is off. Anything else
|
||||
* (unset, `default`, an unknown stored value) follows the unit setting.
|
||||
*/
|
||||
export function resolveTypewriter(
|
||||
preference: TypewriterPreference | string | null | undefined,
|
||||
unitDefault: boolean,
|
||||
): boolean {
|
||||
if (preference === "on") return true;
|
||||
if (preference === "off") return false;
|
||||
return unitDefault;
|
||||
}
|
||||
|
||||
/** Coerce a stored value to a known preference; unknown values mean `default`. */
|
||||
export function normalizeTypewriterPreference(value: unknown): TypewriterPreference {
|
||||
return value === "on" || value === "off" ? value : "default";
|
||||
}
|
||||
111
src/lib/npc-dialogue/visibility.ts
Normal file
111
src/lib/npc-dialogue/visibility.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
/**
|
||||
* Which conversations a player may be offered, and which one they are in.
|
||||
*
|
||||
* A conversation flagged `testing` is authorable but unreleased: superusers can
|
||||
* walk it on the live site, players never see it, its "new" badge, or its text.
|
||||
* Both decisions (the offer, and the node lookups that follow) go through this
|
||||
* module so a flag cannot be enforced on one path and forgotten on another.
|
||||
*
|
||||
* Server only: it reads flags and media-adjacent state through Payload.
|
||||
*/
|
||||
|
||||
import type { Payload } from "payload";
|
||||
|
||||
import type { FlowData } from "./dialogue";
|
||||
import { evaluateCondition } from "./flags";
|
||||
import { selectDialogueForUser } from "./selection";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
|
||||
/** The part of an npc-dialogues document this module reads. */
|
||||
export interface TestingAwareDialogue {
|
||||
testing?: boolean | null;
|
||||
}
|
||||
|
||||
/** A conversation as the conversation client needs it. */
|
||||
export interface PlayerDialogue {
|
||||
id: number;
|
||||
flowData?: FlowData;
|
||||
}
|
||||
|
||||
/** Whether this player may see an unreleased conversation. */
|
||||
export function dialogueVisibleTo(doc: TestingAwareDialogue, canSeeTesting: boolean): boolean {
|
||||
// Anything not explicitly flagged is live, including rows written before the
|
||||
// flag existed (their column predates this check and may hold null).
|
||||
return canSeeTesting || doc.testing !== true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this reader belongs to the superuser tier, which is what "testing
|
||||
* only" means: the built-in admin role and superuser roles, not every author.
|
||||
*/
|
||||
export async function canSeeTestingDialogues(
|
||||
payload: Payload,
|
||||
user: { id: number | string; roleDocs?: unknown } | null | undefined,
|
||||
): Promise<boolean> {
|
||||
return hasPermission(payload, user, "system:admin-access");
|
||||
}
|
||||
|
||||
/** The NPC a stored relationship points at, whichever depth it was read at. */
|
||||
function relatedId(value: unknown): number | null {
|
||||
if (typeof value === "number") return value;
|
||||
if (value && typeof value === "object" && "id" in value) {
|
||||
const id = (value as { id: unknown }).id;
|
||||
return typeof id === "number" ? id : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The conversation this player is in, or null when there is none.
|
||||
*
|
||||
* With `dialogueId` the client is claiming an active conversation: the claim is
|
||||
* verified (right NPC, visible to this reader) rather than trusted, so a player
|
||||
* cannot read a superuser-only conversation's nodes by guessing an id. Without
|
||||
* it, this is the offer: the highest-priority conversation whose entry gate
|
||||
* passes, skipping any the reader may not see.
|
||||
*/
|
||||
export async function loadPlayerDialogue(
|
||||
payload: Payload,
|
||||
options: {
|
||||
npcId: number;
|
||||
userId?: number | null;
|
||||
canSeeTesting: boolean;
|
||||
dialogueId?: number | null;
|
||||
},
|
||||
): Promise<PlayerDialogue | null> {
|
||||
const { npcId, userId, canSeeTesting, dialogueId } = options;
|
||||
|
||||
if (dialogueId) {
|
||||
const doc = await payload
|
||||
.findByID({
|
||||
collection: "npc-dialogues",
|
||||
id: dialogueId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
disableErrors: true,
|
||||
})
|
||||
.catch(() => null);
|
||||
if (!doc) return null;
|
||||
if (relatedId(doc.npc) !== Number(npcId)) return null;
|
||||
if (!dialogueVisibleTo(doc, canSeeTesting)) return null;
|
||||
return { id: doc.id, flowData: doc.flowData as unknown as FlowData | undefined };
|
||||
}
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 25,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
// Filter in code rather than in the query: an unset `testing` column is null,
|
||||
// and `<> true` on null matches nothing, which would hide every older row.
|
||||
const candidates = res.docs.filter((doc) => dialogueVisibleTo(doc, canSeeTesting));
|
||||
const chosen = await selectDialogueForUser(candidates, async (condition) => {
|
||||
if (!userId) return false;
|
||||
return evaluateCondition(payload, userId, condition);
|
||||
});
|
||||
if (!chosen) return null;
|
||||
return { id: chosen.id, flowData: chosen.flowData as unknown as FlowData | undefined };
|
||||
}
|
||||
47097
src/migrations/20261124_223219_add_defined_condition_ops.json
Normal file
47097
src/migrations/20261124_223219_add_defined_condition_ops.json
Normal file
File diff suppressed because it is too large
Load diff
17
src/migrations/20261124_223219_add_defined_condition_ops.ts
Normal file
17
src/migrations/20261124_223219_add_defined_condition_ops.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TYPE "public"."enum_npc_dialogues_entry_gate_op" ADD VALUE 'is_defined' BEFORE 'gte';
|
||||
ALTER TYPE "public"."enum_npc_dialogues_entry_gate_op" ADD VALUE 'is_undefined' BEFORE 'gte';`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "npc_dialogues" ALTER COLUMN "entry_gate_op" SET DATA TYPE text;
|
||||
ALTER TABLE "npc_dialogues" ALTER COLUMN "entry_gate_op" SET DEFAULT 'is_true'::text;
|
||||
DROP TYPE "public"."enum_npc_dialogues_entry_gate_op";
|
||||
CREATE TYPE "public"."enum_npc_dialogues_entry_gate_op" AS ENUM('is_true', 'is_false', 'gte', 'lte', 'gt', 'lt', 'eq');
|
||||
ALTER TABLE "npc_dialogues" ALTER COLUMN "entry_gate_op" SET DEFAULT 'is_true'::"public"."enum_npc_dialogues_entry_gate_op";
|
||||
ALTER TABLE "npc_dialogues" ALTER COLUMN "entry_gate_op" SET DATA TYPE "public"."enum_npc_dialogues_entry_gate_op" USING "entry_gate_op"::"public"."enum_npc_dialogues_entry_gate_op";`)
|
||||
}
|
||||
47128
src/migrations/20261124_223724_add_conversation_typewriter_setting.json
Normal file
47128
src/migrations/20261124_223724_add_conversation_typewriter_setting.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,17 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
CREATE TYPE "public"."enum_users_preferences_dialogue_typewriter" AS ENUM('default', 'on', 'off');
|
||||
ALTER TABLE "users" ADD COLUMN "preferences_dialogue_typewriter" "enum_users_preferences_dialogue_typewriter" DEFAULT 'default';
|
||||
ALTER TABLE "npc_dialogue_settings" ADD COLUMN "presentation_typewriter_default" boolean DEFAULT true;
|
||||
ALTER TABLE "_npc_dialogue_settings_v" ADD COLUMN "version_presentation_typewriter_default" boolean DEFAULT true;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "users" DROP COLUMN "preferences_dialogue_typewriter";
|
||||
ALTER TABLE "npc_dialogue_settings" DROP COLUMN "presentation_typewriter_default";
|
||||
ALTER TABLE "_npc_dialogue_settings_v" DROP COLUMN "version_presentation_typewriter_default";
|
||||
DROP TYPE "public"."enum_users_preferences_dialogue_typewriter";`)
|
||||
}
|
||||
47135
src/migrations/20261124_225400_add_conversation_voice_preference.json
Normal file
47135
src/migrations/20261124_225400_add_conversation_voice_preference.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,11 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "users" ADD COLUMN "preferences_dialogue_voice" boolean DEFAULT true;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "users" DROP COLUMN "preferences_dialogue_voice";`)
|
||||
}
|
||||
47142
src/migrations/20261124_232253_add_npc_dialogue_testing_flag.json
Normal file
47142
src/migrations/20261124_232253_add_npc_dialogue_testing_flag.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,11 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "npc_dialogues" ADD COLUMN "testing" boolean DEFAULT false;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "npc_dialogues" DROP COLUMN "testing";`)
|
||||
}
|
||||
|
|
@ -166,6 +166,10 @@ import * as migration_20261121_015435_add_mission_attendance_unlocks from './202
|
|||
import * as migration_20261123_073019_add_tech_tree_notes from './20261123_073019_add_tech_tree_notes';
|
||||
import * as migration_20261124_174637_add_npc_dialogue_prompt_settings from './20261124_174637_add_npc_dialogue_prompt_settings';
|
||||
import * as migration_20261124_175950_add_ai_connections from './20261124_175950_add_ai_connections';
|
||||
import * as migration_20261124_223219_add_defined_condition_ops from './20261124_223219_add_defined_condition_ops';
|
||||
import * as migration_20261124_223724_add_conversation_typewriter_setting from './20261124_223724_add_conversation_typewriter_setting';
|
||||
import * as migration_20261124_225400_add_conversation_voice_preference from './20261124_225400_add_conversation_voice_preference';
|
||||
import * as migration_20261124_232253_add_npc_dialogue_testing_flag from './20261124_232253_add_npc_dialogue_testing_flag';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -1006,6 +1010,26 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261124_175950_add_ai_connections.up,
|
||||
down: migration_20261124_175950_add_ai_connections.down,
|
||||
name: '20261124_175950_add_ai_connections'
|
||||
name: '20261124_175950_add_ai_connections',
|
||||
},
|
||||
{
|
||||
up: migration_20261124_223219_add_defined_condition_ops.up,
|
||||
down: migration_20261124_223219_add_defined_condition_ops.down,
|
||||
name: '20261124_223219_add_defined_condition_ops',
|
||||
},
|
||||
{
|
||||
up: migration_20261124_223724_add_conversation_typewriter_setting.up,
|
||||
down: migration_20261124_223724_add_conversation_typewriter_setting.down,
|
||||
name: '20261124_223724_add_conversation_typewriter_setting',
|
||||
},
|
||||
{
|
||||
up: migration_20261124_225400_add_conversation_voice_preference.up,
|
||||
down: migration_20261124_225400_add_conversation_voice_preference.down,
|
||||
name: '20261124_225400_add_conversation_voice_preference',
|
||||
},
|
||||
{
|
||||
up: migration_20261124_232253_add_npc_dialogue_testing_flag.up,
|
||||
down: migration_20261124_232253_add_npc_dialogue_testing_flag.down,
|
||||
name: '20261124_232253_add_npc_dialogue_testing_flag'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -552,6 +552,16 @@ export interface User {
|
|||
| boolean
|
||||
| null;
|
||||
};
|
||||
dialogue?: {
|
||||
/**
|
||||
* NPC dialogue lines type out letter by letter. Click a line to finish it immediately. Reduced-motion devices always show lines instantly.
|
||||
*/
|
||||
typewriter?: ('default' | 'on' | 'off') | null;
|
||||
/**
|
||||
* Recorded lines play as they arrive. You can also mute for the rest of a conversation with the speaker button in its header.
|
||||
*/
|
||||
voice?: boolean | null;
|
||||
};
|
||||
discord?: {
|
||||
enabled?: boolean | null;
|
||||
mutedTypes?:
|
||||
|
|
@ -3028,6 +3038,10 @@ export interface NpcDialogue {
|
|||
* When a contact has several conversations, the highest-priority one whose entry gate passes is the one offered. Ties break by oldest first.
|
||||
*/
|
||||
priority?: number | null;
|
||||
/**
|
||||
* Walk this conversation on the live site without releasing it. Only the superuser tier is offered it: players never see it or its new-message badge, and it cannot be resolved by guessing its id. Untick to publish.
|
||||
*/
|
||||
testing?: boolean | null;
|
||||
/**
|
||||
* Only offer this conversation to players whose flags pass this condition. Leave the key empty to always offer it (ungated conversations are the fallback).
|
||||
*/
|
||||
|
|
@ -3039,7 +3053,7 @@ export interface NpcDialogue {
|
|||
/**
|
||||
* Comparison applied to the flag's effective value.
|
||||
*/
|
||||
op?: ('is_true' | 'is_false' | 'gte' | 'lte' | 'gt' | 'lt' | 'eq') | null;
|
||||
op?: ('is_true' | 'is_false' | 'is_defined' | 'is_undefined' | 'gte' | 'lte' | 'gt' | 'lt' | 'eq') | null;
|
||||
/**
|
||||
* Right-hand side for the numeric comparisons.
|
||||
*/
|
||||
|
|
@ -10271,6 +10285,7 @@ export interface NpcDialoguesSelect<T extends boolean = true> {
|
|||
name?: T;
|
||||
npc?: T;
|
||||
priority?: T;
|
||||
testing?: T;
|
||||
entryGate?:
|
||||
| T
|
||||
| {
|
||||
|
|
@ -10479,6 +10494,12 @@ export interface UsersSelect<T extends boolean = true> {
|
|||
showBackgroundTexture?: T;
|
||||
sidebarOrder?: T;
|
||||
};
|
||||
dialogue?:
|
||||
| T
|
||||
| {
|
||||
typewriter?: T;
|
||||
voice?: T;
|
||||
};
|
||||
discord?:
|
||||
| T
|
||||
| {
|
||||
|
|
@ -14276,6 +14297,12 @@ export interface NpcDialogueSetting {
|
|||
* House conventions appended after the voice, for every conversation including ones with their own voice. Keep it short and concrete, e.g. how the unit refers to itself or which slang is banned.
|
||||
*/
|
||||
extraRules?: string | null;
|
||||
presentation?: {
|
||||
/**
|
||||
* The default for everyone. Players can override it in their account preferences, and a player whose device asks for reduced motion never sees the animation.
|
||||
*/
|
||||
typewriterDefault?: boolean | null;
|
||||
};
|
||||
/**
|
||||
* Incremented automatically when the voice or house rules change. Recorded on each stored draft so you can tell which prompt produced it.
|
||||
*/
|
||||
|
|
@ -14440,6 +14467,11 @@ export interface DiscordPresenceSelect<T extends boolean = true> {
|
|||
export interface NpcDialogueSettingsSelect<T extends boolean = true> {
|
||||
voice?: T;
|
||||
extraRules?: T;
|
||||
presentation?:
|
||||
| T
|
||||
| {
|
||||
typewriterDefault?: T;
|
||||
};
|
||||
revision?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { Payload } from "payload";
|
|||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveAttachments } from "@/lib/npc-dialogue/attachments";
|
||||
import { resolveAttachments, resolveVoiceClip } from "@/lib/npc-dialogue/attachments";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
|
|
@ -94,3 +94,43 @@ describe("resolveAttachments", () => {
|
|||
TIMEOUT,
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveVoiceClip", () => {
|
||||
beforeAll(async () => {
|
||||
payload = await getTestPayload();
|
||||
}, TIMEOUT);
|
||||
|
||||
it(
|
||||
"returns a playable reference for a stored clip",
|
||||
async () => {
|
||||
const id = await createMedia("b2-int-line.mp3");
|
||||
try {
|
||||
const clip = await resolveVoiceClip(payload, { mediaId: id });
|
||||
expect(clip).toMatchObject({
|
||||
url: "/api/media/file/b2-int-line.mp3",
|
||||
filename: "b2-int-line.mp3",
|
||||
});
|
||||
} finally {
|
||||
await payload.delete({ collection: "media", id, overrideAccess: true });
|
||||
}
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"stays silent rather than erroring on absent, deleted, or malformed pointers",
|
||||
async () => {
|
||||
expect(await resolveVoiceClip(payload, undefined)).toBeNull();
|
||||
|
||||
const doomed = await createMedia("b2-int-doomed.mp3");
|
||||
await payload.delete({ collection: "media", id: doomed, overrideAccess: true });
|
||||
expect(await resolveVoiceClip(payload, { mediaId: doomed })).toBeNull();
|
||||
|
||||
expect(await resolveVoiceClip(payload, { mediaId: 0 })).toBeNull();
|
||||
expect(
|
||||
await resolveVoiceClip(payload, { mediaId: "nope" as unknown as number }),
|
||||
).toBeNull();
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -157,4 +157,76 @@ describe("condition groups (and / or / nor over leaf conditions)", () => {
|
|||
expect(validation.valid).toBe(false);
|
||||
expect(validation.errors.join(" ")).toContain("needs a flag key");
|
||||
});
|
||||
|
||||
it(
|
||||
"tells an absent flag apart from one set to false, and counts a pending flag as defined",
|
||||
async () => {
|
||||
const user = await createUser(`${RUN}_defined`);
|
||||
const key = `${RUN}_reported`;
|
||||
await applyFlagEffect(payload, user, key, "set_false", 0);
|
||||
await applyFlagEffect(payload, user, `${RUN}_later`, "set_true", 0, undefined, 60);
|
||||
|
||||
const check = (k: string, op: DialogueFlagCondition["op"]) =>
|
||||
evaluateCondition(payload, user, { kind: "flag", key: k, op });
|
||||
|
||||
// A recorded false is defined; a truthiness test cannot express this.
|
||||
expect(await check(key, "is_defined")).toBe(true);
|
||||
expect(await check(key, "is_undefined")).toBe(false);
|
||||
expect(await check(key, "is_true")).toBe(false);
|
||||
expect(await check(key, "is_false")).toBe(true);
|
||||
|
||||
// Nothing recorded at all.
|
||||
expect(await check(`${RUN}_never`, "is_defined")).toBe(false);
|
||||
expect(await check(`${RUN}_never`, "is_undefined")).toBe(true);
|
||||
|
||||
// Scheduled for later: recorded, so defined, but not yet in effect.
|
||||
expect(await check(`${RUN}_later`, "is_defined")).toBe(true);
|
||||
expect(await check(`${RUN}_later`, "is_true")).toBe(false);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"falls back to the global entry once a personal flag expires",
|
||||
async () => {
|
||||
const user = await createUser(`${RUN}_expiry`);
|
||||
const key = `${RUN}_shared`;
|
||||
// Personal entry already expired; global entry still active.
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: {
|
||||
user,
|
||||
key,
|
||||
flagType: "boolean",
|
||||
boolValue: false,
|
||||
expiresAt: new Date(Date.now() - 60_000).toISOString(),
|
||||
},
|
||||
overrideAccess: true,
|
||||
});
|
||||
await applyFlagEffect(payload, null, key, "set_true", 0);
|
||||
|
||||
const leaf = (op: DialogueFlagCondition["op"]): DialogueFlagCondition => ({
|
||||
kind: "flag",
|
||||
key,
|
||||
op,
|
||||
});
|
||||
expect(await evaluateCondition(payload, user, leaf("is_true"))).toBe(true);
|
||||
expect(await evaluateCondition(payload, user, leaf("is_defined"))).toBe(true);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it("summarises defined checks without a stray amount", () => {
|
||||
expect(
|
||||
conditionSummary({
|
||||
kind: "flag",
|
||||
key: "met_informant",
|
||||
op: "is_defined",
|
||||
amount: 3,
|
||||
}),
|
||||
).toBe('"met_informant" is defined');
|
||||
expect(
|
||||
conditionSummary({ kind: "flag", key: "met_informant", op: "is_undefined" }),
|
||||
).toBe('"met_informant" is undefined');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
29
tests/int/npc-dialogue-presentation.int.spec.ts
Normal file
29
tests/int/npc-dialogue-presentation.int.spec.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { normalizeTypewriterPreference, resolveTypewriter } from "@/lib/npc-dialogue/presentation";
|
||||
|
||||
describe("typewriter preference resolution", () => {
|
||||
it("follows the unit default unless the player chose otherwise", () => {
|
||||
for (const preference of [undefined, null, "default", "nonsense"]) {
|
||||
expect(resolveTypewriter(preference, true)).toBe(true);
|
||||
expect(resolveTypewriter(preference, false)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("lets the player override the unit default in both directions", () => {
|
||||
// Someone who dislikes the animation can turn it off even when it is on by
|
||||
// default, and someone who wants it keeps it when the unit turns it off.
|
||||
expect(resolveTypewriter("off", true)).toBe(false);
|
||||
expect(resolveTypewriter("on", false)).toBe(true);
|
||||
expect(resolveTypewriter("on", true)).toBe(true);
|
||||
expect(resolveTypewriter("off", false)).toBe(false);
|
||||
});
|
||||
|
||||
it("coerces stored values to a known preference", () => {
|
||||
expect(normalizeTypewriterPreference("on")).toBe("on");
|
||||
expect(normalizeTypewriterPreference("off")).toBe("off");
|
||||
expect(normalizeTypewriterPreference("default")).toBe("default");
|
||||
expect(normalizeTypewriterPreference(undefined)).toBe("default");
|
||||
expect(normalizeTypewriterPreference("yes")).toBe("default");
|
||||
});
|
||||
});
|
||||
62
tests/int/npc-dialogue-reveal.int.spec.ts
Normal file
62
tests/int/npc-dialogue-reveal.int.spec.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
// @vitest-environment node
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DialogueText, visibleLength } from "@/lib/npc-dialogue/DialogueText";
|
||||
|
||||
/**
|
||||
* The reveal is what makes a conversation line type itself out. It must never
|
||||
* expose markup, so the source is parsed in full and only the rendered strings
|
||||
* are truncated: a half-typed line shows `{amber}the tra` as plain text, not
|
||||
* `{amb`.
|
||||
*/
|
||||
function render(text: string, reveal?: number): string {
|
||||
return renderToStaticMarkup(React.createElement(DialogueText, { text, reveal }));
|
||||
}
|
||||
|
||||
/** Rendered text content (the test inputs carry no entities or attributes). */
|
||||
function textOf(html: string): string {
|
||||
return html.replace(/<[^>]*>/g, "");
|
||||
}
|
||||
|
||||
describe("DialogueText reveal", () => {
|
||||
it("counts visible characters only, ignoring markup", () => {
|
||||
expect(visibleLength("Careful, **{amber}the trail{/}** is watched.")).toBe(
|
||||
"Careful, the trail is watched.".length,
|
||||
);
|
||||
expect(visibleLength("")).toBe(0);
|
||||
// An inline image and a countdown are each one visible unit.
|
||||
expect(visibleLength("Wait {cd|done} now")).toBe("Wait now".length + 1);
|
||||
expect(visibleLength("Look  here")).toBe("Look here".length + 1);
|
||||
});
|
||||
|
||||
it("reveals a prefix of the visible text at every step, never raw markup", () => {
|
||||
const source = "Careful, **{amber}the trail{/}** is watched.";
|
||||
const visible = "Careful, the trail is watched.";
|
||||
|
||||
for (let reveal = 0; reveal <= visible.length; reveal += 1) {
|
||||
const shown = textOf(render(source, reveal));
|
||||
expect(shown).toBe(visible.slice(0, reveal));
|
||||
expect(shown).not.toContain("{");
|
||||
expect(shown).not.toContain("*");
|
||||
}
|
||||
|
||||
// Past the end the whole line renders, styled, with nothing lost.
|
||||
const full = render(source, visible.length + 10);
|
||||
expect(textOf(full)).toBe(visible);
|
||||
expect(full).toContain("<strong");
|
||||
expect(full).toContain("text-amber-400");
|
||||
});
|
||||
|
||||
it("holds back components until the reveal reaches them", () => {
|
||||
const source = "Wait {cd|done} now";
|
||||
expect(render(source, 5)).not.toContain("ready");
|
||||
expect(render(source, 6)).toContain("ready");
|
||||
});
|
||||
|
||||
it("renders everything when no reveal is given", () => {
|
||||
expect(textOf(render("Plain **line**"))).toBe("Plain line");
|
||||
});
|
||||
});
|
||||
|
|
@ -20,7 +20,11 @@ beforeAll(async () => {
|
|||
payload = await getTestPayload();
|
||||
});
|
||||
|
||||
const update = (data: { voice?: string | null; extraRules?: string | null }) =>
|
||||
const update = (data: {
|
||||
voice?: string | null;
|
||||
extraRules?: string | null;
|
||||
presentation?: { typewriterDefault?: boolean | null };
|
||||
}) =>
|
||||
payload.updateGlobal({
|
||||
slug: "npc-dialogue-settings",
|
||||
data,
|
||||
|
|
@ -100,6 +104,27 @@ describe("npc-dialogue-settings global", () => {
|
|||
logger: { warn: () => undefined },
|
||||
} as unknown as Payload);
|
||||
|
||||
expect(settings).toEqual({ voice: null, extraRules: null, revision: null });
|
||||
expect(settings).toEqual({
|
||||
voice: null,
|
||||
extraRules: null,
|
||||
revision: null,
|
||||
typewriterDefault: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("carries the typewriter default without disturbing the prompt revision", async () => {
|
||||
const voice = unique("Unchanged by presentation.");
|
||||
const before = await update({ voice, presentation: { typewriterDefault: true } });
|
||||
const revision = before.revision;
|
||||
|
||||
// Turning the animation off is not a prompt change: stored drafts must not
|
||||
// look like they came from different instructions.
|
||||
const off = await update({ presentation: { typewriterDefault: false } });
|
||||
expect(off.revision).toBe(revision);
|
||||
expect((await loadDialogueSettings(payload)).typewriterDefault).toBe(false);
|
||||
|
||||
const on = await update({ presentation: { typewriterDefault: true } });
|
||||
expect(on.revision).toBe(revision);
|
||||
expect((await loadDialogueSettings(payload)).typewriterDefault).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
210
tests/int/npc-dialogue-visibility.int.spec.ts
Normal file
210
tests/int/npc-dialogue-visibility.int.spec.ts
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
import { getTestPayload } from "../helpers/get-test-payload";
|
||||
import { Payload } from "payload";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import type { Role, User } from "@/payload-types";
|
||||
import {
|
||||
canSeeTestingDialogues,
|
||||
dialogueVisibleTo,
|
||||
loadPlayerDialogue,
|
||||
} from "@/lib/npc-dialogue/visibility";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const RUN = `vis-${Date.now().toString(36)}`;
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
const FLOW = { nodes: [], edges: [] };
|
||||
|
||||
describe("dialogue visibility (testing flag)", () => {
|
||||
const roleIds: number[] = [];
|
||||
const userIds: number[] = [];
|
||||
const dialogueIds: number[] = [];
|
||||
let npcId: number;
|
||||
let otherNpcId: number;
|
||||
let superUser: User;
|
||||
let plainUser: User;
|
||||
let testingId: number;
|
||||
let liveId: number;
|
||||
|
||||
const makeRole = async (label: string, isSuperuser = false): Promise<Role> =>
|
||||
(await payload.create({
|
||||
collection: "roles",
|
||||
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, isSuperuser },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as Role;
|
||||
|
||||
const makeUser = async (label: string, roleId: number): Promise<User> => {
|
||||
const user = (await payload.create({
|
||||
collection: "users",
|
||||
data: {
|
||||
username: `${RUN}-${label}`,
|
||||
discordUsername: `${RUN}-${label}`,
|
||||
displayName: label.toUpperCase(),
|
||||
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||
password: "Test123",
|
||||
roleDocs: [roleId],
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as User;
|
||||
userIds.push(user.id);
|
||||
return user;
|
||||
};
|
||||
|
||||
const makeNpc = async (label: string): Promise<number> =>
|
||||
(
|
||||
(await payload.create({
|
||||
collection: "game-npcs",
|
||||
data: { name: `${RUN}-${label}`, canMessage: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as { id: number }
|
||||
).id;
|
||||
|
||||
const makeDialogue = async (
|
||||
label: string,
|
||||
npc: number,
|
||||
data: { priority: number; testing?: boolean },
|
||||
): Promise<number> => {
|
||||
const doc = (await payload.create({
|
||||
collection: "npc-dialogues",
|
||||
data: { name: `${RUN}-${label}`, npc, flowData: FLOW, ...data },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as { id: number };
|
||||
dialogueIds.push(doc.id);
|
||||
return doc.id;
|
||||
};
|
||||
|
||||
/** The real path: the reader's tier decides what the claim may resolve. */
|
||||
const offerTo = async (user: User, npc: number, dialogueId?: number) =>
|
||||
loadPlayerDialogue(payload, {
|
||||
npcId: npc,
|
||||
userId: user.id,
|
||||
canSeeTesting: await canSeeTestingDialogues(payload, user),
|
||||
dialogueId,
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getTestPayload();
|
||||
|
||||
const superRole = await makeRole("super", true);
|
||||
roleIds.push(superRole.id);
|
||||
const plainRole = await makeRole("plain");
|
||||
roleIds.push(plainRole.id);
|
||||
|
||||
superUser = await makeUser("super", superRole.id);
|
||||
plainUser = await makeUser("plain", plainRole.id);
|
||||
|
||||
npcId = await makeNpc("npc");
|
||||
otherNpcId = await makeNpc("other");
|
||||
testingId = await makeDialogue("testing", npcId, { priority: 10, testing: true });
|
||||
liveId = await makeDialogue("live", npcId, { priority: 0 });
|
||||
}, TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
if (!payload) return;
|
||||
for (const id of dialogueIds) {
|
||||
await payload.delete({ collection: "npc-dialogues", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of [npcId, otherNpcId]) {
|
||||
if (!id) continue;
|
||||
await payload.delete({ collection: "game-npcs", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of userIds) {
|
||||
const profiles = await payload
|
||||
.find({
|
||||
collection: "profiles",
|
||||
where: { user: { equals: id } },
|
||||
limit: 5,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => null);
|
||||
for (const profile of profiles?.docs ?? []) {
|
||||
await payload
|
||||
.delete({ collection: "profiles", id: profile.id, overrideAccess: true })
|
||||
.catch(() => {});
|
||||
}
|
||||
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of roleIds) {
|
||||
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
it("treats only an explicit true as unreleased", () => {
|
||||
expect(dialogueVisibleTo({ testing: true }, false)).toBe(false);
|
||||
expect(dialogueVisibleTo({ testing: false }, false)).toBe(true);
|
||||
expect(dialogueVisibleTo({}, false)).toBe(true);
|
||||
// Rows written before the flag existed read back as null, not false.
|
||||
expect(dialogueVisibleTo({ testing: null }, false)).toBe(true);
|
||||
expect(dialogueVisibleTo({ testing: true }, true)).toBe(true);
|
||||
});
|
||||
|
||||
it(
|
||||
"reserves the superuser tier, not every author",
|
||||
async () => {
|
||||
expect(await canSeeTestingDialogues(payload, superUser)).toBe(true);
|
||||
expect(await canSeeTestingDialogues(payload, plainUser)).toBe(false);
|
||||
expect(await canSeeTestingDialogues(payload, null)).toBe(false);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"offers a player the live conversation even when a testing one outranks it",
|
||||
async () => {
|
||||
const offered = await loadPlayerDialogue(payload, {
|
||||
npcId,
|
||||
userId: plainUser.id,
|
||||
canSeeTesting: await canSeeTestingDialogues(payload, plainUser),
|
||||
});
|
||||
expect(offered?.id).toBe(liveId);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"offers a superuser the testing conversation",
|
||||
async () => {
|
||||
const offered = await loadPlayerDialogue(payload, {
|
||||
npcId,
|
||||
userId: superUser.id,
|
||||
canSeeTesting: await canSeeTestingDialogues(payload, superUser),
|
||||
});
|
||||
expect(offered?.id).toBe(testingId);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"refuses a testing conversation named by a player, and allows a superuser",
|
||||
async () => {
|
||||
expect(await offerTo(plainUser, npcId, testingId)).toBeNull();
|
||||
expect((await offerTo(superUser, npcId, testingId))?.id).toBe(testingId);
|
||||
// A live conversation is still readable by its id for anyone.
|
||||
expect((await offerTo(plainUser, npcId, liveId))?.id).toBe(liveId);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"rejects a conversation that belongs to another NPC",
|
||||
async () => {
|
||||
expect(await offerTo(superUser, otherNpcId, testingId)).toBeNull();
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"rejects a conversation id that does not exist",
|
||||
async () => {
|
||||
expect(await offerTo(superUser, npcId, 2_000_000_000)).toBeNull();
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
});
|
||||
|
|
@ -43,6 +43,8 @@ describe("PreferencesForm", () => {
|
|||
discordEnabled: false,
|
||||
discordMutedTypes: [],
|
||||
xpDisplayMini: false,
|
||||
conversationTypewriter: "default",
|
||||
conversationVoice: true,
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
@ -50,6 +52,8 @@ describe("PreferencesForm", () => {
|
|||
fireEvent.click(screen.getByRole("switch", { name: "Use mini mode for XP display" }));
|
||||
fireEvent.click(screen.getByRole("switch", { name: "Mute all in-app notifications" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Actual" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Show instantly" }));
|
||||
fireEvent.click(screen.getByRole("switch", { name: "Play voice clips in conversations" }));
|
||||
fireEvent.click(screen.getByRole("switch", { name: "Enable Discord notifications" }));
|
||||
const discordMarketOffer = document.getElementById("discord-market-offer");
|
||||
if (!(discordMarketOffer instanceof HTMLElement)) {
|
||||
|
|
@ -69,6 +73,8 @@ describe("PreferencesForm", () => {
|
|||
discordEnabled: true,
|
||||
discordMutedTypes: ["market:offer"],
|
||||
xpDisplayMini: true,
|
||||
conversationTypewriter: "off",
|
||||
conversationVoice: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue