feat(npc-dialogue): type conversation lines out, with unit and player control
Conversation lines appeared whole after a length-based pause with bouncing
dots. They now type themselves out, and the player can finish a line by
clicking it.
Control is two-tier: npc-dialogue-settings.presentation.typewriterDefault sets
the unit default, users.preferences.dialogue.typewriter (default/on/off) lets a
player override it either way. prefers-reduced-motion turns the animation off
regardless. Changing the unit setting does not bump the prompt revision, since
it is not prompt text.
The reveal truncates the rendered strings rather than the source, so a
half-typed line can never flash {amber} or an unclosed **. visibleLength()
gives pacing the same count, and the choice footer waits for the reveal to
land so nobody answers a line they have not seen.
This commit is contained in:
parent
b0457a17b3
commit
66a4337ba5
21 changed files with 47727 additions and 84 deletions
|
|
@ -210,6 +210,7 @@ export async function updatePreferences(input: {
|
|||
discordEnabled: boolean;
|
||||
discordMutedTypes: string[];
|
||||
xpDisplayMini: boolean;
|
||||
conversationTypewriter: "default" | "on" | "off";
|
||||
}): Promise<ActionResult> {
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<div className="p-5 flex flex-col gap-6">
|
||||
<NpcProfile
|
||||
npc={npc}
|
||||
listings={listings}
|
||||
conversationSlot={
|
||||
<NpcConversation npc={npc} dialogue={dialogue} initialSeenNodeIds={seenNodeIds} />
|
||||
<NpcConversation
|
||||
npc={npc}
|
||||
dialogue={dialogue}
|
||||
initialSeenNodeIds={seenNodeIds}
|
||||
typewriter={typewriterEnabled}
|
||||
/>
|
||||
}
|
||||
employmentSlot={
|
||||
<EmploymentCard
|
||||
|
|
|
|||
|
|
@ -80,6 +80,23 @@ export const NpcDialogueSettings: GlobalConfig = {
|
|||
"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.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "presentation",
|
||||
label: "Presentation",
|
||||
type: "group",
|
||||
fields: [
|
||||
{
|
||||
name: "typewriterDefault",
|
||||
label: "Type conversation lines out character by character",
|
||||
type: "checkbox",
|
||||
defaultValue: true,
|
||||
admin: {
|
||||
description:
|
||||
"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.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "revision",
|
||||
type: "number",
|
||||
|
|
|
|||
|
|
@ -322,6 +322,28 @@ export const Users: CollectionConfig = {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "dialogue",
|
||||
label: "Conversations",
|
||||
type: "group",
|
||||
fields: [
|
||||
{
|
||||
name: "typewriter",
|
||||
label: "Typing animation in conversations",
|
||||
type: "select",
|
||||
defaultValue: "default",
|
||||
options: [
|
||||
{ label: "Use the unit default", value: "default" },
|
||||
{ label: "Always type lines out", value: "on" },
|
||||
{ label: "Show lines instantly", value: "off" },
|
||||
],
|
||||
admin: {
|
||||
description:
|
||||
"NPC dialogue lines type out letter by letter. Click a line to finish it immediately. Reduced-motion devices always show lines instantly.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "discord",
|
||||
label: "Discord",
|
||||
|
|
|
|||
|
|
@ -117,6 +117,7 @@ export function CommandPalette({
|
|||
discordEnabled: preferences?.discord?.enabled ?? false,
|
||||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: preferences?.display?.xpDisplayMini ?? false,
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
});
|
||||
if (result.success) {
|
||||
toast.success("Background texture toggled");
|
||||
|
|
@ -137,6 +138,7 @@ export function CommandPalette({
|
|||
discordEnabled: preferences?.discord?.enabled ?? false,
|
||||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: preferences?.display?.xpDisplayMini ?? false,
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
});
|
||||
if (result.success) {
|
||||
toast.success("Callsign display toggled");
|
||||
|
|
@ -157,6 +159,7 @@ export function CommandPalette({
|
|||
discordEnabled: preferences?.discord?.enabled ?? false,
|
||||
discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
|
||||
xpDisplayMini: !(preferences?.display?.xpDisplayMini ?? false),
|
||||
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
|
||||
});
|
||||
if (result.success) {
|
||||
toast.success("XP display toggled");
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ interface PreferencesFormProps {
|
|||
readonly discordEnabled: boolean;
|
||||
readonly discordMutedTypes: readonly string[];
|
||||
readonly xpDisplayMini: boolean;
|
||||
/** Stored choice for the NPC conversation typing animation. */
|
||||
readonly conversationTypewriter: "default" | "on" | "off";
|
||||
}
|
||||
|
||||
export function PreferencesForm({
|
||||
|
|
@ -34,6 +36,7 @@ export function PreferencesForm({
|
|||
discordEnabled: initialDiscordEnabled,
|
||||
discordMutedTypes: initialDiscordMutedTypes,
|
||||
xpDisplayMini: initialXPDisplayMini,
|
||||
conversationTypewriter: initialConversationTypewriter,
|
||||
}: PreferencesFormProps) {
|
||||
const router = useRouter();
|
||||
const [mutedAll, setMutedAll] = useState(initialMutedAll);
|
||||
|
|
@ -47,6 +50,9 @@ export function PreferencesForm({
|
|||
...initialDiscordMutedTypes,
|
||||
]);
|
||||
const [xpDisplayMini, setXPDisplayMini] = useState(initialXPDisplayMini);
|
||||
const [conversationTypewriter, setConversationTypewriter] = useState<
|
||||
"default" | "on" | "off"
|
||||
>(initialConversationTypewriter);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(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({
|
|||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Conversations</CardTitle>
|
||||
<CardDescription>
|
||||
How NPC dialogue is presented when you talk to a contact.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2">
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-sm font-medium">Typing animation</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Type lines out letter by letter. Click a line to finish it immediately.
|
||||
Devices set to reduce motion always show lines instantly.
|
||||
</span>
|
||||
</div>
|
||||
<RadioGroup
|
||||
value={conversationTypewriter}
|
||||
onValueChange={(value) => {
|
||||
if (value === "default" || value === "on" || value === "off") {
|
||||
setConversationTypewriter(value);
|
||||
}
|
||||
}}
|
||||
className="flex flex-wrap gap-4"
|
||||
aria-label="Typing animation in conversations"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem id="typewriter-default" value="default" />
|
||||
<Label htmlFor="typewriter-default" className="py-1.5">
|
||||
Unit default
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem id="typewriter-on" value="on" />
|
||||
<Label htmlFor="typewriter-on" className="py-1.5">
|
||||
Always type out
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RadioGroupItem id="typewriter-off" value="off" />
|
||||
<Label htmlFor="typewriter-off" className="py-1.5">
|
||||
Show instantly
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Notifications</CardTitle>
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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<void>((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<LogEntry[]>([]);
|
||||
|
|
@ -82,6 +123,11 @@ export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConver
|
|||
const [typing, setTyping] = useState<string | null>(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<string | null>(null);
|
||||
/** Set by clicking the log: finish the line instead of waiting. */
|
||||
const skipRevealRef = useRef<string | null>(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
|
|||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={scrollRef} className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
onClick={() => {
|
||||
// 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) => (
|
||||
<TimelineEntry key={entry.id} entry={entry} speakerDefault={npc.name} />
|
||||
))}
|
||||
|
|
@ -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 (
|
||||
<div className="flex flex-col items-center gap-2 py-1 text-center">
|
||||
<p className="max-w-[42rem] text-sm italic leading-relaxed text-white/55">
|
||||
<DialogueText text={text} />
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
</p>
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
|
|
@ -501,7 +590,7 @@ function TimelineEntry({
|
|||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
|
||||
<DialogueText text={text} />
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
</p>
|
||||
<DialogueAttachments attachments={resolved?.attachments} />
|
||||
</div>
|
||||
|
|
@ -509,33 +598,30 @@ function TimelineEntry({
|
|||
}
|
||||
|
||||
if (node.type === "end") {
|
||||
const text = (resolved?.closing ?? node.data.closing) || "The conversation ends.";
|
||||
return (
|
||||
<p className="text-sm italic text-white/50">
|
||||
<DialogueText text={text} />
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<p className="text-sm italic text-white/60">
|
||||
<DialogueText text={leadIn} />
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
const speaker = node.data.speaker?.trim() || speakerDefault;
|
||||
const body = resolved?.body ?? node.data.body;
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className={DOSSIER.readoutLabel}>{speaker}</span>
|
||||
<p className="text-sm text-white/90">
|
||||
{body ? (
|
||||
<DialogueText text={body} />
|
||||
{text ? (
|
||||
<DialogueText text={text} reveal={reveal} />
|
||||
) : (
|
||||
<span className="italic text-white/30">…</span>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -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` ``, ``,
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<span className={`whitespace-pre-wrap ${className ?? ""}`}>
|
||||
{renderBlocks(text, { i: 0 })}
|
||||
{renderBlocks(text, { i: 0 }, budget)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(<span key={`p${keys.i++}`}>{parseSegment(chunk, 0, keys, false).nodes}</span>);
|
||||
out.push(
|
||||
<span key={`p${keys.i++}`}>{parseSegment(chunk, 0, keys, false, budget).nodes}</span>,
|
||||
);
|
||||
};
|
||||
const flushList = () => {
|
||||
if (!listKind) return;
|
||||
|
|
@ -65,7 +108,7 @@ function renderBlocks(text: string, keys: { i: number }): ReactNode[] {
|
|||
<span aria-hidden className="shrink-0 text-white/40">
|
||||
{kind === "ul" ? "\u2022" : `${index + 1}.`}
|
||||
</span>
|
||||
<span>{parseSegment(item, 0, keys, false).nodes}</span>
|
||||
<span>{parseSegment(item, 0, keys, false, budget).nodes}</span>
|
||||
</span>
|
||||
))}
|
||||
</span>,
|
||||
|
|
@ -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(
|
||||
<code
|
||||
key={key()}
|
||||
className="rounded-sm bg-white/10 px-1 py-0.5 font-mono text-[0.85em] text-cyan-300"
|
||||
>
|
||||
{rest.slice(1, end)}
|
||||
</code>,
|
||||
);
|
||||
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
|
||||
key={key()}
|
||||
className="rounded-sm bg-white/10 px-1 py-0.5 font-mono text-[0.85em] text-cyan-300"
|
||||
>
|
||||
{code}
|
||||
</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(<Countdown key={key()} value={cd[1]} />);
|
||||
if (budget.left >= 1) {
|
||||
budget.left -= 1;
|
||||
nodes.push(<Countdown key={key()} value={cd[1]} />);
|
||||
}
|
||||
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
|
||||
key={key()}
|
||||
src={src}
|
||||
alt={img[1]}
|
||||
className="mx-0.5 inline-block h-[1.15em] w-auto align-[-0.2em] object-contain"
|
||||
/>,
|
||||
);
|
||||
if (budget.left >= 1) {
|
||||
budget.left -= 1;
|
||||
nodes.push(
|
||||
<img
|
||||
key={key()}
|
||||
src={src}
|
||||
alt={img[1]}
|
||||
className="mx-0.5 inline-block h-[1.15em] w-auto align-[-0.2em] object-contain"
|
||||
/>,
|
||||
);
|
||||
}
|
||||
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(
|
||||
<DialogueLink key={key()} href={href}>
|
||||
{parseSegment(link[1], depth + 1, keys, false).nodes}
|
||||
</DialogueLink>,
|
||||
);
|
||||
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(
|
||||
<DialogueLink key={key()} href={href}>
|
||||
{label.nodes}
|
||||
</DialogueLink>,
|
||||
);
|
||||
}
|
||||
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(
|
||||
<span key={key()} className={style.className} style={style.style}>
|
||||
{inner.nodes}
|
||||
</span>,
|
||||
);
|
||||
// An unrevealed run contributes nothing; the span appears with the
|
||||
// first character inside it.
|
||||
if (inner.nodes.length > 0) {
|
||||
nodes.push(
|
||||
<span key={key()} className={style.className} style={style.style}>
|
||||
{inner.nodes}
|
||||
</span>,
|
||||
);
|
||||
}
|
||||
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(
|
||||
<strong key={key()} className="font-semibold">
|
||||
{parseSegment(rest.slice(2, end), depth + 1, keys, false).nodes}
|
||||
</strong>,
|
||||
);
|
||||
const inner = parseSegment(rest.slice(2, end), depth + 1, keys, false, budget);
|
||||
if (inner.nodes.length > 0) {
|
||||
nodes.push(
|
||||
<strong key={key()} className="font-semibold">
|
||||
{inner.nodes}
|
||||
</strong>,
|
||||
);
|
||||
}
|
||||
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(
|
||||
<em key={key()}>
|
||||
{parseSegment(rest.slice(1, end), depth + 1, keys, false).nodes}
|
||||
</em>,
|
||||
);
|
||||
const inner = parseSegment(rest.slice(1, end), depth + 1, keys, false, budget);
|
||||
if (inner.nodes.length > 0) {
|
||||
nodes.push(<em key={key()}>{inner.nodes}</em>);
|
||||
}
|
||||
i += end + 1;
|
||||
continue;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<DialoguePromptSettings> {
|
||||
|
|
@ -54,6 +64,9 @@ export async function loadDialogueSettings(payload: Payload): Promise<DialoguePr
|
|||
voice: doc?.voice?.trim() || null,
|
||||
extraRules: doc?.extraRules?.trim() || null,
|
||||
revision: typeof doc?.revision === "number" ? doc.revision : null,
|
||||
// Only an explicit false turns it off, so a document written before this
|
||||
// field existed still types out (its default).
|
||||
typewriterDefault: doc?.presentation?.typewriterDefault !== false,
|
||||
};
|
||||
} catch (error) {
|
||||
// A missing global (fresh database before the migration ran) must not make
|
||||
|
|
|
|||
36
src/lib/npc-dialogue/presentation.ts
Normal file
36
src/lib/npc-dialogue/presentation.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
/**
|
||||
* Player-facing presentation preferences for NPC conversations.
|
||||
*
|
||||
* The unit default lives on the `npc-dialogue-settings` global; a player may
|
||||
* override it in their account preferences. Resolution is pure so the contact
|
||||
* page, the account form and the tests all agree, and so the component never has
|
||||
* to guess what a missing value means.
|
||||
*/
|
||||
|
||||
/** Stored per-user choice. `default` defers to the unit setting. */
|
||||
export type TypewriterPreference = "default" | "on" | "off";
|
||||
|
||||
/** The three stored values, in the order the account form shows them. */
|
||||
export const TYPEWRITER_PREFERENCE_VALUES: TypewriterPreference[] = ["default", "on", "off"];
|
||||
|
||||
/**
|
||||
* Whether conversation lines type out for this player.
|
||||
*
|
||||
* An explicit player choice always wins, in either direction: a player who
|
||||
* dislikes the animation can turn it off even when the unit default is on, and a
|
||||
* player who wants it can keep it when the unit default is off. Anything else
|
||||
* (unset, `default`, an unknown stored value) follows the unit setting.
|
||||
*/
|
||||
export function resolveTypewriter(
|
||||
preference: TypewriterPreference | string | null | undefined,
|
||||
unitDefault: boolean,
|
||||
): boolean {
|
||||
if (preference === "on") return true;
|
||||
if (preference === "off") return false;
|
||||
return unitDefault;
|
||||
}
|
||||
|
||||
/** Coerce a stored value to a known preference; unknown values mean `default`. */
|
||||
export function normalizeTypewriterPreference(value: unknown): TypewriterPreference {
|
||||
return value === "on" || value === "off" ? value : "default";
|
||||
}
|
||||
47128
src/migrations/20261124_223724_add_conversation_typewriter_setting.json
Normal file
47128
src/migrations/20261124_223724_add_conversation_typewriter_setting.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,17 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
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<void> {
|
||||
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";`)
|
||||
}
|
||||
|
|
@ -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'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -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<T extends boolean = true> {
|
|||
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<T extends boolean = true> {
|
|||
export interface NpcDialogueSettingsSelect<T extends boolean = true> {
|
||||
voice?: T;
|
||||
extraRules?: T;
|
||||
presentation?:
|
||||
| T
|
||||
| {
|
||||
typewriterDefault?: T;
|
||||
};
|
||||
revision?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
|
|
|
|||
29
tests/int/npc-dialogue-presentation.int.spec.ts
Normal file
29
tests/int/npc-dialogue-presentation.int.spec.ts
Normal file
|
|
@ -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");
|
||||
});
|
||||
});
|
||||
62
tests/int/npc-dialogue-reveal.int.spec.ts
Normal file
62
tests/int/npc-dialogue-reveal.int.spec.ts
Normal file
|
|
@ -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  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("<strong");
|
||||
expect(full).toContain("text-amber-400");
|
||||
});
|
||||
|
||||
it("holds back components until the reveal reaches them", () => {
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue