d3ro-voice/apps/web/src/app/(app)/dictionary/page.tsx
Yun Chan cfc58458a8 feat(web): manage dictionaries and teams from the console
The console could not create dictionary entries, and team pages showed a
static member list with no record of who changed what. Dictionary
management, a knowledge upload form, and a team activity feed are now
available, alongside a download center that links the published desktop
installer feed rather than repository-local paths that no deploy ships.

Red-team e2e coverage was added for the account and team flows touched here.
2026-09-16 23:24:27 +09:00

537 lines
21 KiB
TypeScript

'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import {
Alert,
Box,
Button,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControl,
IconButton,
InputAdornment,
InputLabel,
MenuItem,
Select,
TextField,
Tooltip,
Typography
} from '@mui/material'
import { Download, Pencil, Plus, RefreshCw, Search, Trash2, Upload } from 'lucide-react'
import type { D3roSupabaseClient, DictionaryEntry } from '@d3ro/api-client'
import { MetalCard, PhosphorText, PhysicalButton, TactileBadge } from '@d3ro/ui/components/ds'
import { d3roFontMono, d3roPalette } from '@d3ro/ui/theme'
import { useAuth } from '@/components/providers/auth-provider'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
import {
createDictionaryEntry,
deleteDictionaryEntry,
DictionaryClientError,
importDictionaryFile,
listDictionaryPage,
normalizeDictionaryDraft,
sanitizeDictionarySearch,
serializeDictionary,
updateDictionaryEntry,
type DictionaryCategory,
type DictionaryCursor,
type DictionaryDraft,
type DictionaryFilter
} from '@/lib/dictionary-client'
const PAGE_SIZE = 20
const SEARCH_DELAY_MS = 300
function downloadText(filename: string, text: string, mime: string): void {
const blob = new Blob([text], { type: mime })
const url = URL.createObjectURL(blob)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = filename
document.body.appendChild(anchor)
anchor.click()
document.body.removeChild(anchor)
URL.revokeObjectURL(url)
}
const CATEGORY_LABELS: Record<DictionaryCategory, string> = {
user: '사용자',
technical: '기술',
auto: '자동'
}
function dictionaryMessage(error: unknown): string {
if (error instanceof DictionaryClientError) {
if (error.code === 'auth') return '세션이 만료되었습니다. 다시 로그인해 주세요.'
if (error.code === 'conflict') return '다른 기기에서 변경된 단어입니다. 목록을 새로고침한 뒤 다시 시도해 주세요.'
if (error.code === 'duplicate') return '같은 분류에 동일한 단어가 이미 있습니다.'
if (error.code === 'network') return '네트워크 연결을 확인한 뒤 다시 시도해 주세요.'
if (error.code === 'validation') return error.message
}
return '사전을 처리하지 못했습니다. 잠시 후 다시 시도해 주세요.'
}
function sortDictionary(entries: DictionaryEntry[]): DictionaryEntry[] {
return [...entries].sort((left, right) => {
const byDate = right.updated_at.localeCompare(left.updated_at)
return byDate !== 0 ? byDate : right.id.localeCompare(left.id)
})
}
function matchesView(entry: DictionaryEntry, category: DictionaryFilter, search: string): boolean {
if (category !== 'all' && entry.category !== category) return false
const normalized = sanitizeDictionarySearch(search).toLocaleLowerCase()
if (!normalized) return true
return entry.word.toLocaleLowerCase().includes(normalized)
|| (entry.pronunciation?.toLocaleLowerCase().includes(normalized) ?? false)
}
export default function DictionaryPage(): React.ReactElement {
const { user, loading: authLoading } = useAuth()
const [entries, setEntries] = useState<DictionaryEntry[]>([])
const [searchInput, setSearchInput] = useState('')
const [search, setSearch] = useState('')
const [category, setCategory] = useState<DictionaryFilter>('all')
const [nextCursor, setNextCursor] = useState<DictionaryCursor | null>(null)
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(true)
const [loadingMore, setLoadingMore] = useState(false)
const [error, setError] = useState<string | null>(null)
const [dialogOpen, setDialogOpen] = useState(false)
const [editing, setEditing] = useState<DictionaryEntry | null>(null)
const [draft, setDraft] = useState<DictionaryDraft>({ word: '', pronunciation: null, category: 'user' })
const [saving, setSaving] = useState(false)
const [mutatingIds, setMutatingIds] = useState<Set<string>>(() => new Set())
const [ioBusy, setIoBusy] = useState(false)
const [notice, setNotice] = useState<string | null>(null)
const requestGeneration = useRef(0)
const fileInputRef = useRef<HTMLInputElement | null>(null)
useEffect(() => {
const timer = window.setTimeout(() => setSearch(searchInput), SEARCH_DELAY_MS)
return () => window.clearTimeout(timer)
}, [searchInput])
const loadFirstPage = useCallback(async (): Promise<void> => {
const generation = ++requestGeneration.current
if (!user) {
if (!authLoading) {
setLoading(false)
setError('세션이 만료되었습니다. 다시 로그인해 주세요.')
}
return
}
setLoading(true)
setError(null)
try {
const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient
const result = await listDictionaryPage(client, {
userId: user.id,
search,
category,
pageSize: PAGE_SIZE,
cursor: null
})
if (generation !== requestGeneration.current) return
setEntries(result.entries)
setNextCursor(result.nextCursor)
setTotal(result.total)
} catch (requestError) {
if (generation !== requestGeneration.current) return
setEntries([])
setNextCursor(null)
setTotal(0)
setError(dictionaryMessage(requestError))
} finally {
if (generation === requestGeneration.current) setLoading(false)
}
}, [authLoading, category, search, user])
useEffect(() => {
void loadFirstPage()
}, [loadFirstPage])
const loadMore = async (): Promise<void> => {
if (!user || loading || loadingMore || !nextCursor) return
const generation = requestGeneration.current
setLoadingMore(true)
setError(null)
try {
const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient
const result = await listDictionaryPage(client, {
userId: user.id,
search,
category,
pageSize: PAGE_SIZE,
cursor: nextCursor
})
if (generation !== requestGeneration.current) return
setEntries((current) => {
const rows = new Map(current.map((entry) => [entry.id, entry]))
for (const entry of result.entries) rows.set(entry.id, entry)
return sortDictionary([...rows.values()])
})
setNextCursor(result.nextCursor)
} catch (requestError) {
if (generation === requestGeneration.current) setError(dictionaryMessage(requestError))
} finally {
if (generation === requestGeneration.current) setLoadingMore(false)
}
}
const openAdd = (): void => {
setEditing(null)
setDraft({ word: '', pronunciation: null, category: 'user' })
setDialogOpen(true)
}
const openEdit = (entry: DictionaryEntry): void => {
setEditing(entry)
setDraft({ word: entry.word, pronunciation: entry.pronunciation, category: entry.category })
setDialogOpen(true)
}
const save = async (): Promise<void> => {
if (!user || saving) return
let normalized: DictionaryDraft
try {
normalized = normalizeDictionaryDraft(draft)
} catch (requestError) {
setError(dictionaryMessage(requestError))
return
}
setSaving(true)
setError(null)
const now = new Date().toISOString()
const original = editing
const optimisticId = original?.id ?? crypto.randomUUID()
const optimistic: DictionaryEntry = {
id: optimisticId,
user_id: user.id,
word: normalized.word,
pronunciation: normalized.pronunciation,
category: normalized.category,
usage_count: original?.usage_count ?? 0,
last_used_at: original?.last_used_at ?? null,
created_at: original?.created_at ?? now,
updated_at: now
}
const wasVisible = original ? matchesView(original, category, search) : false
const willBeVisible = matchesView(optimistic, category, search)
setEntries((current) => {
if (original) {
const without = current.filter((entry) => entry.id !== original.id)
return willBeVisible ? sortDictionary([optimistic, ...without]) : without
}
return willBeVisible ? sortDictionary([optimistic, ...current]) : current
})
if (!original && willBeVisible) setTotal((value) => value + 1)
if (original && wasVisible && !willBeVisible) setTotal((value) => Math.max(0, value - 1))
if (original && !wasVisible && willBeVisible) setTotal((value) => value + 1)
setDialogOpen(false)
try {
const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient
const saved = original
? await updateDictionaryEntry(client, user.id, original, normalized)
: await createDictionaryEntry(client, user.id, normalized)
setEntries((current) => {
const without = current.filter((entry) => entry.id !== optimisticId && entry.id !== saved.id)
return matchesView(saved, category, search) ? sortDictionary([saved, ...without]) : without
})
} catch (requestError) {
setEntries((current) => {
const withoutOptimistic = current.filter((entry) => entry.id !== optimisticId)
return original && wasVisible ? sortDictionary([original, ...withoutOptimistic]) : withoutOptimistic
})
if (!original && willBeVisible) setTotal((value) => Math.max(0, value - 1))
if (original && wasVisible && !willBeVisible) setTotal((value) => value + 1)
if (original && !wasVisible && willBeVisible) setTotal((value) => Math.max(0, value - 1))
setError(dictionaryMessage(requestError))
} finally {
setSaving(false)
}
}
const remove = async (entry: DictionaryEntry): Promise<void> => {
if (!user || mutatingIds.has(entry.id)) return
if (!window.confirm(`“${entry.word}” 단어를 삭제할까요?`)) return
setMutatingIds((current) => new Set(current).add(entry.id))
setError(null)
const index = Math.max(0, entries.findIndex((candidate) => candidate.id === entry.id))
setEntries((current) => current.filter((candidate) => candidate.id !== entry.id))
setTotal((value) => Math.max(0, value - 1))
try {
const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient
await deleteDictionaryEntry(client, user.id, entry)
} catch (requestError) {
setEntries((current) => {
if (current.some((candidate) => candidate.id === entry.id)) return current
const restored = [...current]
restored.splice(Math.min(index, restored.length), 0, entry)
return restored
})
setTotal((value) => value + 1)
setError(dictionaryMessage(requestError))
} finally {
setMutatingIds((current) => {
const next = new Set(current)
next.delete(entry.id)
return next
})
}
}
const emptyMessage = search || category !== 'all'
? '조건에 맞는 사전 단어가 없습니다.'
: '등록된 사전 단어가 없습니다.'
const collectAllEntries = async (): Promise<DictionaryEntry[]> => {
if (!user) return []
const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient
const all: DictionaryEntry[] = []
let cursor: DictionaryCursor | null = null
for (let guard = 0; guard < 200; guard += 1) {
const page = await listDictionaryPage(client, {
userId: user.id,
search: '',
category: 'all',
pageSize: 50,
cursor
})
all.push(...page.entries)
if (!page.nextCursor) break
cursor = page.nextCursor
}
return all
}
const handleExport = async (format: 'json' | 'csv'): Promise<void> => {
if (!user || ioBusy) return
setIoBusy(true)
setError(null)
setNotice(null)
try {
const all = await collectAllEntries()
const visible = all.filter((entry) => matchesView(entry, category, search))
const stamp = new Date().toISOString().slice(0, 10)
downloadText(
`d3ro-dictionary-${stamp}.${format}`,
serializeDictionary(visible, format),
format === 'csv' ? 'text/csv;charset=utf-8' : 'application/json'
)
setNotice(`사전 ${visible.length}개를 내보냈습니다.`)
} catch (requestError) {
setError(dictionaryMessage(requestError))
} finally {
setIoBusy(false)
}
}
const handleImportFile = async (file: File): Promise<void> => {
if (!user) return
const format = file.name.toLowerCase().endsWith('.csv') ? 'csv' : 'json'
setIoBusy(true)
setError(null)
setNotice(null)
try {
const raw = await file.text()
const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient
const result = await importDictionaryFile(client, user.id, raw, format)
await loadFirstPage()
setNotice(`가져오기 ${result.imported}건, 건너뜀 ${result.skipped}건`)
} catch (requestError) {
setError(dictionaryMessage(requestError))
} finally {
setIoBusy(false)
}
}
return (
<Box sx={{ maxWidth: 1080, mx: 'auto', p: { xs: 2.5, md: 4 }, pt: 4, pb: 10 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 2, mb: 3 }}>
<Box>
<PhosphorText variant="title">CUSTOM DICTIONARY</PhosphorText>
<PhosphorText variant="meta" sx={{ display: 'block', mt: 0.75, color: d3roPalette.text.dimLabel }}>
{total} ENTRIES · ACCOUNT SYNC
</PhosphorText>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
<Tooltip title="JSON 내보내기">
<span>
<IconButton aria-label="사전 JSON 내보내기" size="small" disabled={ioBusy} onClick={() => void handleExport('json')} sx={{ color: 'var(--d3-text-label)' }}>
<Download size={16} />
</IconButton>
</span>
</Tooltip>
<Tooltip title="CSV 내보내기">
<span>
<IconButton aria-label="사전 CSV 내보내기" size="small" disabled={ioBusy} onClick={() => void handleExport('csv')} sx={{ color: 'var(--d3-text-label)' }}>
<Download size={16} />
</IconButton>
</span>
</Tooltip>
<Tooltip title="가져오기 (JSON/CSV)">
<span>
<IconButton aria-label="사전 가져오기" size="small" disabled={ioBusy} onClick={() => fileInputRef.current?.click()} sx={{ color: 'var(--d3-text-label)' }}>
<Upload size={16} />
</IconButton>
</span>
</Tooltip>
<input
ref={fileInputRef}
type="file"
accept=".json,.csv,application/json,text/csv"
hidden
onChange={(event) => {
const file = event.target.files?.[0]
event.target.value = ''
if (file) void handleImportFile(file)
}}
/>
<PhysicalButton tone="accent" onClick={openAdd} size="small" trailingIcon={<Plus size={14} />}>
단어 추가
</PhysicalButton>
</Box>
</Box>
{notice && (
<Alert severity="success" sx={{ mb: 3 }} onClose={() => setNotice(null)}>
{notice}
</Alert>
)}
<Box sx={{ display: 'flex', gap: 1.5, mb: 3, flexWrap: 'wrap' }}>
<TextField
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
placeholder="단어 또는 발음 검색..."
size="small"
inputProps={{ 'aria-label': '커스텀 사전 검색', maxLength: 100 }}
InputProps={{
startAdornment: <InputAdornment position="start"><Search size={16} color="var(--d3-text-label)" /></InputAdornment>,
sx: { bgcolor: 'var(--d3-bg-inset)', borderRadius: '12px', border: '1px solid var(--d3-border-default)', color: 'var(--d3-text-secondary)', '& fieldset': { border: 'none' } }
}}
sx={{ flex: 1, minWidth: 260 }}
/>
<Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap' }} aria-label="사전 분류 필터">
{(['all', 'user', 'technical', 'auto'] as const).map((value) => (
<TactileBadge
key={value}
mono
tone={category === value ? 'accent' : 'default'}
onClick={() => setCategory(value)}
sx={{ cursor: 'pointer', height: 36, px: 1.5 }}
>
{value === 'all' ? '전체' : CATEGORY_LABELS[value]}
</TactileBadge>
))}
</Box>
</Box>
{error && (
<Alert
severity="error"
action={<Button color="inherit" size="small" startIcon={<RefreshCw size={14} />} onClick={() => void loadFirstPage()}>새로고침</Button>}
sx={{ mb: 3 }}
>
{error}
</Alert>
)}
{authLoading || loading ? (
<Box role="status" sx={{ py: 8, display: 'flex', justifyContent: 'center' }}>
<CircularProgress size={30} aria-label="사전 불러오는 중" />
</Box>
) : entries.length === 0 ? (
<MetalCard sx={{ p: 6, textAlign: 'center', color: d3roPalette.text.muted }}>{emptyMessage}</MetalCard>
) : (
<Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, gap: 2 }}>
{entries.map((entry) => {
const busy = mutatingIds.has(entry.id)
return (
<MetalCard key={entry.id} sx={{ p: 2.5 }} data-testid={`dictionary-card-${entry.id}`}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 2 }}>
<Box sx={{ minWidth: 0 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 1, flexWrap: 'wrap' }}>
<Typography sx={{ fontSize: 18, fontWeight: 500, color: 'var(--d3-text-inverse)', overflowWrap: 'anywhere' }}>{entry.word}</Typography>
{entry.pronunciation && <TactileBadge mono tone="accent">[{entry.pronunciation}]</TactileBadge>}
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<TactileBadge mono tone="mono">{CATEGORY_LABELS[entry.category]}</TactileBadge>
<Typography sx={{ fontFamily: d3roFontMono, fontSize: 11, color: 'var(--d3-text-label)' }}>{entry.usage_count}회 사용</Typography>
</Box>
</Box>
<Box sx={{ display: 'flex', gap: 0.25 }}>
<Tooltip title="편집"><span><IconButton aria-label={`${entry.word} 편집`} size="small" disabled={busy} onClick={() => openEdit(entry)} sx={{ color: 'var(--d3-text-label)' }}><Pencil size={15} /></IconButton></span></Tooltip>
<Tooltip title="삭제"><span><IconButton aria-label={`${entry.word} 삭제`} size="small" disabled={busy} onClick={() => void remove(entry)} sx={{ color: 'var(--d3-text-label)', '&:hover': { color: 'var(--d3-status-danger)' } }}><Trash2 size={15} /></IconButton></span></Tooltip>
</Box>
</Box>
</MetalCard>
)
})}
</Box>
)}
{!loading && nextCursor && (
<Box sx={{ mt: 4, display: 'flex', justifyContent: 'center' }}>
<Button variant="outlined" disabled={loadingMore} onClick={() => void loadMore()}>
{loadingMore ? <CircularProgress size={20} /> : '더 불러오기'}
</Button>
</Box>
)}
<Dialog
open={dialogOpen}
onClose={() => { if (!saving) setDialogOpen(false) }}
maxWidth="xs"
fullWidth
PaperProps={{ sx: { bgcolor: 'var(--d3-bg-card)', border: '1px solid var(--d3-border-default)', borderRadius: '16px', p: 1 } }}
>
<DialogTitle sx={{ color: 'var(--d3-text-inverse)', fontWeight: 500 }}>{editing ? '단어 편집' : '새 단어 추가'}</DialogTitle>
<DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
<TextField
label="단어"
value={draft.word}
onChange={(event) => setDraft((current) => ({ ...current, word: event.target.value }))}
inputProps={{ maxLength: 120 }}
fullWidth
autoFocus
size="small"
sx={{ mt: 1 }}
/>
<TextField
label="발음 (선택)"
value={draft.pronunciation ?? ''}
onChange={(event) => setDraft((current) => ({ ...current, pronunciation: event.target.value }))}
inputProps={{ maxLength: 200 }}
fullWidth
size="small"
helperText="예: 디쓰리오"
/>
<FormControl fullWidth size="small">
<InputLabel id="dictionary-category-label">분류</InputLabel>
<Select
labelId="dictionary-category-label"
label="분류"
value={draft.category}
onChange={(event) => setDraft((current) => ({ ...current, category: event.target.value as DictionaryCategory }))}
>
{(['user', 'technical', 'auto'] as const).map((value) => <MenuItem key={value} value={value}>{CATEGORY_LABELS[value]}</MenuItem>)}
</Select>
</FormControl>
</DialogContent>
<DialogActions sx={{ p: 2 }}>
<PhysicalButton tone="glass" disabled={saving} onClick={() => setDialogOpen(false)}>취소</PhysicalButton>
<PhysicalButton tone="accent" disabled={saving || !draft.word.trim()} onClick={() => void save()}>
{saving ? '저장 중...' : '저장'}
</PhysicalButton>
</DialogActions>
</Dialog>
</Box>
)
}