Initial commit for Greenlens

This commit is contained in:
Timo Knuth
2026-03-16 21:31:46 +01:00
parent 307135671f
commit 05d4f6e78b
573 changed files with 54233 additions and 1891 deletions

View File

@@ -0,0 +1,60 @@
import React, { useState, useEffect } from 'react';
import { StyleSheet } from 'react-native';
import { Video, ResizeMode } from 'expo-av';
import * as SplashScreen from 'expo-splash-screen';
import Animated, { FadeOut } from 'react-native-reanimated';
import { useApp } from '../context/AppContext';
import { useColors } from '../constants/Colors';
interface Props {
isAppReady: boolean;
onAnimationComplete: () => void;
}
export function AnimatedSplashScreen({ isAppReady, onAnimationComplete }: Props) {
const [hasPlayedEnough, setHasPlayedEnough] = useState(false);
useEffect(() => {
// Ensure the video plays for at least 2 seconds before we allow it to finish,
// so it doesn't flash too fast and provides a premium feel.
const timer = setTimeout(() => {
setHasPlayedEnough(true);
}, 2000);
return () => clearTimeout(timer);
}, []);
useEffect(() => {
if (isAppReady && hasPlayedEnough) {
onAnimationComplete();
}
}, [isAppReady, hasPlayedEnough, onAnimationComplete]);
// Determine the background color to blend perfectly
const { isDarkMode, colorPalette } = useApp();
const colors = useColors(isDarkMode, colorPalette);
return (
<Animated.View exiting={FadeOut.duration(600)} style={[StyleSheet.absoluteFill, { zIndex: 9999, backgroundColor: colors.background, alignItems: 'center', justifyContent: 'center' }]}>
<Animated.View style={{ width: 220, height: 220, borderRadius: 45, overflow: 'hidden', backgroundColor: colors.surface, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.15, shadowRadius: 15, elevation: 8, transform: [{ scale: 1 }] }}>
<Video
source={require('../assets/Make_some_light_leaf_animations_delpmaspu_.mp4')}
style={{ width: '100%', height: '100%' }}
resizeMode={ResizeMode.COVER}
shouldPlay
isMuted
isLooping
rate={2.0} // Play at 2x speed to make the 8-second video feel punchier as a loading screen
onReadyForDisplay={() => {
// Instantly hide the native static splash screen as soon as the video is painted
SplashScreen.hideAsync().catch(() => { });
}}
onError={(err) => {
console.error("Video loading error:", err);
// Fallback in case the video fails to load for any reason
SplashScreen.hideAsync().catch(() => { });
onAnimationComplete();
}}
/>
</Animated.View>
</Animated.View>
);
}

View File

@@ -0,0 +1,286 @@
import React, { useEffect, useRef } from 'react';
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Dimensions,
Animated,
Platform,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useCoachMarks } from '../context/CoachMarksContext';
import { useApp } from '../context/AppContext';
import { useColors } from '../constants/Colors';
const { width: SCREEN_W, height: SCREEN_H } = Dimensions.get('window');
const HIGHLIGHT_PADDING = 10;
const TOOLTIP_VERTICAL_OFFSET = 32;
export const CoachMarksOverlay: React.FC = () => {
const { isActive, currentStep, steps, layouts, next, skip } = useCoachMarks();
const { isDarkMode, colorPalette } = useApp();
const colors = useColors(isDarkMode, colorPalette);
const fadeAnim = useRef(new Animated.Value(0)).current;
const scaleAnim = useRef(new Animated.Value(0.88)).current;
const pulseAnim = useRef(new Animated.Value(1)).current;
// Fade in when tour starts or step changes
useEffect(() => {
if (isActive) {
fadeAnim.setValue(0);
scaleAnim.setValue(0.88);
Animated.parallel([
Animated.timing(fadeAnim, { toValue: 1, duration: 320, useNativeDriver: true }),
Animated.spring(scaleAnim, { toValue: 1, tension: 80, friction: 9, useNativeDriver: true }),
]).start();
// Pulse animation on highlight
Animated.loop(
Animated.sequence([
Animated.timing(pulseAnim, { toValue: 1.06, duration: 900, useNativeDriver: true }),
Animated.timing(pulseAnim, { toValue: 1, duration: 900, useNativeDriver: true }),
])
).start();
} else {
pulseAnim.stopAnimation();
}
}, [isActive, currentStep]);
if (!isActive || steps.length === 0) return null;
const step = steps[currentStep];
const layout = layouts[step.elementKey];
// Fallback wenn Element noch nicht gemessen
const highlight = layout
? {
x: layout.x - HIGHLIGHT_PADDING,
y: layout.y - HIGHLIGHT_PADDING,
w: layout.width + HIGHLIGHT_PADDING * 2,
h: layout.height + HIGHLIGHT_PADDING * 2,
r: Math.min(layout.width, layout.height) / 2 + HIGHLIGHT_PADDING,
}
: { x: SCREEN_W / 2 - 40, y: SCREEN_H / 2 - 40, w: 80, h: 80, r: 40 };
// Tooltip-Position berechnen
const tooltipW = 260;
const tooltipMaxH = 140;
let tooltipX = Math.max(12, Math.min(SCREEN_W - tooltipW - 12, highlight.x + highlight.w / 2 - tooltipW / 2));
let tooltipY: number;
const spaceBelow = SCREEN_H - (highlight.y + highlight.h);
const spaceAbove = highlight.y;
if (step.tooltipSide === 'above' || (step.tooltipSide !== 'below' && spaceAbove > spaceBelow)) {
tooltipY = highlight.y - tooltipMaxH - 24;
if (tooltipY < 60) tooltipY = highlight.y + highlight.h + 24;
} else {
tooltipY = highlight.y + highlight.h + 24;
if (tooltipY + tooltipMaxH > SCREEN_H - 60) tooltipY = highlight.y - tooltipMaxH - 24;
}
// Keep coachmark bubbles slightly higher to avoid overlap with bright focus circles.
tooltipY -= TOOLTIP_VERTICAL_OFFSET;
const minTooltipY = 24;
const maxTooltipY = SCREEN_H - tooltipMaxH - 24;
tooltipY = Math.max(minTooltipY, Math.min(maxTooltipY, tooltipY));
const arrowPointsUp = tooltipY > highlight.y;
return (
<Animated.View style={[StyleSheet.absoluteFill, styles.root, { opacity: fadeAnim }]} pointerEvents="box-none">
{/* Dark overlay — 4 Rechtecke um die Aussparung */}
{/* Oben */}
<View style={[styles.overlay, { top: 0, left: 0, right: 0, height: Math.max(0, highlight.y) }]} />
{/* Links */}
<View style={[styles.overlay, {
top: highlight.y, left: 0, width: Math.max(0, highlight.x), height: highlight.h,
}]} />
{/* Rechts */}
<View style={[styles.overlay, {
top: highlight.y,
left: highlight.x + highlight.w,
right: 0,
height: highlight.h,
}]} />
{/* Unten */}
<View style={[styles.overlay, {
top: highlight.y + highlight.h,
left: 0,
right: 0,
bottom: 0,
}]} />
{/* Pulsierender Ring um das Highlight */}
<Animated.View
style={[
styles.highlightRing,
{
left: highlight.x - 4,
top: highlight.y - 4,
width: highlight.w + 8,
height: highlight.h + 8,
borderRadius: highlight.r + 4,
borderColor: colors.primary,
transform: [{ scale: pulseAnim }],
},
]}
pointerEvents="none"
/>
{/* Tooltip-Karte */}
<Animated.View
style={[
styles.tooltip,
{
left: tooltipX,
top: tooltipY,
width: tooltipW,
backgroundColor: isDarkMode ? colors.surface : '#ffffff',
borderColor: colors.border,
shadowColor: '#000',
transform: [{ scale: scaleAnim }],
},
]}
>
{/* Arrow */}
<View
style={[
styles.arrow,
arrowPointsUp ? styles.arrowUp : styles.arrowDown,
{
left: Math.max(12, Math.min(tooltipW - 28, highlight.x + highlight.w / 2 - tooltipX - 8)),
borderBottomColor: arrowPointsUp ? (isDarkMode ? colors.surface : '#ffffff') : undefined,
borderTopColor: !arrowPointsUp ? (isDarkMode ? colors.surface : '#ffffff') : undefined,
},
]}
/>
{/* Schritt-Indikator */}
<View style={styles.stepRow}>
{steps.map((_, i) => (
<View
key={i}
style={[
styles.stepDot,
{ backgroundColor: i === currentStep ? colors.primary : colors.border },
i === currentStep && { width: 16 },
]}
/>
))}
</View>
<Text style={[styles.tooltipTitle, { color: colors.text }]}>{step.title}</Text>
<Text style={[styles.tooltipDesc, { color: colors.textSecondary }]}>{step.description}</Text>
<View style={styles.tooltipFooter}>
<TouchableOpacity onPress={skip} style={styles.skipBtn}>
<Text style={[styles.skipText, { color: colors.textMuted }]}>Überspringen</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={next}
style={[styles.nextBtn, { backgroundColor: colors.primary }]}
activeOpacity={0.82}
>
<Text style={[styles.nextText, { color: colors.onPrimary }]}>
{currentStep === steps.length - 1 ? 'Fertig' : 'Weiter'}
</Text>
<Ionicons
name={currentStep === steps.length - 1 ? 'checkmark' : 'arrow-forward'}
size={14}
color={colors.onPrimary}
/>
</TouchableOpacity>
</View>
</Animated.View>
</Animated.View>
);
};
const styles = StyleSheet.create({
root: {
zIndex: 9999,
elevation: 9999,
},
overlay: {
position: 'absolute',
backgroundColor: 'rgba(0,0,0,0.72)',
},
highlightRing: {
position: 'absolute',
borderWidth: 2.5,
},
tooltip: {
position: 'absolute',
borderRadius: 18,
borderWidth: 1,
padding: 16,
gap: 8,
shadowOffset: { width: 0, height: 8 },
shadowOpacity: 0.2,
shadowRadius: 20,
elevation: 12,
},
stepRow: {
flexDirection: 'row',
gap: 4,
alignItems: 'center',
marginBottom: 2,
},
stepDot: {
width: 6,
height: 6,
borderRadius: 3,
},
tooltipTitle: {
fontSize: 15,
fontWeight: '700',
lineHeight: 20,
},
tooltipDesc: {
fontSize: 13,
lineHeight: 18,
},
tooltipFooter: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
marginTop: 4,
},
skipBtn: {
padding: 4,
},
skipText: {
fontSize: 13,
},
nextBtn: {
flexDirection: 'row',
alignItems: 'center',
gap: 6,
paddingHorizontal: 16,
paddingVertical: 9,
borderRadius: 20,
},
nextText: {
fontSize: 13,
fontWeight: '600',
},
arrow: {
position: 'absolute',
width: 0,
height: 0,
borderLeftWidth: 8,
borderRightWidth: 8,
borderLeftColor: 'transparent',
borderRightColor: 'transparent',
},
arrowUp: {
top: -8,
borderBottomWidth: 8,
},
arrowDown: {
bottom: -8,
borderTopWidth: 8,
},
});

