diff --git a/packages/app-desktop/gui/NoteList/NoteList2.tsx b/packages/app-desktop/gui/NoteList/NoteList2.tsx index 997a7351b6..5208eb70ce 100644 --- a/packages/app-desktop/gui/NoteList/NoteList2.tsx +++ b/packages/app-desktop/gui/NoteList/NoteList2.tsx @@ -65,7 +65,7 @@ const NoteList = (props: Props) => { props.notes.length, ); - const focusNote = useFocusNote(itemRefs); + const focusNote = useFocusNote(itemRefs, props.notes, makeItemIndexVisible); const moveNote = useMoveNote( props.notesParentType, diff --git a/packages/app-desktop/gui/NoteList/utils/useFocusNote.ts b/packages/app-desktop/gui/NoteList/utils/useFocusNote.ts index 9df60aea6d..89f8602869 100644 --- a/packages/app-desktop/gui/NoteList/utils/useFocusNote.ts +++ b/packages/app-desktop/gui/NoteList/utils/useFocusNote.ts @@ -1,19 +1,31 @@ import shim from '@joplin/lib/shim'; import { useRef, useCallback, MutableRefObject } from 'react'; import { focus } from '@joplin/lib/utils/focusHandler'; +import { NoteEntity } from '@joplin/lib/services/database/types'; export type FocusNote = (noteId: string)=> void; +type ItemRefs = MutableRefObject>; +type OnMakeIndexVisible = (i: number)=> void; -const useFocusNote = (itemRefs: MutableRefObject>) => { +const useFocusNote = (itemRefs: ItemRefs, notes: NoteEntity[], makeItemIndexVisible: OnMakeIndexVisible) => { const focusItemIID = useRef(null); + const notesRef = useRef(notes); + notesRef.current = notes; + const focusNote: FocusNote = useCallback((noteId: string) => { // - We need to focus the item manually otherwise focus might be lost when the // list is scrolled and items within it are being rebuilt. - // - We need to use an interval because when leaving the arrow pressed, the rendering - // of items might lag behind and so the ref is not yet available at this point. + // - We need to use an interval because when leaving the arrow pressed or scrolling + // offscreen items into view, the rendering of items might lag behind and so the + // ref is not yet available at this point. if (!itemRefs.current[noteId]) { + const targetIndex = notesRef.current.findIndex(note => note.id === noteId); + if (targetIndex > -1) { + makeItemIndexVisible(targetIndex); + } + if (focusItemIID.current) shim.clearInterval(focusItemIID.current); focusItemIID.current = shim.setInterval(() => { if (itemRefs.current[noteId]) { @@ -26,7 +38,7 @@ const useFocusNote = (itemRefs: MutableRefObject> if (focusItemIID.current) shim.clearInterval(focusItemIID.current); focus('useFocusNote2', itemRefs.current[noteId]); } - }, [itemRefs]); + }, [itemRefs, makeItemIndexVisible]); return focusNote; };