1
0
Fork 0

feat(npc-dialogue): render inline images in dialogue markup

This commit is contained in:
Jason Fraley 2026-10-06 16:21:53 -04:00
parent c7be90f689
commit 1e0df82725

View file

@ -2,10 +2,12 @@ import type { ReactNode } from "react";
/**
* Renders a dialogue string for display: newlines are preserved and a tiny
* inline markup subset is honoured (**bold**, *italic*, `code`, and
* {color}text{/}). Colors take a friendly name ({red}, {cyan}, ...) or a hex
* code ({#ff00ff}). Shared by the admin flow editor previews and the frontend
* conversation dialog, so it must stay client-safe (no Payload imports).
* inline markup subset is honoured (**bold**, *italic*, `code`, colored runs
* and ![alt](url) inline images). Colors take a friendly name ({red}, {cyan},
* ...) or a hex code ({#ff00ff}). Images render at text height like icons and
* accept only http(s) or site-relative URLs (e.g. /api/media/file/coin.png).
* 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 ?? ""}`}>{renderInline(text)}</span>;
@ -33,7 +35,17 @@ const FRIENDLY_COLORS: Record<string, string> = {
const HEX_COLOR = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
const INLINE_PATTERN =
/(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\{(?:#[0-9a-fA-F]{3,6}|[a-zA-Z]+)\}[^{}]*\{\/\})/g;
/(!\[[^\]]*\]\([^()\s]*\)|\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\{(?:#[0-9a-fA-F]{3,6}|[a-zA-Z]+)\}[^{}]*\{\/\})/g;
/** Matches one `![alt](url)` token produced by INLINE_PATTERN. */
const IMG_TOKEN = /^!\[([^\]]*)\]\(([^()\s]*)\)$/;
/** Only http(s) and site-relative URLs render as images; anything else stays literal. */
function safeImageSrc(url: string): string | null {
if (/^https?:\/\//i.test(url)) return url;
if (url.startsWith("/") && !url.startsWith("//")) return url;
return null;
}
/** Matches one colour token produced by INLINE_PATTERN. */
const COLOR_TOKEN = /^\{(#?[a-zA-Z0-9#]+)\}([^{}]*)\{\/\}$/;
@ -41,6 +53,19 @@ const COLOR_TOKEN = /^\{(#?[a-zA-Z0-9#]+)\}([^{}]*)\{\/\}$/;
function renderInline(text: string): ReactNode {
const parts = text.split(INLINE_PATTERN);
return parts.map((part, index) => {
const imgMatch = part.match(IMG_TOKEN);
if (imgMatch) {
const src = safeImageSrc(imgMatch[2]);
if (!src) return <span key={index}>{part}</span>;
return (
<img
key={index}
src={src}
alt={imgMatch[1]}
className="mx-0.5 inline-block h-[1.15em] w-auto align-[-0.2em] object-contain"
/>
);
}
if (part.length > 4 && part.startsWith("**") && part.endsWith("**")) {
return (
<strong key={index} className="font-semibold">