1
0
Fork 0

feat(npc-dialogue): natural typing rhythm, a beat between lines, a typing sound

The reveal was one linear clock, so every character cost the same and a comma
had nowhere to breathe. It now runs off a schedule: each visible unit costs
BASE_UNIT_MS plus a pause after it, longer at a sentence end and longest at a
line or paragraph break. Pauses never stack (a break after a full stop owns the
pause) and a comma inside a number is not a clause. The schedule is built in
relative units and scaled to the target duration, so a line paced to a recorded
clip keeps the rhythm instead of flattening it.

Between two spoken lines there is now a beat with the speaker's typing dots, and
clicking during it starts the next line at once. The opening line of a cascade
gets no beat.

The typing sound is synthesized (one tick per 55ms at most) from precomputed,
seeded tick times, so a re-render cannot re-roll the rhythm. It stays silent on a
line with a recorded clip, when the header mute is on, and under reduced motion.
It follows a new account preference, users.preferences.dialogue.typewriterSound,
separate from the voice switch, with a migration.

visibleLength is now defined as visibleText(text).length, so the schedule and the
renderer cannot disagree about how long a line is.
This commit is contained in:
Jason Fraley 2026-11-24 19:20:11 -05:00
parent 441c0dbac3
commit 464ba2d5d4
19 changed files with 47873 additions and 15 deletions

View file

