d3ro-voice/apps/mobile-rn/src/screens/HomeScreen.tsx

425 lines
14 KiB
TypeScript

// src/screens/HomeScreen.tsx — 홈(오늘). 데스크톱 HomePage 와 같은 문법:
// 제목·날짜 → 녹음 시작 안내 → 한 줄 요약 → 최근 기록 5 · 최근 회의 3 → (무료) 요금제 한 줄.
// 카드·통계 격자 없이 제목 + 1px 선. 조회한 값만 보여 주고, 못 불러오면 그렇다고 말한다.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
Pressable,
RefreshControl,
ScrollView,
StyleSheet,
View,
} from 'react-native'
import {
type CompositeNavigationProp,
useFocusEffect,
useNavigation,
} from '@react-navigation/native'
import type { BottomTabNavigationProp } from '@react-navigation/bottom-tabs'
import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import type { Meeting } from '@d3ro/api-client'
import { useI18n, type TFunction } from '@d3ro/i18n'
import { CONTENT_MAX_WIDTH_DP } from '@d3ro/ui-native'
import { useAuth } from '../lib/auth-context'
import { useEntitlement } from '../lib/entitlement-context'
import { useMobilePreferences } from '../lib/preferences-context'
import { ThemeButton, ThemeText } from '../theme/themed-components'
import {
loadDashboardStats,
type MobileDashboardStats,
} from '../features/dashboard/dashboard-service'
import { listMeetingsPage } from '../features/meetings/meetings-service'
import type { RootStackParamList } from '../../App'
import type { MainTabParamList } from '../navigation/TabNavigator'
import { useTabScreenBottomPadding } from '../navigation/tab-layout'
const RECENT_RECORD_LIMIT = 5
const RECENT_MEETING_LIMIT = 3
type Palette = ReturnType<typeof useMobilePreferences>['palette']
type HomeNavigation = CompositeNavigationProp<
BottomTabNavigationProp<MainTabParamList, 'Home'>,
NativeStackNavigationProp<RootStackParamList>
>
function formatMinutes(seconds: number): string {
const minutes = seconds / 60
return minutes >= 10 ? String(Math.round(minutes)) : minutes.toFixed(1)
}
/** 오늘 n회 · 단어 · 녹음 시간 · 연속 일수 — 0 인 항목은 생략(같은 값을 두 번 말하지 않는다). */
export function buildTodaySummary(stats: MobileDashboardStats, t: TFunction): string {
const parts: string[] = []
if (stats.todaySessions === 0) {
parts.push(t('mobile.home.summaryNone'))
} else {
parts.push(t('mobile.home.summarySessions', { count: stats.todaySessions }))
if (stats.todayWordCount > 0) {
parts.push(t('mobile.home.summaryWords', { count: stats.todayWordCount }))
}
if (stats.todayRecordingSeconds > 0) {
parts.push(t('mobile.home.summaryMinutes', {
minutes: formatMinutes(stats.todayRecordingSeconds),
}))
}
}
if (stats.streakDays > 0) {
parts.push(t('mobile.home.summaryStreak', { count: stats.streakDays }))
}
return parts.join(' · ')
}
function meetingStatusLabel(status: Meeting['status'], t: TFunction): string {
if (status === 'recording') return t('mobile.meetings.statusRecording')
if (status === 'processing') return t('mobile.meetings.statusProcessing')
if (status === 'completed') return t('mobile.meetings.statusCompleted')
return t('mobile.meetings.statusError')
}
export default function HomeScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
const bottomPadding = useTabScreenBottomPadding()
const navigation = useNavigation<HomeNavigation>()
const { t, formatDate, formatRelativeDate, formatTime } = useI18n()
const { user } = useAuth()
const { refresh: refreshEntitlement, snapshot: entitlementSnapshot } = useEntitlement()
const { palette } = useMobilePreferences()
const styles = useMemo(() => createStyles(palette), [palette])
const [stats, setStats] = useState<MobileDashboardStats | null>(null)
const [statsError, setStatsError] = useState(false)
const [meetings, setMeetings] = useState<Meeting[] | null>(null)
const [meetingsError, setMeetingsError] = useState(false)
const [loading, setLoading] = useState(true)
const [refreshing, setRefreshing] = useState(false)
const mountedRef = useRef(true)
const refreshGenerationRef = useRef(0)
const currentUserIdRef = useRef<string | null>(user?.id ?? null)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
refreshGenerationRef.current += 1
}
}, [])
useEffect(() => {
currentUserIdRef.current = user?.id ?? null
}, [user?.id])
const refresh = useCallback(async (pullToRefresh = false): Promise<void> => {
const generation = ++refreshGenerationRef.current
const targetUserId = user?.id ?? null
if (!targetUserId) {
setStats(null)
setMeetings(null)
setStatsError(true)
setMeetingsError(true)
setLoading(false)
setRefreshing(false)
return
}
if (pullToRefresh) setRefreshing(true)
else setLoading(true)
const [statsResult, meetingsResult] = await Promise.allSettled([
loadDashboardStats(targetUserId),
listMeetingsPage({ userId: targetUserId, page: 0, pageSize: RECENT_MEETING_LIMIT }),
refreshEntitlement(),
])
if (
!mountedRef.current
|| generation !== refreshGenerationRef.current
|| currentUserIdRef.current !== targetUserId
) return
if (statsResult.status === 'fulfilled') {
setStats(statsResult.value)
setStatsError(false)
} else {
setStatsError(true)
}
if (meetingsResult.status === 'fulfilled') {
setMeetings(meetingsResult.value.meetings)
setMeetingsError(false)
} else {
setMeetingsError(true)
}
setLoading(false)
setRefreshing(false)
}, [refreshEntitlement, user?.id])
useFocusEffect(useCallback(() => {
void refresh(false)
}, [refresh]))
const today = formatDate(new Date(), { month: 'long', day: 'numeric', weekday: 'long' })
const recentRecords = stats?.recentHistory.slice(0, RECENT_RECORD_LIMIT) ?? []
const recentMeetings = meetings?.slice(0, RECENT_MEETING_LIMIT) ?? []
return (
<ScrollView
style={styles.container}
contentContainerStyle={[
styles.content,
{ paddingTop: insets.top + 16, paddingBottom: bottomPadding },
]}
refreshControl={(
<RefreshControl
refreshing={refreshing}
onRefresh={() => void refresh(true)}
tintColor={palette.accent.main}
colors={[palette.accent.main]}
/>
)}
testID="home-screen"
>
<View style={styles.header}>
<ThemeText variant="title" accessibilityRole="header">{t('mobile.home.title')}</ThemeText>
<ThemeText variant="small" color="muted">{today}</ThemeText>
</View>
<Pressable
accessibilityRole="button"
accessibilityLabel={t('unifiedSearch.title')}
accessibilityHint={t('unifiedSearch.homeHint')}
onPress={() => navigation.navigate('UnifiedSearch')}
testID="home-open-unified-search"
style={({ pressed }) => [
styles.searchEntry,
{ borderColor: palette.border.subtle },
pressed && { backgroundColor: palette.bg.cardHover },
]}
>
<View style={styles.searchGlyph} accessibilityElementsHidden>
<View style={[styles.searchRing, { borderColor: palette.text.muted }]} />
<View style={[styles.searchHandle, { backgroundColor: palette.text.muted }]} />
</View>
<View style={styles.flex}>
<ThemeText>{t('unifiedSearch.title')}</ThemeText>
<ThemeText variant="small" color="muted" numberOfLines={1}>
{t('unifiedSearch.homeHint')}
</ThemeText>
</View>
<View style={[styles.chevron, { borderColor: palette.text.muted }]} />
</Pressable>
<ThemeText color="secondary" style={styles.hint}>{t('mobile.home.recordHint')}</ThemeText>
<View style={styles.summary} testID="home-summary">
{stats !== null ? (
<ThemeText color="primary">{buildTodaySummary(stats, t)}</ThemeText>
) : loading ? (
<ThemeText color="muted" testID="home-loading">{t('mobile.home.loading')}</ThemeText>
) : statsError ? (
<View style={styles.errorRow} testID="home-error">
<ThemeText color="danger" style={styles.flex}>{t('mobile.home.loadError')}</ThemeText>
<ThemeButton
label={t('mobile.home.retry')}
variant="quiet"
onPress={() => void refresh(false)}
testID="home-retry"
/>
</View>
) : null}
</View>
<SectionHeader
title={t('mobile.home.recentRecords')}
actionLabel={t('mobile.home.seeAll')}
actionAccessibilityLabel={t('mobile.home.seeAllRecords')}
onAction={() => navigation.navigate('Records')}
testID="home-see-all-records"
/>
{stats !== null && recentRecords.length === 0 ? (
<ThemeText color="muted" style={styles.empty}>{t('mobile.home.noRecords')}</ThemeText>
) : recentRecords.map((entry) => {
const createdAt = Date.parse(entry.createdAt)
const title = entry.title?.trim() || entry.text.trim()
return (
<ListRow
key={entry.id}
title={title}
meta={`${formatRelativeDate(createdAt)} ${formatTime(createdAt)}`}
onPress={() => navigation.navigate('HistoryDetail', { historyId: entry.id })}
testID={`home-record-${entry.id}`}
/>
)
})}
<SectionHeader
title={t('mobile.home.recentMeetings')}
actionLabel={t('mobile.home.seeAll')}
actionAccessibilityLabel={t('mobile.home.seeAllMeetings')}
onAction={() => navigation.navigate('Meetings')}
testID="home-see-all-meetings"
/>
{meetingsError && meetings === null ? (
<ThemeText color="danger" style={styles.empty}>{t('mobile.home.meetingsLoadError')}</ThemeText>
) : meetings !== null && recentMeetings.length === 0 ? (
<ThemeText color="muted" style={styles.empty}>{t('mobile.home.noMeetings')}</ThemeText>
) : recentMeetings.map((meeting) => {
const startedAt = Date.parse(meeting.started_at)
return (
<ListRow
key={meeting.id}
title={meeting.title?.trim() || t('mobile.meetings.untitled')}
meta={`${formatRelativeDate(startedAt)} ${formatTime(startedAt)} · ${meetingStatusLabel(meeting.status, t)}`}
onPress={() => navigation.navigate('MeetingDetail', { meetingId: meeting.id })}
testID={`home-meeting-${meeting.id}`}
/>
)
})}
{entitlementSnapshot.tier === 'free' && (
<Pressable
accessibilityRole="button"
accessibilityHint={t('mobile.home.freePlanHint')}
onPress={() => navigation.navigate('ProPaywall')}
testID="home-open-plans"
style={({ pressed }) => [
styles.planLine,
{ borderTopColor: palette.border.subtle },
pressed && { backgroundColor: palette.bg.cardHover },
]}
>
<ThemeText variant="small" color="muted">{t('mobile.home.freePlan')}</ThemeText>
</Pressable>
)}
</ScrollView>
)
}
function SectionHeader({
title,
actionLabel,
actionAccessibilityLabel,
onAction,
testID,
}: {
title: string
actionLabel: string
actionAccessibilityLabel: string
onAction: () => void
testID: string
}): React.ReactElement {
const { palette } = useMobilePreferences()
return (
<View style={[stylesStatic.sectionHeader, { borderBottomColor: palette.border.subtle }]}>
<ThemeText variant="heading" accessibilityRole="header">{title}</ThemeText>
<Pressable
accessibilityRole="button"
accessibilityLabel={actionAccessibilityLabel}
onPress={onAction}
hitSlop={4}
testID={testID}
style={({ pressed }) => [stylesStatic.sectionAction, pressed && { opacity: 0.6 }]}
>
<ThemeText variant="small" color="accent">{actionLabel}</ThemeText>
</Pressable>
</View>
)
}
function ListRow({
title,
meta,
onPress,
testID,
}: {
title: string
meta: string
onPress: () => void
testID: string
}): React.ReactElement {
const { palette } = useMobilePreferences()
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={`${title}, ${meta}`}
onPress={onPress}
testID={testID}
style={({ pressed }) => [
stylesStatic.row,
{ borderBottomColor: palette.border.subtle },
pressed && { backgroundColor: palette.bg.cardHover },
]}
>
<ThemeText numberOfLines={1}>{title}</ThemeText>
<ThemeText variant="small" color="muted" numberOfLines={1}>{meta}</ThemeText>
</Pressable>
)
}
const stylesStatic = StyleSheet.create({
sectionHeader: {
marginTop: 28,
minHeight: 48,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
borderBottomWidth: 1,
},
sectionAction: { minHeight: 48, minWidth: 48, alignItems: 'flex-end', justifyContent: 'center' },
row: {
minHeight: 56,
paddingVertical: 10,
justifyContent: 'center',
gap: 2,
borderBottomWidth: 1,
},
})
function createStyles(palette: Palette) {
return StyleSheet.create({
container: { flex: 1, backgroundColor: palette.bg.app },
content: { paddingHorizontal: 20, width: '100%', maxWidth: CONTENT_MAX_WIDTH_DP, alignSelf: 'center' },
header: { gap: 2 },
searchEntry: {
minHeight: 64,
marginTop: 16,
paddingVertical: 8,
flexDirection: 'row',
alignItems: 'center',
gap: 12,
borderTopWidth: 1,
borderBottomWidth: 1,
},
searchGlyph: { width: 24, height: 24 },
searchRing: {
position: 'absolute',
left: 2,
top: 2,
width: 14,
height: 14,
borderWidth: 1.5,
borderRadius: 7,
},
searchHandle: {
position: 'absolute',
left: 15,
top: 15,
width: 8,
height: 1.5,
borderRadius: 1,
transform: [{ rotate: '45deg' }],
},
chevron: {
width: 8,
height: 8,
marginRight: 4,
borderTopWidth: 1.5,
borderRightWidth: 1.5,
transform: [{ rotate: '45deg' }],
},
hint: { marginTop: 16 },
summary: { marginTop: 12, minHeight: 22 },
errorRow: { flexDirection: 'row', alignItems: 'center', gap: 12 },
flex: { flex: 1 },
empty: { paddingVertical: 14 },
planLine: {
marginTop: 28,
minHeight: 48,
justifyContent: 'center',
borderTopWidth: 1,
},
})
}