添加收藏

This commit is contained in:
yuchenglong
2026-01-16 14:41:15 +08:00
parent 4bccf39a8b
commit d20080eaf3
11 changed files with 656 additions and 75 deletions

View File

@@ -9,7 +9,12 @@ import { IconSymbol } from "@/components/ui/icon-symbol";
import { Colors } from "@/constants/theme"; import { Colors } from "@/constants/theme";
import { useAppState } from "@/context/AppStateContext"; import { useAppState } from "@/context/AppStateContext";
import { useTheme } from "@/context/ThemeContext"; 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 { League, Match, Sport } from "@/types/api";
import React, { useEffect, useMemo, useState } from "react"; import React, { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@@ -310,7 +315,26 @@ export default function HomeScreen() {
selectedDate, selectedDate,
deviceTimeZone 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) { } catch (e) {
console.error(e); console.error(e);
} finally { } 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 currentSport = sports.find((s) => s.id === selectedSportId);
const filteredMatches = useMemo( const filteredMatches = useMemo(
@@ -457,7 +493,9 @@ export default function HomeScreen() {
<FlatList <FlatList
data={filteredMatches} data={filteredMatches}
keyExtractor={(item) => item.id} keyExtractor={(item) => item.id}
renderItem={({ item }) => <MatchCard match={item} />} renderItem={({ item }) => (
<MatchCard match={item} onFavoriteToggle={handleFavoriteToggle} />
)}
contentContainerStyle={styles.listContent} contentContainerStyle={styles.listContent}
ListEmptyComponent={ ListEmptyComponent={
<View style={styles.center}> <View style={styles.center}>

View File

@@ -9,7 +9,12 @@ import { IconSymbol } from "@/components/ui/icon-symbol";
import { Colors } from "@/constants/theme"; import { Colors } from "@/constants/theme";
import { useAppState } from "@/context/AppStateContext"; import { useAppState } from "@/context/AppStateContext";
import { useTheme } from "@/context/ThemeContext"; 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 { League, Match, Sport } from "@/types/api";
import React, { useEffect, useMemo, useState } from "react"; import React, { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@@ -310,7 +315,27 @@ export default function HomeScreen() {
selectedDate, selectedDate,
deviceTimeZone 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) { } catch (e) {
console.error(e); console.error(e);
} finally { } 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); const currentSport = sports.find((s) => s.id === selectedSportId);
// 获取当前运动的国际化名称 // 获取当前运动的国际化名称
@@ -452,7 +489,9 @@ export default function HomeScreen() {
<FlatList <FlatList
data={matches} data={matches}
keyExtractor={(item) => item.id} keyExtractor={(item) => item.id}
renderItem={({ item }) => <MatchCard match={item} />} renderItem={({ item }) => (
<MatchCard match={item} onFavoriteToggle={handleFavoriteToggle} />
)}
contentContainerStyle={styles.listContent} contentContainerStyle={styles.listContent}
ListEmptyComponent={ ListEmptyComponent={
<View style={styles.center}> <View style={styles.center}>

View File

@@ -5,7 +5,7 @@ import { ThemedView } from "@/components/themed-view";
import { Colors } from "@/constants/theme"; import { Colors } from "@/constants/theme";
import { useAppState } from "@/context/AppStateContext"; import { useAppState } from "@/context/AppStateContext";
import { useTheme } from "@/context/ThemeContext"; import { useTheme } from "@/context/ThemeContext";
import { fetchLiveScore } from "@/lib/api"; import { checkFavorite, fetchLiveScore } from "@/lib/api";
import { LiveScoreMatch, Match } from "@/types/api"; import { LiveScoreMatch, Match } from "@/types/api";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
@@ -66,7 +66,25 @@ export default function LiveScreen() {
isLive: true, 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) { } catch (error) {
console.error("Load live matches error:", error); console.error("Load live matches error:", error);
setMatches([]); 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 ( return (
<ThemedView style={styles.container}> <ThemedView style={styles.container}>
<HomeHeader /> <HomeHeader />
@@ -91,6 +121,7 @@ export default function LiveScreen() {
renderItem={({ item }) => ( renderItem={({ item }) => (
<MatchCard <MatchCard
match={item} match={item}
onFavoriteToggle={handleFavoriteToggle}
onPress={(m) => { onPress={(m) => {
router.push({ router.push({
pathname: "/live-detail/[id]", pathname: "/live-detail/[id]",

View File

@@ -7,7 +7,12 @@ import { IconSymbol } from "@/components/ui/icon-symbol";
import { UpcomingMatchCard } from "@/components/upcoming-match-card"; import { UpcomingMatchCard } from "@/components/upcoming-match-card";
import { Colors } from "@/constants/theme"; import { Colors } from "@/constants/theme";
import { useTheme } from "@/context/ThemeContext"; 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 { League, Sport, UpcomingMatch } from "@/types/api";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@@ -66,14 +71,78 @@ export default function HomeScreen() {
const apiList = await fetchSports(); const apiList = await fetchSports();
// 创建8个运动的完整列表 // 创建8个运动的完整列表
const defaultSports: Sport[] = [ const defaultSports: Sport[] = [
{ id: 1, name: "football", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, {
{ id: 2, name: "basketball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, id: 1,
{ id: 3, name: "tennis", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, name: "football",
{ id: 4, name: "cricket", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, description: "",
{ id: 5, name: "baseball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, icon: "",
{ id: 6, name: "badminton", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, isActive: true,
{ id: 7, name: "snooker", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, updatedAt: "",
{ id: 8, name: "volleyball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, 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返回的运动和默认列表 // 合并API返回的运动和默认列表
@@ -98,14 +167,78 @@ export default function HomeScreen() {
console.error(e); console.error(e);
// API失败时使用默认8个运动 // API失败时使用默认8个运动
const defaultSports: Sport[] = [ const defaultSports: Sport[] = [
{ id: 1, name: "football", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, {
{ id: 2, name: "basketball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, id: 1,
{ id: 3, name: "tennis", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, name: "football",
{ id: 4, name: "cricket", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, description: "",
{ id: 5, name: "baseball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, icon: "",
{ id: 6, name: "badminton", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, isActive: true,
{ id: 7, name: "snooker", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, updatedAt: "",
{ id: 8, name: "volleyball", description: "", icon: "", isActive: true, updatedAt: "", createdAt: "" }, 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); setSports(defaultSports);
setSelectedSportId(1); setSelectedSportId(1);
@@ -133,8 +266,30 @@ export default function HomeScreen() {
setLoading(true); setLoading(true);
try { try {
// 使用 fetchUpcomingMatches默认 leagueKey 为空字符串 // 使用 fetchUpcomingMatches默认 leagueKey 为空字符串
const list = await fetchUpcomingMatches(selectedSportId, selectedLeagueKey || ""); const list = await fetchUpcomingMatches(
setMatches(list); 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) { } catch (e) {
console.error(e); console.error(e);
} finally { } finally {
@@ -142,6 +297,18 @@ 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 currentSport = sports.find((s) => s.id === selectedSportId);
// 获取当前运动的国际化名称 // 获取当前运动的国际化名称
@@ -174,9 +341,7 @@ export default function HomeScreen() {
disabled disabled
> >
<IconSymbol name="trophy-outline" size={18} color={iconColor} /> <IconSymbol name="trophy-outline" size={18} color={iconColor} />
<ThemedText style={styles.filterText}> <ThemedText style={styles.filterText}>{t("home.league")}</ThemedText>
{t("home.league")}
</ThemedText>
</TouchableOpacity> </TouchableOpacity>
{/* Sport Selector */} {/* Sport Selector */}
@@ -212,7 +377,8 @@ export default function HomeScreen() {
<IconSymbol name="trophy-outline" size={18} color={iconColor} /> <IconSymbol name="trophy-outline" size={18} color={iconColor} />
<ThemedText style={styles.filterText} numberOfLines={1}> <ThemedText style={styles.filterText} numberOfLines={1}>
{selectedLeagueKey {selectedLeagueKey
? leagues.find(l => l.key === selectedLeagueKey)?.name || t("home.select_league") ? leagues.find((l) => l.key === selectedLeagueKey)?.name ||
t("home.select_league")
: t("home.all_leagues")} : t("home.all_leagues")}
</ThemedText> </ThemedText>
</TouchableOpacity> </TouchableOpacity>
@@ -234,7 +400,12 @@ export default function HomeScreen() {
<FlatList <FlatList
data={matches} data={matches}
keyExtractor={(item) => item.id.toString()} keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => <UpcomingMatchCard match={item} />} renderItem={({ item }) => (
<UpcomingMatchCard
match={item}
onFavoriteToggle={handleFavoriteToggle}
/>
)}
contentContainerStyle={styles.listContent} contentContainerStyle={styles.listContent}
ListEmptyComponent={ ListEmptyComponent={
<View style={styles.center}> <View style={styles.center}>

View File

@@ -1,9 +1,10 @@
import { ThemedText } from "@/components/themed-text"; import { ThemedText } from "@/components/themed-text";
import { IconSymbol } from "@/components/ui/icon-symbol"; import { IconSymbol } from "@/components/ui/icon-symbol";
import { addFavorite, checkFavorite, removeFavorite } from "@/lib/api";
import { LiveScoreMatch } from "@/types/api"; import { LiveScoreMatch } from "@/types/api";
import { LinearGradient } from "expo-linear-gradient"; import { LinearGradient } from "expo-linear-gradient";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import React from "react"; import React, { useState } from "react";
import { Image, StyleSheet, TouchableOpacity, View } from "react-native"; import { Image, StyleSheet, TouchableOpacity, View } from "react-native";
interface LiveScoreHeaderProps { interface LiveScoreHeaderProps {
@@ -32,8 +33,49 @@ export function LiveScoreHeader({ match, topInset }: LiveScoreHeaderProps) {
}; };
const initial = getInitialTime(); const initial = getInitialTime();
const [minutes, setMinutes] = React.useState(initial.min); const [minutes, setMinutes] = useState(initial.min);
const [seconds, setSeconds] = React.useState(initial.sec); 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( const lastServerMatchRef = React.useRef(
`${match.event_status}-${match.event_time}` `${match.event_status}-${match.event_time}`
); );
@@ -104,8 +146,16 @@ export function LiveScoreHeader({ match, topInset }: LiveScoreHeaderProps) {
<TouchableOpacity style={styles.iconBtn}> <TouchableOpacity style={styles.iconBtn}>
<IconSymbol name="notifications-outline" size={24} color="#FFF" /> <IconSymbol name="notifications-outline" size={24} color="#FFF" />
</TouchableOpacity> </TouchableOpacity>
<TouchableOpacity style={styles.iconBtn}> <TouchableOpacity
<IconSymbol name="star-outline" size={24} color="#FFF" /> style={styles.iconBtn}
onPress={toggleFavorite}
disabled={favLoading}
>
<IconSymbol
name={isFav ? "star" : "star-outline"}
size={24}
color={isFav ? "#FFD700" : "#FFF"}
/>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</View> </View>

View File

@@ -2,19 +2,33 @@ import { ThemedText } from "@/components/themed-text";
import { IconSymbol } from "@/components/ui/icon-symbol"; import { IconSymbol } from "@/components/ui/icon-symbol";
import { Colors } from "@/constants/theme"; import { Colors } from "@/constants/theme";
import { useTheme } from "@/context/ThemeContext"; import { useTheme } from "@/context/ThemeContext";
import { addFavorite, removeFavorite } from "@/lib/api";
import { Match } from "@/types/api"; import { Match } from "@/types/api";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import React from "react"; import React, { useState } from "react";
import { Pressable, StyleSheet, View } from "react-native"; import { Pressable, StyleSheet, TouchableOpacity, View } from "react-native";
interface MatchCardProps { interface MatchCardProps {
match: Match; match: Match;
onPress?: (match: Match) => void; 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 router = useRouter();
const { theme } = useTheme(); 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 isDark = theme === "dark";
const iconColor = isDark ? Colors.dark.icon : Colors.light.icon; const iconColor = isDark ? Colors.dark.icon : Colors.light.icon;
const cardBg = isDark ? "#1C1C1E" : "#FFFFFF"; 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 ( return (
<Pressable <Pressable
onPress={handlePress} onPress={handlePress}
@@ -58,11 +101,20 @@ export function MatchCard({ match, onPress }: MatchCardProps) {
<ThemedText type="defaultSemiBold" style={styles.scoreText}> <ThemedText type="defaultSemiBold" style={styles.scoreText}>
{match.scoreText} {match.scoreText}
</ThemedText> </ThemedText>
<TouchableOpacity
onPress={(e) => {
e.stopPropagation();
toggleFavorite();
}}
disabled={loading}
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
>
<IconSymbol <IconSymbol
name={match.fav ? "star" : "star-outline"} name={isFav ? "star" : "star-outline"}
size={20} size={24}
color={match.fav ? "#FFD700" : iconColor} color={isFav ? "#FFD700" : iconColor}
/> />
</TouchableOpacity>
</View> </View>
</View> </View>

View File

@@ -1,9 +1,10 @@
import { ThemedText } from "@/components/themed-text"; import { ThemedText } from "@/components/themed-text";
import { IconSymbol } from "@/components/ui/icon-symbol"; import { IconSymbol } from "@/components/ui/icon-symbol";
import { addFavorite, checkFavorite, removeFavorite } from "@/lib/api";
import { MatchDetailData } from "@/types/api"; import { MatchDetailData } from "@/types/api";
import { LinearGradient } from "expo-linear-gradient"; import { LinearGradient } from "expo-linear-gradient";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import React from "react"; import React, { useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Image, StyleSheet, TouchableOpacity, View } from "react-native"; import { Image, StyleSheet, TouchableOpacity, View } from "react-native";
@@ -18,6 +19,50 @@ export function ScoreHeader({ data, isDark, topInset }: ScoreHeaderProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const { match } = data; 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 ( return (
<LinearGradient <LinearGradient
colors={["#521e10", "#0e0e10"]} colors={["#521e10", "#0e0e10"]}
@@ -46,8 +91,16 @@ export function ScoreHeader({ data, isDark, topInset }: ScoreHeaderProps) {
<TouchableOpacity style={styles.iconBtn}> <TouchableOpacity style={styles.iconBtn}>
<IconSymbol name="notifications-outline" size={24} color="#FFF" /> <IconSymbol name="notifications-outline" size={24} color="#FFF" />
</TouchableOpacity> </TouchableOpacity>
<TouchableOpacity style={styles.iconBtn}> <TouchableOpacity
<IconSymbol name="star-outline" size={24} color="#FFF" /> style={styles.iconBtn}
onPress={toggleFavorite}
disabled={favLoading}
>
<IconSymbol
name={isFav ? "star" : "star-outline"}
size={24}
color={isFav ? "#FFD700" : "#FFF"}
/>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</View> </View>

View File

@@ -2,23 +2,66 @@ import { ThemedText } from "@/components/themed-text";
import { IconSymbol } from "@/components/ui/icon-symbol"; import { IconSymbol } from "@/components/ui/icon-symbol";
import { Colors } from "@/constants/theme"; import { Colors } from "@/constants/theme";
import { useTheme } from "@/context/ThemeContext"; import { useTheme } from "@/context/ThemeContext";
import { addFavorite, removeFavorite } from "@/lib/api";
import { UpcomingMatch } from "@/types/api"; import { UpcomingMatch } from "@/types/api";
import { Image } from "expo-image"; import { Image } from "expo-image";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import React from "react"; import React, { useEffect, useState } from "react";
import { Pressable, StyleSheet, View } from "react-native"; import { Pressable, StyleSheet, TouchableOpacity, View } from "react-native";
interface UpcomingMatchCardProps { interface UpcomingMatchCardProps {
match: UpcomingMatch; match: UpcomingMatch;
onFavoriteToggle?: (matchId: string, isFav: boolean) => void;
} }
export function UpcomingMatchCard({ match }: UpcomingMatchCardProps) { export function UpcomingMatchCard({
match,
onFavoriteToggle,
}: UpcomingMatchCardProps) {
const router = useRouter(); const router = useRouter();
const { theme } = useTheme(); 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 isDark = theme === "dark";
const iconColor = isDark ? Colors.dark.icon : Colors.light.icon; const iconColor = isDark ? Colors.dark.icon : Colors.light.icon;
const cardBg = isDark ? "#1C1C1E" : "#FFFFFF"; const cardBg = isDark ? "#1C1C1E" : "#FFFFFF";
const borderColor = isDark ? "#38383A" : "#E5E5EA"; 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 = () => { const handlePress = () => {
router.push(`/match-detail/${match.id}`); router.push(`/match-detail/${match.id}`);
}; };
@@ -57,7 +100,24 @@ export function UpcomingMatchCard({ match }: UpcomingMatchCardProps) {
{match.leagueName} {match.leagueName}
</ThemedText> </ThemedText>
</View> </View>
<View style={{ flexDirection: "row", alignItems: "center" }}>
<ThemedText style={styles.timeText}>{formatDateTime()}</ThemedText> <ThemedText style={styles.timeText}>{formatDateTime()}</ThemedText>
<TouchableOpacity
onPress={(e) => {
e.stopPropagation();
toggleFavorite();
}}
disabled={loading}
style={{ marginLeft: 8 }}
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
>
<IconSymbol
name={isFav ? "star" : "star-outline"}
size={20}
color={isFav ? "#FFD700" : iconColor}
/>
</TouchableOpacity>
</View>
</View> </View>
<View style={styles.teamsContainer}> <View style={styles.teamsContainer}>
@@ -69,7 +129,11 @@ export function UpcomingMatchCard({ match }: UpcomingMatchCardProps) {
contentFit="contain" contentFit="contain"
/> />
)} )}
<ThemedText type="defaultSemiBold" style={styles.teamName} numberOfLines={1}> <ThemedText
type="defaultSemiBold"
style={styles.teamName}
numberOfLines={1}
>
{match.homeTeamName} {match.homeTeamName}
</ThemedText> </ThemedText>
</View> </View>
@@ -86,7 +150,11 @@ export function UpcomingMatchCard({ match }: UpcomingMatchCardProps) {
contentFit="contain" contentFit="contain"
/> />
)} )}
<ThemedText type="defaultSemiBold" style={styles.teamName} numberOfLines={1}> <ThemedText
type="defaultSemiBold"
style={styles.teamName}
numberOfLines={1}
>
{match.awayTeamName} {match.awayTeamName}
</ThemedText> </ThemedText>
</View> </View>

View File

@@ -14,6 +14,8 @@ export const API_ENDPOINTS = {
ODDS: "/v1/api/odds", ODDS: "/v1/api/odds",
SEARCH: "/v1/api/search", SEARCH: "/v1/api/search",
H2H: "/v1/api/h2h", H2H: "/v1/api/h2h",
FAVORITES: "/v1/api/favorites",
CHECK_FAVORITE: "/v1/api/favorites/check",
APPLE_SIGNIN: "/v1/api/auth/apple-signin", APPLE_SIGNIN: "/v1/api/auth/apple-signin",
LOGOUT: "/v1/api/auth/logout", LOGOUT: "/v1/api/auth/logout",
REFRESH_TOKEN: "/v1/api/auth/refresh-token", REFRESH_TOKEN: "/v1/api/auth/refresh-token",

View File

@@ -5,6 +5,8 @@ import {
AppleSignInRequest, AppleSignInRequest,
AppleSignInResponse, AppleSignInResponse,
Country, Country,
FavoriteCheckResponse,
FavoriteRequest,
H2HData, H2HData,
League, League,
LiveScoreMatch, LiveScoreMatch,
@@ -41,9 +43,10 @@ const refreshTokenApi = async (
request: RefreshTokenRequest request: RefreshTokenRequest
): Promise<RefreshTokenResponse> => { ): Promise<RefreshTokenResponse> => {
try { try {
const response = await apiClient.post< const response = await apiClient.post<ApiResponse<RefreshTokenResponse>>(
ApiResponse<RefreshTokenResponse> API_ENDPOINTS.REFRESH_TOKEN,
>(API_ENDPOINTS.REFRESH_TOKEN, request); request
);
if (response.data.code === 0) { if (response.data.code === 0) {
return response.data.data; return response.data.data;
@@ -65,7 +68,9 @@ apiClient.interceptors.response.use(
try { try {
const refreshTokenValue = await storage.getRefreshToken(); const refreshTokenValue = await storage.getRefreshToken();
if (refreshTokenValue) { if (refreshTokenValue) {
const res = await refreshTokenApi({ refreshToken: refreshTokenValue }); const res = await refreshTokenApi({
refreshToken: refreshTokenValue,
});
await storage.setAccessToken(res.accessToken); await storage.setAccessToken(res.accessToken);
originalRequest.headers.Authorization = `Bearer ${res.accessToken}`; originalRequest.headers.Authorization = `Bearer ${res.accessToken}`;
return apiClient(originalRequest); return apiClient(originalRequest);
@@ -371,9 +376,10 @@ export const appleSignIn = async (
request: AppleSignInRequest request: AppleSignInRequest
): Promise<AppleSignInResponse> => { ): Promise<AppleSignInResponse> => {
try { try {
const response = await apiClient.post< const response = await apiClient.post<ApiResponse<AppleSignInResponse>>(
ApiResponse<AppleSignInResponse> API_ENDPOINTS.APPLE_SIGNIN,
>(API_ENDPOINTS.APPLE_SIGNIN, request); request
);
if (response.data.code === 0) { if (response.data.code === 0) {
return response.data.data; return response.data.data;
@@ -421,3 +427,59 @@ export const fetchUserProfile = async (): Promise<UserProfile> => {
throw error; throw error;
} }
}; };
export const addFavorite = async (request: FavoriteRequest): Promise<any> => {
try {
const response = await apiClient.post<ApiResponse<any>>(
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<any> => {
try {
const response = await apiClient.delete<ApiResponse<any>>(
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<FavoriteCheckResponse> => {
try {
const response = await apiClient.get<ApiResponse<FavoriteCheckResponse>>(
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;
}
};

View File

@@ -94,6 +94,20 @@ export interface ApiResponse<T> {
data: T; 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<T> { export interface ApiListResponse<T> {
list: T[]; list: T[];
total: number; total: number;
@@ -185,6 +199,7 @@ export interface UpcomingMatch {
eventDate: string; eventDate: string;
eventTime: string; eventTime: string;
status: string; // scheduled status: string; // scheduled
fav?: boolean;
venue: string; venue: string;
referee: string; referee: string;
homeTeamKey: string; homeTeamKey: string;