From 6473a20fa4c1cef75e062bf153adc8ba73d8bf23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=A7=E9=9B=A8=E3=83=90=E3=83=8B=E3=83=A9=E3=83=BC?= <118162831+KirisameVanilla@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:59:31 -0500 Subject: [PATCH] feat: use chart ids and level hashes from the level-hash backend Follows TeamMajdata/mmfcapi#44, where scores are stored per level hash and interactions, votes, comments and collections are keyed by chart id. - Score cards rank by GET api/maiscore/leaderboard/chart/by-level/{levelHash} and fall back to the chart leaderboard when a score has no level hash. - The chart leaderboard reads the { hash, levelHashes, scores } response. - The season leaderboard and its per-chart breakdown send songIds (chart ids) instead of songHashes. - Collections add and remove charts with chartIdsToAdd/chartIdsToRemove and save items as chart ids, so the collection page no longer fetches summaries for hashes. - Document the API changes in api-directory.md and add unit tests. --- api-directory.md | 22 +++- src/components/collection/CollectionModal.tsx | 24 +++-- src/components/score/ScoreCard.tsx | 70 +++++++----- src/components/season/SeasonLeaderboard.tsx | 2 +- src/components/song/ScoreRanking.tsx | 9 +- src/components/user/UserSeasons.tsx | 2 +- src/config/api.ts | 9 +- src/hooks/useCollections.ts | 15 ++- src/hooks/useSeasonBreakdown.ts | 11 +- src/hooks/useSeasonCharts.ts | 16 +-- src/hooks/useSeasonLastPlayed.ts | 12 +-- src/hooks/useSeasonRanking.ts | 6 +- src/locales/en.json | 1 - src/locales/ja.json | 1 - src/locales/ko.json | 1 - src/locales/zh.json | 1 - src/pages/SongPage.tsx | 1 + src/pages/collection/CollectionPage.tsx | 53 ++------- src/pages/user/ScoresPage.tsx | 2 +- src/types/event.ts | 3 +- src/types/score.ts | 20 ++++ src/utils/season.ts | 17 +-- .../collection/CollectionModal.test.tsx | 41 +++++++ test/components/score/ScoreCard.test.tsx | 102 ++++++++++++++++++ .../season/SeasonLeaderboard.test.tsx | 10 +- test/config/api.test.ts | 20 ++++ test/hooks/useCollections.test.tsx | 71 ++++++++++++ test/hooks/useSeasonBreakdown.test.tsx | 97 +++++++++++++++++ test/hooks/useSeasonCharts.test.tsx | 96 +++++++++++++++++ test/pages/collection/CollectionPage.test.tsx | 96 +++++++++++++++++ test/utils/season.test.ts | 45 ++++++++ 31 files changed, 741 insertions(+), 135 deletions(-) create mode 100644 test/components/collection/CollectionModal.test.tsx create mode 100644 test/components/score/ScoreCard.test.tsx create mode 100644 test/config/api.test.ts create mode 100644 test/hooks/useCollections.test.tsx create mode 100644 test/hooks/useSeasonBreakdown.test.tsx create mode 100644 test/hooks/useSeasonCharts.test.tsx create mode 100644 test/pages/collection/CollectionPage.test.tsx create mode 100644 test/utils/season.test.ts diff --git a/api-directory.md b/api-directory.md index 613cd96..4c7e472 100644 --- a/api-directory.md +++ b/api-directory.md @@ -27,7 +27,7 @@ - POST `/api/account/profile`:FormData,可提交 `nickname`、`introduction`、`avatar`,返回更新后的资料。 - GET `/api/avatar/{avatarId}`:头像,前端只用这一个接口(`UserAvatar` 组件 / `useAvatarUrl`)。已知 `avatarId` 时直接使用、不发请求:资料对象自带 `avatarId`;总分榜(`/api/maiscore/sum/...` 的 `players[].player`)、季赛榜(`/api/maiscore/leaderboard/period` 每条的 `player`)和评论(`authorProfile`)附带精简资料 `UserBrief` = `{ id, username, nickname, avatarId }`(未上传头像时 `avatarId` 为 `default`,`nickname` 可能为空串;账号已删除或评论为占位符时为 null);单曲排行榜 `scores[][].player` 的 `id`、`avatarId` 也已填充。只有谱面上传者(谱面响应不带资料)以及上述资料为 null 或缺失时,才按用户名读 GET `/api/account/profile?username=...` 取 `avatarId`,同名只请求一次并与个人空间共用缓存;用户不存在或无用户名时用 `default`。这些榜单和评论仍显示用户名,不换成昵称。`/api/account/icon?username=...` 仅留给 MajdataPlay,前端不再调用。 - 头像和简介上传后刷新资料,避免旧头像缓存;昵称用于显示,用户名继续用于链接、归属判断和 API 查询。 -- GET `/api/account/recent?username=...`、GET `/api/account/scores` 的已有调用协议保持兼容。 +- GET `/api/account/recent?username=...` 的已有调用协议保持兼容;GET `/api/account/scores` 的每条成绩增加 `levelHash`(见下文「按 level hash 存储成绩」)。 ## 排行、收藏与评论 @@ -35,8 +35,8 @@ | --- | --- | | 全站总分榜 | 改用 GET `/api/maiscore/sum/all?page=0&pageSize=...` | | 上传者榜 | 改用 GET `/api/maiscore/sum/chart/by-uploader/{uploader}?page=0&pageSize=...`(`uploader` 作为路径段转义);旧 `/api/stats/score-sums` 已废弃 | -| 单曲排行榜/成绩卡排名 | 改用 GET `/api/maiscore/leaderboard/chart/by-id/{chartId}`;旧 GET `/api/maichart/{chartId}/score` 已废弃 | -| 季赛榜 | 改用 POST `/api/maiscore/leaderboard/period`,请求体不变;旧 POST `/api/playhistory/ranking` 已废弃 | +| 单曲排行榜/成绩卡排名 | 单曲排行榜用 GET `/api/maiscore/leaderboard/chart/by-id/{chartId}`,响应为 `{ hash, levelHashes, scores }`;成绩卡排名在成绩带 `levelHash` 时用 GET `/api/maiscore/leaderboard/chart/by-level/{levelHash}`,否则退回 `by-id`;旧 GET `/api/maichart/{chartId}/score` 已废弃 | +| 季赛榜 | 改用 POST `/api/maiscore/leaderboard/period`,请求体用 `songIds`(谱面 Id 数组);旧 POST `/api/playhistory/ranking` 已废弃 | | 总分返回值 | 从旧数组和 `dxAccSum` 改为 `{ geneTime, players: [{ userId, username, acc: { dx, classic }, player }] }`,`player` 为 `UserBrief \| null` | | 收藏歌单列表 | GET `/api/account/favorite/collection/list` 返回 `songHashs`,卡片的 `count` 从数组长度计算 | | 谱面投票 | PUT `/api/maichart/{chartId}/vote`,JSON `{ value: 1 \| 0 \| -1 }`,返回 `{ score, upvotes, downvotes, myVote }`;旧的 like/dislike Form 接口只保留给游戏客户端 | @@ -46,7 +46,21 @@ | 管理员 | 前端用 GET `/api/admin/groups` 是否返回 200 判断当前用户是否为管理员,管理员可移除任何评论 | | 单曲排行榜 | `player` 的昵称、头像信息用于显示,用户名用于个人空间链接 | -已核对仍兼容的接口:谱面搜索/排序/详情及文件下载、上传及哈希检查、删除、标签更新、歌单创建/修改/删除/曲目增删、收藏/取消收藏、季赛榜请求和最近游玩数据、机台扫码授权。列表排序新增 `hotp`(热门)与 `topp`(分数),`likep` 不再使用。 +已核对仍兼容的接口:谱面搜索/排序/详情及文件下载、上传及哈希检查、删除、标签更新、歌单创建/删除、收藏/取消收藏、最近游玩数据、机台扫码授权。列表排序新增 `hotp`(热门)与 `topp`(分数),`likep` 不再使用。歌单修改、曲目增删和季赛榜请求已按下文改为谱面 Id。 + +## 按 level hash 存储成绩(TeamMajdata/mmfcapi#44) + +后端改为按各难度 inote 的 SHA-256(level hash)存成绩,按谱面 Id(`MaiChart.Id`)存互动、投票、评论和歌单,契约见后端仓库 `docs/level-hash.md`。前端只使用后端返回的 level hash,不自己计算。 + +| 功能 | 接口 | 前端的谱面 Id / level hash 来源 | +| --- | --- | --- | +| 单曲排行榜 | GET `/api/maiscore/leaderboard/chart/by-id/{chartId}`,响应 `{ hash, levelHashes, scores }`;`levelHashes` 固定 7 项,`scores` 仍为 8 项 | 谱面页 URL 的 `id` | +| 成绩卡排名 | GET `/api/maiscore/leaderboard/chart/by-level/{levelHash}`,响应 `{ levelHash, scores }`;没有合法 `levelHash`(迁移未完成的旧成绩、最近游玩卡片)时退回 `by-id` | `/api/account/scores` 每条成绩的 `levelHash`;退回时用 `chartInfo.id` | +| 季赛榜及单曲明细 | POST `/api/maiscore/leaderboard/period`,`songIds` 代替 `songHashes` | 季赛歌单 `songlist` 的 `items[].id` | +| 歌单增删曲目 | POST `/api/collection/{id}/diff`,`chartIdsToAdd` / `chartIdsToRemove` 代替 `hashesToAdd` / `hashesToRemove`;是否已收录仍按 `hashlist` 返回的 hash 判断 | 谱面页的谱面 Id | +| 歌单管理保存 | POST `/api/collection/{id}/modify`,`items` 为谱面 Id 数组 | 原有曲目取 `songlist` 的 `items[].id`,新增曲目取搜索结果的 `id`,不再为取 hash 请求 `summary` | + +`hashlist`、`songlist`、`favorite/collection/list` 的响应不变。谱面信息 `/api/maichart/{chartId}/info`、POST `/api/maichart/info` 新增的 `levelHashes` 前端暂未使用(前端读的是 `summary`)。按谱面查成绩总和的 `/api/maiscore/sum/chart/by-id/{chartId}` 前端目前没有调用点。前端没有提交成绩的地方,`POST /api/maiscore/level/{levelHash}`(请求体须带 `chartId`)只供游戏客户端使用。 ## 需要后端修复的阻碍 diff --git a/src/components/collection/CollectionModal.tsx b/src/components/collection/CollectionModal.tsx index 87e7c1f..9ce6283 100644 --- a/src/components/collection/CollectionModal.tsx +++ b/src/components/collection/CollectionModal.tsx @@ -9,6 +9,9 @@ import { useCollections } from '@/hooks'; interface CollectionModalProps { isOpen: boolean; onClose: () => void; + /** 谱面 Id(MaiChart.Id),加入或移出谱单时提交 */ + chartId?: string; + /** 谱面当前的 maidata hash,用于判断是否已在谱单中 */ songHash?: string; onCreate?: () => void; } @@ -43,7 +46,7 @@ const listItemVariants = { }), }; -export default function CollectionModal({ isOpen, onClose, songHash: songId, onCreate }: CollectionModalProps) { +export default function CollectionModal({ isOpen, onClose, chartId, songHash, onCreate }: CollectionModalProps) { const { t } = useTranslation(); const [isCreating, setIsCreating] = useState(false); const [newName, setNewName] = useState(''); @@ -93,10 +96,13 @@ export default function CollectionModal({ isOpen, onClose, songHash: songId, onC return (c.name || '').toLowerCase().includes(q) || (c.description || '').toLowerCase().includes(q); }); + // 增删按谱面 Id 提交,是否已收录按 hash 判断,两者都有才能切换 + const canToggle = !!chartId && !!songHash; + const handleToggle = useCallback(async (collectionId: string) => { - if (!songId) return; - await toggleSongInCollection(collectionId, songId); - }, [songId, toggleSongInCollection]); + if (!chartId || !songHash) return; + await toggleSongInCollection(collectionId, { chartId, songHash }); + }, [chartId, songHash, toggleSongInCollection]); const handleCreate = useCallback(async () => { if (!newName.trim() || creatingLoading) return; @@ -218,7 +224,7 @@ export default function CollectionModal({ isOpen, onClose, songHash: songId, onC
{filteredCollections.map((collection, index) => { const isAdding = isPending(collection.id); - const isInCollection = songId ? isSongInCollection(collection.id, songId) : false; + const isInCollection = isSongInCollection(collection.id, songHash); return ( handleToggle(collection.id) : undefined} - className={`group flex items-start gap-3 rounded-xl p-3 text-left transition-colors ${songId ? 'cursor-pointer hover:bg-white/5' : 'cursor-default' + onClick={canToggle ? () => handleToggle(collection.id) : undefined} + className={`group flex items-start gap-3 rounded-xl p-3 text-left transition-colors ${canToggle ? 'cursor-pointer hover:bg-white/5' : 'cursor-default' } ${isInCollection ? 'bg-blue-500/10' : ''} ${isAdding ? 'bg-blue-500/10' : ''}`} >
score.player?.username?.trim().toLowerCase() === target + ); + return rankIndex === -1 ? null : { rank: rankIndex + 1, total: scoreList.length }; +} + +/** + * 从谱面各难度的成绩列表中查找指定用户的排名:先找 levelIndex 对应的难度,找不到再扫其他难度 */ function findUserRank( payload: { scores?: ChartScore[][] } | null, username: string, levelIndex: number -): { rank: number; total: number } | null { +): UserRank | null { const scores = payload?.scores; if (!scores || !Array.isArray(scores)) return null; @@ -33,15 +52,8 @@ function findUserRank( ].filter((index) => index >= 0 && index < scores.length); for (const index of candidateIndexes) { - const scoreList = scores[index]; - if (!Array.isArray(scoreList)) continue; - - const rankIndex = scoreList.findIndex( - (score) => score.player?.username?.trim().toLowerCase() === target - ); - if (rankIndex !== -1) { - return { rank: rankIndex + 1, total: scoreList.length }; - } + const result = findRankInList(scores[index], target); + if (result) return result; } return null; @@ -68,23 +80,31 @@ export function ScoreCard({ const currentUsername = useUsername(); const targetUsername = rankUsername || currentUsername; - const { data: chartScores } = useSWR( - showRank && targetUsername ? endpoints.maiscore.chartLeaderboard(score.chartInfo.id) : null, + // 成绩带有 level hash(来自 account/scores)时直接查该难度的榜; + // 旧成绩或没有 level hash 的数据(如最近游玩)退回按谱面 Id 查各难度的榜 + const levelHash = isLevelHash(score.levelHash) ? score.levelHash : null; + const shouldFetchRank = showRank && !!targetUsername; + + const { data: levelScores } = useSWR( + shouldFetchRank && levelHash ? endpoints.maiscore.levelLeaderboard(levelHash) : null, + apiFetcher + ); + const { data: chartScores } = useSWR( + shouldFetchRank && !levelHash ? endpoints.maiscore.chartLeaderboard(score.chartInfo.id) : null, apiFetcher ); // 计算最终使用的排名信息 - const resolvedRank = useMemo(() => { - if (!showRank || !chartScores || !targetUsername) return null; - const result = findUserRank(chartScores, targetUsername, score.chartLevel); - return result?.rank ?? null; - }, [showRank, chartScores, targetUsername, score.chartLevel]); - - const resolvedRankTotal = useMemo(() => { - if (!showRank || !chartScores || !targetUsername) return null; - const result = findUserRank(chartScores, targetUsername, score.chartLevel); - return result?.total ?? null; - }, [showRank, chartScores, targetUsername, score.chartLevel]); + const userRank = useMemo(() => { + if (!shouldFetchRank) return null; + if (levelHash) { + return levelScores ? findRankInList(levelScores.scores, targetUsername.trim().toLowerCase()) : null; + } + return chartScores ? findUserRank(chartScores, targetUsername, score.chartLevel) : null; + }, [shouldFetchRank, levelHash, levelScores, chartScores, targetUsername, score.chartLevel]); + + const resolvedRank = userRank?.rank ?? null; + const resolvedRankTotal = userRank?.total ?? null; const comboStateNumber = typeof score.comboState === 'number' ? score.comboState : Number(score.comboState); const comboStateText = comboStateNumber > 0 ? getComboState(comboStateNumber) : ''; diff --git a/src/components/season/SeasonLeaderboard.tsx b/src/components/season/SeasonLeaderboard.tsx index 2e265ac..79f504f 100644 --- a/src/components/season/SeasonLeaderboard.tsx +++ b/src/components/season/SeasonLeaderboard.tsx @@ -18,7 +18,7 @@ interface SeasonLeaderboardProps { export default function SeasonLeaderboard({ event, status, chartState }: SeasonLeaderboardProps) { const { t } = useTranslation(); - const ranking = useSeasonRanking(event, status, chartState.songhashes ?? null); + const ranking = useSeasonRanking(event, status, chartState.songIds ?? null); const { entries } = ranking; const error = chartState.error ?? ranking.error; const isLoading = chartState.isLoading || ranking.isLoading; diff --git a/src/components/song/ScoreRanking.tsx b/src/components/song/ScoreRanking.tsx index a5ee0ed..7dcc532 100644 --- a/src/components/song/ScoreRanking.tsx +++ b/src/components/song/ScoreRanking.tsx @@ -12,7 +12,7 @@ import { getComboState, getLevelName } from '@/utils'; import { LoadingSpinner } from '@/components'; import UserAvatar from '@/components/user/UserAvatar'; import { Link } from 'react-router-dom'; -import type { ChartScore, ScoreListProps } from '@/types'; +import type { ChartLeaderboardResponse, ChartScore, ScoreListProps } from '@/types'; const fetcher = (url: string) => fetch(url, { mode: 'cors', credentials: 'include' }).then((res) => res.json()); @@ -357,14 +357,15 @@ export function ScoreRanking({ songid }: ScoreListProps) { const [activeLevel, setActiveLevel] = useState(0); const [transitionDirection, setTransitionDirection] = useState<1 | -1>(1); - const { data, error, isLoading } = useSWR( + const { data, error, isLoading } = useSWR( endpoints.maiscore.chartLeaderboard(songid), fetcher, { revalidateOnFocus: true } ); - // 获取所有有效等级 - const levels = useMemo(() => data?.levels || [], [data?.levels]); + // 排行榜响应只有 hash、levelHashes、scores,不含难度定数,所以定数一直为空(既有问题); + // 要显示定数需另从谱面信息取 + const levels: string[] = []; const scoreLevels = useMemo(() => data?.scores || [], [data?.scores]); // 确保 activeLevel 在有效范围内 diff --git a/src/components/user/UserSeasons.tsx b/src/components/user/UserSeasons.tsx index 46d91a8..319431d 100644 --- a/src/components/user/UserSeasons.tsx +++ b/src/components/user/UserSeasons.tsx @@ -40,7 +40,7 @@ export default function UserSeasons({ username }: { username: string }) { function UserSeasonResult({ event, status, username }: Omit & { username: string }) { const { t } = useTranslation(); const charts = useSeasonCharts(event.asset); - const ranking = useSeasonRanking(event, status, charts.songhashes ?? null); + const ranking = useSeasonRanking(event, status, charts.songIds ?? null); // Use the same complete standings as the season page, then select this user. const entry = ranking.entries?.find(row => row.username === username); const error = charts.error ?? ranking.error; diff --git a/src/config/api.ts b/src/config/api.ts index 0ba933e..e9c7cee 100644 --- a/src/config/api.ts +++ b/src/config/api.ts @@ -4,10 +4,15 @@ export const apiroot3 = '/api3/api'; export const endpoints = { // 成绩排行与统计,统一位于 /api/maiscore 下 maiscore: { - // 单谱面排行榜,返回 8 个难度各自的前 10 名 + // 单谱面排行榜,响应 { hash, levelHashes, scores }:levelHashes 固定 7 项,下标为难度序号, + // 没有 inote 的难度为 null;scores[level] 为该难度按 level hash 查到的前 10 名,共 8 项,最后一项恒为空数组 chartLeaderboard: (chartId: string | number) => `${apiroot3}/maiscore/leaderboard/chart/by-id/${encodeURIComponent(chartId)}`, - // POST,按谱面 Hash 集合和时间段统计排行(季赛榜) + // 单个难度(level hash)的排行榜,响应 { levelHash, scores };成绩按 level hash 共享, + // 内容相同的难度(换源前后、不同谱面)是同一个榜。levelHash 不是 64 位小写 hex 时返回 400 + levelLeaderboard: (levelHash: string) => + `${apiroot3}/maiscore/leaderboard/chart/by-level/${encodeURIComponent(levelHash)}`, + // POST,按谱面 Id 集合(请求体 songIds)和时间段统计排行(季赛榜) periodLeaderboard: `${apiroot3}/maiscore/leaderboard/period`, // 成绩总和榜;uploader 为空时为全站榜,否则只统计该上传者的谱面 scoreSums: (uploader: string, page: number, pageSize: number) => diff --git a/src/hooks/useCollections.ts b/src/hooks/useCollections.ts index f27f77c..09f089c 100644 --- a/src/hooks/useCollections.ts +++ b/src/hooks/useCollections.ts @@ -14,6 +14,14 @@ import type { Collection, CollectionDanInfo } from '@/types'; const fetcher = (url: string) => fetch(url, { mode: 'cors', credentials: 'include' }).then((res) => res.json()); +/** 要加入或移出谱单的谱面 */ +export interface CollectionChart { + /** 谱面 Id(MaiChart.Id),谱单增删按它提交 */ + chartId: string; + /** 谱面当前的 maidata hash,用于对照 hashlist 判断是否已在谱单中 */ + songHash: string; +} + export function useCollections() { const { t } = useTranslation(); const { username } = useUserContext(); @@ -78,15 +86,16 @@ export function useCollections() { ); // 切换歌曲在收藏夹中的状态(添加 / 移除) + // hashlist 仍返回 hash,所以按 hash 判断是否已收录;增删请求按谱面 Id 提交 const toggleSongInCollection = useCallback( - async (collectionId: string, songHash: string) => { + async (collectionId: string, { chartId, songHash }: CollectionChart) => { if (!username) return; const isIn = isSongInCollection(collectionId, songHash); setPendingIds((prev) => new Set(prev).add(collectionId)); try { const body = isIn - ? { hashesToRemove: [songHash] } - : { hashesToAdd: [songHash] }; + ? { chartIdsToRemove: [chartId] } + : { chartIdsToAdd: [chartId] }; const res = await fetch(endpoints.collection.diff(collectionId), { method: 'POST', diff --git a/src/hooks/useSeasonBreakdown.ts b/src/hooks/useSeasonBreakdown.ts index f819443..cffedb9 100644 --- a/src/hooks/useSeasonBreakdown.ts +++ b/src/hooks/useSeasonBreakdown.ts @@ -18,7 +18,7 @@ export interface SeasonBreakdownItem { } type SeasonStatus = 'upcoming' | 'ongoing' | 'ended'; -type ChartState = Pick; +type ChartState = Pick; interface SeasonBreakdownSnapshot { rows?: PlayHistoryRankingEntry[]; @@ -34,14 +34,15 @@ export function useSeasonBreakdown( status: SeasonStatus, ) { const configuration = useMemo(() => { - if (!chartState.songhashes || chartState.error) return { error: chartState.error }; + if (!chartState.songIds || chartState.error) return { error: chartState.error }; try { - const request = buildSeasonRankingRequest(event, chartState.songhashes); - return { requests: request.songhashes.map(hash => ({ ...request, songhashes: [hash] })) }; + const request = buildSeasonRankingRequest(event, chartState.songIds); + // One request per chart; songIds follows `items`, so results align by index below. + return { requests: request.songIds.map(id => ({ ...request, songIds: [id] })) }; } catch (error) { return { error: error instanceof Error ? error : new Error('Invalid season configuration') }; } - }, [event, chartState.songhashes, chartState.error]); + }, [event, chartState.songIds, chartState.error]); const enabled = active && Boolean(playerId) && status !== 'upcoming' && Boolean(configuration.requests); // Every player uses the same complete per-song standings. SWR handles cache // sharing and in-flight deduplication; playerId only selects rows below. diff --git a/src/hooks/useSeasonCharts.ts b/src/hooks/useSeasonCharts.ts index 4048f5c..741d2bf 100644 --- a/src/hooks/useSeasonCharts.ts +++ b/src/hooks/useSeasonCharts.ts @@ -56,7 +56,7 @@ async function fetchSeasonChart(chart: SeasonChart): Promise return item; } -/** Load the complete collection before resolving current chart versions. */ +/** Load the complete collection before loading chart metadata. */ export async function fetchSeasonCollection(id: string): Promise { const controller = new AbortController(); const timeout = window.setTimeout(() => controller.abort(), 15_000); @@ -83,9 +83,9 @@ export async function fetchSeasonCollection(id: string): Promise } } -/** One metadata snapshot supplies both the visible pool and the ranking hashes. */ +/** One metadata snapshot supplies both the visible pool and the ranking chart IDs. */ export function useSeasonCharts(collectionId: string) { - // Resolve current versions on every visit before reusing cached standings. + // Reload the pool and chart metadata on every visit before reusing cached standings. const snapshotId = useId(); const { data, error: requestError, isLoading, isValidating, mutate } = useSWR( ['season-chart-summaries', snapshotId, collectionId], @@ -104,13 +104,13 @@ export function useSeasonCharts(collectionId: string) { const resolved = useMemo(() => { if (requestError) return { error: requestError }; if (isLoading || isValidating || !data) return {}; + // Rankings wait for every chart, so a missing chart never silently drops out of the totals. const error = data.find(item => item.error)?.error; if (error) return { error }; - const songhashes = data.map(item => item.song!.hash); - if (new Set(songhashes).size !== songhashes.length) { - return { error: new Error('Multiple season charts resolve to the same hash') }; - } - return { songhashes }; + // The collection already normalized and deduplicated these IDs; keep the + // order of `items`, which per-chart breakdowns align with by index. + const songIds = data.map(item => item.id); + return { songIds }; }, [data, requestError, isLoading, isValidating]); async function retry(id?: string) { diff --git a/src/hooks/useSeasonLastPlayed.ts b/src/hooks/useSeasonLastPlayed.ts index 1a47003..8ff924d 100644 --- a/src/hooks/useSeasonLastPlayed.ts +++ b/src/hooks/useSeasonLastPlayed.ts @@ -8,7 +8,6 @@ import { buildSeasonRankingRequest, createSeasonRequestLimiter } from '@/utils/s type SeasonStatus = 'upcoming' | 'ongoing' | 'ended'; interface RecentQuery { chartIds: string[]; - songhashes: string[]; startTime: string; endTime: string; } @@ -37,16 +36,17 @@ function fetchLastPlayed([, url, , query]: RecentKey): Promise { /** Mount only for players on the current leaderboard page. */ export function useSeasonLastPlayed(username: string, event: Event, chartState: SeasonChartsState, status: SeasonStatus) { - const { items, songhashes, isLoading: chartsLoading, error: chartsError } = chartState; + const { songIds, isLoading: chartsLoading, error: chartsError } = chartState; const query = useMemo(() => { - if (chartsLoading || chartsError || !songhashes) return undefined; + if (chartsLoading || chartsError || !songIds) return undefined; try { - const { startTime, endTime } = buildSeasonRankingRequest(event, songhashes); - return { chartIds: items.map(item => item.id), songhashes, startTime, endTime }; + // The same chart IDs as the ranking request, so recent plays cover the same pool. + const { songIds: chartIds, startTime, endTime } = buildSeasonRankingRequest(event, songIds); + return { chartIds, startTime, endTime }; } catch { return undefined; } - }, [event, items, songhashes, chartsLoading, chartsError]); + }, [event, songIds, chartsLoading, chartsError]); const key: RecentKey | null = status !== 'upcoming' && query && username ? ['season-last-played', endpoints.account.recent(username), event.id, query, status] : null; diff --git a/src/hooks/useSeasonRanking.ts b/src/hooks/useSeasonRanking.ts index 742a2a1..8ce8832 100644 --- a/src/hooks/useSeasonRanking.ts +++ b/src/hooks/useSeasonRanking.ts @@ -46,10 +46,10 @@ export function fetchSeasonRanking([url, request]: [string, RankingRequest]): Pr }); } -/** The full payload is part of the SWR key, keeping fixed chart versions and seasons isolated. */ -export function useSeasonRanking(event: Event, status: SeasonStatus, songhashes: string[] | null) { +/** The full payload is part of the SWR key, keeping chart pools and seasons isolated. */ +export function useSeasonRanking(event: Event, status: SeasonStatus, songIds: string[] | null) { // null means the shared metadata snapshot has not resolved the complete pool. - const request = useMemo(() => songhashes === null ? null : buildSeasonRankingRequest(event, songhashes), [event, songhashes]); + const request = useMemo(() => songIds === null ? null : buildSeasonRankingRequest(event, songIds), [event, songIds]); // A status change queries once at the boundary; there is no periodic polling. const { data, error, isLoading, isValidating, mutate } = useSWR( status === 'upcoming' || !request ? null : [endpoints.maiscore.periodLeaderboard, request, status], diff --git a/src/locales/en.json b/src/locales/en.json index b235cdf..ec36d8b 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -118,7 +118,6 @@ "Creator": "Creator", "DescriptionPlaceholder": "Description (Optional)", "EmptyCollection": "Empty Collection", - "FetchHashFailed": "Failed to fetch song hash", "InvalidParams": "Invalid parameters", "LatestActivity": "Latest Activity", "LikeCount": "Likes", diff --git a/src/locales/ja.json b/src/locales/ja.json index 4ff1aad..a739458 100644 --- a/src/locales/ja.json +++ b/src/locales/ja.json @@ -115,7 +115,6 @@ "Creator": "クリエイター", "DescriptionPlaceholder": "説明(オプション)", "EmptyCollection": "空のコレクション", - "FetchHashFailed": "曲のハッシュ取得に失敗しました", "InvalidParams": "無効なパラメータ", "LatestActivity": "最近のアクティビティ", "LikeCount": "いいね数", diff --git a/src/locales/ko.json b/src/locales/ko.json index be0888f..33d8d78 100644 --- a/src/locales/ko.json +++ b/src/locales/ko.json @@ -115,7 +115,6 @@ "Creator": "작성자", "DescriptionPlaceholder": "설명 (선택 사항)", "EmptyCollection": "빈 컬렉션", - "FetchHashFailed": "곡 해시 가져오기 실패", "InvalidParams": "잘못된 매개변수", "LatestActivity": "최근 활동", "LikeCount": "좋아요 수", diff --git a/src/locales/zh.json b/src/locales/zh.json index f17d5e4..28c9bca 100644 --- a/src/locales/zh.json +++ b/src/locales/zh.json @@ -115,7 +115,6 @@ "Creator": "创建者", "DescriptionPlaceholder": "描述内容(可选)", "EmptyCollection": "歌单为空", - "FetchHashFailed": "获取歌曲 hash 失败", "InvalidParams": "参数错误", "LatestActivity": "最近互动", "LikeCount": "赞", diff --git a/src/pages/SongPage.tsx b/src/pages/SongPage.tsx index 7b86ece..be5299b 100644 --- a/src/pages/SongPage.tsx +++ b/src/pages/SongPage.tsx @@ -409,6 +409,7 @@ function SongInfo({ data }: { id: string; data: SongSummary }) { setIsCollectionModalOpen(false)} + chartId={o.id} songHash={o.hash} />
diff --git a/src/pages/collection/CollectionPage.tsx b/src/pages/collection/CollectionPage.tsx index 9776637..ed80c01 100644 --- a/src/pages/collection/CollectionPage.tsx +++ b/src/pages/collection/CollectionPage.tsx @@ -36,7 +36,6 @@ export default function CollectionPage() { const [addedIds, setAddedIds] = useState([]); const [removedIds, setRemovedIds] = useState([]); const [addedSongs, setAddedSongs] = useState([]); - const [addedHashes, setAddedHashes] = useState([]); const [isSubmitting, setIsSubmitting] = useState(false); const [visibilityDraft, setVisibilityDraft] = useState(null); const [nameDraft, setNameDraft] = useState(null); @@ -44,7 +43,6 @@ export default function CollectionPage() { // 搜索状态 const [searchQuery, setSearchQuery] = useState(''); - const [addingSongId, setAddingSongId] = useState(null); const [searchPage, setSearchPage] = useState(0); const [searchMaxPage, setSearchMaxPage] = useState(999999); const [searchSortType, setSearchSortType] = useState(0); @@ -130,44 +128,18 @@ export default function CollectionPage() { setSearchMaxPage(999999); }, 500); - // 添加歌曲到歌单(同时获取 hash) - const handleAddSong = async (song: Song) => { - if (allExistingIds.has(song.id) || addingSongId) return; - - // 先尝试从搜索结果中获取 hash(API 可能返回了但 TS 类型未声明) - let hash = song.hash; - - if (!hash) { - setAddingSongId(song.id); - try { - const summary = await fetch(endpoints.maichart.summary(song.id), { - mode: 'cors', - credentials: 'include', - }).then((res) => res.json()); - hash = summary?.hash; - } catch { - // ignore - } - setAddingSongId(null); - } - - if (!hash) { - toast.error(t("collection/CollectionPage.FetchHashFailed")); - return; - } - + // 添加歌曲到歌单 + const handleAddSong = (song: Song) => { + if (allExistingIds.has(song.id)) return; setAddedIds((prev) => [...prev, song.id]); setAddedSongs((prev) => [...prev, song]); - setAddedHashes((prev) => [...prev, hash]); }; // 从歌单移除歌曲 const handleRemoveSong = (songId: string) => { if (addedIds.includes(songId)) { - const idx = addedIds.indexOf(songId); setAddedIds((prev) => prev.filter((id) => id !== songId)); setAddedSongs((prev) => prev.filter((s) => s.id !== songId)); - setAddedHashes((prev) => prev.filter((_, i) => i !== idx)); } else { setRemovedIds((prev) => (prev.includes(songId) ? prev : [...prev, songId])); } @@ -179,18 +151,10 @@ export default function CollectionPage() { setIsSubmitting(true); - // 构造当前 hash 列表:原有(未移除) + 新增 - const currentHashes: string[] = []; - for (const song of collectionData?.items || []) { - if (!removedIds.includes(song.id)) { - currentHashes.push(song.hash); - } - } - currentHashes.push(...addedHashes); - const body: Record = {}; if (addedIds.length > 0 || removedIds.length > 0) { - body.items = currentHashes; + // 谱面 Id 列表即当前显示的顺序:原有(未移除) + 新增 + body.items = displaySongs.map((s) => s.id); } if (visibilityChanged) { body.visibility = visibilityDraft; @@ -217,7 +181,6 @@ export default function CollectionPage() { setAddedIds([]); setRemovedIds([]); setAddedSongs([]); - setAddedHashes([]); setVisibilityDraft(null); setNameDraft(null); setDescriptionDraft(null); @@ -242,7 +205,6 @@ export default function CollectionPage() { setAddedIds([]); setRemovedIds([]); setAddedSongs([]); - setAddedHashes([]); setVisibilityDraft(null); setNameDraft(null); setDescriptionDraft(null); @@ -407,7 +369,7 @@ export default function CollectionPage() {
- {(isSearchLoading || addingSongId) && ( + {isSearchLoading && (
@@ -429,10 +391,9 @@ export default function CollectionPage() { if (isAdded) handleRemoveSong(song.id) else handleAddSong(song); }} - disabled={!!addingSongId} className={`top-2 right-2 z-10 absolute flex justify-center items-center shadow-lg border-none rounded-full w-6 h-6 font-bold text-white text-base leading-none cursor-pointer transition-colors ${isAdded ? 'bg-red-500/80 hover:bg-red-500' - : 'bg-blue-500/80 hover:bg-blue-500 disabled:bg-white/10 disabled:cursor-not-allowed' + : 'bg-blue-500/80 hover:bg-blue-500' }`} title={isAdded ? t("collection/CollectionPage.RemoveFromCollection") : t("collection/CollectionPage.Add")} > diff --git a/src/pages/user/ScoresPage.tsx b/src/pages/user/ScoresPage.tsx index 0b4e871..48ba975 100644 --- a/src/pages/user/ScoresPage.tsx +++ b/src/pages/user/ScoresPage.tsx @@ -340,7 +340,7 @@ export default function PersonalScoresPage() {
{paginatedData.map((score) => ( 0 || event.type !== 'season') { throw new Error(errors.length > 0 ? errors.join('; ') : 'A valid season event is required'); } - const songhashes = [...resolvedHashes]; - if (songhashes.length === 0 - || !songhashes.every((hash): hash is string => typeof hash === 'string' && hash.trim() !== '' && hash === hash.trim())) { - throw new Error('Every season chart must resolve to a valid hash before querying the ranking'); + const songIds = [...chartIds]; + if (songIds.length === 0 + || !songIds.every((id): id is string => typeof id === 'string' && id.trim() !== '' && id === id.trim())) { + throw new Error('Every season chart must have a valid chart ID before querying the ranking'); } - if (new Set(songhashes).size !== songhashes.length) { - throw new Error('Resolved season chart hashes must not be duplicated'); + if (new Set(songIds).size !== songIds.length) { + throw new Error('Season chart IDs must not be duplicated'); } return { - songhashes, + songIds, startTime: new Date(event.createDate).toISOString(), endTime: new Date(event.endDate).toISOString(), scoreType: 'best', diff --git a/test/components/collection/CollectionModal.test.tsx b/test/components/collection/CollectionModal.test.tsx new file mode 100644 index 0000000..29a5fd5 --- /dev/null +++ b/test/components/collection/CollectionModal.test.tsx @@ -0,0 +1,41 @@ +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import CollectionModal from '@/components/collection/CollectionModal'; + +const collections = vi.hoisted(() => ({ + collections: [{ id: 'collection', name: 'Favorites', createdBy: 'alice', description: null, count: 1 }], + error: undefined, isLoading: false, + isSongInCollection: vi.fn(() => false), toggleSongInCollection: vi.fn(), isPending: vi.fn(() => false), + mutateCollections: vi.fn(), mutateHashLists: vi.fn(), +})); +vi.mock('@/hooks', () => ({ useCollections: () => collections })); +vi.mock('@/components', () => ({ LoadingSpinner: () => null })); +(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +const container = document.createElement('div'); +let root = createRoot(container); +afterEach(async () => { + await act(async () => root.unmount()); + root = createRoot(container); + vi.clearAllMocks(); +}); + +const chartId = '0f8fad5b-d9cb-469f-a165-70867728950e'; +const songHash = 'd41d8cd98f00b204e9800998ecf8427e'; +const collectionButton = () => + Array.from(container.querySelectorAll('button')).find((b) => b.textContent?.includes('Favorites'))!; + +describe('collection modal', () => { + it('toggles with the chart ID and checks membership by hash', async () => { + await act(async () => root.render( {}} chartId={chartId} songHash={songHash} />)); + expect(collections.isSongInCollection).toHaveBeenCalledWith('collection', songHash); + await act(async () => collectionButton().click()); + expect(collections.toggleSongInCollection).toHaveBeenCalledWith('collection', { chartId, songHash }); + }); + + it('cannot toggle without a chart ID', async () => { + await act(async () => root.render( {}} songHash={songHash} />)); + await act(async () => collectionButton().click()); + expect(collections.toggleSongInCollection).not.toHaveBeenCalled(); + }); +}); diff --git a/test/components/score/ScoreCard.test.tsx b/test/components/score/ScoreCard.test.tsx new file mode 100644 index 0000000..6c0a1be --- /dev/null +++ b/test/components/score/ScoreCard.test.tsx @@ -0,0 +1,102 @@ +import { act, type ReactNode } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { MemoryRouter } from 'react-router-dom'; +import { SWRConfig } from 'swr'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { ScoreCard } from '@/components/score/ScoreCard'; +import type { Score } from '@/types'; + +vi.mock('@/components', () => ({ + CoverPic: () => null, + Level: () => null, + LazyLoad: ({ children }: { children: ReactNode }) => <>{children}, +})); +vi.mock('@/components/song/SongInteraction', () => ({ ChartVoteBadge: () => null })); +vi.mock('@/components/user/UserAvatar', () => ({ default: () => null })); +vi.mock('@/hooks', () => ({ useUsername: () => 'Alice' })); +(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const LEVEL_HASH = '0123456789abcdef'.repeat(4); +const CHART_ID = '3f2504e0-4f89-11d3-9a0c-0305e82c3301'; + +const makeScore = (levelHash?: string | null): Score => ({ + acc: { dx: 100.5, classic: 101 }, + dxScore: 1234, + comboState: 0, + chartLevel: 3, + hash: 'u/+9gjE3eW1Xv+7aHzaQ0w==', + ...(levelHash === undefined ? {} : { levelHash }), + chartInfo: { + id: CHART_ID, title: 'Song', artist: 'Artist', designer: 'Designer', description: '', + levels: ['', '', '', '13+'], uploader: 'uploader', timestamp: '', hash: 'u/+9gjE3eW1Xv+7aHzaQ0w==', tags: [], publicTags: [], + }, + timestamp: '2026-10-01T00:00:00Z', +}); +const entry = (username: string, acc: number) => ({ player: { username }, acc, comboState: 0, timestamp: '2026-10-01T00:00:00Z' }); + +let root: Root; +let container: HTMLDivElement; +let fetchMock: ReturnType>; +beforeEach(() => { + container = document.createElement('div'); document.body.append(container); root = createRoot(container); + fetchMock = vi.fn(); vi.stubGlobal('fetch', fetchMock); +}); +afterEach(() => { act(() => root.unmount()); container.remove(); vi.unstubAllGlobals(); }); +async function render(component: ReactNode) { + await act(async () => { root.render( new Map(), shouldRetryOnError: false }}>{component}); }); +} +const requestedUrls = () => fetchMock.mock.calls.map(([url]) => url); +const rankBadge = () => container.querySelector('span[title^="#"]'); + +describe('ScoreCard rank', () => { + it('reads the rank from the level leaderboard when the score has a level hash', async () => { + fetchMock.mockResolvedValue(Response.json({ levelHash: LEVEL_HASH, scores: [entry('bob', 101), entry(' alice ', 100.5), entry('carol', 99)] })); + await render(); + expect(requestedUrls()).toEqual([`/api3/api/maiscore/leaderboard/chart/by-level/${LEVEL_HASH}`]); + expect(rankBadge()?.textContent).toBe('#2'); + expect(rankBadge()?.getAttribute('title')).toBe('#2 / 3'); + }); + + it('shows no rank when the player is not on the level leaderboard', async () => { + fetchMock.mockResolvedValue(Response.json({ levelHash: LEVEL_HASH, scores: [entry('bob', 101)] })); + await render(); + expect(requestedUrls()).toEqual([`/api3/api/maiscore/leaderboard/chart/by-level/${LEVEL_HASH}`]); + expect(rankBadge()).toBeNull(); + }); + + // 迁移期的旧成绩没有 level hash;格式不对的值也不拿去请求 by-level + it.each([ + ['missing', undefined], + ['null', null], + ['empty', ''], + ['uppercase', LEVEL_HASH.toUpperCase()], + ['too short', LEVEL_HASH.slice(1)], + ])('falls back to the chart leaderboard by chart id when the level hash is %s', async (_, levelHash) => { + const scores: unknown[][] = Array.from({ length: 8 }, () => []); + scores[3] = [entry('alice', 100.5), entry('bob', 99)]; + fetchMock.mockResolvedValue(Response.json({ hash: 'u/+9gjE3eW1Xv+7aHzaQ0w==', levelHashes: [null, null, null, LEVEL_HASH, null, null, null], scores })); + await render(); + expect(requestedUrls()).toEqual([`/api3/api/maiscore/leaderboard/chart/by-id/${CHART_ID}`]); + expect(rankBadge()?.getAttribute('title')).toBe('#1 / 2'); + }); + + it('keeps scanning the other levels of the chart leaderboard in the fallback', async () => { + const scores: unknown[][] = Array.from({ length: 8 }, () => []); + scores[1] = [entry('bob', 101), entry('carol', 100), entry('alice', 99)]; + fetchMock.mockResolvedValue(Response.json({ hash: 'h', levelHashes: Array(7).fill(null), scores })); + await render(); + expect(rankBadge()?.getAttribute('title')).toBe('#3 / 3'); + }); + + it('ranks the given player instead of the signed-in one', async () => { + fetchMock.mockResolvedValue(Response.json({ levelHash: LEVEL_HASH, scores: [entry('alice', 101), entry('dave', 100)] })); + await render(); + expect(rankBadge()?.getAttribute('title')).toBe('#2 / 2'); + }); + + it('does not request any leaderboard without showRank', async () => { + await render(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(rankBadge()).toBeNull(); + }); +}); diff --git a/test/components/season/SeasonLeaderboard.test.tsx b/test/components/season/SeasonLeaderboard.test.tsx index abba4ed..5554fff 100644 --- a/test/components/season/SeasonLeaderboard.test.tsx +++ b/test/components/season/SeasonLeaderboard.test.tsx @@ -28,6 +28,7 @@ const event: Event = { alt: 'Season', title: 'Season', description: 'Season', category: 5, createDate: '2026-09-01T00:00:00+08:00', endDate: '2026-09-30T23:59:59.999+08:00', }; +const chartId = '3f2504e0-4f89-11d3-9a0c-0305e82c3301'; const rows = [{ playerId: 'player-one', username: 'Player & One', totalDXScore: 1200, totalAccDX: 100.1234, totalAccClassic: 100, player: { id: 'player-one', username: 'Player & One', nickname: 'P1', avatarId: 'one-avatar' }, @@ -42,7 +43,7 @@ describe('season leaderboard recovery', () => { let fetchMock: ReturnType>; function RankingProbe() { - const state = useSeasonRanking(event, 'ongoing', charts.songhashes ?? null); + const state = useSeasonRanking(event, 'ongoing', charts.songIds ?? null); useEffect(() => { ranking = state; }, [state]); return null; } @@ -51,7 +52,7 @@ describe('season leaderboard recovery', () => { container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container); - charts = { items: [], songhashes: ['current-hash'], isLoading: false, retry: vi.fn().mockResolvedValue(undefined) }; + charts = { items: [], songIds: [chartId], isLoading: false, retry: vi.fn().mockResolvedValue(undefined) }; fetchMock = vi.fn(); vi.stubGlobal('fetch', fetchMock); }); @@ -95,8 +96,9 @@ describe('season leaderboard recovery', () => { const [url, options] = fetchMock.mock.calls[1]; expect(url).toBe('/api3/api/maiscore/leaderboard/period'); expect(options?.method).toBe('POST'); + // 按谱面 Id 查询;请求体里不再有 hash 字段 expect(JSON.parse(options?.body as string)).toEqual({ - songhashes: ['current-hash'], startTime: '2026-08-31T16:00:00.000Z', + songIds: [chartId], startTime: '2026-08-31T16:00:00.000Z', endTime: '2026-09-30T15:59:59.999Z', scoreType: 'best', sortBy: 'Acc.DX', }); }); @@ -119,7 +121,7 @@ describe('season leaderboard recovery', () => { }); it('retries metadata first when the chart pool failed to resolve', async () => { - charts = { ...charts, songhashes: undefined, error: new Error('Chart request failed') }; + charts = { ...charts, songIds: undefined, error: new Error('Chart request failed') }; await render(); await act(async () => retryButton()!.click()); expect(charts.retry).toHaveBeenCalledOnce(); diff --git a/test/config/api.test.ts b/test/config/api.test.ts new file mode 100644 index 0000000..c65d3b7 --- /dev/null +++ b/test/config/api.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { endpoints } from '@/config/api'; + +describe('endpoints.maiscore', () => { + it('builds the chart leaderboard by chart id', () => { + expect(endpoints.maiscore.chartLeaderboard('3f2504e0-4f89-11d3-9a0c-0305e82c3301')) + .toBe('/api3/api/maiscore/leaderboard/chart/by-id/3f2504e0-4f89-11d3-9a0c-0305e82c3301'); + }); + + it('builds the level leaderboard by level hash', () => { + const levelHash = '0123456789abcdef'.repeat(4); + expect(endpoints.maiscore.levelLeaderboard(levelHash)) + .toBe(`/api3/api/maiscore/leaderboard/chart/by-level/${levelHash}`); + }); + + it('escapes the level hash as a single path segment', () => { + expect(endpoints.maiscore.levelLeaderboard('a/b c?d')) + .toBe('/api3/api/maiscore/leaderboard/chart/by-level/a%2Fb%20c%3Fd'); + }); +}); diff --git a/test/hooks/useCollections.test.tsx b/test/hooks/useCollections.test.tsx new file mode 100644 index 0000000..3bdfa0e --- /dev/null +++ b/test/hooks/useCollections.test.tsx @@ -0,0 +1,71 @@ +import { act, useEffect } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { SWRConfig } from 'swr'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { useCollections } from '@/hooks/useCollections'; +import { endpoints } from '@/config/api'; + +vi.mock('@/hooks', () => ({ + useUserContext: () => ({ username: 'alice' }), +})); +vi.mock('react-toastify', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); +(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const chart = { chartId: '0f8fad5b-d9cb-469f-a165-70867728950e', songHash: 'd41d8cd98f00b204e9800998ecf8427e' }; +let hook: ReturnType; +function Probe() { + const value = useCollections(); + useEffect(() => { hook = value; }); + return null; +} + +describe('useCollections', () => { + let container: HTMLDivElement; + let root: Root; + let fetchMock: ReturnType>; + beforeEach(() => { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + fetchMock = vi.fn(async (input) => { + const url = String(input); + if (url === endpoints.collection.list(0, 100, 'alice')) { + return Response.json([ + { id: 'with-song', name: 'A', createdBy: 'alice', description: null, count: 1 }, + { id: 'without-song', name: 'B', createdBy: 'alice', description: null, count: 1 }, + ]); + } + // hashlist 的响应不变:仍是谱面 hash;without-song 里放谱面 Id,确认不会按 Id 判断成员 + if (url === endpoints.collection.hashlist('with-song')) return Response.json({ songHashs: [chart.songHash] }); + if (url === endpoints.collection.hashlist('without-song')) return Response.json({ songHashs: [chart.chartId] }); + return new Response(null, { status: 200 }); + }); + vi.stubGlobal('fetch', fetchMock); + }); + afterEach(() => { + act(() => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); + }); + + function diffBody(collectionId: string) { + const call = fetchMock.mock.calls.find(([url]) => url === endpoints.collection.diff(collectionId)); + expect(call?.[1]?.method).toBe('POST'); + return JSON.parse(String(call![1]!.body)); + } + + it('sends chart IDs in diff requests and decides membership by hashlist hashes', async () => { + await act(async () => root.render( + new Map(), shouldRetryOnError: false }}>, + )); + expect(hook.isLoading).toBe(false); + expect(hook.isSongInCollection('with-song', chart.songHash)).toBe(true); + expect(hook.isSongInCollection('without-song', chart.songHash)).toBe(false); + + await act(async () => hook.toggleSongInCollection('with-song', chart)); + expect(diffBody('with-song')).toEqual({ chartIdsToRemove: [chart.chartId] }); + + await act(async () => hook.toggleSongInCollection('without-song', chart)); + expect(diffBody('without-song')).toEqual({ chartIdsToAdd: [chart.chartId] }); + }); +}); diff --git a/test/hooks/useSeasonBreakdown.test.tsx b/test/hooks/useSeasonBreakdown.test.tsx new file mode 100644 index 0000000..4afd4c4 --- /dev/null +++ b/test/hooks/useSeasonBreakdown.test.tsx @@ -0,0 +1,97 @@ +import { act, useEffect } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { SWRConfig } from 'swr'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { useSeasonBreakdown } from '@/hooks/useSeasonBreakdown'; +import type { SeasonChartsState } from '@/hooks/useSeasonCharts'; +import type { Event, PlayHistoryRankingRequest } from '@/types/event'; + +(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const event: Event = { + id: 'test-season', type: 'season', asset: '69f3ace2bb1f42b84457a4f9', src: '/season.jpg', + alt: 'Season', title: 'Season', description: 'Season', category: 5, + createDate: '2026-09-01T00:00:00+08:00', endDate: '2026-09-30T23:59:59.999+08:00', +}; +const first = '3f2504e0-4f89-11d3-9a0c-0305e82c3301'; +const second = '9b2e6c1a-0d4f-4e6b-8a7c-5f1e2d3c4b5a'; +const row = (playerId: string, totalAccDX: number) => ({ playerId, username: playerId, totalDXScore: 1000, totalAccDX, totalAccClassic: 100 }); +const chart = (id: string) => ({ + id, chart: `/song?id=${id}`, + song: { id, title: `Song ${id}`, artist: '', uploader: '', designer: '', levels: ['', '7'], hash: 'same-hash' }, +}); + +describe('useSeasonBreakdown', () => { + let container: HTMLDivElement; + let root: Root; + let breakdown: ReturnType | undefined; + let fetchMock: ReturnType>; + // 谱单顺序与 Id 字母序相反,结果必须按下标对齐 items + const chartState: Pick = { + items: [chart(second), chart(first)], songIds: [second, first], isLoading: false, + }; + + function Probe() { + const state = useSeasonBreakdown(event, chartState, 'player-one', true, 'ongoing'); + useEffect(() => { breakdown = state; }, [state]); + return null; + } + + beforeEach(() => { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + breakdown = undefined; + fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + }); + + afterEach(() => { + act(() => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); + }); + + async function render() { + await act(async () => root.render( + new Map() }}>, + )); + for (let i = 0; i < 3; i += 1) { + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + } + } + + const requestBodies = () => fetchMock.mock.calls.map(([, options]) => JSON.parse(options?.body as string) as PlayHistoryRankingRequest); + + it('queries each chart by its own ID and aligns the results with the pool', async () => { + fetchMock.mockImplementation(async (_, options) => { + const [id] = (JSON.parse(options?.body as string) as PlayHistoryRankingRequest).songIds; + return Response.json(id === first ? [row('player-one', 50.5), row('player-two', 60)] : [row('player-two', 70)]); + }); + await render(); + + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(fetchMock.mock.calls.every(([url]) => url === '/api3/api/maiscore/leaderboard/period')).toBe(true); + expect(requestBodies()).toEqual(expect.arrayContaining([second, first].map(id => ({ + songIds: [id], startTime: '2026-08-31T16:00:00.000Z', + endTime: '2026-09-30T15:59:59.999Z', scoreType: 'best', sortBy: 'Acc.DX', + })))); + expect(breakdown?.items.map(({ id, score, error }) => ({ id, score, error }))).toEqual([ + { id: second, score: undefined, error: undefined }, + { id: first, score: 50.5, error: undefined }, + ]); + expect(breakdown?.hasErrors).toBe(false); + }); + + it('marks only the chart whose request failed', async () => { + fetchMock.mockImplementation(async (_, options) => { + const [id] = (JSON.parse(options?.body as string) as PlayHistoryRankingRequest).songIds; + return id === second ? new Response('', { status: 503 }) : Response.json([row('player-one', 50.5)]); + }); + await render(); + + expect(breakdown?.items[0].error?.message).toBe('Ranking request failed (503)'); + expect(breakdown?.items[1]).toMatchObject({ id: first, score: 50.5, error: undefined }); + expect(breakdown?.hasErrors).toBe(true); + }); +}); diff --git a/test/hooks/useSeasonCharts.test.tsx b/test/hooks/useSeasonCharts.test.tsx new file mode 100644 index 0000000..8bd9797 --- /dev/null +++ b/test/hooks/useSeasonCharts.test.tsx @@ -0,0 +1,96 @@ +import { act, useEffect } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { SWRConfig } from 'swr'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { useSeasonCharts, type SeasonChartsState } from '@/hooks/useSeasonCharts'; + +(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const collectionId = '69f3ace2bb1f42b84457a4f9'; +const first = '3f2504e0-4f89-11d3-9a0c-0305e82c3301'; +const second = '9b2e6c1a-0d4f-4e6b-8a7c-5f1e2d3c4b5a'; +const summary = (id: string, hash = 'same-hash') => ({ id, title: `Song ${id}`, hash, levels: [null, '7', null, null, null, null, null] }); + +describe('useSeasonCharts', () => { + let container: HTMLDivElement; + let root: Root; + let charts: SeasonChartsState | undefined; + let fetchMock: ReturnType>; + + function Probe() { + const state = useSeasonCharts(collectionId); + useEffect(() => { charts = state; }, [state]); + return null; + } + + beforeEach(() => { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + charts = undefined; + fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + }); + + afterEach(() => { + act(() => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); + }); + + function serve(summaries: Record Promise>) { + fetchMock.mockImplementation(async input => { + const url = String(input); + if (url === `/api3/api/collection/${collectionId}/songlist`) { + // 谱单顺序与 Id 字母序相反,GUID 大写也要规范化成小写 + return Response.json({ items: [{ id: second.toUpperCase() }, { id: first }] }); + } + const id = /\/maichart\/([^/]+)\/summary$/.exec(url)?.[1]; + if (id && summaries[id]) return summaries[id](); + throw new Error(`Unexpected request ${url}`); + }); + } + + // 谱单和各谱面摘要依次经过请求队列,多等几轮让 SWR 完成 + async function flush() { + for (let i = 0; i < 3; i += 1) { + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + } + } + + async function render() { + await act(async () => root.render( + new Map() }}>, + )); + await flush(); + } + + it('gives the collection chart IDs in pool order once every chart has loaded', async () => { + // 两张谱面的 hash 相同也不影响:排行只按谱面 Id 查询 + serve({ [first]: async () => Response.json(summary(first)), [second]: async () => Response.json(summary(second)) }); + await render(); + expect(charts?.error).toBeUndefined(); + expect(charts?.items.map(item => item.id)).toEqual([second, first]); + expect(charts?.songIds).toEqual([second, first]); + }); + + it('withholds chart IDs while any chart is still loading', async () => { + let finish!: () => void; + const pending = new Promise(resolve => { finish = () => resolve(Response.json(summary(second))); }); + serve({ [first]: async () => Response.json(summary(first)), [second]: () => pending }); + await render(); + expect(charts?.isLoading).toBe(true); + expect(charts?.songIds).toBeUndefined(); + + await act(async () => finish()); + await flush(); + expect(charts?.songIds).toEqual([second, first]); + }); + + it('reports an error instead of chart IDs when a chart fails to load', async () => { + serve({ [first]: async () => Response.json(summary(first)), [second]: async () => new Response('', { status: 500 }) }); + await render(); + expect(charts?.songIds).toBeUndefined(); + expect(charts?.error?.message).toBe('Chart request failed (500)'); + }); +}); diff --git a/test/pages/collection/CollectionPage.test.tsx b/test/pages/collection/CollectionPage.test.tsx new file mode 100644 index 0000000..1a9abaa --- /dev/null +++ b/test/pages/collection/CollectionPage.test.tsx @@ -0,0 +1,96 @@ +import { act, type ReactNode } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { MemoryRouter } from 'react-router-dom'; +import { SWRConfig } from 'swr'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import CollectionPage from '@/pages/collection/CollectionPage'; +import { endpoints } from '@/config/api'; +import i18n from '@/i18n'; +import type { Song } from '@/types'; + +vi.mock('@/hooks', () => ({ useUserContext: () => ({ username: 'alice' }) })); +vi.mock('@/components', () => ({ + PageLayout: ({ children }: { children: ReactNode }) =>
{children}
, + SongCard: ({ song }: { song: Song }) => {song.title}, + LoadingSpinner: () => null, +})); +vi.mock('@/components/collection/CollectionSubscribeButton', () => ({ default: () => null })); +vi.mock('react-toastify', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); +(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const collectionId = '69f3ace2bb1f42b84457a4f9'; +const song = (id: string, hash = `hash-${id}`) => ({ id, hash, title: id, artist: '', uploader: 'alice', designer: '', levels: [] }); +const collection = { + id: collectionId, name: 'List', createdBy: 'alice', description: '', count: 3, visibility: 0, + items: [song('chart-1'), song('chart-2'), song('chart-3')], +}; +// 搜索结果不带 hash 也能直接添加,不需要再请求 summary +const searchResults = [song('chart-4', ''), song('chart-5', '')]; + +describe('collection management', () => { + let container: HTMLDivElement; + let root: Root; + let fetchMock: ReturnType>; + beforeEach(() => { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + fetchMock = vi.fn(async (input) => { + const url = String(input); + if (url === endpoints.collection.songlist(collectionId)) return Response.json(collection); + if (url.startsWith(endpoints.maichart.listSearchAndSort('chart'))) return Response.json(searchResults); + return new Response(null, { status: 200 }); + }); + vi.stubGlobal('fetch', fetchMock); + }); + afterEach(() => { + act(() => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); + }); + + const buttonByText = (text: string) => + Array.from(container.querySelectorAll('button')).find((b) => b.textContent === text)!; + const cardButton = (id: string) => + container.querySelector(`[data-song="${id}"]`)!.parentElement!.querySelector('button')!; + const click = (button: HTMLButtonElement) => act(async () => button.click()); + + async function startManagingAndSearch() { + await act(async () => root.render( + new Map(), shouldRetryOnError: false }}> + + , + )); + await click(buttonByText(i18n.t('collection/CollectionPage.Manage'))); + const input = container.querySelector(`input[placeholder="${i18n.t('collection/CollectionPage.SearchToAdd')}"]`)!; + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'chart'); + input.dispatchEvent(new Event('input', { bubbles: true })); + }); + expect(container.querySelector('[data-song="chart-5"]')).not.toBeNull(); + } + + async function submittedItems() { + await click(buttonByText(i18n.t('collection/CollectionPage.Submit'))); + const call = fetchMock.mock.calls.find(([url]) => url === endpoints.collection.modify(collectionId)); + expect(call?.[1]?.method).toBe('POST'); + expect(fetchMock.mock.calls.some(([url]) => String(url).endsWith('/summary'))).toBe(false); + return JSON.parse(String(call![1]!.body)).items; + } + + it('submits chart IDs: kept originals in order, then additions in the order added', async () => { + await startManagingAndSearch(); + await click(cardButton('chart-2')); + await click(cardButton('chart-5')); + await click(cardButton('chart-4')); + expect(await submittedItems()).toEqual(['chart-1', 'chart-3', 'chart-5', 'chart-4']); + }); + + it('drops an addition that is removed again before submitting', async () => { + await startManagingAndSearch(); + await click(cardButton('chart-5')); + await click(cardButton('chart-4')); + await click(cardButton('chart-5')); + expect(await submittedItems()).toEqual(['chart-1', 'chart-2', 'chart-3', 'chart-4']); + }); +}); diff --git a/test/utils/season.test.ts b/test/utils/season.test.ts new file mode 100644 index 0000000..bffd1cf --- /dev/null +++ b/test/utils/season.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest'; +import { buildSeasonRankingRequest } from '@/utils/season'; +import type { Event } from '@/types/event'; + +const event: Event = { + id: 'test-season', type: 'season', asset: '69f3ace2bb1f42b84457a4f9', src: '/season.jpg', + alt: 'Season', title: 'Season', description: 'Season', category: 5, + createDate: '2026-09-01T00:00:00+08:00', endDate: '2026-09-30T23:59:59.999+08:00', +}; +const first = '3f2504e0-4f89-11d3-9a0c-0305e82c3301'; +const second = '9b2e6c1a-0d4f-4e6b-8a7c-5f1e2d3c4b5a'; + +describe('buildSeasonRankingRequest', () => { + it('queries the period leaderboard by chart ID in pool order', () => { + const ids = [second, first]; + const request = buildSeasonRankingRequest(event, ids); + expect(request).toEqual({ + songIds: [second, first], startTime: '2026-08-31T16:00:00.000Z', + endTime: '2026-09-30T15:59:59.999Z', scoreType: 'best', sortBy: 'Acc.DX', + }); + expect(request).not.toHaveProperty('songhashes'); + // 复制一份,调用方之后改动自己的数组不会影响已经组装好的请求 + expect(request.songIds).not.toBe(ids); + }); + + it.each([ + ['an empty pool', []], + ['an empty ID', [first, '']], + ['a blank ID', [first, ' ']], + ['surrounding whitespace', [` ${first}`]], + ['a trailing newline', [`${first}\n`]], + ['a non-string ID', [first, null as unknown as string]], + ])('rejects %s', (_, ids) => { + expect(() => buildSeasonRankingRequest(event, ids)).toThrow('valid chart ID'); + }); + + it('rejects duplicated chart IDs', () => { + expect(() => buildSeasonRankingRequest(event, [first, second, first])).toThrow('Season chart IDs must not be duplicated'); + }); + + it('rejects events that are not valid seasons', () => { + expect(() => buildSeasonRankingRequest({ ...event, type: 'eventTag' }, [first])).toThrow('A valid season event is required'); + expect(() => buildSeasonRankingRequest({ ...event, endDate: event.createDate }, [first])).toThrow('createDate must be earlier than endDate'); + }); +});