"use client";
import { useRef, useState, type CSSProperties, type ReactNode } from "react";
/** Edit a text layer in its own bounds. Enter/blur commits; Escape cancels. */
export function InlineText({ value, label, buttonLabel = value, title, onCommit, onBegin, onEditing, onDraft, formatValue, editorStyle, onMoveStart, onMove, onNudge, className, style, children, multiline = false, maxLength }: {
value: string;
label: string;
buttonLabel?: string;
title?: string;
onCommit: (value: string) => void;
onBegin?: () => void;
onEditing?: (editing: boolean) => void;
onDraft?: (text: string | null) => void;
formatValue?: (text: string) => string;
editorStyle?: CSSProperties;
onMoveStart?: () => void;
onMove?: (dx: number, dy: number) => void;
onNudge?: (dx: number, dy: number) => void;
className?: string;
style?: CSSProperties;
children?: ReactNode;
multiline?: boolean;
maxLength?: number;
}) {
const [editing, setEditing] = useState(false);
const [text, setText] = useState(value);
const finished = useRef(false);
const drag = useRef<{ x: number; y: number; moved: boolean } | null>(null);
const dragged = useRef(false);
const finish = (commit: boolean) => {
if (finished.current) return;
finished.current = true;
if (commit) onCommit(text.trim().replace(/\s+/g, " "));
onDraft?.(null);
setEditing(false);
onEditing?.(false);
};
if (!editing) return (
);
const props = {
autoFocus: true,
"aria-label": label,
value: text,
maxLength,
className,
style: { ...style, ...editorStyle },
spellCheck: false,
onChange: (event: React.ChangeEvent) => {
const input = event.target, raw = input.value;
const formatted = (event.nativeEvent as InputEvent).isComposing ? raw : formatValue?.(raw) ?? raw;
const start = raw.slice(0, input.selectionStart ?? raw.length).replace(/\s+/g, " ").trimStart().length;
const end = raw.slice(0, input.selectionEnd ?? raw.length).replace(/\s+/g, " ").trimStart().length;
setText(formatted); onDraft?.(formatted);
if (formatted !== raw) requestAnimationFrame(() => {
if (document.activeElement === input) input.setSelectionRange(start, end);
});
},
onBlur: () => finish(true),
onKeyDown: (event: React.KeyboardEvent) => {
event.stopPropagation();
if (event.nativeEvent.isComposing) return;
if (event.key === "Escape" || (event.key === "Enter" && !event.shiftKey)) {
event.preventDefault();
finish(event.key === "Enter");
}
},
};
return multiline ? : ;
}