"use client"; import * as React from "react"; import { PencilIcon } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { MAX_TASK_REMARK_RUNES } from "@/lib/types"; import { cn } from "@/lib/utils"; type EditorProps = { value?: string; label: string; onSave: (value: string) => Promise; }; export function RemarkEditor(props: EditorProps) { return ; } export function ScheduleNameEditor(props: EditorProps) { return ; } function InlineTextEditor({ value = "", label, onSave, multiline, fieldName, maxCharacters, emptyLabel, }: EditorProps & { multiline: boolean; fieldName: string; maxCharacters: number; emptyLabel: string }) { const [editing, setEditing] = React.useState(false); const [draft, setDraft] = React.useState(value); const [saving, setSaving] = React.useState(false); const [error, setError] = React.useState(""); const inputRef = React.useRef(null); const textareaRef = React.useRef(null); const cancelOnBlurRef = React.useRef(false); const savingRef = React.useRef(false); const errorID = React.useId(); React.useEffect(() => { if (!editing) setDraft(value); }, [editing, value]); function refocus() { requestAnimationFrame(() => (multiline ? textareaRef.current : inputRef.current)?.focus()); } async function finishEditing() { if (savingRef.current) return; if (cancelOnBlurRef.current) { cancelOnBlurRef.current = false; setDraft(value); setError(""); setEditing(false); return; } const next = draft.trim(); if (next === value.trim()) { setEditing(false); return; } if (!multiline && next.length === 0) { setError("名称不能为空"); refocus(); return; } if (Array.from(next).length > maxCharacters) { setError(`${fieldName}最多 ${maxCharacters} 个字符`); refocus(); return; } savingRef.current = true; setSaving(true); try { await onSave(next); toast.success(`${fieldName}已保存`); setEditing(false); } catch (cause) { setError(`${fieldName}保存失败:${(cause as Error).message}`); refocus(); } finally { savingRef.current = false; setSaving(false); } } if (editing) { const inputProps = { value: draft, autoFocus: true, disabled: saving, "aria-busy": saving, "aria-label": `${label}${fieldName}`, "aria-invalid": error.length > 0, "aria-describedby": error ? errorID : undefined, title: multiline ? "Enter 保存,Shift+Enter 换行,Esc 取消;留空可清除备注" : "Enter 或失焦保存,Esc 取消", onFocus: (event: React.FocusEvent) => event.currentTarget.select(), onChange: (event: React.ChangeEvent) => { setDraft(event.target.value); setError(""); }, onBlur: () => void finishEditing(), onKeyDown: (event: React.KeyboardEvent) => { if (event.nativeEvent.isComposing) return; if (event.key === "Enter" && (!multiline || !event.shiftKey)) { event.preventDefault(); event.currentTarget.blur(); } else if (event.key === "Escape") { event.preventDefault(); cancelOnBlurRef.current = true; event.currentTarget.blur(); } }, }; return (
{multiline ? (