chahinebrini 8f2b93f881 feat(profile): Avatar + Nickname edit-flow
User-Wunsch: auf Profile Avatar + Nickname ändern können. Avatar entweder
preset aus signup-list ODER eigene Foto mit cropper.

New files:
- app/profile/edit.tsx — vollständiger Edit-Screen (Avatar-Gallery + Photo-Picker
  + Nickname TextInput + Save-Button)
- lib/avatars.ts — HERO_AVATARS preset-list (matched mit Nuxt-app Signup) +
  getAvatarUrl helper
- lib/resolveAvatar.ts — resolveAvatar(avatarId, nickname): URL für
  preset-id ODER fallback auf nickname-initial-tile

Profile-Page wiring:
- Avatar-Tap + Nickname-Tap pushen jetzt zu /profile/edit (statt Alert-stub)
- Nach successful save: useMe.reload() + router.back()

Edit-Flow:
- Preset (HERO_AVATARS, 12 items): tap-grid mit selected-State + brand-Border
- Eigenes Photo: expo-image-picker mit allowsEditing+aspect[1,1] (OS-nativer
  Crop-Dialog), expo-file-system/legacy für base64-Konvertierung, upload via
  POST /api/avatar/upload (writes Supabase-Storage rebreak-avatars + updated
  Profile)
- Save: PATCH /api/auth/me { nickname, avatar }

i18n: profile.edit_* keys DE+EN

Backend-API:
- PATCH /api/auth/me — existiert (apps/admin/composables nicht — backend!)
- POST /api/avatar/upload — existiert

