diff --git a/src/components/admin/npc-dialogue/NodeEditDialog.tsx b/src/components/admin/npc-dialogue/NodeEditDialog.tsx index f40f7e4e..be68d532 100644 --- a/src/components/admin/npc-dialogue/NodeEditDialog.tsx +++ b/src/components/admin/npc-dialogue/NodeEditDialog.tsx @@ -318,7 +318,9 @@ export function NodeEditDialog({ with a ternary: {'{{ trust ? friend : hostile }}'}, also {'{{ !key }}'} and {'{{ rep >= 5 ? elite : rookie }}'}. Branches may nest tokens. Inline images use {'![alt](url)'} (e.g. {`![coin](/api/media/file/coin.png)`}) and - render at text height. Lines starting with "- " or "1. " become lists. + render at text height. Hold the typing with {'{1.2s}'} or {'{400ms}'} (up to + 10s); the marker is invisible to players. Lines starting with "- " or "1. " + become lists. Right-click the box for a markup menu.

diff --git a/src/components/frontend/personnel/NpcConversation.tsx b/src/components/frontend/personnel/NpcConversation.tsx index 643ec64f..03ac85ba 100644 --- a/src/components/frontend/personnel/NpcConversation.tsx +++ b/src/components/frontend/personnel/NpcConversation.tsx @@ -12,6 +12,7 @@ import { choiceIndexFromKey, choiceShortcutLabel, isSkipKey } from "@/lib/npc-di import { DEFAULT_PACING_PRESET, beatMs, + lineDurationMs, buildRevealSchedule, scaleSchedule, shownAt, @@ -95,9 +96,10 @@ function resolveFlow(dialogue: NpcConversationProps["dialogue"]): ResolvedFlow | const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); -/** Longest a line may take, pauses included. Past this the schedule is - * compressed: a wall of text still has to arrive while the player is looking. */ -const REVEAL_CAP_MS = 3000; +/* Line duration lives in pacing.ts (`lineDurationMs`): the 3s ceiling that used + * to sit here compressed every line past about 120 characters, down to 8ms per + * character on a long one, which is why the typing felt faster the deeper a + * conversation went. */ /** True when the device asks for reduced motion; the animation is skipped * entirely rather than merely shortened. */ @@ -373,10 +375,9 @@ export function NpcConversation({ // keeps text and speech together. Only a very long line is compressed, by // the cap. const unscaled = buildRevealSchedule(text); - const durationMs = - voiceStarted && clipSeconds > 0.4 - ? Math.min(60_000, clipSeconds * 1000) - : Math.min(REVEAL_CAP_MS, unscaled.total); + const voicedMs = + voiceStarted && clipSeconds > 0.4 ? Math.min(60_000, clipSeconds * 1000) : null; + const durationMs = lineDurationMs(unscaled, voicedMs); setLog((prev) => [ ...prev, diff --git a/src/lib/npc-dialogue/AGENTS.md b/src/lib/npc-dialogue/AGENTS.md index 6e836397..078013b3 100644 --- a/src/lib/npc-dialogue/AGENTS.md +++ b/src/lib/npc-dialogue/AGENTS.md @@ -334,6 +334,28 @@ markers for the offered ones), plus one flag evaluation per NPC that has a gated conversation. The page swallows loader errors and renders no chips rather than failing the directory. +### Typing pace and authored pauses + +`pacing.ts` prices the reveal: `BASE_UNIT_MS` (30ms, about 33 characters a +second) per visible unit plus a pause after punctuation and line breaks. A line +takes `lineDurationMs` of the schedule: a recorded clip sets the target, an +authored pause outlasts a short clip, and a silent line is never compressed +below the base pace (ceiling `MAX_LINE_MS` 20s, floor 500ms). + +That ceiling used to be 3s in the component, which silently compressed every +line past about 120 characters: 240 characters ran at 13ms per character and +360 at 8. Long NPC lines therefore read as if the typing had sped up, which is +what "it gets faster the deeper you go" turned out to be. The cap now sits high +enough that it only catches a wall of text, and the duration rule lives in +`lineDurationMs` so it can be tested without a browser. + +Authors can hold a line anywhere with `{1.2s}` or `{400ms}` (clamped to 10s). +`DialogueText`'s parser skips the marker and records where it sat; +`visibleSegments` exposes that to the schedule, which charges the pause between +the units either side. Pauses are **absolute**: `scaleSchedule` strips them out +before scaling, so matching a line to a voice clip never shortens a beat the +author asked for. The admin preview shows markers as written. + ### The Continue gate `data.requireContinue` (dialogue node, off by default) parks the conversation on diff --git a/src/lib/npc-dialogue/DialogueText.tsx b/src/lib/npc-dialogue/DialogueText.tsx index 8ea0f7ea..bb987199 100644 --- a/src/lib/npc-dialogue/DialogueText.tsx +++ b/src/lib/npc-dialogue/DialogueText.tsx @@ -36,6 +36,9 @@ interface RevealBudget { * An image or a countdown contributes one placeholder character (it costs * one unit but renders no text of its own). */ seen?: string[]; + /** Authored pauses (`{1.2s}`), positioned by how many visible characters + * precede them. Renders nothing; the schedule is what gives it a duration. */ + pauses?: { at: number; ms: number }[]; } /** One visible unit of an image or a countdown: countable, non-space, and @@ -89,9 +92,22 @@ export function visibleLength(text: string): number { * it fits. */ export function visibleText(text: string): string { - const budget: RevealBudget = { left: UNLIMITED_REVEAL, seen: [] }; + return visibleSegments(text).text; +} + +/** + * The same walk as `visibleText`, plus where the authored pauses fall. `at` is + * the count of visible characters before the pause, so a schedule can charge + * the gap between two specific units. Markers cost nothing themselves and never + * reach the page. + */ +export function visibleSegments(text: string): { + text: string; + pauses: { at: number; ms: number }[]; +} { + const budget: RevealBudget = { left: UNLIMITED_REVEAL, seen: [], pauses: [] }; renderBlocks(text, { i: 0 }, budget); - return (budget.seen ?? []).join(""); + return { text: (budget.seen ?? []).join(""), pauses: budget.pauses ?? [] }; } const BULLET_RE = /^[-*]\s+/; @@ -185,6 +201,12 @@ const MAX_DEPTH = 8; const IMG_RE = /^!\[([^\]]*)\]\(([^()\s]*)\)/; const LINK_RE = /^\[([^\]]*)\]\(([^()\s]*)\)/; const COLOR_OPEN_RE = /^\{([^{}|]{1,20})\}/; +/** An authored pause: `{1.2s}`, `{400ms}`, `{2S}`. Digits first so it can never + * collide with the colour tokens that also use braces. */ +const PAUSE_RE = /^\{(\d+(?:\.\d+)?)(ms|s)\}/i; +/** Longest an authored pause may hold a line. A conversation is not a place to + * park a player, and a typo such as `{90s}` should not read as a broken line. */ +export const MAX_PAUSE_MS = 10_000; const COUNTDOWN_RE = /^\{cd\|([^}]*)\}/; /** Only http(s) and site-relative URLs render; anything else stays literal. */ @@ -327,11 +349,35 @@ function parseSegment( } } + // Authored pause. It renders nothing; the pacing schedule reads where it + // sits from the budget and gives the line that much extra time. + if (rest[0] === "{") { + const pause = PAUSE_RE.exec(rest); + if (pause) { + flush(); + const amount = Number.parseFloat(pause[1]); + const ms = Math.round(pause[2].toLowerCase() === "s" ? amount * 1000 : amount); + budget.pauses?.push({ + at: budget.seen ? budget.seen.reduce((total, chunk) => total + chunk.length, 0) : 0, + ms: Math.min(MAX_PAUSE_MS, Math.max(0, ms)), + }); + i += pause[0].length; + continue; + } + } + // Color run: recurse so inner markup renders inside the colored span. if (rest[0] === "{") { const open = COLOR_OPEN_RE.exec(rest); if (open && open[1] !== "/") { flush(); + // A failed attempt (unknown token, unclosed run) falls through and + // renders the braces literally, so what it consumed has to be given + // back: the recursion had already spent budget on the "inner" text and + // the line would otherwise count those characters twice. + const leftBefore = budget.left; + const seenBefore = budget.seen ? [...budget.seen] : undefined; + const pausesBefore = budget.pauses ? [...budget.pauses] : undefined; const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true, budget); const style = colorStyle(open[1]); if (inner.closed && style) { @@ -347,7 +393,11 @@ function parseSegment( i += open[0].length + inner.consumed; continue; } - // Unknown token or unclosed: fall through and render literally. + // Unknown token or unclosed: restore what the attempt consumed, then + // fall through and render the braces literally. + budget.left = leftBefore; + if (seenBefore) budget.seen = seenBefore; + if (pausesBefore) budget.pauses = pausesBefore; } } diff --git a/src/lib/npc-dialogue/pacing.ts b/src/lib/npc-dialogue/pacing.ts index 9c2feb3b..f1f8c5e8 100644 --- a/src/lib/npc-dialogue/pacing.ts +++ b/src/lib/npc-dialogue/pacing.ts @@ -1,4 +1,4 @@ -import { visibleText } from "./DialogueText"; +import { visibleSegments } from "./DialogueText"; /** * Pacing for a conversation line that types itself out. @@ -27,8 +27,14 @@ export interface PauseProfile { readonly beatMs: number; } -/** Cost of one visible unit before any pause is added. */ -export const BASE_UNIT_MS = 24; +/** + * Cost of one visible unit before any pause is added. + * + * Thirty milliseconds is about 33 characters a second, the top of a comfortable + * reading pace for prose read aloud to yourself. It was 24, which measured fine + * on paper and read as a blur in the app. + */ +export const BASE_UNIT_MS = 30; /** * The three approved strengths. `natural` is the unit default: long enough to @@ -61,8 +67,14 @@ export interface RevealSchedule { * 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. */ + * arrived, so trailing punctuation pause is deliberately excluded. */ readonly total: number; + /** Authored pause (ms) to insert after each unit, index-aligned with + * `arrival`; 0 for a unit with no marker. These are absolute: they are the + * author's beat, so scaling the line to a voice clip must not shorten them. */ + readonly pauses: readonly number[]; + /** Sum of `pauses`, i.e. how much of the line's duration is authored pause. */ + readonly explicitTotal: 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. */ @@ -138,18 +150,32 @@ export function buildRevealSchedule( 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 segments = visibleSegments(text); + const visible = segments.text; + // Widen the authored markers to "after this unit", so the loop below can price + // them with the rest of the rhythm. A marker at the very start (index 0) has no + // unit to follow, so it is charged against the first unit's gap instead. + const pauses = new Array(visible.length).fill(0); + for (const pause of segments.pauses) { + const index = Math.min(visible.length - 1, Math.max(0, pause.at - 1)); + if (visible.length > 0) pauses[index] += pause.ms; + } + const explicitTotal = pauses.reduce((sum, ms) => sum + ms, 0); + + if (visible.length === 0) { + return { arrival: [], total: explicitTotal, ticks: [], text: visible, pauses, explicitTotal }; + } 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); + cursor += BASE_UNIT_MS + pauseAfter(visible, i, profile) + pauses[i]; } - // 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; + // The last unit's own cost is what finishes the line; its trailing punctuation + // pause is dropped so the reveal never sits on a complete line waiting for + // nothing. An authored pause there is kept: that is a deliberate beat. + const total = arrival[arrival.length - 1] + BASE_UNIT_MS + pauses[pauses.length - 1]; const random = seededRandom(hashText(visible)); const ticks: number[] = []; @@ -161,7 +187,7 @@ export function buildRevealSchedule( nextTick = arrival[i] + TICK_MIN_GAP + random() * (TICK_MAX_GAP - TICK_MIN_GAP); } - return { arrival, total, ticks, text: visible }; + return { arrival, total, ticks, text: visible, pauses, explicitTotal }; } export interface ScaledSchedule { @@ -180,15 +206,50 @@ export interface ScaledSchedule { */ 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; + if (schedule.total <= 0) { + // A line that is nothing but pauses still lasts as long as they do. + return { arrivalMs: [], tickMs: [], durationMs: Math.max(target, schedule.explicitTotal) }; + } + // Authored pauses are absolute: only the typed part stretches or shrinks to + // fit. A 1.2s beat stays 1.2s whether the line is silent or matched to a clip. + const baseTotal = Math.max(1, schedule.total - schedule.explicitTotal); + const baseTarget = Math.max(0, target - schedule.explicitTotal); + const factor = baseTarget / baseTotal; + // `arrival` already contains the authored pauses, so strip them before + // scaling and put them back untouched afterwards. + let pausedBefore = 0; + const arrivalMs = schedule.arrival.map((value, index) => { + const scaled = (value - pausedBefore) * factor + pausedBefore; + pausedBefore += schedule.pauses[index] ?? 0; + return scaled; + }); + const durationMs = Math.max(target, schedule.explicitTotal); return { - arrivalMs: schedule.arrival.map((value) => value * factor), + arrivalMs, tickMs: schedule.ticks.map((value) => value * factor), - durationMs: target, + durationMs, }; } +/** Longest a silent line may take. A safety rail for a wall of text, not a pace: + * past this a line is compressed, and compression is what made long lines read + * as if the typing had sped up. */ +export const MAX_LINE_MS = 20_000; +/** Floor for a very short line, so "Yes." is not a single frame. */ +export const MIN_LINE_MS = 500; + +/** + * How long one line should take. A recorded clip sets the target so text and + * speech stay together; otherwise the schedule's own total is used, never + * compressed below the base pace. An authored pause outlasts a short clip. + */ +export function lineDurationMs(schedule: RevealSchedule, voicedMs?: number | null): number { + if (voicedMs !== null && voicedMs !== undefined && voicedMs > 0) { + return Math.max(voicedMs, schedule.explicitTotal); + } + return Math.min(MAX_LINE_MS, Math.max(MIN_LINE_MS, schedule.total)); +} + /** 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 { diff --git a/tests/int/npc-dialogue-pacing.int.spec.ts b/tests/int/npc-dialogue-pacing.int.spec.ts index d70b0e16..345831da 100644 --- a/tests/int/npc-dialogue-pacing.int.spec.ts +++ b/tests/int/npc-dialogue-pacing.int.spec.ts @@ -1,12 +1,16 @@ // @vitest-environment node import { describe, expect, it } from "vitest"; +import { MAX_PAUSE_MS, visibleSegments } from "@/lib/npc-dialogue/DialogueText"; import { BASE_UNIT_MS, DEFAULT_PACING_PRESET, + MAX_LINE_MS, + MIN_LINE_MS, PACING_PRESETS, beatMs, buildRevealSchedule, + lineDurationMs, scaleSchedule, shownAt, } from "@/lib/npc-dialogue/pacing"; @@ -145,7 +149,7 @@ describe("reveal pacing", () => { it("has nothing to schedule for an empty line", () => { const empty = buildRevealSchedule(""); - expect(empty).toEqual({ arrival: [], total: 0, ticks: [], text: "" }); + expect(empty).toMatchObject({ arrival: [], total: 0, ticks: [], text: "" }); expect(scaleSchedule(empty, 900)).toEqual({ arrivalMs: [], tickMs: [], durationMs: 900 }); }); @@ -166,3 +170,63 @@ describe("reveal pacing", () => { expect(beatMs("unknown" as never)).toBe(beatMs("natural")); }); }); + +describe("authored pauses", () => { + it("keeps the marker out of the line and reports where it sat", () => { + const segments = visibleSegments("Hold{1.2s} there."); + expect(segments.text).toBe("Hold there."); + expect(segments.pauses).toEqual([{ at: 4, ms: 1200 }]); + }); + + it("reads both units, and refuses nonsense", () => { + expect(visibleSegments("a{400ms}b").pauses).toEqual([{ at: 1, ms: 400 }]); + expect(visibleSegments("a{2S}b").pauses).toEqual([{ at: 1, ms: 2000 }]); + // Not a pause token: it stays literal text, like any unknown brace run. + expect(visibleSegments("a{1.2x}b").text).toBe("a{1.2x}b"); + expect(visibleSegments("a{1.2x}b").pauses).toEqual([]); + // Clamped, so a typo cannot park a player for minutes. + expect(visibleSegments("a{90s}b").pauses).toEqual([{ at: 1, ms: MAX_PAUSE_MS }]); + }); + + it("costs exactly the authored time, on top of the base pace", () => { + const plain = buildRevealSchedule("ab"); + const paused = buildRevealSchedule("a{1.2s}b"); + expect(paused.text).toBe("ab"); + expect(paused.explicitTotal).toBe(1200); + expect(paused.pauses).toEqual([1200, 0]); + expect(gapAfter(paused.arrival, 0)).toBe(BASE_UNIT_MS + 1200); + expect(paused.total - plain.total).toBe(1200); + }); + + it("stays absolute when the line is stretched or squeezed to fit", () => { + const schedule = buildRevealSchedule("a{1.2s}bcd"); + const stretched = scaleSchedule(schedule, schedule.total * 3); + const squeezed = scaleSchedule(schedule, 2000); + // Two neighbouring units across the pause: the extra 1.2s is still there. + const gap = (arrival: readonly number[]) => arrival[1] - arrival[0]; + expect(gap(stretched.arrivalMs) - BASE_UNIT_MS * 3).toBeGreaterThanOrEqual(1200); + expect(gap(squeezed.arrivalMs)).toBeGreaterThanOrEqual(1200); + }); +}); + +describe("line duration", () => { + it("does not compress a long line below the base pace", () => { + // 400 characters at the old 3s ceiling ran at 7.5ms per character. + const schedule = buildRevealSchedule("word ".repeat(80).trim()); + const duration = lineDurationMs(schedule); + expect(duration).toBe(schedule.total); + expect(duration / schedule.text.length).toBeGreaterThanOrEqual(BASE_UNIT_MS - 1); + }); + + it("still has a ceiling, and a floor for a very short line", () => { + const wall = buildRevealSchedule("word ".repeat(400).trim()); + expect(lineDurationMs(wall)).toBe(MAX_LINE_MS); + expect(lineDurationMs(buildRevealSchedule("Hi."))).toBeGreaterThanOrEqual(MIN_LINE_MS); + }); + + it("lets a clip set the target but never cuts an authored pause", () => { + const schedule = buildRevealSchedule("a{1.2s}bcd"); + expect(lineDurationMs(schedule, 4000)).toBe(4000); + expect(lineDurationMs(schedule, 600)).toBeGreaterThanOrEqual(1200); + }); +});