feat(release): prepare 1.1.0 candidate

This commit is contained in:
Yun Chan 2026-08-29 18:33:45 +09:00
parent 5a34f66981
commit 5205dcdfa9
736 changed files with 115667 additions and 12203 deletions

View file

@ -0,0 +1,698 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import {
ActivityIndicator,
Alert,
Pressable,
ScrollView,
Share,
StyleSheet,
TextInput,
View,
} from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useSoundWithStates } from 'react-native-nitro-sound'
import {
MetalCard,
NativeThemeProvider,
PhosphorText,
PhysicalButton,
} from '@d3ro/ui-native'
import { useI18n } from '@d3ro/i18n'
import type { AudioFile, HistoryEntry } from '@d3ro/api-client'
import { useAuth } from '../lib/auth-context'
import {
createAudioPlaybackUrl,
deleteHistoryRevisionSafe,
getHistoryDetail,
HistoryServiceError,
updateHistoryRevisionSafe,
type HistoryDetail,
} from '../features/history/history-service'
import { loadHistoryCache } from '../features/history/history-cache'
import { useMobilePreferences } from '../lib/preferences-context'
interface HistoryDetailScreenProps {
route: { params: { historyId: string } }
navigation: { goBack: () => void }
}
export default function HistoryDetailScreen({
route,
navigation,
}: HistoryDetailScreenProps): React.ReactElement {
const insets = useSafeAreaInsets()
const { user } = useAuth()
const { t, formatDate } = useI18n()
const { palette } = useMobilePreferences()
const styles = useMemo(() => createStyles(palette), [palette])
const player = useSoundWithStates()
const [detail, setDetail] = useState<HistoryDetail | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [offline, setOffline] = useState(false)
const [editing, setEditing] = useState(false)
const [title, setTitle] = useState('')
const [originalText, setOriginalText] = useState('')
const [polishedText, setPolishedText] = useState('')
const [saving, setSaving] = useState(false)
const [conflict, setConflict] = useState(false)
const [deleting, setDeleting] = useState(false)
const [activeAudioId, setActiveAudioId] = useState<string | null>(null)
const [paused, setPaused] = useState(false)
const [audioBusy, setAudioBusy] = useState(false)
const applyEntry = useCallback((entry: HistoryEntry): void => {
setTitle(entry.title ?? '')
setOriginalText(entry.original_text)
setPolishedText(entry.polished_text ?? '')
}, [])
const load = useCallback(async (): Promise<void> => {
if (user === null) {
setError(t('mobile.account.loginRequired'))
setLoading(false)
return
}
setLoading(true)
setError(null)
try {
const nextDetail = await getHistoryDetail(user.id, route.params.historyId)
setDetail(nextDetail)
applyEntry(nextDetail.entry)
setOffline(false)
setConflict(false)
} catch (requestError) {
if (requestError instanceof HistoryServiceError && requestError.code === 'network') {
try {
const cached = await loadHistoryCache(user.id)
const entry = cached?.entries.find((item) => item.id === route.params.historyId)
if (entry !== undefined) {
setDetail({ entry, audioFiles: [], jobs: [] })
applyEntry(entry)
setOffline(true)
return
}
} catch {
// The request error below remains authoritative when secure cache access fails.
}
}
setError(
requestError instanceof HistoryServiceError && requestError.code === 'not-found'
? t('mobile.hist.notFound')
: t('mobile.hist.loadError'),
)
} finally {
setLoading(false)
}
}, [applyEntry, route.params.historyId, t, user])
useEffect(() => {
void load()
}, [load])
const cancelEdit = (): void => {
if (detail !== null) applyEntry(detail.entry)
setEditing(false)
setConflict(false)
setError(null)
}
const save = async (): Promise<void> => {
if (user === null || detail === null || saving) return
const normalizedTitle = title.trim()
const normalizedOriginal = originalText.trim()
const normalizedPolished = polishedText.trim()
if (normalizedTitle.length > 160) {
setError(t('mobile.hist.validationTitle'))
return
}
if (normalizedOriginal.length === 0) {
setError(t('mobile.hist.validationOriginal'))
return
}
const patch: {
title?: string | null
original_text?: string
polished_text?: string | null
} = {}
if ((detail.entry.title ?? '') !== normalizedTitle) patch.title = normalizedTitle || null
if (detail.entry.original_text !== normalizedOriginal) patch.original_text = normalizedOriginal
if ((detail.entry.polished_text ?? '') !== normalizedPolished) {
patch.polished_text = normalizedPolished || null
}
if (Object.keys(patch).length === 0) {
setEditing(false)
return
}
setSaving(true)
setError(null)
try {
const updated = await updateHistoryRevisionSafe(
user.id,
detail.entry.id,
detail.entry.revision,
patch,
)
setDetail((current) => current === null ? null : { ...current, entry: updated })
applyEntry(updated)
setEditing(false)
setConflict(false)
} catch (requestError) {
if (requestError instanceof HistoryServiceError && requestError.code === 'conflict') {
setConflict(true)
setError(t('mobile.hist.conflict'))
} else {
setError(t('mobile.hist.editFailed'))
}
} finally {
setSaving(false)
}
}
const toggleFavorite = async (): Promise<void> => {
if (user === null || detail === null || saving) return
const previous = detail.entry
const optimistic = { ...previous, is_favorite: !previous.is_favorite }
setDetail((current) => current === null ? null : { ...current, entry: optimistic })
setSaving(true)
try {
const updated = await updateHistoryRevisionSafe(
user.id,
previous.id,
previous.revision,
{ is_favorite: optimistic.is_favorite },
)
setDetail((current) => current === null ? null : { ...current, entry: updated })
} catch {
setDetail((current) => current === null ? null : { ...current, entry: previous })
setError(t('mobile.hist.favoriteFailed'))
} finally {
setSaving(false)
}
}
const confirmDelete = (): void => {
if (detail === null || deleting) return
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 deleteEntry() },
},
],
)
}
const deleteEntry = async (): Promise<void> => {
if (user === null || detail === null || deleting) return
setDeleting(true)
setError(null)
try {
await deleteHistoryRevisionSafe(user.id, detail.entry.id, detail.entry.revision)
navigation.goBack()
} catch {
setError(t('mobile.hist.deleteFailed'))
setDeleting(false)
}
}
const shareTranscript = async (): Promise<void> => {
if (detail === null) return
const content = detail.entry.polished_text ?? detail.entry.original_text
const summary = detail.entry.summary_text?.trim()
const message = [detail.entry.title, content, summary].filter(Boolean).join('\n\n')
try {
await Share.share({
title: detail.entry.title ?? t('mobile.hist.detailTitle'),
message,
})
} catch {
setError(t('mobile.hist.shareFailed'))
}
}
const controlAudio = async (audioFile: AudioFile): Promise<void> => {
if (user === null || audioBusy) return
setAudioBusy(true)
setError(null)
try {
if (activeAudioId === audioFile.id && player.state.isPlaying) {
await player.pausePlayer()
setPaused(true)
return
}
if (activeAudioId === audioFile.id && paused) {
await player.resumePlayer()
setPaused(false)
return
}
if (activeAudioId !== null) await player.stopPlayer()
const signedUrl = await createAudioPlaybackUrl(user.id, audioFile)
await player.startPlayer(signedUrl)
setActiveAudioId(audioFile.id)
setPaused(false)
} catch {
setActiveAudioId(null)
setPaused(false)
setError(t('mobile.hist.audioError'))
} finally {
setAudioBusy(false)
}
}
const stopAudio = async (): Promise<void> => {
setAudioBusy(true)
try {
await player.stopPlayer()
setActiveAudioId(null)
setPaused(false)
} catch {
setError(t('mobile.hist.audioError'))
} finally {
setAudioBusy(false)
}
}
return (
<NativeThemeProvider palette={palette}>
<View style={styles.container}>
<View style={[styles.header, { paddingTop: insets.top + 8 }]}>
<Pressable
accessibilityRole="button"
accessibilityLabel={t('mobile.hist.back')}
onPress={navigation.goBack}
style={styles.headerButton}
testID="history-detail-back"
>
<PhosphorText variant="label" color="amber">‹ {t('mobile.hist.back')}</PhosphorText>
</Pressable>
<PhosphorText
variant="label"
color="muted"
style={styles.headerTitle}
accessibilityRole="header"
>
{t('mobile.hist.detailTitle').toUpperCase()}
</PhosphorText>
<View style={styles.headerSpacer} />
</View>
{loading ? (
<View accessibilityLiveRegion="polite" style={styles.center} testID="history-detail-loading">
<ActivityIndicator size="large" color={palette.accent.main} />
<PhosphorText color="muted" style={styles.loadingText}>
{t('mobile.hist.detailLoading')}
</PhosphorText>
</View>
) : detail === null ? (
<View style={styles.center} testID="history-detail-error">
<PhosphorText color="primary" style={styles.centerText}>
{error ?? t('mobile.hist.notFound')}
</PhosphorText>
<PhysicalButton label={t('mobile.hist.retry')} onPress={() => { void load() }} />
</View>
) : (
<ScrollView
contentContainerStyle={[styles.content, { paddingBottom: insets.bottom + 40 }]}
keyboardShouldPersistTaps="handled"
>
{offline && (
<View
accessibilityRole="alert"
accessibilityLiveRegion="polite"
style={styles.offlineBanner}
testID="history-detail-offline"
>
<PhosphorText variant="small" color="amber">{t('mobile.hist.offline')}</PhosphorText>
</View>
)}
{error !== null && (
<View
accessibilityRole="alert"
accessibilityLiveRegion="assertive"
style={styles.errorBanner}
testID="history-detail-message"
>
<PhosphorText variant="small" color="primary">{error}</PhosphorText>
{conflict && (
<Pressable
accessibilityRole="button"
accessibilityLabel={t('mobile.hist.reloadLatest')}
onPress={() => { void load() }}
style={styles.inlineButton}
>
<PhosphorText variant="small" color="amber">
{t('mobile.hist.reloadLatest')}
</PhosphorText>
</Pressable>
)}
</View>
)}
<MetalCard style={styles.primaryCard}>
<View style={styles.actionRow}>
<Pressable
accessibilityRole="button"
accessibilityLabel={detail.entry.is_favorite
? t('mobile.hist.unfavorite')
: t('mobile.hist.favorite')}
disabled={saving || offline}
onPress={() => { void toggleFavorite() }}
style={styles.compactButton}
testID="history-detail-favorite"
>
<PhosphorText color="amber">
{detail.entry.is_favorite ? '★' : '☆'}
</PhosphorText>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel={t('mobile.hist.edit')}
disabled={editing}
onPress={() => setEditing(true)}
style={styles.compactButton}
testID="history-detail-edit"
>
<PhosphorText variant="small" color="primary">{t('mobile.hist.edit')}</PhosphorText>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel={t('mobile.hist.share')}
onPress={() => { void shareTranscript() }}
style={styles.compactButton}
testID="history-detail-share"
>
<PhosphorText variant="small" color="primary">{t('mobile.hist.share')}</PhosphorText>
</Pressable>
</View>
<FieldLabel label={t('mobile.hist.titleLabel')} />
{editing ? (
<TextInput
accessibilityLabel={t('mobile.hist.titleLabel')}
value={title}
onChangeText={setTitle}
maxLength={161}
placeholderTextColor={palette.text.muted}
style={styles.input}
testID="history-detail-title-input"
/>
) : (
<PhosphorText color="primary" style={styles.fieldValue}>
{detail.entry.title ?? '—'}
</PhosphorText>
)}
<FieldLabel label={t('mobile.hist.originalLabel')} />
{editing ? (
<TextInput
accessibilityLabel={t('mobile.hist.originalLabel')}
value={originalText}
onChangeText={setOriginalText}
multiline
textAlignVertical="top"
style={[styles.input, styles.multiline]}
testID="history-detail-original-input"
/>
) : (
<PhosphorText color="primary" style={styles.transcript} selectable>
{detail.entry.original_text}
</PhosphorText>
)}
<FieldLabel label={t('mobile.hist.polishedLabel')} />
{editing ? (
<TextInput
accessibilityLabel={t('mobile.hist.polishedLabel')}
value={polishedText}
onChangeText={setPolishedText}
multiline
textAlignVertical="top"
style={[styles.input, styles.multiline]}
testID="history-detail-polished-input"
/>
) : (
<PhosphorText color="primary" style={styles.transcript} selectable>
{detail.entry.polished_text ?? '—'}
</PhosphorText>
)}
{editing && (
<View style={styles.editorActions}>
<PhysicalButton
label={t('mobile.hist.cancel')}
variant="secondary"
disabled={saving}
onPress={cancelEdit}
style={styles.flexButton}
/>
<PhysicalButton
label={saving ? t('mobile.hist.saving') : t('mobile.hist.save')}
disabled={saving || offline}
onPress={() => { void save() }}
style={styles.flexButton}
testID="history-detail-save"
/>
</View>
)}
</MetalCard>
{detail.entry.summary_text !== null && (
<Section title={t('mobile.hist.summaryLabel')}>
<PhosphorText color="primary" selectable>{detail.entry.summary_text}</PhosphorText>
</Section>
)}
<Section title={t('mobile.hist.metadata')}>
<MetaRow label={t('mobile.hist.mode')} value={detail.entry.mode} />
<MetaRow label={t('mobile.hist.status')} value={detail.entry.status} />
<MetaRow label={t('mobile.hist.language')} value={detail.entry.detected_language ?? '—'} />
<MetaRow label={t('mobile.hist.duration')} value={formatDuration(detail.entry.duration * 1000)} />
<MetaRow label={t('mobile.hist.model')} value={detail.entry.stt_model ?? '—'} />
<MetaRow
label={t('mobile.hist.created')}
value={formatDate(new Date(detail.entry.created_at), { dateStyle: 'medium', timeStyle: 'short' })}
/>
<MetaRow
label={t('mobile.hist.updated')}
value={formatDate(new Date(detail.entry.updated_at), { dateStyle: 'medium', timeStyle: 'short' })}
/>
<MetaRow label={t('mobile.hist.revision')} value={String(detail.entry.revision)} />
</Section>
<Section title={t('mobile.hist.audio')}>
{detail.audioFiles.length === 0 ? (
<PhosphorText color="muted">{t('mobile.hist.audioNone')}</PhosphorText>
) : detail.audioFiles.map((audioFile) => (
<View key={audioFile.id} style={styles.audioRow} testID={`history-audio-${audioFile.id}`}>
<View style={styles.audioInfo}>
<PhosphorText variant="small" color="primary" numberOfLines={1}>
{audioFile.original_name ?? audioFile.mime_type}
</PhosphorText>
<PhosphorText variant="meta" color="muted">
{formatBytes(audioFile.size_bytes)} · {formatDuration(audioFile.duration_ms ?? 0)}
</PhosphorText>
{audioFile.upload_status !== 'uploaded' && (
<PhosphorText variant="meta" color="amber">
{t('mobile.hist.audioPending', { status: audioFile.upload_status })}
</PhosphorText>
)}
</View>
<Pressable
accessibilityRole="button"
accessibilityLabel={activeAudioId === audioFile.id && player.state.isPlaying
? t('mobile.hist.audioPause')
: activeAudioId === audioFile.id && paused
? t('mobile.hist.audioResume')
: t('mobile.hist.audioPlay')}
disabled={audioBusy || audioFile.upload_status !== 'uploaded' || offline}
onPress={() => { void controlAudio(audioFile) }}
style={styles.compactButton}
>
<PhosphorText variant="small" color="amber">
{activeAudioId === audioFile.id && player.state.isPlaying
? t('mobile.hist.audioPause')
: activeAudioId === audioFile.id && paused
? t('mobile.hist.audioResume')
: t('mobile.hist.audioPlay')}
</PhosphorText>
</Pressable>
</View>
))}
{activeAudioId !== null && (
<View style={styles.playbackRow}>
<PhosphorText variant="meta" color="muted">
{formatDuration(player.state.playback.position)} / {formatDuration(player.state.playback.duration)}
</PhosphorText>
<Pressable
accessibilityRole="button"
accessibilityLabel={t('mobile.hist.audioStop')}
onPress={() => { void stopAudio() }}
disabled={audioBusy}
style={styles.playbackButton}
>
<PhosphorText variant="small" color="amber">{t('mobile.hist.audioStop')}</PhosphorText>
</Pressable>
</View>
)}
</Section>
<Section title={t('mobile.hist.jobs')}>
{detail.jobs.length === 0 ? (
<PhosphorText color="muted">{t('mobile.hist.jobsNone')}</PhosphorText>
) : detail.jobs.map((job) => (
<MetaRow
key={job.id}
label={job.kind}
value={`${job.status} · ${job.progress}%`}
/>
))}
</Section>
<PhysicalButton
label={deleting ? t('mobile.hist.saving') : t('mobile.hist.delete')}
variant="danger"
disabled={deleting || offline}
onPress={confirmDelete}
testID="history-detail-delete"
/>
</ScrollView>
)}
</View>
</NativeThemeProvider>
)
}
function FieldLabel({ label }: { label: string }): React.ReactElement {
const styles = useHistoryDetailStyles()
return <PhosphorText variant="label" color="muted" style={styles.fieldLabel}>{label}</PhosphorText>
}
function Section({ title, children }: { title: string; children: React.ReactNode }): React.ReactElement {
const styles = useHistoryDetailStyles()
return (
<MetalCard style={styles.section}>
<PhosphorText variant="label" color="muted" style={styles.sectionTitle}>{title}</PhosphorText>
{children}
</MetalCard>
)
}
function MetaRow({ label, value }: { label: string; value: string }): React.ReactElement {
const styles = useHistoryDetailStyles()
return (
<View style={styles.metaRow}>
<PhosphorText variant="small" color="muted" style={styles.metaLabel}>{label}</PhosphorText>
<PhosphorText variant="small" color="primary" style={styles.metaValue} selectable>{value}</PhosphorText>
</View>
)
}
export function formatDuration(durationMs: number): string {
const totalSeconds = Math.max(0, Math.floor(durationMs / 1000))
const minutes = Math.floor(totalSeconds / 60)
const seconds = totalSeconds % 60
return `${minutes}:${String(seconds).padStart(2, '0')}`
}
export function formatBytes(bytes: number): string {
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
if (bytes < 1024) return `${Math.round(bytes)} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
type Palette = ReturnType<typeof useMobilePreferences>['palette']
function useHistoryDetailStyles(): ReturnType<typeof createStyles> {
const { palette } = useMobilePreferences()
return useMemo(() => createStyles(palette), [palette])
}
function createStyles(palette: Palette) {
return StyleSheet.create({
container: { flex: 1, backgroundColor: palette.bg.app },
header: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingHorizontal: 16,
paddingBottom: 12,
borderBottomWidth: 1,
borderBottomColor: palette.border.subtle,
},
headerButton: { minWidth: 80, minHeight: 48, justifyContent: 'center' },
headerTitle: { letterSpacing: 2 },
headerSpacer: { width: 80 },
center: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 18, padding: 32 },
centerText: { textAlign: 'center' },
loadingText: { marginTop: 12 },
content: { padding: 20, gap: 14 },
offlineBanner: {
padding: 12,
borderRadius: 8,
backgroundColor: palette.accent.dim,
},
errorBanner: {
padding: 12,
gap: 10,
borderRadius: 8,
borderWidth: 1,
borderColor: palette.tag.red,
backgroundColor: palette.bg.card,
},
inlineButton: { minHeight: 48, justifyContent: 'center' },
primaryCard: { gap: 8 },
actionRow: { flexDirection: 'row', justifyContent: 'flex-end', gap: 8, marginBottom: 4 },
compactButton: {
minWidth: 48,
minHeight: 48,
paddingHorizontal: 12,
alignItems: 'center',
justifyContent: 'center',
borderWidth: 1,
borderColor: palette.border.default,
borderRadius: 8,
},
fieldLabel: { marginTop: 12, marginBottom: 4 },
fieldValue: { minHeight: 30 },
transcript: { lineHeight: 23 },
input: {
minHeight: 48,
paddingHorizontal: 12,
paddingVertical: 10,
borderWidth: 1,
borderColor: palette.border.strong,
borderRadius: 8,
backgroundColor: palette.bg.inset,
color: palette.text.primary,
fontSize: 14,
},
multiline: { minHeight: 140 },
editorActions: { flexDirection: 'row', gap: 10, marginTop: 12 },
flexButton: { flex: 1 },
section: { gap: 8 },
sectionTitle: { letterSpacing: 2, marginBottom: 8 },
metaRow: {
flexDirection: 'row',
justifyContent: 'space-between',
gap: 16,
paddingVertical: 6,
borderBottomWidth: 1,
borderBottomColor: palette.border.subtle,
},
metaLabel: { flex: 1 },
metaValue: { flex: 2, textAlign: 'right' },
audioRow: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 6 },
audioInfo: { flex: 1, gap: 3 },
playbackRow: { flexDirection: 'row', justifyContent: 'space-between', paddingTop: 8 },
playbackButton: { minWidth: 48, minHeight: 48, alignItems: 'center', justifyContent: 'center' },
})
}