diff --git a/api-directory.md b/api-directory.md index 4c7e472..f1b33a8 100644 --- a/api-directory.md +++ b/api-directory.md @@ -56,11 +56,12 @@ | --- | --- | --- | | 单曲排行榜 | 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` | +| 季赛榜及单曲明细 | POST `/api/maiscore/leaderboard/period`,`songIds` 代替 `songHashes` | 季赛歌单 `songlist` 的 `items`(谱面 Id 数组) | +| 歌单增删曲目 | 先 GET `songlist` 取当前 `items`,本地增删后 PUT `/api/collection/{id}/modify` 提交完整 `items`;原 POST `/api/collection/{id}/diff` 已移除。是否已收录仍按 `hashlist` 返回的 hash 判断 | 谱面页的谱面 Id | +| 歌单管理保存 | PUT `/api/collection/{id}/modify`(原为 POST),`items` 为谱面 Id 数组,整体替换并按请求顺序保存 | 原有曲目取 `songlist` 的 `items`,新增曲目取搜索结果的 `id`,不再为取 hash 请求 `summary` | +| 歌单曲目展示 | GET `/api/collection/{id}/songlist` 的 `items` 为谱面 Id 数组(歌单顺序);POST `/api/maichart/info`(请求体为 Id 数组)一次取回元信息,按 `items` 的顺序显示,空歌单不请求 | `songlist` 的 `items` | -`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`)只供游戏客户端使用。 +`hashlist`、`favorite/collection/list` 的响应不变;`songlist` 的 `items` 后来改为谱面 Id 数组(见上表)。谱面信息 `/api/maichart/{chartId}/info`、POST `/api/maichart/info` 新增的 `levelHashes` 前端暂未使用;歌单页只读 POST `/api/maichart/info` 的 `metadata`,其余页面读 `summary`。按谱面查成绩总和的 `/api/maiscore/sum/chart/by-id/{chartId}` 前端目前没有调用点。前端没有提交成绩的地方,`POST /api/maiscore/level/{levelHash}`(请求体须带 `chartId`)只供游戏客户端使用。 ## 需要后端修复的阻碍 diff --git a/docs/changelog/2026-11-09-collection-chart-ids.md b/docs/changelog/2026-11-09-collection-chart-ids.md new file mode 100644 index 0000000..d8bba25 --- /dev/null +++ b/docs/changelog/2026-11-09-collection-chart-ids.md @@ -0,0 +1,31 @@ +# 歌单改用谱面 Id 列表与批量谱面信息 + +日期:2026-11-09 +分支:`feat/collection-chart-ids` +提交:`343b73b` feat!: follow mmfcapi collection API changes +配套后端:mmfcapi `dev`(`09a2872`),见该仓库的 `docs/changelog/2026-11-09-collection-chart-ids.md` +接口对照:[api-directory.md](../../api-directory.md) + +## 背景 + +后端移除了歌单增量接口 `POST /api/collection/{id}/diff`,把 `modify` 改为 `PUT`,并让 `songlist` 的 `items` 只返回谱面 Id(歌单顺序),谱面信息改由 `POST /api/maichart/info` 批量获取。 + +## 前端改动 + +| 位置 | 改动 | +| --- | --- | +| `src/hooks/useCollections.ts` | 谱面页加入/移出歌单:先读 `songlist` 的 `items`,本地增删后 `PUT modify` 提交完整列表,不再调用 diff | +| `src/pages/collection/CollectionPage.tsx` | 按 `items` 一次请求 `maichart/info`,按歌单顺序显示,空歌单不请求;管理模式保存改用 `PUT`,提交“原有(未移除)+ 新增”的 Id 列表 | +| `src/utils/chartInfo.ts` | 新增 `fetchChartInfos`:批量取谱面信息,按请求顺序返回,略过不存在的谱面 | +| `src/hooks/useSeasonCharts.ts` | 季赛歌单直接读取 Id 数组 | +| `src/components/collection/CollectionCard.tsx` | 封面使用 Id 数组 | +| `src/types/collection.ts` | `CollectionSongList.items` 改为 `string[]` | + +## 验证 + +- 新增 `e2e/collection.spec.ts`(模拟后端):批量请求谱面信息且保持歌单顺序;空歌单不请求;所有者保存时发送 `PUT modify` 与完整 `items`;全程不调用 diff。 +- e2e 20/20、ESLint、`tsc -b`、Vitest 252/252 通过。未对真实后端联调。 + +## 部署 + +须与后端同时部署。 diff --git a/e2e/collection.spec.ts b/e2e/collection.spec.ts new file mode 100644 index 0000000..ce853a0 --- /dev/null +++ b/e2e/collection.spec.ts @@ -0,0 +1,131 @@ +import { expect, test } from '@playwright/test'; +import type { Page, Request } from '@playwright/test'; + +const collectionId = '6a70107b8d6a8b09dbb5e8aa'; +const chartA = '11111111-1111-4111-8111-111111111111'; +const chartB = '22222222-2222-4222-8222-222222222222'; +const chartC = '33333333-3333-4333-8333-333333333333'; +const missingChart = '99999999-9999-4999-8999-999999999999'; +const titles: Record = { [chartA]: 'Alpha fixture', [chartB]: 'Bravo fixture', [chartC]: 'Charlie fixture' }; +// A 1×1 transparent PNG: covers and avatars load without depending on any file in public/. +const placeholderImage = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', 'base64'); + +/** One item of `POST /api/maichart/info`, shaped like the backend's `OnlineChartInfo`. */ +const chartInfo = (id: string) => ({ + metadata: { + id, + title: titles[id], + artist: 'Acceptance fixture', + uploader: 'owner', + designer: 'Test designer', + levels: ['3', '6', '9', '12', null, null, null], + hash: `hash-${id}`, + tags: [], + publicTags: [], + timestamp: '2026-09-20T00:00:00Z', + }, + resources: {}, + levelHashes: [null, null, null, null, null, null, null], +}); + +interface MockOptions { + /** Chart ids the songlist returns, in collection order. */ + items: string[]; + /** Username the session reports; the page needs a logged-in user, and only the creator `owner` can edit. */ + username?: string; +} + +/** + * Mocks the backend for the collection page. Returns every API request the page sends, so tests can check that the + * removed `diff` endpoint is never called. + */ +async function mockApi(page: Page, { items, username = 'viewer' }: MockOptions) { + const requests: Request[] = []; + let currentItems = items; + await page.route('**/api3/**', async (route) => { + const request = route.request(); + requests.push(request); + const path = new URL(request.url()).pathname; + const collection = () => ({ + id: collectionId, + name: 'E2E playlist', + createdBy: 'owner', + description: 'Collection fixture', + visibility: 1, + // The backend lists the charts that still exist. + items: currentItems.filter((id) => id !== missingChart), + count: currentItems.filter((id) => id !== missingChart).length, + }); + if (path.endsWith('/image') || path.includes('/avatar/')) { + await route.fulfill({ body: placeholderImage, contentType: 'image/png' }); + return; + } + if (path.endsWith(`/collection/${collectionId}/songlist`)) { + await route.fulfill({ json: collection() }); + return; + } + if (path.endsWith('/maichart/info') && request.method() === 'POST') { + // Answer in reverse request order and leave out missing charts, as the real endpoint may. + const ids = request.postDataJSON() as string[]; + await route.fulfill({ json: ids.filter((id) => titles[id]).reverse().map(chartInfo) }); + return; + } + if (path.endsWith(`/collection/${collectionId}/modify`) && request.method() === 'PUT') { + currentItems = (request.postDataJSON() as { items?: string[] }).items ?? currentItems; + await route.fulfill({ json: { code: 0, message: 'Ok', collection: collection() } }); + return; + } + if (path.endsWith('/maichart/interactsum')) { + const chartIds = request.postDataJSON() as string[]; + await route.fulfill({ json: chartIds.map((chartId) => ({ chartId, plays: 0, score: 0, upvotes: 0, downvotes: 0, comments: 0, myVote: 0 })) }); + return; + } + const body = path.endsWith('/account/profile') ? { username } + : path.endsWith('/interactsum') ? { chartId: path.split('/').at(-2), plays: 0, score: 0, upvotes: 0, downvotes: 0, comments: 0, myVote: 0 } + : []; + await route.fulfill({ json: body }); + }); + await page.addInitScript(() => localStorage.setItem('language', 'en')); + return requests; +} + +const songTitles = (page: Page) => page.locator('main').getByText(/^(Alpha|Bravo|Charlie) fixture$/); + +test('desktop: collection page loads chart metadata in one batch, in collection order', async ({ page }) => { + const requests = await mockApi(page, { items: [chartB, chartA] }); + + await page.goto(`/collection?id=${collectionId}`); + + await expect(songTitles(page)).toHaveText(['Bravo fixture', 'Alpha fixture']); + const infoRequests = requests.filter((r) => r.url().endsWith('/maichart/info')); + expect(infoRequests).toHaveLength(1); + expect(infoRequests[0].postDataJSON()).toEqual([chartB, chartA]); + expect(requests.some((r) => r.url().includes('/diff'))).toBe(false); +}); + +test('desktop: an empty collection sends no chart info request', async ({ page }) => { + const requests = await mockApi(page, { items: [] }); + + await page.goto(`/collection?id=${collectionId}`); + + await expect(page.getByText('E2E playlist')).toBeVisible(); + await expect(songTitles(page)).toHaveCount(0); + expect(requests.some((r) => r.url().endsWith('/maichart/info'))).toBe(false); +}); + +test('desktop: the owner saves edits with PUT modify and the full item list', async ({ page }) => { + const requests = await mockApi(page, { items: [chartB, chartA, chartC], username: 'owner' }); + await page.goto(`/collection?id=${collectionId}`); + await expect(songTitles(page)).toHaveText(['Bravo fixture', 'Alpha fixture', 'Charlie fixture']); + + await page.getByRole('button', { name: 'Manage', exact: true }).click(); + await page.getByTitle('Remove from Collection').nth(1).click(); + const modify = page.waitForRequest((r) => r.url().endsWith(`/collection/${collectionId}/modify`)); + await page.getByRole('button', { name: 'Submit', exact: true }).click(); + + const request = await modify; + expect(request.method()).toBe('PUT'); + expect(request.postDataJSON()).toEqual({ items: [chartB, chartC] }); + await expect(songTitles(page)).toHaveText(['Bravo fixture', 'Charlie fixture']); + expect(requests.some((r) => r.url().includes('/diff'))).toBe(false); +}); diff --git a/src/components/collection/CollectionCard.tsx b/src/components/collection/CollectionCard.tsx index 5f93072..5048c69 100644 --- a/src/components/collection/CollectionCard.tsx +++ b/src/components/collection/CollectionCard.tsx @@ -83,7 +83,7 @@ const CollectionCardContent = memo(({ collection, isManaging, onDelete }: Collec ) : data && data.items && data.items.length > 0 ? ( - + ) : (
{t("collection/CollectionCard.NoCover")} diff --git a/src/config/api.ts b/src/config/api.ts index e9c7cee..9773251 100644 --- a/src/config/api.ts +++ b/src/config/api.ts @@ -34,10 +34,12 @@ export const endpoints = { }, create: `${apiroot3}/collection/create`, hashlist: (id: string) => `${apiroot3}/collection/${id}/hashlist`, + // 响应的 items 为谱面 Id 数组(歌单顺序),谱面信息用 maichart.info 批量获取 songlist: (id: string) => `${apiroot3}/collection/${id}/songlist`, destroy: (id: string) => `${apiroot3}/collection/${id}/destroy`, + // PUT,请求体 { name?, description?, visibility?, items? };items 为谱面 Id 数组,整体替换歌单内容(按请求顺序), + // 空数组清空歌单,不传则保留原内容 modify: (id: string) => `${apiroot3}/collection/${id}/modify`, - diff: (id: string) => `${apiroot3}/collection/${id}/diff`, }, // 收藏的歌单 favorite: { @@ -78,6 +80,8 @@ export const endpoints = { hashStatus: (hash: string) => `${apiroot3}/maichart/hash-status?hash=${encodeURIComponent(hash)}`, delete: (chartId: string) => `${apiroot3}/maichart/delete?chartId=${chartId}`, summary: (id: string | number) => `${apiroot3}/maichart/${id}/summary`, + // POST,请求体为谱面 Id 数组;按请求顺序返回 { metadata, resources, levelHashes } 数组,不存在的谱面被略过 + info: `${apiroot3}/maichart/info`, radar: (id: string, chartLevel: number) => `${apiroot3}/maichart/${encodeURIComponent(id)}/radar?chartLevel=${chartLevel}`, image: (id: string | number) => `${apiroot3}/maichart/${id}/image`, fullImage: (id: string | number) => `${apiroot3}/maichart/${id}/image?fullImage=true`, diff --git a/src/hooks/useCollections.ts b/src/hooks/useCollections.ts index 09f089c..0791bf4 100644 --- a/src/hooks/useCollections.ts +++ b/src/hooks/useCollections.ts @@ -9,7 +9,7 @@ import useSWR from 'swr'; import { toast } from 'react-toastify'; import { endpoints } from '@/config/api'; import { useUserContext } from '@/hooks'; -import type { Collection, CollectionDanInfo } from '@/types'; +import type { Collection, CollectionDanInfo, CollectionSongList } from '@/types'; const fetcher = (url: string) => fetch(url, { mode: 'cors', credentials: 'include' }).then((res) => res.json()); @@ -86,23 +86,33 @@ export function useCollections() { ); // 切换歌曲在收藏夹中的状态(添加 / 移除) - // hashlist 仍返回 hash,所以按 hash 判断是否已收录;增删请求按谱面 Id 提交 + // hashlist 仍返回 hash,所以按 hash 判断是否已收录;增删时先取最新的谱面 Id 列表, + // 在本地算出新列表后用 modify 整体替换 const toggleSongInCollection = useCallback( 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 - ? { chartIdsToRemove: [chartId] } - : { chartIdsToAdd: [chartId] }; + const listRes = await fetch(endpoints.collection.songlist(collectionId), { + mode: 'cors', + credentials: 'include', + }); + if (!listRes.ok) throw new Error(`Collection request failed (${listRes.status})`); + const current: CollectionSongList = await listRes.json(); + const currentIds = Array.isArray(current?.items) ? current.items : []; + const target = chartId.toLowerCase(); + const has = currentIds.some((id) => id.toLowerCase() === target); + const items = isIn + ? currentIds.filter((id) => id.toLowerCase() !== target) + : has ? currentIds : [...currentIds, chartId]; - const res = await fetch(endpoints.collection.diff(collectionId), { - method: 'POST', + const res = await fetch(endpoints.collection.modify(collectionId), { + method: 'PUT', mode: 'cors', credentials: 'include', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), + body: JSON.stringify({ items }), }); if (res.ok) { diff --git a/src/hooks/useSeasonCharts.ts b/src/hooks/useSeasonCharts.ts index 741d2bf..a5ddc2f 100644 --- a/src/hooks/useSeasonCharts.ts +++ b/src/hooks/useSeasonCharts.ts @@ -69,12 +69,12 @@ export async function fetchSeasonCollection(id: string): Promise if (!value || !Array.isArray(value.items) || value.items.length === 0) { throw new Error('Season collection must contain charts'); } + // items are chart IDs in collection order. const ids = value.items.map((item: unknown) => { - if (!item || typeof item !== 'object' || !('id' in item) - || typeof item.id !== 'string' || !item.id || /\s/.test(item.id)) { + if (typeof item !== 'string' || !item || /\s/.test(item)) { throw new Error('Unexpected collection chart'); } - return parseSeasonChart(`/song?id=${encodeURIComponent(item.id)}`); + return parseSeasonChart(`/song?id=${encodeURIComponent(item)}`); }) as string[]; if (new Set(ids).size !== ids.length) throw new Error('Duplicate collection chart'); return ids.map(id => `/song?id=${encodeURIComponent(id)}`); diff --git a/src/pages/collection/CollectionPage.tsx b/src/pages/collection/CollectionPage.tsx index ed80c01..4c38995 100644 --- a/src/pages/collection/CollectionPage.tsx +++ b/src/pages/collection/CollectionPage.tsx @@ -9,6 +9,7 @@ import { PageLayout, SongCard, LoadingSpinner } from '@/components'; import { endpoints } from '@/config/api'; import { useUserContext } from '@/hooks'; import type { CollectionSongList, Song } from '@/types'; +import { fetchChartInfos } from '@/utils/chartInfo'; import CollectionSubscribeButton from '@/components/collection/CollectionSubscribeButton'; const fetcher = (url: string) => @@ -49,12 +50,20 @@ export default function CollectionPage() { const sortWords = ['', 'likep', 'commp', 'playp', 'timep']; - // 歌单中原有的歌曲 ID + // 歌单中原有的谱面 Id(歌单顺序) const originalIds = useMemo( - () => collectionData?.items?.map((s) => s.id) || [], + () => collectionData?.items ?? [], [collectionData] ); + // 谱面信息一次批量获取;空歌单不发请求 + const { data: originalSongs, error: songsError, isLoading: isSongsLoading } = useSWR( + originalIds.length > 0 ? ['collection-chart-infos', ...originalIds] : null, + ([, ...ids]: string[]) => fetchChartInfos(ids), + // 保存后 Id 列表变化,先保留旧数据避免整页闪回加载状态 + { revalidateOnFocus: false, keepPreviousData: true } + ); + // 已存在的所有 ID(用于搜索结果中标记已添加) const allExistingIds = useMemo( () => new Set([...originalIds, ...addedIds]), @@ -81,12 +90,20 @@ export default function CollectionPage() { // 是否有变更 const hasChanges = addedIds.length > 0 || removedIds.length > 0 || nameChanged || descriptionChanged || visibilityChanged; - // 当前显示的歌曲列表 - const displaySongs = useMemo(() => { + // 当前的谱面 Id 列表:原有(未移除) + 新增,即提交的顺序 + const displayIds = useMemo(() => { const removedSet = new Set(removedIds); - const existing = (collectionData?.items || []).filter((s) => !removedSet.has(s.id)); + return [...originalIds.filter((chartId) => !removedSet.has(chartId)), ...addedIds]; + }, [originalIds, removedIds, addedIds]); + + // 当前显示的歌曲列表,顺序与 displayIds 一致;已不存在的谱面不显示 + const displaySongs = useMemo(() => { + // originalSongs 可能是保存前的旧数据,只保留仍在歌单中的谱面 + const kept = new Set(originalIds); + for (const chartId of removedIds) kept.delete(chartId); + const existing = (originalSongs ?? []).filter((s) => kept.has(s.id)); return [...existing, ...addedSongs]; - }, [collectionData, removedIds, addedSongs]); + }, [originalIds, originalSongs, removedIds, addedSongs]); // 搜索排序选项 const searchSortOptions = [ @@ -153,8 +170,8 @@ export default function CollectionPage() { const body: Record = {}; if (addedIds.length > 0 || removedIds.length > 0) { - // 谱面 Id 列表即当前显示的顺序:原有(未移除) + 新增 - body.items = displaySongs.map((s) => s.id); + // 整体替换:原有(未移除) + 新增 + body.items = displayIds; } if (visibilityChanged) { body.visibility = visibilityDraft; @@ -168,7 +185,7 @@ export default function CollectionPage() { try { const res = await fetch(endpoints.collection.modify(id), { - method: 'POST', + method: 'PUT', mode: 'cors', credentials: 'include', headers: { 'Content-Type': 'application/json' }, @@ -224,7 +241,7 @@ export default function CollectionPage() { ); } - if (error) { + if (error || songsError) { return (
@@ -234,7 +251,7 @@ export default function CollectionPage() { ); } - if (isLoading) { + if (isLoading || (isSongsLoading && !originalSongs)) { return (
diff --git a/src/types/collection.ts b/src/types/collection.ts index 434e5bd..fb7ce79 100644 --- a/src/types/collection.ts +++ b/src/types/collection.ts @@ -1,4 +1,4 @@ -import type { Song } from './song'; export interface Collection { id: string; name: string; createdBy: string; description: string | null; count: number; } -export interface CollectionSongList extends Collection { visibility: number; items: Song[]; } +/** `items` are chart Ids (GUIDs) in collection order; fetch their metadata with `endpoints.maichart.info`. */ +export interface CollectionSongList extends Collection { visibility: number; items: string[]; } export interface CollectionDanInfo extends Omit { songHashs: string[]; isPlayList: boolean; isForceGameover: boolean; } diff --git a/src/utils/chartInfo.ts b/src/utils/chartInfo.ts new file mode 100644 index 0000000..c3c7292 --- /dev/null +++ b/src/utils/chartInfo.ts @@ -0,0 +1,34 @@ +import { endpoints } from '@/config/api'; +import type { Song } from '@/types/song'; +import { apiRequest, jsonRequest } from './apiClient'; + +/** One item of `POST /api/maichart/info`; only the fields the frontend reads are typed. */ +export interface OnlineChartInfo { + metadata: Omit & { levels: (string | null)[] }; + levelHashes: (string | null)[]; +} + +/** + * Loads the metadata of several charts with one request, in the order of `ids`. + * Charts that no longer exist are left out; an empty list sends no request. + */ +export async function fetchChartInfos(ids: readonly string[]): Promise { + if (ids.length === 0) return []; + const infos = await apiRequest(endpoints.maichart.info, jsonRequest('POST', ids)); + const byId = new Map(); + for (const { metadata } of Array.isArray(infos) ? infos : []) { + if (!metadata || typeof metadata.id !== 'string') continue; + byId.set(metadata.id.toLowerCase(), { + id: metadata.id, + title: metadata.title, + artist: metadata.artist, + uploader: metadata.uploader, + designer: metadata.designer, + hash: metadata.hash, + // Keep positions: their indices identify the difficulty. + levels: (metadata.levels ?? []).map(level => level ?? ''), + }); + } + // GUIDs compare case-insensitively; follow the requested order rather than the response's. + return ids.flatMap(id => byId.get(id.toLowerCase()) ?? []); +} diff --git a/test/hooks/seasonCollection.test.ts b/test/hooks/seasonCollection.test.ts index e5af0af..b454927 100644 --- a/test/hooks/seasonCollection.test.ts +++ b/test/hooks/seasonCollection.test.ts @@ -7,14 +7,14 @@ afterEach(() => vi.unstubAllGlobals()); describe('season collections', () => { it('loads chart IDs from the configured collection in collection order', async () => { - const fetcher = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ items: [{ id: 'second' }, { id: 'first' }] }) }); + const fetcher = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ items: ['second', 'first'] }) }); vi.stubGlobal('fetch', fetcher); expect(await fetchSeasonCollection(id)).toEqual(['/song?id=second', '/song?id=first']); expect(fetcher).toHaveBeenCalledWith(`/api3/api/collection/${id}/songlist`, expect.objectContaining({ credentials: 'include' })); expect(getEventHref({ id: 'ffmc-re', type: 'season', asset: id })).toBe('/season?id=ffmc-re'); }); - it.each([[], [{ id: 'same' }, { id: 'same' }], [{ hash: 'missing-id' }]])('rejects unusable chart pools: %j', async items => { + it.each([[], ['same', 'same'], [{ id: 'chart-object' }], ['']])('rejects unusable chart pools: %j', async items => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ items }) })); await expect(fetchSeasonCollection(id)).rejects.toThrow(); }); diff --git a/test/hooks/useCollections.test.tsx b/test/hooks/useCollections.test.tsx index 3bdfa0e..d12d376 100644 --- a/test/hooks/useCollections.test.tsx +++ b/test/hooks/useCollections.test.tsx @@ -38,6 +38,11 @@ describe('useCollections', () => { // 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] }); + // songlist 给出谱面 Id 列表;with-song 里的 Id 用大写,确认移除时大小写不敏感 + if (url === endpoints.collection.songlist('with-song')) { + return Response.json({ items: ['other-1', chart.chartId.toUpperCase(), 'other-2'], count: 3 }); + } + if (url === endpoints.collection.songlist('without-song')) return Response.json({ items: ['other-1'], count: 1 }); return new Response(null, { status: 200 }); }); vi.stubGlobal('fetch', fetchMock); @@ -48,13 +53,13 @@ describe('useCollections', () => { vi.unstubAllGlobals(); }); - function diffBody(collectionId: string) { - const call = fetchMock.mock.calls.find(([url]) => url === endpoints.collection.diff(collectionId)); - expect(call?.[1]?.method).toBe('POST'); + function modifyBody(collectionId: string) { + const call = fetchMock.mock.calls.find(([url]) => url === endpoints.collection.modify(collectionId)); + expect(call?.[1]?.method).toBe('PUT'); return JSON.parse(String(call![1]!.body)); } - it('sends chart IDs in diff requests and decides membership by hashlist hashes', async () => { + it('replaces the item list via modify and decides membership by hashlist hashes', async () => { await act(async () => root.render( new Map(), shouldRetryOnError: false }}>, )); @@ -63,9 +68,9 @@ describe('useCollections', () => { 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] }); + expect(modifyBody('with-song')).toEqual({ items: ['other-1', 'other-2'] }); await act(async () => hook.toggleSongInCollection('without-song', chart)); - expect(diffBody('without-song')).toEqual({ chartIdsToAdd: [chart.chartId] }); + expect(modifyBody('without-song')).toEqual({ items: ['other-1', chart.chartId] }); }); }); diff --git a/test/hooks/useSeasonCharts.test.tsx b/test/hooks/useSeasonCharts.test.tsx index 8bd9797..8e2ed86 100644 --- a/test/hooks/useSeasonCharts.test.tsx +++ b/test/hooks/useSeasonCharts.test.tsx @@ -43,7 +43,7 @@ describe('useSeasonCharts', () => { const url = String(input); if (url === `/api3/api/collection/${collectionId}/songlist`) { // 谱单顺序与 Id 字母序相反,GUID 大写也要规范化成小写 - return Response.json({ items: [{ id: second.toUpperCase() }, { id: first }] }); + return Response.json({ items: [second.toUpperCase(), first] }); } const id = /\/maichart\/([^/]+)\/summary$/.exec(url)?.[1]; if (id && summaries[id]) return summaries[id](); diff --git a/test/pages/collection/CollectionPage.test.tsx b/test/pages/collection/CollectionPage.test.tsx index 1a9abaa..6a4e926 100644 --- a/test/pages/collection/CollectionPage.test.tsx +++ b/test/pages/collection/CollectionPage.test.tsx @@ -20,10 +20,12 @@ vi.mock('react-toastify', () => ({ toast: { success: vi.fn(), error: vi.fn() } } 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')], +// 歌单只列谱面 Id;chart-gone 已被删除,info 接口不会返回它 +let collection = { + id: collectionId, name: 'List', createdBy: 'alice', description: '', count: 4, visibility: 0, + items: ['chart-1', 'chart-2', 'chart-gone', 'chart-3'], }; +const info = (id: string) => ({ metadata: song(id), levelHashes: [], resources: {} }); // 搜索结果不带 hash 也能直接添加,不需要再请求 summary const searchResults = [song('chart-4', ''), song('chart-5', '')]; @@ -32,12 +34,18 @@ describe('collection management', () => { let root: Root; let fetchMock: ReturnType>; beforeEach(() => { + collection = { ...collection, count: 4, items: ['chart-1', 'chart-2', 'chart-gone', 'chart-3'] }; container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container); - fetchMock = vi.fn(async (input) => { + fetchMock = vi.fn(async (input, init) => { const url = String(input); if (url === endpoints.collection.songlist(collectionId)) return Response.json(collection); + if (url === endpoints.maichart.info) { + // 故意打乱响应顺序,页面应按 items 的顺序显示 + const ids: string[] = JSON.parse(String(init?.body)); + return Response.json(ids.filter((id) => id !== 'chart-gone').reverse().map(info)); + } if (url.startsWith(endpoints.maichart.listSearchAndSort('chart'))) return Response.json(searchResults); return new Response(null, { status: 200 }); }); @@ -55,12 +63,18 @@ describe('collection management', () => { container.querySelector(`[data-song="${id}"]`)!.parentElement!.querySelector('button')!; const click = (button: HTMLButtonElement) => act(async () => button.click()); - async function startManagingAndSearch() { + async function renderPage() { await act(async () => root.render( new Map(), shouldRetryOnError: false }}> , )); + } + const shownIds = () => Array.from(container.querySelectorAll('[data-song]')).map((e) => e.getAttribute('data-song')); + const infoCalls = () => fetchMock.mock.calls.filter(([url]) => url === endpoints.maichart.info); + + async function startManagingAndSearch() { + await renderPage(); await click(buttonByText(i18n.t('collection/CollectionPage.Manage'))); const input = container.querySelector(`input[placeholder="${i18n.t('collection/CollectionPage.SearchToAdd')}"]`)!; await act(async () => { @@ -73,17 +87,33 @@ describe('collection management', () => { 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(call?.[1]?.method).toBe('PUT'); expect(fetchMock.mock.calls.some(([url]) => String(url).endsWith('/summary'))).toBe(false); return JSON.parse(String(call![1]!.body)).items; } + it('loads chart metadata with one batch request and shows charts in collection order', async () => { + await renderPage(); + expect(infoCalls()).toHaveLength(1); + expect(infoCalls()[0][1]?.method).toBe('POST'); + expect(JSON.parse(String(infoCalls()[0][1]?.body))).toEqual(['chart-1', 'chart-2', 'chart-gone', 'chart-3']); + expect(shownIds()).toEqual(['chart-1', 'chart-2', 'chart-3']); + expect(fetchMock.mock.calls.some(([url]) => String(url).endsWith('/summary'))).toBe(false); + }); + + it('sends no metadata request for an empty collection', async () => { + collection = { ...collection, count: 0, items: [] }; + await renderPage(); + expect(infoCalls()).toHaveLength(0); + expect(container.textContent).toContain(i18n.t('collection/CollectionPage.EmptyCollection')); + }); + 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']); + expect(await submittedItems()).toEqual(['chart-1', 'chart-gone', 'chart-3', 'chart-5', 'chart-4']); }); it('drops an addition that is removed again before submitting', async () => { @@ -91,6 +121,6 @@ describe('collection management', () => { 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']); + expect(await submittedItems()).toEqual(['chart-1', 'chart-2', 'chart-gone', 'chart-3', 'chart-4']); }); });