feat(whole project): huge changes, huge updates

This commit is contained in:
sankalp committed 2025-04-24 20:17:52 +05:45
1 parent 666b5bb827
commit 2bd8bb2dfc
196 files changed
+9146 -4316

No files matched your search

+58 -11
View File
@@ -1,10 +1,12 @@
import { View, Text, Image, TouchableOpacity, StyleSheet } from 'react-native'
import React from 'react'
import { View, Text, Image, TouchableOpacity, ActivityIndicator, Alert } from 'react-native'
import React, { useState } from 'react'
import { useNavigation } from '@react-navigation/native'
import { fetchProductById } from '../api'
export default function ActiveOrder({ orders = [], navigation: propNavigation }) {
// Use provided navigation prop if available, otherwise get from hook
const navigation = propNavigation || useNavigation();
const [loading, setLoading] = useState(false);
// Safe number formatting helper
const formatCurrency = (value) => {
@@ -17,6 +19,48 @@ export default function ActiveOrder({ orders = [], navigation: propNavigation })
return '0.00';
};
const handleReOrder = async (order) => {
console.log('Order data:', order);
// Use order_items as primary source, fallback to items if order_items is empty
const orderItems = (order.order_items && order.order_items.length > 0) ? order.order_items : order.items;
console.log('Order items:', orderItems);
if (!orderItems || orderItems.length === 0) {
Alert.alert('Error', 'No items found in this order');
return;
}
try {
setLoading(true);
const firstItem = orderItems[0];
console.log('First item:', firstItem);
const productId = firstItem.product || firstItem.product_id || firstItem.id;
console.log('Product ID:', productId);
if (!productId) {
Alert.alert('Error', 'Could not find product ID');
return;
}
const product = await fetchProductById(productId);
console.log('Fetched product:', product);
if (!product) {
Alert.alert('Error', 'Product not found');
return;
}
navigation.navigate('ProductDetails', { id: product.id });
} catch (error) {
console.error('Error in handleReOrder:', error);
Alert.alert('Error', 'Failed to load product details. Please try again.');
} finally {
setLoading(false);
}
};
if (!orders || orders.length === 0) {
return (
<View className="flex-1 justify-center items-center py-10">
@@ -28,7 +72,7 @@ export default function ActiveOrder({ orders = [], navigation: propNavigation })
return (
<View className={`mx-4`}>
{orders.map((order, index) => {
// Each order can have multiple items
const orderItems = (order.order_items && order.order_items.length > 0) ? order.order_items : order.items;
return (
<View key={index} className="mb-6 border rounded-lg border-gray-200 overflow-hidden">
<View className="bg-gray-100 p-3 border-b border-gray-200">
@@ -39,8 +83,8 @@ export default function ActiveOrder({ orders = [], navigation: propNavigation })
</Text>
</View>
{order.items && order.items.map((item, itemIndex) => (
<View key={itemIndex} className={`flex-row items-center gap-6 py-3 px-3 ${itemIndex < order.items.length - 1 ? 'border-b border-gray-200' : ''}`}>
{orderItems && orderItems.map((item, itemIndex) => (
<View key={itemIndex} className={`flex-row items-center gap-6 py-3 px-3 ${itemIndex < orderItems.length - 1 ? 'border-b border-gray-200' : ''}`}>
<Image
source={{ uri: item.product_image || item.product?.image || 'https://via.placeholder.com/100' }}
className="size-[90px] rounded-lg"
@@ -58,12 +102,15 @@ export default function ActiveOrder({ orders = [], navigation: propNavigation })
<View className="bg-gray-50 p-3 border-t border-gray-200 flex-row justify-between items-center">
<Text className="font-bold">Total: ${formatCurrency(order.total_price || order.total_amount)}</Text>
<TouchableOpacity
onPress={() => navigation.navigate('Track Order', { orderId: order.id })}
className={`bg-primary rounded-full px-4 py-2`}
>
<Text className={`text-white font-medium`}>Track Order</Text>
</TouchableOpacity>
<View className="flex-row gap-2">
<TouchableOpacity
onPress={() => navigation.navigate('Track Order', { orderId: order.id })}
className={`bg-primary rounded-full px-4 py-2`}
>
<Text className={`text-white font-medium`}>Track Order</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
+56 -7
View File
@@ -1,10 +1,12 @@
import { View, Text, Image, TouchableOpacity } from 'react-native'
import React from 'react'
import { View, Text, Image, TouchableOpacity, ActivityIndicator, Alert } from 'react-native'
import React, { useState } from 'react'
import { useNavigation } from '@react-navigation/native'
import { fetchProductById } from '../api'
export default function CancelledOrder({ orders = [], navigation: propNavigation }) {
// Use provided navigation prop if available, otherwise get from hook
const navigation = propNavigation || useNavigation();
const [loading, setLoading] = useState(false);
// Safe number formatting helper
const formatCurrency = (value) => {
@@ -17,6 +19,48 @@ export default function CancelledOrder({ orders = [], navigation: propNavigation
return '0.00';
};
const handleReOrder = async (order) => {
console.log('Order data:', order);
// Use order_items as primary source, fallback to items if order_items is empty
const orderItems = (order.order_items && order.order_items.length > 0) ? order.order_items : order.items;
console.log('Order items:', orderItems);
if (!orderItems || orderItems.length === 0) {
Alert.alert('Error', 'No items found in this order');
return;
}
try {
setLoading(true);
const firstItem = orderItems[0];
console.log('First item:', firstItem);
const productId = firstItem.product || firstItem.product_id || firstItem.id;
console.log('Product ID:', productId);
if (!productId) {
Alert.alert('Error', 'Could not find product ID');
return;
}
const product = await fetchProductById(productId);
console.log('Fetched product:', product);
if (!product) {
Alert.alert('Error', 'Product not found');
return;
}
navigation.navigate('ProductDetails', { id: product.id });
} catch (error) {
console.error('Error in handleReOrder:', error);
Alert.alert('Error', 'Failed to load product details. Please try again.');
} finally {
setLoading(false);
}
};
if (!orders || orders.length === 0) {
return (
<View className="flex-1 justify-center items-center py-10">
@@ -28,7 +72,7 @@ export default function CancelledOrder({ orders = [], navigation: propNavigation
return (
<View className={`mx-4`}>
{orders.map((order, index) => {
// Each order can have multiple items
const orderItems = (order.order_items && order.order_items.length > 0) ? order.order_items : order.items;
return (
<View key={index} className="mb-6 border rounded-lg border-gray-200 overflow-hidden">
<View className="bg-gray-100 p-3 border-b border-gray-200">
@@ -39,8 +83,8 @@ export default function CancelledOrder({ orders = [], navigation: propNavigation
</Text>
</View>
{order.items && order.items.map((item, itemIndex) => (
<View key={itemIndex} className={`flex-row items-center gap-6 py-3 px-3 ${itemIndex < order.items.length - 1 ? 'border-b border-gray-200' : ''}`}>
{orderItems && orderItems.map((item, itemIndex) => (
<View key={itemIndex} className={`flex-row items-center gap-6 py-3 px-3 ${itemIndex < orderItems.length - 1 ? 'border-b border-gray-200' : ''}`}>
<Image
source={{ uri: item.product_image || item.product?.image || 'https://via.placeholder.com/100' }}
className="size-[90px] rounded-lg"
@@ -59,10 +103,15 @@ export default function CancelledOrder({ orders = [], navigation: propNavigation
<View className="bg-gray-50 p-3 border-t border-gray-200 flex-row justify-between items-center">
<Text className="font-bold">Total: ${formatCurrency(order.total_price || order.total_amount)}</Text>
<TouchableOpacity
onPress={() => navigation.navigate('Home')}
onPress={() => handleReOrder(order)}
className={`bg-primary rounded-full px-4 py-2`}
disabled={loading}
>
<Text className={`text-white font-medium`}>Re-Order</Text>
{loading ? (
<ActivityIndicator color="white" />
) : (
<Text className={`text-white font-medium`}>Re-Order</Text>
)}
</TouchableOpacity>
</View>
</View>
+34 -33
View File
@@ -34,44 +34,45 @@ export default function Category({ categories = [] }) {
image: "https://cdn-icons-png.flaticon.com/512/2934/2934315.png"
}
]
const handleCategoryPress = (category) => {
// Ensure we have a valid category ID
if (!category.id || isNaN(parseInt(category.id))) {
console.error('Invalid category ID:', category.id);
return;
}
// Navigate to the category screen with the category ID as a number
navigation.navigate('Category', {
title: category.name,
categoryId: parseInt(category.id)
});
};
return (
<View className=" flex-col gap-4 mb-6">
<View className="flex-row justify-between items-center px-1 mx-4" >
<Text className="text-xl font-semibold">Category</Text>
<Text className="text-secondary font-medium">See All</Text>
</View>
<View className="flex-1">
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
className="ml-4"
className="flex-row gap-4"
>
{
displayCategories.map((item, index) => {
return (
<TouchableOpacity
key={item.id}
onPress={() => {
navigation.navigate('Category', {
categoryId: item.id,
title: item.name
})
}}
className={`${index + 1 == displayCategories.length ? "mr-4" : " mr-4"} flex-col items-center gap-2`}
>
<View className="bg-secondary flex justify-center items-center rounded-full" style={{ height: hp('8%'), width: hp('8%') }}>
<Image
source={{ uri: item.image }}
className="size-10"
style={{ width: hp('6%'), height: hp('6%'), borderRadius: 30 }}
/>
</View>
<Text className="text-center">{item.name}</Text>
</TouchableOpacity>
)
})
}
{displayCategories.map((category, index) => (
<TouchableOpacity
key={category.id || index}
onPress={() => handleCategoryPress(category)}
className="items-center"
>
<View className="rounded-full p-4 bg-gray-100">
<Image
source={{ uri: category.image }}
style={{ width: wp(12), height: wp(12) }}
className="rounded-full"
/>
</View>
<Text className="text-sm font-medium mt-2">{category.name}</Text>
</TouchableOpacity>
))}
</ScrollView>
</View>
)
);
}
+109 -11
View File
@@ -1,10 +1,12 @@
import { View, Text, Image, TouchableOpacity } from 'react-native'
import React from 'react'
import { View, Text, Image, TouchableOpacity, ActivityIndicator, Alert } from 'react-native'
import React, { useState } from 'react'
import { useNavigation } from '@react-navigation/native'
import { fetchProductById } from '../api'
export default function CompletedOrder({ orders = [], navigation: propNavigation }) {
// Use provided navigation prop if available, otherwise get from hook
const navigation = propNavigation || useNavigation();
const [loading, setLoading] = useState(false);
// Safe number formatting helper
const formatCurrency = (value) => {
@@ -17,6 +19,95 @@ export default function CompletedOrder({ orders = [], navigation: propNavigation
return '0.00';
};
const handleReOrder = async (order) => {
console.log('Order data:', order);
// Use order_items as primary source, fallback to items if order_items is empty
const orderItems = (order.order_items && order.order_items.length > 0) ? order.order_items : order.items;
console.log('Order items:', orderItems);
if (!orderItems || orderItems.length === 0) {
Alert.alert('Error', 'No items found in this order');
return;
}
try {
setLoading(true);
const firstItem = orderItems[0];
console.log('First item:', firstItem);
const productId = firstItem.product || firstItem.product_id || firstItem.id;
console.log('Product ID:', productId);
if (!productId) {
Alert.alert('Error', 'Could not find product ID');
return;
}
const product = await fetchProductById(productId);
console.log('Fetched product:', product);
if (!product) {
Alert.alert('Error', 'Product not found');
return;
}
navigation.navigate('ProductDetails', { id: product.id });
} catch (error) {
console.error('Error in handleReOrder:', error);
Alert.alert('Error', 'Failed to load product details. Please try again.');
} finally {
setLoading(false);
}
};
const handleLeaveReview = async (order) => {
console.log('Order data for review:', order);
// Use order_items as primary source, fallback to items if order_items is empty
const orderItems = (order.order_items && order.order_items.length > 0) ? order.order_items : order.items;
console.log('Order items for review:', orderItems);
if (!orderItems || orderItems.length === 0) {
Alert.alert('Error', 'No items found in this order');
return;
}
try {
setLoading(true);
const firstItem = orderItems[0];
console.log('First item for review:', firstItem);
const productId = firstItem.product || firstItem.product_id || firstItem.id;
console.log('Product ID for review:', productId);
if (!productId) {
Alert.alert('Error', 'Could not find product ID');
return;
}
const product = await fetchProductById(productId);
console.log('Fetched product for review:', product);
if (!product) {
Alert.alert('Error', 'Product not found');
return;
}
navigation.navigate('Leave Review', {
productId: product.id,
productName: product.name,
productImage: product.image,
orderId: order.id
});
} catch (error) {
console.error('Error in handleLeaveReview:', error);
Alert.alert('Error', 'Failed to load product details. Please try again.');
} finally {
setLoading(false);
}
};
if (!orders || orders.length === 0) {
return (
<View className="flex-1 justify-center items-center py-10">
@@ -28,7 +119,7 @@ export default function CompletedOrder({ orders = [], navigation: propNavigation
return (
<View className={`mx-4`}>
{orders.map((order, index) => {
// Each order can have multiple items
const orderItems = (order.order_items && order.order_items.length > 0) ? order.order_items : order.items;
return (
<View key={index} className="mb-6 border rounded-lg border-gray-200 overflow-hidden">
<View className="bg-gray-100 p-3 border-b border-gray-200">
@@ -39,8 +130,8 @@ export default function CompletedOrder({ orders = [], navigation: propNavigation
</Text>
</View>
{order.items && order.items.map((item, itemIndex) => (
<View key={itemIndex} className={`flex-row items-center gap-6 py-3 px-3 ${itemIndex < order.items.length - 1 ? 'border-b border-gray-200' : ''}`}>
{orderItems && orderItems.map((item, itemIndex) => (
<View key={itemIndex} className={`flex-row items-center gap-6 py-3 px-3 ${itemIndex < orderItems.length - 1 ? 'border-b border-gray-200' : ''}`}>
<Image
source={{ uri: item.product_image || item.product?.image || 'https://via.placeholder.com/100' }}
className="size-[90px] rounded-lg"
@@ -58,12 +149,19 @@ export default function CompletedOrder({ orders = [], navigation: propNavigation
<View className="bg-gray-50 p-3 border-t border-gray-200 flex-row justify-between items-center">
<Text className="font-bold">Total: ${formatCurrency(order.total_price || order.total_amount)}</Text>
<TouchableOpacity
onPress={() => navigation.navigate('Leave Review')}
className={`bg-primary rounded-full px-4 py-2`}
>
<Text className={`text-white font-medium`}>Leave Review</Text>
</TouchableOpacity>
<View className="flex-row gap-2">
<TouchableOpacity
onPress={() => handleLeaveReview(order)}
className={`bg-primary rounded-full px-4 py-2`}
disabled={loading}
>
{loading ? (
<ActivityIndicator color="white" />
) : (
<Text className={`text-white font-medium`}>Leave Review</Text>
)}
</TouchableOpacity>
</View>
</View>
</View>
);
+163 -59
View File
@@ -1,68 +1,172 @@
import { View, Text } from 'react-native'
import React from 'react'
import { View, Text, Animated, ActivityIndicator, Linking } from 'react-native'
import React, { useState, useRef, useEffect } from 'react'
import { TouchableOpacity } from 'react-native'
import { ChevronDownIcon, ChevronUpIcon, GlobeAltIcon } from 'react-native-heroicons/outline'
import Icon from 'react-native-vector-icons/FontAwesome6';
import Icon from 'react-native-vector-icons/FontAwesome6'
import { getContacts } from '../api'
export default function ContactUsCenter() {
const [contacts, setContacts] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [expandedItems, setExpandedItems] = useState({})
const animations = useRef({})
useEffect(() => {
fetchContacts()
}, [])
const fetchContacts = async () => {
try {
setLoading(true)
const data = await getContacts()
setContacts(data)
// Initialize expanded state and animations
const initialExpandedState = {}
data.forEach(contact => {
initialExpandedState[contact.id] = contact.contact_type === 'whatsapp'
animations.current[contact.id] = new Animated.Value(contact.contact_type === 'whatsapp' ? 1 : 0)
})
setExpandedItems(initialExpandedState)
} catch (err) {
setError('Failed to load contacts')
console.error('Error fetching contacts:', err)
} finally {
setLoading(false)
}
}
const toggleItem = (itemId) => {
const isExpanded = !expandedItems[itemId]
setExpandedItems(prev => ({
...prev,
[itemId]: isExpanded
}))
Animated.timing(animations.current[itemId], {
toValue: isExpanded ? 1 : 0,
duration: 300,
useNativeDriver: false,
}).start()
}
const handleContactPress = async (contact) => {
try {
let url = '';
switch (contact.contact_type) {
case 'whatsapp':
// Remove any non-numeric characters from the phone number
const phoneNumber = contact.value.replace(/\D/g, '');
url = `https://wa.me/${phoneNumber}`;
break;
case 'website':
url = contact.value.startsWith('http') ? contact.value : `https://${contact.value}`;
break;
case 'facebook':
url = `https://facebook.com/${contact.value.replace('@', '')}`;
break;
case 'instagram':
url = `https://instagram.com/${contact.value.replace('@', '')}`;
break;
case 'twitter':
url = `https://twitter.com/${contact.value.replace('@', '')}`;
break;
case 'customer_service':
// For phone numbers, use tel: protocol
const telNumber = contact.value.replace(/\D/g, '');
url = `tel:${telNumber}`;
break;
default:
return;
}
const supported = await Linking.canOpenURL(url);
if (supported) {
await Linking.openURL(url);
} else {
console.error(`Don't know how to open URL: ${url}`);
}
} catch (error) {
console.error('Error opening URL:', error);
}
}
const getIcon = (contactType) => {
switch (contactType) {
case 'customer_service':
return <Icon name='headset' color="#704f38" size={25} />
case 'whatsapp':
return <Icon name='whatsapp' color="#704f38" size={25} />
case 'website':
return <GlobeAltIcon color="#704f38" size={26} />
case 'facebook':
return <Icon name='facebook' color="#704f38" size={26} />
case 'instagram':
return <Icon name='instagram' color="#704f38" size={26} />
case 'twitter':
return <Icon name='twitter' color="#704f38" size={26} />
default:
return null
}
}
if (loading) {
return (
<View className="flex-1 justify-center items-center">
<ActivityIndicator size="large" color="#704f38" />
</View>
)
}
if (error) {
return (
<View className="flex-1 justify-center items-center">
<Text className="text-red-500">{error}</Text>
</View>
)
}
return (
<View className={` mt-4 mx-4 `}>
<View className={` flex-row items-center justify-between p-4 border rounded-xl border-gray-300 mb-3`}>
<View className={`flex-row items-center gap-4 `}>
<Icon name='headset' color={"#704f38"} size={25} />
<Text className={`text-lg font-semibold`}>Customer Service</Text>
</View>
<View className={`justify-center items-center`}>
<ChevronDownIcon color={"#704f38"} size={24} />
</View>
</View>
<View className={`border mb-3 rounded-xl border-gray-300`}>
<View className={` flex-row items-center justify-between p-4 border-b border-b-gray-300 mb-3`}>
<View className={`flex-row items-center gap-4 `}>
<Icon name='whatsapp' color={"#704f38"} size={25} />
<Text className={`text-lg font-semibold`}>WhatsApp</Text>
</View>
<View className={`justify-center items-center`}>
<ChevronUpIcon color={"#704f38"} size={24} />
<View className="mt-4 mx-4">
{contacts.map((contact) => (
<View key={contact.id} className="mb-3">
<View className="border rounded-xl border-gray-300 bg-white overflow-hidden">
<TouchableOpacity
onPress={() => toggleItem(contact.id)}
className="flex-row items-center justify-between p-4">
<View className="flex-row items-center gap-4">
{getIcon(contact.contact_type)}
<Text className="text-lg font-semibold">{contact.title}</Text>
</View>
{expandedItems[contact.id] ? (
<ChevronUpIcon color="#704f38" size={24} />
) : (
<ChevronDownIcon color="#704f38" size={24} />
)}
</TouchableOpacity>
<Animated.View
style={{
maxHeight: animations.current[contact.id].interpolate({
inputRange: [0, 1],
outputRange: [0, 1000],
}),
opacity: animations.current[contact.id],
overflow: 'hidden',
}}
>
<View className="px-4 pb-4">
<View className="h-px bg-gray-200 mb-4" />
<TouchableOpacity onPress={() => handleContactPress(contact)}>
<Text className="text-gray-500 text-base ml-9">
{contact.value}
</Text>
</TouchableOpacity>
</View>
</Animated.View>
</View>
</View>
<Text className={`p-4 text-left mx-9 text-gray-500`}>(480)555-0103</Text>
</View>
<View className={` flex-row items-center justify-between p-4 border rounded-xl border-gray-300 mb-3`}>
<View className={`flex-row items-center gap-4 `}>
<GlobeAltIcon color={"#704f38"} size={26} />
<Text className={`text-lg font-semibold`}>Website</Text>
</View>
<View className={`justify-center items-center`}>
<ChevronDownIcon color={"#704f38"} size={24} />
</View>
</View>
<View className={` flex-row items-center justify-between p-4 border rounded-xl border-gray-300 mb-3`}>
<View className={`flex-row items-center gap-4 `}>
<Icon name='facebook' color={"#704f38"} size={26} />
<Text className={`text-lg font-semibold`}>Facebook</Text>
</View>
<View className={`justify-center items-center`}>
<ChevronDownIcon color={"#704f38"} size={24} />
</View>
</View>
<View className={` flex-row items-center justify-between p-4 border rounded-xl border-gray-300 mb-3`}>
<View className={`flex-row items-center gap-4 `}>
<Icon name='instagram' color={"#704f38"} size={26} />
<Text className={`text-lg font-semibold`}>Instagram</Text>
</View>
<View className={`justify-center items-center`}>
<ChevronDownIcon color={"#704f38"} size={24} />
</View>
</View>
<View className={` flex-row items-center justify-between p-4 border rounded-xl border-gray-300 mb-3`}>
<View className={`flex-row items-center gap-4 `}>
<Icon name='twitter' color={"#704f38"} size={26} />
<Text className={`text-lg font-semibold`}>Twitter</Text>
</View>
<View className={`justify-center items-center`}>
<ChevronDownIcon color={"#704f38"} size={24} />
</View>
</View>
))}
</View>
)
}
+127 -61
View File
@@ -1,68 +1,134 @@
import { View, Text, ScrollView } from 'react-native'
import React, { useState } from 'react'
import { View, Text, ScrollView, ActivityIndicator, Animated } from 'react-native'
import React, { useState, useEffect, useRef } from 'react'
import { TouchableOpacity } from 'react-native';
import { ChevronDownIcon, ChevronUpIcon } from 'react-native-heroicons/outline';
import { getFAQs, getFAQCategories } from '../api';
export default function FaqCenter() {
const faq = ["All", "Services", "General", "Account"]
const [faqActive, setfaqActive] = useState(0);
return (
<View className={`mx-4 mt-5 `} >
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
{
faq.map((item, index) => {
let isActive = index == faqActive;
return (
<TouchableOpacity
key={index}
onPress={() => setfaqActive(index)}
className={`
border border-gray-200 bg-gray-200 px-5 mr-4 mb-4 rounded-full py-3
${isActive ? "bg-primary" : ""}
`}>
<Text className={`${isActive ? "text-white " : ""} capitalize font-bold`}>
{item}
</Text>
</TouchableOpacity>
)
})
}
</ScrollView>
<View className={`border border-gray-300 rounded-2xl mb-5`}>
<View className={`flex-row justify-between items-center p-3 border-b border-b-gray-300 `}>
<Text className={`font-semibold text-lg`}>Can i track my order's delevery status ?</Text>
<ChevronUpIcon color={"#704f38"} />
</View>
<Text className={`p-3`}>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab distinctio nihil assumenda nostrum laboriosam quo,
officia eligendi obcaecati accusamus aliquam debitis, voluptatibus excepturi consequatur expedita eius quisquam velit. Rerum, officia?</Text>
</View>
<View className={`mb-`}>
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2 `}>
<Text className={`font-semibold text-lg`}>Is there a return policy ?</Text>
<ChevronDownIcon color={"#704f38"} />
</View>
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2 `}>
<Text className={`font-semibold text-lg`}>Can i save my favorite item for later ?</Text>
<ChevronDownIcon color={"#704f38"} />
</View>
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2`}>
<Text className={`font-semibold text-lg`}>Can i share products with my friends ?</Text>
<ChevronDownIcon color={"#704f38"} />
</View>
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2`}>
<Text className={`font-semibold text-lg`}>How do i contact customer support ?</Text>
<ChevronDownIcon color={"#704f38"} />
</View>
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2`}>
<Text className={`font-semibold text-lg`}>What payment methods are accepted ?</Text>
<ChevronDownIcon color={"#704f38"} />
</View>
<View className={`flex-row justify-between items-center p-3 border rounded-2xl border-gray-300 mb-2`}>
<Text className={`font-semibold text-lg`}>How to add review ?</Text>
<ChevronDownIcon color={"#704f38"} />
</View>
</View>
const [categories, setCategories] = useState(['All', 'Services', 'General', 'Account']);
const [activeCategory, setActiveCategory] = useState('All');
const [faqs, setFaqs] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [expandedFaqs, setExpandedFaqs] = useState({});
const animations = useRef({});
useEffect(() => {
fetchCategories();
}, []);
useEffect(() => {
fetchFAQs();
}, [activeCategory]);
const fetchCategories = async () => {
try {
const data = await getFAQCategories();
setCategories(data);
} catch (err) {
console.error('Error fetching categories:', err);
}
};
const fetchFAQs = async () => {
try {
setLoading(true);
const data = await getFAQs(activeCategory);
setFaqs(data);
const initialExpandedState = {};
data.forEach(faq => {
initialExpandedState[faq.id] = false;
animations.current[faq.id] = new Animated.Value(0);
});
setExpandedFaqs(initialExpandedState);
} catch (err) {
setError('Failed to load FAQs');
console.error('Error fetching FAQs:', err);
} finally {
setLoading(false);
}
};
const toggleFaq = (faqId) => {
const isExpanded = !expandedFaqs[faqId];
setExpandedFaqs(prev => ({
...prev,
[faqId]: isExpanded
}));
Animated.timing(animations.current[faqId], {
toValue: isExpanded ? 1 : 0,
duration: 300,
useNativeDriver: false,
}).start();
};
return (
<View className="mx-4 mt-5">
<ScrollView horizontal showsHorizontalScrollIndicator={false} className="mb-4">
{categories.map((category, index) => {
const isActive = category === activeCategory;
return (
<TouchableOpacity
key={index}
onPress={() => setActiveCategory(category)}
className={`
border border-gray-200 bg-gray-200 px-5 mr-4 rounded-full py-3
${isActive ? "bg-primary" : ""}
`}>
<Text className={`${isActive ? "text-white" : ""} capitalize font-bold`}>
{category}
</Text>
</TouchableOpacity>
);
})}
</ScrollView>
{loading ? (
<ActivityIndicator size="large" color="#704f38" />
) : error ? (
<Text className="text-red-500 text-center">{error}</Text>
) : faqs.length > 0 ? (
faqs.map((faq) => (
<View key={faq.id} className="mb-4">
<View className="border rounded-2xl border-gray-300 bg-white overflow-hidden">
<TouchableOpacity
onPress={() => toggleFaq(faq.id)}
className="flex-row justify-between items-center p-4">
<Text className="font-semibold text-lg flex-1 mr-2">{faq.question}</Text>
{expandedFaqs[faq.id] ? (
<ChevronUpIcon color="#704f38" size={24} />
) : (
<ChevronDownIcon color="#704f38" size={24} />
)}
</TouchableOpacity>
<Animated.View
style={{
maxHeight: animations.current[faq.id].interpolate({
inputRange: [0, 1],
outputRange: [0, 1000],
}),
opacity: animations.current[faq.id],
overflow: 'hidden',
}}
>
<View className="px-4 pb-4">
<View className="h-px bg-gray-200 mb-4" />
<Text className="text-gray-700 leading-6 text-base">
{faq.answer}
</Text>
</View>
</Animated.View>
</View>
</View>
))
) : (
<View className="items-center justify-center py-8">
<Text className="text-gray-500 text-center text-lg">
No FAQs available for this category
</Text>
</View>
)}
</View>
)
);
}
+21 -19
View File
@@ -1,7 +1,8 @@
import { TouchableOpacity, ActivityIndicator } from 'react-native'
import React, { useState, useEffect } from 'react'
import { TouchableOpacity } from 'react-native'
import React from 'react'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import { HeartIcon } from 'react-native-heroicons/outline'
import { HeartIcon as HeartSolid } from 'react-native-heroicons/solid'
import { HeartIcon as SolidHeartIcon } from 'react-native-heroicons/solid'
import { getFavorites } from '../api'
/**
@@ -17,15 +18,7 @@ import { getFavorites } from '../api'
* @param {number} props.productId The ID of the product
* @returns {React.Component} Favorite button component
*/
export default function FavoriteButton({
isFavorite = false,
onToggleFavorite,
size = 24,
activeColor = '#ff3b30',
inactiveColor = '#000000',
style = {},
productId
}) {
const FavoriteButton = ({ isFavorite, onToggleFavorite, size = 25, style, productId }) => {
const [loading, setLoading] = useState(false);
const [favoriteState, setFavoriteState] = useState(isFavorite);
@@ -70,16 +63,25 @@ export default function FavoriteButton({
<TouchableOpacity
onPress={handlePress}
disabled={loading}
style={style}
className="justify-center items-center"
style={[
style,
{
width: wp('10%'),
height: wp('10%'),
justifyContent: 'center',
alignItems: 'center'
}
]}
>
{loading ? (
<ActivityIndicator size="small" color={activeColor} />
<ActivityIndicator size="small" color="red" />
) : favoriteState ? (
<HeartSolid size={size} color={activeColor} />
<SolidHeartIcon size={wp('6%')} color="red" />
) : (
<HeartIcon size={size} color={inactiveColor} />
<HeartIcon size={wp('6%')} color="black" />
)}
</TouchableOpacity>
)
}
);
}
export default FavoriteButton;
+103 -41
View File
@@ -2,23 +2,27 @@
// demoData //camel case ex:iAmAGoodBBoy
// demo_data // snake case ex:i_am_a_good_boy
import { View, Text, ScrollView, TouchableOpacity, Image } from 'react-native'
import React, { useEffect, useState } from 'react'
import { View, Text, ScrollView, TouchableOpacity, Image, ActivityIndicator } from 'react-native'
import React, { useEffect, useState, forwardRef } from 'react'
import MasonryList from '@react-native-seoul/masonry-list';
import flashSalesData from '../constants/flashSalesData';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import { StarIcon } from 'react-native-heroicons/solid';
import { HeartIcon } from 'react-native-heroicons/outline';
import { HeartIcon as SolidHeartIcon } from 'react-native-heroicons/solid';
import Icon from "react-native-vector-icons/FontAwesome"
import { useNavigation } from '@react-navigation/native';
import { getFavorites, toggleFavorite } from '../api';
import { getFavorites, toggleFavorite, fetchProducts } from '../api';
import TabBar from '../themes/TabBar'
import { ArrowLeftIcon, ChevronLeftIcon } from 'react-native-heroicons/outline'
const FlashSales = ({data}) => {
const FlashSales = forwardRef((props, ref) => {
const navigation = useNavigation()
const saleEnd = "2024-12-20T23:45:30";
const [endDate, setEndDate] = useState(calenderLastDate(saleEnd))
const [favorites, setFavorites] = useState([]);
const [loading, setLoading] = useState(true);
const [products, setProducts] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
const timer = setInterval(() => {
@@ -31,21 +35,28 @@ const FlashSales = ({data}) => {
return () => clearInterval(timer)
}, [saleEnd])
// Load favorites when component mounts
// Load products and favorites when component mounts
useEffect(() => {
const loadFavorites = async () => {
const loadData = async () => {
try {
setLoading(true);
const favoriteProducts = await getFavorites();
const [productsData, favoriteProducts] = await Promise.all([
fetchProducts(),
getFavorites()
]);
setProducts(productsData || []);
setFavorites(favoriteProducts || []);
setError(null);
} catch (error) {
console.error('Error loading favorites:', error);
console.error('Error loading data:', error);
setError('Failed to load products');
setProducts([]);
setFavorites([]);
} finally {
setLoading(false);
}
};
loadFavorites();
loadData();
}, []);
//Category toggle
@@ -56,8 +67,13 @@ const FlashSales = ({data}) => {
setActiveSet(item)
}
const handleFavouriteToggle = async (product) => {
const handleFavouriteToggle = async (productId) => {
try {
const product = products.find(p => p.id === productId);
if (!product) {
console.error('Product not found:', productId);
return;
}
const updatedFavorites = await toggleFavorite(product);
setFavorites(updatedFavorites || []);
} catch (error) {
@@ -66,20 +82,60 @@ const FlashSales = ({data}) => {
};
const isProductFavorited = (productId) => {
if (!Array.isArray(favorites)) return false;
return favorites.some(fav => fav.id === productId);
};
const navigateToProductDetails = (productId) => {
navigation.navigate('ProductDetails', { id: productId });
};
if (loading) {
return (
<View className="flex-1 justify-center items-center">
<Text>Loading...</Text>
<View className="flex-1 justify-center items-center bg-white">
<ActivityIndicator size="large" color="#704f38" />
</View>
);
}
if (error) {
return (
<View className="flex-1 justify-center items-center bg-white">
<Text className="text-red-500 text-lg">{error}</Text>
<TouchableOpacity
onPress={() => {
setLoading(true);
fetchProducts()
.then(data => {
setProducts(data);
setError(null);
})
.catch(err => setError(err.message || 'Failed to fetch products'))
.finally(() => setLoading(false));
}}
className="mt-4 bg-primary py-2 px-4 rounded-lg"
>
<Text className="text-white">Retry</Text>
</TouchableOpacity>
</View>
);
}
return (
<View>
<ScrollView ref={ref} className="bg-white">
<TabBar
prefix={""}
title={"Flash Sales"}
titleStyle={{
color: "black",
fontWeight: "bold",
fontSize: 20
}}
prefixStyle={{
backgroundColor: "transparent"
}}
/>
<View className="flex-row justify-between items-center px-1 mx-4 mb-4">
<Text className="text-xl font-semibold">FlashSales</Text>
{
@@ -122,25 +178,31 @@ const FlashSales = ({data}) => {
})
}
</ScrollView>
<MasonryList
data={data}
keyExtractor={(item) => item.id}
numColumns={2}
showsVerticalScrollIndicator={false}
renderItem={({ item, index }) => (
<CardItem
item={item}
index={index}
handleFavouriteToggle={() => handleFavouriteToggle(item)}
isFavourite={isProductFavorited(item.id)}
navigation={navigation}
/>
)}
className="mx-4"
/>
</View>
{products.length === 0 ? (
<View className="items-center justify-center py-20">
<Text className="text-lg text-gray-500">No products available</Text>
</View>
) : (
<MasonryList
data={products}
keyExtractor={(item) => item.id.toString()}
numColumns={2}
showsVerticalScrollIndicator={false}
renderItem={({ item, index }) => (
<CardItem
item={item}
index={index}
handleFavouriteToggle={() => handleFavouriteToggle(item.id)}
isFavourite={isProductFavorited(item.id)}
onProductPress={() => navigateToProductDetails(item.id)}
/>
)}
className="mx-4"
/>
)}
</ScrollView>
)
}
})
const calenderLastDate = (saleEnd) => {
const nowDate = new Date();
@@ -161,7 +223,8 @@ const calenderLastDate = (saleEnd) => {
}
}
const CardItem = ({ item, index, handleFavouriteToggle, isFavourite, navigation }) => {
const CardItem = ({ item, index, handleFavouriteToggle, isFavourite, onProductPress }) => {
const navigation = useNavigation();
let isEven = item.id % 2 == 0
const getRating = () => {
@@ -183,7 +246,7 @@ const CardItem = ({ item, index, handleFavouriteToggle, isFavourite, navigation
return (
<View className={`${isEven ? "pl-4" : " pr-4"} flex-col gap-3 mb-4`}>
<TouchableOpacity onPress={() => { navigation.navigate('ProductDetails',{id:item.id,}) }} className="relative">
<TouchableOpacity onPress={onProductPress} className="relative">
<Image source={{ uri: item.image }} height={hp(20)} className=" object-cover rounded-3xl" />
<TouchableOpacity
onPress={(e) => {
@@ -192,12 +255,11 @@ const CardItem = ({ item, index, handleFavouriteToggle, isFavourite, navigation
}}
className="absolute right-4 top-4 bg-white/50 p-2 rounded-full"
>
{
isFavourite ?
<Icon name='heart' size={16} color={"red"} />
:
<HeartIcon size={20} color={"white"} />
}
{isFavourite ? (
<SolidHeartIcon size={20} color="red" />
) : (
<HeartIcon size={20} color="black" />
)}
</TouchableOpacity>
</TouchableOpacity>
<View className="flex-row justify-between px-1">
+47 -11
View File
@@ -1,9 +1,43 @@
import { View, Text, Image } from 'react-native'
import { View, Text, Image, TouchableOpacity } from 'react-native'
import React, { useEffect, useState } from 'react'
import PagerView from 'react-native-pager-view';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import { useNavigation } from '@react-navigation/native';
const HomeCarousel = ({ setPage, slider }) => {
const navigation = useNavigation();
const handleShopNow = (category) => {
// Handle both category object and direct category ID
let categoryId;
let categoryName;
if (typeof category === 'object' && category !== null) {
// If category is an object
if (!category.id) {
console.error('Invalid category data:', category);
return;
}
categoryId = parseInt(category.id);
categoryName = category.name || 'Category';
} else {
// If category is a direct ID
categoryId = parseInt(category);
categoryName = 'Category';
}
if (isNaN(categoryId)) {
console.error('Invalid category ID:', category);
return;
}
// Navigate to the category screen with the category ID as a number
navigation.navigate('Category', {
title: categoryName,
categoryId: categoryId
});
};
return (
<PagerView
style={{ flex: 1 }}
@@ -19,19 +53,21 @@ const HomeCarousel = ({ setPage, slider }) => {
return (
<View key={index} className={`justify-center items-center bg-[#ece4da] mx-4 mb-3 rounded-xl flex-1`} >
<View className={`flex-row justify-between flex-1 p-4`}>
<View className={`justify-center gap-3 items- w-1/2`}>
<Text className={`capitalize font-semibold text-xl`}>{item.title}</Text>
<Text className={`capitalize text-[#797979]`}>{item.description}</Text>
<View className={`justify-center items-start`}>
<View className={`px-3 py-2 bg-primary w-fit rounded-lg`}>
<Text className={`text-white font-bold`}>Shop Now</Text>
<View style={{ width: wp('45%') }} className={`justify-center gap-3 items-start`}>
<Text style={{ fontSize: wp('5%') }} className={`capitalize font-semibold`}>{item.title}</Text>
<Text style={{ fontSize: wp('3.5%') }} className={`capitalize text-[#797979]`}>{item.description}</Text>
<TouchableOpacity
onPress={() => handleShopNow(item.category || item.category_id)}
className={`justify-center items-start`}
>
<View style={{ paddingHorizontal: wp('3%'), paddingVertical: hp('1%') }} className={`bg-primary w-fit rounded-lg`}>
<Text style={{ fontSize: wp('3.5%') }} className={`text-white font-bold`}>Shop Now</Text>
</View>
</View>
</TouchableOpacity>
</View>
<Image
source={{ uri: "https://cdn.clo3d.com/resource/images/artwork/landing/watermark_landing_sustainably_renewal_1920.png" }}
className={`w-1/2 h-full`}
style={{}}
source={{ uri: item.image_url || "https://cdn.clo3d.com/resource/images/artwork/landing/watermark_landing_sustainably_renewal_1920.png" }}
style={{ width: wp('45%'), height: hp('20%') }}
/>
</View>
</View>
+40 -20
View File
@@ -1,30 +1,50 @@
import React from 'react';
import { View, Text, Image, StyleSheet, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import { HeartIcon } from 'react-native-heroicons/outline';
import { HeartIcon as SolidHeartIcon, StarIcon } from 'react-native-heroicons/solid';
import { useNavigation } from '@react-navigation/native';
const ItemCard = ({ item, onPress, onFavoritePress, isFavourite }) => (
<View style={styles.card}>
<TouchableOpacity onPress={onPress}>
<Image source={{ uri: item.image }} style={styles.image} />
const ItemCard = ({ item, isFavorite, onToggleFavorite }) => {
const navigation = useNavigation();
return (
<TouchableOpacity
onPress={() => navigation.navigate('ProductDetails', { id: item.id })}
className="relative"
style={{ width: wp('45%') }}
>
<Image
source={{ uri: item.image || 'https://via.placeholder.com/150' }}
style={{ height: hp('20%') }}
className="object-cover rounded-3xl"
/>
<TouchableOpacity
style={styles.heartButton}
onPress={onFavoritePress}
onPress={(e) => {
e.stopPropagation();
onToggleFavorite(item);
}}
className="absolute right-4 top-4 bg-white/50 p-2 rounded-full"
>
<Icon
name={isFavourite ? "heart" : "heart-o"}
size={20}
color={isFavourite ? "#ff0000" : "#333"}
/>
{isFavorite ? (
<SolidHeartIcon size={wp('5%')} color="red" />
) : (
<HeartIcon size={wp('5%')} color="black" />
)}
</TouchableOpacity>
<View className="flex-row justify-between px-1 mt-2">
<Text style={{ fontSize: wp('3.5%') }} className="flex-1">{item.name || item.title}</Text>
<View className="flex-row gap-1">
<StarIcon size={wp('4%')} color={"orange"} />
<Text style={{ fontSize: wp('3.5%') }}>{item.rating || 0}</Text>
</View>
</View>
<View className="px-1">
<Text style={{ fontSize: wp('4%') }} className="font-medium">Rs {item.price || 0}</Text>
</View>
</TouchableOpacity>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.price}>${item.price}</Text>
<View style={styles.ratingContainer}>
<Text style={styles.rating}>{item.rating}</Text>
<Icon name="star" size={16} color="#f5a623" />
</View>
</View>
);
);
}
const styles = StyleSheet.create({
card: {
+280
View File
@@ -0,0 +1,280 @@
import { View, Text, TouchableOpacity, Alert, Modal, TextInput, FlatList, ActivityIndicator } from 'react-native'
import React, { useState, useEffect, useRef } from 'react'
import { ChevronLeftIcon, MagnifyingGlassIcon, XMarkIcon } from 'react-native-heroicons/outline'
import Icon from 'react-native-vector-icons/Ionicons'
import * as Location from 'expo-location';
import AsyncStorage from '@react-native-async-storage/async-storage';
export default function LocationModal({ visible, onClose, onLocationSelected }) {
const [isLoading, setIsLoading] = useState(false);
const [currentLocation, setCurrentLocation] = useState(null);
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState([]);
const [isSearching, setIsSearching] = useState(false);
const searchTimeoutRef = useRef(null);
const isMounted = useRef(true);
// Cleanup function to prevent memory leaks and state updates after unmount
useEffect(() => {
return () => {
isMounted.current = false;
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
};
}, []);
// Reset state when modal becomes visible
useEffect(() => {
if (visible) {
isMounted.current = true;
setSearchQuery('');
setSearchResults([]);
setIsSearching(false);
}
}, [visible]);
useEffect(() => {
if (searchQuery.length > 2) {
// Clear any existing timeout
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
// Debounce the search to prevent too many API calls
searchTimeoutRef.current = setTimeout(() => {
if (isMounted.current) {
searchLocations();
}
}, 300);
} else {
setSearchResults([]);
}
return () => {
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
};
}, [searchQuery]);
const searchLocations = async () => {
if (!isMounted.current) return;
setIsSearching(true);
try {
const response = await fetch(
`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(
searchQuery
)}&limit=10`,
{
headers: {
'Accept': 'application/json',
'User-Agent': 'ShopingApp/1.0' // Replace with your app name
}
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (!isMounted.current) return;
if (data && Array.isArray(data)) {
setSearchResults(data);
} else {
setSearchResults([]);
}
} catch (error) {
if (isMounted.current) {
console.error('Search error:', error);
if (error.message.includes('429')) {
Alert.alert('Error', 'Too many requests. Please wait a moment and try again.');
} else {
Alert.alert('Error', 'Failed to search locations. Please try again.');
}
}
} finally {
if (isMounted.current) {
setIsSearching(false);
}
}
};
const handleUseCurrentLocation = async () => {
if (!isMounted.current) return;
setIsLoading(true);
try {
const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
if (isMounted.current) {
Alert.alert('Permission Denied', 'Please enable location services to use this feature.');
}
return;
}
const location = await Location.getCurrentPositionAsync({});
const { latitude, longitude } = location.coords;
// Get address from coordinates using reverse geocoding
const [address] = await Location.reverseGeocodeAsync({
latitude,
longitude
});
if (!isMounted.current) return;
if (address) {
const locationData = {
name: 'Current Location',
address: `${address.street || ''} ${address.name || ''}, ${address.city || ''}, ${address.region || ''} ${address.postalCode || ''}`.trim(),
coordinates: { latitude, longitude }
};
await saveLocation(locationData);
onLocationSelected(locationData);
handleClose();
} else {
Alert.alert('Error', 'Could not determine your address. Please try again.');
}
} catch (error) {
if (isMounted.current) {
Alert.alert('Error', 'Failed to get your location. Please try again.');
}
} finally {
if (isMounted.current) {
setIsLoading(false);
}
}
};
const saveLocation = async (location) => {
try {
await AsyncStorage.setItem('userLocation', JSON.stringify(location));
if (isMounted.current) {
setCurrentLocation(location);
}
} catch (error) {
if (isMounted.current) {
Alert.alert('Error', 'Failed to save location. Please try again.');
}
}
};
const handleSelectLocation = (place) => {
const locationData = {
name: place.display_name.split(',')[0],
address: place.display_name,
coordinates: {
latitude: parseFloat(place.lat),
longitude: parseFloat(place.lon)
}
};
saveLocation(locationData);
onLocationSelected(locationData);
handleClose();
};
const handleClose = () => {
// Reset state before closing to improve performance
setSearchQuery('');
setSearchResults([]);
setIsSearching(false);
onClose();
};
const renderSearchResult = ({ item }) => (
<TouchableOpacity
className="py-3 px-4 border-b border-gray-100"
onPress={() => handleSelectLocation(item)}
>
<Text className="text-base font-medium">{item.display_name.split(',')[0]}</Text>
<Text className="text-sm text-gray-500">{item.display_name}</Text>
</TouchableOpacity>
);
return (
<Modal
visible={visible}
animationType="slide"
transparent={true}
onRequestClose={handleClose}
>
<View className="flex-1 bg-black/50">
<View className="flex-1 bg-white mt-20 rounded-t-3xl">
<View className="flex-row items-center justify-between p-4 border-b border-gray-200">
<TouchableOpacity onPress={handleClose}>
<ChevronLeftIcon size={30} color="black" />
</TouchableOpacity>
<Text className="text-xl font-bold">Select Location</Text>
<View style={{ width: 30 }} />
</View>
<View className="flex-1 p-4">
{/* Search Bar */}
<View className="flex-row items-center border border-gray-300 rounded-xl px-3 mb-4">
<MagnifyingGlassIcon size={20} color="gray" />
<TextInput
className="flex-1 py-3 px-2 text-base"
placeholder="Search for a location"
value={searchQuery}
onChangeText={setSearchQuery}
/>
{searchQuery.length > 0 && (
<TouchableOpacity onPress={() => setSearchQuery('')}>
<XMarkIcon size={20} color="gray" />
</TouchableOpacity>
)}
</View>
{/* Current Location Button */}
<TouchableOpacity
onPress={handleUseCurrentLocation}
disabled={isLoading}
className="flex-row items-center gap-4 py-6 px-8 border-2 border-primary rounded-xl bg-white mb-4"
>
<Icon name="location" size={30} color={"#704f38"} />
<Text className="text-xl font-bold text-primary">
{isLoading ? "Getting Location..." : "Use My Current Location"}
</Text>
</TouchableOpacity>
{/* Search Results */}
{isSearching ? (
<View className="flex-1 justify-center items-center">
<ActivityIndicator size="large" color="#704f38" />
<Text className="mt-2 text-gray-500">Searching locations...</Text>
</View>
) : searchResults.length > 0 ? (
<FlatList
data={searchResults}
renderItem={renderSearchResult}
keyExtractor={(item) => item.place_id}
className="flex-1"
initialNumToRender={10}
maxToRenderPerBatch={10}
windowSize={5}
/>
) : searchQuery.length > 2 ? (
<View className="flex-1 justify-center items-center">
<Text className="text-gray-500">No locations found</Text>
</View>
) : null}
{currentLocation && !searchQuery && (
<View className="mt-4 p-4 bg-gray-50 rounded-xl">
<Text className="text-lg font-medium text-gray-800">Current Location:</Text>
<Text className="text-base text-gray-600 mt-2">{currentLocation.address}</Text>
</View>
)}
</View>
</View>
</View>
</Modal>
);
}
@@ -1,5 +1,6 @@
import { View, Text, TouchableOpacity } from 'react-native'
import React from 'react'
import React, { useState } from 'react'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import { MinusIcon, PlusIcon } from 'react-native-heroicons/outline'
/**
@@ -13,34 +14,34 @@ import { MinusIcon, PlusIcon } from 'react-native-heroicons/outline'
* @param {Object} props.containerStyle Additional styles for the container
* @returns {React.Component} Quantity selector component
*/
export default function ProductQuantityInput({
quantity = 1,
onIncrease,
onDecrease,
label = "Quantity",
containerStyle = {}
}) {
return (
<View style={containerStyle}>
{label && <Text className="text-[17px] font-medium mb-2">{label}</Text>}
<View className="flex-row items-center">
<TouchableOpacity
onPress={onDecrease}
className={`bg-primary/40 rounded-lg p-1 ${quantity <= 1 ? 'opacity-50' : ''}`}
disabled={quantity <= 1}
>
<MinusIcon color={quantity <= 1 ? "gray" : "black"} size={25} />
</TouchableOpacity>
<Text className="mx-4 text-xl">{quantity}</Text>
<TouchableOpacity
onPress={onIncrease}
className="bg-primary rounded-lg p-1"
>
<PlusIcon color="white" size={25} />
</TouchableOpacity>
</View>
</View>
)
}
const ProductQuantityInput = ({ initialQuantity = 1, onQuantityChange }) => {
const [quantity, setQuantity] = useState(initialQuantity);
const handleDecrease = () => {
if (quantity > 1) {
const newQuantity = quantity - 1;
setQuantity(newQuantity);
onQuantityChange(newQuantity);
}
};
const handleIncrease = () => {
const newQuantity = quantity + 1;
setQuantity(newQuantity);
onQuantityChange(newQuantity);
};
return (
<View className="flex-row items-center justify-between border border-gray-300 rounded-full px-4 py-2" style={{ width: wp('30%') }}>
<TouchableOpacity onPress={handleDecrease} disabled={quantity <= 1}>
<MinusIcon size={wp('5%')} color={quantity <= 1 ? '#ccc' : '#000'} />
</TouchableOpacity>
<Text style={{ fontSize: wp('4%') }} className="font-semibold">{quantity}</Text>
<TouchableOpacity onPress={handleIncrease}>
<PlusIcon size={wp('5%')} color="#000" />
</TouchableOpacity>
</View>
);
}
export default ProductQuantityInput;