dramaling-vocab-learning/frontend/hooks/review/useReviewSession.ts

84 lines
2.7 KiB
TypeScript

/**
* 簡化的複習會話 Hook - Store 包裝器
* 提供便捷的 Store 訪問方式,但所有邏輯都統一在 Store 中
*/
import { useReviewSessionStore } from '@/store/review/useReviewSessionStore'
import { flashcardsService } from '@/lib/services/flashcards'
import type { ExtendedFlashcard, ReviewMode } from '@/lib/types/review'
interface UseReviewSessionReturn {
// 狀態 (從 Store 直接取得)
currentCard: ExtendedFlashcard | null
dueCards: ExtendedFlashcard[]
currentCardIndex: number
isLoadingCard: boolean
mode: ReviewMode
isAutoSelecting: boolean
showNoDueCards: boolean
showComplete: boolean
// 操作 (Store 的包裝方法)
loadNextCard: () => Promise<void>
setCurrentCard: (card: ExtendedFlashcard | null) => void
setCurrentCardIndex: (index: number) => void
setMode: (mode: ReviewMode) => void
setAutoSelecting: (auto: boolean) => void
setShowNoDueCards: (show: boolean) => void
setShowComplete: (show: boolean) => void
resetSession: () => void
}
export function useReviewSession(): UseReviewSessionReturn {
// 從 Store 取得狀態和操作
const store = useReviewSessionStore()
// 載入卡片的業務邏輯 (唯一的 Hook 專有邏輯)
const loadNextCard = async () => {
try {
store.setLoading(true)
store.setError(null)
const result = await flashcardsService.getDueFlashcards(50)
if (result.success && result.data && result.data.length > 0) {
store.setDueCards(result.data)
store.setCurrentCard(result.data[0])
store.setCurrentCardIndex(0)
store.setShowNoDueCards(false)
} else {
store.setShowNoDueCards(true)
store.setCurrentCard(null)
store.setDueCards([])
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : '載入卡片失敗'
store.setError(errorMessage)
store.setShowNoDueCards(true)
} finally {
store.setLoading(false)
}
}
return {
// 狀態 (直接從 Store 映射)
currentCard: store.currentCard,
dueCards: store.dueCards,
currentCardIndex: store.currentCardIndex,
isLoadingCard: store.isLoading,
mode: store.mode,
isAutoSelecting: store.isAutoSelecting,
showNoDueCards: store.showNoDueCards,
showComplete: store.showComplete,
// 操作 (Store 方法的直接映射 + 業務邏輯)
loadNextCard,
setCurrentCard: store.setCurrentCard,
setCurrentCardIndex: store.setCurrentCardIndex,
setMode: store.setMode,
setAutoSelecting: store.setAutoSelecting,
setShowNoDueCards: store.setShowNoDueCards,
setShowComplete: store.setShowComplete,
resetSession: store.resetSession
}
}