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:
parent
441c0dbac3
commit
464ba2d5d4
19 changed files with 47873 additions and 15 deletions
|
|
@ -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}
|
||||
/>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -8,6 +8,14 @@ import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc
|
|||
import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate";
|
||||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import { DialogueText, 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 { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
|
||||
import { DOSSIER } from "@/components/frontend/operations";
|
||||
|
|
@ -41,6 +49,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;
|
||||
}
|
||||
|
|
@ -137,6 +147,7 @@ export function NpcConversation({
|
|||
dialogue,
|
||||
initialSeenNodeIds,
|
||||
typewriter = true,
|
||||
typewriterSound = true,
|
||||
voice = true,
|
||||
}: NpcConversationProps) {
|
||||
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
|
||||
|
|
@ -151,6 +162,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);
|
||||
|
|
@ -324,16 +337,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(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();
|
||||
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 +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
|
||||
// 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 +405,11 @@ 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;
|
||||
setLog([]);
|
||||
setTyping(null);
|
||||
setPlayerTyping(false);
|
||||
|
|
@ -413,7 +473,22 @@ 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;
|
||||
}
|
||||
|
|
@ -547,8 +622,8 @@ export function NpcConversation({
|
|||
}
|
||||
}}
|
||||
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" />}
|
||||
|
|
@ -583,8 +658,10 @@ export function NpcConversation({
|
|||
ref={scrollRef}
|
||||
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"
|
||||
>
|
||||
|
|
|
|||
|
|
@ -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`
|
||||
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 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
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -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()}
|
||||
|
|
|
|||
202
src/lib/npc-dialogue/pacing.ts
Normal file
202
src/lib/npc-dialogue/pacing.ts
Normal 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;
|
||||
}
|
||||
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);
|
||||
}
|
||||
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?:
|
||||
|
|
|
|||
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"));
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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