Add custom word entry + language pair support for learning units
Some checks failed
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / test-go-school (push) Successful in 31s
CI / test-go-edu-search (push) Successful in 31s
CI / test-python-klausur (push) Failing after 2m29s
CI / test-python-agent-core (push) Successful in 24s
CI / test-nodejs-website (push) Successful in 22s

- New UnitBuilder component with language pair selector (DE⇄EN, ES, FR, etc.)
- Manual word entry form with auto-suggest from Kaikki dictionary (6M words)
- "No results" prompt to add multi-word terms (e.g. "schottisches Hochland")
- New backend endpoint GET /vocabulary/lookup-translation (any→any via EN hub)
- Updated POST /vocabulary/units: accepts custom_words + source_lang/target_lang
- Split unit endpoints into vocabulary/unit_api.py (500 LOC budget)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Benjamin Admin
2026-04-29 15:24:13 +02:00
parent 855cc4caf4
commit 52a15b24fe
5 changed files with 762 additions and 295 deletions

View File

@@ -5,11 +5,14 @@ import { useRouter } from 'next/navigation'
import { useTheme } from '@/lib/ThemeContext'
import { Sidebar } from '@/components/Sidebar'
import { AudioButton } from '@/components/learn/AudioButton'
import UnitBuilder, { type UnitWord } from './components/UnitBuilder'
interface VocabWord {
id: string
english: string
german: string
word?: string
lang?: string
ipa_en: string
ipa_de: string
part_of_speech: string
@@ -20,11 +23,18 @@ interface VocabWord {
image_url: string
difficulty: number
tags: string[]
translations?: Record<string, any>
}
/** Use Next.js API proxy to avoid mixed-content/CORS issues */
function getApiBase() {
return '' // Same-origin: /api/vocabulary/... proxied by Next.js
function vocabToUnit(w: VocabWord, searchLang: string): UnitWord {
// Source = the word in the language we searched, Target = the translation
const src = w.word || w.english || ''
const tgt = searchLang === 'en'
? (w.german || '')
: searchLang === 'de'
? (w.english || '')
: (w.english || w.german || '')
return { id: w.id, source_text: src, target_text: tgt, pos: w.part_of_speech }
}
export default function VocabularyPage() {
@@ -39,11 +49,9 @@ export default function VocabularyPage() {
const [diffFilter, setDiffFilter] = useState(0)
const [searchLang, setSearchLang] = useState('en')
const [topics, setTopics] = useState<{ topic: string; words: string[]; display_words?: string[]; word_count: number }[]>([])
const [showTopics, setShowTopics] = useState(false)
// Unit builder
const [selectedWords, setSelectedWords] = useState<VocabWord[]>([])
const [unitTitle, setUnitTitle] = useState('')
// Unit builder state (UnitWord format)
const [unitWords, setUnitWords] = useState<UnitWord[]>([])
const [isCreating, setIsCreating] = useState(false)
const glassCard = isDark
@@ -54,9 +62,8 @@ export default function VocabularyPage() {
? 'bg-white/10 border-white/20 text-white placeholder-white/40'
: 'bg-white border-slate-200 text-slate-900 placeholder-slate-400'
// Load filters on mount
useEffect(() => {
fetch(`${getApiBase()}/api/vocabulary/filters`)
fetch('/api/vocabulary/filters')
.then(r => r.ok ? r.json() : null)
.then(d => { if (d) setFilters(d) })
.catch(() => {})
@@ -66,30 +73,28 @@ export default function VocabularyPage() {
useEffect(() => {
if (!query.trim() && !posFilter && !diffFilter) {
setResults([])
setTopics([])
return
}
const timer = setTimeout(async () => {
setIsSearching(true)
try {
let url: string
if (query.trim()) {
url = `${getApiBase()}/api/vocabulary/search?q=${encodeURIComponent(query)}&lang=${searchLang}&limit=30&source=kaikki`
url = `/api/vocabulary/search?q=${encodeURIComponent(query)}&lang=${searchLang}&limit=30&source=kaikki`
} else {
const params = new URLSearchParams({ limit: '30' })
if (posFilter) params.set('pos', posFilter)
if (diffFilter) params.set('difficulty', String(diffFilter))
url = `${getApiBase()}/api/vocabulary/browse?${params}`
url = `/api/vocabulary/browse?${params}`
}
const resp = await fetch(url)
if (resp.ok) {
const data = await resp.json()
setResults(data.words || [])
}
// Also search for matching topics
if (query.trim()) {
const topicResp = await fetch(`${getApiBase()}/api/vocabulary/topics?q=${encodeURIComponent(query)}&lang=${searchLang}`)
const topicResp = await fetch(`/api/vocabulary/topics?q=${encodeURIComponent(query)}&lang=${searchLang}`)
if (topicResp.ok) {
const topicData = await topicResp.json()
setTopics(topicData.topics || [])
@@ -101,28 +106,38 @@ export default function VocabularyPage() {
setIsSearching(false)
}
}, 300)
return () => clearTimeout(timer)
}, [query, posFilter, diffFilter, searchLang])
const toggleWord = useCallback((word: VocabWord) => {
setSelectedWords(prev => {
setUnitWords(prev => {
const exists = prev.find(w => w.id === word.id)
if (exists) return prev.filter(w => w.id !== word.id)
return [...prev, word]
return [...prev, vocabToUnit(word, searchLang)]
})
}, [])
}, [searchLang])
const createUnit = useCallback(async () => {
if (!unitTitle.trim() || selectedWords.length === 0) return
const isSelected = (wordId: string) => unitWords.some(w => w.id === wordId)
const createUnit = useCallback(async (title: string, sourceLang: string, targetLang: string) => {
if (!title.trim() || unitWords.length === 0) return
setIsCreating(true)
try {
const resp = await fetch(`${getApiBase()}/api/vocabulary/units`, {
const dictWords = unitWords.filter(w => !w.is_custom)
const customWords = unitWords.filter(w => w.is_custom)
const resp = await fetch('/api/vocabulary/units', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: unitTitle,
word_ids: selectedWords.map(w => w.id),
title,
word_ids: dictWords.map(w => w.id),
custom_words: customWords.map(w => ({
source_text: w.source_text,
target_text: w.target_text,
})),
source_lang: sourceLang,
target_lang: targetLang,
}),
})
if (resp.ok) {
@@ -134,9 +149,29 @@ export default function VocabularyPage() {
} finally {
setIsCreating(false)
}
}, [unitTitle, selectedWords, router])
}, [unitWords, router])
const isSelected = (wordId: string) => selectedWords.some(w => w.id === wordId)
const addTopicWords = useCallback(async (topic: { words: string[] }, showOnly: boolean) => {
setIsSearching(true)
const topicWords: VocabWord[] = []
for (const w of topic.words) {
const r = await fetch(`/api/vocabulary/search?q=${encodeURIComponent(w)}&lang=en&limit=1&source=kaikki`)
if (r.ok) {
const d = await r.json()
if (d.words?.[0]) topicWords.push(d.words[0])
}
}
if (!showOnly) {
const newUnitWords = topicWords
.filter(tw => !unitWords.find(uw => uw.id === tw.id))
.map(tw => vocabToUnit(tw, 'en'))
setUnitWords(prev => [...prev, ...newUnitWords])
}
setResults(topicWords)
setIsSearching(false)
}, [unitWords])
const noSearchResults = !isSearching && results.length === 0 && !!query.trim() && topics.length === 0
return (
<div className={`min-h-screen flex relative overflow-hidden ${
@@ -157,7 +192,7 @@ export default function VocabularyPage() {
<div>
<h1 className={`text-xl font-bold ${isDark ? 'text-white' : 'text-slate-900'}`}>Woerterbuch</h1>
<p className={`text-sm ${isDark ? 'text-white/60' : 'text-slate-500'}`}>
{(filters as any).kaikki_total > 0 ? `${((filters as any).kaikki_total as number).toLocaleString()} Woerter in ${(filters as any).kaikki_languages} Sprachen` : filters.total_words > 0 ? `${filters.total_words.toLocaleString()} Woerter` : 'Woerter suchen und Lernunits erstellen'}
{(filters as any).kaikki_total > 0 ? `${((filters as any).kaikki_total as number).toLocaleString()} Woerter in ${(filters as any).kaikki_languages} Sprachen` : 'Woerter suchen und Lernunits erstellen'}
</p>
</div>
</div>
@@ -184,18 +219,6 @@ export default function VocabularyPage() {
<option value="ar">AR</option>
<option value="uk">UK</option>
<option value="pl">PL</option>
<option value="sv">SV</option>
<option value="fi">FI</option>
<option value="da">DA</option>
<option value="ro">RO</option>
<option value="el">EL</option>
<option value="hu">HU</option>
<option value="cs">CS</option>
<option value="bg">BG</option>
<option value="lv">LV</option>
<option value="lt">LT</option>
<option value="sk">SK</option>
<option value="et">ET</option>
</select>
<input
type="text"
@@ -205,24 +228,9 @@ export default function VocabularyPage() {
className={`flex-1 px-4 py-3 rounded-xl border outline-none text-lg ${glassInput}`}
autoFocus
/>
<select value={posFilter} onChange={e => setPosFilter(e.target.value)}
className={`px-3 py-2 rounded-xl border text-sm ${glassInput}`}>
<option value="">Alle Wortarten</option>
{filters.parts_of_speech.map(p => <option key={p} value={p}>{p}</option>)}
</select>
<select value={diffFilter} onChange={e => setDiffFilter(Number(e.target.value))}
className={`px-3 py-2 rounded-xl border text-sm ${glassInput}`}>
<option value={0}>Alle Level</option>
<option value={1}>A1</option>
<option value={2}>A2</option>
<option value={3}>B1</option>
<option value={4}>B2</option>
<option value={5}>C1</option>
</select>
</div>
</div>
{/* Results */}
{isSearching && (
<div className="flex justify-center py-8">
<div className={`w-6 h-6 border-2 ${isDark ? 'border-blue-400' : 'border-blue-600'} border-t-transparent rounded-full animate-spin`} />
@@ -236,7 +244,7 @@ export default function VocabularyPage() {
<div key={topic.topic} className={`${glassCard} rounded-xl p-3`}>
<div className="mb-2">
<span className={`text-sm font-semibold ${isDark ? 'text-cyan-300' : 'text-cyan-700'}`}>
💡 {topic.topic} ({topic.word_count})
{topic.topic} ({topic.word_count})
</span>
</div>
<div className="flex flex-wrap gap-1 mb-3">
@@ -248,44 +256,13 @@ export default function VocabularyPage() {
)}
</div>
<div className="flex gap-2">
<button
onClick={async () => {
setIsSearching(true)
const topicWords: VocabWord[] = []
for (const w of topic.words) {
const r = await fetch(`${getApiBase()}/api/vocabulary/search?q=${encodeURIComponent(w)}&lang=en&limit=1&source=kaikki`)
if (r.ok) {
const d = await r.json()
if (d.words?.[0]) topicWords.push(d.words[0])
}
}
setResults(topicWords)
setIsSearching(false)
}}
className={`flex-1 text-xs px-3 py-2 rounded-lg ${isDark ? 'bg-white/10 text-white/60 hover:bg-white/20' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}
>
<button onClick={() => addTopicWords(topic, true)}
className={`flex-1 text-xs px-3 py-2 rounded-lg ${isDark ? 'bg-white/10 text-white/60 hover:bg-white/20' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}>
Anzeigen
</button>
<button
onClick={async () => {
setIsSearching(true)
const topicWords: VocabWord[] = []
for (const w of topic.words) {
const r = await fetch(`${getApiBase()}/api/vocabulary/search?q=${encodeURIComponent(w)}&lang=en&limit=1&source=kaikki`)
if (r.ok) {
const d = await r.json()
if (d.words?.[0] && !selectedWords.find(s => s.id === d.words[0].id)) {
topicWords.push(d.words[0])
}
}
}
setSelectedWords(prev => [...prev, ...topicWords])
setResults(topicWords)
setIsSearching(false)
}}
className={`flex-1 text-xs px-3 py-2 rounded-lg font-semibold ${isDark ? 'bg-cyan-500/30 text-cyan-200 hover:bg-cyan-500/40 border border-cyan-400/30' : 'bg-cyan-100 text-cyan-700 hover:bg-cyan-200 border border-cyan-300'}`}
>
Alle zur Unit
<button onClick={() => addTopicWords(topic, false)}
className={`flex-1 text-xs px-3 py-2 rounded-lg font-semibold ${isDark ? 'bg-cyan-500/30 text-cyan-200 hover:bg-cyan-500/40 border border-cyan-400/30' : 'bg-cyan-100 text-cyan-700 hover:bg-cyan-200 border border-cyan-300'}`}>
+ Alle zur Unit
</button>
</div>
</div>
@@ -293,12 +270,17 @@ export default function VocabularyPage() {
</div>
)}
{!isSearching && results.length === 0 && query.trim() && topics.length === 0 && (
{/* No results message */}
{noSearchResults && (
<div className={`${glassCard} rounded-2xl p-8 text-center`}>
<p className={isDark ? 'text-white/50' : 'text-slate-500'}>Keine Ergebnisse fuer &quot;{query}&quot;</p>
<p className={`text-xs mt-2 ${isDark ? 'text-white/30' : 'text-slate-400'}`}>
Du kannst das Wort rechts manuell hinzufuegen
</p>
</div>
)}
{/* Result list */}
<div className="space-y-2">
{results.map(word => (
<div
@@ -310,7 +292,6 @@ export default function VocabularyPage() {
}`}
onClick={() => toggleWord(word)}
>
{/* Image or emoji placeholder */}
<div className={`w-14 h-14 rounded-xl flex items-center justify-center text-2xl flex-shrink-0 ${isDark ? 'bg-white/5' : 'bg-slate-100'}`}>
{word.image_url ? (
<img src={word.image_url} alt={word.english} className="w-full h-full object-cover rounded-xl" />
@@ -318,33 +299,22 @@ export default function VocabularyPage() {
<span className="text-xl">📝</span>
)}
</div>
{/* Word info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className={`font-bold text-lg ${isDark ? 'text-white' : 'text-slate-900'}`}>{word.english}</span>
<span className={`font-bold text-lg ${isDark ? 'text-white' : 'text-slate-900'}`}>{word.word || word.english}</span>
{word.ipa_en && <span className={`text-sm ${isDark ? 'text-white/40' : 'text-slate-400'}`}>{word.ipa_en}</span>}
<AudioButton text={word.english} lang="en" isDark={isDark} size="sm" />
<AudioButton text={word.word || word.english} lang={word.lang || searchLang} isDark={isDark} size="sm" />
</div>
<div className="flex items-center gap-2">
<span className={`${isDark ? 'text-white/70' : 'text-slate-600'}`}>{word.german}</span>
<AudioButton text={word.german} lang="de" isDark={isDark} size="sm" />
</div>
<div className="flex items-center gap-2 mt-1">
{word.part_of_speech && (
<span className={`text-xs px-2 py-0.5 rounded-full ${isDark ? 'bg-purple-500/20 text-purple-300' : 'bg-purple-100 text-purple-700'}`}>
{word.part_of_speech}
</span>
)}
{word.syllables_en.length > 0 && (
<span className={`text-xs ${isDark ? 'text-white/30' : 'text-slate-400'}`}>
{word.syllables_en.join(' · ')}
</span>
)}
<span className={`${isDark ? 'text-white/70' : 'text-slate-600'}`}>{word.german || word.english}</span>
{word.german && <AudioButton text={word.german} lang="de" isDark={isDark} size="sm" />}
</div>
{word.part_of_speech && (
<span className={`text-xs px-2 py-0.5 rounded-full mt-1 inline-block ${isDark ? 'bg-purple-500/20 text-purple-300' : 'bg-purple-100 text-purple-700'}`}>
{word.part_of_speech}
</span>
)}
</div>
{/* Select indicator */}
<div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 transition-colors ${
isSelected(word.id)
? 'bg-blue-500 text-white'
@@ -360,59 +330,17 @@ export default function VocabularyPage() {
</div>
{/* Right: Unit Builder */}
<div className="w-80 flex-shrink-0">
<div className={`${glassCard} rounded-2xl p-5 sticky top-6`}>
<h3 className={`text-lg font-semibold mb-3 ${isDark ? 'text-white' : 'text-slate-900'}`}>
Lernunit erstellen
</h3>
<input
type="text"
value={unitTitle}
onChange={e => setUnitTitle(e.target.value)}
placeholder="Titel (z.B. Unit 3 - Food)"
className={`w-full px-4 py-2.5 rounded-xl border outline-none text-sm mb-4 ${glassInput}`}
/>
{selectedWords.length === 0 ? (
<p className={`text-sm text-center py-6 ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
Klicke auf Woerter um sie hinzuzufuegen
</p>
) : (
<div className="space-y-1.5 max-h-80 overflow-y-auto mb-4">
{selectedWords.map((w, i) => (
<div key={w.id} className={`flex items-center justify-between px-3 py-2 rounded-lg ${isDark ? 'bg-white/5' : 'bg-slate-50'}`}>
<div className="flex items-center gap-2 min-w-0">
<span className={`text-xs w-5 text-center ${isDark ? 'text-white/30' : 'text-slate-400'}`}>{i+1}</span>
<span className={`text-sm font-medium truncate ${isDark ? 'text-white' : 'text-slate-900'}`}>{w.english}</span>
<span className={`text-xs truncate ${isDark ? 'text-white/40' : 'text-slate-400'}`}>{w.german}</span>
</div>
<button onClick={(e) => { e.stopPropagation(); toggleWord(w) }}
className={`text-xs ${isDark ? 'text-red-400 hover:text-red-300' : 'text-red-500 hover:text-red-700'}`}>
</button>
</div>
))}
</div>
)}
<div className={`text-xs mb-3 ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
{selectedWords.length} Woerter ausgewaehlt
</div>
<button
onClick={createUnit}
disabled={isCreating || selectedWords.length === 0 || !unitTitle.trim()}
className={`w-full py-3 rounded-xl font-medium transition-all ${
selectedWords.length > 0 && unitTitle.trim()
? 'bg-gradient-to-r from-blue-500 to-cyan-500 text-white hover:shadow-lg'
: isDark ? 'bg-white/5 text-white/30' : 'bg-slate-100 text-slate-400'
}`}
>
{isCreating ? 'Wird erstellt...' : 'Lernunit starten'}
</button>
</div>
</div>
<UnitBuilder
isDark={isDark}
glassCard={glassCard}
glassInput={glassInput}
selectedWords={unitWords}
onWordsChange={setUnitWords}
onCreateUnit={createUnit}
isCreating={isCreating}
noSearchResults={noSearchResults}
searchQuery={query}
/>
</div>
</div>
</div>