- Converse button no longer floats over the hero text on phones: it sits in the card's content flow below the status chips and only anchors to the hero's right edge from md up - conversation dialog keeps a side margin on small screens instead of rendering edge-to-edge - dialog titles truncate with min-w-0 so long NPC names and attachment urls cannot push the close buttons out
340 lines
11 KiB
TypeScript
340 lines
11 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
|
|
*  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
|
|
*
|
|
* 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 }) {
|
|
return (
|
|
<span className={`whitespace-pre-wrap ${className ?? ""}`}>
|
|
{parseSegment(text, 0, { i: 0 }, false).nodes}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
/** 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): ParseResult {
|
|
const nodes: ReactNode[] = [];
|
|
let plain = "";
|
|
let i = 0;
|
|
const key = () => `${depth}:${keys.i++}`;
|
|
const flush = () => {
|
|
if (plain) {
|
|
nodes.push(plain);
|
|
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();
|
|
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>,
|
|
);
|
|
i += end + 1;
|
|
continue;
|
|
}
|
|
}
|
|
|
|
// Countdown leaf.
|
|
const cd = COUNTDOWN_RE.exec(rest);
|
|
if (cd) {
|
|
flush();
|
|
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();
|
|
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();
|
|
nodes.push(
|
|
<DialogueLink key={key()} href={href}>
|
|
{parseSegment(link[1], depth + 1, keys, false).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] !== "/") {
|
|
const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true);
|
|
const style = colorStyle(open[1]);
|
|
if (inner.closed && style) {
|
|
flush();
|
|
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();
|
|
nodes.push(
|
|
<strong key={key()} className="font-semibold">
|
|
{parseSegment(rest.slice(2, end), depth + 1, keys, false).nodes}
|
|
</strong>,
|
|
);
|
|
i += end + 2;
|
|
continue;
|
|
}
|
|
}
|
|
if (rest[0] === "*" && rest[1] !== "*") {
|
|
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>,
|
|
);
|
|
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>;
|
|
return (
|
|
<span
|
|
className="font-mono tabular-nums text-cyan-300"
|
|
title={new Date(target).toISOString()}
|
|
>
|
|
{formatRemaining(remaining)}
|
|
</span>
|
|
);
|
|
}
|