Files
play-life/play-life-web/src/components/WordList.jsx

262 lines
8.5 KiB
React
Raw Normal View History

2025-12-29 20:01:55 +03:00
import React, { useState, useEffect } from 'react'
import { useAuth } from './auth/AuthContext'
2025-12-29 20:01:55 +03:00
import './WordList.css'
const API_URL = '/api'
function WordList({ onNavigate, dictionaryId, isNewDictionary, refreshTrigger = 0 }) {
const { authFetch } = useAuth()
2025-12-29 20:01:55 +03:00
const [words, setWords] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [dictionary, setDictionary] = useState(null)
const [dictionaryName, setDictionaryName] = useState('')
const [originalDictionaryName, setOriginalDictionaryName] = useState('')
const [isSavingName, setIsSavingName] = useState(false)
2025-12-30 18:27:12 +03:00
// Normalize undefined to null for clarity: new dictionary if dictionaryId is null or undefined
const [currentDictionaryId, setCurrentDictionaryId] = useState(dictionaryId ?? null)
// isNewDict is computed from currentDictionaryId: new dictionary if currentDictionaryId == null
const isNewDict = currentDictionaryId == null
// Helper function to check if dictionary exists and is not new
const hasValidDictionary = (dictId) => {
return dictId !== undefined && dictId !== null
}
2025-12-29 20:01:55 +03:00
useEffect(() => {
2025-12-30 18:27:12 +03:00
// Normalize undefined to null: if dictionaryId is undefined, treat it as null (new dictionary)
const normalizedDictionaryId = dictionaryId ?? null
setCurrentDictionaryId(normalizedDictionaryId)
2025-12-29 20:01:55 +03:00
2025-12-30 18:27:12 +03:00
if (normalizedDictionaryId == null) {
2025-12-29 20:01:55 +03:00
setLoading(false)
setDictionary(null)
setDictionaryName('')
setOriginalDictionaryName('')
setWords([])
2025-12-30 18:27:12 +03:00
} else if (hasValidDictionary(normalizedDictionaryId)) {
fetchDictionary(normalizedDictionaryId)
fetchWords(normalizedDictionaryId)
2025-12-29 20:01:55 +03:00
} else {
setLoading(false)
setWords([])
}
2025-12-30 18:27:12 +03:00
}, [dictionaryId, refreshTrigger])
2025-12-29 20:01:55 +03:00
2025-12-30 18:27:12 +03:00
const fetchDictionary = async (dictId) => {
2025-12-29 20:01:55 +03:00
try {
const response = await authFetch(`${API_URL}/dictionaries`)
2025-12-29 20:01:55 +03:00
if (!response.ok) {
throw new Error('Ошибка при загрузке словарей')
}
const dictionaries = await response.json()
2025-12-30 18:27:12 +03:00
const dict = dictionaries.find(d => d.id === dictId)
2025-12-29 20:01:55 +03:00
if (dict) {
setDictionary(dict)
setDictionaryName(dict.name)
setOriginalDictionaryName(dict.name)
}
} catch (err) {
console.error('Error fetching dictionary:', err)
}
}
2025-12-30 18:27:12 +03:00
const fetchWords = async (dictId) => {
if (!hasValidDictionary(dictId)) {
2025-12-29 20:01:55 +03:00
setWords([])
setLoading(false)
return
}
2025-12-30 18:27:12 +03:00
await fetchWordsForDictionary(dictId)
2025-12-29 20:01:55 +03:00
}
const fetchWordsForDictionary = async (dictId) => {
try {
setLoading(true)
const url = `${API_URL}/words?dictionary_id=${dictId}`
const response = await authFetch(url)
2025-12-29 20:01:55 +03:00
if (!response.ok) {
throw new Error('Ошибка при загрузке слов')
}
const data = await response.json()
setWords(Array.isArray(data) ? data : [])
setError('')
} catch (err) {
setError(err.message)
setWords([])
} finally {
setLoading(false)
}
}
const handleNameChange = (e) => {
setDictionaryName(e.target.value)
}
const handleNameSave = async () => {
if (!dictionaryName.trim()) {
return
}
setIsSavingName(true)
try {
2025-12-30 18:27:12 +03:00
if (!hasValidDictionary(currentDictionaryId)) {
2025-12-29 20:01:55 +03:00
// Create new dictionary
const response = await authFetch(`${API_URL}/dictionaries`, {
2025-12-29 20:01:55 +03:00
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: dictionaryName.trim() }),
})
if (!response.ok) {
throw new Error('Ошибка при создании словаря')
}
const newDict = await response.json()
const newDictionaryId = newDict.id
2025-12-30 18:27:12 +03:00
// Update local state
2025-12-29 20:01:55 +03:00
setOriginalDictionaryName(newDict.name)
setDictionaryName(newDict.name)
setDictionary(newDict)
setCurrentDictionaryId(newDictionaryId)
2025-12-30 18:27:12 +03:00
// Reinitialize screen: fetch dictionary info and words for the new dictionary
await fetchDictionary(newDictionaryId)
2025-12-29 20:01:55 +03:00
await fetchWordsForDictionary(newDictionaryId)
2025-12-30 18:27:12 +03:00
// Update navigation to use the new dictionary ID
onNavigate?.('words', { dictionaryId: newDictionaryId })
} else if (hasValidDictionary(currentDictionaryId)) {
// Update existing dictionary (rename)
const response = await authFetch(`${API_URL}/dictionaries/${currentDictionaryId}`, {
2025-12-29 20:01:55 +03:00
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: dictionaryName.trim() }),
})
if (!response.ok) {
throw new Error('Ошибка при обновлении словаря')
}
setOriginalDictionaryName(dictionaryName.trim())
if (dictionary) {
setDictionary({ ...dictionary, name: dictionaryName.trim() })
}
}
} catch (err) {
setError(err.message)
} finally {
setIsSavingName(false)
}
}
2025-12-30 18:27:12 +03:00
// Show save button only if name is not empty and has changed
2025-12-29 20:01:55 +03:00
const showSaveButton = dictionaryName.trim() !== '' && dictionaryName.trim() !== originalDictionaryName
if (loading) {
return (
<div className="word-list">
<div className="fixed inset-0 flex justify-center items-center">
<div className="flex flex-col items-center">
<div className="w-12 h-12 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mb-4"></div>
<div className="text-gray-600 font-medium">Загрузка...</div>
</div>
</div>
2025-12-29 20:01:55 +03:00
</div>
)
}
if (error) {
return (
<div className="word-list">
<div className="error-message">{error}</div>
</div>
)
}
return (
<div className="word-list">
<button
onClick={() => onNavigate?.('test-config')}
className="close-x-button"
title="Закрыть"
>
</button>
{/* Dictionary name input */}
<div className="dictionary-name-input-container">
<input
type="text"
className="dictionary-name-input"
value={dictionaryName}
onChange={handleNameChange}
placeholder="Введите название словаря"
/>
{showSaveButton && (
<button
className="dictionary-name-save-button"
onClick={handleNameSave}
disabled={isSavingName}
title="Сохранить название"
>
</button>
)}
</div>
2025-12-30 18:27:12 +03:00
{/* Show add button and words list only if dictionaryId exists and is not new */}
{hasValidDictionary(currentDictionaryId) && (
2025-12-29 20:01:55 +03:00
<>
{(!words || words.length === 0) ? (
<>
<button onClick={() => onNavigate?.('add-words', { dictionaryId: currentDictionaryId, dictionaryName })} className="add-button">
Добавить
</button>
<div className="empty-state">
<p>Слов пока нет. Добавьте слова через экран "Добавить слова".</p>
</div>
</>
) : (
<>
<button onClick={() => onNavigate?.('add-words', { dictionaryId: currentDictionaryId, dictionaryName })} className="add-button">
Добавить
</button>
<div className="words-grid">
{words.map((word) => (
<div key={word.id} className="word-card">
<div className="word-content">
<div className="word-header">
<h3 className="word-name">{word.name}</h3>
</div>
<div className="word-translation">{word.translation}</div>
{word.description && (
<div className="word-description">{word.description}</div>
)}
</div>
<div className="word-stats">
<span className="stat-success">{word.success || 0}</span>
<span className="stat-separator"> | </span>
<span className="stat-failure">{word.failure || 0}</span>
</div>
</div>
))}
</div>
</>
)}
</>
)}
</div>
)
}
export default WordList