TS-fixes:
- expo-file-system → /legacy import (SDK 54 breaking change, siehe Task #14)
- ?? + || mixing fixed mit klammern

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 22:15:13 +02:00

319 lines
9.5 KiB
TypeScript

import { useState } from 'react';
import {
View,
Text,
TextInput,
Pressable,
ScrollView,
Image,
ActivityIndicator,
KeyboardAvoidingView,
Platform,
Alert,
} from 'react-native';
import { useRouter } from 'expo-router';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
// TODO(sdk54): migrate to new expo-file-system class-based API — see Task #14
import * as FileSystem from 'expo-file-system/legacy';
import { useTranslation } from 'react-i18next';
import { colors } from '../../lib/theme';
import { HERO_AVATARS, getAvatarUrl } from '../../lib/avatars';
import { resolveAvatar } from '../../lib/resolveAvatar';
import { apiFetch } from '../../lib/api';
import { useMe } from '../../hooks/useMe';
const INPUT_STYLE = {
fontSize: 16,
lineHeight: 22,
paddingVertical: 14,
paddingHorizontal: 16,
color: colors.text,
fontFamily: 'Nunito_400Regular',
backgroundColor: '#f5f5f5',
borderRadius: 12,
} as const;
export default function ProfileEditScreen() {
const router = useRouter();
const insets = useSafeAreaInsets();
const { t } = useTranslation();
const { me, reload } = useMe();
const [nickname, setNickname] = useState(me?.nickname ?? '');
const [avatarId, setAvatarId] = useState<string | null>(me?.avatar ?? null);
const [photoUri, setPhotoUri] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const displayAvatar = photoUri ?? avatarId;
async function pickPhoto() {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
Alert.alert(
t('profile.edit_photo_perm_title'),
t('profile.edit_photo_perm_desc'),
);
return;
}
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'],
allowsEditing: true,
aspect: [1, 1],
quality: 0.7,
});
if (result.canceled || !result.assets[0]) return;
const uri = result.assets[0].uri;
setPhotoUri(uri);
setAvatarId(null);
}
async function save() {
if (!nickname.trim()) return;
setSaving(true);
try {
let finalAvatar: string | null = avatarId;
if (photoUri) {
setUploading(true);
const base64 = await FileSystem.readAsStringAsync(photoUri, {
encoding: FileSystem.EncodingType.Base64,
});
const ext = photoUri.toLowerCase().endsWith('.png') ? 'png' : 'jpeg';
const dataUrl = `data:image/${ext};base64,${base64}`;
const res = await apiFetch<{ url: string }>('/api/avatar/upload', {
method: 'POST',
body: { dataUrl },
});
finalAvatar = res.url;
setUploading(false);
}
await apiFetch('/api/auth/me', {
method: 'PATCH',
body: {
nickname: nickname.trim(),
...(finalAvatar !== me?.avatar ? { avatar: finalAvatar } : {}),
},
});
reload();
router.back();
} catch {
setUploading(false);
Alert.alert(t('common.error'), t('common.unknown_error'));
} finally {
setSaving(false);
}
}
const resolvedPreview = photoUri
? photoUri
: resolveAvatar(avatarId, nickname || (me?.nickname ?? ''));
const hasChanges =
nickname.trim() !== (me?.nickname ?? '') ||
photoUri !== null ||
avatarId !== me?.avatar;
return (
<KeyboardAvoidingView
style={{ flex: 1, backgroundColor: colors.bg }}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
paddingTop: insets.top + 8,
paddingBottom: 12,
paddingHorizontal: 16,
borderBottomWidth: 1,
borderBottomColor: colors.border,
backgroundColor: colors.bg,
}}
>
<Pressable
onPress={() => router.back()}
hitSlop={10}
style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1, marginRight: 12 })}
>
<Ionicons name="chevron-back" size={24} color={colors.text} />
</Pressable>
<Text style={{ flex: 1, fontSize: 17, color: colors.text, fontFamily: 'Nunito_700Bold' }}>
{t('profile.edit_title')}
</Text>
<Pressable
onPress={save}
disabled={saving || !hasChanges || !nickname.trim()}
style={({ pressed }) => ({
opacity: pressed || saving || !hasChanges || !nickname.trim() ? 0.4 : 1,
})}
>
{saving ? (
<ActivityIndicator size="small" color={colors.brandOrange} />
) : (
<Text
style={{
fontSize: 16,
color: colors.brandOrange,
fontFamily: 'Nunito_700Bold',
}}
>
{t('profile.edit_save')}
</Text>
)}
</Pressable>
</View>
<ScrollView
contentContainerStyle={{ paddingBottom: insets.bottom + 32 }}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
{/* Avatar preview + pick-photo button */}
<View style={{ alignItems: 'center', paddingTop: 32, paddingBottom: 24 }}>
<View style={{ position: 'relative' }}>
<Image
source={{ uri: resolvedPreview }}
style={{
width: 96,
height: 96,
borderRadius: 48,
backgroundColor: '#e5e5e5',
borderWidth: 2,
borderColor: colors.border,
}}
/>
{uploading ? (
<View
style={{
position: 'absolute',
inset: 0,
borderRadius: 48,
backgroundColor: 'rgba(0,0,0,0.45)',
alignItems: 'center',
justifyContent: 'center',
}}
>
<ActivityIndicator color="#fff" size="small" />
</View>
) : null}
</View>
<Pressable
onPress={pickPhoto}
style={({ pressed }) => ({
marginTop: 12,
flexDirection: 'row',
alignItems: 'center',
gap: 6,
opacity: pressed ? 0.5 : 1,
})}
>
<Ionicons name="camera-outline" size={18} color={colors.brandOrange} />
<Text
style={{
fontSize: 14,
color: colors.brandOrange,
fontFamily: 'Nunito_600SemiBold',
}}
>
{t('profile.edit_photo_cta')}
</Text>
</Pressable>
</View>
{/* Preset avatars */}
<View style={{ paddingHorizontal: 16, marginBottom: 24 }}>
<Text
style={{
fontSize: 12,
color: colors.textMuted,
fontFamily: 'Nunito_700Bold',
letterSpacing: 0.8,
marginBottom: 12,
}}
>
{t('profile.edit_preset_label').toUpperCase()}
</Text>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 10 }}>
{HERO_AVATARS.map((avatar) => {
const isSelected = !photoUri && avatarId === avatar.id;
return (
<Pressable
key={avatar.id}
onPress={() => {
setAvatarId(avatar.id);
setPhotoUri(null);
}}
style={({ pressed }) => ({
opacity: pressed ? 0.7 : 1,
})}
>
<Image
source={{ uri: getAvatarUrl(avatar.id) }}
style={{
width: 56,
height: 56,
borderRadius: 28,
borderWidth: isSelected ? 3 : 1.5,
borderColor: isSelected ? colors.brandOrange : colors.border,
opacity: isSelected ? 1 : 0.55,
}}
/>
</Pressable>
);
})}
</View>
</View>
{/* Divider */}
<View style={{ height: 1, backgroundColor: colors.border, marginHorizontal: 16, marginBottom: 24 }} />
{/* Nickname */}
<View style={{ paddingHorizontal: 16 }}>
<Text
style={{
fontSize: 12,
color: colors.textMuted,
fontFamily: 'Nunito_700Bold',
letterSpacing: 0.8,
marginBottom: 8,
}}
>
{t('profile.edit_nickname_label').toUpperCase()}
</Text>
<TextInput
style={INPUT_STYLE}
value={nickname}
onChangeText={setNickname}
placeholder={t('auth.nicknamePlaceholder')}
placeholderTextColor="#a3a3a3"
autoCapitalize="none"
autoCorrect={false}
maxLength={32}
returnKeyType="done"
/>
<Text
style={{
marginTop: 6,
fontSize: 12,
color: colors.textMuted,
fontFamily: 'Nunito_400Regular',
}}
>
{t('profile.edit_nickname_hint')}
</Text>
</View>
</ScrollView>
</KeyboardAvoidingView>
);
}