From 1e0df827254c3c1e714eab2dbe1618ef9a119856 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 6 Oct 2026 16:21:53 -0400 Subject: [PATCH] feat(npc-dialogue): render inline images in dialogue markup --- src/lib/npc-dialogue/DialogueText.tsx | 35 +++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/src/lib/npc-dialogue/DialogueText.tsx b/src/lib/npc-dialogue/DialogueText.tsx index 397cab24..f0b4b1e2 100644 --- a/src/lib/npc-dialogue/DialogueText.tsx +++ b/src/lib/npc-dialogue/DialogueText.tsx @@ -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 {renderInline(text)}; @@ -33,7 +35,17 @@ const FRIENDLY_COLORS: Record = { 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 {part}; + return ( + {imgMatch[1]} + ); + } if (part.length > 4 && part.startsWith("**") && part.endsWith("**")) { return (