feat(release): prepare 1.1.0 candidate
This commit is contained in:
parent
5a34f66981
commit
5205dcdfa9
736 changed files with 115667 additions and 12203 deletions
419
apps/web/src/app/(app)/dictionary/page.tsx
Normal file
419
apps/web/src/app/(app)/dictionary/page.tsx
Normal file
|
|
@ -0,0 +1,419 @@
|
|||
'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 { Pencil, Plus, RefreshCw, Search, Trash2 } 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,
|
||||
listDictionaryPage,
|
||||
normalizeDictionaryDraft,
|
||||
sanitizeDictionarySearch,
|
||||
updateDictionaryEntry,
|
||||
type DictionaryCategory,
|
||||
type DictionaryCursor,
|
||||
type DictionaryDraft,
|
||||
type DictionaryFilter
|
||||
} from '@/lib/dictionary-client'
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
const SEARCH_DELAY_MS = 300
|
||||
|
||||
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 requestGeneration = useRef(0)
|
||||
|
||||
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'
|
||||
? '조건에 맞는 사전 단어가 없습니다.'
|
||||
: '등록된 사전 단어가 없습니다.'
|
||||
|
||||
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>
|
||||
<PhysicalButton tone="accent" onClick={openAdd} size="small" trailingIcon={<Plus size={14} />}>
|
||||
단어 추가
|
||||
</PhysicalButton>
|
||||
</Box>
|
||||
|
||||
<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: '#fff', 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: '#ef4444' } }}><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: '#fff', 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>
|
||||
)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue