fix: add photo in recipes page

This commit is contained in:
Tantikon Phasanphaengsi 2025-05-12 22:10:58 +07:00
parent 2aafebc323
commit ae53b78ba6
3 changed files with 248 additions and 255 deletions

View File

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

View File

@ -1,23 +1,29 @@
"use client";
import RecipeHighlightCard from "@/components/RecipeHighlightCard";
import { supabase } from "@/services/supabase";
import { useQuery } from "@tanstack/react-query";
import { router } from "expo-router";
import { ActivityIndicator, ScrollView, Text, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
"use client"
import { supabase } from "@/services/supabase"
import { Feather } from "@expo/vector-icons"
import { useQuery } from "@tanstack/react-query"
import { router } from "expo-router"
import { useState, useEffect } from "react"
import { ActivityIndicator, ScrollView, Text, View, TextInput, TouchableOpacity, Image, Dimensions } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
interface Recipe {
id: number;
name: string;
description: string;
image_url: string;
created_by: string;
is_shared: boolean;
time_to_cook_minutes?: number;
id: number
name: string
description: string
image_url: string
created_by: string
is_shared: boolean
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() {
const [searchQuery, setSearchQuery] = useState("")
const [filteredRecipes, setFilteredRecipes] = useState<Recipe[]>([])
const {
data: allRecipes,
isLoading: isAllLoading,
@ -29,63 +35,123 @@ export default function RecipesScreen() {
.from("foods")
.select("*")
.eq("is_shared", true)
.order("created_at", { ascending: false });
if (error) throw error;
return data ?? [];
.order("created_at", { ascending: false })
if (error) throw error
return data ?? []
},
staleTime: 1000 * 60,
});
})
const recipes: Recipe[] = allRecipes || [];
const loading = isAllLoading;
const error = allError;
// Filter recipes based on search query
useEffect(() => {
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) {
return (
<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>
);
)
}
if (error) {
return (
<SafeAreaView className="flex-1 bg-white items-center justify-center">
<Text className="text-lg text-red-600">Failed to load recipes</Text>
<SafeAreaView className="flex-1 bg-white items-center justify-center px-4">
<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>
);
)
}
return (
<SafeAreaView className="flex-1 bg-white" edges={["top"]}>
<Text className="text-2xl font-bold text-[#bb0718] mx-4 mt-6 mb-4">
All Recipes
</Text>
<ScrollView className="flex-1">
<View className="flex-row flex-wrap px-2 pb-8">
<View className="px-4 pt-4 pb-2">
<Text className="text-2xl font-bold text-[#bb0718] mb-4">All Recipes</Text>
{/* Search Bar */}
<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 ? (
<View className="w-full items-center mt-10">
<Text className="text-gray-500">No recipes found.</Text>
<View className="w-full items-center justify-center py-16">
<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>
) : (
recipes.map((item, idx) => (
recipes.map((item) => (
<View key={item.id} className="w-1/2 p-2">
<RecipeHighlightCard
recipe={{
id: item.id,
name: item.name,
description: item.description,
image_url: item.image_url,
time_to_cook_minutes: item.time_to_cook_minutes,
}}
onPress={() => {
router.push(`/food/${item.id}`);
}}
/>
<TouchableOpacity
className="bg-white rounded-xl overflow-hidden shadow-sm border border-gray-100"
onPress={() => router.push(`/food/${item.id}`)}
activeOpacity={0.7}
>
<View className="w-full h-32 bg-gray-200">
{item.image_url ? (
<Image
source={{ uri: item.image_url }}
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>
</ScrollView>
</SafeAreaView>
);
)
}