59 lines
1.7 KiB
TypeScript
59 lines
1.7 KiB
TypeScript
import { useState } from 'react'
|
|
import { useToast } from '@/components/shared/Toast'
|
|
import { flashcardsService } from '@/lib/services/flashcards'
|
|
|
|
interface WordAnalysis {
|
|
word: string
|
|
translation: string
|
|
definition: string
|
|
partOfSpeech: string
|
|
pronunciation: string
|
|
synonyms: string[]
|
|
cefr: string
|
|
example?: string
|
|
exampleTranslation?: string
|
|
[key: string]: any
|
|
}
|
|
|
|
export function useVocabularySave() {
|
|
const [isSaving, setIsSaving] = useState(false)
|
|
const toast = useToast()
|
|
|
|
const saveWord = async (word: string, analysis: WordAnalysis) => {
|
|
setIsSaving(true)
|
|
|
|
try {
|
|
const flashcardData = {
|
|
word: analysis.word || word,
|
|
translation: analysis.translation || '',
|
|
definition: analysis.definition || '',
|
|
partOfSpeech: analysis.partOfSpeech || 'unknown',
|
|
pronunciation: analysis.pronunciation || '',
|
|
example: analysis.example || '',
|
|
exampleTranslation: analysis.exampleTranslation || '',
|
|
cefr: analysis.cefr || 'A1'
|
|
}
|
|
|
|
const result = await flashcardsService.createFlashcard(flashcardData)
|
|
|
|
if (result.success) {
|
|
toast.success(`「${word}」已成功加入詞卡!`)
|
|
return { success: true }
|
|
} else {
|
|
toast.error(result.error || '保存失敗,請重試')
|
|
return { success: false, error: result.error }
|
|
}
|
|
} catch (error: any) {
|
|
const errorMessage = error.message || '保存失敗,請重試'
|
|
toast.error(errorMessage)
|
|
return { success: false, error: errorMessage }
|
|
} finally {
|
|
setIsSaving(false)
|
|
}
|
|
}
|
|
|
|
return {
|
|
saveWord,
|
|
isSaving
|
|
}
|
|
} |