View File

@@ -1,59 +1,102 @@
import React from 'react';
import { Plant } from '../types';
import { Droplets } from 'lucide-react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { ColorPalette } from '../types';
import { useColors } from '../constants/Colors';
import { SafeImage } from './SafeImage';
interface PlantCardProps {
plant: Plant;
onClick: () => void;
t: any; // Using any for simplicity with the dynamic translation object
plant: {
name: string;
botanicalName?: string;
imageUri: string;
careInfo: {
waterIntervalDays: number;
};
};
width: number;
onPress: () => void;
t: any;
isDark: boolean;
colorPalette: ColorPalette;
}
export const PlantCard: React.FC<PlantCardProps> = ({ plant, onClick, t }) => {
const daysUntilWatering = plant.careInfo.waterIntervalDays;
// Very basic check logic for MVP
const isUrgent = daysUntilWatering <= 1;
const wateringText = isUrgent
? t.waterToday
: t.inXDays.replace('{0}', daysUntilWatering.toString());
export const PlantCard: React.FC<PlantCardProps> = ({
plant,
width,
onPress,
t,
isDark,
colorPalette,
}) => {
const colors = useColors(isDark, colorPalette);
const isUrgent = plant.careInfo?.waterIntervalDays <= 1;
const wateringText = plant.careInfo?.waterIntervalDays
? (isUrgent
? t.waterToday
: t.inXDays.replace('{0}', plant.careInfo.waterIntervalDays.toString()))
: t.showDetails; // Default for lexicon entries
return (
<button
onClick={onClick}
className="relative aspect-[4/5] rounded-2xl overflow-hidden shadow-md group active:scale-[0.98] transition-transform w-full text-left"
<TouchableOpacity
style={[styles.container, { width, shadowColor: colors.overlayStrong }]}
activeOpacity={0.9}
onPress={onPress}
>
<img
src={plant.imageUri}
alt={plant.name}
className="w-full h-full object-cover"
/>
{/* Gradient Overlay */}
<div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/20 to-transparent" />
<SafeImage uri={plant.imageUri} style={styles.image} />
<View style={[styles.gradient, { backgroundColor: colors.overlay }]} />
{/* Badge */}
<div className="absolute top-3 left-3">
<div className={`flex items-center space-x-1.5 px-2.5 py-1 rounded-full backdrop-blur-md ${
isUrgent
? 'bg-orange-500 text-white'
: 'bg-black/40 text-stone-200 border border-white/10'
}`}>
<Droplets size={10} className="fill-current" />
<span className="text-[10px] font-bold">
{wateringText}
</span>
</div>
</div>
<View
style={[
styles.badge,
isUrgent
? { backgroundColor: colors.warning }
: { backgroundColor: colors.overlayStrong, borderWidth: 1, borderColor: colors.heroButtonBorder },
]}
>
<Ionicons name="water" size={10} color={colors.iconOnImage} />
<Text style={[styles.badgeText, { color: colors.iconOnImage }]}>{wateringText}</Text>
</View>
{/* Content */}
<div className="absolute bottom-4 left-3 right-3">
<h3 className="text-white font-bold text-lg leading-tight font-serif mb-0.5 shadow-sm">
{plant.name}
</h3>
<p className="text-stone-300 text-xs truncate">
{plant.botanicalName}
</p>
</div>
</button>
<View style={styles.content}>
<Text style={[styles.name, { color: colors.textOnImage }]} numberOfLines={1}>{plant.name}</Text>
<Text style={[styles.botanical, { color: colors.heroButton }]} numberOfLines={1}>{plant.botanicalName}</Text>
</View>
</TouchableOpacity>
);
};
};
const styles = StyleSheet.create({
container: {
aspectRatio: 0.8,
borderRadius: 18,
overflow: 'hidden',
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 6,
elevation: 4,
},
image: { width: '100%', height: '100%', resizeMode: 'cover' },
gradient: {
...StyleSheet.absoluteFillObject,
opacity: 0.8,
},
badge: {
position: 'absolute',
top: 10,
left: 10,
flexDirection: 'row',
alignItems: 'center',
gap: 4,
paddingHorizontal: 8,
paddingVertical: 4,
borderRadius: 12,
},
badgeText: { fontSize: 9, fontWeight: '700' },
content: { position: 'absolute', bottom: 14, left: 10, right: 10 },
name: { fontSize: 16, fontWeight: '700' },
botanical: { fontSize: 11 },
});

