Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions api-directory.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)只供游戏客户端使用。

## 需要后端修复的阻碍

Expand Down
31 changes: 31 additions & 0 deletions docs/changelog/2026-11-09-collection-chart-ids.md
Original file line number Diff line number Diff line change
@@ -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 通过。未对真实后端联调。

## 部署

须与后端同时部署。
131 changes: 131 additions & 0 deletions e2e/collection.spec.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = { [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);
});
2 changes: 1 addition & 1 deletion src/components/collection/CollectionCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ const CollectionCardContent = memo(({ collection, isManaging, onDelete }: Collec
<LoadingSpinner size="30px" />
</div>
) : data && data.items && data.items.length > 0 ? (
<CoverPic id={data.items[currentCoverIndex].id} />
<CoverPic id={data.items[currentCoverIndex] ?? data.items[0]} />
) : (
<div className="flex flex-col justify-center items-center bg-black/60 w-full h-full text-white/50 text-xs">
<span>{t("collection/CollectionCard.NoCover")}</span>
Expand Down
6 changes: 5 additions & 1 deletion src/config/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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`,
Expand Down
26 changes: 18 additions & 8 deletions src/hooks/useCollections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -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) {
Expand Down
6 changes: 3 additions & 3 deletions src/hooks/useSeasonCharts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,12 @@ export async function fetchSeasonCollection(id: string): Promise<SeasonChart[]>
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)}`);
Expand Down
39 changes: 28 additions & 11 deletions src/pages/collection/CollectionPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand Down Expand Up @@ -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<Song[]>(
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]),
Expand All @@ -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 = [
Expand Down Expand Up @@ -153,8 +170,8 @@ export default function CollectionPage() {

const body: Record<string, unknown> = {};
if (addedIds.length > 0 || removedIds.length > 0) {
// 谱面 Id 列表即当前显示的顺序:原有(未移除) + 新增
body.items = displaySongs.map((s) => s.id);
// 整体替换:原有(未移除) + 新增
body.items = displayIds;
}
if (visibilityChanged) {
body.visibility = visibilityDraft;
Expand All @@ -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' },
Expand Down Expand Up @@ -224,7 +241,7 @@ export default function CollectionPage() {
);
}

if (error) {
if (error || songsError) {
return (
<PageLayout>
<div className="flex justify-center items-center min-h-[60vh]">
Expand All @@ -234,7 +251,7 @@ export default function CollectionPage() {
);
}

if (isLoading) {
if (isLoading || (isSongsLoading && !originalSongs)) {
return (
<PageLayout>
<div className="flex justify-center items-center min-h-[60vh]">
Expand Down
Loading
Loading