"use client";
import { memo, useEffect, useRef, useState } from "react";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
/** Friendly color names offered by the color picker (mirrors DialogueText). */
const COLOR_CHOICES = [
"red",
"amber",
"cyan",
"emerald",
"green",
"sky",
"violet",
"purple",
"pink",
"slate",
] as const;
/**
* How long the preview waits after the last keystroke.
*
* The preview is a full markup parse and render, and it used to run on every
* character: typing a long line with colours, bold and a link meant re-parsing
* the whole line per keypress, which is what made the box feel sticky. A fifth
* of a second is below noticing for a preview and removes the work entirely while
* someone is typing.
*/
const PREVIEW_DEBOUNCE_MS = 220;
/** The rendered preview, memoised so an unchanged line never re-parses. */
const MarkupPreview = memo(function MarkupPreview({ text }: { text: string }) {
return (
);
});
/**
* Textarea for authored dialogue strings with a formatting toolbar, a
* right-click markup menu, and a live `DialogueText` preview. Storage stays
* the plain custom-markup string (this only wraps the selection in tokens);
* one component serves every interpolatable field (line, narration, lead-in,
* closing, tooltip, lock message) so authoring affordances are consistent.
*/
export function MarkupEditor({
value,
onChange,
rows = 4,
placeholder,
className,
textareaRef,
preview = true,
}: {
value: string;
onChange: (next: string) => void;
rows?: number;
placeholder?: string;
/** Extra classes for the textarea itself (sizing/colors per surface). */
className?: string;
/** Optional external ref, e.g. the line box's auto-grow logic. */
textareaRef?: React.RefObject;
/** Show the rendered preview under the box (default true). */
preview?: boolean;
}) {
const innerRef = useRef(null);
const el = () => textareaRef?.current ?? innerRef.current;
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);
/** What the preview shows: the value as of the last pause in typing. */
const [previewText, setPreviewText] = useState(value);
useEffect(() => {
if (previewText === value) return;
const timer = setTimeout(() => setPreviewText(value), PREVIEW_DEBOUNCE_MS);
return () => clearTimeout(timer);
}, [value, previewText]);
// Close the context menu on any outside click or Escape.
useEffect(() => {
if (!menu) return;
const close = () => setMenu(null);
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setMenu(null);
window.addEventListener("mousedown", close);
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("mousedown", close);
window.removeEventListener("keydown", onKey);
};
}, [menu]);
/** Replace the selection with `before + sel + after`, keeping it selected. */
const wrap = (before: string, after: string) => {
const node = el();
if (!node) return;
const start = node.selectionStart;
const end = node.selectionEnd;
const selected = value.slice(start, end);
onChange(value.slice(0, start) + before + selected + after + value.slice(end));
requestAnimationFrame(() => {
node.focus();
node.setSelectionRange(start + before.length, start + before.length + selected.length);
});
};
/** Toggle a line prefix (`- `, `1. `) across the selected lines. */
const toggleLines = (kind: "ul" | "ol") => {
const node = el();
if (!node) return;
const lineStart = value.lastIndexOf("\n", node.selectionStart - 1) + 1;
const nextBreak = value.indexOf("\n", node.selectionEnd);
const lineEnd = nextBreak === -1 ? value.length : nextBreak;
const lines = value.slice(lineStart, lineEnd).split("\n");
const marker = kind === "ul" ? /^(\s*)[-*]\s/ : /^(\s*)\d+[.)]\s/;
const allMarked = lines.every((line) => marker.test(line));
const nextLines = lines.map((line, index) => {
if (allMarked) return line.replace(marker, "$1");
const stripped = line.replace(marker, "$1");
return kind === "ul" ? `- ${stripped}` : `${index + 1}. ${stripped}`;
});
onChange(value.slice(0, lineStart) + nextLines.join("\n") + value.slice(lineEnd));
requestAnimationFrame(() => node.focus());
};
const insertLink = () => {
const node = el();
if (!node) return;
const start = node.selectionStart;
const end = node.selectionEnd;
const selected = value.slice(start, end) || "label";
onChange(`${value.slice(0, start)}[${selected}](${value.slice(end)})`);
requestAnimationFrame(() => {
node.focus();
const urlAt = start + selected.length + 3;
node.setSelectionRange(urlAt, urlAt);
});
};
const toolbarButton =
"h-6 min-w-6 rounded-sm border border-white/15 bg-black/40 px-1.5 font-mono text-[11px] text-white/70 transition-colors hover:border-cyan-400/50 hover:text-cyan-300";
const menuItems: { label: string; run: () => void }[] = [
{ label: "** bold **", run: () => wrap("**", "**") },
{ label: "* italic *", run: () => wrap("*", "*") },
{ label: "` code `", run: () => wrap("`", "`") },
{ label: "[ link ]", run: insertLink },
{ label: "- bullet list", run: () => toggleLines("ul") },
{ label: "1. numbered list", run: () => toggleLines("ol") },
];
return (