View File

@@ -1,302 +0,0 @@
import React, { useState } from 'react';
import { Plant, Language } from '../types';
import { Droplets, Sun, Thermometer, ArrowLeft, Calendar, Trash2, Share2, Edit2, AlertCircle, Check, Clock, Bell, BellOff } from 'lucide-react';
interface PlantDetailProps {
plant: Plant;
onClose: () => void;
onDelete: (id: string) => void;
onUpdate: (plant: Plant) => void;
t: any;
language: Language;
}
export const PlantDetail: React.FC<PlantDetailProps> = ({ plant, onClose, onDelete, onUpdate, t, language }) => {
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
// Map internal language codes to locale strings for Date
const localeMap: Record<string, string> = {
de: 'de-DE',
en: 'en-US',
es: 'es-ES'
};
const formattedAddedDate = new Date(plant.dateAdded).toLocaleDateString(localeMap[language] || 'de-DE');
const formattedWateredDate = new Date(plant.lastWatered).toLocaleDateString(localeMap[language] || 'de-DE');
// Calculate next watering date
const lastWateredObj = new Date(plant.lastWatered);
const nextWateringDate = new Date(lastWateredObj);
nextWateringDate.setDate(lastWateredObj.getDate() + plant.careInfo.waterIntervalDays);
const formattedNextWatering = nextWateringDate.toLocaleDateString(localeMap[language] || 'de-DE', { weekday: 'long', day: 'numeric', month: 'numeric' });
const nextWateringText = t.nextWatering.replace('{0}', formattedNextWatering);
const lastWateredText = t.lastWateredDate.replace('{0}', formattedWateredDate);
// Check if watered today
const isWateredToday = new Date(plant.lastWatered).toDateString() === new Date().toDateString();
const handleWaterPlant = () => {
const now = new Date().toISOString();
// Update history: add new date to the beginning, keep last 10 entries max
const currentHistory = plant.wateringHistory || [];
const newHistory = [now, ...currentHistory].slice(0, 10);
const updatedPlant = {
...plant,
lastWatered: now,
wateringHistory: newHistory
};
onUpdate(updatedPlant);
};
const toggleReminder = async () => {
const newValue = !plant.notificationsEnabled;
if (newValue) {
// Request permission if enabling
if (!('Notification' in window)) {
alert("Notifications are not supported by this browser.");
return;
}
if (Notification.permission === 'granted') {
onUpdate({ ...plant, notificationsEnabled: true });
} else if (Notification.permission !== 'denied') {
const permission = await Notification.requestPermission();
if (permission === 'granted') {
onUpdate({ ...plant, notificationsEnabled: true });
}
} else {
alert(t.reminderPermissionNeeded);
}
} else {
// Disabling
onUpdate({ ...plant, notificationsEnabled: false });
}
};
const handleDeleteClick = () => {
setShowDeleteConfirm(true);
};
const handleConfirmDelete = () => {
onDelete(plant.id);
};
const handleCancelDelete = () => {
setShowDeleteConfirm(false);
};
return (
<div className="fixed inset-0 z-50 flex flex-col h-full bg-stone-50 dark:bg-stone-950 overflow-y-auto no-scrollbar animate-in slide-in-from-right duration-300">
{/* Header */}
<div className="absolute top-0 left-0 right-0 z-10 flex justify-between items-center p-6 text-stone-900 dark:text-white">
<button onClick={onClose} className="bg-white/80 dark:bg-black/50 backdrop-blur-md p-2 rounded-full shadow-sm">
<ArrowLeft size={20} />
</button>
<div className="flex space-x-2">
<button className="bg-white/80 dark:bg-black/50 backdrop-blur-md p-2 rounded-full shadow-sm">
<Share2 size={20} />
</button>
<button className="bg-white/80 dark:bg-black/50 backdrop-blur-md p-2 rounded-full shadow-sm">
<Edit2 size={20} />
</button>
</div>
</div>
<div className="flex-1">
{/* Hero Image */}
<div className="relative w-full aspect-[4/5] md:aspect-video rounded-b-[2.5rem] overflow-hidden shadow-lg mb-6">
<img src={plant.imageUri} alt={plant.name} className="w-full h-full object-cover" />
<div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent"></div>
<div className="absolute bottom-8 left-6 right-6">
<h1 className="text-3xl font-serif font-bold text-white leading-tight mb-1 shadow-sm">
{plant.name}
</h1>
<p className="text-stone-200 italic text-sm">
{plant.botanicalName}
</p>
</div>
</div>
{/* Content Container */}
<div className="px-6 pb-24">
{/* Added Date Info */}
<div className="flex justify-between items-center text-xs text-stone-500 dark:text-stone-400 mb-6">
<div className="flex items-center space-x-1.5 bg-white dark:bg-stone-900 px-3 py-1.5 rounded-full border border-stone-100 dark:border-stone-800">
<Calendar size={12} />
<span>{t.addedOn} {formattedAddedDate}</span>
</div>
</div>
{/* Main Action: Water */}
<div className={`mb-3 p-4 rounded-2xl border flex justify-between items-center transition-colors ${
isWateredToday
? 'bg-green-50 dark:bg-green-900/10 border-green-100 dark:border-green-800/30'
: 'bg-blue-50 dark:bg-blue-900/10 border-blue-100 dark:border-blue-800/30'
}`}>
<div>
<span className="block text-xs text-stone-500 dark:text-stone-400 font-medium mb-0.5">{lastWateredText}</span>
<span className={`block text-sm font-bold ${isWateredToday ? 'text-green-700 dark:text-green-300' : 'text-stone-900 dark:text-stone-200'}`}>
{nextWateringText}
</span>
</div>
<button
onClick={handleWaterPlant}
disabled={isWateredToday}
className={`px-4 py-2.5 rounded-xl font-bold text-xs flex items-center shadow-lg transition-all ${
isWateredToday
? 'bg-green-500 text-white cursor-default shadow-green-500/30'
: 'bg-blue-500 hover:bg-blue-600 active:scale-95 text-white shadow-blue-500/30'
}`}
>
{isWateredToday ? (
<>
<Check size={14} className="mr-2" />
{t.watered}
</>
) : (
<>
<Droplets size={14} className="mr-2 fill-current" />
{t.waterNow}
</>
)}
</button>
</div>
{/* Reminder Toggle */}
<div className="mb-8 flex items-center justify-between p-3 rounded-xl bg-white dark:bg-stone-900 border border-stone-100 dark:border-stone-800">
<div className="flex items-center space-x-3">
<div className={`p-2 rounded-full ${plant.notificationsEnabled ? 'bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400' : 'bg-stone-100 text-stone-400 dark:bg-stone-800 dark:text-stone-500'}`}>
{plant.notificationsEnabled ? <Bell size={18} /> : <BellOff size={18} />}
</div>
<div className="flex flex-col">
<span className="text-sm font-bold text-stone-900 dark:text-stone-100">{t.reminder}</span>
<span className="text-[10px] text-stone-500">{plant.notificationsEnabled ? t.reminderOn : t.reminderOff}</span>
</div>
</div>
<button
onClick={toggleReminder}
className={`w-11 h-6 rounded-full relative transition-colors duration-300 ${plant.notificationsEnabled ? 'bg-primary-500' : 'bg-stone-300 dark:bg-stone-700'}`}
>
<div className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-all duration-300 shadow-sm ${plant.notificationsEnabled ? 'left-6' : 'left-1'}`} />
</button>
</div>
<h3 className="font-bold text-stone-900 dark:text-stone-100 mb-2">{t.aboutPlant}</h3>
<p className="text-stone-600 dark:text-stone-300 text-sm leading-relaxed mb-8">
{plant.description || t.noDescription}
</p>
{/* Care Info */}
<h3 className="font-bold text-stone-900 dark:text-stone-100 mb-4">{t.careTips}</h3>
<div className="grid grid-cols-3 gap-3 mb-10">
<div className="bg-white dark:bg-stone-900 p-3 rounded-2xl border border-stone-100 dark:border-stone-800 flex flex-col items-center text-center shadow-sm">
<div className="w-8 h-8 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-500 flex items-center justify-center mb-2">
<Droplets size={16} className="fill-current" />
</div>
<span className="text-[10px] text-stone-400 font-medium mb-0.5">{t.water}</span>
<span className="text-xs font-bold text-stone-800 dark:text-stone-200">
{plant.careInfo.waterIntervalDays} {t.days || 'Tage'}
</span>
</div>
<div className="bg-white dark:bg-stone-900 p-3 rounded-2xl border border-stone-100 dark:border-stone-800 flex flex-col items-center text-center shadow-sm">
<div className="w-8 h-8 rounded-full bg-amber-50 dark:bg-amber-900/20 text-amber-500 flex items-center justify-center mb-2">
<Sun size={16} className="fill-current" />
</div>
<span className="text-[10px] text-stone-400 font-medium mb-0.5">{t.light}</span>
<span className="text-xs font-bold text-stone-800 dark:text-stone-200 truncate w-full">
{plant.careInfo.light}
</span>
</div>
<div className="bg-white dark:bg-stone-900 p-3 rounded-2xl border border-stone-100 dark:border-stone-800 flex flex-col items-center text-center shadow-sm">
<div className="w-8 h-8 rounded-full bg-rose-50 dark:bg-rose-900/20 text-rose-500 flex items-center justify-center mb-2">
<Thermometer size={16} className="fill-current" />
</div>
<span className="text-[10px] text-stone-400 font-medium mb-0.5">{t.temp}</span>
<span className="text-xs font-bold text-stone-800 dark:text-stone-200">
{plant.careInfo.temp}
</span>
</div>
</div>
{/* Watering History Section */}
<h3 className="font-bold text-stone-900 dark:text-stone-100 mb-4">{t.wateringHistory}</h3>
<div className="bg-white dark:bg-stone-900 rounded-2xl border border-stone-100 dark:border-stone-800 overflow-hidden mb-10 shadow-sm">
{(!plant.wateringHistory || plant.wateringHistory.length === 0) ? (
<div className="p-6 text-center text-stone-400 text-sm">
<Clock size={24} className="mx-auto mb-2 opacity-50" />
{t.noHistory}
</div>
) : (
<ul className="divide-y divide-stone-100 dark:divide-stone-800">
{plant.wateringHistory.slice(0, 5).map((dateStr, index) => (
<li key={index} className="px-5 py-3 flex justify-between items-center group hover:bg-stone-50 dark:hover:bg-stone-800/50 transition-colors">
<div className="flex items-center space-x-3">
<div className="w-8 h-8 rounded-full bg-blue-50 dark:bg-blue-900/10 text-blue-500 flex items-center justify-center">
<Droplets size={14} className="fill-current" />
</div>
<span className="text-sm font-medium text-stone-700 dark:text-stone-300">
{new Date(dateStr).toLocaleDateString(localeMap[language] || 'de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })}
</span>
</div>
<span className="text-xs font-mono text-stone-400 bg-stone-100 dark:bg-stone-800 px-2 py-1 rounded-md">
{new Date(dateStr).toLocaleTimeString(localeMap[language] || 'de-DE', { hour: '2-digit', minute: '2-digit' })}
</span>
</li>
))}
</ul>
)}
</div>
{/* Danger Zone */}
<div className="border-t border-stone-200 dark:border-stone-800 pt-6 flex justify-center">
<button
onClick={handleDeleteClick}
className="flex items-center space-x-2 text-red-500 hover:text-red-600 px-4 py-2 rounded-xl hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
>
<Trash2 size={16} />
<span className="text-sm font-medium">{t.delete}</span>
</button>
</div>
</div>
</div>
{/* Delete Confirmation Modal */}
{showDeleteConfirm && (
<div className="absolute inset-0 z-[60] bg-black/40 backdrop-blur-sm flex items-center justify-center p-6 animate-in fade-in duration-200">
<div className="bg-white dark:bg-stone-900 w-full max-w-sm rounded-2xl p-6 shadow-2xl scale-100 animate-in zoom-in-95 duration-200">
<div className="w-12 h-12 bg-red-100 dark:bg-red-900/30 text-red-500 rounded-full flex items-center justify-center mb-4 mx-auto">
<AlertCircle size={24} />
</div>
<h3 className="text-xl font-bold text-center text-stone-900 dark:text-white mb-2">{t.deleteConfirmTitle}</h3>
<p className="text-stone-500 dark:text-stone-400 text-center text-sm mb-6 leading-relaxed">
{t.deleteConfirmMessage}
</p>
<div className="grid grid-cols-2 gap-3">
<button
onClick={handleCancelDelete}
className="py-3 px-4 rounded-xl bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300 font-bold text-sm"
>
{t.cancel}
</button>
<button
onClick={handleConfirmDelete}
className="py-3 px-4 rounded-xl bg-red-500 text-white font-bold text-sm hover:bg-red-600"
>
{t.confirm}
</button>
</div>
</div>
</div>
)}
</div>
);
};

View File

@@ -1,21 +0,0 @@
import React from 'react';
export const PlantSkeleton: React.FC = () => {
return (
<div className="relative aspect-[4/5] rounded-2xl overflow-hidden bg-stone-200 dark:bg-stone-800 animate-pulse border border-stone-300 dark:border-stone-700/50">
{/* Badge Placeholder */}
<div className="absolute top-3 left-3">
<div className="h-6 w-20 bg-stone-300 dark:bg-stone-700 rounded-full" />
</div>
{/* Content Placeholder */}
<div className="absolute bottom-4 left-3 right-3 space-y-2">
{/* Title */}
<div className="h-6 w-3/4 bg-stone-300 dark:bg-stone-700 rounded-md" />
{/* Subtitle */}
<div className="h-3 w-1/2 bg-stone-300 dark:bg-stone-700 rounded-md" />
</div>
</div>
);
};

View File

@@ -1,7 +1,10 @@
import React, { useState } from 'react';
import { IdentificationResult } from '../types';
import { Droplets, Sun, Thermometer, CheckCircle2, ArrowLeft, Share2 } from 'lucide-react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Share, Alert } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { ColorPalette, IdentificationResult } from '../types';
import { useColors } from '../constants/Colors';
import { SafeImage } from './SafeImage';
interface ResultCardProps {
result: IdentificationResult;
@@ -9,132 +12,255 @@ interface ResultCardProps {
onSave: () => void;
onClose: () => void;
t: any;
isDark: boolean;
colorPalette: ColorPalette;
isGuest?: boolean;
}
export const ResultCard: React.FC<ResultCardProps> = ({ result, imageUri, onSave, onClose, t }) => {
export const ResultCard: React.FC<ResultCardProps> = ({
result,
imageUri,
onSave,
onClose,
t,
isDark,
colorPalette,
isGuest = false,
}) => {
const colors = useColors(isDark, colorPalette);
const insets = useSafeAreaInsets();
const [showDetails, setShowDetails] = useState(false);
return (
<div className="flex flex-col h-full bg-stone-50 dark:bg-stone-950 overflow-y-auto no-scrollbar animate-in slide-in-from-right duration-300">
{/* Header */}
<div className="absolute top-0 left-0 right-0 z-10 flex justify-between items-center p-6 text-stone-900 dark:text-white">
<button onClick={onClose} className="bg-white/80 dark:bg-black/50 backdrop-blur-md p-2 rounded-full shadow-sm">
<ArrowLeft size={20} />
</button>
<span className="font-bold text-sm bg-white/80 dark:bg-black/50 backdrop-blur-md px-3 py-1 rounded-full">{t.result}</span>
<button className="bg-white/80 dark:bg-black/50 backdrop-blur-md p-2 rounded-full shadow-sm">
<Share2 size={20} />
</button>
</div>
const handleShare = async () => {
try {
await Share.share({
message: `I just identified a ${result.name} (${result.botanicalName}) with ${Math.round(result.confidence * 100)}% confidence using GreenLens!`,
});
} catch (error: any) {
Alert.alert('Error', error.message);
}
};
<div className="p-4 pt-20">
return (
<SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={['top', 'bottom']}>
{/* Header */}
<View style={[styles.header, { paddingTop: insets.top + 8 }]}>
<TouchableOpacity
style={[styles.headerBtn, { backgroundColor: colors.heroButton, borderColor: colors.heroButtonBorder }]}
onPress={onClose}
>
<Ionicons name="arrow-back" size={20} color={colors.text} />
</TouchableOpacity>
<View style={[styles.headerBadge, { backgroundColor: colors.heroButton, borderColor: colors.heroButtonBorder }]}>
<Text style={[styles.headerBadgeText, { color: colors.text }]}>{t.result}</Text>
</View>
<TouchableOpacity
style={[styles.headerBtn, { backgroundColor: colors.heroButton, borderColor: colors.heroButtonBorder }]}
onPress={handleShare}
>
<Ionicons name="share-outline" size={20} color={colors.text} />
</TouchableOpacity>
</View>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={[
styles.scrollContent,
{ paddingTop: insets.top + 76, paddingBottom: insets.bottom + 36 },
]}
>
{/* Hero Image */}
<div className="relative w-full aspect-[4/3] rounded-[2rem] overflow-hidden shadow-lg mb-6">
<img src={imageUri} alt="Analyzed Plant" className="w-full h-full object-cover" />
<div className="absolute bottom-4 left-4 bg-white/90 backdrop-blur-sm text-primary-700 px-3 py-1.5 rounded-full text-xs font-bold shadow-sm flex items-center">
<CheckCircle2 size={14} className="mr-1.5 fill-primary-600 text-white" />
{Math.round(result.confidence * 100)}% {t.match}
</div>
</div>
<View style={[styles.heroContainer, { shadowColor: colors.overlayStrong }]}>
<SafeImage uri={imageUri} style={styles.heroImage} />
<View style={[styles.confidenceBadge, { backgroundColor: colors.heroButton }]}>
<Ionicons name="checkmark-circle" size={14} color={colors.success} />
<Text style={[styles.confidenceText, { color: colors.success }]}>
{Math.round(result.confidence * 100)}% {t.match}
</Text>
</View>
</View>
{/* Info */}
<div className="px-2">
<h1 className="text-3xl font-serif font-bold text-stone-900 dark:text-stone-100 leading-tight mb-1">
{result.name}
</h1>
<p className="text-stone-400 dark:text-stone-500 italic text-sm mb-6">
{result.botanicalName}
</p>
<Text style={[styles.plantName, { color: colors.text }]}>{result.name}</Text>
<Text style={[styles.botanical, { color: colors.textMuted }]}>{result.botanicalName}</Text>
<Text style={[styles.description, { color: colors.textSecondary }]}>
{result.description || t.noDescription}
</Text>
<p className="text-stone-600 dark:text-stone-300 text-sm leading-relaxed mb-8">
{result.description || t.noDescription}
</p>
{/* Care Check */}
<View style={styles.careHeader}>
<Text style={[styles.sectionTitle, { color: colors.text }]}>{t.careCheck}</Text>
<TouchableOpacity onPress={() => setShowDetails(!showDetails)}>
<Text style={[styles.detailsToggle, { color: colors.primaryDark }]}>
{showDetails ? t.hideDetails : t.showDetails}
</Text>
</TouchableOpacity>
</View>
{/* Care Check */}
<div className="flex justify-between items-end mb-4">
<h3 className="font-bold text-stone-900 dark:text-stone-100">{t.careCheck}</h3>
<button
onClick={() => setShowDetails(!showDetails)}
className="text-[10px] font-bold text-primary-600 uppercase tracking-wide"
>
{showDetails ? t.hideDetails : t.showDetails}
</button>
</div>
<View style={styles.careGrid}>
{[
{ icon: 'water' as const, label: t.water, value: result.careInfo.waterIntervalDays <= 7 ? t.waterModerate : t.waterLittle, color: colors.info, bg: colors.infoSoft },
{ icon: 'sunny' as const, label: t.light, value: result.careInfo.light, color: colors.warning, bg: colors.warningSoft },
{ icon: 'thermometer' as const, label: t.temp, value: result.careInfo.temp, color: colors.danger, bg: colors.dangerSoft },
].map((item) => (
<View key={item.label} style={[styles.careCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
<View style={[styles.careIcon, { backgroundColor: item.bg }]}>
<Ionicons name={item.icon} size={16} color={item.color} />
</View>
<Text style={[styles.careLabel, { color: colors.textMuted }]}>{item.label}</Text>
<Text style={[styles.careValue, { color: colors.text }]}>{item.value}</Text>
</View>
))}
</View>
<div className="grid grid-cols-3 gap-3 mb-8">
<div className="bg-white dark:bg-stone-900 p-3 rounded-2xl border border-stone-100 dark:border-stone-800 flex flex-col items-center text-center shadow-sm">
<div className="w-8 h-8 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-500 flex items-center justify-center mb-2">
<Droplets size={16} className="fill-current" />
</div>
<span className="text-[10px] text-stone-400 font-medium mb-0.5">{t.water}</span>
<span className="text-xs font-bold text-stone-800 dark:text-stone-200">
{result.careInfo.waterIntervalDays <= 7 ? t.waterModerate : t.waterLittle}
</span>
</div>
{showDetails && (
<View style={[styles.detailsBox, { backgroundColor: colors.surfaceMuted, borderColor: colors.border }]}>
<Text style={[styles.detailsTitle, { color: colors.textSecondary }]}>{t.detailedCare}</Text>
{[
{ text: t.careTextWater.replace('{0}', result.careInfo.waterIntervalDays.toString()), color: colors.success },
{ text: t.careTextLight.replace('{0}', result.careInfo.light), color: colors.warning },
{ text: t.careTextTemp.replace('{0}', result.careInfo.temp), color: colors.danger },
].map((item, i) => (
<View key={i} style={styles.detailRow}>
<View style={[styles.detailDot, { backgroundColor: item.color }]} />
<Text style={[styles.detailText, { color: colors.textSecondary }]}>{item.text}</Text>
</View>
))}
</View>
)}
<div className="bg-white dark:bg-stone-900 p-3 rounded-2xl border border-stone-100 dark:border-stone-800 flex flex-col items-center text-center shadow-sm">
<div className="w-8 h-8 rounded-full bg-amber-50 dark:bg-amber-900/20 text-amber-500 flex items-center justify-center mb-2">
<Sun size={16} className="fill-current" />
</div>
<span className="text-[10px] text-stone-400 font-medium mb-0.5">{t.light}</span>
<span className="text-xs font-bold text-stone-800 dark:text-stone-200 truncate w-full">
{result.careInfo.light}
</span>
</div>
{/* Save */}
<View style={styles.localInfo}>
<View style={[styles.localIcon, { borderColor: colors.borderStrong }]} />
<Text style={[styles.localText, { color: colors.textMuted }]}>{t.dataSavedLocally}</Text>
</View>
<div className="bg-white dark:bg-stone-900 p-3 rounded-2xl border border-stone-100 dark:border-stone-800 flex flex-col items-center text-center shadow-sm">
<div className="w-8 h-8 rounded-full bg-rose-50 dark:bg-rose-900/20 text-rose-500 flex items-center justify-center mb-2">
<Thermometer size={16} className="fill-current" />
</div>
<span className="text-[10px] text-stone-400 font-medium mb-0.5">{t.temp}</span>
<span className="text-xs font-bold text-stone-800 dark:text-stone-200">
{result.careInfo.temp}
</span>
</div>
</div>
{/* Expanded Details */}
{showDetails && (
<div className="mb-8 p-5 bg-stone-100 dark:bg-stone-900/50 rounded-2xl animate-in fade-in slide-in-from-top-2 border border-stone-200 dark:border-stone-800">
<h4 className="font-bold text-xs mb-3 text-stone-700 dark:text-stone-300 uppercase tracking-wide">{t.detailedCare}</h4>
<ul className="space-y-3 text-sm text-stone-600 dark:text-stone-300">
<li className="flex items-start">
<span className="mr-3 text-primary-500"></span>
<span>{t.careTextWater.replace('{0}', result.careInfo.waterIntervalDays.toString())}</span>
</li>
<li className="flex items-start">
<span className="mr-3 text-amber-500"></span>
<span>{t.careTextLight.replace('{0}', result.careInfo.light)}</span>
</li>
<li className="flex items-start">
<span className="mr-3 text-rose-500"></span>
<span>{t.careTextTemp.replace('{0}', result.careInfo.temp)}</span>
</li>
</ul>
</div>
)}
{/* Save Button */}
<div className="flex items-center justify-center space-x-2 text-xs text-stone-400 mb-4">
<div className="w-3 h-3 rounded-sm border border-stone-300 flex items-center justify-center">
<div className="w-1.5 h-1.5 bg-stone-400 rounded-[1px]"></div>
</div>
<span>{t.dataSavedLocally}</span>
</div>
<button
onClick={onSave}
className="w-full py-4 bg-primary-500 hover:bg-primary-600 text-black font-bold text-sm rounded-xl shadow-lg shadow-primary-500/30 active:scale-[0.98] transition-all flex items-center justify-center"
>
<div className="bg-black/20 rounded-full p-0.5 mr-2">
<CheckCircle2 size={14} className="text-black" />
</div>
{t.addToPlants}
</button>
<div className="h-8"></div>
</div>
</div>
</div>
<TouchableOpacity
style={[
styles.saveBtn,
{ backgroundColor: colors.primary, shadowColor: colors.primary },
]}
activeOpacity={0.8}
onPress={onSave}
>
<Ionicons name={isGuest ? "person-add" : "checkmark-circle"} size={16} color={colors.onPrimary} />
<Text style={[styles.saveBtnText, { color: colors.onPrimary }]}>
{isGuest ? t.registerToSave : t.addToPlants}
</Text>
</TouchableOpacity>
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: { flex: 1 },
header: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
zIndex: 10,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 20,
},
headerBtn: {
borderRadius: 20,
padding: 8,
borderWidth: 1,
},
headerBadge: {
borderRadius: 20,
paddingHorizontal: 12,
paddingVertical: 4,
borderWidth: 1,
},
headerBadgeText: { fontWeight: '700', fontSize: 13 },
scrollContent: { paddingHorizontal: 16 },
heroContainer: {
width: '100%',
aspectRatio: 4 / 3,
borderRadius: 24,
overflow: 'hidden',
marginBottom: 20,
shadowColor: '#000',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.15,
shadowRadius: 8,
elevation: 6,
},
heroImage: { width: '100%', height: '100%', resizeMode: 'cover' },
confidenceBadge: {
position: 'absolute',
bottom: 14,
left: 14,
borderRadius: 20,
paddingHorizontal: 10,
paddingVertical: 6,
flexDirection: 'row',
alignItems: 'center',
gap: 4,
},
confidenceText: { fontSize: 11, fontWeight: '700' },
plantName: { fontSize: 28, fontWeight: '700', marginBottom: 2 },
botanical: { fontSize: 13, fontStyle: 'italic', marginBottom: 14 },
description: { fontSize: 13, lineHeight: 20, marginBottom: 24 },
careHeader: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-end',
marginBottom: 12,
},
sectionTitle: { fontSize: 16, fontWeight: '700' },
detailsToggle: { fontSize: 10, fontWeight: '700', textTransform: 'uppercase', letterSpacing: 0.5 },
careGrid: { flexDirection: 'row', gap: 10, marginBottom: 20 },
careCard: {
flex: 1,
alignItems: 'center',
padding: 12,
borderRadius: 18,
borderWidth: 1,
gap: 6,
},
careIcon: { width: 32, height: 32, borderRadius: 16, justifyContent: 'center', alignItems: 'center' },
careLabel: { fontSize: 10, fontWeight: '500' },
careValue: {
width: '100%',
fontSize: 11,
lineHeight: 14,
fontWeight: '700',
textAlign: 'center',
flexShrink: 1,
},
detailsBox: {
borderRadius: 18,
borderWidth: 1,
padding: 16,
marginBottom: 20,
gap: 10,
},
detailsTitle: { fontSize: 11, fontWeight: '700', textTransform: 'uppercase', letterSpacing: 0.5 },
detailRow: { flexDirection: 'row', alignItems: 'flex-start', gap: 10 },
detailDot: { width: 6, height: 6, borderRadius: 3, marginTop: 6 },
detailText: { fontSize: 13, flex: 1 },
localInfo: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', gap: 6, marginBottom: 12 },
localIcon: { width: 12, height: 12, borderRadius: 2, borderWidth: 1, borderColor: '#d6d3d1' },
localText: { fontSize: 11 },
saveBtn: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
gap: 8,
backgroundColor: '#4ade80',
paddingVertical: 16,
borderRadius: 14,
shadowColor: '#4ade80',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 6,
},
saveBtnText: { fontWeight: '700', fontSize: 14 },
});

134
components/SafeImage.tsx Normal file
View File

@@ -0,0 +1,134 @@
import React from 'react';
import { Image, ImageProps, StyleSheet, Text, View } from 'react-native';
import {
DEFAULT_PLANT_IMAGE_URI,
getCategoryFallbackImage,
getPlantImageSourceFallbackUri,
getWikimediaFilePathFromThumbnailUrl,
resolveImageUri,
tryResolveImageUri,
} from '../utils/imageUri';
type SafeImageFallbackMode = 'category' | 'default' | 'none';
interface SafeImageProps extends Omit<ImageProps, 'source'> {
uri?: string | null;
categories?: string[];
fallbackMode?: SafeImageFallbackMode;
placeholderLabel?: string;
}
const getPlaceholderInitial = (label?: string): string => {
if (!label) return '?';
const trimmed = label.trim();
if (!trimmed) return '?';
return trimmed.charAt(0).toUpperCase();
};
export const SafeImage: React.FC<SafeImageProps> = ({
uri,
categories,
fallbackMode = 'category',
placeholderLabel,
onError,
style,
...props
}) => {
const categoryFallback = categories && categories.length > 0
? getCategoryFallbackImage(categories)
: DEFAULT_PLANT_IMAGE_URI;
const selectedFallback = fallbackMode === 'category'
? categoryFallback
: DEFAULT_PLANT_IMAGE_URI;
const [resolvedUri, setResolvedUri] = React.useState<string>(() => {
const strictResolved = tryResolveImageUri(uri);
if (strictResolved) return strictResolved;
return fallbackMode === 'none' ? '' : selectedFallback;
});
const [showPlaceholder, setShowPlaceholder] = React.useState<boolean>(() => {
if (fallbackMode !== 'none') return false;
return !tryResolveImageUri(uri);
});
const [retryCount, setRetryCount] = React.useState(0);
const lastAttemptUri = React.useRef<string | null>(null);
React.useEffect(() => {
const strictResolved = tryResolveImageUri(uri);
setResolvedUri(strictResolved || (fallbackMode === 'none' ? '' : selectedFallback));
setShowPlaceholder(fallbackMode === 'none' && !strictResolved);
setRetryCount(0);
lastAttemptUri.current = strictResolved;
}, [uri, fallbackMode, selectedFallback]);
if (fallbackMode === 'none' && showPlaceholder) {
return (
<View style={[styles.placeholder, style]}>
<Text style={styles.placeholderText}>{getPlaceholderInitial(placeholderLabel)}</Text>
</View>
);
}
return (
<Image
{...props}
style={style}
source={{
uri: resolvedUri || selectedFallback
}}
onError={(event) => {
onError?.(event);
const currentUri = resolvedUri || selectedFallback;
// Smart Retry Logic for Wikimedia (first failure only)
if (retryCount === 0 && currentUri.includes('upload.wikimedia.org')) {
const fileName = getWikimediaFilePathFromThumbnailUrl(currentUri);
if (fileName) {
const redirectUrl = `https://commons.wikimedia.org/wiki/Special:FilePath/${encodeURIComponent(fileName)}`;
setRetryCount(1);
setResolvedUri(redirectUrl);
lastAttemptUri.current = redirectUrl;
return;
}
}
const sourceFallbackUri = getPlantImageSourceFallbackUri(uri);
if (sourceFallbackUri && sourceFallbackUri !== currentUri && lastAttemptUri.current !== sourceFallbackUri) {
setResolvedUri(sourceFallbackUri);
lastAttemptUri.current = sourceFallbackUri;
return;
}
// If we get here, either it wasn't a Wikimedia URL, or filename extraction failed,
// or the retry itself failed.
if (fallbackMode === 'none') {
setShowPlaceholder(true);
return;
}
setResolvedUri((current) => {
if (current === DEFAULT_PLANT_IMAGE_URI) return current;
if (current === selectedFallback) return DEFAULT_PLANT_IMAGE_URI;
return selectedFallback;
});
// Prevent infinite loops if fallbacks also fail
setRetryCount(current => current + 1);
}}
/>
);
};
const styles = StyleSheet.create({
placeholder: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#e7ece8',
},
placeholderText: {
fontSize: 18,
fontWeight: '700',
color: '#5f6f63',
},
});

