d3ro-voice/apps/mobile/app/(tabs)/record.tsx
Yun Chan 660e622a93 refactor(ui-native): d3roNativePalette amber->main 개명 (WS-NATIVE)
- packages/ui-native theme.ts accent: amber->main, amberDim->dim, amberGlow->glow (값 보존)
- apps/mobile 20건 + apps/mobile-rn 18건 + ui-native 컴포넌트 9건 = 47 참조 치환
SKIP: Led/PhosphorText/Header color prop 'amber'(의미론적 컴포넌트 API, 별도 마이그레이션)
       green/greenGlow 키(amber계 범위外)
정책: docs/REFACTOR_POLICY.md DP1, 이식 인사이트 P7
2026-07-22 02:37:45 +09:00

287 lines
8.2 KiB
TypeScript

// apps/mobile/app/(tabs)/record.tsx
// Recording tab — expo-av + STT pipeline
// Design ref: docs/v3/designs/recording.html
import { useState, useRef } from 'react'
import { View, StyleSheet, ActivityIndicator, ScrollView } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { Audio } from 'expo-av'
import Constants from 'expo-constants'
import {
MetalCard,
PhosphorText,
PhysicalButton,
Led,
Header,
WaveBars,
AppStatusBar,
d3roNativePalette,
d3roNativeFonts
} from '@d3ro/ui-native'
import { useI18n } from '@d3ro/i18n'
import { supabase, isSupabaseConfigured } from '../../lib/supabase'
type RecordingState = 'idle' | 'recording' | 'processing' | 'done' | 'error'
export default function RecordScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
const { t } = useI18n()
const [state, setState] = useState<RecordingState>('idle')
const [transcript, setTranscript] = useState<string>('')
const [error, setError] = useState<string | null>(null)
const [duration, setDuration] = useState(0)
const recordingRef = useRef<Audio.Recording | null>(null)
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
async function startRecording(): Promise<void> {
setError(null)
setTranscript('')
setDuration(0)
try {
const perm = await Audio.requestPermissionsAsync()
if (perm.status !== 'granted') {
setError(t('mobile.rec.micDenied'))
setState('error')
return
}
await Audio.setAudioModeAsync({
allowsRecordingIOS: true,
playsInSilentModeIOS: true
})
const recording = new Audio.Recording()
await recording.prepareToRecordAsync(Audio.RecordingOptionsPresets.HIGH_QUALITY)
await recording.startAsync()
recordingRef.current = recording
setState('recording')
timerRef.current = setInterval(() => {
setDuration((d) => d + 1)
}, 1000)
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to start')
setState('error')
}
}
async function stopRecording(): Promise<void> {
if (!recordingRef.current) return
if (timerRef.current) {
clearInterval(timerRef.current)
timerRef.current = null
}
setState('processing')
try {
await recordingRef.current.stopAndUnloadAsync()
const uri = recordingRef.current.getURI()
recordingRef.current = null
if (!uri) throw new Error('No recording URI')
if (!isSupabaseConfigured()) {
setError(t('mobile.rec.supabaseNotConfigured'))
setState('error')
return
}
const { data: { session } } = await supabase.auth.getSession()
if (!session) {
setError(t('mobile.rec.loginRequired'))
setState('error')
return
}
const formData = new FormData()
formData.append('audio', {
uri,
name: 'recording.m4a',
type: 'audio/m4a'
} as unknown as Blob)
formData.append('language_code', 'ko-KR')
const url = (Constants.expoConfig?.extra?.supabaseUrl as string) ?? ''
const response = await fetch(`${url}/functions/v1/stt-proxy`, {
method: 'POST',
headers: { Authorization: `Bearer ${session.access_token}` },
body: formData
})
if (!response.ok) throw new Error(`STT failed: ${response.status}`)
const result = (await response.json()) as { transcript: string }
setTranscript(result.transcript)
setState('done')
} catch (e) {
setError(e instanceof Error ? e.message : 'Unknown error')
setState('error')
}
}
async function cancelRecording(): Promise<void> {
if (timerRef.current) {
clearInterval(timerRef.current)
timerRef.current = null
}
if (recordingRef.current) {
try { await recordingRef.current.stopAndUnloadAsync() } catch { /* ignore */ }
recordingRef.current = null
}
setState('idle')
setTranscript('')
setError(null)
setDuration(0)
}
const formatTime = (s: number): string => {
const m = Math.floor(s / 60)
const sec = s % 60
return `${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`
}
const statusLabel =
state === 'recording' ? t('mobile.rec.recording')
: state === 'processing' ? t('mobile.rec.processing')
: state === 'done' ? t('mobile.rec.done')
: state === 'error' ? t('mobile.rec.error')
: t('mobile.rec.ready')
return (
<ScrollView style={styles.container} contentContainerStyle={styles.content}>
<Header
title={state === 'recording' ? t('mobile.rec.session') : t('mobile.rec.title')}
paddingTop={insets.top}
rightContent={
state === 'recording' ? (
<View style={styles.headerRight}>
<PhosphorText variant="label" color="amber">
{formatTime(duration)}
</PhosphorText>
<Led color="green" size={6} />
</View>
) : undefined
}
/>
{/* Wave Bars */}
<WaveBars active={state === 'recording'} />
{/* Transcript Area */}
<View style={styles.transcriptArea}>
{state === 'idle' && (
<PhosphorText
variant="small"
color="muted"
style={styles.initLog}
>
{t('mobile.rec.initLog')}
</PhosphorText>
)}
{state === 'processing' && (
<ActivityIndicator size="large" color={d3roNativePalette.accent.main} />
)}
{transcript !== '' && state === 'done' && (
<View style={styles.transcriptBox}>
<PhosphorText variant="body" color="primary">
{transcript}
</PhosphorText>
</View>
)}
{error !== null && (
<View style={styles.errorBox}>
<PhosphorText variant="small" color="label">
{error}
</PhosphorText>
</View>
)}
</View>
{/* Status Line */}
{state === 'recording' && (
<View style={styles.listeningRow}>
<Led color="amber" size={6} />
<PhosphorText variant="label" color="amber" style={styles.listeningText}>
{t('mobile.rec.listening')}
</PhosphorText>
<PhosphorText variant="label" color="muted">
{t('mobile.rec.realtime')}
</PhosphorText>
</View>
)}
{/* Buttons */}
<View style={styles.buttons}>
{(state === 'idle' || state === 'done' || state === 'error') && (
<PhysicalButton
label={state === 'done' ? t('mobile.rec.newRecording') : t('mobile.rec.start')}
variant="primary"
onPress={() => void startRecording()}
/>
)}
{state === 'recording' && (
<>
<PhysicalButton
label={t('mobile.rec.stop')}
variant="danger"
onPress={() => void stopRecording()}
/>
<View style={styles.buttonSpacer} />
<PhysicalButton
label={t('mobile.rec.cancel')}
variant="secondary"
onPress={() => void cancelRecording()}
/>
</>
)}
</View>
<AppStatusBar />
</ScrollView>
)
}
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: d3roNativePalette.bg.app },
content: { paddingBottom: 100 },
headerRight: { flexDirection: 'row', alignItems: 'center', gap: 8 },
transcriptArea: {
minHeight: 160,
justifyContent: 'center',
alignItems: 'center',
paddingHorizontal: 20,
paddingVertical: 24
},
initLog: {
fontFamily: d3roNativeFonts.mono,
textAlign: 'center'
},
transcriptBox: {
backgroundColor: d3roNativePalette.bg.inset,
padding: 12,
borderRadius: 8,
width: '100%'
},
errorBox: {
borderWidth: 1,
borderColor: d3roNativePalette.accent.main,
backgroundColor: d3roNativePalette.accent.dim,
padding: 10,
borderRadius: 6,
width: '100%'
},
listeningRow: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: 8,
paddingBottom: 16
},
listeningText: { letterSpacing: 2 },
buttons: { paddingHorizontal: 20, paddingBottom: 16 },
buttonSpacer: { height: 12 }
})