Merge pull request #6 from Sosokker/home

fix: add photo in recipes page
This commit is contained in:
Tantikon P. 2025-05-12 22:28:19 +07:00 committed by GitHub
commit 21784ac58a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 248 additions and 255 deletions

View File

@ -1,61 +1,49 @@
"use client"; "use client"
import { getFoods, insertGenAIResult } from "@/services/data/foods"
import { IconSymbol } from "@/components/ui/IconSymbol"; import { uploadImageToSupabase } from "@/services/data/imageUpload"
import { getFoods, insertGenAIResult } from "@/services/data/foods"; import { getProfile } from "@/services/data/profile"
import { uploadImageToSupabase } from "@/services/data/imageUpload"; import { callGenAIonImage } from "@/services/gemini"
import { getProfile } from "@/services/data/profile"; import { supabase } from "@/services/supabase"
import { callGenAIonImage } from "@/services/gemini"; import { Feather, FontAwesome, Ionicons } from "@expo/vector-icons"
import { supabase } from "@/services/supabase"; import { useQuery } from "@tanstack/react-query"
import { Feather, FontAwesome, Ionicons } from "@expo/vector-icons"; import * as FileSystem from "expo-file-system"
import { useQuery } from "@tanstack/react-query"; import * as ImagePicker from "expo-image-picker"
import * as FileSystem from "expo-file-system"; import { router } from "expo-router"
import * as ImagePicker from "expo-image-picker"; import { useEffect, useState } from "react"
import { router } from "expo-router"; import { Alert, Image, SafeAreaView, ScrollView, StatusBar, Text, TouchableOpacity, View } from "react-native"
import { useEffect, useMemo, useState } from "react";
import {
Alert,
Image,
SafeAreaView,
ScrollView,
StatusBar,
Text,
TextInput,
TouchableOpacity,
View,
} from "react-native";
const useFoodsQuery = () => { const useFoodsQuery = () => {
return useQuery({ return useQuery({
queryKey: ["highlight-foods"], queryKey: ["highlight-foods"],
queryFn: async () => { queryFn: async () => {
const { data, error } = await getFoods(undefined, true, undefined, 3); const { data, error } = await getFoods(undefined, true, undefined, 6) // Fetch 6 items for multiple rows
if (error) throw error; if (error) throw error
return data || []; return data || []
}, },
staleTime: 1000 * 60 * 5, staleTime: 1000 * 60 * 5,
}); })
}; }
const useUserProfile = () => { const useUserProfile = () => {
const [userId, setUserId] = useState<string | null>(null); const [userId, setUserId] = useState<string | null>(null)
const [isLoadingUserId, setIsLoadingUserId] = useState(true); const [isLoadingUserId, setIsLoadingUserId] = useState(true)
// Get current user ID // Get current user ID
useEffect(() => { useEffect(() => {
const fetchUserId = async () => { const fetchUserId = async () => {
try { try {
const { data, error } = await supabase.auth.getUser(); const { data, error } = await supabase.auth.getUser()
if (error) throw error; if (error) throw error
setUserId(data?.user?.id || null); setUserId(data?.user?.id || null)
} catch (error) { } catch (error) {
console.error("Error fetching user:", error); console.error("Error fetching user:", error)
} finally { } finally {
setIsLoadingUserId(false); setIsLoadingUserId(false)
}
} }
};
fetchUserId(); fetchUserId()
}, []); }, [])
// Fetch user profile data // Fetch user profile data
const { const {
@ -65,104 +53,78 @@ const useUserProfile = () => {
} = useQuery({ } = useQuery({
queryKey: ["profile", userId], queryKey: ["profile", userId],
queryFn: async () => { queryFn: async () => {
if (!userId) throw new Error("No user id"); if (!userId) throw new Error("No user id")
return getProfile(userId); return getProfile(userId)
}, },
enabled: !!userId, enabled: !!userId,
staleTime: 1000 * 60 * 5, // 5 minutes staleTime: 1000 * 60 * 5, // 5 minutes
}); })
return { return {
userId, userId,
profileData: profileData?.data, profileData: profileData?.data,
isLoading: isLoadingUserId || isLoadingProfile, isLoading: isLoadingUserId || isLoadingProfile,
error: profileError, error: profileError,
}; }
}; }
const runImagePipeline = async ( const runImagePipeline = async (imageBase64: string, imageType: string, userId: string) => {
imageBase64: string, const imageUri = await uploadImageToSupabase(imageBase64, imageType, userId)
imageType: string, const genAIResult = await callGenAIonImage(imageUri)
userId: string if (genAIResult.error) throw genAIResult.error
) => { const { data: genAIResultData } = genAIResult
const imageUri = await uploadImageToSupabase(imageBase64, imageType, userId); if (!genAIResultData) throw new Error("GenAI result is null")
const genAIResult = await callGenAIonImage(imageUri); await insertGenAIResult(genAIResultData, userId, imageUri)
if (genAIResult.error) throw genAIResult.error; }
const { data: genAIResultData } = genAIResult;
if (!genAIResultData) throw new Error("GenAI result is null");
await insertGenAIResult(genAIResultData, userId, imageUri);
};
const processImage = async ( const processImage = async (asset: ImagePicker.ImagePickerAsset, userId: string) => {
asset: ImagePicker.ImagePickerAsset,
userId: string
) => {
const base64 = await FileSystem.readAsStringAsync(asset.uri, { const base64 = await FileSystem.readAsStringAsync(asset.uri, {
encoding: "base64", encoding: "base64",
}); })
const imageType = asset.mimeType || "image/jpeg"; const imageType = asset.mimeType || "image/jpeg"
await runImagePipeline(base64, imageType, userId); await runImagePipeline(base64, imageType, userId)
}; }
const navigateToFoodDetail = (foodId: string) => { const navigateToFoodDetail = (foodId: string) => {
router.push({ pathname: "/food/[id]", params: { id: foodId } }); router.push({ pathname: "/food/[id]", params: { id: foodId } })
}; }
export default function HomeScreen() { export default function HomeScreen() {
const [imageProcessing, setImageProcessing] = useState(false); const [imageProcessing, setImageProcessing] = useState(false)
const [searchQuery, setSearchQuery] = useState(""); const { profileData } = useUserProfile()
const { data: foodsData = [], isLoading: isLoadingFoods, error: foodsError } = useFoodsQuery()
const { profileData } = useUserProfile();
const {
data: foodsData = [],
isLoading: isLoadingFoods,
error: foodsError,
} = useFoodsQuery();
const handleImageSelection = async ( const handleImageSelection = async (
pickerFn: pickerFn: typeof ImagePicker.launchCameraAsync | typeof ImagePicker.launchImageLibraryAsync,
| typeof ImagePicker.launchCameraAsync
| typeof ImagePicker.launchImageLibraryAsync
) => { ) => {
const result = await pickerFn({ const result = await pickerFn({
mediaTypes: ["images"], mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true, allowsEditing: true,
aspect: [1, 1], aspect: [1, 1],
quality: 1, quality: 1,
}); })
if (!result.canceled) { if (!result.canceled) {
setImageProcessing(true); setImageProcessing(true)
try { try {
const { data, error } = await supabase.auth.getUser(); const { data, error } = await supabase.auth.getUser()
if (error || !data?.user?.id) throw new Error("Cannot get user id"); if (error || !data?.user?.id) throw new Error("Cannot get user id")
const userId = data.user.id; const userId = data.user.id
await processImage(result.assets[0], userId); await processImage(result.assets[0], userId)
} catch (err) { } catch (err) {
Alert.alert( Alert.alert("Image Processing Failed", (err as Error).message || "Unknown error")
"Image Processing Failed",
(err as Error).message || "Unknown error"
);
} finally { } finally {
setImageProcessing(false); setImageProcessing(false)
} }
router.push({ router.push({
pathname: "/profile", pathname: "/profile",
}); })
}
} }
};
const filteredFoods = useMemo(() => {
return searchQuery
? foodsData.filter((food) =>
food.name.toLowerCase().includes(searchQuery.toLowerCase())
)
: foodsData;
}, [foodsData, searchQuery]);
// Get username or fallback to a default greeting // Get username or fallback to a default greeting
const username = profileData?.username || profileData?.full_name || "Chef"; const username = profileData?.username || profileData?.full_name || "Chef"
const greeting = `Hi! ${username}`; const greeting = `Hi! ${username}`
return ( return (
<SafeAreaView className="flex-1 bg-white"> <SafeAreaView className="flex-1 bg-white">
@ -189,29 +151,18 @@ export default function HomeScreen() {
alignItems: "center", alignItems: "center",
}} }}
> >
<Text <Text style={{ fontSize: 18, fontWeight: "bold", marginBottom: 12 }}>Processing image...</Text>
style={{ fontSize: 18, fontWeight: "bold", marginBottom: 12 }}
>
Processing image...
</Text>
<View style={{ marginBottom: 8 }}> <View style={{ marginBottom: 8 }}>
<FontAwesome <FontAwesome name="spinner" size={36} color="#ffd60a" style={{}} />
name="spinner"
size={36}
color="#ffd60a"
style={{}}
/>
</View> </View>
<Text style={{ color: "#888" }}>Please wait</Text> <Text style={{ color: "#888" }}>Please wait</Text>
</View> </View>
</View> </View>
)} )}
<View className="flex-row justify-between items-center px-6 pt-4 pb-2"> {/* Header with greeting only (settings button removed) */}
<View className="px-6 pt-4 pb-2">
<Text className="text-3xl font-bold">{greeting}</Text> <Text className="text-3xl font-bold">{greeting}</Text>
<View className="bg-[#ffd60a] p-3 rounded-lg">
<Ionicons name="settings-outline" size={24} color="black" />
</View>
</View> </View>
<ScrollView <ScrollView
@ -221,24 +172,12 @@ export default function HomeScreen() {
> >
{/* Main content container with consistent padding */} {/* Main content container with consistent padding */}
<View className="px-6"> <View className="px-6">
{/* "Show your dishes" section */} {/* "Show your dishes" section - Search bar removed */}
<View className="mb-6"> <View className="mb-6">
<View className="flex-row items-center mb-4"> <View className="flex-row items-center mb-4">
<Text className="mr-2 text-2xl font-bold">Show your dishes</Text> <Text className="mr-2 text-2xl font-bold">Show your dishes</Text>
<Feather name="wifi" size={20} color="black" /> <Feather name="wifi" size={20} color="black" />
</View> </View>
<View className="flex-row items-center px-4 py-3 mb-6 bg-white border border-gray-300 rounded-full">
<TextInput
className="flex-1"
placeholder="Search..."
value={searchQuery}
onChangeText={setSearchQuery}
/>
<View className="bg-[#ffd60a] p-2 rounded-full">
<Feather name="send" size={20} color="black" />
</View>
</View>
</View> </View>
{/* Upload feature section */} {/* Upload feature section */}
@ -247,49 +186,35 @@ export default function HomeScreen() {
<TouchableOpacity <TouchableOpacity
className="bg-[#ffd60a] p-4 rounded-xl w-[48%]" className="bg-[#ffd60a] p-4 rounded-xl w-[48%]"
onPress={async () => { onPress={async () => {
const { status } = const { status } = await ImagePicker.requestCameraPermissionsAsync()
await ImagePicker.requestCameraPermissionsAsync();
if (status !== "granted") { if (status !== "granted") {
Alert.alert( Alert.alert("Permission needed", "Please grant camera permissions.")
"Permission needed", return
"Please grant camera permissions."
);
return;
} }
await handleImageSelection(ImagePicker.launchCameraAsync); await handleImageSelection(ImagePicker.launchCameraAsync)
}} }}
> >
<View className="items-center"> <View className="items-center">
<FontAwesome name="camera" size={24} color="black" /> <FontAwesome name="camera" size={24} color="black" />
<Text className="mt-2 text-lg font-bold">From Camera</Text> <Text className="mt-2 text-lg font-bold">From Camera</Text>
<Text className="text-sm text-gray-700"> <Text className="text-sm text-gray-700">Straight from Camera</Text>
Straight from Camera
</Text>
</View> </View>
</TouchableOpacity> </TouchableOpacity>
<TouchableOpacity <TouchableOpacity
className="bg-[#f9be25] p-4 rounded-xl w-[48%]" className="bg-[#f9be25] p-4 rounded-xl w-[48%]"
onPress={async () => { onPress={async () => {
const { status } = const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync()
await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== "granted") { if (status !== "granted") {
Alert.alert( Alert.alert("Permission needed", "Please grant gallery permissions.")
"Permission needed", return
"Please grant gallery permissions."
);
return;
} }
await handleImageSelection( await handleImageSelection(ImagePicker.launchImageLibraryAsync)
ImagePicker.launchImageLibraryAsync
);
}} }}
> >
<View className="items-center"> <View className="items-center">
<Feather name="image" size={24} color="black" /> <Feather name="image" size={24} color="black" />
<Text className="mt-2 text-lg font-bold">From Gallery</Text> <Text className="mt-2 text-lg font-bold">From Gallery</Text>
<Text className="text-sm text-gray-700"> <Text className="text-sm text-gray-700">Straight from Gallery</Text>
Straight from Gallery
</Text>
</View> </View>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
@ -297,66 +222,68 @@ export default function HomeScreen() {
{/* Highlights section */} {/* Highlights section */}
<View className="mb-8"> <View className="mb-8">
<View className="flex-row items-center mb-4"> <View className="flex-row items-center justify-between mb-4">
<View className="flex-row items-center">
<Text className="mr-2 text-2xl font-bold">Highlights</Text> <Text className="mr-2 text-2xl font-bold">Highlights</Text>
<Ionicons name="star-outline" size={20} color="#bb0718" /> <Ionicons name="star-outline" size={20} color="#bb0718" />
</View> </View>
<TouchableOpacity onPress={() => router.push("/recipes")}>
<Text className="text-[#bb0718] font-medium">See All</Text>
</TouchableOpacity>
</View>
{isLoadingFoods ? ( {isLoadingFoods ? (
<Text className="text-center text-gray-500"> <View className="items-center justify-center py-8">
Loading highlights... <FontAwesome name="spinner" size={24} color="#ffd60a" />
</Text> <Text className="text-center text-gray-500 mt-2">Loading highlights...</Text>
</View>
) : foodsError ? ( ) : foodsError ? (
<Text className="text-center text-red-600"> <View className="items-center justify-center py-8">
Failed to load highlights <Feather name="alert-circle" size={24} color="#bb0718" />
</Text> <Text className="text-center text-red-600 mt-2">Failed to load highlights</Text>
) : filteredFoods.length === 0 ? ( </View>
<Text className="text-center text-gray-400"> ) : foodsData.length === 0 ? (
No highlights available <View className="items-center justify-center py-8">
</Text> <Feather name="coffee" size={24} color="#888" />
<Text className="text-center text-gray-400 mt-2">No highlights available</Text>
</View>
) : ( ) : (
<View className="flex-row justify-between"> <View className="flex-row flex-wrap justify-between">
{filteredFoods.map((food, idx) => ( {foodsData.map((food, idx) => (
<TouchableOpacity <TouchableOpacity
key={food.id} key={food.id}
className="flex-1 mr-4 bg-white shadow-sm rounded-xl" className="bg-[#f8f8f8] p-4 rounded-xl w-[48%] mb-4"
style={{
marginRight: idx === filteredFoods.length - 1 ? 0 : 12,
}}
onPress={() => navigateToFoodDetail(food.id)} onPress={() => navigateToFoodDetail(food.id)}
> >
<View className="items-center">
{food.image_url ? ( {food.image_url ? (
<Image <Image
source={{ uri: food.image_url }} source={{ uri: food.image_url }}
className="w-full h-32 rounded-t-xl" style={{ width: 60, height: 60, borderRadius: 30 }}
resizeMode="cover" resizeMode="cover"
/> />
) : ( ) : (
<View className="items-center justify-center w-full h-32 bg-gray-200 rounded-t-xl"> <View
<Text className="text-gray-400">No Image</Text> style={{
width: 60,
height: 60,
borderRadius: 30,
backgroundColor: "#e0e0e0",
justifyContent: "center",
alignItems: "center",
}}
>
<Feather name="image" size={24} color="#bbb" />
</View> </View>
)} )}
<View className="justify-between flex-1 p-3"> <Text className="mt-2 text-lg font-bold text-center" numberOfLines={1}>
<Text
className="text-base font-bold text-[#333] mb-1"
numberOfLines={1}
>
{food.name} {food.name}
</Text> </Text>
<Text <View className="flex-row items-center mt-1">
className="text-sm text-[#666] mb-2" <Feather name="clock" size={14} color="#666" />
numberOfLines={1} <Text className="text-sm text-gray-700 ml-1">
> {food.time_to_cook_minutes ? `${food.time_to_cook_minutes} min` : "-"}
{food.description || "No description"}
</Text> </Text>
<View className="flex-row justify-between">
<View className="flex-row items-center">
<IconSymbol name="clock" size={12} color="#666" />
<Text className="text-xs text-[#666] ml-1">
{food.time_to_cook_minutes
? `${food.time_to_cook_minutes} min`
: "-"}
</Text>
</View>
</View> </View>
</View> </View>
</TouchableOpacity> </TouchableOpacity>
@ -370,5 +297,5 @@ export default function HomeScreen() {
<View className="h-20"></View> <View className="h-20"></View>
</ScrollView> </ScrollView>
</SafeAreaView> </SafeAreaView>
); )
} }

View File

@ -1,23 +1,29 @@
"use client"; "use client"
import { supabase } from "@/services/supabase"
import RecipeHighlightCard from "@/components/RecipeHighlightCard"; import { Feather } from "@expo/vector-icons"
import { supabase } from "@/services/supabase"; import { useQuery } from "@tanstack/react-query"
import { useQuery } from "@tanstack/react-query"; import { router } from "expo-router"
import { router } from "expo-router"; import { useState, useEffect } from "react"
import { ActivityIndicator, ScrollView, Text, View } from "react-native"; import { ActivityIndicator, ScrollView, Text, View, TextInput, TouchableOpacity, Image, Dimensions } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"; import { SafeAreaView } from "react-native-safe-area-context"
interface Recipe { interface Recipe {
id: number; id: number
name: string; name: string
description: string; description: string
image_url: string; image_url: string
created_by: string; created_by: string
is_shared: boolean; is_shared: boolean
time_to_cook_minutes?: number; time_to_cook_minutes?: number
} }
const { width } = Dimensions.get("window")
const cardWidth = (width - 32) / 2 // 2 cards per row with 16px padding on each side
export default function RecipesScreen() { export default function RecipesScreen() {
const [searchQuery, setSearchQuery] = useState("")
const [filteredRecipes, setFilteredRecipes] = useState<Recipe[]>([])
const { const {
data: allRecipes, data: allRecipes,
isLoading: isAllLoading, isLoading: isAllLoading,
@ -29,63 +35,123 @@ export default function RecipesScreen() {
.from("foods") .from("foods")
.select("*") .select("*")
.eq("is_shared", true) .eq("is_shared", true)
.order("created_at", { ascending: false }); .order("created_at", { ascending: false })
if (error) throw error; if (error) throw error
return data ?? []; return data ?? []
}, },
staleTime: 1000 * 60, staleTime: 1000 * 60,
}); })
const recipes: Recipe[] = allRecipes || []; // Filter recipes based on search query
const loading = isAllLoading; useEffect(() => {
const error = allError; if (!allRecipes) return
if (!searchQuery.trim()) {
setFilteredRecipes(allRecipes)
return
}
const filtered = allRecipes.filter((recipe) => recipe.name.toLowerCase().includes(searchQuery.toLowerCase()))
setFilteredRecipes(filtered)
}, [searchQuery, allRecipes])
const recipes: Recipe[] = filteredRecipes || []
const loading = isAllLoading
const error = allError
if (loading) { if (loading) {
return ( return (
<SafeAreaView className="flex-1 bg-white items-center justify-center"> <SafeAreaView className="flex-1 bg-white items-center justify-center">
<ActivityIndicator size="large" color="#FFCC00" /> <ActivityIndicator size="large" color="#bb0718" />
<Text className="mt-4 text-gray-600">Loading recipes...</Text>
</SafeAreaView> </SafeAreaView>
); )
} }
if (error) { if (error) {
return ( return (
<SafeAreaView className="flex-1 bg-white items-center justify-center"> <SafeAreaView className="flex-1 bg-white items-center justify-center px-4">
<Text className="text-lg text-red-600">Failed to load recipes</Text> <Feather name="alert-circle" size={48} color="#bb0718" />
<Text className="text-lg text-red-600 mt-4 text-center">Failed to load recipes</Text>
<TouchableOpacity className="mt-6 bg-[#ffd60a] px-6 py-3 rounded-full" onPress={() => router.push("/home")}>
<Text className="font-bold text-[#bb0718]">Go back to home</Text>
</TouchableOpacity>
</SafeAreaView> </SafeAreaView>
); )
} }
return ( return (
<SafeAreaView className="flex-1 bg-white" edges={["top"]}> <SafeAreaView className="flex-1 bg-white" edges={["top"]}>
<Text className="text-2xl font-bold text-[#bb0718] mx-4 mt-6 mb-4"> <View className="px-4 pt-4 pb-2">
All Recipes <Text className="text-2xl font-bold text-[#bb0718] mb-4">All Recipes</Text>
</Text>
<ScrollView className="flex-1"> {/* Search Bar */}
<View className="flex-row flex-wrap px-2 pb-8"> <View className="flex-row items-center bg-gray-100 rounded-full px-4 py-2 mb-4">
<Feather name="search" size={20} color="#bb0718" />
<TextInput
className="flex-1 ml-2 text-base"
placeholder="Search recipes..."
value={searchQuery}
onChangeText={setSearchQuery}
/>
{searchQuery.length > 0 && (
<TouchableOpacity onPress={() => setSearchQuery("")}>
<Feather name="x" size={20} color="#666" />
</TouchableOpacity>
)}
</View>
</View>
<ScrollView className="flex-1" showsVerticalScrollIndicator={false}>
<View className="flex-row flex-wrap px-4 pb-8">
{recipes.length === 0 ? ( {recipes.length === 0 ? (
<View className="w-full items-center mt-10"> <View className="w-full items-center justify-center py-16">
<Text className="text-gray-500">No recipes found.</Text> <Feather name="book-open" size={64} color="#e0e0e0" />
<Text className="text-gray-500 mt-4 text-center">
{searchQuery.trim() ? `No recipes found for "${searchQuery}"` : "No recipes available."}
</Text>
</View> </View>
) : ( ) : (
recipes.map((item, idx) => ( recipes.map((item) => (
<View key={item.id} className="w-1/2 p-2"> <View key={item.id} className="w-1/2 p-2">
<RecipeHighlightCard <TouchableOpacity
recipe={{ className="bg-white rounded-xl overflow-hidden shadow-sm border border-gray-100"
id: item.id, onPress={() => router.push(`/food/${item.id}`)}
name: item.name, activeOpacity={0.7}
description: item.description, >
image_url: item.image_url, <View className="w-full h-32 bg-gray-200">
time_to_cook_minutes: item.time_to_cook_minutes, {item.image_url ? (
}} <Image
onPress={() => { source={{ uri: item.image_url }}
router.push(`/food/${item.id}`); className="w-full h-full"
}} style={{ resizeMode: "cover" }}
/> />
) : (
<View className="w-full h-full items-center justify-center">
<Feather name="image" size={32} color="#ccc" />
</View>
)}
</View>
<View className="p-3">
<Text className="font-bold text-gray-800 mb-1" numberOfLines={1}>
{item.name}
</Text>
<Text className="text-xs text-gray-500 mb-2" numberOfLines={2}>
{item.description || "No description available"}
</Text>
{item.time_to_cook_minutes !== undefined && (
<View className="flex-row items-center">
<Feather name="clock" size={12} color="#bb0718" />
<Text className="text-xs text-gray-600 ml-1">{item.time_to_cook_minutes} min</Text>
</View>
)}
</View>
</TouchableOpacity>
</View> </View>
)) ))
)} )}
</View> </View>
</ScrollView> </ScrollView>
</SafeAreaView> </SafeAreaView>
); )
} }