d3ro-voice/apps/mobile-rn/src/screens/HistoryScreen.tsx
Yun Chan 5ca3709b32
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Failing after 50s
ci / 워크스페이스 빌드 검증 (push) Has been skipped
ci / Supabase Edge Functions + Cloudflare Worker (push) Successful in 20s
ci / .NET API 서버 테스트 (push) Successful in 12s
deploy-site / deploy (push) Successful in 39s
ci / 모바일 린트·타입·Jest (push) Failing after 3h10m31s
feat: add mobile shell and unified search
2026-09-28 23:23:36 +09:00

382 lines
15 KiB
TypeScript

import { useMemo } from 'react'
import {
ActivityIndicator,
Alert,
FlatList,
Pressable,
RefreshControl,
StyleSheet,
TextInput,
View,
} from 'react-native'
import type { NavigationProp, ParamListBase } from '@react-navigation/native'
import {
MetalCard,
PhosphorText,
Led,
FilterChip,
NativeThemeProvider,
} from '@d3ro/ui-native'
import { useI18n } from '@d3ro/i18n'
import { useHistorySync } from '../features/history/use-history-sync'
import type { HistoryFilter, HistoryListEntry } from '../features/history/history-service'
import { useMobilePreferences } from '../lib/preferences-context'
import { ScreenHeader } from '../components/ScreenHeader'
import { useTabScreenBottomPadding } from '../navigation/tab-layout'
interface HistoryScreenProps {
navigation: NavigationProp<ParamListBase>
}
type GroupedItem =
| { id: string; type: 'header'; label: string }
| { id: string; type: 'entry'; entry: HistoryListEntry }
export default function HistoryScreen({ navigation }: HistoryScreenProps): React.ReactElement {
const bottomPadding = useTabScreenBottomPadding()
const { t, formatTime, formatRelativeDate } = useI18n()
const { palette } = useMobilePreferences()
const styles = useMemo(() => createStyles(palette), [palette])
const history = useHistorySync()
const grouped = useMemo(
() => groupByDate(history.entries, formatRelativeDate),
[formatRelativeDate, history.entries],
)
const openDetail = (entry: HistoryListEntry): void => {
// WORKS 허브에서 루트 스택으로 푸시된 경우 getParent()가 없으므로
// 현재 네비게이터(루트 스택) 자체로 HistoryDetail을 푸시한다.
const target = navigation.getParent() ?? navigation
target.navigate('HistoryDetail', { historyId: entry.id })
}
const changeFavorite = async (entry: HistoryListEntry): Promise<void> => {
try {
await history.toggleFavorite(entry)
} catch {
Alert.alert(t('mobile.auth.errorTitle'), t('mobile.hist.favoriteFailed'))
}
}
const confirmDelete = (entry: HistoryListEntry): void => {
Alert.alert(
t('mobile.hist.deleteTitle'),
t('mobile.hist.deleteBody'),
[
{ text: t('mobile.hist.cancel'), style: 'cancel' },
{
text: t('mobile.hist.delete'),
style: 'destructive',
onPress: () => {
void history.deleteEntry(entry).catch(() => {
Alert.alert(t('mobile.auth.errorTitle'), t('mobile.hist.deleteFailed'))
})
},
},
],
)
}
if (history.loading) {
return (
<NativeThemeProvider palette={palette}>
<View
accessibilityLiveRegion="polite"
style={styles.center}
testID="history-loading"
>
<ActivityIndicator size="large" color={palette.accent.main} />
</View>
</NativeThemeProvider>
)
}
return (
<NativeThemeProvider palette={palette}>
<View style={styles.container}>
<ScreenHeader
title={t('mobile.hist.title')}
showBack={false}
rightContent={
<PhosphorText variant="meta" color="muted">
{t('mobile.hist.entries', { count: history.entries.length })}
</PhosphorText>
}
testID="history-header"
/>
<View style={styles.searchRow}>
<TextInput
accessibilityLabel={t('mobile.hist.searchPlaceholder')}
value={history.search}
onChangeText={history.setSearch}
placeholder={t('mobile.hist.searchPlaceholder')}
placeholderTextColor={palette.text.muted}
returnKeyType="search"
autoCapitalize="none"
autoCorrect={false}
style={styles.searchInput}
testID="history-search"
/>
</View>
<View style={styles.filters}>
<HistoryFilterChip label={t('mobile.hist.all')} value="all" active={history.filter} onChange={history.setFilter} />
<HistoryFilterChip label={t('mobile.hist.saved')} value="favorites" active={history.filter} onChange={history.setFilter} />
<HistoryFilterChip label={t('mobile.hist.processing')} value="processing" active={history.filter} onChange={history.setFilter} />
</View>
{history.offline && (
<View
accessibilityRole="alert"
accessibilityLiveRegion="polite"
style={styles.offlineBanner}
testID="history-offline-banner"
>
<PhosphorText variant="small" color="amber">{t('mobile.hist.offline')}</PhosphorText>
{history.staleAt !== null && (
<PhosphorText variant="meta" color="muted">
{t('mobile.hist.cachedAt', { time: formatTime(new Date(history.staleAt).getTime()) })}
</PhosphorText>
)}
</View>
)}
{history.cacheWarning && !history.offline && (
<View accessibilityLiveRegion="polite" style={styles.warningBanner} testID="history-cache-warning">
<PhosphorText variant="meta" color="muted">{t('mobile.hist.cacheWarning')}</PhosphorText>
</View>
)}
{history.realtimeDisconnected && !history.offline && (
<View accessibilityLiveRegion="polite" style={styles.warningBanner} testID="history-realtime-warning">
<PhosphorText variant="meta" color="muted">{t('mobile.hist.realtimeWaiting')}</PhosphorText>
</View>
)}
{history.error !== null && (
<View
accessibilityRole="alert"
accessibilityLiveRegion="assertive"
style={styles.errorBanner}
testID="history-error-banner"
>
<PhosphorText variant="small" color="primary">{t('mobile.hist.loadError')}</PhosphorText>
<Pressable
accessibilityRole="button"
onPress={() => { void history.refresh() }}
style={styles.retryButton}
testID="history-retry"
>
<PhosphorText variant="small" color="amber">{t('mobile.hist.retry')}</PhosphorText>
</Pressable>
</View>
)}
<FlatList
data={grouped}
keyExtractor={(item) => item.id}
contentContainerStyle={history.entries.length === 0
? [styles.emptyList, { paddingBottom: bottomPadding }]
: [styles.listContent, { paddingBottom: bottomPadding }]}
keyboardShouldPersistTaps="handled"
refreshControl={
<RefreshControl
refreshing={history.refreshing}
onRefresh={() => { void history.refresh() }}
tintColor={palette.accent.main}
/>
}
onEndReached={() => { void history.loadMore() }}
onEndReachedThreshold={0.35}
ListEmptyComponent={
history.error === null ? (
<PhosphorText variant="body" color="muted" style={styles.emptyText} testID="history-empty">
{history.search.trim().length > 0 || history.filter !== 'all'
? t('mobile.hist.emptySearch')
: t('mobile.hist.empty')}
</PhosphorText>
) : null
}
renderItem={({ item }) => {
if (item.type === 'header') {
return (
<PhosphorText variant="label" color="muted" style={styles.dateHeader}>
{item.label}
</PhosphorText>
)
}
const entry = item.entry
const isOld = !isToday(entry.created_at)
const busy = history.isMutating(entry.id)
return (
<MetalCard style={[styles.card, isOld && styles.cardOld]} testID={`history-card-${entry.id}`}>
<Pressable
accessibilityRole="button"
accessibilityLabel={entry.title ?? entry.polished_text ?? entry.original_text}
onPress={() => openDetail(entry)}
style={styles.cardBody}
>
<View style={styles.cardHeader}>
<View style={styles.cardHeaderLeft}>
<Led
color={entry.activeJob !== null
? 'amber'
: entry.status === 'completed' ? 'green' : 'amber'}
size={6}
on={!isOld || entry.activeJob !== null}
/>
<PhosphorText variant="label" color="primary" style={styles.timeLabel}>
{formatTime(new Date(entry.created_at).getTime())}
</PhosphorText>
</View>
{entry.word_count > 0 && (
<View style={styles.wordBadge}>
<PhosphorText variant="label" color="amber">
{t('mobile.hist.wordsShort', { count: entry.word_count })}
</PhosphorText>
</View>
)}
</View>
{entry.title !== null && (
<PhosphorText variant="small" color="primary" numberOfLines={1} style={styles.entryTitle}>
{entry.title}
</PhosphorText>
)}
<PhosphorText variant="body" color="primary" style={styles.transcriptText} numberOfLines={3}>
{entry.polished_text ?? entry.original_text}
</PhosphorText>
<View style={styles.cardMeta}>
<PhosphorText variant="label" color="muted">
{entry.stt_model?.toUpperCase() ?? entry.mode.toUpperCase()}
</PhosphorText>
{entry.activeJob !== null && (
<PhosphorText variant="meta" color="amber">
{t('mobile.hist.processingProgress', { progress: entry.activeJob.progress })}
</PhosphorText>
)}
</View>
</Pressable>
<View style={styles.cardActions}>
<Pressable
accessibilityRole="button"
accessibilityLabel={entry.is_favorite ? t('mobile.hist.unfavorite') : t('mobile.hist.favorite')}
disabled={busy || history.offline}
onPress={() => { void changeFavorite(entry) }}
style={styles.cardAction}
testID={`history-favorite-${entry.id}`}
>
{busy ? (
<ActivityIndicator size="small" color={palette.accent.main} />
) : (
<PhosphorText color="amber">{entry.is_favorite ? '★' : '☆'}</PhosphorText>
)}
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel={t('mobile.hist.delete')}
disabled={busy || history.offline}
onPress={() => confirmDelete(entry)}
style={styles.cardAction}
testID={`history-delete-${entry.id}`}
>
<PhosphorText variant="small" color="muted">{t('mobile.hist.delete')}</PhosphorText>
</Pressable>
</View>
</MetalCard>
)
}}
ListFooterComponent={history.loadingMore ? (
<View style={styles.loadingMore} testID="history-loading-more">
<ActivityIndicator size="small" color={palette.accent.main} />
<PhosphorText variant="meta" color="muted">{t('mobile.hist.loadMore')}</PhosphorText>
</View>
) : null}
/>
</View>
</NativeThemeProvider>
)
}
function HistoryFilterChip({
label,
value,
active,
onChange,
}: {
label: string
value: HistoryFilter
active: HistoryFilter
onChange: (filter: HistoryFilter) => void
}): React.ReactElement {
return <FilterChip label={label} active={active === value} onPress={() => onChange(value)} />
}
function isToday(dateStr: string): boolean {
const date = new Date(dateStr)
const now = new Date()
return date.toDateString() === now.toDateString()
}
export function groupByDate(
entries: HistoryListEntry[],
formatRelativeDate: (timestamp: number) => string,
): GroupedItem[] {
const result: GroupedItem[] = []
let lastDate = ''
for (const entry of entries) {
const dateLabel = formatRelativeDate(new Date(entry.created_at).getTime())
if (dateLabel !== lastDate) {
result.push({ id: `header-${entry.created_at.slice(0, 10)}`, type: 'header', label: dateLabel })
lastDate = dateLabel
}
result.push({ id: entry.id, type: 'entry', entry })
}
return result
}
type Palette = ReturnType<typeof useMobilePreferences>['palette']
function createStyles(palette: Palette) {
return StyleSheet.create({
container: { flex: 1, backgroundColor: palette.bg.app },
center: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 32, backgroundColor: palette.bg.app },
searchRow: { paddingHorizontal: 20, paddingTop: 12 },
searchInput: {
minHeight: 48,
paddingHorizontal: 14,
borderWidth: 1,
borderColor: palette.border.default,
borderRadius: 10,
backgroundColor: palette.bg.inset,
color: palette.text.primary,
fontSize: 14,
},
filters: { flexDirection: 'row', paddingHorizontal: 20, paddingVertical: 12, gap: 12, borderBottomWidth: 1, borderBottomColor: palette.border.subtle },
offlineBanner: { gap: 4, paddingHorizontal: 20, paddingVertical: 10, backgroundColor: palette.accent.dim },
warningBanner: { paddingHorizontal: 20, paddingVertical: 8 },
errorBanner: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 12, paddingHorizontal: 20, paddingVertical: 10, backgroundColor: palette.bg.card, borderBottomWidth: 1, borderBottomColor: palette.tag.red },
retryButton: { minWidth: 72, minHeight: 48, alignItems: 'center', justifyContent: 'center' },
listContent: { padding: 20 },
emptyList: { flexGrow: 1, alignItems: 'center', justifyContent: 'center', padding: 32 },
emptyText: { textAlign: 'center' },
dateHeader: { letterSpacing: 3, marginBottom: 8, marginTop: 16 },
card: { marginBottom: 12, padding: 0 },
cardOld: { opacity: 0.82 },
cardBody: { minHeight: 48, padding: 16, paddingBottom: 10 },
cardHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 },
cardHeaderLeft: { flexDirection: 'row', alignItems: 'center' },
timeLabel: { marginLeft: 8 },
wordBadge: { backgroundColor: palette.accent.dim, paddingHorizontal: 8, paddingVertical: 2, borderRadius: 4 },
entryTitle: { marginBottom: 6 },
transcriptText: { marginBottom: 8 },
cardMeta: { flexDirection: 'row', justifyContent: 'space-between', gap: 12 },
cardActions: { flexDirection: 'row', justifyContent: 'flex-end', borderTopWidth: 1, borderTopColor: palette.border.subtle },
cardAction: { minWidth: 64, minHeight: 48, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 12, borderLeftWidth: 1, borderLeftColor: palette.border.subtle },
loadingMore: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 10, padding: 18 },
})
}