diff --git a/src/app/(frontend)/account/actions.ts b/src/app/(frontend)/account/actions.ts index 8f736253..7962fbed 100644 --- a/src/app/(frontend)/account/actions.ts +++ b/src/app/(frontend)/account/actions.ts @@ -210,6 +210,7 @@ export async function updatePreferences(input: { discordEnabled: boolean; discordMutedTypes: string[]; xpDisplayMini: boolean; + conversationTypewriter: "default" | "on" | "off"; }): Promise { try { const { payload, user } = await authenticate(); @@ -246,6 +247,9 @@ export async function updatePreferences(input: { xpDisplayMini: input.xpDisplayMini, sidebarOrder: stored.display?.sidebarOrder ?? null, }, + dialogue: { + typewriter: input.conversationTypewriter, + }, discord: { enabled: input.discordEnabled, mutedTypes: discordMutedTypes, diff --git a/src/app/(frontend)/account/page.tsx b/src/app/(frontend)/account/page.tsx index 017e1010..de50014c 100644 --- a/src/app/(frontend)/account/page.tsx +++ b/src/app/(frontend)/account/page.tsx @@ -181,6 +181,7 @@ export default async function AccountPage() { mutedTypes={notifications?.mutedTypes ?? []} showCallsign={fullUser.preferences?.display?.showCallsign ?? false} showVersionOverlay={fullUser.preferences?.display?.showVersionOverlay ?? true} + conversationTypewriter={fullUser.preferences?.dialogue?.typewriter ?? "default"} showBackgroundTexture={fullUser.preferences?.display?.showBackgroundTexture ?? true} leadOrActual={fullUser.preferences?.display?.leadOrActual ?? "lead"} discordEnabled={discord?.enabled ?? false} diff --git a/src/app/(frontend)/personnel/contacts/[id]/page.tsx b/src/app/(frontend)/personnel/contacts/[id]/page.tsx index b74e47b2..41ac50c9 100644 --- a/src/app/(frontend)/personnel/contacts/[id]/page.tsx +++ b/src/app/(frontend)/personnel/contacts/[id]/page.tsx @@ -7,6 +7,9 @@ import type { FlowData } from "@/lib/npc-dialogue/dialogue"; import { selectDialogueForUser } from "@/lib/npc-dialogue/selection"; import { evaluateCondition } from "@/lib/npc-dialogue/flags"; import { listSeenNodeIds } from "@/lib/npc-dialogue/states"; +import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings"; +import { resolveTypewriter } from "@/lib/npc-dialogue/presentation"; +import { isPayloadUser } from "@/utils/access-control/isPayloadUser"; import { NpcProfile } from "@/components/frontend/personnel/NpcProfile"; import { NpcConversation } from "@/components/frontend/personnel/NpcConversation"; import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard"; @@ -168,13 +171,27 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) { ? await listSeenNodeIds(payload, user.id as number, dialogue.id) : []; + // Typing animation: the unit default from the settings global, overridden by + // this player's own preference. Read here so the dialog needs no round trip. + const typewriterEnabled = dialogue + ? resolveTypewriter( + isPayloadUser(user) ? user.preferences?.dialogue?.typewriter : undefined, + (await loadDialogueSettings(payload)).typewriterDefault, + ) + : false; + return (
+ } employmentSlot={ (initialConversationTypewriter); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const [loading, setLoading] = useState(false); @@ -80,6 +86,7 @@ export function PreferencesForm({ discordEnabled, discordMutedTypes, xpDisplayMini, + conversationTypewriter, }); if (!result.success) { @@ -191,6 +198,53 @@ export function PreferencesForm({ + + + Conversations + + How NPC dialogue is presented when you talk to a contact. + + + +
+ Typing animation + + Type lines out letter by letter. Click a line to finish it immediately. + Devices set to reduce motion always show lines instantly. + +
+ { + if (value === "default" || value === "on" || value === "off") { + setConversationTypewriter(value); + } + }} + className="flex flex-wrap gap-4" + aria-label="Typing animation in conversations" + > +
+ + +
+
+ + +
+
+ + +
+
+
+
+ Notifications diff --git a/src/components/frontend/blocks/AppSidebar.tsx b/src/components/frontend/blocks/AppSidebar.tsx index fdc2dd08..e931fe63 100644 --- a/src/components/frontend/blocks/AppSidebar.tsx +++ b/src/components/frontend/blocks/AppSidebar.tsx @@ -177,6 +177,7 @@ export function AppSidebar({ discordEnabled: preferences?.discord?.enabled ?? false, discordMutedTypes: preferences?.discord?.mutedTypes ?? [], xpDisplayMini: !isMiniMode, + conversationTypewriter: preferences?.dialogue?.typewriter ?? "default", }); setIsMiniMode(!isMiniMode); } catch (error) { diff --git a/src/components/frontend/personnel/NpcConversation.tsx b/src/components/frontend/personnel/NpcConversation.tsx index 7a6338c6..22d1817f 100644 --- a/src/components/frontend/personnel/NpcConversation.tsx +++ b/src/components/frontend/personnel/NpcConversation.tsx @@ -7,7 +7,7 @@ import type { GameNpc } from "@/payload-types"; import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue"; import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate"; import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate"; -import { DialogueText } from "@/lib/npc-dialogue/DialogueText"; +import { DialogueText, visibleLength } from "@/lib/npc-dialogue/DialogueText"; import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments"; import { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue"; import { DOSSIER } from "@/components/frontend/operations"; @@ -38,6 +38,9 @@ interface NpcConversationProps { * local seen set; reads during the session are sent to the server and * merged optimistically. */ readonly initialSeenNodeIds?: readonly string[]; + /** Type lines out character by character. Resolved server-side from the + * player's preference and the unit default; reduced-motion always wins. */ + readonly typewriter?: boolean; } interface ResolvedFlow { @@ -53,6 +56,12 @@ type LogEntry = /** Server-resolved display strings (flag tokens interpolated), when the * node had tokens. Undefined = render the raw authored strings. */ resolved?: ResolvedNodeTexts; + /** The line as shown, resolved text first. Stored so the reveal length and + * the renderer can never disagree about what is being typed. */ + text: string; + /** Visible characters revealed so far while typing; undefined = whole + * line is showing. */ + reveal?: number; } | { kind: "player"; id: string; text: string }; @@ -65,16 +74,48 @@ function resolveFlow(dialogue: NpcConversationProps["dialogue"]): ResolvedFlow | const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); -/** Text length drives how long the NPC "types"; jitter keeps it human. */ -function typingDelayMs(text: string): number { - return Math.min(2600, 450 + text.length * 24) * (0.85 + Math.random() * 0.3); +/** How long a line takes to type out: brisk for short lines, capped so a long + * paragraph does not hold the player up. `visibleLength` units, not raw + * characters, so markup does not slow the reveal down. */ +function revealDurationMs(units: number): number { + return Math.min(2600, 450 + units * 24); } -function nodeText(node: DialogueNode): string { - return node.data.body || node.data.effect?.message || node.data.closing || node.data.leadIn || ""; +/** True when the device asks for reduced motion; the animation is skipped + * entirely rather than merely shortened. */ +function prefersReducedMotion(): boolean { + return ( + typeof window !== "undefined" && + typeof window.matchMedia === "function" && + window.matchMedia("(prefers-reduced-motion: reduce)").matches + ); } -export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConversationProps) { +/** The line a node displays, resolved text first (flag tokens interpolated). + * Single source of truth for both the reveal length and the rendered line. */ +function displayText(node: DialogueNode, resolved?: ResolvedNodeTexts): string { + if (node.type === "event") { + return ( + (resolved?.body ?? node.data.body) || + (resolved?.message ?? node.data.effect?.message) || + "An event unfolds…" + ); + } + if (node.type === "end") { + return (resolved?.closing ?? node.data.closing) || "The conversation ends."; + } + if (node.type === "choice") { + return (resolved?.leadIn ?? node.data.leadIn) || ""; + } + return (resolved?.body ?? node.data.body) || ""; +} + +export function NpcConversation({ + npc, + dialogue, + initialSeenNodeIds, + typewriter = true, +}: NpcConversationProps) { const flow = useMemo(() => resolveFlow(dialogue), [dialogue]); const [open, setOpen] = useState(false); const [log, setLog] = useState([]); @@ -82,6 +123,11 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver const [typing, setTyping] = useState(null); /** True while the player's chosen line is "typing" into the log. */ const [playerTyping, setPlayerTyping] = useState(false); + /** Log entry currently typing itself out, if any. Gates the choice footer so + * a player cannot answer a line they have not finished reading. */ + const [streamingId, setStreamingId] = useState(null); + /** Set by clicking the log: finish the line instead of waiting. */ + const skipRevealRef = useRef(null); /** `${nodeId}:${index}` keys of one-time choices picked in THIS conversation. * Purely local: it resets on every `begin()`, so a choice hidden here * reappears the next time the conversation is opened. Persist across @@ -166,9 +212,9 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver void markNpcDialogueNodeRead(dialogue.id, nodeId).catch(() => undefined); }; - /** Resolves the node's display strings server-side (flag tokens), then - * appends it to the log after a length-based "typing" delay. Nodes without - * tokens skip the round trip and render their raw authored text. */ + /** Resolves the node's display strings server-side (flag tokens), appends the + * line to the log, then types it out unless the player has the animation off. + * Nodes without tokens skip the round trip and use their authored text. */ const typeIn = async (node: DialogueNode, token: number) => { let resolved: ResolvedNodeTexts | undefined; if (collectNodeTokens(node).length > 0 || (node.data.attachments?.length ?? 0) > 0) { @@ -176,12 +222,47 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver if (sessionRef.current !== token) return; if (res.success && res.data) resolved = res.data; } - setTyping(node.type === "event" ? "" : node.data.speaker?.trim() || npc.name); - await sleep(typingDelayMs(nodeText(node))); - if (sessionRef.current !== token) return; - setTyping(null); - setLog((prev) => [...prev, { kind: "node", id: nextId(), node, resolved }]); + + const text = displayText(node, resolved); + const id = nextId(); + const total = visibleLength(text); + // Nothing to animate for an empty line, and a reduced-motion device skips + // the animation outright. + const animate = typewriter && total > 0 && !prefersReducedMotion(); + + setLog((prev) => [ + ...prev, + { kind: "node", id, node, resolved, text, reveal: animate ? 0 : undefined }, + ]); markSeen(node.id); + if (!animate) return; + + const setReveal = (shown: number | undefined) => + setLog((prev) => + prev.map((entry) => + entry.kind === "node" && entry.id === id ? { ...entry, reveal: shown } : entry, + ), + ); + + setStreamingId(id); + skipRevealRef.current = null; + const msPerUnit = revealDurationMs(total) / total; + const startedAt = performance.now(); + try { + for (;;) { + if (sessionRef.current !== token) return; + if (skipRevealRef.current === id) break; + const shown = Math.min(total, Math.floor((performance.now() - startedAt) / msPerUnit)); + setReveal(shown); + if (shown >= total) break; + await sleep(32); + } + } finally { + // Land on the full line whether it finished, was skipped, or the dialog + // closed mid-reveal (the session check above returns through here). + setReveal(undefined); + setStreamingId((current) => (current === id ? null : current)); + } }; // Opening the conversation walks the start node and auto-advances through @@ -193,6 +274,7 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver setLog([]); setTyping(null); setPlayerTyping(false); + setStreamingId(null); setTakenChoices(new Set()); setChoiceGates({}); setOpen(true); @@ -254,6 +336,7 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver sessionRef.current += 1; setTyping(null); setPlayerTyping(false); + setStreamingId(null); setOpen(false); }; @@ -383,7 +466,15 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
) : ( <> -
+
{ + // A click anywhere in the log finishes the line that is + // typing, rather than leaving the player to wait it out. + if (streamingId) skipRevealRef.current = streamingId; + }} + className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5" + > {log.map((entry) => ( ))} @@ -393,6 +484,7 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver {!typing && !playerTyping && + streamingId === null && lastNode && lastNode.kind === "node" && (lastNode.node.type === "choice" || lastNode.node.type === "end") && ( @@ -478,12 +570,9 @@ function TimelineEntry({ ); } - const { node, resolved } = entry; + const { node, resolved, text, reveal } = entry; if (node.type === "event") { - const body = resolved?.body ?? node.data.body; - const message = resolved?.message ?? node.data.effect?.message; - const text = body || message || "An event unfolds…"; if (node.data.presentation === "narration") { // Descriptive narrative: the narrator's voice, not the NPC's. Centered // and muted with no accent bar so it reads as scene-setting rather than @@ -491,7 +580,7 @@ function TimelineEntry({ return (

- +

@@ -501,7 +590,7 @@ function TimelineEntry({ return (

- +

@@ -509,33 +598,30 @@ function TimelineEntry({ } if (node.type === "end") { - const text = (resolved?.closing ?? node.data.closing) || "The conversation ends."; return (

- +

); } if (node.type === "choice") { // The choice buttons live in the footer; only the lead-in joins the log. - const leadIn = resolved?.leadIn ?? node.data.leadIn; - if (!leadIn) return null; + if (!text) return null; return (

- +

); } const speaker = node.data.speaker?.trim() || speakerDefault; - const body = resolved?.body ?? node.data.body; return (
{speaker}

- {body ? ( - + {text ? ( + ) : ( … )} diff --git a/src/lib/npc-dialogue/AGENTS.md b/src/lib/npc-dialogue/AGENTS.md index f41c4e02..bee4a914 100644 --- a/src/lib/npc-dialogue/AGENTS.md +++ b/src/lib/npc-dialogue/AGENTS.md @@ -46,6 +46,7 @@ src/lib/npc-dialogue/ selection.ts # Which conversation is offered to a player (Payload) states.ts # Per-player read markers (Payload) attachments.ts # media ids to URLs (Payload) + presentation.ts # Typewriter preference resolution (pure) reorder.ts, DialogueText.tsx (pure) src/components/admin/npc-dialogue/ @@ -104,10 +105,29 @@ its own copy of the op list for the drafting schema; update both. Lines support `**bold**`, `*italic*`, `{red}color{/}`, `` `code` ``, `![alt](url)`, list prefixes, `{{flag}}`, `{{countdown:key}}`, and ternaries -`{{ cond ? a : b }}` including numeric comparisons. Interpolation is a single +`{{ cond ? key : other }}` including numeric comparisons. Interpolation is a single pass server-side, so a flag value can never smuggle in another token. `DialogueText.tsx` is the only renderer; don't hand-roll one. +## Typing animation + +Lines type themselves out. `DialogueText` takes a `reveal` count and truncates the +**rendered** strings, never the source, so a half-typed line can never show `{gre` +or an unclosed `**`. `visibleLength(text)` is the matching count (markup costs +nothing, an image or countdown costs one) and is what pacing and "is it finished" +both use. + +- Unit default: `npc-dialogue-settings.presentation.typewriterDefault`. Changing it + deliberately does not bump the prompt `revision`, since it is not prompt text. +- Per player: `users.preferences.dialogue.typewriter` (`default` / `on` / `off`), + resolved by `resolveTypewriter()` in `presentation.ts`. An explicit choice wins + over the unit default in both directions. +- `prefers-reduced-motion` forces the animation off regardless of either setting. +- The choice footer and End button are gated on the reveal finishing, so nobody + answers a line they have not seen. Clicking the log finishes it immediately. +- The component stores the line's resolved text on the log entry and renders that, + so the reveal length and the rendered string cannot drift apart. + ## AI drafting behaviour worth knowing - Two attempts maximum: the second prompt carries the validator's complaints. diff --git a/src/lib/npc-dialogue/DialogueText.tsx b/src/lib/npc-dialogue/DialogueText.tsx index e48cc470..353b2564 100644 --- a/src/lib/npc-dialogue/DialogueText.tsx +++ b/src/lib/npc-dialogue/DialogueText.tsx @@ -25,14 +25,55 @@ import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; * Shared by the admin flow editor previews and the frontend conversation * dialog, so it must stay client-safe (no Payload imports). */ -export function DialogueText({ text, className }: { text: string; className?: string }) { +/** + * Characters still allowed to appear while a line types out. Markup costs + * nothing, a countdown or an inline image costs one, so a reveal can stop + * anywhere without flashing raw markup or cutting a component in half. + */ +interface RevealBudget { + left: number; +} + +/** Budget for a fully revealed line (a number, not Infinity, so the consumed + * count stays computable). */ +const UNLIMITED_REVEAL = Number.MAX_SAFE_INTEGER; + +/** + * Renders dialogue markup. `reveal` limits how many visible characters appear, + * which is how conversation lines type themselves out; leave it undefined for + * the whole line. Truncation happens on the rendered strings, never on the + * source, so a half-typed line can never show `{gre` or an unclosed `**`. + */ +export function DialogueText({ + text, + className, + reveal, +}: { + text: string; + className?: string; + reveal?: number; +}) { + const budget: RevealBudget = { + left: reveal === undefined ? UNLIMITED_REVEAL : Math.max(0, Math.floor(reveal)), + }; return ( - {renderBlocks(text, { i: 0 })} + {renderBlocks(text, { i: 0 }, budget)} ); } +/** + * Visible characters in a line, counted the way `reveal` counts them (markup + * costs nothing, an image or countdown costs one). Pacing a reveal and knowing + * when it is finished both need this, and both must agree with the renderer. + */ +export function visibleLength(text: string): number { + const budget: RevealBudget = { left: UNLIMITED_REVEAL }; + renderBlocks(text, { i: 0 }, budget); + return UNLIMITED_REVEAL - budget.left; +} + const BULLET_RE = /^[-*]\s+/; const ORDERED_RE = /^\d+[.)]\s+/; @@ -42,7 +83,7 @@ const ORDERED_RE = /^\d+[.)]\s+/; * inline wrapper), everything else flushes as a paragraph rendered by the * inline parser. A blank line or a kind change splits adjacent lists. */ -function renderBlocks(text: string, keys: { i: number }): ReactNode[] { +function renderBlocks(text: string, keys: { i: number }, budget: RevealBudget): ReactNode[] { if (!text) return []; const out: ReactNode[] = []; let paragraph: string[] = []; @@ -53,7 +94,9 @@ function renderBlocks(text: string, keys: { i: number }): ReactNode[] { if (paragraph.length === 0) return; const chunk = paragraph.join("\n"); paragraph = []; - out.push({parseSegment(chunk, 0, keys, false).nodes}); + out.push( + {parseSegment(chunk, 0, keys, false, budget).nodes}, + ); }; const flushList = () => { if (!listKind) return; @@ -65,7 +108,7 @@ function renderBlocks(text: string, keys: { i: number }): ReactNode[] { {kind === "ul" ? "\u2022" : `${index + 1}.`} - {parseSegment(item, 0, keys, false).nodes} + {parseSegment(item, 0, keys, false, budget).nodes} ))} , @@ -145,16 +188,27 @@ interface ParseResult { * keeps both). When `insideColor` is set, scanning stops at the matching * `{/}` so nested colors close inner-first. */ -function parseSegment(text: string, depth: number, keys: { i: number }, insideColor: boolean): ParseResult { +function parseSegment( + text: string, + depth: number, + keys: { i: number }, + insideColor: boolean, + budget: RevealBudget, +): ParseResult { const nodes: ReactNode[] = []; let plain = ""; let i = 0; const key = () => `${depth}:${keys.i++}`; const flush = () => { - if (plain) { - nodes.push(plain); - plain = ""; + if (!plain) return; + // Only the part of the run the reveal has reached is emitted; the rest is + // dropped this render (the prefix is rebuilt from the full source next tick). + if (budget.left > 0) { + const take = Math.min(plain.length, budget.left); + nodes.push(take === plain.length ? plain : plain.slice(0, take)); + budget.left -= take; } + plain = ""; }; while (i < text.length) { @@ -171,14 +225,20 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo const end = rest.indexOf("`", 1); if (end > 1) { flush(); - nodes.push( - - {rest.slice(1, end)} - , - ); + const code = rest.slice(1, end); + // A code run is atomic: it pops in as one unit rather than typing out, + // since its characters are literal and often not prose. + if (budget.left >= code.length) { + budget.left -= code.length; + nodes.push( + + {code} + , + ); + } i += end + 1; continue; } @@ -188,7 +248,10 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo const cd = COUNTDOWN_RE.exec(rest); if (cd) { flush(); - nodes.push(); + if (budget.left >= 1) { + budget.left -= 1; + nodes.push(); + } i += cd[0].length; continue; } @@ -200,14 +263,17 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo const src = safeUrl(img[2]); if (src) { flush(); - nodes.push( - {img[1]}, - ); + if (budget.left >= 1) { + budget.left -= 1; + nodes.push( + {img[1]}, + ); + } i += img[0].length; continue; } @@ -221,11 +287,16 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo const href = safeUrl(link[2]); if (href) { flush(); - nodes.push( - - {parseSegment(link[1], depth + 1, keys, false).nodes} - , - ); + const label = parseSegment(link[1], depth + 1, keys, false, budget); + // An unrevealed label renders nothing; the link appears as its text + // types in, and never as an empty clickable fragment. + if (label.nodes.length > 0) { + nodes.push( + + {label.nodes} + , + ); + } i += link[0].length; continue; } @@ -236,15 +307,19 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo if (rest[0] === "{") { const open = COLOR_OPEN_RE.exec(rest); if (open && open[1] !== "/") { - const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true); + flush(); + const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true, budget); const style = colorStyle(open[1]); if (inner.closed && style) { - flush(); - nodes.push( - - {inner.nodes} - , - ); + // An unrevealed run contributes nothing; the span appears with the + // first character inside it. + if (inner.nodes.length > 0) { + nodes.push( + + {inner.nodes} + , + ); + } i += open[0].length + inner.consumed; continue; } @@ -257,11 +332,14 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo const end = rest.indexOf("**", 2); if (end > 2) { flush(); - nodes.push( - - {parseSegment(rest.slice(2, end), depth + 1, keys, false).nodes} - , - ); + const inner = parseSegment(rest.slice(2, end), depth + 1, keys, false, budget); + if (inner.nodes.length > 0) { + nodes.push( + + {inner.nodes} + , + ); + } i += end + 2; continue; } @@ -270,11 +348,10 @@ function parseSegment(text: string, depth: number, keys: { i: number }, insideCo const end = rest.indexOf("*", 1); if (end > 1 && rest[end + 1] !== "*") { flush(); - nodes.push( - - {parseSegment(rest.slice(1, end), depth + 1, keys, false).nodes} - , - ); + const inner = parseSegment(rest.slice(1, end), depth + 1, keys, false, budget); + if (inner.nodes.length > 0) { + nodes.push({inner.nodes}); + } i += end + 1; continue; } diff --git a/src/lib/npc-dialogue/generationSettings.ts b/src/lib/npc-dialogue/generationSettings.ts index 2c5108ab..aa69e24d 100644 --- a/src/lib/npc-dialogue/generationSettings.ts +++ b/src/lib/npc-dialogue/generationSettings.ts @@ -25,6 +25,9 @@ type SettingsDoc = { voice?: string | null; extraRules?: string | null; revision?: number | null; + presentation?: { + typewriterDefault?: boolean | null; + } | null; } | null; export interface DialoguePromptSettings { @@ -34,9 +37,16 @@ export interface DialoguePromptSettings { extraRules: string | null; /** Bumped by the global's beforeChange hook whenever the text changes. */ revision: number | null; + /** Unit default for typing conversation lines out character by character. */ + typewriterDefault: boolean; } -const EMPTY: DialoguePromptSettings = { voice: null, extraRules: null, revision: null }; +const EMPTY: DialoguePromptSettings = { + voice: null, + extraRules: null, + revision: null, + typewriterDefault: true, +}; /** Read the prompt settings, falling back to the built-in defaults on any miss. */ export async function loadDialogueSettings(payload: Payload): Promise { @@ -54,6 +64,9 @@ export async function loadDialogueSettings(payload: Payload): Promise { + await db.execute(sql` + CREATE TYPE "public"."enum_users_preferences_dialogue_typewriter" AS ENUM('default', 'on', 'off'); + ALTER TABLE "users" ADD COLUMN "preferences_dialogue_typewriter" "enum_users_preferences_dialogue_typewriter" DEFAULT 'default'; + ALTER TABLE "npc_dialogue_settings" ADD COLUMN "presentation_typewriter_default" boolean DEFAULT true; + ALTER TABLE "_npc_dialogue_settings_v" ADD COLUMN "version_presentation_typewriter_default" boolean DEFAULT true;`) +} + +export async function down({ db, payload, req }: MigrateDownArgs): Promise { + await db.execute(sql` + ALTER TABLE "users" DROP COLUMN "preferences_dialogue_typewriter"; + ALTER TABLE "npc_dialogue_settings" DROP COLUMN "presentation_typewriter_default"; + ALTER TABLE "_npc_dialogue_settings_v" DROP COLUMN "version_presentation_typewriter_default"; + DROP TYPE "public"."enum_users_preferences_dialogue_typewriter";`) +} diff --git a/src/migrations/index.ts b/src/migrations/index.ts index ec165b84..3dfbd931 100644 --- a/src/migrations/index.ts +++ b/src/migrations/index.ts @@ -167,6 +167,7 @@ import * as migration_20261123_073019_add_tech_tree_notes from './20261123_07301 import * as migration_20261124_174637_add_npc_dialogue_prompt_settings from './20261124_174637_add_npc_dialogue_prompt_settings'; import * as migration_20261124_175950_add_ai_connections from './20261124_175950_add_ai_connections'; import * as migration_20261124_223219_add_defined_condition_ops from './20261124_223219_add_defined_condition_ops'; +import * as migration_20261124_223724_add_conversation_typewriter_setting from './20261124_223724_add_conversation_typewriter_setting'; export const migrations = [ { @@ -1012,6 +1013,11 @@ export const migrations = [ { up: migration_20261124_223219_add_defined_condition_ops.up, down: migration_20261124_223219_add_defined_condition_ops.down, - name: '20261124_223219_add_defined_condition_ops' + name: '20261124_223219_add_defined_condition_ops', + }, + { + up: migration_20261124_223724_add_conversation_typewriter_setting.up, + down: migration_20261124_223724_add_conversation_typewriter_setting.down, + name: '20261124_223724_add_conversation_typewriter_setting' }, ]; diff --git a/src/payload-types.ts b/src/payload-types.ts index f82ffbb6..954b8b77 100644 --- a/src/payload-types.ts +++ b/src/payload-types.ts @@ -552,6 +552,12 @@ export interface User { | boolean | null; }; + dialogue?: { + /** + * NPC dialogue lines type out letter by letter. Click a line to finish it immediately. Reduced-motion devices always show lines instantly. + */ + typewriter?: ('default' | 'on' | 'off') | null; + }; discord?: { enabled?: boolean | null; mutedTypes?: @@ -10479,6 +10485,11 @@ export interface UsersSelect { showBackgroundTexture?: T; sidebarOrder?: T; }; + dialogue?: + | T + | { + typewriter?: T; + }; discord?: | T | { @@ -14276,6 +14287,12 @@ export interface NpcDialogueSetting { * House conventions appended after the voice, for every conversation including ones with their own voice. Keep it short and concrete, e.g. how the unit refers to itself or which slang is banned. */ extraRules?: string | null; + presentation?: { + /** + * The default for everyone. Players can override it in their account preferences, and a player whose device asks for reduced motion never sees the animation. + */ + typewriterDefault?: boolean | null; + }; /** * Incremented automatically when the voice or house rules change. Recorded on each stored draft so you can tell which prompt produced it. */ @@ -14440,6 +14457,11 @@ export interface DiscordPresenceSelect { export interface NpcDialogueSettingsSelect { voice?: T; extraRules?: T; + presentation?: + | T + | { + typewriterDefault?: T; + }; revision?: T; updatedAt?: T; createdAt?: T; diff --git a/tests/int/npc-dialogue-presentation.int.spec.ts b/tests/int/npc-dialogue-presentation.int.spec.ts new file mode 100644 index 00000000..5b64d6a6 --- /dev/null +++ b/tests/int/npc-dialogue-presentation.int.spec.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; + +import { normalizeTypewriterPreference, resolveTypewriter } from "@/lib/npc-dialogue/presentation"; + +describe("typewriter preference resolution", () => { + it("follows the unit default unless the player chose otherwise", () => { + for (const preference of [undefined, null, "default", "nonsense"]) { + expect(resolveTypewriter(preference, true)).toBe(true); + expect(resolveTypewriter(preference, false)).toBe(false); + } + }); + + it("lets the player override the unit default in both directions", () => { + // Someone who dislikes the animation can turn it off even when it is on by + // default, and someone who wants it keeps it when the unit turns it off. + expect(resolveTypewriter("off", true)).toBe(false); + expect(resolveTypewriter("on", false)).toBe(true); + expect(resolveTypewriter("on", true)).toBe(true); + expect(resolveTypewriter("off", false)).toBe(false); + }); + + it("coerces stored values to a known preference", () => { + expect(normalizeTypewriterPreference("on")).toBe("on"); + expect(normalizeTypewriterPreference("off")).toBe("off"); + expect(normalizeTypewriterPreference("default")).toBe("default"); + expect(normalizeTypewriterPreference(undefined)).toBe("default"); + expect(normalizeTypewriterPreference("yes")).toBe("default"); + }); +}); diff --git a/tests/int/npc-dialogue-reveal.int.spec.ts b/tests/int/npc-dialogue-reveal.int.spec.ts new file mode 100644 index 00000000..111793dd --- /dev/null +++ b/tests/int/npc-dialogue-reveal.int.spec.ts @@ -0,0 +1,62 @@ +// @vitest-environment node +import React from "react"; +import { renderToStaticMarkup } from "react-dom/server"; + +import { describe, expect, it } from "vitest"; + +import { DialogueText, visibleLength } from "@/lib/npc-dialogue/DialogueText"; + +/** + * The reveal is what makes a conversation line type itself out. It must never + * expose markup, so the source is parsed in full and only the rendered strings + * are truncated: a half-typed line shows `{amber}the tra` as plain text, not + * `{amb`. + */ +function render(text: string, reveal?: number): string { + return renderToStaticMarkup(React.createElement(DialogueText, { text, reveal })); +} + +/** Rendered text content (the test inputs carry no entities or attributes). */ +function textOf(html: string): string { + return html.replace(/<[^>]*>/g, ""); +} + +describe("DialogueText reveal", () => { + it("counts visible characters only, ignoring markup", () => { + expect(visibleLength("Careful, **{amber}the trail{/}** is watched.")).toBe( + "Careful, the trail is watched.".length, + ); + expect(visibleLength("")).toBe(0); + // An inline image and a countdown are each one visible unit. + expect(visibleLength("Wait {cd|done} now")).toBe("Wait now".length + 1); + expect(visibleLength("Look ![map](/x.png) here")).toBe("Look here".length + 1); + }); + + it("reveals a prefix of the visible text at every step, never raw markup", () => { + const source = "Careful, **{amber}the trail{/}** is watched."; + const visible = "Careful, the trail is watched."; + + for (let reveal = 0; reveal <= visible.length; reveal += 1) { + const shown = textOf(render(source, reveal)); + expect(shown).toBe(visible.slice(0, reveal)); + expect(shown).not.toContain("{"); + expect(shown).not.toContain("*"); + } + + // Past the end the whole line renders, styled, with nothing lost. + const full = render(source, visible.length + 10); + expect(textOf(full)).toBe(visible); + expect(full).toContain(" { + const source = "Wait {cd|done} now"; + expect(render(source, 5)).not.toContain("ready"); + expect(render(source, 6)).toContain("ready"); + }); + + it("renders everything when no reveal is given", () => { + expect(textOf(render("Plain **line**"))).toBe("Plain line"); + }); +}); diff --git a/tests/int/npc-dialogue-settings-global.int.spec.ts b/tests/int/npc-dialogue-settings-global.int.spec.ts index 58a232e9..d08580db 100644 --- a/tests/int/npc-dialogue-settings-global.int.spec.ts +++ b/tests/int/npc-dialogue-settings-global.int.spec.ts @@ -20,7 +20,11 @@ beforeAll(async () => { payload = await getTestPayload(); }); -const update = (data: { voice?: string | null; extraRules?: string | null }) => +const update = (data: { + voice?: string | null; + extraRules?: string | null; + presentation?: { typewriterDefault?: boolean | null }; +}) => payload.updateGlobal({ slug: "npc-dialogue-settings", data, @@ -100,6 +104,27 @@ describe("npc-dialogue-settings global", () => { logger: { warn: () => undefined }, } as unknown as Payload); - expect(settings).toEqual({ voice: null, extraRules: null, revision: null }); + expect(settings).toEqual({ + voice: null, + extraRules: null, + revision: null, + typewriterDefault: true, + }); + }); + + it("carries the typewriter default without disturbing the prompt revision", async () => { + const voice = unique("Unchanged by presentation."); + const before = await update({ voice, presentation: { typewriterDefault: true } }); + const revision = before.revision; + + // Turning the animation off is not a prompt change: stored drafts must not + // look like they came from different instructions. + const off = await update({ presentation: { typewriterDefault: false } }); + expect(off.revision).toBe(revision); + expect((await loadDialogueSettings(payload)).typewriterDefault).toBe(false); + + const on = await update({ presentation: { typewriterDefault: true } }); + expect(on.revision).toBe(revision); + expect((await loadDialogueSettings(payload)).typewriterDefault).toBe(true); }); }); diff --git a/tests/int/preferences-form.int.spec.ts b/tests/int/preferences-form.int.spec.ts index 089d8ee6..be5029e8 100644 --- a/tests/int/preferences-form.int.spec.ts +++ b/tests/int/preferences-form.int.spec.ts @@ -43,6 +43,7 @@ describe("PreferencesForm", () => { discordEnabled: false, discordMutedTypes: [], xpDisplayMini: false, + conversationTypewriter: "default", }), ); @@ -50,6 +51,7 @@ describe("PreferencesForm", () => { fireEvent.click(screen.getByRole("switch", { name: "Use mini mode for XP display" })); fireEvent.click(screen.getByRole("switch", { name: "Mute all in-app notifications" })); fireEvent.click(screen.getByRole("radio", { name: "Actual" })); + fireEvent.click(screen.getByRole("radio", { name: "Show instantly" })); fireEvent.click(screen.getByRole("switch", { name: "Enable Discord notifications" })); const discordMarketOffer = document.getElementById("discord-market-offer"); if (!(discordMarketOffer instanceof HTMLElement)) { @@ -69,6 +71,7 @@ describe("PreferencesForm", () => { discordEnabled: true, discordMutedTypes: ["market:offer"], xpDisplayMini: true, + conversationTypewriter: "off", }); }); });