View File

@@ -0,0 +1,70 @@
import React, { useEffect, useRef } from 'react';
import { View, Text, Animated, StyleSheet, Image } from 'react-native';
export default function SplashScreen() {
const fadeAnim = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.timing(fadeAnim, {
toValue: 1,
duration: 800,
useNativeDriver: true,
}).start();
}, []);
return (
<View style={styles.container}>
<Animated.View style={[styles.content, { opacity: fadeAnim }]}>
<View style={styles.iconContainer}>
<Image
source={require('../assets/icon.png')}
style={styles.icon}
resizeMode="cover"
/>
</View>
<Text style={styles.title}>GreenLens</Text>
<Text style={styles.subtitle}>Identify any plant</Text>
</Animated.View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#1c1917',
alignItems: 'center',
justifyContent: 'center',
},
content: {
alignItems: 'center',
},
iconContainer: {
width: 100,
height: 100,
borderRadius: 24,
backgroundColor: '#ffffff',
elevation: 8,
shadowColor: '#4ade80',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.2,
shadowRadius: 12,
marginBottom: 8,
overflow: 'hidden',
},
icon: {
width: '100%',
height: '100%',
},
title: {
fontSize: 36,
fontWeight: '700',
color: '#fafaf9',
marginTop: 16,
},
subtitle: {
fontSize: 16,
color: '#a8a29e',
marginTop: 8,
},
});

