Compare commits
11 commits
4ce82a1f87
...
5032956da7
| Author | SHA1 | Date | |
|---|---|---|---|
| 5032956da7 | |||
| e596c5c9c4 | |||
| de765fe725 | |||
| 4dc82c0d5d | |||
| 4bfa34a775 | |||
| b71e94b23d | |||
| 6db4ecc3a7 | |||
| ccbbeaaa99 | |||
| cde1e2f5d1 | |||
| 464ba2d5d4 | |||
| 441c0dbac3 |
35 changed files with 49521 additions and 90 deletions
19
CHANGELOG.md
19
CHANGELOG.md
|
|
@ -1,5 +1,24 @@
|
|||
# Changelog
|
||||
|
||||
# v0.19.0
|
||||
|
||||
Conversations read and type at the pace of a person speaking, and the contacts list shows who has something new to say.
|
||||
|
||||
### Features
|
||||
|
||||
- **Voiced replies start on time.** A line's recording now loads while the previous line is still playing, so the voice begins when the text does rather than after a download. Every voiced line also carries a Replay control and a thin progress line while it plays.
|
||||
- **A typing rhythm closer to speech.** Lines pause at commas and hold a little longer after a full stop or a paragraph break. A soft tick accompanies text that has no recording, the contact shows a brief typing beat before answering, and a click skips either one. Both the typing and the tick can be switched off in your account preferences.
|
||||
- **Ask by number.** Press 1 through 9 to take a reply, press Enter to finish a line that is still typing, and press Escape to leave. Screen readers announce each line in full as it arrives.
|
||||
- **New conversations on Contacts.** A contact who offers a conversation you have never read is marked New in the contacts list.
|
||||
|
||||
### Fixes
|
||||
|
||||
- The conversation window no longer jumps when its choices appear: the menu slides in and the lines above it settle.
|
||||
- The conversation log follows new lines to the end, and stops following while you scroll back to re-read something.
|
||||
- Various bug fixes and improvements.
|
||||
|
||||
---
|
||||
|
||||
# v0.18.0
|
||||
|
||||
Conversations can be spoken aloud and type themselves out, and you decide whether either happens.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "polaris-task-force",
|
||||
"version": "0.18.0",
|
||||
"version": "0.19.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",
|
||||
|
|
|
|||
|
|
@ -211,6 +211,7 @@ export async function updatePreferences(input: {
|
|||
discordMutedTypes: string[];
|
||||
xpDisplayMini: boolean;
|
||||
conversationTypewriter: "default" | "on" | "off";
|
||||
conversationTypewriterSound: boolean;
|
||||
conversationVoice: boolean;
|
||||
}): Promise<ActionResult> {
|
||||
try {
|
||||
|
|
@ -250,6 +251,7 @@ export async function updatePreferences(input: {
|
|||
},
|
||||
dialogue: {
|
||||
typewriter: input.conversationTypewriter,
|
||||
typewriterSound: input.conversationTypewriterSound,
|
||||
voice: input.conversationVoice,
|
||||
},
|
||||
discord: {
|
||||
|
|
|
|||
|
|
@ -182,6 +182,9 @@ export default async function AccountPage() {
|
|||
showCallsign={fullUser.preferences?.display?.showCallsign ?? false}
|
||||
showVersionOverlay={fullUser.preferences?.display?.showVersionOverlay ?? true}
|
||||
conversationTypewriter={fullUser.preferences?.dialogue?.typewriter ?? "default"}
|
||||
conversationTypewriterSound={
|
||||
fullUser.preferences?.dialogue?.typewriterSound !== false
|
||||
}
|
||||
conversationVoice={fullUser.preferences?.dialogue?.voice !== false}
|
||||
showBackgroundTexture={fullUser.preferences?.display?.showBackgroundTexture ?? true}
|
||||
leadOrActual={fullUser.preferences?.display?.leadOrActual ?? "lead"}
|
||||
|
|
|
|||
|
|
@ -188,6 +188,11 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
const voiceEnabled = dialogue
|
||||
? (isPayloadUser(user) ? user.preferences?.dialogue?.voice : undefined) !== false
|
||||
: false;
|
||||
// The typing sound has its own switch; it is silent anyway on lines that carry
|
||||
// a recorded clip, so the two preferences do not have to agree.
|
||||
const typewriterSoundEnabled = dialogue
|
||||
? (isPayloadUser(user) ? user.preferences?.dialogue?.typewriterSound : undefined) !== false
|
||||
: false;
|
||||
|
||||
return (
|
||||
<div className="p-5 flex flex-col gap-6">
|
||||
|
|
@ -200,6 +205,7 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
dialogue={dialogue}
|
||||
initialSeenNodeIds={seenNodeIds}
|
||||
typewriter={typewriterEnabled}
|
||||
typewriterSound={typewriterSoundEnabled}
|
||||
voice={voiceEnabled}
|
||||
/>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import { headers as nextHeaders } from "next/headers";
|
|||
import type { GameNpc } from "@/payload-types";
|
||||
import { UsersIcon } from "lucide-react";
|
||||
import { NpcDirectory } from "@/components/frontend/personnel/NpcDirectory";
|
||||
import { loadUnreadNpcIds } from "@/lib/npc-dialogue/unread";
|
||||
import { canSeeTestingDialogues } from "@/lib/npc-dialogue/visibility";
|
||||
import { ClassificationStrip, CornerBrackets, DOSSIER } from "@/components/frontend/operations";
|
||||
|
||||
export const metadata = {
|
||||
|
|
@ -24,6 +26,18 @@ export default async function ContactsPage() {
|
|||
});
|
||||
const npcs = npcsRes.docs as unknown as GameNpc[];
|
||||
|
||||
// Which contacts have conversation content this player has never opened. Two
|
||||
// queries for the whole page, not one per card, and the same gates the offer
|
||||
// uses: `canMessage` first, because a contact that cannot start a
|
||||
// conversation should not advertise one, then the entry gate and testing
|
||||
// flag inside the loader.
|
||||
const canSeeTesting = await canSeeTestingDialogues(payload, user);
|
||||
const unreadNpcIds = await loadUnreadNpcIds(payload, {
|
||||
npcIds: npcs.filter((npc) => npc.canMessage === true).map((npc) => npc.id),
|
||||
userId: user?.id ?? null,
|
||||
canSeeTesting,
|
||||
}).catch(() => []);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 p-5">
|
||||
<header className="group relative overflow-hidden rounded-none border border-border/70 bg-card">
|
||||
|
|
@ -49,7 +63,7 @@ export default async function ContactsPage() {
|
|||
</div>
|
||||
</header>
|
||||
|
||||
<NpcDirectory npcs={npcs} />
|
||||
<NpcDirectory npcs={npcs} unreadNpcIds={unreadNpcIds} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ export const AiConnections: CollectionConfig = {
|
|||
slug: "ai-connections",
|
||||
labels: { singular: "AI Connection", plural: "AI Connections" },
|
||||
admin: {
|
||||
group: "Server",
|
||||
group: "AI",
|
||||
useAsTitle: "label",
|
||||
defaultColumns: ["label", "modelId", "structuredMode", "hasApiKey", "lastTestOk"],
|
||||
description:
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ export const AiSettings: GlobalConfig = {
|
|||
slug: "ai-settings",
|
||||
label: "AI Settings",
|
||||
admin: {
|
||||
group: "Server",
|
||||
group: "AI",
|
||||
description:
|
||||
"Which model connection each AI surface uses. Leave a selector blank to use the Unsloth env defaults.",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -342,6 +342,16 @@ export const Users: CollectionConfig = {
|
|||
"NPC dialogue lines type out letter by letter. Click a line to finish it immediately. Reduced-motion devices always show lines instantly.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "typewriterSound",
|
||||
label: "Typing sound in conversations",
|
||||
type: "checkbox",
|
||||
defaultValue: true,
|
||||
admin: {
|
||||
description:
|
||||
"A soft key tick under lines that type out. Silent on lines with a recorded voice, and muted by the speaker button in a conversation header.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "voice",
|
||||
label: "Play voice clips in conversations",
|
||||
|
|
|
|||
363
src/components/admin/npc-dialogue/DialoguePreviewDialog.tsx
Normal file
363
src/components/admin/npc-dialogue/DialoguePreviewDialog.tsx
Normal file
|
|
@ -0,0 +1,363 @@
|
|||
"use client";
|
||||
|
||||
/**
|
||||
* Walk an unsaved conversation draft in the editor.
|
||||
*
|
||||
* The player runtime reads the stored document, so a draft on the canvas cannot
|
||||
* be played there: you have to save, leave the admin, and find the contact. This
|
||||
* replays the graph as it stands right now, with real flag values from the
|
||||
* server (`previewDialogueCondition`), and dry-runs effects instead of writing
|
||||
* them.
|
||||
*
|
||||
* Deliberately not the runtime component: it resolves text and choices through
|
||||
* server actions keyed on a saved dialogue id, and reusing it here would mean
|
||||
* teaching four actions a draft mode. A small walker shows the same branch
|
||||
* decisions, which is what an author is actually checking.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { PlayIcon, RotateCcwIcon, XIcon } from "lucide-react";
|
||||
|
||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||
import type { DialogueCondition, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
|
||||
import {
|
||||
automaticTarget,
|
||||
describeCondition,
|
||||
isTerminal,
|
||||
nodeForTarget,
|
||||
previewStep,
|
||||
} from "@/lib/npc-dialogue/preview";
|
||||
import { previewDialogueCondition } from "./previewActions";
|
||||
|
||||
const NODE_LABEL: Record<string, string> = {
|
||||
dialogue: "Dialogue",
|
||||
choice: "Choice",
|
||||
condition: "Condition",
|
||||
event: "Event",
|
||||
delay: "Delay",
|
||||
end: "End",
|
||||
};
|
||||
|
||||
interface DialoguePreviewDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
flow: FlowData;
|
||||
contactName: string;
|
||||
}
|
||||
|
||||
export function DialoguePreviewDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
flow,
|
||||
contactName,
|
||||
}: DialoguePreviewDialogProps) {
|
||||
const start = useMemo(() => findStartNode(flow.nodes as DialogueNode[]), [flow.nodes]);
|
||||
const [currentId, setCurrentId] = useState<string | null>(start?.id ?? null);
|
||||
const [visited, setVisited] = useState<string[]>([]);
|
||||
/** Every hop taken, including revisits, so the footer counts what happened
|
||||
* rather than how many distinct cards it saw. */
|
||||
const [steps, setSteps] = useState(0);
|
||||
/** Gate answers for condition nodes, keyed by node id, so a step is not
|
||||
* re-evaluated on every render. */
|
||||
const [gates, setGates] = useState<Record<string, boolean>>({});
|
||||
const [gateErrors, setGateErrors] = useState<string | null>(null);
|
||||
const [checking, setChecking] = useState(false);
|
||||
/** Gate answers for conditional choices, keyed `<nodeId>:<index>`, so the
|
||||
* preview disables a choice the runtime would hide. */
|
||||
const [choiceGates, setChoiceGates] = useState<Record<string, boolean>>({});
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setCurrentId(findStartNode(flow.nodes as DialogueNode[])?.id ?? null);
|
||||
setVisited([]);
|
||||
setSteps(0);
|
||||
setGates({});
|
||||
setGateErrors(null);
|
||||
}, [flow.nodes]);
|
||||
|
||||
// Reopening starts a fresh walk rather than resuming wherever it stopped.
|
||||
useEffect(() => {
|
||||
if (open) reset();
|
||||
}, [open, reset]);
|
||||
|
||||
const node = currentId ? nodeForTarget(flow.nodes as DialogueNode[], currentId) : null;
|
||||
const nodeChoices = node?.data.choices ?? [];
|
||||
|
||||
// A condition node has no body: ask the server, then continue on its branch.
|
||||
useEffect(() => {
|
||||
if (!open || !node || node.type !== "condition") return;
|
||||
const condition = node.data.condition as DialogueCondition | undefined;
|
||||
if (!condition) {
|
||||
setGateErrors("This condition node has no condition set.");
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
setChecking(true);
|
||||
void previewDialogueCondition(condition)
|
||||
.then((result) => {
|
||||
if (cancelled) return;
|
||||
if (!result.success || typeof result.data !== "boolean") {
|
||||
setGateErrors(result.error ?? "Could not evaluate this condition.");
|
||||
return;
|
||||
}
|
||||
setGateErrors(null);
|
||||
setGates((current) => ({ ...current, [node.id]: result.data as boolean }));
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setChecking(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, node]);
|
||||
|
||||
// Conditional choices: ask once per node which of them pass for this author.
|
||||
useEffect(() => {
|
||||
if (!open || !node || node.type !== "choice") return;
|
||||
const gated = nodeChoices
|
||||
.map((choice, index) => ({ choice, index }))
|
||||
.filter((entry) => entry.choice.condition);
|
||||
if (gated.length === 0) return;
|
||||
let cancelled = false;
|
||||
void Promise.all(
|
||||
gated.map(async ({ choice, index }) => {
|
||||
const result = await previewDialogueCondition(choice.condition as DialogueCondition);
|
||||
return { index, passed: result.success ? Boolean(result.data) : true };
|
||||
}),
|
||||
).then((answers) => {
|
||||
if (cancelled) return;
|
||||
setChoiceGates((current) => {
|
||||
const next = { ...current };
|
||||
for (const answer of answers) {
|
||||
next[`${node.id}:${answer.index}`] = answer.passed;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// nodeChoices is derived from node, so node identity is enough.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, node]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const step = node ? previewStep(node) : null;
|
||||
const gateAnswer = node && node.id in gates ? gates[node.id] : null;
|
||||
const auto = node ? automaticTarget(node, gateAnswer) : { target: null, waitingOnGate: false };
|
||||
|
||||
const go = (target: string | null) => {
|
||||
if (!target) return;
|
||||
setVisited((current) => (current.includes(target) ? current : [...current, target]));
|
||||
setSteps((current) => current + 1);
|
||||
setCurrentId(target);
|
||||
};
|
||||
|
||||
/** A `once` choice is spent if its target was already visited this run, which
|
||||
* is the closest the preview can get to the runtime's per-player bookkeeping.
|
||||
* A gated choice is unavailable when the author's own flags fail its gate. */
|
||||
const choiceAvailable = (index: number) => {
|
||||
const choice = node?.data.choices?.[index];
|
||||
if (!choice) return false;
|
||||
if (choice.once === true && choice.target && visited.includes(choice.target)) return false;
|
||||
if (!choice.condition) return true;
|
||||
const answer = node ? choiceGates[`${node.id}:${index}`] : undefined;
|
||||
// Not answered yet: keep it clickable rather than flashing disabled.
|
||||
return answer === undefined ? true : answer;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[60] flex items-start justify-center bg-black/70 p-6">
|
||||
<div className="flex max-h-[80vh] w-full max-w-xl flex-col overflow-hidden rounded-md border border-white/20 bg-zinc-900 text-white shadow-2xl">
|
||||
<div className="flex items-center gap-2 border-b border-white/10 px-4 py-2">
|
||||
<PlayIcon className="size-3.5 text-cyan-300" />
|
||||
<span className="font-mono text-[10px] uppercase tracking-widest text-white/70">
|
||||
Draft preview
|
||||
</span>
|
||||
<span className="truncate text-xs text-white/40">{contactName || "unassigned contact"}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={reset}
|
||||
className="ml-auto inline-flex cursor-pointer items-center gap-1 rounded-sm border border-white/15 bg-transparent px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-white/60 hover:border-cyan-500/60 hover:text-cyan-200"
|
||||
>
|
||||
<RotateCcwIcon className="size-2.5" /> Restart
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpenChange(false)}
|
||||
aria-label="Close preview"
|
||||
className="cursor-pointer bg-transparent text-white/40 hover:text-white"
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-3">
|
||||
{!start && (
|
||||
<p className="text-sm text-amber-200">
|
||||
This draft has no start node. Mark one as the start, or draw a node nothing points at.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{start && !node && (
|
||||
<p className="text-sm text-amber-200">
|
||||
The start node points at a card that no longer exists.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{step && node && (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-2 font-mono text-[9px] uppercase tracking-widest text-white/40">
|
||||
<span className="rounded-sm border border-white/15 px-1 py-0.5">
|
||||
{NODE_LABEL[node.type] ?? node.type}
|
||||
</span>
|
||||
<span className="truncate">{node.id}</span>
|
||||
{node.data.presentation === "narration" && <span>narration</span>}
|
||||
</div>
|
||||
|
||||
{step.speaker && (
|
||||
<span className="font-mono text-[9px] uppercase tracking-widest text-white/50">
|
||||
{step.speaker}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{step.text ? (
|
||||
<p className="whitespace-pre-wrap text-sm leading-relaxed text-white/90">
|
||||
<DialogueText text={step.text} />
|
||||
</p>
|
||||
) : (
|
||||
node.type !== "condition" && (
|
||||
<p className="text-sm italic text-white/35">Empty line.</p>
|
||||
)
|
||||
)}
|
||||
|
||||
{step.effectLines.length > 0 && (
|
||||
<ul className="flex flex-col gap-1 rounded-sm border border-amber-900/50 bg-amber-950/30 px-2 py-1.5">
|
||||
{step.effectLines.map((line) => (
|
||||
<li key={line} className="font-mono text-[10px] leading-snug text-amber-200/90">
|
||||
{line}
|
||||
</li>
|
||||
))}
|
||||
<li className="font-mono text-[9px] uppercase tracking-wider text-amber-200/50">
|
||||
Dry run, nothing written
|
||||
</li>
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{node.type === "condition" && (
|
||||
<div className="rounded-sm border border-white/15 bg-black/30 px-2 py-1.5 font-mono text-[10px] leading-snug text-white/70">
|
||||
<div>if {describeCondition(node.data.condition) ?? "(no condition)"}</div>
|
||||
{checking && <div className="text-cyan-300">checking...</div>}
|
||||
{gateErrors && <div className="text-red-300">{gateErrors}</div>}
|
||||
{gateAnswer !== null && (
|
||||
<div className="text-cyan-300">
|
||||
{gateAnswer ? "true" : "false"} for you, so this draft continues{" "}
|
||||
{gateAnswer ? "true" : "false"}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{node.type === "choice" && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{step.choices.length === 0 && (
|
||||
<p className="text-xs text-amber-200">This choice node has no choices yet.</p>
|
||||
)}
|
||||
{step.choices.map((choice) => {
|
||||
const available = choiceAvailable(choice.index);
|
||||
return (
|
||||
<button
|
||||
key={choice.index}
|
||||
type="button"
|
||||
disabled={!choice.target || !available}
|
||||
onClick={() => go(choice.target)}
|
||||
className={`w-full cursor-pointer rounded-sm border px-2.5 py-1.5 text-left text-sm transition-colors disabled:cursor-not-allowed ${
|
||||
choice.target && available
|
||||
? "border-white/20 bg-black/40 text-white/85 hover:border-cyan-500/60 hover:text-white"
|
||||
: "border-white/10 bg-black/20 text-white/35"
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="font-mono text-[9px] text-white/40">{choice.index + 1}</span>
|
||||
<DialogueText text={choice.label} />
|
||||
</span>
|
||||
{choice.conditionNote && (
|
||||
<span className="mt-0.5 block font-mono text-[9px] text-amber-200/70">
|
||||
gate: {choice.conditionNote}
|
||||
{node && choiceGates[`${node.id}:${choice.index}`] === false
|
||||
? " (hidden for you)"
|
||||
: ""}
|
||||
</span>
|
||||
)}
|
||||
{!choice.target && (
|
||||
<span className="mt-0.5 block font-mono text-[9px] text-red-300/80">
|
||||
not wired
|
||||
</span>
|
||||
)}
|
||||
{choice.once && (
|
||||
<span className="mt-0.5 block font-mono text-[9px] text-white/35">
|
||||
once per player
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{node.type === "condition" && gateAnswer !== null && auto.target && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => go(auto.target)}
|
||||
className="w-fit cursor-pointer rounded-sm border border-white/20 bg-black/40 px-2.5 py-1 text-xs text-white/80 transition-colors hover:border-cyan-500/60 hover:text-white"
|
||||
>
|
||||
Continue down the {gateAnswer ? "true" : "false"} branch
|
||||
</button>
|
||||
)}
|
||||
|
||||
{node.type !== "choice" && node.type !== "condition" && !isTerminal(node) && (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => go(auto.target)}
|
||||
disabled={!auto.target}
|
||||
className="cursor-pointer rounded-sm border border-white/20 bg-black/40 px-2.5 py-1 text-xs text-white/80 transition-colors hover:border-cyan-500/60 hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
Continue
|
||||
</button>
|
||||
{!auto.target && (
|
||||
<span className="font-mono text-[9px] uppercase tracking-wider text-amber-200/70">
|
||||
this node goes nowhere
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isTerminal(node) && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-[9px] uppercase tracking-widest text-white/40">
|
||||
conversation ends
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={reset}
|
||||
className="cursor-pointer rounded-sm border border-white/20 bg-black/40 px-2.5 py-1 text-xs text-white/80 hover:border-cyan-500/60 hover:text-white"
|
||||
>
|
||||
Play again
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-white/10 px-4 py-2 font-mono text-[9px] uppercase tracking-widest text-white/35">
|
||||
{steps} step{steps === 1 ? "" : "s"} walked, {visited.length} card
|
||||
{visited.length === 1 ? "" : "s"} visited. Text shows tokens as
|
||||
authored; the player sees them resolved.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -22,7 +22,7 @@ import {
|
|||
type XYPosition,
|
||||
} from "@xyflow/react";
|
||||
import "@xyflow/react/dist/style.css";
|
||||
import { Magnet, Maximize2, Minimize2, Sparkles } from "lucide-react";
|
||||
import { Magnet, Maximize2, Minimize2, Play, Sparkles } from "lucide-react";
|
||||
|
||||
import { useDocumentInfo, useField } from "@payloadcms/ui";
|
||||
import type { NpcDialogue } from "@/payload-types";
|
||||
|
|
@ -50,6 +50,7 @@ import {
|
|||
import type { RouteRect } from "@/lib/flow-edge-routing";
|
||||
import { NpcDialogueNode } from "./NpcDialogueNode";
|
||||
import { NodeEditDialog } from "./NodeEditDialog";import { GenerateDraftDialog } from "./GenerateDraftDialog";
|
||||
import { DialoguePreviewDialog } from "./DialoguePreviewDialog";
|
||||
import type { AttachTarget, DraftPlacementChoice } from "./GenerateDraftDialog";
|
||||
import { RoutedFlowEdge } from "./RoutedFlowEdge";
|
||||
|
||||
|
|
@ -118,6 +119,9 @@ function FlowEditor() {
|
|||
const [snap, setSnap] = useState(true);
|
||||
const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null);
|
||||
const [generateOpen, setGenerateOpen] = useState(false);
|
||||
// Walks the unsaved canvas as it stands, so an author can test a branch
|
||||
// without saving and leaving the admin.
|
||||
const [previewOpen, setPreviewOpen] = useState(false);
|
||||
// Set after a draft lands, cleared when the author dismisses it. Purely a
|
||||
// reminder: the document's own modified state is what actually guards saving.
|
||||
const [draftNotice, setDraftNotice] = useState<string | null>(null);
|
||||
|
|
@ -154,6 +158,15 @@ function FlowEditor() {
|
|||
return null;
|
||||
}, [docData]);
|
||||
|
||||
const npcLabel = useMemo(() => {
|
||||
const raw = (docData as Record<string, unknown> | undefined)?.npc;
|
||||
if (raw && typeof raw === "object" && "name" in raw) {
|
||||
const name = (raw as { name?: unknown }).name;
|
||||
if (typeof name === "string") return name;
|
||||
}
|
||||
return npcId === null ? "" : `contact ${npcId}`;
|
||||
}, [docData, npcId]);
|
||||
|
||||
// This document's own id. New documents have none until the first save, which
|
||||
// is also when a voice override could first be stored.
|
||||
const dialogueId = useMemo(() => {
|
||||
|
|
@ -764,6 +777,21 @@ function FlowEditor() {
|
|||
{NODE_LABELS.end}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPreviewOpen(true)}
|
||||
disabled={nodes.length === 0}
|
||||
title={
|
||||
nodes.length === 0
|
||||
? "Add a node before previewing"
|
||||
: "Walk this draft without saving it"
|
||||
}
|
||||
className={`${buttonClass} inline-flex items-center gap-1 bg-emerald-950 border-emerald-700 text-emerald-200 hover:bg-emerald-900 disabled:opacity-40 disabled:cursor-not-allowed`}
|
||||
>
|
||||
<Play size={12} />
|
||||
Play
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setGenerateOpen(true)}
|
||||
|
|
@ -1037,6 +1065,13 @@ function FlowEditor() {
|
|||
dialogueId={dialogueId}
|
||||
/>
|
||||
|
||||
<DialoguePreviewDialog
|
||||
open={previewOpen}
|
||||
onOpenChange={setPreviewOpen}
|
||||
flow={{ nodes: nodes as DialogueNode[], edges: syncedEdges.map((e) => ({ id: e.id, source: e.source, target: e.target })) }}
|
||||
contactName={npcLabel}
|
||||
/>
|
||||
|
||||
<GenerateDraftDialog
|
||||
open={generateOpen}
|
||||
onOpenChange={setGenerateOpen}
|
||||
|
|
|
|||
58
src/components/admin/npc-dialogue/previewActions.ts
Normal file
58
src/components/admin/npc-dialogue/previewActions.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
"use server";
|
||||
|
||||
/**
|
||||
* Evaluation for the editor's draft preview.
|
||||
*
|
||||
* The preview walks the author's unsaved graph on the client (it has the nodes),
|
||||
* but flag values live in the database, so a condition can only be answered
|
||||
* here. Gated like authoring: previewing is reading conversation content, and
|
||||
* the caller is already editing this document.
|
||||
*
|
||||
* Nothing is written. Effects are described by the preview and never applied.
|
||||
*/
|
||||
|
||||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
|
||||
import type { DialogueCondition } from "@/lib/npc-dialogue/dialogue";
|
||||
import { evaluateCondition } from "@/lib/npc-dialogue/flags";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
|
||||
export type PreviewConditionResult = { success: boolean; error?: string; data?: boolean };
|
||||
|
||||
async function authenticate() {
|
||||
const payload = await getPayload({ config });
|
||||
const { headers } = await import("next/headers");
|
||||
const { user } = await payload.auth({ headers: await headers() });
|
||||
return { payload, user };
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a condition passes for the editing user.
|
||||
*
|
||||
* `condition` comes from a client component, so it is checked for its kind
|
||||
* before it reaches the evaluator; a malformed payload answers false rather than
|
||||
* throwing inside the flag reader.
|
||||
*/
|
||||
export async function previewDialogueCondition(
|
||||
condition: DialogueCondition,
|
||||
): Promise<PreviewConditionResult> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!user) return { success: false, error: "You must be logged in." };
|
||||
const allowed = await hasPermission(payload, user, "npc-dialogues:update");
|
||||
if (!allowed) {
|
||||
return { success: false, error: "You are not allowed to preview conversations." };
|
||||
}
|
||||
if (!condition || (condition.kind !== "flag" && condition.kind !== "group")) {
|
||||
return { success: false, error: "Unsupported condition." };
|
||||
}
|
||||
const passed = await evaluateCondition(payload, user.id as number, condition);
|
||||
return { success: true, data: passed };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -118,6 +118,7 @@ export function CommandPalette({
|
|||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: preferences?.display?.xpDisplayMini ?? false,
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
conversationTypewriterSound: preferences?.dialogue?.typewriterSound !== false,
|
||||
conversationVoice: preferences?.dialogue?.voice !== false,
|
||||
});
|
||||
if (result.success) {
|
||||
|
|
@ -140,6 +141,7 @@ export function CommandPalette({
|
|||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: preferences?.display?.xpDisplayMini ?? false,
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
conversationTypewriterSound: preferences?.dialogue?.typewriterSound !== false,
|
||||
conversationVoice: preferences?.dialogue?.voice !== false,
|
||||
});
|
||||
if (result.success) {
|
||||
|
|
@ -162,6 +164,7 @@ export function CommandPalette({
|
|||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: !(preferences?.display?.xpDisplayMini ?? false),
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
conversationTypewriterSound: preferences?.dialogue?.typewriterSound !== false,
|
||||
conversationVoice: preferences?.dialogue?.voice !== false,
|
||||
});
|
||||
if (result.success) {
|
||||
|
|
|
|||
|
|
@ -24,6 +24,8 @@ interface PreferencesFormProps {
|
|||
readonly xpDisplayMini: boolean;
|
||||
/** Stored choice for the NPC conversation typing animation. */
|
||||
readonly conversationTypewriter: "default" | "on" | "off";
|
||||
/** Whether the typing sound plays under lines that type out. */
|
||||
readonly conversationTypewriterSound: boolean;
|
||||
/** Whether recorded voice clips play in conversations. */
|
||||
readonly conversationVoice: boolean;
|
||||
}
|
||||
|
|
@ -39,6 +41,7 @@ export function PreferencesForm({
|
|||
discordMutedTypes: initialDiscordMutedTypes,
|
||||
xpDisplayMini: initialXPDisplayMini,
|
||||
conversationTypewriter: initialConversationTypewriter,
|
||||
conversationTypewriterSound: initialConversationTypewriterSound,
|
||||
conversationVoice: initialConversationVoice,
|
||||
}: PreferencesFormProps) {
|
||||
const router = useRouter();
|
||||
|
|
@ -57,6 +60,9 @@ export function PreferencesForm({
|
|||
"default" | "on" | "off"
|
||||
>(initialConversationTypewriter);
|
||||
const [conversationVoice, setConversationVoice] = useState(initialConversationVoice);
|
||||
const [conversationTypewriterSound, setConversationTypewriterSound] = useState(
|
||||
initialConversationTypewriterSound,
|
||||
);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
|
@ -91,6 +97,7 @@ export function PreferencesForm({
|
|||
discordMutedTypes,
|
||||
xpDisplayMini,
|
||||
conversationTypewriter,
|
||||
conversationTypewriterSound,
|
||||
conversationVoice,
|
||||
});
|
||||
|
||||
|
|
@ -248,6 +255,26 @@ export function PreferencesForm({
|
|||
</div>
|
||||
</RadioGroup>
|
||||
|
||||
<Label
|
||||
htmlFor="conversationTypewriterSound"
|
||||
className="flex items-center justify-between gap-4 text-sm"
|
||||
>
|
||||
<span className="flex min-w-0 flex-col gap-1">
|
||||
<span>Typing sound</span>
|
||||
<span className="text-sm font-normal text-muted-foreground">
|
||||
A soft key tick under lines that type out. Lines with a recorded voice stay
|
||||
silent, and the speaker button in a conversation header mutes it for that
|
||||
conversation.
|
||||
</span>
|
||||
</span>
|
||||
<Switch
|
||||
id="conversationTypewriterSound"
|
||||
checked={conversationTypewriterSound}
|
||||
onCheckedChange={setConversationTypewriterSound}
|
||||
aria-label="Play a typing sound in conversations"
|
||||
/>
|
||||
</Label>
|
||||
|
||||
<Label
|
||||
htmlFor="conversationVoice"
|
||||
className="mt-2 flex items-center justify-between gap-4 text-sm"
|
||||
|
|
|
|||
|
|
@ -178,6 +178,7 @@ export function AppSidebar({
|
|||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: !isMiniMode,
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
conversationTypewriterSound: preferences?.dialogue?.typewriterSound !== false,
|
||||
conversationVoice: preferences?.dialogue?.voice !== false,
|
||||
});
|
||||
setIsMiniMode(!isMiniMode);
|
||||
|
|
|
|||
|
|
@ -9,9 +9,11 @@ import { initialsOf } from "@/components/frontend/personnel/initials";
|
|||
|
||||
interface NpcCardProps {
|
||||
readonly npc: GameNpc;
|
||||
/** This contact offers conversation content the player has never read. */
|
||||
readonly unread?: boolean;
|
||||
}
|
||||
|
||||
export function NpcCard({ npc }: NpcCardProps) {
|
||||
export function NpcCard({ npc, unread = false }: NpcCardProps) {
|
||||
const factionName =
|
||||
typeof npc.faction === "object" && npc.faction !== null ? npc.faction.name : null;
|
||||
const locationName =
|
||||
|
|
@ -33,7 +35,7 @@ export function NpcCard({ npc }: NpcCardProps) {
|
|||
return (
|
||||
<Link
|
||||
href={`/personnel/contacts/${npc.id}`}
|
||||
aria-label={`Open contact ${npc.name}`}
|
||||
aria-label={`Open contact ${npc.name}${unread ? ", unread conversation" : ""}`}
|
||||
className="block rounded-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
>
|
||||
<article className="group relative flex aspect-[4/5] flex-col overflow-hidden rounded-none border border-border/70 bg-card transition-colors duration-300 hover:border-foreground/30 motion-reduce:transition-none">
|
||||
|
|
@ -41,6 +43,18 @@ export function NpcCard({ npc }: NpcCardProps) {
|
|||
<ClassificationStrip left="Contact" right={`REF ${refCode}`} />
|
||||
</div>
|
||||
|
||||
{/* New conversation content. Positioned over the portrait rather than in
|
||||
the readout footer, which is already three cells wide. */}
|
||||
{unread && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute right-2 top-10 z-30 flex items-center gap-1 rounded-sm bg-cyan-400 px-1 py-0.5 font-mono text-[8px] font-bold uppercase leading-tight tracking-widest text-black shadow-[0_0_8px_rgba(34,211,238,0.55)]"
|
||||
>
|
||||
<span className="size-1 rounded-full bg-black/70" />
|
||||
New
|
||||
</span>
|
||||
)}
|
||||
|
||||
<div className="relative min-h-0 flex-1 overflow-hidden">
|
||||
{imageUrl ? (
|
||||
<img src={imageUrl} alt="" className="absolute inset-0 size-full object-cover" />
|
||||
|
|
|
|||
|
|
@ -1,13 +1,22 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState, Fragment } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, Fragment } from "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, visibleLength } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { DialogueText, visibleLength, visibleText } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { choiceIndexFromKey, choiceShortcutLabel, isSkipKey } from "@/lib/npc-dialogue/keys";
|
||||
import {
|
||||
DEFAULT_PACING_PRESET,
|
||||
beatMs,
|
||||
buildRevealSchedule,
|
||||
scaleSchedule,
|
||||
shownAt,
|
||||
} from "@/lib/npc-dialogue/pacing";
|
||||
import { playTypeTick, primeTypeSound } from "@/lib/npc-dialogue/typeSound";
|
||||
import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments";
|
||||
import { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
|
||||
import { DOSSIER } from "@/components/frontend/operations";
|
||||
|
|
@ -41,6 +50,8 @@ interface NpcConversationProps {
|
|||
/** 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;
|
||||
/** Sound under the typing. Silent on lines that have a recorded clip. */
|
||||
readonly typewriterSound?: boolean;
|
||||
/** Play recorded voice clips. The header button mutes for the session. */
|
||||
readonly voice?: boolean;
|
||||
}
|
||||
|
|
@ -80,12 +91,9 @@ function resolveFlow(dialogue: NpcConversationProps["dialogue"]): ResolvedFlow |
|
|||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/** 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);
|
||||
}
|
||||
/** Longest a line may take, pauses included. Past this the schedule is
|
||||
* compressed: a wall of text still has to arrive while the player is looking. */
|
||||
const REVEAL_CAP_MS = 3000;
|
||||
|
||||
/** True when the device asks for reduced motion; the animation is skipped
|
||||
* entirely rather than merely shortened. */
|
||||
|
|
@ -137,6 +145,7 @@ export function NpcConversation({
|
|||
dialogue,
|
||||
initialSeenNodeIds,
|
||||
typewriter = true,
|
||||
typewriterSound = true,
|
||||
voice = true,
|
||||
}: NpcConversationProps) {
|
||||
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
|
||||
|
|
@ -151,6 +160,8 @@ export function NpcConversation({
|
|||
const [streamingId, setStreamingId] = useState<string | null>(null);
|
||||
/** Set by clicking the log: finish the line instead of waiting. */
|
||||
const skipRevealRef = useRef<string | null>(null);
|
||||
/** Set by clicking the log during the beat between lines: start the next one. */
|
||||
const skipBeatRef = useRef(false);
|
||||
/** 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);
|
||||
|
|
@ -161,6 +172,14 @@ export function NpcConversation({
|
|||
const [soundOn, setSoundOn] = useState(voice);
|
||||
const soundOnRef = useRef(soundOn);
|
||||
soundOnRef.current = soundOn;
|
||||
|
||||
/** Which line's clip is playing, and how far through it is, for the progress
|
||||
* hairline under that line. */
|
||||
const [playing, setPlaying] = useState<{ id: string; ratio: number } | null>(null);
|
||||
/** Fetched clips, keyed by their server URL, as object URLs so the next line
|
||||
* starts from memory instead of the network. Bounded, and revoked on eviction. */
|
||||
const clipCacheRef = useRef<Map<string, string>>(new Map());
|
||||
const clipPendingRef = useRef<Set<string>>(new Set());
|
||||
/** `${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
|
||||
|
|
@ -179,9 +198,65 @@ export function NpcConversation({
|
|||
const seq = useRef(0);
|
||||
const sessionRef = useRef(0);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
/** The scroller as state, not just a ref: the dialog's DOM is mounted by Radix
|
||||
* a commit after `open` flips, so an effect keyed on `open` would run before
|
||||
* the element exists and never attach its observers. */
|
||||
const [scroller, setScroller] = useState<HTMLDivElement | null>(null);
|
||||
/** The log's content block, observed so a line growing as it types keeps the
|
||||
* newest character in view. */
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
/** Stable ref callback. An inline arrow here would be a new function every
|
||||
* render, so React would detach and reattach it each time and the state write
|
||||
* would loop. */
|
||||
const attachScroller = useCallback((node: HTMLDivElement | null) => {
|
||||
scrollRef.current = node;
|
||||
setScroller((current) => (current === node ? current : node));
|
||||
}, []);
|
||||
|
||||
const nextId = () => `entry-${seq.current++}`;
|
||||
|
||||
/** The URL to hand the audio element: the in-memory copy when it has been
|
||||
* fetched, the server URL otherwise. */
|
||||
const playableUrl = (url: string) => clipCacheRef.current.get(url) ?? url;
|
||||
|
||||
/** Fetch a clip before its line arrives. Failure is silent: the line then
|
||||
* loads its clip the old way, one request later. */
|
||||
const preloadClip = (url: string | undefined) => {
|
||||
if (!url || !soundOnRef.current) return;
|
||||
if (clipCacheRef.current.has(url) || clipPendingRef.current.has(url)) return;
|
||||
clipPendingRef.current.add(url);
|
||||
void fetch(url)
|
||||
.then((res) => (res.ok ? res.blob() : null))
|
||||
.then((blob) => {
|
||||
if (!blob) return;
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const cache = clipCacheRef.current;
|
||||
cache.set(url, objectUrl);
|
||||
// Eight clips is a few hundred kB and covers the usual branch depth.
|
||||
while (cache.size > 8) {
|
||||
const [oldest, value] = [...cache.entries()][0] ?? [];
|
||||
if (!oldest) break;
|
||||
URL.revokeObjectURL(value);
|
||||
cache.delete(oldest);
|
||||
}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.finally(() => clipPendingRef.current.delete(url));
|
||||
};
|
||||
|
||||
// Release the prefetched clips when the dialog goes away. Object URLs are not
|
||||
// collected on their own, so without this every opened conversation would
|
||||
// leave a few hundred kB behind.
|
||||
useEffect(
|
||||
() => () => {
|
||||
const cache = clipCacheRef.current;
|
||||
for (const value of cache.values()) URL.revokeObjectURL(value);
|
||||
cache.clear();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Invalidate pending typing timers when the component unmounts.
|
||||
useEffect(
|
||||
() => () => {
|
||||
|
|
@ -190,12 +265,6 @@ export function NpcConversation({
|
|||
[],
|
||||
);
|
||||
|
||||
// Keep the newest line in view.
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
}, [log, typing, playerTyping, open]);
|
||||
|
||||
// The choice node the log currently rests on (if any).
|
||||
const activeChoiceNodeId = useMemo(() => {
|
||||
const last = [...log].reverse().find((entry) => entry.kind === "node");
|
||||
|
|
@ -274,14 +343,16 @@ export function NpcConversation({
|
|||
let clipSeconds = 0;
|
||||
if (voiceUrl && soundOnRef.current && audioRef.current) {
|
||||
const audio = audioRef.current;
|
||||
audio.src = voiceUrl;
|
||||
audio.src = playableUrl(voiceUrl);
|
||||
audio.currentTime = 0;
|
||||
try {
|
||||
await audio.play();
|
||||
voiceStarted = true;
|
||||
setPlaying({ id, ratio: 0 });
|
||||
clipSeconds = await clipDuration(audio);
|
||||
} catch {
|
||||
voiceStarted = false;
|
||||
setPlaying(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -292,12 +363,16 @@ export function NpcConversation({
|
|||
// 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.
|
||||
// The schedule is already a duration in milliseconds (one base cost per
|
||||
// unit plus its pauses), so a preset's pause values mean what they say. A
|
||||
// clip takes over as the target and the schedule is scaled to fit it, which
|
||||
// keeps text and speech together. Only a very long line is compressed, by
|
||||
// the cap.
|
||||
const unscaled = buildRevealSchedule(text);
|
||||
const durationMs =
|
||||
voiceStarted && clipSeconds > 0.4
|
||||
? Math.min(60_000, clipSeconds * 1000)
|
||||
: revealDurationMs(total);
|
||||
: Math.min(REVEAL_CAP_MS, unscaled.total);
|
||||
|
||||
setLog((prev) => [
|
||||
...prev,
|
||||
|
|
@ -313,6 +388,13 @@ export function NpcConversation({
|
|||
},
|
||||
]);
|
||||
markSeen(node.id);
|
||||
|
||||
// Fetch the next line's clip now, while this one is still being read.
|
||||
const nextTarget = node.data.next?.target;
|
||||
const nextNode = nextTarget ? flow?.nodes.find((candidate) => candidate.id === nextTarget) : null;
|
||||
const nextFilename = nextNode?.data.voice?.filename;
|
||||
if (nextFilename) preloadClip(`/api/media/file/${nextFilename}`);
|
||||
|
||||
if (!animate) return;
|
||||
|
||||
const setReveal = (shown: number | undefined) =>
|
||||
|
|
@ -324,16 +406,39 @@ export function NpcConversation({
|
|||
|
||||
setStreamingId(id);
|
||||
skipRevealRef.current = null;
|
||||
const msPerUnit = durationMs / total;
|
||||
|
||||
// A schedule, not a fixed tick per character: the line arrives on its own
|
||||
// timing, with a pause after punctuation and line breaks. It is built in
|
||||
// relative units and scaled here, so a recorded line keeps the rhythm and
|
||||
// only stretches. Ticks are precomputed from the same schedule (seeded, so
|
||||
// a re-render cannot re-roll the rhythm) and fire as the reveal crosses them.
|
||||
const schedule = scaleSchedule(unscaled, durationMs);
|
||||
const unitCount = Math.min(total, schedule.arrivalMs.length);
|
||||
const ticking = typewriterSound && soundOnRef.current && !voiceStarted;
|
||||
let tickIndex = 0;
|
||||
let shown = 0;
|
||||
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);
|
||||
const elapsed = performance.now() - startedAt;
|
||||
if (ticking) {
|
||||
while (
|
||||
tickIndex < schedule.tickMs.length &&
|
||||
schedule.tickMs[tickIndex] <= elapsed
|
||||
) {
|
||||
playTypeTick();
|
||||
tickIndex += 1;
|
||||
}
|
||||
}
|
||||
const next = Math.min(unitCount, shownAt(schedule.arrivalMs, elapsed));
|
||||
if (next !== shown) {
|
||||
shown = next;
|
||||
setReveal(shown);
|
||||
}
|
||||
if (shown >= unitCount) break;
|
||||
await sleep(24);
|
||||
}
|
||||
} finally {
|
||||
// Land on the full line whether it finished, was skipped, or the dialog
|
||||
|
|
@ -343,6 +448,25 @@ export function NpcConversation({
|
|||
}
|
||||
};
|
||||
|
||||
/** The beat between two lines: the speaker's typing dots, then the next line.
|
||||
* The gap is what gives the player a moment to finish reading; a click during
|
||||
* it starts the next line at once, the same way clicking a line finishes it. */
|
||||
const beatThen = async (node: DialogueNode, token: number) => {
|
||||
skipBeatRef.current = false;
|
||||
setTyping(node.data.speaker?.trim() || npc.name);
|
||||
const wait = beatMs();
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
while (performance.now() - startedAt < wait) {
|
||||
if (sessionRef.current !== token || skipBeatRef.current) break;
|
||||
await sleep(40);
|
||||
}
|
||||
} finally {
|
||||
skipBeatRef.current = false;
|
||||
if (sessionRef.current === token) setTyping(null);
|
||||
}
|
||||
};
|
||||
|
||||
// Opening the conversation walks the start node and auto-advances through
|
||||
// linear dialogue/event nodes, so the player lands on the first interactive
|
||||
// node (a choice, an end, or a dead end) without clicking Continue. Each
|
||||
|
|
@ -350,6 +474,12 @@ export function NpcConversation({
|
|||
const begin = () => {
|
||||
const token = ++sessionRef.current;
|
||||
audioRef.current?.pause();
|
||||
// Opening the conversation is a user gesture, the only moment a browser
|
||||
// will let us create and resume the audio context. Without it the typing
|
||||
// sound stays silent for the whole conversation.
|
||||
primeTypeSound();
|
||||
skipBeatRef.current = false;
|
||||
followRef.current = true;
|
||||
setLog([]);
|
||||
setTyping(null);
|
||||
setPlayerTyping(false);
|
||||
|
|
@ -413,13 +543,57 @@ export function NpcConversation({
|
|||
if (sessionRef.current !== token) return;
|
||||
}
|
||||
const target: string | undefined = current.data.next?.target;
|
||||
current = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null;
|
||||
const nextNode = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null;
|
||||
// A beat before the next spoken line. The opening line of a cascade
|
||||
// never gets one, because no hop precedes it: the player just opened
|
||||
// the conversation, or just sent a line of their own. The typing dots
|
||||
// keep the gap from reading as a hang, and a click during it skips it.
|
||||
if (
|
||||
nextNode &&
|
||||
typewriter &&
|
||||
nextNode.type === "dialogue" &&
|
||||
(nextNode.data.body ?? "").trim().length > 0 &&
|
||||
!prefersReducedMotion()
|
||||
) {
|
||||
await beatThen(nextNode, token);
|
||||
if (sessionRef.current !== token) return;
|
||||
}
|
||||
current = nextNode;
|
||||
} else {
|
||||
current = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** Digits pick a choice, Enter or Space finishes the line that is typing (or
|
||||
* starts the next one during the beat). Attached to the dialog's content, so
|
||||
* it only acts when focus is inside the conversation, and it steps aside for
|
||||
* a focused control, where the browser's own activation is correct. */
|
||||
const onConversationKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target?.closest("button, a, input, select, textarea, [role='button']")) return;
|
||||
|
||||
const choiceIndex = choiceIndexFromKey(event.key, selectableChoices.length);
|
||||
if (choiceIndex !== null) {
|
||||
const choice = selectableChoices[choiceIndex];
|
||||
if (choice) {
|
||||
event.preventDefault();
|
||||
pick(choice.hop, choice.index, choiceLabel(choice.hop, choice.index));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isSkipKey(event.key)) return;
|
||||
if (streamingId) {
|
||||
event.preventDefault();
|
||||
skipRevealRef.current = streamingId;
|
||||
} else if (typing !== null) {
|
||||
event.preventDefault();
|
||||
skipBeatRef.current = true;
|
||||
}
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
sessionRef.current += 1;
|
||||
audioRef.current?.pause();
|
||||
|
|
@ -435,6 +609,9 @@ export function NpcConversation({
|
|||
// the NPC starts typing its reply. `displayText` is the label as shown on
|
||||
// the button (flag tokens already interpolated server-side).
|
||||
const pick = (hop: DialogueNext, choiceIndex: number, displayText?: string) => {
|
||||
// Choosing is the player saying they are done reading up the log, so the
|
||||
// log resumes following their own line and the reply that comes back.
|
||||
followRef.current = true;
|
||||
const token = sessionRef.current;
|
||||
const text = displayText || hop.label || "…";
|
||||
if (hop.once && lastNode && lastNode.kind === "node") {
|
||||
|
|
@ -478,6 +655,93 @@ export function NpcConversation({
|
|||
}, [])
|
||||
: [];
|
||||
const anySelectableChoice = visibleChoices.some((choice) => !choice.locked);
|
||||
/** Only the choices a keypress may take. Numbering and the keyboard both run
|
||||
* off this list, so a locked option never consumes a digit. */
|
||||
const selectableChoices = visibleChoices.filter((choice) => !choice.locked);
|
||||
|
||||
/** The node whose options belong on screen. Null while anything is still
|
||||
* arriving, which is what opens and closes the footer: the row animates from
|
||||
* 0fr to 1fr, so the menu slides in instead of the text jumping. */
|
||||
const footerNode = (() => {
|
||||
if (typing !== null || playerTyping || streamingId !== null) return null;
|
||||
if (!lastNode || lastNode.kind !== "node") return null;
|
||||
const node = lastNode.node;
|
||||
return node.type === "choice" || node.type === "end" ? node : null;
|
||||
})();
|
||||
|
||||
/** True while the log follows new content. A player who scrolls up to read
|
||||
* something keeps their place; coming back to the bottom, or picking a choice,
|
||||
* resumes the follow. */
|
||||
const followRef = useRef(true);
|
||||
/** When we last wrote `scrollTop` ourselves, so our own writes are never read
|
||||
* as the player scrolling away. */
|
||||
const lastAutoScrollRef = useRef(0);
|
||||
|
||||
const scrollToEnd = () => {
|
||||
if (!scroller) return;
|
||||
scroller.scrollTop = scroller.scrollHeight;
|
||||
lastAutoScrollRef.current =
|
||||
typeof performance === "undefined" ? 0 : performance.now();
|
||||
};
|
||||
|
||||
// Follow new lines, the typing dots and the footer opening, but only while the
|
||||
// player is following: someone reading further up keeps their place instead of
|
||||
// being dragged to the bottom when a menu appears.
|
||||
useEffect(() => {
|
||||
if (followRef.current) scrollToEnd();
|
||||
}, [log, typing, playerTyping, open, streamingId, visibleChoices.length]);
|
||||
|
||||
// Two things keep changing after the effect above has run: the footer opening
|
||||
// shrinks the box, and a line being typed out grows the content. Both are
|
||||
// watched, so the newest character stays in view while the player is
|
||||
// following. Depends on `open` because the dialog's DOM does not exist until
|
||||
// it is first opened, and the refs would be null on mount.
|
||||
useEffect(() => {
|
||||
if (!scroller || typeof ResizeObserver === "undefined") return;
|
||||
const content = contentRef.current;
|
||||
const observer = new ResizeObserver(() => {
|
||||
if (followRef.current) scrollToEnd();
|
||||
});
|
||||
observer.observe(scroller);
|
||||
if (content) observer.observe(content);
|
||||
return () => observer.disconnect();
|
||||
}, [scroller]);
|
||||
|
||||
// Stop following when the player scrolls up, resume at the bottom. The wheel
|
||||
// and touch listeners catch the gesture itself (before the scroll lands), the
|
||||
// scroll listener resumes and also catches a dragged scrollbar.
|
||||
useEffect(() => {
|
||||
const el = scroller;
|
||||
if (!el) return;
|
||||
const distanceFromEnd = () => el.scrollHeight - el.clientHeight - el.scrollTop;
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
if (event.deltaY < 0 && distanceFromEnd() > 8) followRef.current = false;
|
||||
};
|
||||
const onTouchMove = () => {
|
||||
if (distanceFromEnd() > 8) followRef.current = false;
|
||||
};
|
||||
const onScroll = () => {
|
||||
if (distanceFromEnd() <= 8) {
|
||||
followRef.current = true;
|
||||
return;
|
||||
}
|
||||
const now = typeof performance === "undefined" ? 0 : performance.now();
|
||||
// A box change (the footer opening) or our own pin can make the distance
|
||||
// grow for a frame. Only a scroll well after our last write counts as the
|
||||
// player leaving the bottom.
|
||||
if (now - lastAutoScrollRef.current < 150) return;
|
||||
followRef.current = false;
|
||||
};
|
||||
el.addEventListener("wheel", onWheel, { passive: true });
|
||||
el.addEventListener("touchmove", onTouchMove, { passive: true });
|
||||
el.addEventListener("scroll", onScroll, { passive: true });
|
||||
return () => {
|
||||
el.removeEventListener("wheel", onWheel);
|
||||
el.removeEventListener("touchmove", onTouchMove);
|
||||
el.removeEventListener("scroll", onScroll);
|
||||
};
|
||||
}, [scroller]);
|
||||
|
||||
|
||||
/** Button text for a choice: the server-resolved label when the choice
|
||||
* node's strings contained flag tokens, the raw label otherwise. */
|
||||
|
|
@ -528,7 +792,16 @@ export function NpcConversation({
|
|||
<Dialog open={open} onOpenChange={(next) => !next && close()}>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
className="flex w-[calc(100%-1.5rem)] max-w-2xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white sm:w-full sm:rounded-none"
|
||||
onKeyDown={onConversationKeyDown}
|
||||
className={`flex w-[calc(100%-1.5rem)] max-w-2xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white sm:w-full sm:rounded-none ${
|
||||
// A frame of fixed height. The dialog used to size itself to its
|
||||
// content, so the choice footer appearing made it taller, and being
|
||||
// vertically centred made the whole box jump up and down. With a
|
||||
// fixed height the window never moves: the log gives up space and
|
||||
// scrolls instead, and a long choice list scrolls inside its own
|
||||
// band rather than shrinking the conversation to nothing.
|
||||
flow.startId === null ? "" : "h-[min(80dvh,36rem)]"
|
||||
}`}
|
||||
>
|
||||
<div className={`relative flex items-center justify-between ${DOSSIER.strip}`}>
|
||||
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
|
||||
|
|
@ -544,11 +817,12 @@ export function NpcConversation({
|
|||
// Muting mid-line silences the clip immediately; the reveal
|
||||
// keeps its current pace.
|
||||
audioRef.current?.pause();
|
||||
setPlaying(null);
|
||||
}
|
||||
}}
|
||||
aria-pressed={!soundOn}
|
||||
aria-label={soundOn ? "Mute voice clips" : "Unmute voice clips"}
|
||||
title={soundOn ? "Mute voice clips" : "Unmute voice clips"}
|
||||
aria-label={soundOn ? "Mute conversation sound" : "Unmute conversation sound"}
|
||||
title={soundOn ? "Mute conversation sound" : "Unmute conversation sound"}
|
||||
className="text-white/40 transition-colors hover:text-white/90"
|
||||
>
|
||||
{soundOn ? <Volume2Icon className="size-4" /> : <VolumeXIcon className="size-4" />}
|
||||
|
|
@ -571,7 +845,18 @@ export function NpcConversation({
|
|||
|
||||
{/* 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" />
|
||||
<audio
|
||||
ref={audioRef}
|
||||
preload="none"
|
||||
className="hidden"
|
||||
onTimeUpdate={(event) => {
|
||||
const audio = event.currentTarget;
|
||||
if (!audio.duration || !Number.isFinite(audio.duration)) return;
|
||||
const ratio = audio.currentTime / audio.duration;
|
||||
setPlaying((current) => (current ? { ...current, ratio } : current));
|
||||
}}
|
||||
onEnded={() => setPlaying(null)}
|
||||
/>
|
||||
|
||||
{flow.startId === null ? (
|
||||
<div className="p-5 text-sm text-white/50">
|
||||
|
|
@ -580,61 +865,97 @@ export function NpcConversation({
|
|||
) : (
|
||||
<>
|
||||
<div
|
||||
ref={scrollRef}
|
||||
ref={attachScroller}
|
||||
onClick={() => {
|
||||
// A click anywhere in the log finishes the line that is
|
||||
// typing, rather than leaving the player to wait it out.
|
||||
// typing, or starts the next one when the beat is showing,
|
||||
// rather than leaving the player to wait either out.
|
||||
if (streamingId) skipRevealRef.current = streamingId;
|
||||
else skipBeatRef.current = true;
|
||||
}}
|
||||
className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5"
|
||||
data-log="conversation"
|
||||
role="log"
|
||||
aria-live="polite"
|
||||
aria-relevant="additions"
|
||||
aria-busy={streamingId !== null || typing !== null || playerTyping}
|
||||
aria-label={`Conversation with ${npc.name}`}
|
||||
className="min-h-0 flex-1 overflow-y-auto p-5"
|
||||
>
|
||||
{log.map((entry) => (
|
||||
<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,
|
||||
{/* Bottom-anchored like a messenger: a short conversation sits
|
||||
just above its choices instead of floating in a tall empty
|
||||
box. `min-h-full` keeps the block able to grow past the
|
||||
viewport, so a long conversation still scrolls from the top
|
||||
and nothing becomes unreachable above the scroll origin. */}
|
||||
<div
|
||||
ref={contentRef}
|
||||
className="flex min-h-full flex-col justify-end gap-3"
|
||||
>
|
||||
{log.map((entry) => (
|
||||
<TimelineEntry
|
||||
key={entry.id}
|
||||
entry={entry}
|
||||
speakerDefault={npc.name}
|
||||
playingRatio={playing?.id === entry.id ? playing.ratio : null}
|
||||
onPlayVoice={(url) => {
|
||||
// Explicit click: always allowed, and clears the notice.
|
||||
const audio = audioRef.current;
|
||||
if (!audio) return;
|
||||
audio.src = playableUrl(url);
|
||||
audio.currentTime = 0;
|
||||
setPlaying({ id: entry.id, ratio: 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 />}
|
||||
)
|
||||
.catch(() => undefined);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{typing !== null && <TypingIndicator speaker={typing} />}
|
||||
{playerTyping && <TypingIndicator player />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!typing &&
|
||||
!playerTyping &&
|
||||
streamingId === null &&
|
||||
lastNode &&
|
||||
lastNode.kind === "node" &&
|
||||
(lastNode.node.type === "choice" || lastNode.node.type === "end") && (
|
||||
<div className="flex flex-col gap-2 border-t border-white/15 bg-black/50 p-4">
|
||||
{lastNode.node.type === "choice" && visibleChoices.length > 0 && (
|
||||
{/* The footer opens by growing its grid row, so the menu slides in
|
||||
and the log above it gives up height over the same 260ms
|
||||
instead of the text jumping up in one frame. Always mounted so
|
||||
the transition has something to animate; `motion-reduce`
|
||||
collapses the timing to nothing. */}
|
||||
<div
|
||||
data-footer="choices"
|
||||
className={`grid shrink-0 overflow-hidden transition-[grid-template-rows] duration-300 ease-out motion-reduce:transition-none ${
|
||||
footerNode ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
|
||||
}`}
|
||||
>
|
||||
<div className="min-h-0">
|
||||
{footerNode && (
|
||||
<div className="flex max-h-[260px] flex-col gap-2 overflow-y-auto border-t border-white/15 bg-black/50 p-4">
|
||||
{footerNode.type === "choice" && visibleChoices.length > 0 && (
|
||||
<TooltipProvider delayDuration={150}>
|
||||
{visibleChoices.map(({ hop, index, locked }) => {
|
||||
const isNew = unseenTargets.has(hop.target);
|
||||
// The number matches the key that picks it; locked
|
||||
// choices are unnumbered because no key reaches them.
|
||||
const shortcut = locked
|
||||
? null
|
||||
: choiceShortcutLabel(
|
||||
selectableChoices.findIndex((choice) => choice.index === index),
|
||||
);
|
||||
const button = (
|
||||
<button
|
||||
type="button"
|
||||
disabled={locked}
|
||||
onClick={() => pick(hop, index, choiceLabel(hop, index))}
|
||||
className={`w-full rounded-none border px-3 py-2 text-left text-sm transition-colors ${
|
||||
aria-keyshortcuts={shortcut ?? undefined}
|
||||
style={{ animationDelay: `${Math.min(index, 6) * 40}ms` }}
|
||||
className={`w-full rounded-none border px-3 py-2 text-left text-sm transition-colors animate-in fade-in-0 slide-in-from-bottom-1 fill-mode-both duration-200 motion-reduce:animate-none ${
|
||||
locked
|
||||
? "cursor-not-allowed border-white/10 bg-black/20 text-white/35"
|
||||
: "border-white/20 bg-black/40 text-white/80 hover:border-cyan-500/60 hover:text-white"
|
||||
|
|
@ -644,6 +965,14 @@ export function NpcConversation({
|
|||
{locked && (
|
||||
<LockIcon className="size-3 shrink-0 text-amber-400/70" />
|
||||
)}
|
||||
{shortcut && (
|
||||
<span
|
||||
aria-hidden
|
||||
className="shrink-0 rounded-sm border border-white/15 bg-black/40 px-1 font-mono text-[10px] leading-tight text-white/40"
|
||||
>
|
||||
{shortcut}
|
||||
</span>
|
||||
)}
|
||||
<DialogueText text={choiceLabel(hop, index)} />
|
||||
{isNew && !locked && (
|
||||
<span className="ml-auto shrink-0 rounded-sm bg-cyan-400 px-1 font-mono text-[9px] font-bold uppercase leading-tight text-black">
|
||||
|
|
@ -670,7 +999,7 @@ export function NpcConversation({
|
|||
})}
|
||||
</TooltipProvider>
|
||||
)}
|
||||
{(lastNode.node.type === "end" || !anySelectableChoice) && (
|
||||
{(footerNode.type === "end" || !anySelectableChoice) && (
|
||||
<Button
|
||||
onClick={close}
|
||||
className="w-full rounded-none border border-white/20 bg-black/40 text-xs uppercase tracking-widest text-white/80 hover:border-cyan-500/60 hover:bg-black/40 hover:text-white"
|
||||
|
|
@ -679,7 +1008,9 @@ export function NpcConversation({
|
|||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
|
|
@ -688,14 +1019,38 @@ export function NpcConversation({
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A line that may still be typing.
|
||||
*
|
||||
* The visible copy truncates character by character, which is exactly what a
|
||||
* live region must not be fed: it would announce a stutter of fragments. So
|
||||
* while a reveal is running the visible text is hidden from assistive tech and
|
||||
* the whole sentence sits in an `sr-only` copy that never changes. A screen
|
||||
* reader therefore gets the line once, in full, at the moment it arrives.
|
||||
*/
|
||||
function RevealingText({ text, reveal }: { readonly text: string; readonly reveal?: number }) {
|
||||
if (reveal === undefined) return <DialogueText text={text} />;
|
||||
return (
|
||||
<>
|
||||
<span aria-hidden>
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
</span>
|
||||
<span className="sr-only">{visibleText(text)}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function TimelineEntry({
|
||||
entry,
|
||||
speakerDefault,
|
||||
onPlayVoice,
|
||||
playingRatio,
|
||||
}: {
|
||||
entry: LogEntry;
|
||||
speakerDefault: string;
|
||||
onPlayVoice?: (url: string) => void;
|
||||
/** How far through this line's clip playback is, or null when it is silent. */
|
||||
playingRatio?: number | null;
|
||||
}) {
|
||||
if (entry.kind === "player") {
|
||||
return (
|
||||
|
|
@ -709,6 +1064,34 @@ function TimelineEntry({
|
|||
}
|
||||
|
||||
const { node, resolved, text, reveal } = entry;
|
||||
/** Replay for a line that has a clip and played normally. Autoplay-blocked
|
||||
* lines keep the louder "Play voice" button instead. */
|
||||
const replayButton =
|
||||
entry.kind === "node" && entry.voiceUrl && !entry.voiceBlocked && onPlayVoice ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPlayVoice(entry.voiceUrl as string)}
|
||||
aria-label="Replay this line"
|
||||
title="Replay this line"
|
||||
className="inline-flex items-center gap-1 rounded-sm border border-white/10 bg-black/30 px-1 py-0.5 font-mono text-[9px] uppercase tracking-wider text-white/40 transition-colors hover:border-cyan-500/60 hover:text-cyan-300"
|
||||
>
|
||||
<Volume2Icon className="size-2.5" />
|
||||
Replay
|
||||
</button>
|
||||
) : null;
|
||||
|
||||
/** A hairline under the line, filling as the clip plays, so a long read has
|
||||
* visible progress instead of only audio. */
|
||||
const voiceProgress =
|
||||
playingRatio === null || playingRatio === undefined ? null : (
|
||||
<span aria-hidden className="mt-0.5 block h-px w-full bg-white/10">
|
||||
<span
|
||||
className="block h-full bg-cyan-400/70 transition-[width] duration-150 ease-linear"
|
||||
style={{ width: `${Math.max(0, Math.min(1, playingRatio)) * 100}%` }}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
|
||||
/** A clip the browser refused to autoplay gets a button rather than nothing. */
|
||||
const voiceFallback =
|
||||
entry.voiceBlocked && entry.voiceUrl && onPlayVoice ? (
|
||||
|
|
@ -730,8 +1113,10 @@ function TimelineEntry({
|
|||
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} />
|
||||
<RevealingText text={text} reveal={reveal} />
|
||||
</p>
|
||||
{voiceProgress}
|
||||
{replayButton}
|
||||
{voiceFallback}
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
|
|
@ -741,8 +1126,10 @@ function TimelineEntry({
|
|||
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} reveal={reveal} />
|
||||
<RevealingText text={text} reveal={reveal} />
|
||||
</p>
|
||||
{voiceProgress}
|
||||
{replayButton}
|
||||
{voiceFallback}
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
|
|
@ -753,8 +1140,10 @@ function TimelineEntry({
|
|||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-sm italic text-white/50">
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
<RevealingText text={text} reveal={reveal} />
|
||||
</p>
|
||||
{voiceProgress}
|
||||
{replayButton}
|
||||
{voiceFallback}
|
||||
</div>
|
||||
);
|
||||
|
|
@ -765,7 +1154,7 @@ function TimelineEntry({
|
|||
if (!text) return null;
|
||||
return (
|
||||
<p className="text-sm italic text-white/60">
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
<RevealingText text={text} reveal={reveal} />
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
|
@ -773,14 +1162,18 @@ function TimelineEntry({
|
|||
const speaker = node.data.speaker?.trim() || speakerDefault;
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className={DOSSIER.readoutLabel}>{speaker}</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className={DOSSIER.readoutLabel}>{speaker}</span>
|
||||
{replayButton}
|
||||
</span>
|
||||
<p className="text-sm text-white/90">
|
||||
{text ? (
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
<RevealingText text={text} reveal={reveal} />
|
||||
) : (
|
||||
<span className="italic text-white/30">…</span>
|
||||
)}
|
||||
</p>
|
||||
{voiceProgress}
|
||||
{voiceFallback}
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -12,9 +12,12 @@ import { DOSSIER, NoticeState } from "@/components/frontend/operations";
|
|||
|
||||
interface NpcDirectoryProps {
|
||||
readonly npcs: GameNpc[];
|
||||
/** Contacts with conversation content this player has never read. */
|
||||
readonly unreadNpcIds?: readonly number[];
|
||||
}
|
||||
|
||||
export function NpcDirectory({ npcs }: NpcDirectoryProps) {
|
||||
export function NpcDirectory({ npcs, unreadNpcIds = [] }: NpcDirectoryProps) {
|
||||
const unread = new Set(unreadNpcIds);
|
||||
const [search, setSearch] = useState("");
|
||||
const [inGameOnly, setInGameOnly] = useState(false);
|
||||
const [vendorsOnly, setVendorsOnly] = useState(false);
|
||||
|
|
@ -117,7 +120,7 @@ export function NpcDirectory({ npcs }: NpcDirectoryProps) {
|
|||
) : (
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{filteredNpcs.map((npc) => (
|
||||
<NpcCard key={npc.id} npc={npc} />
|
||||
<NpcCard key={npc.id} npc={npc} unread={unread.has(npc.id)} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -162,19 +162,230 @@ footer never waits on a lead-in. `DialogueText` takes a `reveal` count and trunc
|
|||
**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.
|
||||
both use. It is defined as `visibleText(text).length`, one walker for both, so the
|
||||
schedule and the renderer cannot disagree about how long a line is.
|
||||
|
||||
**The rhythm is a schedule, not a clock.** `pacing.ts` (pure, unit-tested in
|
||||
`tests/int/npc-dialogue-pacing.int.spec.ts`) gives every visible unit a cost of
|
||||
`BASE_UNIT_MS` plus a pause after it: `clauseMs` after `, ; :`, `sentenceMs`
|
||||
after `. ! ? …`, `newlineMs` after one break, `paragraphMs` after a blank line.
|
||||
Presets `subtle` / `natural` / `pronounced` carry those four values plus
|
||||
`beatMs`; `natural` is what the component uses today.
|
||||
|
||||
Rules that keep pauses from stacking or misfiring:
|
||||
|
||||
- A break after a character owns the pause, so `End.\nNext` pays the newline
|
||||
pause once, never sentence plus newline.
|
||||
- A run of newlines is one paragraph break: the first carries `paragraphMs`, the
|
||||
rest are free.
|
||||
- Punctuation followed by a closing quote or bracket (`"Fine."`) pauses after the
|
||||
cluster, not between the mark and its quote.
|
||||
- A comma between two digits (`1,000 rounds`) is a number, not a clause.
|
||||
|
||||
The schedule is already a duration: `BASE_UNIT_MS` per unit plus its pauses, so a
|
||||
preset's numbers are the milliseconds a player actually waits. The default target
|
||||
is `schedule.total`, with a `REVEAL_CAP_MS` ceiling (3000) that compresses the
|
||||
whole schedule for a wall of text. `scaleSchedule` exists for the one case that
|
||||
needs a different target: a recorded line scales the schedule to the clip length,
|
||||
so the rhythm is preserved and only stretched. The last unit's trailing pause is
|
||||
excluded from `total`, so a finished line never sits waiting for nothing.
|
||||
|
||||
`natural` (155 / 370 / 450 / 720, beat 720) was tuned up once from the first cut,
|
||||
which read as too rushed at commas. Do not lower it back without asking: the
|
||||
original values were the author's first reaction, not a preference.
|
||||
|
||||
**The beat between lines.** After a spoken line, if the next node is another
|
||||
spoken line, `cascadeFrom` shows the speaker's typing dots for `beatMs` before
|
||||
starting it. The opening line of a cascade gets no beat: no hop precedes it, so
|
||||
the player either just opened the conversation or just sent a line. Clicking the
|
||||
log during the beat starts the next line at once (`skipBeatRef`), the same way a
|
||||
click finishes a line that is still typing.
|
||||
|
||||
**The typing sound.** `typeSound.ts` synthesizes one tick per `MIN_TICK_SPACING_MS`
|
||||
from precomputed schedule times: a short low-passed noise burst plus a low
|
||||
triangle body, jittered in pitch and gain. Tick times come from a seeded RNG in
|
||||
`pacing.ts`, keyed on the line text, so a re-render cannot re-roll the rhythm.
|
||||
It stays silent on a line that has a recorded clip, when the header mute is on,
|
||||
and whenever the reveal is not running. `primeTypeSound()` is called from the
|
||||
Converse click because a browser only grants audio inside a gesture; without
|
||||
that call the ticks stay silent for the whole conversation while clips still
|
||||
fall back to their Play button.
|
||||
|
||||
- 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.
|
||||
- Sound per player: `users.preferences.dialogue.typewriterSound` (default on). It
|
||||
is a separate switch from the voice preference on purpose, so a player can keep
|
||||
recorded lines and lose the ticks (or the reverse).
|
||||
- `prefers-reduced-motion` forces the animation off regardless of either setting,
|
||||
which also skips the beat and the sound.
|
||||
- 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.
|
||||
|
||||
### Accessibility
|
||||
|
||||
The log is a live region (`role="log"`, `aria-live="polite"`, `aria-relevant="additions"`)
|
||||
with a per-NPC `aria-label`, and `aria-busy` is true while a line types or the beat
|
||||
runs, so a screen reader is never fed a half-finished sentence.
|
||||
|
||||
**The reveal is why this needed care.** A polite live region would announce every
|
||||
mutation of the truncating text, which is a stutter of fragments. `RevealingText`
|
||||
therefore hides the visible copy (`aria-hidden`) while a `reveal` value is present and
|
||||
renders the whole line once in an `sr-only` sibling that never changes. The line is
|
||||
announced once, in full, when it arrives.
|
||||
|
||||
Keyboard: digits `1`-`9` take a choice (`choiceIndexFromKey` in `keys.ts`, mapped over
|
||||
the *selectable* choices so a locked option never consumes a digit); the same number is
|
||||
shown on the button as a mono badge and exposed as `aria-keyshortcuts`. `Enter` or
|
||||
`Space` finishes the line that is typing, or starts the next one during the beat.
|
||||
`Escape` closes, from Radix. The handler sits on `DialogContent` and returns early when
|
||||
the event came from a control, so a focused button keeps its own activation.
|
||||
|
||||
Measured: 2587ms to idle naturally against 382ms when `Enter` is pressed at 300ms.
|
||||
|
||||
### Voice clips: preload, replay and progress
|
||||
|
||||
Clips are fetched ahead of time and kept as object URLs
|
||||
(`clipCacheRef`, bounded at 8 with `revokeObjectURL` on eviction and on unmount),
|
||||
so a line plays from memory instead of starting a request when its turn comes. The
|
||||
URL is built from the node's own `voice.filename` (`/api/media/file/<filename>`),
|
||||
which is why no server round trip is needed to preload it.
|
||||
|
||||
The next clip is fetched **once the current line knows where it goes** (`typeIn`,
|
||||
after `markSeen`): `node.data.next.target` gives the successor, and its
|
||||
`data.voice.filename` the file. This is deliberately not routed through the
|
||||
condition logic. Guessing the successor wrong only wastes one small download, while
|
||||
preloading across an event node would be wrong (its effect can change interpolated
|
||||
text, though not which file plays).
|
||||
|
||||
Measured: the second line's clip was requested 2.8s before the second line
|
||||
appeared, while the first was still playing. Never preload across a branch the
|
||||
walker has not taken, and never prefetch before `soundOn` is known true.
|
||||
|
||||
Each voiced line gets a `Replay` control beside its speaker label, and while a clip
|
||||
plays a cyan hairline under the line fills from `audio.timeupdate` (`playing`
|
||||
state, keyed by log entry id, so only the line actually playing shows it). The
|
||||
element reports progress and clears on `ended`; muting and closing clear it
|
||||
immediately.
|
||||
|
||||
### Play the draft (editor preview)
|
||||
|
||||
The player runtime reads the stored document, so an unsaved canvas cannot be
|
||||
played on the contact page. `DialoguePreviewDialog` (client) walks the live
|
||||
`nodes` from `useField` instead: a `Play` button in the toolbar opens it, and
|
||||
`preview.ts` answers what can be answered locally (choices in runtime order,
|
||||
branch targets, effect descriptions).
|
||||
|
||||
Conditions are the one thing that needs the server: flag values live in the
|
||||
database. `previewActions.previewDialogueCondition` authenticates, requires
|
||||
`npc-dialogues:update`, and calls the same `evaluateCondition` the runtime uses,
|
||||
so the preview cannot disagree with the player's outcome. Gated choices are
|
||||
evaluated per node and shown as "hidden for you", matching what the runtime would
|
||||
hide.
|
||||
|
||||
**Effects are dry-run.** `previewEffectLines` describes the write ("Would set flag
|
||||
X to true") and nothing calls the effect applier. Verified on a temp document with
|
||||
a flag effect and a condition node: the event step showed the dry-run line, the
|
||||
condition answered false for a missing flag, the walk followed the false branch,
|
||||
and `player_flags` gained no row.
|
||||
|
||||
Two traps specific to this component, both costs of rendering inside the admin:
|
||||
|
||||
- Every bare `<button>` shows the UA's white background, because the admin bundle
|
||||
has no theme tokens and no preflight for buttons. Give each one an explicit
|
||||
background (`bg-transparent` or `bg-black/40`), not just a border.
|
||||
- `contactName` comes from the relationship field, which is often a bare id at the
|
||||
editor's depth. It falls back to `contact <id>`, which is honest; do not try to
|
||||
fetch the name here.
|
||||
|
||||
`once` choices are treated as spent once their target was visited in this run,
|
||||
which is the closest the preview gets to the runtime's per-player bookkeeping.
|
||||
The preview never writes read markers, so it cannot make a conversation look read.
|
||||
|
||||
### Unread markers
|
||||
|
||||
A contact card shows a `NEW` chip when the conversation that would be offered has
|
||||
a node with no read marker for this player (`src/lib/npc-dialogue/unread.ts`). The
|
||||
read markers already existed for the in-conversation badge; this surfaces them
|
||||
where they decide anything, on the directory.
|
||||
|
||||
Definition: any unread node in the offered flow counts, so a branch added after a
|
||||
player finished a conversation brings the chip back. That is deliberate (the
|
||||
content is new to them), but it means a partially explored conversation stays
|
||||
marked until every branch is read. Do not "fix" that by only checking the start
|
||||
node without asking, and do not check nodes that are no longer in the flow: stale
|
||||
markers for deleted nodes are ignored.
|
||||
|
||||
Two gates come before the chip, matching the offer: callers pass only contacts with
|
||||
`game-npcs.canMessage` true, and the loader runs the same `selectDialogueForUser`
|
||||
gate the contact page runs, so a chip never advertises a conversation the entry
|
||||
gate hides. `testing` conversations are filtered by `dialogueVisibleTo`.
|
||||
|
||||
Cost is two queries for the whole directory (conversations for the NPCs, read
|
||||
markers for the offered ones), plus one flag evaluation per NPC that has a gated
|
||||
conversation. The page swallows loader errors and renders no chips rather than
|
||||
failing the directory.
|
||||
|
||||
### The conversation frame
|
||||
|
||||
The dialog is a **fixed-height frame** (`h-[min(80dvh,36rem)]`), not a box that
|
||||
sizes itself to its content. It used to grow when the choice footer appeared, and
|
||||
because Radix centres it vertically the whole window jumped up and down at the
|
||||
moment the player was about to read a menu. Now the window never moves: the log is
|
||||
`flex-1 min-h-0` and gives up height to the footer, and the footer is
|
||||
`max-h-[45%] shrink-0 overflow-y-auto`, so a long menu scrolls inside its own band
|
||||
instead of squeezing the conversation to nothing.
|
||||
|
||||
The log's content is bottom-anchored (`flex min-h-full flex-col justify-end`) so a
|
||||
short conversation sits just above its choices rather than floating in a tall empty
|
||||
box. `min-h-full` is what keeps a long conversation scrollable from the top: without
|
||||
it, `justify-end` puts overflow above the scroll origin where it cannot be reached.
|
||||
|
||||
The auto-scroll effect depends on `streamingId` and `visibleChoices.length` as well
|
||||
as the log: the footer appearing (or a menu gaining items) changes how much room the
|
||||
log has, and without those the newest line can end up scrolled out of sight.
|
||||
|
||||
**Following is a state, not a rule about position.** `followRef` starts true and the
|
||||
log pins to the end on new lines, the typing dots, the footer opening and any content
|
||||
growth. The player scrolling up turns it off, so nothing drags them to the bottom
|
||||
while they are reading; coming back to the bottom, or picking a choice, turns it back
|
||||
on. Detection uses `wheel` (upward delta), `touchmove`, and `scroll` (resuming at the
|
||||
bottom, and catching a dragged scrollbar), with a 150ms guard after our own write so a
|
||||
pin cannot be mistaken for the player leaving. Measured: untouched, the log ends at
|
||||
the new `maxTop` (228px, distance 0) when the footer opens; scrolled up first, it stays
|
||||
exactly where the player left it (76px) while the footer opens beneath.
|
||||
|
||||
Two things had to be watched, because both change the layout without changing the log
|
||||
array: the footer opening (the box shrinks) and a line growing as it types (the content
|
||||
grows). One `ResizeObserver` watches the scroller and the content block, and re-pins
|
||||
only while following. Without the content observer the newest characters drift below
|
||||
the fold mid-line, which is what the reveal looked like before.
|
||||
|
||||
The scroller reaches the effects through a **callback ref plus state**, not a plain
|
||||
`useCallback`-less ref: Radix mounts the dialog's DOM a commit after `open` flips, so
|
||||
an effect keyed on `open` ran while `scrollRef.current` was still null, attached
|
||||
nothing, and every follow behaviour silently did nothing. The callback ref is also
|
||||
`useCallback`-wrapped, because an inline arrow is a new function each render and React
|
||||
would detach and reattach it, looping on the state write.
|
||||
|
||||
**The footer slides in.** It is wrapped in a grid whose
|
||||
`grid-template-rows` goes `0fr` to `1fr` over 300ms, with the item `min-h-0` and the
|
||||
wrapper `overflow-hidden`; the content mounts at the same moment the row starts
|
||||
growing, so the log gives up height progressively and the lines above glide instead
|
||||
of being knocked upward in one frame (measured: 19 frames from 0 to 163 px, log 529
|
||||
to 366 in step). The buttons stagger in behind it with `animate-in` and a 40ms
|
||||
per-item delay. `motion-reduce` sets `transition-property: none`, so the menu lands
|
||||
at once for a reduced-motion device.
|
||||
|
||||
The **exit is deliberately instant**: a pick swaps the footer for the player's typing
|
||||
indicator, and the menu vanishing the moment it is used is the expected feedback.
|
||||
Animating it out would mean latching the last choice node so its buttons could stay
|
||||
mounted while collapsing; that is not worth the extra state unless someone asks.
|
||||
|
||||
## AI drafting behaviour worth knowing
|
||||
|
||||
- Two attempts maximum: the second prompt carries the validator's complaints.
|
||||
|
|
|
|||
|
|
@ -32,8 +32,16 @@ import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
|||
*/
|
||||
interface RevealBudget {
|
||||
left: number;
|
||||
/** Every unit the budget granted, in order, when the caller asked for it.
|
||||
* An image or a countdown contributes one placeholder character (it costs
|
||||
* one unit but renders no text of its own). */
|
||||
seen?: string[];
|
||||
}
|
||||
|
||||
/** One visible unit of an image or a countdown: countable, non-space, and
|
||||
* never mistaken for punctuation by the pacing schedule. */
|
||||
const ATOMIC_UNIT = "\uFFFC";
|
||||
|
||||
/** Budget for a fully revealed line (a number, not Infinity, so the consumed
|
||||
* count stays computable). */
|
||||
const UNLIMITED_REVEAL = Number.MAX_SAFE_INTEGER;
|
||||
|
|
@ -69,9 +77,21 @@ export function DialogueText({
|
|||
* 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 };
|
||||
return visibleText(text).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* The line's visible characters, flattened in reveal order, so a schedule can
|
||||
* be built per unit (a pause belongs after a particular comma). Built by the
|
||||
* same walk as `visibleLength`, which is defined in terms of it, so the two
|
||||
* cannot drift: markup and list prefixes contribute nothing, an image or a
|
||||
* countdown contributes `ATOMIC_UNIT`, and a code run appears all at once when
|
||||
* it fits.
|
||||
*/
|
||||
export function visibleText(text: string): string {
|
||||
const budget: RevealBudget = { left: UNLIMITED_REVEAL, seen: [] };
|
||||
renderBlocks(text, { i: 0 }, budget);
|
||||
return UNLIMITED_REVEAL - budget.left;
|
||||
return (budget.seen ?? []).join("");
|
||||
}
|
||||
|
||||
const BULLET_RE = /^[-*]\s+/;
|
||||
|
|
@ -207,6 +227,7 @@ function parseSegment(
|
|||
const take = Math.min(plain.length, budget.left);
|
||||
nodes.push(take === plain.length ? plain : plain.slice(0, take));
|
||||
budget.left -= take;
|
||||
budget.seen?.push(plain.slice(0, take));
|
||||
}
|
||||
plain = "";
|
||||
};
|
||||
|
|
@ -230,6 +251,7 @@ function parseSegment(
|
|||
// since its characters are literal and often not prose.
|
||||
if (budget.left >= code.length) {
|
||||
budget.left -= code.length;
|
||||
budget.seen?.push(code);
|
||||
nodes.push(
|
||||
<code
|
||||
key={key()}
|
||||
|
|
@ -250,6 +272,7 @@ function parseSegment(
|
|||
flush();
|
||||
if (budget.left >= 1) {
|
||||
budget.left -= 1;
|
||||
budget.seen?.push(ATOMIC_UNIT);
|
||||
nodes.push(<Countdown key={key()} value={cd[1]} />);
|
||||
}
|
||||
i += cd[0].length;
|
||||
|
|
@ -265,6 +288,7 @@ function parseSegment(
|
|||
flush();
|
||||
if (budget.left >= 1) {
|
||||
budget.left -= 1;
|
||||
budget.seen?.push(ATOMIC_UNIT);
|
||||
nodes.push(
|
||||
<img
|
||||
key={key()}
|
||||
|
|
|
|||
34
src/lib/npc-dialogue/keys.ts
Normal file
34
src/lib/npc-dialogue/keys.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
/**
|
||||
* Keyboard picks for a conversation's choices.
|
||||
*
|
||||
* Digits 1 through 9 select a choice by its position among the ones the player
|
||||
* can actually take, so a locked option does not shift the numbers in a way
|
||||
* that makes "2" pick the third button. Pure, so the mapping is tested rather
|
||||
* than trusted.
|
||||
*/
|
||||
|
||||
const MAX_SHORTCUT_CHOICES = 9;
|
||||
|
||||
/** Zero-based index of the choice a keypress selects, or null if it selects
|
||||
* none. Only single digits 1-9 count: "0" is not a choice, and a modifier
|
||||
* combination belongs to the browser. */
|
||||
export function choiceIndexFromKey(key: string, selectableCount: number): number | null {
|
||||
if (key.length !== 1) return null;
|
||||
const digit = key.charCodeAt(0) - 48;
|
||||
if (digit < 1 || digit > MAX_SHORTCUT_CHOICES) return null;
|
||||
const index = digit - 1;
|
||||
return index < selectableCount ? index : null;
|
||||
}
|
||||
|
||||
/** The digit shown on a choice, 1-9, or null past the shortcut range. */
|
||||
export function choiceShortcutLabel(selectableIndex: number): string | null {
|
||||
if (selectableIndex < 0 || selectableIndex >= MAX_SHORTCUT_CHOICES) return null;
|
||||
return String(selectableIndex + 1);
|
||||
}
|
||||
|
||||
/** Whether a keypress should finish a line that is still typing (or start the
|
||||
* next one when the beat is showing). Space and Enter only, and never on a
|
||||
* focused control, where the browser's own activation is the right answer. */
|
||||
export function isSkipKey(key: string): boolean {
|
||||
return key === "Enter" || key === " ";
|
||||
}
|
||||
203
src/lib/npc-dialogue/pacing.ts
Normal file
203
src/lib/npc-dialogue/pacing.ts
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
import { visibleText } from "./DialogueText";
|
||||
|
||||
/**
|
||||
* Pacing for a conversation line that types itself out.
|
||||
*
|
||||
* A plain clock (one duration divided by the character count) cannot pause at a
|
||||
* comma, so the reveal is driven by a schedule instead: every visible unit gets
|
||||
* its own cost, plus a pause after punctuation and line breaks. The schedule is
|
||||
* built in relative units and scaled to the target duration at the last moment,
|
||||
* so a recorded line (whose length sets the target) keeps the same rhythm as a
|
||||
* silent one, just stretched.
|
||||
*
|
||||
* Pure and client-safe: no Payload, no timers. The component owns the clock.
|
||||
*/
|
||||
|
||||
/** How long each of the four kinds of pause costs. */
|
||||
export interface PauseProfile {
|
||||
/** After a comma, semicolon or colon. */
|
||||
readonly clauseMs: number;
|
||||
/** After a full stop, question mark, exclamation mark or ellipsis. */
|
||||
readonly sentenceMs: number;
|
||||
/** After a single line break. */
|
||||
readonly newlineMs: number;
|
||||
/** After a blank line (a paragraph break). */
|
||||
readonly paragraphMs: number;
|
||||
/** The beat between two lines, when the next speaker starts. */
|
||||
readonly beatMs: number;
|
||||
}
|
||||
|
||||
/** Cost of one visible unit before any pause is added. */
|
||||
export const BASE_UNIT_MS = 24;
|
||||
|
||||
/**
|
||||
* The three approved strengths. `natural` is the unit default: long enough to
|
||||
* read as speech, short enough that a ten line conversation is not a chore.
|
||||
* Tuned up once from the first cut, which read as too rushed at commas.
|
||||
*/
|
||||
export const PACING_PRESETS: Record<string, PauseProfile> = {
|
||||
subtle: { clauseMs: 80, sentenceMs: 220, newlineMs: 280, paragraphMs: 460, beatMs: 460 },
|
||||
natural: { clauseMs: 155, sentenceMs: 370, newlineMs: 450, paragraphMs: 720, beatMs: 720 },
|
||||
pronounced: {
|
||||
clauseMs: 225,
|
||||
sentenceMs: 540,
|
||||
newlineMs: 640,
|
||||
paragraphMs: 1000,
|
||||
beatMs: 1020,
|
||||
},
|
||||
};
|
||||
|
||||
export type PacingPreset = keyof typeof PACING_PRESETS;
|
||||
|
||||
export const DEFAULT_PACING_PRESET: PacingPreset = "natural";
|
||||
|
||||
/** Gaps between typing ticks, in relative units. Wide enough that a fast line
|
||||
* does not turn into a buzz, narrow enough to sound like keys under a sentence. */
|
||||
const TICK_MIN_GAP = 95;
|
||||
const TICK_MAX_GAP = 165;
|
||||
|
||||
export interface RevealSchedule {
|
||||
/** Start of each visible unit in relative units; `arrival[i]` is the moment
|
||||
* unit `i` appears. */
|
||||
readonly arrival: readonly number[];
|
||||
/** The denominator for scaling: the line is finished once the last unit has
|
||||
* arrived, so trailing pause is deliberately excluded. */
|
||||
readonly total: number;
|
||||
/** Moments (relative units) at which to play a typing tick, ascending. */
|
||||
readonly ticks: readonly number[];
|
||||
/** The flattened line the schedule was built from, for debugging and tests. */
|
||||
readonly text: string;
|
||||
}
|
||||
|
||||
const CLAUSE_PUNCTUATION = ",;:";
|
||||
const SENTENCE_PUNCTUATION = ".!?\u2026";
|
||||
/** Punctuation is often followed by a closing quote or bracket; the pause
|
||||
* belongs after the whole cluster, not between the mark and its quote. */
|
||||
const CLOSERS = "\"'\u201d\u2019)]";
|
||||
|
||||
/** Which pause, if any, belongs immediately after `text[i]`. */
|
||||
function pauseAfter(text: string, i: number, profile: PauseProfile): number {
|
||||
const char = text[i];
|
||||
|
||||
if (char === "\n") {
|
||||
// A run of newlines is one paragraph break, not one pause per newline.
|
||||
if (text[i - 1] === "\n") return 0;
|
||||
return text[i + 1] === "\n" ? profile.paragraphMs : profile.newlineMs;
|
||||
}
|
||||
|
||||
// A break after this character supplies the pause on its own; adding the
|
||||
// punctuation pause too would make a sentence ending a paragraph wait twice.
|
||||
if (text[i + 1] === "\n") return 0;
|
||||
|
||||
let mark = char;
|
||||
if (CLOSERS.includes(mark)) mark = text[i - 1] ?? "";
|
||||
|
||||
if (SENTENCE_PUNCTUATION.includes(mark)) return profile.sentenceMs;
|
||||
|
||||
if (CLAUSE_PUNCTUATION.includes(mark)) {
|
||||
// "1,000 rounds" is a number, not a clause. Only skip when the comma sits
|
||||
// between two digits; a comma after a digit and before a letter still reads.
|
||||
const before = text[i - 1] ?? "";
|
||||
const after = text[i + 1] ?? "";
|
||||
if (/\d/.test(before) && /\d/.test(after)) return 0;
|
||||
return profile.clauseMs;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Stable 32 bit hash, so a line's tick rhythm never changes between renders. */
|
||||
function hashText(text: string): number {
|
||||
let hash = 2166136261;
|
||||
for (let i = 0; i < text.length; i += 1) {
|
||||
hash ^= text.charCodeAt(i);
|
||||
hash = Math.imul(hash, 16777619);
|
||||
}
|
||||
return hash >>> 0;
|
||||
}
|
||||
|
||||
/** Small deterministic PRNG (mulberry32). */
|
||||
function seededRandom(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let value = state;
|
||||
value = Math.imul(value ^ (value >>> 15), value | 1);
|
||||
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
|
||||
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the arrival schedule for one line. `text` is the authored string; it
|
||||
* goes through `visibleText` first, so markup and list prefixes cost nothing
|
||||
* and the schedule lines up with what `DialogueText` will actually paint.
|
||||
*/
|
||||
export function buildRevealSchedule(
|
||||
text: string,
|
||||
preset: PacingPreset = DEFAULT_PACING_PRESET,
|
||||
): RevealSchedule {
|
||||
const profile = PACING_PRESETS[preset] ?? PACING_PRESETS.natural;
|
||||
const visible = visibleText(text);
|
||||
if (visible.length === 0) return { arrival: [], total: 0, ticks: [], text: visible };
|
||||
|
||||
const arrival: number[] = [];
|
||||
let cursor = 0;
|
||||
for (let i = 0; i < visible.length; i += 1) {
|
||||
arrival.push(cursor);
|
||||
cursor += BASE_UNIT_MS + pauseAfter(visible, i, profile);
|
||||
}
|
||||
// The last unit's own cost is what finishes the line; its trailing pause is
|
||||
// dropped so the reveal never sits on a complete line waiting for nothing.
|
||||
const total = arrival[arrival.length - 1] + BASE_UNIT_MS;
|
||||
|
||||
const random = seededRandom(hashText(visible));
|
||||
const ticks: number[] = [];
|
||||
let nextTick = TICK_MIN_GAP;
|
||||
for (let i = 0; i < visible.length; i += 1) {
|
||||
if (visible[i].trim().length === 0) continue;
|
||||
if (arrival[i] < nextTick) continue;
|
||||
ticks.push(arrival[i]);
|
||||
nextTick = arrival[i] + TICK_MIN_GAP + random() * (TICK_MAX_GAP - TICK_MIN_GAP);
|
||||
}
|
||||
|
||||
return { arrival, total, ticks, text: visible };
|
||||
}
|
||||
|
||||
export interface ScaledSchedule {
|
||||
/** Absolute arrival time of each unit, in milliseconds from the line's start. */
|
||||
readonly arrivalMs: readonly number[];
|
||||
/** Absolute tick times, in milliseconds. */
|
||||
readonly tickMs: readonly number[];
|
||||
/** When the whole line has landed. */
|
||||
readonly durationMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stretches a schedule to a target duration. Used both for the default curve
|
||||
* and for a recorded line, so pauses stay proportional to the read rather than
|
||||
* collapsing under a long clip.
|
||||
*/
|
||||
export function scaleSchedule(schedule: RevealSchedule, targetMs: number): ScaledSchedule {
|
||||
const target = Math.max(0, targetMs);
|
||||
if (schedule.total <= 0) return { arrivalMs: [], tickMs: [], durationMs: target };
|
||||
const factor = target / schedule.total;
|
||||
return {
|
||||
arrivalMs: schedule.arrival.map((value) => value * factor),
|
||||
tickMs: schedule.ticks.map((value) => value * factor),
|
||||
durationMs: target,
|
||||
};
|
||||
}
|
||||
|
||||
/** How many units have arrived by `elapsedMs`. Counted with the same comparison
|
||||
* the reveal loop uses, so "finished" and "how much is shown" cannot disagree. */
|
||||
export function shownAt(arrivalMs: readonly number[], elapsedMs: number): number {
|
||||
let shown = 0;
|
||||
while (shown < arrivalMs.length && arrivalMs[shown] <= elapsedMs) shown += 1;
|
||||
return shown;
|
||||
}
|
||||
|
||||
/** The beat before the next line starts. */
|
||||
export function beatMs(preset: PacingPreset = DEFAULT_PACING_PRESET): number {
|
||||
return (PACING_PRESETS[preset] ?? PACING_PRESETS.natural).beatMs;
|
||||
}
|
||||
169
src/lib/npc-dialogue/preview.ts
Normal file
169
src/lib/npc-dialogue/preview.ts
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
/**
|
||||
* Read-only helpers for walking a draft conversation in the editor.
|
||||
*
|
||||
* The author's problem this solves: an unsaved canvas cannot be walked by the
|
||||
* player runtime, which resolves everything from the stored document. The
|
||||
* preview therefore replays the graph on the client and asks the server only
|
||||
* what it cannot know locally: the player's flag values.
|
||||
*
|
||||
* Nothing here writes. Effects are described, never applied, so previewing a
|
||||
* draft cannot grant a flag or send a notification.
|
||||
*/
|
||||
|
||||
import type { DialogueCondition, DialogueNode, DialogueNext, NpcDialogueEffect } from "./dialogue";
|
||||
|
||||
/** What a choice node offers, as the preview should show it. */
|
||||
export interface PreviewChoice {
|
||||
/** Position among the node's choices, which is the runtime's index. */
|
||||
index: number;
|
||||
label: string;
|
||||
/** Where it goes, or null when the author never wired it. */
|
||||
target: string | null;
|
||||
/** Gate text for the author when the choice is conditional. */
|
||||
conditionNote: string | null;
|
||||
/** Shown-but-unavailable because its `once` flag already fired this run. */
|
||||
once: boolean;
|
||||
}
|
||||
|
||||
function conditionValue(condition: DialogueCondition): string {
|
||||
if (condition.kind === "group") {
|
||||
const children = condition.children ?? [];
|
||||
return children.map(conditionValue).join(` ${condition.op ?? "and"} `);
|
||||
}
|
||||
const amount = condition.amount ?? 0;
|
||||
const flag = condition.key || "(no key)";
|
||||
switch (condition.op) {
|
||||
case "is_true":
|
||||
return `${flag} is true`;
|
||||
case "is_false":
|
||||
return `${flag} is false`;
|
||||
case "is_defined":
|
||||
return `${flag} is defined`;
|
||||
case "is_undefined":
|
||||
return `${flag} is undefined`;
|
||||
case "gte":
|
||||
return `${flag} >= ${amount}`;
|
||||
case "lte":
|
||||
return `${flag} <= ${amount}`;
|
||||
case "gt":
|
||||
return `${flag} > ${amount}`;
|
||||
case "lt":
|
||||
return `${flag} < ${amount}`;
|
||||
case "eq":
|
||||
return `${flag} = ${amount}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Plain-language summary of a condition, for badges and the preview trace. */
|
||||
export function describeCondition(condition: DialogueCondition | undefined): string | null {
|
||||
if (!condition) return null;
|
||||
return conditionValue(condition);
|
||||
}
|
||||
|
||||
/** The choices on a choice node, in runtime order. */
|
||||
export function previewChoices(node: DialogueNode): PreviewChoice[] {
|
||||
return (node.data.choices ?? []).map((choice: DialogueNext, index) => ({
|
||||
index,
|
||||
label: choice.label?.trim() || "(unlabeled choice)",
|
||||
target: choice.target ?? null,
|
||||
conditionNote: describeCondition(choice.condition),
|
||||
once: choice.once === true,
|
||||
}));
|
||||
}
|
||||
|
||||
/** One line per thing an effect would do, for a dry-run trace. */
|
||||
export function previewEffectLines(effect: NpcDialogueEffect | undefined): string[] {
|
||||
if (!effect) return [];
|
||||
switch (effect.type) {
|
||||
case "flag": {
|
||||
const key = effect.flagKey || "(no key)";
|
||||
switch (effect.flagOp) {
|
||||
case "set_true":
|
||||
return [`Would set flag ${key} to true`];
|
||||
case "set_false":
|
||||
return [`Would set flag ${key} to false`];
|
||||
case "set_number":
|
||||
return [`Would set flag ${key} to ${effect.flagAmount ?? 0}`];
|
||||
case "add":
|
||||
return [`Would add ${effect.flagAmount ?? 0} to flag ${key}`];
|
||||
case "set_text":
|
||||
return [`Would set flag ${key} to text: ${effect.flagText || "(empty)"}`];
|
||||
default:
|
||||
return [`Would write flag ${key}`];
|
||||
}
|
||||
}
|
||||
case "notify":
|
||||
return [`Would notify the player: ${effect.title || effect.message || "(empty)"}`];
|
||||
case "emit":
|
||||
return [`Would write an event: ${effect.message || "(empty)"}`];
|
||||
case "reward":
|
||||
return [`Would reward the player: ${effect.message || "(no detail)"}`];
|
||||
default:
|
||||
return [`Would run an effect (${String((effect as { type?: unknown }).type)})`];
|
||||
}
|
||||
}
|
||||
|
||||
/** The node a hop points at, if it still exists. A dangling target means the
|
||||
* author deleted the card without unwiring it, which is worth showing. */
|
||||
export function nodeForTarget(
|
||||
nodes: readonly DialogueNode[],
|
||||
target: string | undefined | null,
|
||||
): DialogueNode | null {
|
||||
if (!target) return null;
|
||||
return nodes.find((node) => node.id === target) ?? null;
|
||||
}
|
||||
|
||||
/** Everything the preview needs to draw one step. */
|
||||
export interface PreviewStep {
|
||||
node: DialogueNode;
|
||||
/** Body text as authored. Tokens stay visible: the preview does not resolve
|
||||
* them, so the author sees exactly which placeholders the line depends on. */
|
||||
text: string;
|
||||
speaker: string | null;
|
||||
choices: PreviewChoice[];
|
||||
effectLines: string[];
|
||||
/** The single continuation for nodes that only go one way. */
|
||||
nextTarget: string | null;
|
||||
}
|
||||
|
||||
export function previewStep(node: DialogueNode): PreviewStep {
|
||||
const body =
|
||||
node.type === "choice" ? (node.data.leadIn ?? "") : (node.data.body ?? node.data.closing ?? "");
|
||||
const effects = [
|
||||
...previewEffectLines(node.data.effect),
|
||||
...(node.data.attachments?.length
|
||||
? [`${node.data.attachments.length} attachment(s) the player can open`]
|
||||
: []),
|
||||
...(node.data.voice?.filename ? [`Voice clip: ${node.data.voice.filename}`] : []),
|
||||
];
|
||||
const continuation =
|
||||
node.type === "condition" ? null : (node.data.next?.target ?? null);
|
||||
return {
|
||||
node,
|
||||
text: body,
|
||||
speaker: node.data.speaker?.trim() || null,
|
||||
choices: node.type === "choice" ? previewChoices(node) : [],
|
||||
effectLines: effects,
|
||||
nextTarget: continuation,
|
||||
};
|
||||
}
|
||||
|
||||
/** Where a node sends the walker on its own, without the player choosing. */
|
||||
export function automaticTarget(
|
||||
node: DialogueNode,
|
||||
conditionPassed: boolean | null,
|
||||
): { target: string | null; waitingOnGate: boolean } {
|
||||
if (node.type === "condition") {
|
||||
if (conditionPassed === null) return { target: null, waitingOnGate: true };
|
||||
const target = conditionPassed ? node.data.trueTarget : node.data.falseTarget;
|
||||
return { target: target ?? null, waitingOnGate: false };
|
||||
}
|
||||
if (node.type === "choice") return { target: null, waitingOnGate: false };
|
||||
if (node.type === "end") return { target: null, waitingOnGate: false };
|
||||
return { target: node.data.next?.target ?? null, waitingOnGate: false };
|
||||
}
|
||||
|
||||
/** Node types the preview can continue through without the player picking. */
|
||||
export function isTerminal(node: DialogueNode): boolean {
|
||||
return node.type === "end";
|
||||
}
|
||||
88
src/lib/npc-dialogue/typeSound.ts
Normal file
88
src/lib/npc-dialogue/typeSound.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
/**
|
||||
* The sound under a line that is typing itself out.
|
||||
*
|
||||
* Synthesized rather than a file: no asset to ship, no licensing, no fetch on
|
||||
* a page that has to open instantly. Each tick is a short filtered noise burst
|
||||
* (the key) over a low sine body (the case), with a little pitch and volume
|
||||
* jitter so a line of twenty ticks does not sound like a machine.
|
||||
*
|
||||
* Client only, and silent by policy: the caller decides when ticks are allowed
|
||||
* (no recorded clip, sound not muted, typewriter on, motion allowed).
|
||||
*/
|
||||
|
||||
let audioCtx: AudioContext | null = null;
|
||||
let lastTickAt = 0;
|
||||
|
||||
/** Floor between ticks, so a stretched-out line cannot turn into a rattle. */
|
||||
const MIN_TICK_SPACING_MS = 55;
|
||||
|
||||
function getCtx(): AudioContext | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
const AudioCtor =
|
||||
window.AudioContext ??
|
||||
(window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
|
||||
if (!AudioCtor) return null;
|
||||
if (!audioCtx) audioCtx = new AudioCtor();
|
||||
if (audioCtx.state === "suspended") void audioCtx.resume();
|
||||
return audioCtx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and resumes the audio context from a user gesture. Browsers only grant
|
||||
* playback inside one, and the conversation opens on a click, so calling this
|
||||
* there is what lets later ticks be audible at all.
|
||||
*/
|
||||
export function primeTypeSound(): void {
|
||||
getCtx();
|
||||
}
|
||||
|
||||
/** One key tick. Cheap enough to call per arrival; rate limited internally. */
|
||||
export function playTypeTick(): void {
|
||||
const now = typeof performance === "undefined" ? Date.now() : performance.now();
|
||||
if (now - lastTickAt < MIN_TICK_SPACING_MS) return;
|
||||
const ctx = getCtx();
|
||||
if (!ctx) return;
|
||||
lastTickAt = now;
|
||||
|
||||
const pitch = 0.92 + Math.random() * 0.16;
|
||||
const gain = 0.5 + Math.random() * 0.35;
|
||||
const t0 = ctx.currentTime;
|
||||
|
||||
// The click: a very short noise burst, low-passed so it reads as a soft
|
||||
// "thock" rather than a hiss.
|
||||
const burstMs = 14;
|
||||
const frames = Math.max(1, Math.floor((ctx.sampleRate * burstMs) / 1000));
|
||||
const buffer = ctx.createBuffer(1, frames, ctx.sampleRate);
|
||||
const data = buffer.getChannelData(0);
|
||||
for (let i = 0; i < frames; i += 1) {
|
||||
// Decaying envelope inside the buffer keeps the tail from clicking off.
|
||||
data[i] = (Math.random() * 2 - 1) * (1 - i / frames);
|
||||
}
|
||||
const noise = ctx.createBufferSource();
|
||||
noise.buffer = buffer;
|
||||
const filter = ctx.createBiquadFilter();
|
||||
filter.type = "lowpass";
|
||||
filter.frequency.setValueAtTime(1500 * pitch, t0);
|
||||
const noiseGain = ctx.createGain();
|
||||
noiseGain.gain.setValueAtTime(0.0001, t0);
|
||||
noiseGain.gain.exponentialRampToValueAtTime(0.055 * gain, t0 + 0.002);
|
||||
noiseGain.gain.exponentialRampToValueAtTime(0.0001, t0 + burstMs / 1000);
|
||||
noise.connect(filter);
|
||||
filter.connect(noiseGain);
|
||||
noiseGain.connect(ctx.destination);
|
||||
noise.start(t0);
|
||||
|
||||
// The body: a low sine that gives the tick its weight.
|
||||
const body = ctx.createOscillator();
|
||||
const bodyGain = ctx.createGain();
|
||||
body.type = "triangle";
|
||||
body.frequency.setValueAtTime(150 * pitch, t0);
|
||||
body.frequency.exponentialRampToValueAtTime(90 * pitch, t0 + 0.05);
|
||||
bodyGain.gain.setValueAtTime(0.0001, t0);
|
||||
bodyGain.gain.exponentialRampToValueAtTime(0.05 * gain, t0 + 0.004);
|
||||
bodyGain.gain.exponentialRampToValueAtTime(0.0001, t0 + 0.055);
|
||||
body.connect(bodyGain);
|
||||
bodyGain.connect(ctx.destination);
|
||||
body.start(t0);
|
||||
body.stop(t0 + 0.08);
|
||||
}
|
||||
154
src/lib/npc-dialogue/unread.ts
Normal file
154
src/lib/npc-dialogue/unread.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
/**
|
||||
* Which contacts have conversation content this player has never read.
|
||||
*
|
||||
* The read markers `markNpcDialogueNodeRead` writes are per node id, and node
|
||||
* ids live inside `flowData` JSON, so "unread" has to be derived rather than
|
||||
* stored. A conversation counts as unread while any node it can offer has no
|
||||
* marker for this player, which also covers a branch an author added later: the
|
||||
* dot comes back rather than the conversation silently staying "read".
|
||||
*
|
||||
* The directory needs this for every contact at once, so the caller resolves
|
||||
* *which* conversation would be offered (the same selector the offer uses) and
|
||||
* this module answers the per-conversation question. Two queries total, not one
|
||||
* per NPC.
|
||||
*
|
||||
* Server only, in the same sense as `visibility.ts`: the query helper takes a
|
||||
* Payload instance.
|
||||
*/
|
||||
|
||||
import type { Payload } from "payload";
|
||||
|
||||
import { evaluateCondition } from "./flags";
|
||||
import { gateCondition, selectDialogueForUser, type GateCandidate } from "./selection";
|
||||
import { dialogueVisibleTo, type TestingAwareDialogue } from "./visibility";
|
||||
|
||||
/** Node ids in a stored flow, defensively: flowData is author JSON. */
|
||||
export function dialogueNodeIds(flowData: unknown): string[] {
|
||||
const nodes = (flowData as { nodes?: unknown } | null | undefined)?.nodes;
|
||||
if (!Array.isArray(nodes)) return [];
|
||||
const ids: string[] = [];
|
||||
for (const node of nodes) {
|
||||
const id = (node as { id?: unknown } | null | undefined)?.id;
|
||||
if (typeof id === "string" && id.length > 0) ids.push(id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** Node ids in `nodeIds` that this player has not read. */
|
||||
export function unreadNodeIds(
|
||||
nodeIds: readonly string[],
|
||||
readIds: ReadonlySet<string>,
|
||||
): string[] {
|
||||
return nodeIds.filter((id) => !readIds.has(id));
|
||||
}
|
||||
|
||||
/** Whether a conversation still has something this player has not read. */
|
||||
export function isDialogueUnread(
|
||||
nodeIds: readonly string[],
|
||||
readIds: ReadonlySet<string>,
|
||||
): boolean {
|
||||
// An empty conversation cannot be read, so it cannot be unread either.
|
||||
if (nodeIds.length === 0) return false;
|
||||
return unreadNodeIds(nodeIds, readIds).length > 0;
|
||||
}
|
||||
|
||||
/** The part of a conversation doc this module needs. */
|
||||
interface UnreadCandidate extends GateCandidate, TestingAwareDialogue {
|
||||
id: number;
|
||||
npc?: number | { id: number } | null;
|
||||
flowData?: unknown;
|
||||
}
|
||||
|
||||
function npcIdOf(value: UnreadCandidate["npc"]): 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* NPC ids (from `npcIds`) whose offered conversation has unread nodes.
|
||||
*
|
||||
* Callers pass only contacts that may start a conversation at all
|
||||
* (`game-npcs.canMessage`, the same switch the contact page checks before it
|
||||
* offers Converse); a contact that cannot be talked to must not show a dot.
|
||||
*
|
||||
* The offered conversation is resolved exactly as the contact page resolves it
|
||||
* (`selectDialogueForUser` against the player's flags), so the dot agrees with
|
||||
* the Converse button rather than advertising a conversation the gate hides.
|
||||
*/
|
||||
export async function loadUnreadNpcIds(
|
||||
payload: Payload,
|
||||
options: {
|
||||
npcIds: readonly number[];
|
||||
userId?: number | null;
|
||||
canSeeTesting: boolean;
|
||||
},
|
||||
): Promise<number[]> {
|
||||
const { npcIds, userId, canSeeTesting } = options;
|
||||
if (!userId || npcIds.length === 0) return [];
|
||||
|
||||
const dialogues = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { in: [...npcIds] } },
|
||||
limit: 400,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
const candidates = (dialogues.docs as unknown as UnreadCandidate[]).filter((doc) =>
|
||||
dialogueVisibleTo(doc, canSeeTesting),
|
||||
);
|
||||
if (candidates.length === 0) return [];
|
||||
|
||||
const byNpc = new Map<number, UnreadCandidate[]>();
|
||||
for (const doc of candidates) {
|
||||
const npcId = npcIdOf(doc.npc);
|
||||
if (npcId === null) continue;
|
||||
const list = byNpc.get(npcId) ?? [];
|
||||
list.push(doc);
|
||||
byNpc.set(npcId, list);
|
||||
}
|
||||
|
||||
const offered = new Map<number, UnreadCandidate>();
|
||||
for (const [npcId, docs] of byNpc) {
|
||||
const chosen = await selectDialogueForUser(docs, async (condition) => {
|
||||
return evaluateCondition(payload, userId, condition);
|
||||
});
|
||||
if (chosen) offered.set(npcId, chosen);
|
||||
}
|
||||
if (offered.size === 0) return [];
|
||||
|
||||
const states = await payload.find({
|
||||
collection: "npc-dialogue-states",
|
||||
where: {
|
||||
user: { equals: userId },
|
||||
dialogue: { in: [...offered.values()].map((doc) => doc.id) },
|
||||
},
|
||||
limit: 2000,
|
||||
depth: 0,
|
||||
pagination: false,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
const readByDialogue = new Map<number, Set<string>>();
|
||||
for (const state of states.docs as unknown as { dialogue?: unknown; nodeId?: unknown }[]) {
|
||||
const dialogue =
|
||||
typeof state.dialogue === "number"
|
||||
? state.dialogue
|
||||
: (state.dialogue as { id?: unknown } | null)?.id;
|
||||
if (typeof dialogue !== "number" || typeof state.nodeId !== "string") continue;
|
||||
const set = readByDialogue.get(dialogue) ?? new Set<string>();
|
||||
set.add(state.nodeId);
|
||||
readByDialogue.set(dialogue, set);
|
||||
}
|
||||
|
||||
const unread: number[] = [];
|
||||
for (const [npcId, doc] of offered) {
|
||||
const readIds = readByDialogue.get(doc.id) ?? new Set<string>();
|
||||
if (isDialogueUnread(dialogueNodeIds(doc.flowData), readIds)) unread.push(npcId);
|
||||
}
|
||||
return unread;
|
||||
}
|
||||
47149
src/migrations/20261125_000236_add_dialogue_typing_sound_preference.json
Normal file
47149
src/migrations/20261125_000236_add_dialogue_typing_sound_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_typewriter_sound" 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_sound";`)
|
||||
}
|
||||
|
|
@ -170,6 +170,7 @@ import * as migration_20261124_223219_add_defined_condition_ops from './20261124
|
|||
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';
|
||||
import * as migration_20261125_000236_add_dialogue_typing_sound_preference from './20261125_000236_add_dialogue_typing_sound_preference';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -1030,6 +1031,11 @@ export const migrations = [
|
|||
{
|
||||
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'
|
||||
name: '20261124_232253_add_npc_dialogue_testing_flag',
|
||||
},
|
||||
{
|
||||
up: migration_20261125_000236_add_dialogue_typing_sound_preference.up,
|
||||
down: migration_20261125_000236_add_dialogue_typing_sound_preference.down,
|
||||
name: '20261125_000236_add_dialogue_typing_sound_preference'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -557,6 +557,10 @@ export interface User {
|
|||
* 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;
|
||||
/**
|
||||
* A soft key tick under lines that type out. Silent on lines with a recorded voice, and muted by the speaker button in a conversation header.
|
||||
*/
|
||||
typewriterSound?: boolean | null;
|
||||
/**
|
||||
* Recorded lines play as they arrive. You can also mute for the rest of a conversation with the speaker button in its header.
|
||||
*/
|
||||
|
|
@ -10498,6 +10502,7 @@ export interface UsersSelect<T extends boolean = true> {
|
|||
| T
|
||||
| {
|
||||
typewriter?: T;
|
||||
typewriterSound?: T;
|
||||
voice?: T;
|
||||
};
|
||||
discord?:
|
||||
|
|
|
|||
46
tests/int/npc-dialogue-keys.int.spec.ts
Normal file
46
tests/int/npc-dialogue-keys.int.spec.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { choiceIndexFromKey, choiceShortcutLabel, isSkipKey } from "@/lib/npc-dialogue/keys";
|
||||
|
||||
/**
|
||||
* Digit shortcuts for choices. The number shown on a button and the number the
|
||||
* keyboard accepts must agree, and a locked choice must not shift the numbering,
|
||||
* so both are computed from the selectable list rather than the server index.
|
||||
*/
|
||||
describe("conversation keyboard picks", () => {
|
||||
it("maps 1-9 onto the selectable choices", () => {
|
||||
expect(choiceIndexFromKey("1", 4)).toBe(0);
|
||||
expect(choiceIndexFromKey("2", 4)).toBe(1);
|
||||
expect(choiceIndexFromKey("4", 4)).toBe(3);
|
||||
});
|
||||
|
||||
it("ignores digits past the number of choices", () => {
|
||||
expect(choiceIndexFromKey("5", 4)).toBeNull();
|
||||
expect(choiceIndexFromKey("1", 0)).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores anything that is not a digit 1-9", () => {
|
||||
for (const key of ["0", "a", "Enter", " ", "Escape", "ArrowDown", "10"]) {
|
||||
expect(choiceIndexFromKey(key, 9)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("labels choices with the same numbers the keyboard accepts", () => {
|
||||
expect([0, 1, 2].map((i) => choiceShortcutLabel(i))).toEqual(["1", "2", "3"]);
|
||||
expect(choiceShortcutLabel(8)).toBe("9");
|
||||
expect(choiceShortcutLabel(9)).toBeNull();
|
||||
expect(choiceShortcutLabel(-1)).toBeNull();
|
||||
// Every label the button shows resolves to the same choice on keypress.
|
||||
for (let i = 0; i < 9; i += 1) {
|
||||
expect(choiceIndexFromKey(choiceShortcutLabel(i) as string, 9)).toBe(i);
|
||||
}
|
||||
});
|
||||
|
||||
it("treats only Enter and Space as skip keys", () => {
|
||||
expect(isSkipKey("Enter")).toBe(true);
|
||||
expect(isSkipKey(" ")).toBe(true);
|
||||
expect(isSkipKey("a")).toBe(false);
|
||||
expect(isSkipKey("Escape")).toBe(false);
|
||||
});
|
||||
});
|
||||
168
tests/int/npc-dialogue-pacing.int.spec.ts
Normal file
168
tests/int/npc-dialogue-pacing.int.spec.ts
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
BASE_UNIT_MS,
|
||||
DEFAULT_PACING_PRESET,
|
||||
PACING_PRESETS,
|
||||
beatMs,
|
||||
buildRevealSchedule,
|
||||
scaleSchedule,
|
||||
shownAt,
|
||||
} from "@/lib/npc-dialogue/pacing";
|
||||
|
||||
/**
|
||||
* The typing rhythm. A plain clock cannot pause at a comma, so the reveal runs
|
||||
* off a schedule: each visible unit has its own cost plus a pause after
|
||||
* punctuation and line breaks. These tests pin the shape of that schedule, not
|
||||
* the exact milliseconds of every character, so tuning a preset does not turn
|
||||
* into a wall of rewritten assertions.
|
||||
*/
|
||||
|
||||
/** How long unit `i` waits before the next one starts. */
|
||||
function gapAfter(arrival: readonly number[], i: number): number {
|
||||
return arrival[i + 1] - arrival[i];
|
||||
}
|
||||
|
||||
const sample = "Hold, trooper. The road ahead is watched.";
|
||||
|
||||
describe("reveal pacing", () => {
|
||||
it("costs a base unit per visible character when there is no punctuation", () => {
|
||||
const schedule = buildRevealSchedule("abc");
|
||||
expect(schedule.arrival).toEqual([0, BASE_UNIT_MS, BASE_UNIT_MS * 2]);
|
||||
// The last unit's own cost finishes the line; no trailing pause is waited on.
|
||||
expect(schedule.total).toBe(BASE_UNIT_MS * 3);
|
||||
});
|
||||
|
||||
it("pauses after a comma, longer after a sentence end, longest at a break", () => {
|
||||
const profile = PACING_PRESETS[DEFAULT_PACING_PRESET];
|
||||
const schedule = buildRevealSchedule("a,b. c\nd");
|
||||
const text = schedule.text;
|
||||
const at = (char: string, from = 0) => text.indexOf(char, from);
|
||||
|
||||
// The unit right after each mark waits longer than a plain neighbour.
|
||||
expect(gapAfter(schedule.arrival, at(","))).toBe(BASE_UNIT_MS + profile.clauseMs);
|
||||
expect(gapAfter(schedule.arrival, at("."))).toBe(BASE_UNIT_MS + profile.sentenceMs);
|
||||
expect(gapAfter(schedule.arrival, at("\n"))).toBe(BASE_UNIT_MS + profile.newlineMs);
|
||||
expect(gapAfter(schedule.arrival, at("a"))).toBe(BASE_UNIT_MS);
|
||||
|
||||
expect(profile.clauseMs).toBeLessThan(profile.sentenceMs);
|
||||
expect(profile.sentenceMs).toBeLessThan(profile.newlineMs);
|
||||
expect(profile.newlineMs).toBeLessThan(profile.paragraphMs);
|
||||
});
|
||||
|
||||
it("treats a blank line as one paragraph pause, not two line pauses", () => {
|
||||
const profile = PACING_PRESETS[DEFAULT_PACING_PRESET];
|
||||
const schedule = buildRevealSchedule("a\n\nb");
|
||||
// Units: a, \n, \n, b. The first break carries the paragraph pause, the
|
||||
// second is free, and the character before a break charges nothing, so the
|
||||
// break is never paid for twice.
|
||||
expect(gapAfter(schedule.arrival, 0)).toBe(BASE_UNIT_MS);
|
||||
expect(gapAfter(schedule.arrival, 1)).toBe(BASE_UNIT_MS + profile.paragraphMs);
|
||||
expect(gapAfter(schedule.arrival, 2)).toBe(BASE_UNIT_MS);
|
||||
});
|
||||
|
||||
it("does not add a punctuation pause before a line break", () => {
|
||||
// "End." then a newline: the break supplies the pause, so the sentence mark
|
||||
// must not charge again on top of it.
|
||||
const profile = PACING_PRESETS[DEFAULT_PACING_PRESET];
|
||||
const schedule = buildRevealSchedule("End.\nNext");
|
||||
const period = schedule.text.indexOf(".");
|
||||
expect(gapAfter(schedule.arrival, period)).toBe(BASE_UNIT_MS);
|
||||
const newline = schedule.text.indexOf("\n");
|
||||
expect(gapAfter(schedule.arrival, newline)).toBe(BASE_UNIT_MS + profile.newlineMs);
|
||||
});
|
||||
|
||||
it("charges the pause after a closing quote, not inside it", () => {
|
||||
const profile = PACING_PRESETS[DEFAULT_PACING_PRESET];
|
||||
const schedule = buildRevealSchedule('"Fine." Then');
|
||||
const quote = schedule.text.indexOf('"', 1);
|
||||
expect(gapAfter(schedule.arrival, quote)).toBe(BASE_UNIT_MS + profile.sentenceMs);
|
||||
});
|
||||
|
||||
it("leaves a thousands separator inside a number unpaused", () => {
|
||||
const profile = PACING_PRESETS[DEFAULT_PACING_PRESET];
|
||||
const schedule = buildRevealSchedule("1,000 rounds");
|
||||
const comma = schedule.text.indexOf(",");
|
||||
expect(gapAfter(schedule.arrival, comma)).toBe(BASE_UNIT_MS);
|
||||
// A comma between a digit and a letter still reads as a clause break.
|
||||
const prose = buildRevealSchedule("50, or so");
|
||||
expect(gapAfter(prose.arrival, prose.text.indexOf(","))).toBe(
|
||||
BASE_UNIT_MS + profile.clauseMs,
|
||||
);
|
||||
});
|
||||
|
||||
it("scales to a target duration without changing the rhythm", () => {
|
||||
const schedule = buildRevealSchedule(sample);
|
||||
const doubled = scaleSchedule(schedule, schedule.total * 2);
|
||||
const plain = scaleSchedule(schedule, schedule.total);
|
||||
|
||||
expect(plain.durationMs).toBeCloseTo(schedule.total, 5);
|
||||
// Every arrival moves by the same factor, so a long line paced to a voice
|
||||
// clip keeps its pauses in proportion instead of flattening them.
|
||||
const ratio = doubled.arrivalMs[5] / plain.arrivalMs[5];
|
||||
expect(ratio).toBeCloseTo(2, 5);
|
||||
expect(doubled.tickMs[0] / plain.tickMs[0]).toBeCloseTo(2, 5);
|
||||
});
|
||||
|
||||
it("counts arrivals the same way the reveal loop does", () => {
|
||||
const schedule = buildRevealSchedule(sample);
|
||||
const scaled = scaleSchedule(schedule, schedule.total);
|
||||
const last = scaled.arrivalMs[scaled.arrivalMs.length - 1];
|
||||
|
||||
expect(shownAt(scaled.arrivalMs, -1)).toBe(0);
|
||||
expect(shownAt(scaled.arrivalMs, 0)).toBe(1);
|
||||
// The last unit arrives a base cost before the line is "done", so the line
|
||||
// never waits on a trailing pause once every character is visible.
|
||||
expect(last).toBeLessThan(scaled.durationMs);
|
||||
expect(shownAt(scaled.arrivalMs, last - 1)).toBe(schedule.arrival.length - 1);
|
||||
expect(shownAt(scaled.arrivalMs, last)).toBe(schedule.arrival.length);
|
||||
});
|
||||
|
||||
it("places ticks on visible characters, spaced out and ascending", () => {
|
||||
const schedule = buildRevealSchedule(sample, "natural");
|
||||
expect(schedule.ticks.length).toBeGreaterThan(3);
|
||||
|
||||
for (let i = 1; i < schedule.ticks.length; i += 1) {
|
||||
expect(schedule.ticks[i]).toBeGreaterThan(schedule.ticks[i - 1]);
|
||||
expect(schedule.ticks[i] - schedule.ticks[i - 1]).toBeGreaterThanOrEqual(95);
|
||||
}
|
||||
// A tick only ever lands on a unit that actually appears on screen.
|
||||
for (const tick of schedule.ticks) {
|
||||
const index = schedule.arrival.indexOf(tick);
|
||||
expect(index).toBeGreaterThanOrEqual(0);
|
||||
expect(schedule.text[index].trim().length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a line's rhythm stable across rebuilds", () => {
|
||||
// Seeded from the text, so a re-render cannot re-roll the ticks mid-line.
|
||||
const first = buildRevealSchedule(sample);
|
||||
const second = buildRevealSchedule(sample);
|
||||
expect(second.ticks).toEqual(first.ticks);
|
||||
expect(buildRevealSchedule(`${sample}?`).ticks).not.toEqual(first.ticks);
|
||||
});
|
||||
|
||||
it("has nothing to schedule for an empty line", () => {
|
||||
const empty = buildRevealSchedule("");
|
||||
expect(empty).toEqual({ arrival: [], total: 0, ticks: [], text: "" });
|
||||
expect(scaleSchedule(empty, 900)).toEqual({ arrivalMs: [], tickMs: [], durationMs: 900 });
|
||||
});
|
||||
|
||||
it("follows the preset it is given, and falls back to natural", () => {
|
||||
const subtle = PACING_PRESETS.subtle;
|
||||
const pronounced = PACING_PRESETS.pronounced;
|
||||
const text = "Hold, trooper.";
|
||||
const comma = text.indexOf(",");
|
||||
|
||||
expect(gapAfter(buildRevealSchedule(text, "subtle").arrival, comma)).toBe(
|
||||
BASE_UNIT_MS + subtle.clauseMs,
|
||||
);
|
||||
expect(gapAfter(buildRevealSchedule(text, "pronounced").arrival, comma)).toBe(
|
||||
BASE_UNIT_MS + pronounced.clauseMs,
|
||||
);
|
||||
expect(beatMs("subtle")).toBeLessThan(beatMs("natural"));
|
||||
expect(beatMs("natural")).toBeLessThan(beatMs("pronounced"));
|
||||
expect(beatMs("unknown" as never)).toBe(beatMs("natural"));
|
||||
});
|
||||
});
|
||||
130
tests/int/npc-dialogue-preview.int.spec.ts
Normal file
130
tests/int/npc-dialogue-preview.int.spec.ts
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
|
||||
import {
|
||||
automaticTarget,
|
||||
describeCondition,
|
||||
isTerminal,
|
||||
nodeForTarget,
|
||||
previewChoices,
|
||||
previewEffectLines,
|
||||
previewStep,
|
||||
} from "@/lib/npc-dialogue/preview";
|
||||
|
||||
/**
|
||||
* The editor's draft preview walks an unsaved graph, so its reading of the
|
||||
* author's nodes has to match the runtime's: same choice order, same branch for
|
||||
* a condition, and effects described rather than applied.
|
||||
*/
|
||||
function node(partial: Partial<DialogueNode> & { id: string; type: DialogueNode["type"] }): DialogueNode {
|
||||
return {
|
||||
position: { x: 0, y: 0 },
|
||||
data: {},
|
||||
...partial,
|
||||
} as DialogueNode;
|
||||
}
|
||||
|
||||
describe("draft preview reading the graph", () => {
|
||||
it("lists choices in runtime order with their gate text", () => {
|
||||
const choice = node({
|
||||
id: "c1",
|
||||
type: "choice",
|
||||
data: {
|
||||
leadIn: "Pick one.",
|
||||
choices: [
|
||||
{ label: "First", target: "a" },
|
||||
{ label: "", target: "b" },
|
||||
{ label: "Third", target: "c", condition: { kind: "flag", key: "rank", op: "gt", amount: 2 } },
|
||||
],
|
||||
},
|
||||
});
|
||||
const choices = previewChoices(choice);
|
||||
expect(choices.map((c) => c.index)).toEqual([0, 1, 2]);
|
||||
expect(choices[1]?.label).toBe("(unlabeled choice)");
|
||||
expect(choices[2]?.conditionNote).toBe("rank > 2");
|
||||
});
|
||||
|
||||
it("describes condition groups in plain language", () => {
|
||||
expect(
|
||||
describeCondition({
|
||||
kind: "group",
|
||||
op: "and",
|
||||
children: [
|
||||
{ kind: "flag", key: "a", op: "is_true" },
|
||||
{ kind: "flag", key: "b", op: "is_undefined" },
|
||||
],
|
||||
}),
|
||||
).toBe("a is true and b is undefined");
|
||||
expect(describeCondition(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it("sends a condition node down the branch its answer picks", () => {
|
||||
const condition = node({
|
||||
id: "k1",
|
||||
type: "condition",
|
||||
data: { condition: { kind: "flag", key: "a", op: "is_true" }, trueTarget: "yes", falseTarget: "no" },
|
||||
});
|
||||
expect(automaticTarget(condition, null)).toEqual({ target: null, waitingOnGate: true });
|
||||
expect(automaticTarget(condition, true)).toEqual({ target: "yes", waitingOnGate: false });
|
||||
expect(automaticTarget(condition, false)).toEqual({ target: "no", waitingOnGate: false });
|
||||
});
|
||||
|
||||
it("keeps the single continuation for linear nodes", () => {
|
||||
const dialogue = node({ id: "d1", type: "dialogue", data: { body: "Hi", next: { target: "d2" } } });
|
||||
expect(automaticTarget(dialogue, null).target).toBe("d2");
|
||||
expect(automaticTarget(node({ id: "e1", type: "end", data: {} }), null).target).toBeNull();
|
||||
});
|
||||
|
||||
it("only treats end nodes as terminal", () => {
|
||||
expect(isTerminal(node({ id: "e1", type: "end", data: {} }))).toBe(true);
|
||||
expect(isTerminal(node({ id: "d1", type: "dialogue", data: {} }))).toBe(false);
|
||||
expect(isTerminal(node({ id: "y1", type: "delay", data: {} }))).toBe(false);
|
||||
});
|
||||
|
||||
it("describes flag effects by their actual write, never as applied", () => {
|
||||
expect(previewEffectLines({ type: "flag", flagKey: "trust", flagOp: "set_number", flagAmount: 3 })).toEqual([
|
||||
"Would set flag trust to 3",
|
||||
]);
|
||||
expect(previewEffectLines({ type: "flag", flagKey: "trust", flagOp: "add", flagAmount: 2 })).toEqual([
|
||||
"Would add 2 to flag trust",
|
||||
]);
|
||||
expect(previewEffectLines({ type: "notify", title: "Heads up" })).toEqual([
|
||||
"Would notify the player: Heads up",
|
||||
]);
|
||||
expect(previewEffectLines(undefined)).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports a step's text, attachments and voice without resolving them", () => {
|
||||
const step = previewStep(
|
||||
node({
|
||||
id: "d1",
|
||||
type: "dialogue",
|
||||
data: {
|
||||
body: "You owe {{debt}} credits.",
|
||||
speaker: "Quartermaster",
|
||||
attachments: [{ mediaId: 1 }],
|
||||
voice: { mediaId: 2, filename: "line.mp3" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(step.text).toBe("You owe {{debt}} credits.");
|
||||
expect(step.speaker).toBe("Quartermaster");
|
||||
expect(step.effectLines).toEqual([
|
||||
"1 attachment(s) the player can open",
|
||||
"Voice clip: line.mp3",
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses the closing text for an end node and the lead-in for a choice", () => {
|
||||
expect(previewStep(node({ id: "e1", type: "end", data: { closing: "Goodbye." } })).text).toBe("Goodbye.");
|
||||
expect(previewStep(node({ id: "c1", type: "choice", data: { leadIn: "Well?" } })).text).toBe("Well?");
|
||||
});
|
||||
|
||||
it("finds a target only when the card still exists", () => {
|
||||
const nodes = [node({ id: "a", type: "dialogue", data: {} })];
|
||||
expect(nodeForTarget(nodes, "a")?.id).toBe("a");
|
||||
expect(nodeForTarget(nodes, "gone")).toBeNull();
|
||||
expect(nodeForTarget(nodes, undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
@ -4,7 +4,7 @@ import { renderToStaticMarkup } from "react-dom/server";
|
|||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DialogueText, visibleLength } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { DialogueText, visibleLength, visibleText } from "@/lib/npc-dialogue/DialogueText";
|
||||
|
||||
/**
|
||||
* The reveal is what makes a conversation line type itself out. It must never
|
||||
|
|
@ -59,4 +59,32 @@ describe("DialogueText reveal", () => {
|
|||
it("renders everything when no reveal is given", () => {
|
||||
expect(textOf(render("Plain **line**"))).toBe("Plain line");
|
||||
});
|
||||
|
||||
it("flattens the same units the reveal counts", () => {
|
||||
// The pacing schedule is built from `visibleText`, so the two must agree
|
||||
// character for character; a disagreement would make a line finish early or
|
||||
// hang one unit short.
|
||||
const cases = [
|
||||
"Careful, **{amber}the trail{/}** is watched.",
|
||||
"- one\n- two\n\n1. three",
|
||||
"Wait {cd|done} now",
|
||||
"Look  here",
|
||||
"A `code run` inside prose.",
|
||||
"Line one\nline two",
|
||||
"",
|
||||
];
|
||||
for (const source of cases) {
|
||||
expect(visibleText(source).length).toBe(visibleLength(source));
|
||||
}
|
||||
expect(visibleText("Careful, **{amber}the trail{/}** is watched.")).toBe(
|
||||
"Careful, the trail is watched.",
|
||||
);
|
||||
// A list marker is formatting, not text: it costs nothing and is not shown.
|
||||
expect(visibleText("- one")).toBe("one");
|
||||
});
|
||||
|
||||
it("gives an image and a countdown one placeholder unit each", () => {
|
||||
expect(visibleText("Wait {cd|done} now")).toHaveLength("Wait now".length + 1);
|
||||
expect(visibleText("Look  here")).toHaveLength("Look here".length + 1);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
51
tests/int/npc-dialogue-unread.int.spec.ts
Normal file
51
tests/int/npc-dialogue-unread.int.spec.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { dialogueNodeIds, isDialogueUnread, unreadNodeIds } from "@/lib/npc-dialogue/unread";
|
||||
|
||||
/**
|
||||
* "Unread" is derived from per-node read markers inside flowData JSON. These
|
||||
* cover the shapes an author's canvas can actually produce, including a
|
||||
* half-written flow, since the directory reads every conversation's flow.
|
||||
*/
|
||||
describe("conversation unread derivation", () => {
|
||||
it("reads node ids out of a stored flow", () => {
|
||||
const flow = {
|
||||
nodes: [{ id: "n1" }, { id: "n2" }, { id: "" }, { notAnId: true }, null],
|
||||
edges: [],
|
||||
};
|
||||
expect(dialogueNodeIds(flow)).toEqual(["n1", "n2"]);
|
||||
});
|
||||
|
||||
it("treats a missing or broken flow as having no nodes", () => {
|
||||
expect(dialogueNodeIds(null)).toEqual([]);
|
||||
expect(dialogueNodeIds(undefined)).toEqual([]);
|
||||
expect(dialogueNodeIds({})).toEqual([]);
|
||||
expect(dialogueNodeIds({ nodes: "nope" })).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports the nodes this player has not read", () => {
|
||||
const nodeIds = ["n1", "n2", "n3"];
|
||||
expect(unreadNodeIds(nodeIds, new Set(["n1", "n3"]))).toEqual(["n2"]);
|
||||
expect(unreadNodeIds(nodeIds, new Set(["n1", "n2", "n3"]))).toEqual([]);
|
||||
expect(unreadNodeIds(nodeIds, new Set())).toEqual(["n1", "n2", "n3"]);
|
||||
});
|
||||
|
||||
it("is unread while any node is unread, and clean once all are", () => {
|
||||
const nodeIds = ["n1", "n2"];
|
||||
expect(isDialogueUnread(nodeIds, new Set(["n1"]))).toBe(true);
|
||||
expect(isDialogueUnread(nodeIds, new Set(["n1", "n2"]))).toBe(false);
|
||||
});
|
||||
|
||||
it("never calls an empty conversation unread", () => {
|
||||
expect(isDialogueUnread([], new Set())).toBe(false);
|
||||
});
|
||||
|
||||
it("counts read markers for nodes that no longer exist as harmless", () => {
|
||||
// An author deleted a branch after the player read it. The stale marker
|
||||
// must not make the conversation look read, and must not make it look
|
||||
// unread either: only node ids still in the flow are considered.
|
||||
expect(isDialogueUnread(["n1"], new Set(["deleted-node"]))).toBe(true);
|
||||
expect(isDialogueUnread(["n1"], new Set(["n1", "deleted-node"]))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -44,6 +44,7 @@ describe("PreferencesForm", () => {
|
|||
discordMutedTypes: [],
|
||||
xpDisplayMini: false,
|
||||
conversationTypewriter: "default",
|
||||
conversationTypewriterSound: true,
|
||||
conversationVoice: true,
|
||||
}),
|
||||
);
|
||||
|
|
@ -54,6 +55,7 @@ describe("PreferencesForm", () => {
|
|||
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: "Play a typing sound in conversations" }));
|
||||
fireEvent.click(screen.getByRole("switch", { name: "Enable Discord notifications" }));
|
||||
const discordMarketOffer = document.getElementById("discord-market-offer");
|
||||
if (!(discordMarketOffer instanceof HTMLElement)) {
|
||||
|
|
@ -74,6 +76,7 @@ describe("PreferencesForm", () => {
|
|||
discordMutedTypes: ["market:offer"],
|
||||
xpDisplayMini: true,
|
||||
conversationTypewriter: "off",
|
||||
conversationTypewriterSound: false,
|
||||
conversationVoice: false,
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue