210 lines
5.7 KiB
TypeScript
210 lines
5.7 KiB
TypeScript
import { useReducer, useEffect, useMemo } from 'react'
|
|
import { SIMPLE_CARDS, CardState, sortCardsByPriority } from '../data'
|
|
|
|
interface ReviewState {
|
|
cards: CardState[]
|
|
score: { correct: number; total: number }
|
|
isComplete: boolean
|
|
}
|
|
|
|
type ReviewAction =
|
|
| { type: 'LOAD_PROGRESS'; payload: ReviewState }
|
|
| { type: 'ANSWER_CARD'; payload: { cardId: string; confidence: number } }
|
|
| { type: 'SKIP_CARD'; payload: { cardId: string } }
|
|
| { type: 'RESTART' }
|
|
|
|
// 內部狀態更新函數
|
|
const updateCardState = (
|
|
cards: CardState[],
|
|
cardIndex: number,
|
|
updates: Partial<CardState>
|
|
): CardState[] => {
|
|
return cards.map((card, index) =>
|
|
index === cardIndex
|
|
? { ...card, ...updates }
|
|
: card
|
|
)
|
|
}
|
|
|
|
const reviewReducer = (state: ReviewState, action: ReviewAction): ReviewState => {
|
|
switch (action.type) {
|
|
case 'LOAD_PROGRESS':
|
|
return action.payload
|
|
|
|
case 'ANSWER_CARD': {
|
|
const { cardId, confidence } = action.payload
|
|
const isCorrect = confidence >= 2
|
|
|
|
// 使用 Map 優化查找性能
|
|
const cardMap = new Map(state.cards.map((card, index) => [card.id, { card, index }]))
|
|
const cardData = cardMap.get(cardId)
|
|
|
|
if (!cardData) return state
|
|
|
|
const { index: cardIndex } = cardData
|
|
const currentCard = state.cards[cardIndex]
|
|
|
|
const updatedCards = updateCardState(state.cards, cardIndex, {
|
|
isCompleted: isCorrect,
|
|
wrongCount: isCorrect ? currentCard.wrongCount : currentCard.wrongCount + 1
|
|
})
|
|
|
|
const newScore = {
|
|
correct: state.score.correct + (isCorrect ? 1 : 0),
|
|
total: state.score.total + 1
|
|
}
|
|
|
|
const remainingCards = updatedCards.filter(card => !card.isCompleted)
|
|
const isComplete = remainingCards.length === 0
|
|
|
|
return {
|
|
cards: updatedCards,
|
|
score: newScore,
|
|
isComplete
|
|
}
|
|
}
|
|
|
|
case 'SKIP_CARD': {
|
|
const { cardId } = action.payload
|
|
|
|
// 使用 Map 優化查找性能
|
|
const cardMap = new Map(state.cards.map((card, index) => [card.id, { card, index }]))
|
|
const cardData = cardMap.get(cardId)
|
|
|
|
if (!cardData) return state
|
|
|
|
const { index: cardIndex } = cardData
|
|
const currentCard = state.cards[cardIndex]
|
|
|
|
const updatedCards = updateCardState(state.cards, cardIndex, {
|
|
skipCount: currentCard.skipCount + 1
|
|
})
|
|
|
|
const remainingCards = updatedCards.filter(card => !card.isCompleted)
|
|
const isComplete = remainingCards.length === 0
|
|
|
|
return {
|
|
cards: updatedCards,
|
|
score: state.score,
|
|
isComplete
|
|
}
|
|
}
|
|
|
|
case 'RESTART':
|
|
return {
|
|
cards: SIMPLE_CARDS,
|
|
score: { correct: 0, total: 0 },
|
|
isComplete: false
|
|
}
|
|
|
|
default:
|
|
return state
|
|
}
|
|
}
|
|
|
|
export function useReviewSession() {
|
|
// 使用 useReducer 統一狀態管理
|
|
const [state, dispatch] = useReducer(reviewReducer, {
|
|
cards: SIMPLE_CARDS,
|
|
score: { correct: 0, total: 0 },
|
|
isComplete: false
|
|
})
|
|
|
|
const { cards, score, isComplete } = state
|
|
|
|
// 智能排序獲取當前卡片 - 使用 useMemo 優化性能
|
|
const sortedCards = useMemo(() => sortCardsByPriority(cards), [cards])
|
|
const incompleteCards = useMemo(() =>
|
|
sortedCards.filter((card: CardState) => !card.isCompleted),
|
|
[sortedCards]
|
|
)
|
|
const currentCard = incompleteCards[0] // 總是選擇優先級最高的未完成卡片
|
|
|
|
// localStorage進度保存和載入
|
|
useEffect(() => {
|
|
// 載入保存的進度
|
|
const savedProgress = localStorage.getItem('review-progress')
|
|
if (savedProgress) {
|
|
try {
|
|
const parsed = JSON.parse(savedProgress)
|
|
const saveTime = new Date(parsed.timestamp)
|
|
const now = new Date()
|
|
const isToday = saveTime.toDateString() === now.toDateString()
|
|
|
|
if (isToday && parsed.cards) {
|
|
dispatch({
|
|
type: 'LOAD_PROGRESS',
|
|
payload: {
|
|
cards: parsed.cards,
|
|
score: parsed.score || { correct: 0, total: 0 },
|
|
isComplete: parsed.isComplete || false
|
|
}
|
|
})
|
|
console.log('📖 載入保存的複習進度')
|
|
}
|
|
} catch (error) {
|
|
console.warn('進度載入失敗:', error)
|
|
localStorage.removeItem('review-progress')
|
|
}
|
|
}
|
|
}, [])
|
|
|
|
// 保存進度到localStorage
|
|
const saveProgress = () => {
|
|
const progress = {
|
|
cards,
|
|
score,
|
|
isComplete,
|
|
timestamp: new Date().toISOString()
|
|
}
|
|
localStorage.setItem('review-progress', JSON.stringify(progress))
|
|
console.log('💾 進度已保存')
|
|
}
|
|
|
|
// 處理答題 - 使用 dispatch 統一管理
|
|
const handleAnswer = (confidence: number) => {
|
|
if (!currentCard) return
|
|
|
|
dispatch({
|
|
type: 'ANSWER_CARD',
|
|
payload: { cardId: currentCard.id, confidence }
|
|
})
|
|
|
|
// 保存進度
|
|
setTimeout(() => saveProgress(), 100) // 延遲一點確保狀態更新
|
|
}
|
|
|
|
// 處理跳過 - 使用 dispatch 統一管理
|
|
const handleSkip = () => {
|
|
if (!currentCard) return
|
|
|
|
dispatch({
|
|
type: 'SKIP_CARD',
|
|
payload: { cardId: currentCard.id }
|
|
})
|
|
|
|
// 保存進度
|
|
setTimeout(() => saveProgress(), 100) // 延遲一點確保狀態更新
|
|
}
|
|
|
|
// 重新開始 - 重置所有狀態
|
|
const handleRestart = () => {
|
|
dispatch({ type: 'RESTART' })
|
|
localStorage.removeItem('review-progress') // 清除保存的進度
|
|
console.log('🔄 複習進度已重置')
|
|
}
|
|
|
|
return {
|
|
// 狀態
|
|
cards,
|
|
score,
|
|
isComplete,
|
|
currentCard,
|
|
sortedCards,
|
|
|
|
// 動作
|
|
handleAnswer,
|
|
handleSkip,
|
|
handleRestart
|
|
}
|
|
} |