View File

@@ -1,51 +0,0 @@
import React from 'react';
import { Tab } from '../types';
import { LayoutGrid, Search, User } from 'lucide-react';
interface TabBarProps {
currentTab: Tab;
onTabChange: (tab: Tab) => void;
labels: {
home: string;
search: string;
settings: string;
};
}
export const TabBar: React.FC<TabBarProps> = ({ currentTab, onTabChange, labels }) => {
return (
<div className="fixed bottom-0 left-0 right-0 bg-white dark:bg-stone-900 border-t border-stone-200 dark:border-stone-800 pb-safe pt-2 px-6 z-40">
<div className="flex justify-between items-center h-16 max-w-sm mx-auto">
<button
onClick={() => onTabChange(Tab.HOME)}
className={`flex flex-col items-center justify-center w-16 space-y-1.5 ${
currentTab === Tab.HOME ? 'text-stone-900 dark:text-stone-100' : 'text-stone-400 dark:text-stone-600'
}`}
>
<LayoutGrid size={24} strokeWidth={currentTab === Tab.HOME ? 2.5 : 2} />
<span className="text-[10px] font-medium">{labels.home}</span>
</button>
<button
onClick={() => onTabChange(Tab.SEARCH)}
className={`flex flex-col items-center justify-center w-16 space-y-1.5 ${
currentTab === Tab.SEARCH ? 'text-stone-900 dark:text-stone-100' : 'text-stone-400 dark:text-stone-600'
}`}
>
<Search size={24} strokeWidth={currentTab === Tab.SEARCH ? 2.5 : 2} />
<span className="text-[10px] font-medium">{labels.search}</span>
</button>
<button
onClick={() => onTabChange(Tab.SETTINGS)}
className={`flex flex-col items-center justify-center w-16 space-y-1.5 ${
currentTab === Tab.SETTINGS ? 'text-stone-900 dark:text-stone-100' : 'text-stone-400 dark:text-stone-600'
}`}
>
<User size={24} strokeWidth={currentTab === Tab.SETTINGS ? 2.5 : 2} />
<span className="text-[10px] font-medium">{labels.settings}</span>
</button>
</div>
</div>
);
};

