feat: MVP-4 P2 - Preload notes on hover

- Add prefetchNote function in useNoteListKeyboard hook
- Prefetch note pages when navigating with arrow keys
- Add hover prefetch in NoteCard using router.prefetch
- Update KeyboardNavigableNoteList to use prefetchNote
This commit is contained in:
2026-03-22 20:22:57 -03:00
parent e66a678160
commit 33a4705f95
3 changed files with 35 additions and 10 deletions

View File

@@ -1,4 +1,4 @@
import { useEffect, useCallback, useState } from 'react'
import { useEffect, useCallback, useState, useRef } from 'react'
import { useRouter } from 'next/navigation'
import { Note } from '@/types/note'
@@ -17,10 +17,19 @@ export function useNoteListKeyboard({
}: UseNoteListKeyboardOptions) {
const [selectedIndex, setSelectedIndex] = useState(-1)
const router = useRouter()
const prefetchedRef = useRef<Set<string>>(new Set())
// Prefetch a note's page data for faster navigation
const prefetchNote = useCallback((noteId: string) => {
if (prefetchedRef.current.has(noteId)) return
prefetchedRef.current.add(noteId)
router.prefetch(`/notes/${noteId}`)
}, [router])
// Reset selection when notes change
useEffect(() => {
setSelectedIndex(-1)
prefetchedRef.current.clear()
}, [notes.length])
const handleKeyDown = useCallback(
@@ -38,13 +47,19 @@ export function useNoteListKeyboard({
switch (e.key) {
case 'ArrowDown':
e.preventDefault()
setSelectedIndex((prev) =>
prev < notes.length - 1 ? prev + 1 : notes.length - 1
)
setSelectedIndex((prev) => {
const next = prev < notes.length - 1 ? prev + 1 : notes.length - 1
if (notes[next]) prefetchNote(notes[next].id)
return next
})
break
case 'ArrowUp':
e.preventDefault()
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : -1))
setSelectedIndex((prev) => {
const next = prev > 0 ? prev - 1 : -1
if (next >= 0 && notes[next]) prefetchNote(notes[next].id)
return next
})
break
case 'Enter':
e.preventDefault()
@@ -75,7 +90,7 @@ export function useNoteListKeyboard({
break
}
},
[notes, selectedIndex, router, onEdit, onFavorite, onPin]
[notes, selectedIndex, router, onEdit, onFavorite, onPin, prefetchNote]
)
useEffect(() => {
@@ -83,5 +98,5 @@ export function useNoteListKeyboard({
return () => window.removeEventListener('keydown', handleKeyDown)
}, [handleKeyDown])
return { selectedIndex, setSelectedIndex }
return { selectedIndex, setSelectedIndex, prefetchNote }
}