From b6fcdc63f0518267f2fe4201331fa9dd77485d20 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: Sun, 8 Nov 2026 11:54:52 -0500 Subject: [PATCH 1/2] feat: save chart tags with PUT/PATCH instead of the removed POST mmfcapi f8167e7 removed POST /maichart/{id}/tags and /publictags (they now answer 405) and added PUT (replace with a string[] body) and PATCH ({ add, remove }). Both return the tags held after the request. This must ship together with that backend. - Private (uploader) tags have a single editor, so they are replaced with PUT of the whole list. - Public tags are edited by many players, so the widget sends only this edit as PATCH { add, remove }, diffed against the tags it last read from the server; a replacing write would drop tags others added since the window was opened. The diff never lists a tag in both add and remove, so the backend 400 for that case cannot be triggered. - The widget shows the tags the server returns (normalized, and merged with concurrent edits) and updates its SWR summary cache with them, instead of assuming its local list was saved as is. - A failed request (including a network error) now always closes the loading toast and reports the failure. --- src/components/ui/TagManageWidget.tsx | 46 ++++----- src/utils/chartTags.ts | 42 ++++++++ test/components/ui/TagManageWidget.test.tsx | 100 ++++++++++++++++++++ test/utils/chartTags.test.ts | 63 ++++++++++++ 4 files changed, 228 insertions(+), 23 deletions(-) create mode 100644 src/utils/chartTags.ts create mode 100644 test/components/ui/TagManageWidget.test.tsx create mode 100644 test/utils/chartTags.test.ts diff --git a/src/components/ui/TagManageWidget.tsx b/src/components/ui/TagManageWidget.tsx index c3b52a3..34a8fbe 100644 --- a/src/components/ui/TagManageWidget.tsx +++ b/src/components/ui/TagManageWidget.tsx @@ -20,6 +20,7 @@ import { endpoints } from '@/config/api'; import { toast } from 'react-toastify'; import LoadingSpinner from './LoadingSpinner'; import sleep from '@/utils/sleep'; +import { saveChartTags } from '@/utils/chartTags'; import { motion } from 'framer-motion'; import type { TagManageWidgetProps, @@ -159,6 +160,8 @@ const TagManageWindow = forwardRef( 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([]); useEffect(() => { const handleClickOutside = (e: MouseEvent) => { @@ -220,7 +223,7 @@ const TagManageWindow = forwardRef( const fetcher = (url: string) => fetch(url, { mode: 'cors', credentials: 'include' }).then((res) => res.json()); - const { data, error, isLoading } = useSWR( + const { data, error, isLoading, mutate } = useSWR( endpoints.maichart.summary(songid), fetcher ); @@ -229,6 +232,7 @@ const TagManageWindow = forwardRef( 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 { @@ -236,6 +240,7 @@ const TagManageWindow = forwardRef( } } else { if (data.publicTags !== undefined) { + serverTagsRef.current = data.publicTags; dispatch({ type: 'INIT_TAGS', payload: data.publicTags }); initializedRef.current = true; } else { @@ -249,31 +254,26 @@ const TagManageWindow = forwardRef( 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', - } - ); - toast.done(uploading); - - if (!response.ok) { + let saved: string[]; + try { + saved = await saveChartTags(songid, isInPrivatePage ? 'private' : 'public', serverTagsRef.current, tags); + } catch { toast.error('好像上传失败惹……'); - } else { - //TODO: 刷新页面,重载数据,应该可以热重载,之后研究 - toast.success('上传成功了喵'); - if (window.location.pathname !== '/user/charts') { - await sleep(1000); - window.location.reload(); - } + return; + } finally { + toast.done(uploading); } - return response; + // 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(); + } }; if (error) { diff --git a/src/utils/chartTags.ts b/src/utils/chartTags.ts new file mode 100644 index 0000000..886e52a --- /dev/null +++ b/src/utils/chartTags.ts @@ -0,0 +1,42 @@ +import { endpoints } from '@/config/api'; +import { 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'; + +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. + */ +export function saveChartTags( + chartId: string, + scope: ChartTagScope, + before: readonly string[], + after: readonly string[], +): Promise { + if (scope === 'private') { + return apiRequest(endpoints.maichart.tags(chartId), jsonRequest('PUT', [...after])); + } + return apiRequest(endpoints.maichart.publictags(chartId), jsonRequest('PATCH', diffChartTags(before, after))); +} diff --git a/test/components/ui/TagManageWidget.test.tsx b/test/components/ui/TagManageWidget.test.tsx new file mode 100644 index 0000000..fa9bcbf --- /dev/null +++ b/test/components/ui/TagManageWidget.test.tsx @@ -0,0 +1,100 @@ +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(() => {}) })); + +describe('TagManageWidget', () => { + let container: HTMLDivElement; + let root: Root; + let fetchMock: ReturnType>; + + beforeEach(() => { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + fetchMock = vi.fn(); + 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( + new Map() }}>, + )); + 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('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('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']); + }); +}); diff --git a/test/utils/chartTags.test.ts b/test/utils/chartTags.test.ts new file mode 100644 index 0000000..82ef436 --- /dev/null +++ b/test/utils/chartTags.test.ts @@ -0,0 +1,63 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { diffChartTags, saveChartTags } from '@/utils/chartTags'; + +afterEach(() => vi.unstubAllGlobals()); + +function stubFetch(response: Response) { + const fetchMock = vi.fn().mockResolvedValue(response); + vi.stubGlobal('fetch', fetchMock); + return fetchMock; +} + +describe('diffChartTags', () => { + it('lists only added and removed tags', () => { + expect(diffChartTags(['A', 'B', 'C'], ['B', 'D', 'C'])).toEqual({ add: ['D'], remove: ['A'] }); + }); + + it('never puts a tag in both lists, so the backend 400 for overlapping lists cannot happen', () => { + // Removed and then added back, plus a duplicate add: nothing changed. + expect(diffChartTags(['A', 'B'], ['B', 'A', 'A'])).toEqual({ add: [], remove: [] }); + }); + + it('is case-sensitive like the backend', () => { + expect(diffChartTags(['pops'], ['POPS'])).toEqual({ add: ['POPS'], remove: ['pops'] }); + }); +}); + +describe('saveChartTags', () => { + it('replaces private tags with PUT and resolves to the tags the server holds', async () => { + const fetchMock = stubFetch(Response.json(['x', 'y'])); + await expect(saveChartTags('c 1', 'private', ['x'], ['x', 'y'])).resolves.toEqual(['x', 'y']); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe('/api3/api/maichart/c 1/tags'); + expect(init).toMatchObject({ method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json' } }); + expect(JSON.parse(String(init?.body))).toEqual(['x', 'y']); + }); + + it('clears private tags with an empty PUT body', async () => { + const fetchMock = stubFetch(Response.json([])); + await expect(saveChartTags('c1', 'private', ['x'], [])).resolves.toEqual([]); + expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toEqual([]); + }); + + it('sends only this edit of public tags with PATCH, keeping tags others added meanwhile', async () => { + const fetchMock = stubFetch(Response.json(['B', 'Other', 'POPS'])); + await expect(saveChartTags('c1', 'public', ['A', 'B'], ['B', 'POPS'])).resolves.toEqual(['B', 'Other', 'POPS']); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe('/api3/api/maichart/c1/publictags'); + expect(init).toMatchObject({ method: 'PATCH', credentials: 'include' }); + expect(JSON.parse(String(init?.body))).toEqual({ add: ['POPS'], remove: ['A'] }); + }); + + it('rejects with the backend code when the server refuses the edit', async () => { + stubFetch(Response.json({ code: 40000, message: 'A tag cannot be both added and removed' }, { status: 400 })); + await expect(saveChartTags('c1', 'public', [], ['A'])).rejects.toMatchObject({ + status: 400, code: 40000, message: 'A tag cannot be both added and removed', + }); + }); + + it('rejects on a 404 without a body', async () => { + stubFetch(new Response(null, { status: 404 })); + await expect(saveChartTags('missing', 'public', [], ['A'])).rejects.toMatchObject({ status: 404 }); + }); +}); From 9bcb4a11c0942807129bb3ca799c5b69c0e8c6f6 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: Sun, 8 Nov 2026 12:00:12 -0500 Subject: [PATCH 2/2] feat: enforce the 32-tag limit and handle tag edit conflicts mmfcapi now caps each kind of chart tag at 32 (counted after normalization) and answers 400 with the new code TooManyElements = 40002 when a PUT, or a PATCH that grows the list, goes over it. A PATCH that loses to concurrent edits three times now gets 409. - Add CODE_TOO_MANY_ELEMENTS = 40002 to apiRetCode. - The tag window refuses a 33rd tag (and duplicates) before sending and shows the limit, and shows the same message if the server answers 40002 anyway (another player may have filled the list meanwhile). - A public-tag PATCH that gets 409 is sent once more (PATCH is idempotent); if that conflicts too, the window asks to try again. - New i18n keys TooManyTags and TagsChanged in all four languages. --- src/components/ui/TagManageWidget.tsx | 34 ++++++++++++++------ src/config/apiRetCode.ts | 1 + src/locales/en.json | 2 ++ src/locales/ja.json | 2 ++ src/locales/ko.json | 2 ++ src/locales/zh.json | 2 ++ src/utils/chartTags.ts | 23 ++++++++++++-- test/components/ui/TagManageWidget.test.tsx | 35 +++++++++++++++++++++ test/utils/chartTags.test.ts | 30 ++++++++++++++++++ 9 files changed, 119 insertions(+), 12 deletions(-) diff --git a/src/components/ui/TagManageWidget.tsx b/src/components/ui/TagManageWidget.tsx index 34a8fbe..15d6d65 100644 --- a/src/components/ui/TagManageWidget.tsx +++ b/src/components/ui/TagManageWidget.tsx @@ -20,7 +20,9 @@ import { endpoints } from '@/config/api'; import { toast } from 'react-toastify'; import LoadingSpinner from './LoadingSpinner'; import sleep from '@/utils/sleep'; -import { saveChartTags } from '@/utils/chartTags'; +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, @@ -133,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); @@ -257,8 +259,14 @@ const TagManageWindow = forwardRef( let saved: string[]; try { saved = await saveChartTags(songid, isInPrivatePage ? 'private' : 'public', serverTagsRef.current, tags); - } catch { - toast.error('好像上传失败惹……'); + } 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('好像上传失败惹……'); + } return; } finally { toast.done(uploading); @@ -276,6 +284,17 @@ const TagManageWindow = forwardRef( } }; + /** 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) { return
failed to load
; } @@ -408,8 +427,7 @@ const TagManageWindow = forwardRef(