View File

@@ -0,0 +1,108 @@
import React, { useMemo } from 'react';
import { StyleSheet, View } from 'react-native';
import { AppColors } from '../constants/Colors';
interface ThemeBackdropProps {
colors: AppColors;
}
const texturePoints = [
[4, 6, 2], [12, 14, 1], [20, 9, 2], [26, 19, 1], [34, 8, 2], [42, 16, 1],
[50, 10, 1], [58, 18, 2], [66, 7, 1], [74, 15, 2], [82, 11, 1], [90, 17, 2],
[8, 30, 1], [16, 25, 2], [24, 33, 1], [32, 27, 2], [40, 35, 1], [48, 28, 2],
[56, 36, 1], [64, 26, 2], [72, 34, 1], [80, 29, 2], [88, 37, 1], [94, 31, 2],
[6, 48, 2], [14, 44, 1], [22, 52, 2], [30, 46, 1], [38, 54, 2], [46, 49, 1],
[54, 56, 2], [62, 45, 1], [70, 53, 2], [78, 47, 1], [86, 55, 2], [92, 50, 1],
[10, 70, 1], [18, 64, 2], [26, 72, 1], [34, 67, 2], [42, 74, 1], [50, 68, 2],
[58, 76, 1], [66, 65, 2], [74, 73, 1], [82, 69, 2], [90, 77, 1], [96, 71, 2],
];
const parseColor = (value: string) => {
if (value.startsWith('#')) {
const cleaned = value.replace('#', '');
const normalized = cleaned.length === 3
? cleaned.split('').map((c) => `${c}${c}`).join('')
: cleaned;
const int = Number.parseInt(normalized, 16);
return {
r: (int >> 16) & 255,
g: (int >> 8) & 255,
b: int & 255,
a: 1,
};
}
const match = value.match(/rgba?\(([^)]+)\)/i);
if (!match) return { r: 0, g: 0, b: 0, a: 0 };
const parts = match[1].split(',').map((part) => part.trim());
return {
r: Number.parseFloat(parts[0]) || 0,
g: Number.parseFloat(parts[1]) || 0,
b: Number.parseFloat(parts[2]) || 0,
a: parts.length > 3 ? Number.parseFloat(parts[3]) || 0 : 1,
};
};
const mixColor = (start: string, end: string, ratio: number) => {
const a = parseColor(start);
const b = parseColor(end);
const t = Math.max(0, Math.min(1, ratio));
const r = Math.round(a.r + (b.r - a.r) * t);
const g = Math.round(a.g + (b.g - a.g) * t);
const bl = Math.round(a.b + (b.b - a.b) * t);
const alpha = a.a + (b.a - a.a) * t;
return `rgba(${r}, ${g}, ${bl}, ${alpha})`;
};
const ThemeBackdropInner: React.FC<ThemeBackdropProps> = ({ colors }) => {
const gradientStrips = useMemo(() =>
Array.from({ length: 18 }).map((_, index, arr) => {
const ratio = index / (arr.length - 1);
return mixColor(colors.pageGradientStart, colors.pageGradientEnd, ratio);
}),
[colors.pageGradientStart, colors.pageGradientEnd]);
return (
<View pointerEvents="none" style={[StyleSheet.absoluteFill, { backgroundColor: colors.pageBase }]}>
<View style={styles.gradientLayer}>
{gradientStrips.map((stripColor, index) => (
<View
key={`strip-${index}`}
style={[styles.gradientStrip, { backgroundColor: stripColor }]}
/>
))}
</View>
<View style={styles.textureLayer}>
{texturePoints.map(([x, y, size], index) => (
<View
key={index}
style={[
styles.noiseDot,
{
left: `${x}%`,
top: `${y}%`,
width: size,
height: size,
borderRadius: size / 2,
backgroundColor: colors.pageTexture,
},
]}
/>
))}
</View>
</View>
);
};
export const ThemeBackdrop = React.memo(ThemeBackdropInner);
const styles = StyleSheet.create({
gradientLayer: { ...StyleSheet.absoluteFillObject },
gradientStrip: { flex: 1 },
textureLayer: {
...StyleSheet.absoluteFillObject,
},
noiseDot: {
position: 'absolute',
},
});

