1
0
Fork 0
polaris-task-force/src/lib/npc-dialogue/DialogueText.tsx
Z8MB1E bf9fd09752 perf(npc-dialogue): stop re-parsing the markup preview on every keystroke
Typing a line in the editor felt sticky. The line box renders a live markup
preview, and that preview is a full parse and render of the authored string: it
ran on every character, so a long line with colours, bold and a link was re-parsed
per keypress while the whole edit dialog re-rendered around it.

The preview now waits 220ms after the last keystroke (the textarea itself stays
instant), and both the preview and DialogueText are memoised, so an unchanged
line never re-parses. DialogueText is shared with the canvas, which re-renders
every card on any diagram change.

Measured in the running app on a 24 node diagram and a 150 character line, 40
programmatic keystrokes through the browser's own metrics: script 319ms to 221ms
(8.0 to 5.5 per key), total main-thread task 767ms to 633ms, style recalc 386ms
to 338ms. The preview still updates 220ms after typing stops.

What is left is the dialog re-render itself: on this file a keystroke still
re-renders every section of the edit dialog. Removing that means giving the line
box its own state and committing on a debounce, which needs the Save path to
flush, and belongs after the in-progress poll work in NodeEditDialog lands.
2026-12-01 14:12:09 -05:00

571 lines
20 KiB
TypeScript

"use client";
import { memo, 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[];
/** Authored pauses (`{1.2s}`), positioned by how many visible characters
* precede them. Renders nothing; the schedule is what gives it a duration. */
pauses?: { at: number; ms: number }[];
}
/** One visible unit of an image or a countdown: countable, non-space, and
* 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 `**`.
*/
/** Memoised: the canvas and the editor preview render the same line many times
* per interaction, and a re-parse is the expensive part. */
const DialogueText = memo(function DialogueTextImpl({
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>
);
});
export { DialogueText };
/**
* 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 {
return visibleSegments(text).text;
}
/**
* The same walk as `visibleText`, plus where the authored pauses fall. `at` is
* the count of visible characters before the pause, so a schedule can charge
* the gap between two specific units. Markers cost nothing themselves and never
* reach the page.
*/
export function visibleSegments(text: string): {
text: string;
pauses: { at: number; ms: number }[];
} {
const budget: RevealBudget = { left: UNLIMITED_REVEAL, seen: [], pauses: [] };
renderBlocks(text, { i: 0 }, budget);
return { text: (budget.seen ?? []).join(""), pauses: budget.pauses ?? [] };
}
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})\}/;
/** An authored pause: `{1.2s}`, `{400ms}`, `{2S}`. Digits first so it can never
* collide with the colour tokens that also use braces. */
const PAUSE_RE = /^\{(\d+(?:\.\d+)?)(ms|s)\}/i;
/** Longest an authored pause may hold a line. A conversation is not a place to
* park a player, and a typo such as `{90s}` should not read as a broken line. */
export const MAX_PAUSE_MS = 10_000;
const COUNTDOWN_RE = /^\{cd\|([^}]*)\}/;
/** Only http(s) and site-relative URLs render; anything else stays literal. */
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;
}
}
}
// Authored pause. It renders nothing; the pacing schedule reads where it
// sits from the budget and gives the line that much extra time.
if (rest[0] === "{") {
const pause = PAUSE_RE.exec(rest);
if (pause) {
flush();
const amount = Number.parseFloat(pause[1]);
const ms = Math.round(pause[2].toLowerCase() === "s" ? amount * 1000 : amount);
budget.pauses?.push({
at: budget.seen ? budget.seen.reduce((total, chunk) => total + chunk.length, 0) : 0,
ms: Math.min(MAX_PAUSE_MS, Math.max(0, ms)),
});
i += pause[0].length;
continue;
}
}
// Color run: recurse so inner markup renders inside the colored span.
if (rest[0] === "{") {
const open = COLOR_OPEN_RE.exec(rest);
if (open && open[1] !== "/") {
flush();
// A failed attempt (unknown token, unclosed run) falls through and
// renders the braces literally, so what it consumed has to be given
// back: the recursion had already spent budget on the "inner" text and
// the line would otherwise count those characters twice.
const leftBefore = budget.left;
const seenBefore = budget.seen ? [...budget.seen] : undefined;
const pausesBefore = budget.pauses ? [...budget.pauses] : undefined;
const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true, budget);
const style = colorStyle(open[1]);
if (inner.closed && style) {
// 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: restore what the attempt consumed, then
// fall through and render the braces literally.
budget.left = leftBefore;
if (seenBefore) budget.seen = seenBefore;
if (pausesBefore) budget.pauses = pausesBefore;
}
}
// 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>
);
}