1
0
Fork 0
polaris-task-force/src/lib/npc-dialogue/DialogueText.tsx
Z8MB1E 464ba2d5d4 feat(npc-dialogue): natural typing rhythm, a beat between lines, a typing sound
The reveal was one linear clock, so every character cost the same and a comma
had nowhere to breathe. It now runs off a schedule: each visible unit costs
BASE_UNIT_MS plus a pause after it, longer at a sentence end and longest at a
line or paragraph break. Pauses never stack (a break after a full stop owns the
pause) and a comma inside a number is not a clause. The schedule is built in
relative units and scaled to the target duration, so a line paced to a recorded
clip keeps the rhythm instead of flattening it.

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

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

visibleLength is now defined as visibleText(text).length, so the schedule and the
renderer cannot disagree about how long a line is.
2026-11-24 19:20:11 -05:00

517 lines
17 KiB
TypeScript

"use client";
import { useEffect, useState, type ReactNode } from "react";
import { ExternalLinkIcon, XIcon } from "lucide-react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
/**
* Renders a dialogue string for display. Newlines are preserved and a tiny
* inline markup subset is honoured, freely NESTABLE (markup accumulates):
*
* **bold**, *italic*, `code`
* {green}colored{/} or {#ff00ff} — wraps bold/italic/images/links inside it
* ![alt](url) inline images at text height (http(s) or site-relative URLs)
* [label](url) links opening in an in-page popup frame (same-origin pages
* stay put; no navigation, so conversation progress survives)
* {cd|<iso|done>} countdown leaf produced by `{{countdown:key}}` resolution
*
* Block level: consecutive lines starting with `- `/`* ` render as a bullet
* list, consecutive lines starting with `1.`/`2)` as an ordered list; item
* content runs through the inline parser like any other text. A line whose
* prose merely starts with "- " also becomes a bullet, so start list items
* deliberately.
*
* Shared by the admin flow editor previews and the frontend conversation
* dialog, so it must stay client-safe (no Payload imports).
*/
/**
* 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;
/** Every unit the budget granted, in order, when the caller asked for it.
* An image or a countdown contributes one placeholder character (it costs
* one unit but renders no text of its own). */
seen?: string[];
}
/** One visible unit of an image or a countdown: countable, non-space, and
* never mistaken for punctuation by the pacing schedule. */
const ATOMIC_UNIT = "\uFFFC";
/** Budget for a fully revealed line (a number, not Infinity, so the consumed
* count stays computable). */
const UNLIMITED_REVEAL = Number.MAX_SAFE_INTEGER;
/**
* 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 }, 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 {
return visibleText(text).length;
}
/**
* The line's visible characters, flattened in reveal order, so a schedule can
* be built per unit (a pause belongs after a particular comma). Built by the
* same walk as `visibleLength`, which is defined in terms of it, so the two
* cannot drift: markup and list prefixes contribute nothing, an image or a
* countdown contributes `ATOMIC_UNIT`, and a code run appears all at once when
* it fits.
*/
export function visibleText(text: string): string {
const budget: RevealBudget = { left: UNLIMITED_REVEAL, seen: [] };
renderBlocks(text, { i: 0 }, budget);
return (budget.seen ?? []).join("");
}
const BULLET_RE = /^[-*]\s+/;
const ORDERED_RE = /^\d+[.)]\s+/;
/**
* Line-based block pass over `text`: runs of bullet / ordered lines collapse
* into list groups (spans with list roles, so they stay valid inside the
* 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 }, budget: RevealBudget): ReactNode[] {
if (!text) return [];
const out: ReactNode[] = [];
let paragraph: string[] = [];
let listKind: "ul" | "ol" | null = null;
let items: string[] = [];
const flushParagraph = () => {
if (paragraph.length === 0) return;
const chunk = paragraph.join("\n");
paragraph = [];
out.push(
<span key={`p${keys.i++}`}>{parseSegment(chunk, 0, keys, false, budget).nodes}</span>,
);
};
const flushList = () => {
if (!listKind) return;
const kind = listKind;
out.push(
<span key={`l${keys.i++}`} role="list" className="my-0.5 flex flex-col gap-0.5 pl-2">
{items.map((item, index) => (
<span key={index} role="listitem" className="flex gap-2">
<span aria-hidden className="shrink-0 text-white/40">
{kind === "ul" ? "\u2022" : `${index + 1}.`}
</span>
<span>{parseSegment(item, 0, keys, false, budget).nodes}</span>
</span>
))}
</span>,
);
items = [];
listKind = null;
};
for (const line of text.split("\n")) {
const kind: "ul" | "ol" | null = BULLET_RE.test(line)
? "ul"
: ORDERED_RE.test(line)
? "ol"
: null;
if (kind) {
if (listKind && listKind !== kind) flushList();
flushParagraph();
listKind = kind;
items.push(line.replace(kind === "ul" ? BULLET_RE : ORDERED_RE, ""));
continue;
}
if (listKind) flushList();
paragraph.push(line);
}
flushList();
flushParagraph();
return out;
}
/** Friendly color names mapped to Tailwind text classes (400 shades read well
* on the dark conversation surface). Keys are lowercase. */
const FRIENDLY_COLORS: Record<string, string> = {
red: "text-red-400",
rose: "text-rose-400",
orange: "text-orange-400",
amber: "text-amber-400",
yellow: "text-yellow-400",
green: "text-green-400",
emerald: "text-emerald-400",
cyan: "text-cyan-400",
sky: "text-sky-400",
blue: "text-blue-400",
violet: "text-violet-400",
purple: "text-purple-400",
pink: "text-pink-400",
slate: "text-slate-300",
};
const HEX_COLOR = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
/** Guards against pathological nesting like `**{red}**{red}**...`. */
const MAX_DEPTH = 8;
const IMG_RE = /^!\[([^\]]*)\]\(([^()\s]*)\)/;
const LINK_RE = /^\[([^\]]*)\]\(([^()\s]*)\)/;
const COLOR_OPEN_RE = /^\{([^{}|]{1,20})\}/;
const COUNTDOWN_RE = /^\{cd\|([^}]*)\}/;
/** Only http(s) and site-relative URLs render; anything else stays literal. */
function safeUrl(url: string): string | null {
if (/^https?:\/\//i.test(url)) return url;
if (url.startsWith("/") && !url.startsWith("//")) return url;
return null;
}
interface ParseResult {
nodes: ReactNode[];
/** True when the segment ended at a `{/}` (consumed by the caller's color). */
closed: boolean;
/** Characters consumed, including the closing `{/}` when closed. */
consumed: number;
}
/**
* Scans `text` left to right, turning markup runs into elements and recursing
* into their contents so styling accumulates (a bold run inside a color span
* 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,
budget: RevealBudget,
): ParseResult {
const nodes: ReactNode[] = [];
let plain = "";
let i = 0;
const key = () => `${depth}:${keys.i++}`;
const flush = () => {
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;
budget.seen?.push(plain.slice(0, take));
}
plain = "";
};
while (i < text.length) {
const rest = text.slice(i);
if (insideColor && rest.startsWith("{/}")) {
flush();
return { nodes, closed: true, consumed: i + 3 };
}
if (depth < MAX_DEPTH) {
// Inline code (literal content, no nesting).
if (rest[0] === "`") {
const end = rest.indexOf("`", 1);
if (end > 1) {
flush();
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;
budget.seen?.push(code);
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;
}
}
// Countdown leaf.
const cd = COUNTDOWN_RE.exec(rest);
if (cd) {
flush();
if (budget.left >= 1) {
budget.left -= 1;
budget.seen?.push(ATOMIC_UNIT);
nodes.push(<Countdown key={key()} value={cd[1]} />);
}
i += cd[0].length;
continue;
}
// Image (leaf).
if (rest.startsWith("![")) {
const img = IMG_RE.exec(rest);
if (img) {
const src = safeUrl(img[2]);
if (src) {
flush();
if (budget.left >= 1) {
budget.left -= 1;
budget.seen?.push(ATOMIC_UNIT);
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;
}
}
}
// Link: label keeps its own markup; the popup frame preserves context.
if (rest[0] === "[") {
const link = LINK_RE.exec(rest);
if (link) {
const href = safeUrl(link[2]);
if (href) {
flush();
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;
}
}
}
// 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();
const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true, budget);
const style = colorStyle(open[1]);
if (inner.closed && style) {
// 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;
}
// Unknown token or unclosed: fall through and render literally.
}
}
// Bold, then italic (bold checked first so `**` never reads as two stars).
if (rest.startsWith("**")) {
const end = rest.indexOf("**", 2);
if (end > 2) {
flush();
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;
}
}
if (rest[0] === "*" && rest[1] !== "*") {
const end = rest.indexOf("*", 1);
if (end > 1 && rest[end + 1] !== "*") {
flush();
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;
}
}
}
plain += text[i];
i += 1;
}
flush();
return { nodes, closed: false, consumed: text.length };
}
/** Resolves a color token to a className or inline style; null = not a color. */
function colorStyle(token: string): { className?: string; style?: { color: string } } | null {
if (token.startsWith("#")) {
// Only well-formed hex codes reach the style attribute; anything else
// (e.g. {#12345}) renders as literal text.
return HEX_COLOR.test(token) ? { style: { color: token } } : null;
}
const cls = FRIENDLY_COLORS[token.toLowerCase()];
return cls ? { className: cls } : null;
}
/**
* A dialogue link. Clicking opens the destination in a popup frame instead of
* navigating, so the conversation (and its progress) stays mounted behind it.
*/
function DialogueLink({ href, children }: { href: string; children: ReactNode }) {
const [open, setOpen] = useState(false);
return (
<>
<a
href={href}
onClick={(event) => {
event.preventDefault();
setOpen(true);
}}
className="font-medium text-cyan-400 underline decoration-cyan-500/40 underline-offset-2 transition-colors hover:text-cyan-300"
>
{children}
</a>
<Dialog
open={open}
onOpenChange={(next) => {
if (!next) setOpen(false);
}}
>
<DialogContent
showCloseButton={false}
className="flex h-[85vh] w-[92vw] max-w-6xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white sm:max-w-6xl"
>
<div className="flex items-center justify-between gap-4 border-b border-white/15 bg-black/50 px-4 py-2 backdrop-blur-sm">
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
Attachment // {href.slice(0, 96)}
</DialogTitle>
<div className="flex shrink-0 items-center gap-3">
<a
href={href}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-widest text-white/40 transition-colors hover:text-cyan-400"
>
<ExternalLinkIcon className="size-3" />
Open in new tab
</a>
<button
type="button"
onClick={() => setOpen(false)}
aria-label="Close attachment"
className="text-white/40 transition-colors hover:text-white/90"
>
<XIcon className="size-4" />
</button>
</div>
</div>
<iframe
src={href}
title="Dialogue link"
className="min-h-0 flex-1 bg-zinc-900"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
/>
</DialogContent>
</Dialog>
</>
);
}
/** Formats a countdown duration: `2d 07h`, `7h 05m`, `12m 03s`, `9s`. */
export function formatRemaining(ms: number): string {
const total = Math.max(0, Math.floor(ms / 1000));
const days = Math.floor(total / 86400);
const hours = Math.floor((total % 86400) / 3600);
const minutes = Math.floor((total % 3600) / 60);
const seconds = total % 60;
if (days > 0) return `${days}d ${hours}h`;
if (hours > 0) return `${hours}h ${String(minutes).padStart(2, "0")}m`;
if (minutes > 0) return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
return `${seconds}s`;
}
/**
* Live countdown leaf. Value is an ISO activation time (ticks every second),
* `done` (the flag already activated), or empty (flag missing: renders
* nothing). Ticks client-side from the mount-time clock.
*/
function Countdown({ value }: { value: string }) {
const target = value === "done" || value === "" ? null : Date.parse(value);
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (target === null || Number.isNaN(target)) return;
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, [target]);
if (value === "done") return <span className="font-mono text-emerald-400">ready</span>;
if (value === "") return null;
if (target === null || Number.isNaN(target)) return null;
const remaining = target - now;
if (remaining <= 0) return <span className="font-mono text-emerald-400">ready</span>;
// Each unit is its own inline-flex cell so the gap between them is controlled
// (a monospace font's raw space reads wide/odd inline with proportional text).
return (
<span
className="inline-flex items-center gap-1.5 font-mono tabular-nums text-cyan-300"
title={new Date(target).toISOString()}
>
{formatRemaining(remaining)
.split(" ")
.map((unit, i) => (
<span key={i} className="whitespace-nowrap">
{unit}
</span>
))}
</span>
);
}