Typing a line in the editor felt sticky. The line box renders a live markup preview, and that preview is a full parse and render of the authored string: it ran on every character, so a long line with colours, bold and a link was re-parsed per keypress while the whole edit dialog re-rendered around it. The preview now waits 220ms after the last keystroke (the textarea itself stays instant), and both the preview and DialogueText are memoised, so an unchanged line never re-parses. DialogueText is shared with the canvas, which re-renders every card on any diagram change. Measured in the running app on a 24 node diagram and a 150 character line, 40 programmatic keystrokes through the browser's own metrics: script 319ms to 221ms (8.0 to 5.5 per key), total main-thread task 767ms to 633ms, style recalc 386ms to 338ms. The preview still updates 220ms after typing stops. What is left is the dialog re-render itself: on this file a keystroke still re-renders every section of the edit dialog. Removing that means giving the line box its own state and committing on a debounce, which needs the Save path to flush, and belongs after the in-progress poll work in NodeEditDialog lands.
231 lines
8.3 KiB
TypeScript
231 lines
8.3 KiB
TypeScript
"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 (
|
|
<div className="min-w-0 break-words rounded border border-white/10 bg-black/40 px-2 py-1.5 text-sm text-white/80">
|
|
<DialogueText text={text} />
|
|
</div>
|
|
);
|
|
});
|
|
|
|
/**
|
|
* 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<HTMLTextAreaElement | null>;
|
|
/** Show the rendered preview under the box (default true). */
|
|
preview?: boolean;
|
|
}) {
|
|
const innerRef = useRef<HTMLTextAreaElement | null>(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 (
|
|
<div className="flex flex-col gap-1">
|
|
<div className="flex flex-wrap items-center gap-1">
|
|
<button type="button" title="Bold" onClick={() => wrap("**", "**")} className={`${toolbarButton} font-bold`}>
|
|
B
|
|
</button>
|
|
<button type="button" title="Italic" onClick={() => wrap("*", "*")} className={`${toolbarButton} italic`}>
|
|
I
|
|
</button>
|
|
<button type="button" title="Code" onClick={() => wrap("`", "`")} className={toolbarButton}>
|
|
{"<>"}
|
|
</button>
|
|
<select
|
|
value=""
|
|
title="Wrap in a color"
|
|
onChange={(e) => e.target.value && wrap(`{${e.target.value}}`, "{/}")}
|
|
className="h-6 rounded-sm border border-white/15 bg-zinc-800 px-1 text-[11px] text-white/70"
|
|
>
|
|
<option value="">color</option>
|
|
{COLOR_CHOICES.map((color) => (
|
|
<option key={color} value={color}>
|
|
{color}
|
|
</option>
|
|
))}
|
|
</select>
|
|
<button type="button" title="Link (opens in a popup)" onClick={insertLink} className={toolbarButton}>
|
|
link
|
|
</button>
|
|
<button type="button" title="Bullet list" onClick={() => toggleLines("ul")} className={toolbarButton}>
|
|
• list
|
|
</button>
|
|
<button type="button" title="Numbered list" onClick={() => toggleLines("ol")} className={toolbarButton}>
|
|
1. list
|
|
</button>
|
|
</div>
|
|
<textarea
|
|
ref={textareaRef ?? innerRef}
|
|
value={value}
|
|
onChange={(e) => onChange(e.target.value)}
|
|
onContextMenu={(e) => {
|
|
e.preventDefault();
|
|
setMenu({ x: e.clientX, y: e.clientY });
|
|
}}
|
|
placeholder={placeholder}
|
|
rows={rows}
|
|
className={
|
|
className ??
|
|
"bg-zinc-800 border border-white/20 rounded px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
|
}
|
|
/>
|
|
{preview && previewText.trim() !== "" && (
|
|
<div className="flex flex-col gap-0.5">
|
|
<span className="text-[9px] uppercase tracking-wider text-white/30">Preview</span>
|
|
<MarkupPreview text={previewText} />
|
|
</div>
|
|
)}
|
|
{menu && (
|
|
<div
|
|
className="fixed z-[120] flex min-w-40 flex-col rounded border border-zinc-700 bg-zinc-900 py-1 shadow-xl"
|
|
style={{ left: menu.x, top: menu.y }}
|
|
onMouseDown={(e) => e.stopPropagation()}
|
|
>
|
|
{menuItems.map((item) => (
|
|
<button
|
|
key={item.label}
|
|
type="button"
|
|
onClick={() => {
|
|
item.run();
|
|
setMenu(null);
|
|
}}
|
|
className="px-3 py-1 text-left font-mono text-xs text-white/70 hover:bg-zinc-800 hover:text-cyan-300"
|
|
>
|
|
{item.label}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|