Files
Endoleap/src/components/canvas/node-title.tsx
T

21 lines
1.7 KiB
TypeScript

"use client";
import { useContext, useEffect, useRef, useState } from "react";
import { NodeEditing } from "./transformable-node";
import styles from "./canvas.module.css";
export function NodeTitle({ id, title, selected }: { id: string; title: string; selected: boolean }) {
const actions = useContext(NodeEditing);
const [editing, setEditing] = useState(false), [value, setValue] = useState(title);
const input = useRef<HTMLInputElement>(null), cancelled = useRef(false);
useEffect(() => { if (!editing) setValue(title); }, [title, editing]);
useEffect(() => { if (!selected) setEditing(false); }, [selected]);
useEffect(() => { if (editing) { input.current?.focus(); input.current?.select(); } }, [editing]);
function save() {
if (!cancelled.current) { const name = value.trim(); if (name && name !== title) actions.rename(id, name); }
cancelled.current = false; setEditing(false);
}
if (editing) return <input ref={input} className={`${styles.nodeTitleInput} nodrag nopan nowheel`} value={value} maxLength={300} aria-label="节点名称" onChange={(event) => setValue(event.target.value)} onBlur={save}
onKeyDown={(event) => { event.stopPropagation(); if (event.key === "Enter" && !event.nativeEvent.isComposing) event.currentTarget.blur(); if (event.key === "Escape") { cancelled.current = true; event.currentTarget.blur(); } }} />;
return <span className={styles.nodeTitle} title="双击编辑名称" role="button" tabIndex={selected ? 0 : -1} onDoubleClick={(event) => { event.preventDefault(); event.stopPropagation(); actions.select(id); setEditing(true); }}
onKeyDown={(event) => { if (event.key === "F2" || event.key === "Enter") { event.preventDefault(); event.stopPropagation(); setEditing(true); } }}>{title}</span>;
}