"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|} 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 ( {renderBlocks(text, { i: 0 }, budget)} ); }); 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( {parseSegment(chunk, 0, keys, false, budget).nodes}, ); }; const flushList = () => { if (!listKind) return; const kind = listKind; out.push( {items.map((item, index) => ( {kind === "ul" ? "\u2022" : `${index + 1}.`} {parseSegment(item, 0, keys, false, budget).nodes} ))} , ); 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 = { 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} , ); } 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(); } 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[1]}, ); } 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( {label.nodes} , ); } 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( {inner.nodes} , ); } 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( {inner.nodes} , ); } 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({inner.nodes}); } 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 ( <> { 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} { if (!next) setOpen(false); }} >
Attachment // {href.slice(0, 96)}
Open in new tab