From d20080eaf3f648cfee4062ab42d0f67746165abf Mon Sep 17 00:00:00 2001 From: yuchenglong Date: Fri, 16 Jan 2026 14:41:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=94=B6=E8=97=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/(tabs)/finished.tsx | 44 +++- app/(tabs)/index.tsx | 45 +++- app/(tabs)/live.tsx | 35 ++- app/(tabs)/upcoming.tsx | 231 ++++++++++++++++--- components/live-detail/live-score-header.tsx | 62 ++++- components/match-card.tsx | 68 +++++- components/match-detail/score-header.tsx | 59 ++++- components/upcoming-match-card.tsx | 80 ++++++- constants/api.ts | 2 + lib/api.ts | 82 ++++++- types/api.ts | 23 +- 11 files changed, 656 insertions(+), 75 deletions(-) diff --git a/app/(tabs)/finished.tsx b/app/(tabs)/finished.tsx index 4ee7f67..4bdcad4 100644 --- a/app/(tabs)/finished.tsx +++ b/app/(tabs)/finished.tsx @@ -9,7 +9,12 @@ import { IconSymbol } from "@/components/ui/icon-symbol"; import { Colors } from "@/constants/theme"; import { useAppState } from "@/context/AppStateContext"; import { useTheme } from "@/context/ThemeContext"; -import { fetchLeagues, fetchSports, fetchTodayMatches } from "@/lib/api"; +import { + checkFavorite, + fetchLeagues, + fetchSports, + fetchTodayMatches, +} from "@/lib/api"; import { League, Match, Sport } from "@/types/api"; import React, { useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; @@ -310,7 +315,26 @@ export default function HomeScreen() { selectedDate, deviceTimeZone ); - setMatches(list); + + // 直接传递 match.id 查询是否收藏,并更新列表状态 + const listWithFavStatus = await Promise.all( + list.map(async (m) => { + try { + const favRes = await checkFavorite("match", m.id); + return { ...m, fav: favRes.isFavorite }; + } catch (error) { + console.error(`Check favorite failed for match ${m.id}:`, error); + return m; + } + }) + ); + + // 将收藏的比赛置顶 + const sortedList = [...listWithFavStatus].sort((a, b) => { + if (a.fav === b.fav) return 0; + return a.fav ? -1 : 1; + }); + setMatches(sortedList); } catch (e) { console.error(e); } finally { @@ -318,6 +342,18 @@ export default function HomeScreen() { } }; + const handleFavoriteToggle = (matchId: string, isFav: boolean) => { + setMatches((prev) => { + const updated = prev.map((m) => + m.id === matchId ? { ...m, fav: isFav } : m + ); + return [...updated].sort((a, b) => { + if (a.fav === b.fav) return 0; + return a.fav ? -1 : 1; + }); + }); + }; + const currentSport = sports.find((s) => s.id === selectedSportId); const filteredMatches = useMemo( @@ -457,7 +493,9 @@ export default function HomeScreen() { item.id} - renderItem={({ item }) => } + renderItem={({ item }) => ( + + )} contentContainerStyle={styles.listContent} ListEmptyComponent={ diff --git a/app/(tabs)/index.tsx b/app/(tabs)/index.tsx index 939b46c..97dbea0 100644 --- a/app/(tabs)/index.tsx +++ b/app/(tabs)/index.tsx @@ -9,7 +9,12 @@ import { IconSymbol } from "@/components/ui/icon-symbol"; import { Colors } from "@/constants/theme"; import { useAppState } from "@/context/AppStateContext"; import { useTheme } from "@/context/ThemeContext"; -import { fetchLeagues, fetchSports, fetchTodayMatches } from "@/lib/api"; +import { + checkFavorite, + fetchLeagues, + fetchSports, + fetchTodayMatches, +} from "@/lib/api"; import { League, Match, Sport } from "@/types/api"; import React, { useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; @@ -310,7 +315,27 @@ export default function HomeScreen() { selectedDate, deviceTimeZone ); - setMatches(list); + + // 直接传递 match.id 查询是否收藏,并更新列表状态 + const listWithFavStatus = await Promise.all( + list.map(async (m) => { + try { + // 查询比赛是否已被收藏 + const favRes = await checkFavorite("match", m.id); + return { ...m, fav: favRes.isFavorite }; + } catch (error) { + console.error(`Check favorite failed for match ${m.id}:`, error); + return m; + } + }) + ); + + // 将收藏的比赛置顶 + const sortedList = [...listWithFavStatus].sort((a, b) => { + if (a.fav === b.fav) return 0; + return a.fav ? -1 : 1; + }); + setMatches(sortedList); } catch (e) { console.error(e); } finally { @@ -318,6 +343,18 @@ export default function HomeScreen() { } }; + const handleFavoriteToggle = (matchId: string, isFav: boolean) => { + setMatches((prev) => { + const updated = prev.map((m) => + m.id === matchId ? { ...m, fav: isFav } : m + ); + return [...updated].sort((a, b) => { + if (a.fav === b.fav) return 0; + return a.fav ? -1 : 1; + }); + }); + }; + const currentSport = sports.find((s) => s.id === selectedSportId); // 获取当前运动的国际化名称 @@ -452,7 +489,9 @@ export default function HomeScreen() { item.id} - renderItem={({ item }) => } + renderItem={({ item }) => ( + + )} contentContainerStyle={styles.listContent} ListEmptyComponent={ diff --git a/app/(tabs)/live.tsx b/app/(tabs)/live.tsx index 2ea4f5a..f4abec3 100644 --- a/app/(tabs)/live.tsx +++ b/app/(tabs)/live.tsx @@ -5,7 +5,7 @@ import { ThemedView } from "@/components/themed-view"; import { Colors } from "@/constants/theme"; import { useAppState } from "@/context/AppStateContext"; import { useTheme } from "@/context/ThemeContext"; -import { fetchLiveScore } from "@/lib/api"; +import { checkFavorite, fetchLiveScore } from "@/lib/api"; import { LiveScoreMatch, Match } from "@/types/api"; import { useRouter } from "expo-router"; import React, { useEffect, useState } from "react"; @@ -66,7 +66,25 @@ export default function LiveScreen() { isLive: true, })); - setMatches(converted); + // 直接传递 match.id 查询是否收藏,并更新列表状态 + const listWithFavStatus = await Promise.all( + converted.map(async (m) => { + try { + const favRes = await checkFavorite("match", m.id); + return { ...m, fav: favRes.isFavorite }; + } catch (error) { + console.error(`Check favorite failed for match ${m.id}:`, error); + return m; + } + }) + ); + + // 将收藏的比赛置顶 + const sortedList = [...listWithFavStatus].sort((a, b) => { + if (a.fav === b.fav) return 0; + return a.fav ? -1 : 1; + }); + setMatches(sortedList); } catch (error) { console.error("Load live matches error:", error); setMatches([]); @@ -75,6 +93,18 @@ export default function LiveScreen() { } }; + const handleFavoriteToggle = (matchId: string, isFav: boolean) => { + setMatches((prev) => { + const updated = prev.map((m) => + m.id === matchId ? { ...m, fav: isFav } : m + ); + return [...updated].sort((a, b) => { + if (a.fav === b.fav) return 0; + return a.fav ? -1 : 1; + }); + }); + }; + return ( @@ -91,6 +121,7 @@ export default function LiveScreen() { renderItem={({ item }) => ( { router.push({ pathname: "/live-detail/[id]", diff --git a/app/(tabs)/upcoming.tsx b/app/(tabs)/upcoming.tsx index 6df174a..5f98023 100644 --- a/app/(tabs)/upcoming.tsx +++ b/app/(tabs)/upcoming.tsx @@ -7,7 +7,12 @@ import { IconSymbol } from "@/components/ui/icon-symbol"; import { UpcomingMatchCard } from "@/components/upcoming-match-card"; import { Colors } from "@/constants/theme"; import { useTheme } from "@/context/ThemeContext"; -import { fetchLeagues, fetchSports, fetchUpcomingMatches } from "@/lib/api"; +import { + checkFavorite, + fetchLeagues, + fetchSports, + fetchUpcomingMatches, +} from "@/lib/api"; import { League, Sport, UpcomingMatch } from "@/types/api"; import React, { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; @@ -66,29 +71,93 @@ export default function HomeScreen() { const apiList = await fetchSports(); // 创建8个运动的完整列表 const defaultSports: Sport[] = [ - { id: 1, name: "football", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 2, name: "basketball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 3, name: "tennis", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 4, name: "cricket", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 5, name: "baseball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 6, name: "badminton", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 7, name: "snooker", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 8, name: "volleyball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, + { + id: 1, + name: "football", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 2, + name: "basketball", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 3, + name: "tennis", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 4, + name: "cricket", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 5, + name: "baseball", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 6, + name: "badminton", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 7, + name: "snooker", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 8, + name: "volleyball", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, ]; - + // 合并API返回的运动和默认列表 const sportsMap = new Map(); apiList.forEach((sport) => { sportsMap.set(sport.id, sport); }); - + // 补充默认运动到8个 defaultSports.forEach((sport) => { if (!sportsMap.has(sport.id)) { sportsMap.set(sport.id, sport); } }); - + const allSports = Array.from(sportsMap.values()) .sort((a, b) => a.id - b.id) .slice(0, 8); @@ -98,14 +167,78 @@ export default function HomeScreen() { console.error(e); // API失败时使用默认8个运动 const defaultSports: Sport[] = [ - { id: 1, name: "football", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 2, name: "basketball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 3, name: "tennis", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 4, name: "cricket", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 5, name: "baseball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 6, name: "badminton", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 7, name: "snooker", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, - { id: 8, name: "volleyball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, + { + id: 1, + name: "football", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 2, + name: "basketball", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 3, + name: "tennis", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 4, + name: "cricket", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 5, + name: "baseball", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 6, + name: "badminton", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 7, + name: "snooker", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, + { + id: 8, + name: "volleyball", + description: "", + icon: "", + isActive: true, + updatedAt: "", + createdAt: "", + }, ]; setSports(defaultSports); setSelectedSportId(1); @@ -129,12 +262,34 @@ export default function HomeScreen() { const loadMatches = async () => { if (selectedSportId === null) return; - + setLoading(true); try { // 使用 fetchUpcomingMatches,默认 leagueKey 为空字符串 - const list = await fetchUpcomingMatches(selectedSportId, selectedLeagueKey || ""); - setMatches(list); + const list = await fetchUpcomingMatches( + selectedSportId, + selectedLeagueKey || "" + ); + + // 直接传递 match.id 查询是否收藏,并更新列表状态 + const listWithFavStatus = await Promise.all( + list.map(async (m) => { + try { + const favRes = await checkFavorite("match", m.id.toString()); + return { ...m, fav: favRes.isFavorite }; + } catch (error) { + console.error(`Check favorite failed for match ${m.id}:`, error); + return m; + } + }) + ); + + // 将收藏的比赛置顶 + const sortedList = [...listWithFavStatus].sort((a, b) => { + if (a.fav === b.fav) return 0; + return a.fav ? -1 : 1; + }); + setMatches(sortedList); } catch (e) { console.error(e); } finally { @@ -142,8 +297,20 @@ export default function HomeScreen() { } }; + const handleFavoriteToggle = (matchId: string, isFav: boolean) => { + setMatches((prev) => { + const updated = prev.map((m) => + m.id.toString() === matchId ? { ...m, fav: isFav } : m + ); + return [...updated].sort((a, b) => { + if (a.fav === b.fav) return 0; + return a.fav ? -1 : 1; + }); + }); + }; + const currentSport = sports.find((s) => s.id === selectedSportId); - + // 获取当前运动的国际化名称 const getSportName = (sport: Sport | undefined): string => { if (!sport) return t("home.select_sport"); @@ -174,9 +341,7 @@ export default function HomeScreen() { disabled > - - {t("home.league")} - + {t("home.league")} {/* Sport Selector */} @@ -211,8 +376,9 @@ export default function HomeScreen() { > - {selectedLeagueKey - ? leagues.find(l => l.key === selectedLeagueKey)?.name || t("home.select_league") + {selectedLeagueKey + ? leagues.find((l) => l.key === selectedLeagueKey)?.name || + t("home.select_league") : t("home.all_leagues")} @@ -234,7 +400,12 @@ export default function HomeScreen() { item.id.toString()} - renderItem={({ item }) => } + renderItem={({ item }) => ( + + )} contentContainerStyle={styles.listContent} ListEmptyComponent={ diff --git a/components/live-detail/live-score-header.tsx b/components/live-detail/live-score-header.tsx index e51bcd4..3433373 100644 --- a/components/live-detail/live-score-header.tsx +++ b/components/live-detail/live-score-header.tsx @@ -1,9 +1,10 @@ import { ThemedText } from "@/components/themed-text"; import { IconSymbol } from "@/components/ui/icon-symbol"; +import { addFavorite, checkFavorite, removeFavorite } from "@/lib/api"; import { LiveScoreMatch } from "@/types/api"; import { LinearGradient } from "expo-linear-gradient"; import { useRouter } from "expo-router"; -import React from "react"; +import React, { useState } from "react"; import { Image, StyleSheet, TouchableOpacity, View } from "react-native"; interface LiveScoreHeaderProps { @@ -32,8 +33,49 @@ export function LiveScoreHeader({ match, topInset }: LiveScoreHeaderProps) { }; const initial = getInitialTime(); - const [minutes, setMinutes] = React.useState(initial.min); - const [seconds, setSeconds] = React.useState(initial.sec); + const [minutes, setMinutes] = useState(initial.min); + const [seconds, setSeconds] = useState(initial.sec); + const [isFav, setIsFav] = useState(false); + const [favLoading, setFavLoading] = useState(false); + + // 检查收藏状态 + React.useEffect(() => { + const loadFavStatus = async () => { + try { + const res = await checkFavorite("match", match.event_key.toString()); + setIsFav(res.isFavorite); + } catch (error) { + console.error("Check favorite status error:", error); + } + }; + loadFavStatus(); + }, [match.event_key]); + + const toggleFavorite = async () => { + if (favLoading) return; + setFavLoading(true); + const newFavState = !isFav; + try { + if (newFavState) { + await addFavorite({ + matchId: match.event_key, + type: "match", + typeId: match.event_key.toString(), + notify: true, + }); + } else { + await removeFavorite({ + type: "match", + typeId: match.event_key.toString(), + }); + } + setIsFav(newFavState); + } catch (error) { + console.error("Toggle favorite error:", error); + } finally { + setFavLoading(false); + } + }; const lastServerMatchRef = React.useRef( `${match.event_status}-${match.event_time}` ); @@ -104,8 +146,16 @@ export function LiveScoreHeader({ match, topInset }: LiveScoreHeaderProps) { - - + + @@ -179,7 +229,7 @@ const styles = StyleSheet.create({ marginBottom: 20, }, leftContainer: { - width: 60, + width: 60, }, rightActions: { flexDirection: "row", diff --git a/components/match-card.tsx b/components/match-card.tsx index 635752f..18ca36e 100644 --- a/components/match-card.tsx +++ b/components/match-card.tsx @@ -2,19 +2,33 @@ import { ThemedText } from "@/components/themed-text"; import { IconSymbol } from "@/components/ui/icon-symbol"; import { Colors } from "@/constants/theme"; import { useTheme } from "@/context/ThemeContext"; +import { addFavorite, removeFavorite } from "@/lib/api"; import { Match } from "@/types/api"; import { useRouter } from "expo-router"; -import React from "react"; -import { Pressable, StyleSheet, View } from "react-native"; +import React, { useState } from "react"; +import { Pressable, StyleSheet, TouchableOpacity, View } from "react-native"; interface MatchCardProps { match: Match; onPress?: (match: Match) => void; + onFavoriteToggle?: (matchId: string, isFav: boolean) => void; } -export function MatchCard({ match, onPress }: MatchCardProps) { +export function MatchCard({ + match, + onPress, + onFavoriteToggle, +}: MatchCardProps) { const router = useRouter(); const { theme } = useTheme(); + const [isFav, setIsFav] = useState(match.fav); + const [loading, setLoading] = useState(false); + + // 当外部传入的 match.fav 改变时,更新内部状态 + React.useEffect(() => { + setIsFav(match.fav); + }, [match.fav]); + const isDark = theme === "dark"; const iconColor = isDark ? Colors.dark.icon : Colors.light.icon; const cardBg = isDark ? "#1C1C1E" : "#FFFFFF"; @@ -28,6 +42,35 @@ export function MatchCard({ match, onPress }: MatchCardProps) { } }; + const toggleFavorite = async () => { + if (loading) return; + setLoading(true); + const newFavState = !isFav; + try { + if (newFavState) { + await addFavorite({ + matchId: parseInt(match.id), + type: "match", + typeId: match.id, + notify: true, + }); + } else { + await removeFavorite({ + type: "match", + typeId: match.id, + }); + } + setIsFav(newFavState); + if (onFavoriteToggle) { + onFavoriteToggle(match.id, newFavState); + } + } catch (error) { + console.error("Toggle favorite error:", error); + } finally { + setLoading(false); + } + }; + return ( {match.scoreText} - + { + e.stopPropagation(); + toggleFavorite(); + }} + disabled={loading} + hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }} + > + + diff --git a/components/match-detail/score-header.tsx b/components/match-detail/score-header.tsx index 041a572..50aa96f 100644 --- a/components/match-detail/score-header.tsx +++ b/components/match-detail/score-header.tsx @@ -1,9 +1,10 @@ import { ThemedText } from "@/components/themed-text"; import { IconSymbol } from "@/components/ui/icon-symbol"; +import { addFavorite, checkFavorite, removeFavorite } from "@/lib/api"; import { MatchDetailData } from "@/types/api"; import { LinearGradient } from "expo-linear-gradient"; import { useRouter } from "expo-router"; -import React from "react"; +import React, { useState } from "react"; import { useTranslation } from "react-i18next"; import { Image, StyleSheet, TouchableOpacity, View } from "react-native"; @@ -18,6 +19,50 @@ export function ScoreHeader({ data, isDark, topInset }: ScoreHeaderProps) { const { t } = useTranslation(); const { match } = data; + const [isFav, setIsFav] = useState(false); + const [favLoading, setFavLoading] = useState(false); + + // 检查收藏状态 + React.useEffect(() => { + const loadFavStatus = async () => { + try { + const res = await checkFavorite("match", match.eventKey.toString()); + setIsFav(res.isFavorite); + } catch (error) { + console.error("Check favorite status error:", error); + } + }; + if (match.eventKey) { + loadFavStatus(); + } + }, [match.eventKey]); + + const toggleFavorite = async () => { + if (favLoading) return; + setFavLoading(true); + const newFavState = !isFav; + try { + if (newFavState) { + await addFavorite({ + matchId: Number(match.eventKey), + type: "match", + typeId: match.eventKey.toString(), + notify: true, + }); + } else { + await removeFavorite({ + type: "match", + typeId: match.eventKey.toString(), + }); + } + setIsFav(newFavState); + } catch (error) { + console.error("Toggle favorite error:", error); + } finally { + setFavLoading(false); + } + }; + return ( - - + + diff --git a/components/upcoming-match-card.tsx b/components/upcoming-match-card.tsx index 7263915..fd23993 100644 --- a/components/upcoming-match-card.tsx +++ b/components/upcoming-match-card.tsx @@ -2,23 +2,66 @@ import { ThemedText } from "@/components/themed-text"; import { IconSymbol } from "@/components/ui/icon-symbol"; import { Colors } from "@/constants/theme"; import { useTheme } from "@/context/ThemeContext"; +import { addFavorite, removeFavorite } from "@/lib/api"; import { UpcomingMatch } from "@/types/api"; import { Image } from "expo-image"; import { useRouter } from "expo-router"; -import React from "react"; -import { Pressable, StyleSheet, View } from "react-native"; +import React, { useEffect, useState } from "react"; +import { Pressable, StyleSheet, TouchableOpacity, View } from "react-native"; interface UpcomingMatchCardProps { match: UpcomingMatch; + onFavoriteToggle?: (matchId: string, isFav: boolean) => void; } -export function UpcomingMatchCard({ match }: UpcomingMatchCardProps) { +export function UpcomingMatchCard({ + match, + onFavoriteToggle, +}: UpcomingMatchCardProps) { const router = useRouter(); const { theme } = useTheme(); + const [isFav, setIsFav] = useState(match.fav || false); + const [loading, setLoading] = useState(false); + + // 当外部传入的 match.fav 改变时,更新内部状态 + useEffect(() => { + setIsFav(match.fav || false); + }, [match.fav]); + const isDark = theme === "dark"; const iconColor = isDark ? Colors.dark.icon : Colors.light.icon; const cardBg = isDark ? "#1C1C1E" : "#FFFFFF"; const borderColor = isDark ? "#38383A" : "#E5E5EA"; + + const toggleFavorite = async () => { + if (loading) return; + setLoading(true); + const newFavState = !isFav; + try { + if (newFavState) { + await addFavorite({ + matchId: match.id, + type: "match", + typeId: match.id.toString(), + notify: true, + }); + } else { + await removeFavorite({ + type: "match", + typeId: match.id.toString(), + }); + } + setIsFav(newFavState); + if (onFavoriteToggle) { + onFavoriteToggle(match.id.toString(), newFavState); + } + } catch (error) { + console.error("Toggle favorite error:", error); + } finally { + setLoading(false); + } + }; + const handlePress = () => { router.push(`/match-detail/${match.id}`); }; @@ -57,7 +100,24 @@ export function UpcomingMatchCard({ match }: UpcomingMatchCardProps) { {match.leagueName} - {formatDateTime()} + + {formatDateTime()} + { + e.stopPropagation(); + toggleFavorite(); + }} + disabled={loading} + style={{ marginLeft: 8 }} + hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }} + > + + + @@ -69,7 +129,11 @@ export function UpcomingMatchCard({ match }: UpcomingMatchCardProps) { contentFit="contain" /> )} - + {match.homeTeamName} @@ -86,7 +150,11 @@ export function UpcomingMatchCard({ match }: UpcomingMatchCardProps) { contentFit="contain" /> )} - + {match.awayTeamName} diff --git a/constants/api.ts b/constants/api.ts index b62f928..bd9dbf3 100644 --- a/constants/api.ts +++ b/constants/api.ts @@ -14,6 +14,8 @@ export const API_ENDPOINTS = { ODDS: "/v1/api/odds", SEARCH: "/v1/api/search", H2H: "/v1/api/h2h", + FAVORITES: "/v1/api/favorites", + CHECK_FAVORITE: "/v1/api/favorites/check", APPLE_SIGNIN: "/v1/api/auth/apple-signin", LOGOUT: "/v1/api/auth/logout", REFRESH_TOKEN: "/v1/api/auth/refresh-token", diff --git a/lib/api.ts b/lib/api.ts index c94b799..daae61f 100644 --- a/lib/api.ts +++ b/lib/api.ts @@ -5,6 +5,8 @@ import { AppleSignInRequest, AppleSignInResponse, Country, + FavoriteCheckResponse, + FavoriteRequest, H2HData, League, LiveScoreMatch, @@ -41,9 +43,10 @@ const refreshTokenApi = async ( request: RefreshTokenRequest ): Promise => { try { - const response = await apiClient.post< - ApiResponse - >(API_ENDPOINTS.REFRESH_TOKEN, request); + const response = await apiClient.post>( + API_ENDPOINTS.REFRESH_TOKEN, + request + ); if (response.data.code === 0) { return response.data.data; @@ -65,7 +68,9 @@ apiClient.interceptors.response.use( try { const refreshTokenValue = await storage.getRefreshToken(); if (refreshTokenValue) { - const res = await refreshTokenApi({ refreshToken: refreshTokenValue }); + const res = await refreshTokenApi({ + refreshToken: refreshTokenValue, + }); await storage.setAccessToken(res.accessToken); originalRequest.headers.Authorization = `Bearer ${res.accessToken}`; return apiClient(originalRequest); @@ -203,9 +208,9 @@ export const fetchLiveScore = async ( ): Promise => { try { const params: { sport_id: number; league_id?: number; timezone?: string } = - { - sport_id: sportId, - }; + { + sport_id: sportId, + }; if (leagueId) { params.league_id = leagueId; @@ -371,9 +376,10 @@ export const appleSignIn = async ( request: AppleSignInRequest ): Promise => { try { - const response = await apiClient.post< - ApiResponse - >(API_ENDPOINTS.APPLE_SIGNIN, request); + const response = await apiClient.post>( + API_ENDPOINTS.APPLE_SIGNIN, + request + ); if (response.data.code === 0) { return response.data.data; @@ -421,3 +427,59 @@ export const fetchUserProfile = async (): Promise => { throw error; } }; + +export const addFavorite = async (request: FavoriteRequest): Promise => { + try { + const response = await apiClient.post>( + API_ENDPOINTS.FAVORITES, + request + ); + if (response.data.code === 0) { + return response.data.data; + } + throw new Error(response.data.message); + } catch (error) { + console.error("Add favorite error:", error); + throw error; + } +}; + +export const removeFavorite = async (request: { + type: string; + typeId: string; +}): Promise => { + try { + const response = await apiClient.delete>( + API_ENDPOINTS.FAVORITES, + { data: request } + ); + if (response.data.code === 0) { + return response.data.data; + } + throw new Error(response.data.message); + } catch (error) { + console.error("Remove favorite error:", error); + throw error; + } +}; + +export const checkFavorite = async ( + type: string, + typeId: string +): Promise => { + try { + const response = await apiClient.get>( + API_ENDPOINTS.CHECK_FAVORITE, + { + params: { type, typeId }, + } + ); + if (response.data.code === 0) { + return response.data.data; + } + throw new Error(response.data.message); + } catch (error) { + console.error("Check favorite error:", error); + throw error; + } +}; diff --git a/types/api.ts b/types/api.ts index 7d5f900..4ed1a1f 100644 --- a/types/api.ts +++ b/types/api.ts @@ -71,11 +71,11 @@ export interface LiveScoreMatch { substitutes?: { time: string; home_scorer: - | { in: string; out: string; in_id: number; out_id: number } - | any[]; + | { in: string; out: string; in_id: number; out_id: number } + | any[]; away_scorer: - | { in: string; out: string; in_id: number; out_id: number } - | any[]; + | { in: string; out: string; in_id: number; out_id: number } + | any[]; info: string; info_time: string; score: string; @@ -94,6 +94,20 @@ export interface ApiResponse { data: T; } +export interface FavoriteRequest { + matchId?: number; + notify?: boolean; + playerId?: number; + teamId?: number; + type: "match" | "team" | "player"; + typeId: string; +} + +export interface FavoriteCheckResponse { + favoriteId: number; + isFavorite: boolean; +} + export interface ApiListResponse { list: T[]; total: number; @@ -185,6 +199,7 @@ export interface UpcomingMatch { eventDate: string; eventTime: string; status: string; // scheduled + fav?: boolean; venue: string; referee: string; homeTeamKey: string;