@ -211,6 +211,7 @@ export async function updatePreferences(input: {
discordMutedTypes: string[]; discordMutedTypes: string[];
xpDisplayMini: boolean; xpDisplayMini: boolean;
conversationTypewriter: "default" | "on" | "off"; conversationTypewriter: "default" | "on" | "off";
conversationTypewriterSound: boolean;
conversationVoice: boolean; conversationVoice: boolean;
}): Promise<ActionResult> { }): Promise<ActionResult> {
try { try {
@ -250,6 +251,7 @@ export async function updatePreferences(input: {
}, },
dialogue: { dialogue: {
typewriter: input.conversationTypewriter, typewriter: input.conversationTypewriter,
typewriterSound: input.conversationTypewriterSound,
voice: input.conversationVoice, voice: input.conversationVoice,
}, },
discord: { discord: {

View file

@ -182,6 +182,9 @@ export default async function AccountPage() {
showCallsign={fullUser.preferences?.display?.showCallsign ?? false} showCallsign={fullUser.preferences?.display?.showCallsign ?? false}
showVersionOverlay={fullUser.preferences?.display?.showVersionOverlay ?? true} showVersionOverlay={fullUser.preferences?.display?.showVersionOverlay ?? true}
conversationTypewriter={fullUser.preferences?.dialogue?.typewriter ?? "default"} conversationTypewriter={fullUser.preferences?.dialogue?.typewriter ?? "default"}
conversationTypewriterSound={
fullUser.preferences?.dialogue?.typewriterSound !== false
}
conversationVoice={fullUser.preferences?.dialogue?.voice !== false} conversationVoice={fullUser.preferences?.dialogue?.voice !== false}
showBackgroundTexture={fullUser.preferences?.display?.showBackgroundTexture ?? true} showBackgroundTexture={fullUser.preferences?.display?.showBackgroundTexture ?? true}
leadOrActual={fullUser.preferences?.display?.leadOrActual ?? "lead"} leadOrActual={fullUser.preferences?.display?.leadOrActual ?? "lead"}

View file

@ -188,6 +188,11 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
const voiceEnabled = dialogue const voiceEnabled = dialogue
? (isPayloadUser(user) ? user.preferences?.dialogue?.voice : undefined) !== false ? (isPayloadUser(user) ? user.preferences?.dialogue?.voice : undefined) !== false
: 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 ( return (
<div className="p-5 flex flex-col gap-6"> <div className="p-5 flex flex-col gap-6">
@ -200,6 +205,7 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
dialogue={dialogue} dialogue={dialogue}
initialSeenNodeIds={seenNodeIds} initialSeenNodeIds={seenNodeIds}
typewriter={typewriterEnabled} typewriter={typewriterEnabled}
typewriterSound={typewriterSoundEnabled}
voice={voiceEnabled} voice={voiceEnabled}
/> />
} }

View file

@ -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.", "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", name: "voice",
label: "Play voice clips in conversations", label: "Play voice clips in conversations",

View file

@ -118,6 +118,7 @@ export function CommandPalette({
discordMutedTypes: preferences?.discord?.mutedTypes ?? [], discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
xpDisplayMini: preferences?.display?.xpDisplayMini ?? false, xpDisplayMini: preferences?.display?.xpDisplayMini ?? false,
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default", conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
conversationTypewriterSound: preferences?.dialogue?.typewriterSound !== false,
conversationVoice: preferences?.dialogue?.voice !== false, conversationVoice: preferences?.dialogue?.voice !== false,
}); });
if (result.success) { if (result.success) {
@ -140,6 +141,7 @@ export function CommandPalette({
discordMutedTypes: preferences?.discord?.mutedTypes ?? [], discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
xpDisplayMini: preferences?.display?.xpDisplayMini ?? false, xpDisplayMini: preferences?.display?.xpDisplayMini ?? false,
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default", conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
conversationTypewriterSound: preferences?.dialogue?.typewriterSound !== false,
conversationVoice: preferences?.dialogue?.voice !== false, conversationVoice: preferences?.dialogue?.voice !== false,
}); });
if (result.success) { if (result.success) {
@ -162,6 +164,7 @@ export function CommandPalette({
discordMutedTypes: preferences?.discord?.mutedTypes ?? [], discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
xpDisplayMini: !(preferences?.display?.xpDisplayMini ?? false), xpDisplayMini: !(preferences?.display?.xpDisplayMini ?? false),
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default", conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
conversationTypewriterSound: preferences?.dialogue?.typewriterSound !== false,
conversationVoice: preferences?.dialogue?.voice !== false, conversationVoice: preferences?.dialogue?.voice !== false,
}); });
if (result.success) { if (result.success) {

View file

@ -24,6 +24,8 @@ interface PreferencesFormProps {
readonly xpDisplayMini: boolean; readonly xpDisplayMini: boolean;
/** Stored choice for the NPC conversation typing animation. */ /** Stored choice for the NPC conversation typing animation. */
readonly conversationTypewriter: "default" | "on" | "off"; 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. */ /** Whether recorded voice clips play in conversations. */
readonly conversationVoice: boolean; readonly conversationVoice: boolean;
} }
@ -39,6 +41,7 @@ export function PreferencesForm({
discordMutedTypes: initialDiscordMutedTypes, discordMutedTypes: initialDiscordMutedTypes,
xpDisplayMini: initialXPDisplayMini, xpDisplayMini: initialXPDisplayMini,
conversationTypewriter: initialConversationTypewriter, conversationTypewriter: initialConversationTypewriter,
conversationTypewriterSound: initialConversationTypewriterSound,
conversationVoice: initialConversationVoice, conversationVoice: initialConversationVoice,
}: PreferencesFormProps) { }: PreferencesFormProps) {
const router = useRouter(); const router = useRouter();
@ -57,6 +60,9 @@ export function PreferencesForm({
"default" | "on" | "off" "default" | "on" | "off"
>(initialConversationTypewriter); >(initialConversationTypewriter);
const [conversationVoice, setConversationVoice] = useState(initialConversationVoice); const [conversationVoice, setConversationVoice] = useState(initialConversationVoice);
const [conversationTypewriterSound, setConversationTypewriterSound] = useState(
initialConversationTypewriterSound,
);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null); const [success, setSuccess] = useState<string | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -91,6 +97,7 @@ export function PreferencesForm({
discordMutedTypes, discordMutedTypes,
xpDisplayMini, xpDisplayMini,
conversationTypewriter, conversationTypewriter,
conversationTypewriterSound,
conversationVoice, conversationVoice,
}); });
@ -248,6 +255,26 @@ export function PreferencesForm({
</div> </div>
</RadioGroup> </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 <Label
htmlFor="conversationVoice" htmlFor="conversationVoice"
className="mt-2 flex items-center justify-between gap-4 text-sm" className="mt-2 flex items-center justify-between gap-4 text-sm"

View file

@ -178,6 +178,7 @@ export function AppSidebar({
discordMutedTypes: preferences?.discord?.mutedTypes ?? [], discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
xpDisplayMini: !isMiniMode, xpDisplayMini: !isMiniMode,
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default", conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
conversationTypewriterSound: preferences?.dialogue?.typewriterSound !== false,
conversationVoice: preferences?.dialogue?.voice !== false, conversationVoice: preferences?.dialogue?.voice !== false,
}); });
setIsMiniMode(!isMiniMode); setIsMiniMode(!isMiniMode);

View file

@ -8,6 +8,14 @@ import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc
import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate"; import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate";
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate"; import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import { DialogueText, visibleLength } from "@/lib/npc-dialogue/DialogueText"; import { DialogueText, visibleLength } from "@/lib/npc-dialogue/DialogueText";
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 { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments";
import { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue"; import { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
import { DOSSIER } from "@/components/frontend/operations"; import { DOSSIER } from "@/components/frontend/operations";
@ -41,6 +49,8 @@ interface NpcConversationProps {
/** Type lines out character by character. Resolved server-side from the /** Type lines out character by character. Resolved server-side from the
* player's preference and the unit default; reduced-motion always wins. */ * player's preference and the unit default; reduced-motion always wins. */
readonly typewriter?: boolean; 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. */ /** Play recorded voice clips. The header button mutes for the session. */
readonly voice?: boolean; readonly voice?: boolean;
} }
@ -137,6 +147,7 @@ export function NpcConversation({
dialogue, dialogue,
initialSeenNodeIds, initialSeenNodeIds,
typewriter = true, typewriter = true,
typewriterSound = true,
voice = true, voice = true,
}: NpcConversationProps) { }: NpcConversationProps) {
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]); const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
@ -151,6 +162,8 @@ export function NpcConversation({
const [streamingId, setStreamingId] = useState<string | null>(null); const [streamingId, setStreamingId] = useState<string | null>(null);
/** Set by clicking the log: finish the line instead of waiting. */ /** Set by clicking the log: finish the line instead of waiting. */
const skipRevealRef = useRef<string | null>(null); 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 /** 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. */ * starts, and the browser keeps its autoplay permission for the session. */
const audioRef = useRef<HTMLAudioElement | null>(null); const audioRef = useRef<HTMLAudioElement | null>(null);
@ -324,16 +337,39 @@ export function NpcConversation({
setStreamingId(id); setStreamingId(id);
skipRevealRef.current = null; 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(buildRevealSchedule(text), 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(); const startedAt = performance.now();
try { try {
for (;;) { for (;;) {
if (sessionRef.current !== token) return; if (sessionRef.current !== token) return;
if (skipRevealRef.current === id) break; if (skipRevealRef.current === id) break;
const shown = Math.min(total, Math.floor((performance.now() - startedAt) / msPerUnit)); const elapsed = performance.now() - startedAt;
setReveal(shown); if (ticking) {
if (shown >= total) break; while (
await sleep(32); 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 { } finally {
// Land on the full line whether it finished, was skipped, or the dialog // Land on the full line whether it finished, was skipped, or the dialog
@ -343,6 +379,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 // Opening the conversation walks the start node and auto-advances through
// linear dialogue/event nodes, so the player lands on the first interactive // 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 // node (a choice, an end, or a dead end) without clicking Continue. Each
@ -350,6 +405,11 @@ export function NpcConversation({
const begin = () => { const begin = () => {
const token = ++sessionRef.current; const token = ++sessionRef.current;
audioRef.current?.pause(); 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;
setLog([]); setLog([]);
setTyping(null); setTyping(null);
setPlayerTyping(false); setPlayerTyping(false);
@ -413,7 +473,22 @@ export function NpcConversation({
if (sessionRef.current !== token) return; if (sessionRef.current !== token) return;
} }
const target: string | undefined = current.data.next?.target; 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 { } else {
current = null; current = null;
} }
@ -547,8 +622,8 @@ export function NpcConversation({
} }
}} }}
aria-pressed={!soundOn} aria-pressed={!soundOn}
aria-label={soundOn ? "Mute voice clips" : "Unmute voice clips"} aria-label={soundOn ? "Mute conversation sound" : "Unmute conversation sound"}
title={soundOn ? "Mute voice clips" : "Unmute voice clips"} title={soundOn ? "Mute conversation sound" : "Unmute conversation sound"}
className="text-white/40 transition-colors hover:text-white/90" className="text-white/40 transition-colors hover:text-white/90"
> >
{soundOn ? <Volume2Icon className="size-4" /> : <VolumeXIcon className="size-4" />} {soundOn ? <Volume2Icon className="size-4" /> : <VolumeXIcon className="size-4" />}
@ -583,8 +658,10 @@ export function NpcConversation({
ref={scrollRef} ref={scrollRef}
onClick={() => { onClick={() => {
// A click anywhere in the log finishes the line that is // 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; if (streamingId) skipRevealRef.current = streamingId;
else skipBeatRef.current = true;
}} }}
className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5" className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5"
> >

View file

@ -162,14 +162,59 @@ 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` **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 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" 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 built in relative units and scaled to the target duration by
`scaleSchedule`, which is also how a recorded line is paced: the rhythm is
preserved and only stretched, so a clip does not flatten the pauses. The last
unit's trailing pause is excluded from `total`, so a finished line never sits
waiting for nothing.
**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 - Unit default: `npc-dialogue-settings.presentation.typewriterDefault`. Changing it
deliberately does not bump the prompt `revision`, since it is not prompt text. deliberately does not bump the prompt `revision`, since it is not prompt text.
- Per player: `users.preferences.dialogue.typewriter` (`default` / `on` / `off`), - Per player: `users.preferences.dialogue.typewriter` (`default` / `on` / `off`),
resolved by `resolveTypewriter()` in `presentation.ts`. An explicit choice wins resolved by `resolveTypewriter()` in `presentation.ts`. An explicit choice wins
over the unit default in both directions. 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 - 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. 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, - The component stores the line's resolved text on the log entry and renders that,

View file

@ -32,8 +32,16 @@ import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
*/ */
interface RevealBudget { interface RevealBudget {
left: number; 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 /** Budget for a fully revealed line (a number, not Infinity, so the consumed
* count stays computable). */ * count stays computable). */
const UNLIMITED_REVEAL = Number.MAX_SAFE_INTEGER; 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. * when it is finished both need this, and both must agree with the renderer.
*/ */
export function visibleLength(text: string): number { 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); renderBlocks(text, { i: 0 }, budget);
return UNLIMITED_REVEAL - budget.left; return (budget.seen ?? []).join("");
} }
const BULLET_RE = /^[-*]\s+/; const BULLET_RE = /^[-*]\s+/;
@ -207,6 +227,7 @@ function parseSegment(
const take = Math.min(plain.length, budget.left); const take = Math.min(plain.length, budget.left);
nodes.push(take === plain.length ? plain : plain.slice(0, take)); nodes.push(take === plain.length ? plain : plain.slice(0, take));
budget.left -= take; budget.left -= take;
budget.seen?.push(plain.slice(0, take));
} }
plain = ""; plain = "";
}; };
@ -230,6 +251,7 @@ function parseSegment(
// since its characters are literal and often not prose. // since its characters are literal and often not prose.
if (budget.left >= code.length) { if (budget.left >= code.length) {
budget.left -= code.length; budget.left -= code.length;
budget.seen?.push(code);
nodes.push( nodes.push(
<code <code
key={key()} key={key()}
@ -250,6 +272,7 @@ function parseSegment(
flush(); flush();
if (budget.left >= 1) { if (budget.left >= 1) {
budget.left -= 1; budget.left -= 1;
budget.seen?.push(ATOMIC_UNIT);
nodes.push(<Countdown key={key()} value={cd[1]} />); nodes.push(<Countdown key={key()} value={cd[1]} />);
} }
i += cd[0].length; i += cd[0].length;
@ -265,6 +288,7 @@ function parseSegment(
flush(); flush();
if (budget.left >= 1) { if (budget.left >= 1) {
budget.left -= 1; budget.left -= 1;
budget.seen?.push(ATOMIC_UNIT);
nodes.push( nodes.push(
<img <img
key={key()} key={key()}

View file

@ -0,0 +1,202 @@
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.
*/
export const PACING_PRESETS: Record<string, PauseProfile> = {
subtle: { clauseMs: 60, sentenceMs: 160, newlineMs: 200, paragraphMs: 320, beatMs: 380 },
natural: { clauseMs: 110, sentenceMs: 260, newlineMs: 320, paragraphMs: 520, beatMs: 620 },
pronounced: {
clauseMs: 170,
sentenceMs: 400,
newlineMs: 480,
paragraphMs: 800,
beatMs: 900,
},
};
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;
}

View 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);
}

File diff suppressed because it is too large Load diff

View file

@ -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";`)
}

View file

@ -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_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_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_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 = [ export const migrations = [
{ {
@ -1030,6 +1031,11 @@ export const migrations = [
{ {
up: migration_20261124_232253_add_npc_dialogue_testing_flag.up, up: migration_20261124_232253_add_npc_dialogue_testing_flag.up,
down: migration_20261124_232253_add_npc_dialogue_testing_flag.down, 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'
}, },
]; ];

View file

@ -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. * 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; 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. * 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 | T
| { | {
typewriter?: T; typewriter?: T;
typewriterSound?: T;
voice?: T; voice?: T;
}; };
discord?: discord?:

View 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"));
});
});

View file

@ -4,7 +4,7 @@ import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest"; 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 * 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", () => { it("renders everything when no reveal is given", () => {
expect(textOf(render("Plain **line**"))).toBe("Plain line"); 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 ![map](/x.png) 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 ![map](/x.png) here")).toHaveLength("Look here".length + 1);
});
}); });

View file

@ -44,6 +44,7 @@ describe("PreferencesForm", () => {
discordMutedTypes: [], discordMutedTypes: [],
xpDisplayMini: false, xpDisplayMini: false,
conversationTypewriter: "default", conversationTypewriter: "default",
conversationTypewriterSound: true,
conversationVoice: true, conversationVoice: true,
}), }),
); );
@ -54,6 +55,7 @@ describe("PreferencesForm", () => {
fireEvent.click(screen.getByRole("radio", { name: "Actual" })); fireEvent.click(screen.getByRole("radio", { name: "Actual" }));
fireEvent.click(screen.getByRole("radio", { name: "Show instantly" })); 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 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" })); fireEvent.click(screen.getByRole("switch", { name: "Enable Discord notifications" }));
const discordMarketOffer = document.getElementById("discord-market-offer"); const discordMarketOffer = document.getElementById("discord-market-offer");
if (!(discordMarketOffer instanceof HTMLElement)) { if (!(discordMarketOffer instanceof HTMLElement)) {
@ -74,6 +76,7 @@ describe("PreferencesForm", () => {
discordMutedTypes: ["market:offer"], discordMutedTypes: ["market:offer"],
xpDisplayMini: true, xpDisplayMini: true,
conversationTypewriter: "off", conversationTypewriter: "off",
conversationTypewriterSound: false,
conversationVoice: false, conversationVoice: false,
}); });
}); });