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
72 changes: 44 additions & 28 deletions src/components/ui/TagManageWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ import { endpoints } from '@/config/api';
import { toast } from 'react-toastify';
import LoadingSpinner from './LoadingSpinner';
import sleep from '@/utils/sleep';
import { MAX_CHART_TAGS, saveChartTags } from '@/utils/chartTags';
import { ApiError } from '@/utils/apiClient';
import { CODE_TOO_MANY_ELEMENTS } from '@/config/apiRetCode';
import { motion } from 'framer-motion';
import type {
TagManageWidgetProps,
Expand Down Expand Up @@ -132,7 +135,7 @@ function tagsReducer(state: string[], action: TagsAction): string[] {
case 'INIT_TAGS':
return action.payload;
case 'ADD_TAG':
return [...state, action.payload];
return state.includes(action.payload) ? state : [...state, action.payload];
case 'REMOVE_TAG': {
const newTags = [...state];
newTags.splice(action.payload, 1);
Expand All @@ -159,6 +162,8 @@ const TagManageWindow = forwardRef<HTMLDivElement, TagManageWindowProps>(
const [tags, dispatch] = useReducer(tagsReducer, []);
const isInPrivatePage = window.location.pathname === '/user/charts';
const initializedRef = useRef(false);
/** Tags as last read from or saved to the server: the base of the public-tag PATCH diff. */
const serverTagsRef = useRef<string[]>([]);

useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
Expand Down Expand Up @@ -220,7 +225,7 @@ const TagManageWindow = forwardRef<HTMLDivElement, TagManageWindowProps>(
const fetcher = (url: string) =>
fetch(url, { mode: 'cors', credentials: 'include' }).then((res) => res.json());

const { data, error, isLoading } = useSWR<SongSummary>(
const { data, error, isLoading, mutate } = useSWR<SongSummary>(
endpoints.maichart.summary(songid),
fetcher
);
Expand All @@ -229,13 +234,15 @@ const TagManageWindow = forwardRef<HTMLDivElement, TagManageWindowProps>(
if (data && !initializedRef.current) {
if (isInPrivatePage) {
if (data.tags !== undefined) {
serverTagsRef.current = data.tags;
dispatch({ type: 'INIT_TAGS', payload: data.tags });
initializedRef.current = true;
} else {
toast.error('没有Tags字段');
}
} else {
if (data.publicTags !== undefined) {
serverTagsRef.current = data.publicTags;
dispatch({ type: 'INIT_TAGS', payload: data.publicTags });
initializedRef.current = true;
} else {
Expand All @@ -249,31 +256,43 @@ const TagManageWindow = forwardRef<HTMLDivElement, TagManageWindowProps>(
const uploading = toast.loading(t("shared/TagManageWidget.Uploading"), {
hideProgressBar: true,
});
const response = await fetch(
isInPrivatePage ? endpoints.maichart.tags(songid) : endpoints.maichart.publictags(songid),
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(tags),
credentials: 'include',
let saved: string[];
try {
saved = await saveChartTags(songid, isInPrivatePage ? 'private' : 'public', serverTagsRef.current, tags);
} catch (error) {
if (error instanceof ApiError && error.code === CODE_TOO_MANY_ELEMENTS) {
toast.error(t("shared/TagManageWidget.TooManyTags", { max: MAX_CHART_TAGS }));
} else if (error instanceof ApiError && error.status === 409) {
toast.error(t("shared/TagManageWidget.TagsChanged"));
} else {
toast.error('好像上传失败惹……');
}
);
toast.done(uploading);
return;
} finally {
toast.done(uploading);
}

if (!response.ok) {
toast.error('好像上传失败惹……');
} else {
//TODO: 刷新页面,重载数据,应该可以热重载,之后研究
toast.success('上传成功了喵');
if (window.location.pathname !== '/user/charts') {
await sleep(1000);
window.location.reload();
}
// The server normalizes tags and PATCH merges other players' edits, so show what it now holds.
serverTagsRef.current = saved;
dispatch({ type: 'SET_TAGS', payload: saved });
await mutate((summary) => summary && { ...summary, [isInPrivatePage ? 'tags' : 'publicTags']: saved }, { revalidate: false });
toast.success('上传成功了喵');
//TODO: 刷新页面,重载数据,应该可以热重载,之后研究
if (window.location.pathname !== '/user/charts') {
await sleep(1000);
window.location.reload();
}
};

return response;
/** Adds a tag unless it is already there; refuses one past the backend's per-kind limit. */
const addTag = (tag: string) => {
if (tags.includes(tag)) return true;
if (tags.length >= MAX_CHART_TAGS) {
toast.error(t("shared/TagManageWidget.TooManyTags", { max: MAX_CHART_TAGS }));
return false;
}
dispatch({ type: 'ADD_TAG', payload: tag });
return true;
};

if (error) {
Expand Down Expand Up @@ -408,8 +427,7 @@ const TagManageWindow = forwardRef<HTMLDivElement, TagManageWindowProps>(
<button
onClick={() => {
const trimmed = newTag.trim();
if (trimmed !== '') {
dispatch({ type: 'ADD_TAG', payload: trimmed });
if (trimmed !== '' && addTag(trimmed)) {
setNewTag(''); // 清空输入框
}
}}
Expand Down Expand Up @@ -455,9 +473,7 @@ const TagManageWindow = forwardRef<HTMLDivElement, TagManageWindowProps>(
<span
className="bg-gray-100 hover:bg-gray-300 px-2.5 py-0.75 rounded-xl text-[#333] text-xs transition-colors duration-200 cursor-pointer"
key={tag}
onClick={() => {
dispatch({ type: 'ADD_TAG', payload: tag });
}}
onClick={() => addTag(tag)}
>
{tag}
</span>
Expand Down
1 change: 1 addition & 0 deletions src/config/apiRetCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const CODE_ERROR = -114514;
// 请求错误 4XXXX
export const CODE_INVALID_VALUE = 40000;
export const CODE_PAYLOAD_REQUIRED = 40001;
export const CODE_TOO_MANY_ELEMENTS = 40002;
export const CODE_NO_SUCH_ITEM = 40400;
export const CODE_ITEM_ALREADY_EXISTS = 40900;
export const CODE_ITEM_DELETED = 41000;
Expand Down
2 changes: 2 additions & 0 deletions src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,8 @@
"CustomTag": "Custom tag",
"DeleteTag": "Delete tag",
"NoTags": "No tags",
"TagsChanged": "Someone else changed these tags at the same time. Please try again.",
"TooManyTags": "A chart can have at most {{max}} tags of each kind",
"Uploading": "Uploading..."
},
"shared/UserMenu": {
Expand Down
2 changes: 2 additions & 0 deletions src/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,8 @@
"CustomTag": "カスタムタグ",
"DeleteTag": "タグを削除",
"NoTags": "タグがありません",
"TagsChanged": "タグが同時に他のユーザーに変更されました。もう一度お試しください",
"TooManyTags": "譜面ごとに各種類のタグは最大 {{max}} 個までです",
"Uploading": "爆速アップロード中..."
},
"shared/UserMenu": {
Expand Down
2 changes: 2 additions & 0 deletions src/locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,8 @@
"CustomTag": "사용자 지정 태그",
"DeleteTag": "태그 삭제",
"NoTags": "태그 없음",
"TagsChanged": "다른 사용자가 동시에 태그를 변경했습니다. 다시 시도해 주세요",
"TooManyTags": "채보마다 종류별로 태그는 최대 {{max}}개까지입니다",
"Uploading": "업로드 중..."
},
"shared/UserMenu": {
Expand Down
2 changes: 2 additions & 0 deletions src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,8 @@
"CustomTag": "自定标签",
"DeleteTag": "删除标签",
"NoTags": "暂无标签",
"TagsChanged": "标签刚被其他人同时修改了,请重试",
"TooManyTags": "每张谱面的每类标签最多 {{max}} 个",
"Uploading": "正在爆速上传..."
},
"shared/UserMenu": {
Expand Down
59 changes: 59 additions & 0 deletions src/utils/chartTags.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { endpoints } from '@/config/api';
import { ApiError, apiRequest, jsonRequest } from './apiClient';

/** `private`: the uploader's own tags; `public`: player tags that any logged-in user may edit. */
export type ChartTagScope = 'private' | 'public';

/** The backend keeps at most this many tags of each kind per chart, counted after normalization. */
export const MAX_CHART_TAGS = 32;

/** How often a PATCH that lost to concurrent edits (409) is sent again before giving up. */
const PATCH_CONFLICT_RETRIES = 1;

export interface ChartTagPatch {
add: string[];
remove: string[];
}

/**
* Changes from the tags last read from the server to the edited ones.
* A tag is in at most one list: one that was removed and added back is unchanged.
*/
export function diffChartTags(before: readonly string[], after: readonly string[]): ChartTagPatch {
const beforeSet = new Set(before);
const afterSet = new Set(after);
return {
add: [...afterSet].filter((tag) => !beforeSet.has(tag)),
remove: [...beforeSet].filter((tag) => !afterSet.has(tag)),
};
}

/**
* Saves the edited tags and resolves to the tags the server holds afterwards.
*
* Private tags have a single editor (the uploader), so the whole list replaces them with PUT.
* Public tags are edited by many players, so only this editor's additions and removals are sent
* with PATCH; a replacing PUT would drop tags that others added since the window was opened.
* PATCH is idempotent, so a 409 (the server lost to concurrent edits several times) is retried.
*
* Rejects with an ApiError; `code` is CODE_TOO_MANY_ELEMENTS when the result would exceed
* MAX_CHART_TAGS, and the status is 409 when the conflict outlasted the retries.
*/
export async function saveChartTags(
chartId: string,
scope: ChartTagScope,
before: readonly string[],
after: readonly string[],
): Promise<string[]> {
if (scope === 'private') {
return apiRequest<string[]>(endpoints.maichart.tags(chartId), jsonRequest('PUT', [...after]));
}
const patch = jsonRequest('PATCH', diffChartTags(before, after));
for (let attempt = 0; ; attempt++) {
try {
return await apiRequest<string[]>(endpoints.maichart.publictags(chartId), patch);
} catch (error) {
if (!(error instanceof ApiError && error.status === 409 && attempt < PATCH_CONFLICT_RETRIES)) throw error;
}
}
}
135 changes: 135 additions & 0 deletions test/components/ui/TagManageWidget.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { SWRConfig } from 'swr';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import TagManageWidget from '@/components/ui/TagManageWidget';
import i18n from '@/i18n';
import { TooltipProvider } from '@/components/ui/Tooltip';

(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

const toastMock = vi.hoisted(() => ({
loading: vi.fn(() => 'toast-id'), done: vi.fn(), error: vi.fn(), success: vi.fn(),
}));
vi.mock('react-toastify', () => ({ toast: toastMock }));
// The song page reloads a second after saving; never let that reach jsdom.
vi.mock('@/utils/sleep', () => ({ default: () => new Promise<void>(() => {}) }));

describe('TagManageWidget', () => {
let container: HTMLDivElement;
let root: Root;
let fetchMock: ReturnType<typeof vi.fn<typeof fetch>>;

beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
fetchMock = vi.fn<typeof fetch>();
vi.stubGlobal('fetch', fetchMock);
vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} unobserve() {} });
Object.values(toastMock).forEach((fn) => fn.mockClear());
});
afterEach(() => {
act(() => root.unmount());
container.remove();
vi.unstubAllGlobals();
window.history.replaceState(null, '', '/');
});

async function open(path: string, summary: { tags?: string[]; publicTags?: string[] }) {
window.history.replaceState(null, '', path);
fetchMock.mockResolvedValueOnce(Response.json(summary));
await act(async () => root.render(
<SWRConfig value={{ provider: () => new Map() }}><TooltipProvider><TagManageWidget songid="c1" /></TooltipProvider></SWRConfig>,
));
await act(async () => (container.querySelector('svg')!.parentElement as HTMLElement).click());
}
const shownTags = () => {
const label = [...document.body.querySelectorAll('div')].find((div) => div.textContent === 'Tags:')!;
return [...label.nextElementSibling!.querySelectorAll('span')].map((span) => span.textContent);
};
const clickText = async (text: string) => {
const element = [...document.body.querySelectorAll<HTMLElement>('span, button')].find((el) => el.textContent === text)!;
await act(async () => element.click());
};
const saveRequest = () => {
const [url, init] = fetchMock.mock.calls[1];
return { url: String(url), method: init?.method, body: JSON.parse(String(init?.body)) };
};

it('sends public tag edits as a PATCH and shows the tags the server returns', async () => {
await open('/song', { publicTags: ['A', 'B'] });
await clickText('A');
await clickText('POPS');
expect(shownTags()).toEqual(['B', 'POPS']);
fetchMock.mockResolvedValueOnce(Response.json(['B', 'Other', 'POPS']));
await clickText('更新Tags');

expect(saveRequest()).toEqual({ url: '/api3/api/maichart/c1/publictags', method: 'PATCH', body: { add: ['POPS'], remove: ['A'] } });
expect(shownTags()).toEqual(['B', 'Other', 'POPS']);
expect(toastMock.success).toHaveBeenCalledOnce();
});

it('replaces private tags with a PUT of the whole list', async () => {
await open('/user/charts', { tags: ['x'] });
await act(async () => {
const input = document.body.querySelector<HTMLInputElement>('input[type="text"]')!;
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
setValue.call(input, ' y ');
input.dispatchEvent(new Event('input', { bubbles: true }));
});
await clickText(i18n.t('shared/TagManageWidget.AddTag'));
fetchMock.mockResolvedValueOnce(Response.json(['x', 'y']));
await clickText('更新Tags');

expect(saveRequest()).toEqual({ url: '/api3/api/maichart/c1/tags', method: 'PUT', body: ['x', 'y'] });
expect(shownTags()).toEqual(['x', 'y']);
});

it('keeps the edit and reports the failure when saving is refused', async () => {
await open('/song', { publicTags: ['A'] });
await clickText('POPS');
fetchMock.mockResolvedValueOnce(new Response(null, { status: 401 }));
await clickText('更新Tags');

expect(toastMock.error).toHaveBeenCalledOnce();
expect(toastMock.done).toHaveBeenCalledWith('toast-id');
expect(toastMock.success).not.toHaveBeenCalled();
expect(shownTags()).toEqual(['A', 'POPS']);
});

const tooManyTags = () => i18n.t('shared/TagManageWidget.TooManyTags', { max: 32 });

it('refuses a 33rd tag before sending anything', async () => {
const full = Array.from({ length: 32 }, (_, index) => `t${index}`);
await open('/song', { publicTags: full });
await clickText('POPS');

expect(toastMock.error).toHaveBeenCalledWith(tooManyTags());
expect(shownTags()).toEqual(full);
expect(fetchMock).toHaveBeenCalledTimes(1); // only the summary
});

it('shows the tag limit when the server refuses with 40002', async () => {
await open('/song', { publicTags: ['A'] });
await clickText('POPS');
fetchMock.mockResolvedValueOnce(Response.json({ code: 40002, message: 'A chart can have at most 32 tags of each kind' }, { status: 400 }));
await clickText('更新Tags');

expect(toastMock.error).toHaveBeenCalledWith(tooManyTags());
expect(toastMock.success).not.toHaveBeenCalled();
expect(shownTags()).toEqual(['A', 'POPS']);
});

it('asks to try again when concurrent edits keep winning after the retry', async () => {
await open('/song', { publicTags: ['A'] });
await clickText('POPS');
const conflict = () => Response.json({ code: -114514, message: 'The tags were changed by other requests, try again' }, { status: 409 });
fetchMock.mockResolvedValueOnce(conflict()).mockResolvedValueOnce(conflict());
await clickText('更新Tags');

expect(fetchMock).toHaveBeenCalledTimes(3); // summary, PATCH, retried PATCH
expect(toastMock.error).toHaveBeenCalledWith(i18n.t('shared/TagManageWidget.TagsChanged'));
expect(shownTags()).toEqual(['A', 'POPS']);
});
});
Loading
Loading