"use client" import { useEffect, useRef, useState } from "react" import { cn } from "@/lib/utils" export function OfficeEditorInlineTitle({ value, onRename, disabled = false, className, }: { value: string onRename: (next: string) => Promise disabled?: boolean className?: string }) { const [editing, setEditing] = useState(false) const [draft, setDraft] = useState(value) const [busy, setBusy] = useState(false) const inputRef = useRef(null) const skipBlurCommitRef = useRef(false) useEffect(() => { if (!editing) setDraft(value) }, [value, editing]) useEffect(() => { if (!editing) return const timer = window.setTimeout(() => { const el = inputRef.current if (!el) return el.focus() el.select() }, 0) return () => window.clearTimeout(timer) }, [editing]) const cancelEdit = () => { skipBlurCommitRef.current = true setDraft(value) setEditing(false) } const commitEdit = async () => { if (skipBlurCommitRef.current) { skipBlurCommitRef.current = false return } const trimmed = draft.trim() if (!trimmed || trimmed === value) { setDraft(value) setEditing(false) return } setBusy(true) try { await onRename(trimmed) setEditing(false) } catch { setDraft(value) setEditing(false) } finally { setBusy(false) } } if (editing && !disabled) { return ( setDraft(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault() void commitEdit() } if (event.key === "Escape") { event.preventDefault() cancelEdit() } }} onBlur={() => void commitEdit()} /> ) } return ( ) }