View File

@@ -1,37 +1,79 @@
import React, { useEffect, useState } from 'react';
import { CheckCircle2 } from 'lucide-react';
import React, { useEffect, useRef } from 'react';
import { Animated, Text, StyleSheet, View } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useColors } from '../constants/Colors';
import { ColorPalette } from '../types';
interface ToastProps {
message: string;
isVisible: boolean;
onClose: () => void;
isDark?: boolean;
colorPalette?: ColorPalette;
}
export const Toast: React.FC<ToastProps> = ({ message, isVisible, onClose }) => {
const [show, setShow] = useState(false);
export const Toast: React.FC<ToastProps> = ({
message,
isVisible,
onClose,
isDark = false,
colorPalette = 'forest',
}) => {
const colors = useColors(isDark, colorPalette);
const opacity = useRef(new Animated.Value(0)).current;
const translateY = useRef(new Animated.Value(20)).current;
useEffect(() => {
if (isVisible) {
setShow(true);
const timer = setTimeout(() => {
setShow(false);
setTimeout(onClose, 300); // Wait for animation
}, 3000);
return () => clearTimeout(timer);
} else {
setShow(false);
}
}, [isVisible, onClose]);
Animated.parallel([
Animated.timing(opacity, { toValue: 1, duration: 300, useNativeDriver: true }),
Animated.timing(translateY, { toValue: 0, duration: 300, useNativeDriver: true }),
]).start();
if (!isVisible && !show) return null;
const timer = setTimeout(() => {
Animated.parallel([
Animated.timing(opacity, { toValue: 0, duration: 300, useNativeDriver: true }),
Animated.timing(translateY, { toValue: 20, duration: 300, useNativeDriver: true }),
]).start(() => onClose());
}, 3000);
return () => clearTimeout(timer);
}
}, [isVisible]);
if (!isVisible) return null;
return (
<div className={`fixed bottom-20 left-0 right-0 z-[70] flex justify-center pointer-events-none transition-all duration-300 transform ${show ? 'translate-y-0 opacity-100' : 'translate-y-4 opacity-0'}`}>
<div className="bg-stone-900 dark:bg-white text-white dark:text-stone-900 px-4 py-3 rounded-full shadow-lg flex items-center space-x-2">
<CheckCircle2 size={18} className="text-green-500" />
<span className="text-sm font-medium">{message}</span>
</div>
</div>
<Animated.View style={[styles.container, { opacity, transform: [{ translateY }] }]}>
<View style={[styles.toast, { backgroundColor: colors.surface, shadowColor: colors.overlayStrong }]}>
<Ionicons name="checkmark-circle" size={18} color={colors.success} />
<Text style={[styles.text, { color: colors.text }]}>{message}</Text>
</View>
</Animated.View>
);
};
const styles = StyleSheet.create({
container: {
position: 'absolute',
bottom: 100,
left: 0,
right: 0,
alignItems: 'center',
zIndex: 70,
pointerEvents: 'none',
},
toast: {
flexDirection: 'row',
alignItems: 'center',
gap: 8,
paddingHorizontal: 16,
paddingVertical: 12,
borderRadius: 24,
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.2,
shadowRadius: 8,
elevation: 8,
},
text: { fontSize: 13, fontWeight: '500' },
});