// 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['palette'] type HomeNavigation = CompositeNavigationProp< BottomTabNavigationProp, NativeStackNavigationProp > 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() 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(null) const [statsError, setStatsError] = useState(false) const [meetings, setMeetings] = useState(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(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 => { 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 ( void refresh(true)} tintColor={palette.accent.main} colors={[palette.accent.main]} /> )} testID="home-screen" > {t('mobile.home.title')} {today} navigation.navigate('UnifiedSearch')} testID="home-open-unified-search" style={({ pressed }) => [ styles.searchEntry, { borderColor: palette.border.subtle }, pressed && { backgroundColor: palette.bg.cardHover }, ]} > {t('unifiedSearch.title')} {t('unifiedSearch.homeHint')} {t('mobile.home.recordHint')} {stats !== null ? ( {buildTodaySummary(stats, t)} ) : loading ? ( {t('mobile.home.loading')} ) : statsError ? ( {t('mobile.home.loadError')} void refresh(false)} testID="home-retry" /> ) : null} navigation.navigate('Records')} testID="home-see-all-records" /> {stats !== null && recentRecords.length === 0 ? ( {t('mobile.home.noRecords')} ) : recentRecords.map((entry) => { const createdAt = Date.parse(entry.createdAt) const title = entry.title?.trim() || entry.text.trim() return ( navigation.navigate('HistoryDetail', { historyId: entry.id })} testID={`home-record-${entry.id}`} /> ) })} navigation.navigate('Meetings')} testID="home-see-all-meetings" /> {meetingsError && meetings === null ? ( {t('mobile.home.meetingsLoadError')} ) : meetings !== null && recentMeetings.length === 0 ? ( {t('mobile.home.noMeetings')} ) : recentMeetings.map((meeting) => { const startedAt = Date.parse(meeting.started_at) return ( navigation.navigate('MeetingDetail', { meetingId: meeting.id })} testID={`home-meeting-${meeting.id}`} /> ) })} {entitlementSnapshot.tier === 'free' && ( navigation.navigate('ProPaywall')} testID="home-open-plans" style={({ pressed }) => [ styles.planLine, { borderTopColor: palette.border.subtle }, pressed && { backgroundColor: palette.bg.cardHover }, ]} > {t('mobile.home.freePlan')} )} ) } function SectionHeader({ title, actionLabel, actionAccessibilityLabel, onAction, testID, }: { title: string actionLabel: string actionAccessibilityLabel: string onAction: () => void testID: string }): React.ReactElement { const { palette } = useMobilePreferences() return ( {title} [stylesStatic.sectionAction, pressed && { opacity: 0.6 }]} > {actionLabel} ) } function ListRow({ title, meta, onPress, testID, }: { title: string meta: string onPress: () => void testID: string }): React.ReactElement { const { palette } = useMobilePreferences() return ( [ stylesStatic.row, { borderBottomColor: palette.border.subtle }, pressed && { backgroundColor: palette.bg.cardHover }, ]} > {title} {meta} ) } 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, }, }) }