fix: use uncontrolled inputs for note title and editor to prevent focus leak to search field

This commit is contained in:
Hermes
2026-08-01 13:04:24 +00:00
parent 420ebfe24a
commit 3f1a1982ca
2 changed files with 62 additions and 67 deletions
+17 -67
View File
@@ -17,7 +17,6 @@ import { cn } from "@/lib/utils";
import type { Note, PaginatedResponse } from "@/lib/types"; import type { Note, PaginatedResponse } from "@/lib/types";
// Simple TipTap-like editor using contentEditable // Simple TipTap-like editor using contentEditable
// Uses a key to force remount on note change instead of setting innerHTML
const NoteEditor = memo(function NoteEditor({ initialContent, onSave, placeholder = "Start writing..." }: { initialContent: string; onSave: (html: string) => void; placeholder?: string }) { const NoteEditor = memo(function NoteEditor({ initialContent, onSave, placeholder = "Start writing..." }: { initialContent: string; onSave: (html: string) => void; placeholder?: string }) {
const editorRef = useRef<HTMLDivElement>(null); const editorRef = useRef<HTMLDivElement>(null);
const [isPlaceholder, setIsPlaceholder] = useState(!initialContent); const [isPlaceholder, setIsPlaceholder] = useState(!initialContent);
@@ -27,7 +26,7 @@ const NoteEditor = memo(function NoteEditor({ initialContent, onSave, placeholde
editorRef.current.innerHTML = initialContent || ""; editorRef.current.innerHTML = initialContent || "";
} }
setIsPlaceholder(!initialContent); setIsPlaceholder(!initialContent);
}, []); // Only set initial content once on mount }, []);
const handleBlur = () => { const handleBlur = () => {
const html = editorRef.current?.innerHTML || ""; const html = editorRef.current?.innerHTML || "";
@@ -50,57 +49,32 @@ const NoteEditor = memo(function NoteEditor({ initialContent, onSave, placeholde
); );
}); });
// Isolated title input component - memo prevents re-render when parent re-renders // Separate component for title input - completely uncontrolled to prevent focus stealing
const NoteTitleInput = memo(function NoteTitleInput({ noteId, initialTitle }: { noteId: string; initialTitle: string }) { const NoteTitleInput = memo(function NoteTitleInput({ noteId, initialTitle }: { noteId: string; initialTitle: string }) {
const [title, setTitle] = useState(initialTitle);
const queryClient = useQueryClient();
useEffect(() => {
setTitle(initialTitle);
}, [noteId]);
const handleBlur = () => {
if (title !== initialTitle) {
api.patch<Note>("/notes/" + noteId, { title: title }).then(() => {
queryClient.invalidateQueries({ queryKey: ["notes"] });
});
}
};
return (
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
onBlur={handleBlur}
className="flex h-9 w-full rounded-md border-0 bg-transparent px-0 py-1 text-lg font-semibold text-base shadow-none transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-0 disabled:cursor-not-allowed disabled:opacity-50"
/>
);
});
// Isolated title input component - memo prevents re-render when parent re-renders
const NoteTitleInput = memo(function NoteTitleInput({ noteId, initialTitle }: { noteId: string; initialTitle: string }) {
const [title, setTitle] = useState(initialTitle);
const queryClient = useQueryClient();
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const queryClient = useQueryClient();
useEffect(() => { useEffect(() => {
setTitle(initialTitle); if (inputRef.current) {
inputRef.current?.focus(); inputRef.current.value = initialTitle;
}
}, [noteId]); }, [noteId]);
const handleBlur = () => { const handleBlur = () => {
if (title !== initialTitle) { if (inputRef.current && noteId) {
api.patch<Note>("/notes/" + noteId, { title: title }).then(() => { const newTitle = inputRef.current.value;
queryClient.invalidateQueries({ queryKey: ["notes"] }); if (newTitle !== initialTitle) {
}); api.patch<Note>("/notes/" + noteId, { title: newTitle }).then(() => {
queryClient.invalidateQueries({ queryKey: ["notes"] });
});
}
} }
}; };
return ( return (
<input <input
ref={inputRef} ref={inputRef}
value={title} defaultValue={initialTitle}
onChange={(e) => setTitle(e.target.value)}
onBlur={handleBlur} onBlur={handleBlur}
className="flex h-9 w-full rounded-md border-0 bg-transparent px-0 py-1 text-lg font-semibold text-base shadow-none transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-0 disabled:cursor-not-allowed disabled:opacity-50" className="flex h-9 w-full rounded-md border-0 bg-transparent px-0 py-1 text-lg font-semibold text-base shadow-none transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-0 disabled:cursor-not-allowed disabled:opacity-50"
/> />
@@ -111,9 +85,6 @@ function NotesPage() {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [selectedNote, setSelectedNote] = useState<Note | null>(null); const [selectedNote, setSelectedNote] = useState<Note | null>(null);
const [editorContent, setEditorContent] = useState("");
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const selectedNoteRef = useRef<Note | null>(null);
const [showBacklinks, setShowBacklinks] = useState(false); const [showBacklinks, setShowBacklinks] = useState(false);
const [showVersions, setShowVersions] = useState(false); const [showVersions, setShowVersions] = useState(false);
@@ -131,7 +102,6 @@ function NotesPage() {
onSuccess: (note) => { onSuccess: (note) => {
queryClient.invalidateQueries({ queryKey: ["notes"] }); queryClient.invalidateQueries({ queryKey: ["notes"] });
setSelectedNote(note); setSelectedNote(note);
setEditorContent("");
}, },
}); });
@@ -152,27 +122,13 @@ function NotesPage() {
try { try {
const detail = await api.get<Note>("/notes/" + note.id); const detail = await api.get<Note>("/notes/" + note.id);
setSelectedNote(detail); setSelectedNote(detail);
selectedNoteRef.current = detail;
setEditorContent(detail.content || "");
} catch { } catch {
setSelectedNote(note); setSelectedNote(note);
selectedNoteRef.current = note;
setEditorContent(note.content || "");
} }
setShowBacklinks(false); setShowBacklinks(false);
setShowVersions(false); setShowVersions(false);
}; };
const handleContentChange = useCallback((html: string) => {
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
saveTimerRef.current = setTimeout(() => {
const note = selectedNoteRef.current;
if (note) {
updateMutation.mutate({ id: note.id, data: { content: html } });
}
}, 500);
}, [updateMutation]);
return ( return (
<div className="flex h-[calc(100vh-8rem)] -m-4 md:-m-6"> <div className="flex h-[calc(100vh-8rem)] -m-4 md:-m-6">
{/* Left pane - note list */} {/* Left pane - note list */}
@@ -180,7 +136,7 @@ function NotesPage() {
<div className="p-3 border-b"> <div className="p-3 border-b">
<div className="relative"> <div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" /> <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input placeholder="Search notes..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-8" tabIndex={-1} /> <Input placeholder="Search notes..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-8" />
</div> </div>
</div> </div>
<div className="p-2"> <div className="p-2">
@@ -223,13 +179,7 @@ function NotesPage() {
{selectedNote ? ( {selectedNote ? (
<> <>
<div className="flex items-center gap-2 p-3 border-b"> <div className="flex items-center gap-2 p-3 border-b">
{selectedNote && ( <NoteTitleInput key={selectedNote.id} noteId={selectedNote.id} initialTitle={selectedNote.title} />
<NoteTitleInput
key={selectedNote.id}
noteId={selectedNote.id}
initialTitle={selectedNote.title}
/>
)}
<div className="flex items-center gap-1 shrink-0"> <div className="flex items-center gap-1 shrink-0">
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setShowBacklinks(!showBacklinks)} aria-label="Backlinks"> <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setShowBacklinks(!showBacklinks)} aria-label="Backlinks">
<LinkIcon className="h-4 w-4" /> <LinkIcon className="h-4 w-4" />
@@ -257,7 +207,7 @@ function NotesPage() {
</div> </div>
</div> </div>
<div className="flex-1 overflow-auto"> <div className="flex-1 overflow-auto">
<NoteEditor key={selectedNote?.id || 'none'} initialContent={editorContent} onSave={handleContentChange} /> <NoteEditor key={selectedNote?.id || 'none'} initialContent={selectedNote?.content || ''} onSave={(html) => { if (selectedNote) { updateMutation.mutate({ id: selectedNote.id, data: { content: html } }); } }} />
</div> </div>
{/* Backlinks section */} {/* Backlinks section */}
{showBacklinks && selectedNote.backlinks && selectedNote.backlinks.length > 0 && ( {showBacklinks && selectedNote.backlinks && selectedNote.backlinks.length > 0 && (
+45
View File
@@ -0,0 +1,45 @@
import sys
with open(sys.argv[1], 'r') as f:
content = f.read()
# Remove all setEditorContent calls
content = content.replace(' setEditorContent("");\n', '', 1)
content = content.replace(' setEditorContent(detail.content || "");\n', '', 1)
content = content.replace(' setEditorContent(note.content || "");\n', '', 1)
# Remove editorContent state
content = content.replace(' const [editorContent, setEditorContent] = useState("");\n', '', 1)
# Remove saveTimerRef
content = content.replace(' const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n', '', 1)
# Remove selectedNoteRef
content = content.replace(' const selectedNoteRef = useRef<Note | null>(null);\n', '', 1)
# Remove selectedNoteRef.current assignments
content = content.replace(' selectedNoteRef.current = detail;\n', '', 1)
content = content.replace(' selectedNoteRef.current = note;\n', '', 1)
content = content.replace(' selectedNoteRef.current = note;\n', '', 1)
# Remove handleContentChange
old = ''' const handleContentChange = useCallback((html: string) => {
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
saveTimerRef.current = setTimeout(() => {
const note = selectedNoteRef.current;
if (note) {
updateMutation.mutate({ id: note.id, data: { content: html } });
}
}, 500);
}, [updateMutation]);'''
content = content.replace(old, '', 1)
# Update NoteEditor usage
old_editor = ' <NoteEditor key={selectedNote?.id || \'none\'} initialContent={editorContent} onSave={handleContentChange} />'
new_editor = ' <NoteEditor key={selectedNote?.id || \'none\'} initialContent={selectedNote?.content || \'\'} onSave={(html) => { if (selectedNote) { updateMutation.mutate({ id: selectedNote.id, data: { content: html } }); } }} />'
content = content.replace(old_editor, new_editor, 1)
with open(sys.argv[1], 'w') as f:
f.write(content)
print('Done')