From 572cf2fdb06c9ccc0673e80a7715caa98c1fbf85 Mon Sep 17 00:00:00 2001 From: LingFeng-bbben Date: Sat, 28 Nov 2026 00:22:37 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix(user):=20=E4=B8=8A=E4=BC=A0=E8=B0=B1?= =?UTF-8?q?=E9=9D=A2=E5=8F=AA=E6=A0=A1=E9=AA=8C=E6=A0=BC=E5=BC=8F=EF=BC=8C?= =?UTF-8?q?=E4=B8=8A=E6=8A=A5=E6=97=B6=E6=94=B9=E7=94=A8=E6=A0=87=E5=87=86?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 手机端背景图的选择改成扩展名 accept,和 maidata.txt 一样直接打开文件选择器;用户文件名叫什么都能选,提交时按扩展名改写成 maidata.txt / bg.png / bg.jpg / track.mp3 / pv.mp4。 --- .../2026-11-27-chart-upload-format.md | 48 +++++++ src/components/user/ChartUploader.tsx | 65 ++++------ src/locales/en.json | 2 +- src/locales/ja.json | 2 +- src/locales/ko.json | 2 +- src/locales/zh.json | 2 +- src/utils/chartUploadValidation.ts | 121 ++++++++++++++++-- test/utils/chartUploadValidation.test.ts | 115 +++++++++++++++-- 8 files changed, 292 insertions(+), 65 deletions(-) create mode 100644 docs/changelog/2026-11-27-chart-upload-format.md diff --git a/docs/changelog/2026-11-27-chart-upload-format.md b/docs/changelog/2026-11-27-chart-upload-format.md new file mode 100644 index 00000000..7a23a044 --- /dev/null +++ b/docs/changelog/2026-11-27-chart-upload-format.md @@ -0,0 +1,48 @@ +# 上传页:手机端选背景图改走「文件」,且不再要求用户文件名 + +日期:2026-11-27 +分支:`main` + +## 背景 + +谱面上传有四个槽位:`maidata.txt`、`bg.png / bg.jpg`、`track.mp3`、`bg.mp4 / pv.mp4`。 +原来有三个问题叠在一起: + +1. **手机端点「选择」背景图会先进相册**。`accept="image/png,image/jpeg"` 是 MIME 类型, + iOS 看到图片类型会先弹「照片图库 / 拍照 / 选择文件」菜单;`maidata.txt` 用的是 + `.txt` 扩展名,所以能直接打开「文件」App。同一张谱面文件夹里的东西,两边体验不一致。 +2. **文件名被要求得死死的**。校验只认 `bg.png`、`bg.jpg`、`track.mp3`、`pv.mp4` 这些 + 精确名字(区分大小写)。手机相册导出的 `IMG_0001.JPG`、网盘下载的 `封面.jpg` 全被判 + 成非法,用户得先改名才能上传。 +3. **接口靠标准文件名认文件**。`formfiles` 里的每个 part 用 `maidata.txt` / `bg.jpg` / + `track.mp3` / `pv.mp4` 区分用途,不能直接把用户的原始文件名发过去。 + +## 前端改动 + +| 位置 | 改动 | +| --- | --- | +| `src/utils/chartUploadValidation.ts` | 改为「格式规则表」:每个槽位声明允许的扩展名、是否必填、扩展名 → 标准文件名的映射。新增 `isChartUploadFileFormatAccepted`(只按扩展名判断)、`getChartUploadAccept`(只用扩展名拼 `accept`)、`toStandardChartUploadFile`(改写成标准文件名并补正 MIME)、`buildChartUploadFormData`(按槽位顺序组装 FormData) | +| `src/components/user/ChartUploader.tsx` | 选择文件时只提示格式不对,不再提示文件名;提交时从 `picked` 状态组装 FormData,用户文件名不参与上报。背景图按扩展名映射 `bg.png` / `bg.jpg`(`.jpeg` 也算 jpg),视频统一 `pv.mp4`,音频统一 `track.mp3`,谱面统一 `maidata.txt` | +| `src/locales/{zh,en,ja,ko}.json` | `InvalidFileName` 改为 `InvalidFileFormat`,用 `{{formats}}` 显示该槽位接受的扩展名 | + +`accept` 全部改成扩展名形式:`.txt` / `.png,.jpg,.jpeg` / `.mp3` / `.mp4`。WebKit 对只含 +扩展名的 accept 会直接打开文件选择器,不再先给相册菜单;桌面端同样按扩展名过滤。 + +## 验证 + +- `test/utils/chartUploadValidation.test.ts` 重写(37 个用例):任意文件名只要扩展名对就 + 接受、大小写不敏感;`.gif` / `.webp` / `.wav` / `.mov` / 无扩展名 / `xxx.png.bak` 被拒; + `accept` 不含任何 MIME(防止手机端退回相册);标准名映射(含 `.jpeg` → `bg.jpg`)和 + FormData 的顺序、跳过空槽位、可选视频都覆盖。 +- `pnpm test`(60 个文件、489 个用例)、`pnpm lint`、`tsc -p tsconfig.app.json --noEmit` + / `tsc -p tsconfig.node.json --noEmit`、`pnpm i18n:check` 通过。 +- 手机端行为依赖浏览器对 accept 的处理,无法在单元测试里模拟;用 iOS Safari 从「文件」 + App 选 `IMG_0001.JPG` 后,请求里的 part 名应为 `bg.jpg`,槽位显示仍是原文件名。 + +## 注意 + +- 只改文件名,不改文件内容;格式仍按扩展名判断,HEIC 之类后端不存的格式会被拒绝。 +- 视频接口同时接受 `bg.mp4` 和 `pv.mp4`,这里统一用 `pv.mp4`(下载 zip 和编辑器查找 + 视频时也是 `pv.mp4` 优先)。 +- FormData 不再给未选中的槽位塞空 `File`,只按槽位顺序放已选文件;接口按文件名识别, + 不依赖 part 个数。 diff --git a/src/components/user/ChartUploader.tsx b/src/components/user/ChartUploader.tsx index 624c8d85..733ef174 100644 --- a/src/components/user/ChartUploader.tsx +++ b/src/components/user/ChartUploader.tsx @@ -7,7 +7,13 @@ import { endpoints } from '@/config/api'; import { useUserContext } from '@/hooks'; import { getDisplayMessage, sleep } from '@/utils'; import { getFileKey, hashCandidatesFromBytes } from '@/utils/maidataHash'; -import { getExpectedChartUploadFileNames, isValidChartUploadFileName } from '@/utils/chartUploadValidation'; +import { + buildChartUploadFormData, + CHART_UPLOAD_FILE_RULES, + getChartUploadAccept, + getChartUploadFormatHint, + isChartUploadFileFormatAccepted, +} from '@/utils/chartUploadValidation'; import { LuFileAudio, LuFileText, LuFileVideo, LuImage, LuUpload } from 'react-icons/lu'; import { LoadingSpinner } from '@/components'; import type { Song } from '@/types'; @@ -36,7 +42,7 @@ export default function ChartUploader() { const [hashLookup, setHashLookup] = useState({ status: 'idle' }); const hashLookupSeq = useRef(0); const hashLookupAbort = useRef(null); - /** 每个槽位当前选中的文件(只用于显示;提交时仍从表单里的 input 读取) */ + /** 每个槽位当前选中的文件;提交时按槽位顺序改写文件名后放进 FormData */ const [picked, setPicked] = useState<(File | null)[]>([null, null, null, null]); const inputRefs = useRef<(HTMLInputElement | null)[]>([]); const setPickedAt = (index: number, file: File | null) => setPicked((prev) => prev.map((value, i) => (i === index ? file : value))); @@ -151,10 +157,9 @@ export default function ChartUploader() { return; } - if (!isValidChartUploadFileName(index, file.name)) { + if (!isChartUploadFileFormatAccepted(index, file.name)) { toast.error( - t("user/ChartUploader.InvalidFileName") - + getExpectedChartUploadFileNames(index), + t("user/ChartUploader.InvalidFileFormat", { formats: getChartUploadFormatHint(index) }), ); event.currentTarget.value = ''; if (index === 0) { @@ -172,23 +177,10 @@ export default function ChartUploader() { async function onSubmit(event: React.FormEvent) { event.preventDefault(); - const formData = new FormData(event.currentTarget); - const filesNecessary = formData.getAll('formfiles'); - - const fileChecks = [ - { file: filesNecessary[0], name: 'maidata.txt' }, - { file: filesNecessary[1], name: 'bg.png/bg.jpg' }, - { file: filesNecessary[2], name: 'track' }, - ]; - - const missedFiles: string[] = []; - - for (const { file, name } of fileChecks) { - const fileObj = file as File; - if (!fileObj || fileObj.name === '' || fileObj.size === 0) { - missedFiles.push(name); - } - } + const isMissing = (file: File | null) => !file || file.size === 0; + const missedFiles = CHART_UPLOAD_FILE_RULES + .filter((rule, index) => rule.required && isMissing(picked[index])) + .map((rule) => rule.label); if (missedFiles.length > 0) { for (const file of missedFiles) { @@ -197,22 +189,20 @@ export default function ChartUploader() { return; } - for (let index = 0; index < filesNecessary.length; index += 1) { - const file = filesNecessary[index] as File; - // The fourth file is optional; an empty file input can appear as an empty File. - if (!file || file.name === '' || file.size === 0) { - continue; - } + for (const [index, file] of picked.entries()) { + if (!file || isMissing(file)) continue; - if (!isValidChartUploadFileName(index, file.name)) { + if (!isChartUploadFileFormatAccepted(index, file.name)) { toast.error( - t("user/ChartUploader.InvalidFileName") - + getExpectedChartUploadFileNames(index), + t("user/ChartUploader.InvalidFileFormat", { formats: getChartUploadFormatHint(index) }), ); return; } } + // 用户文件名不参与上传:这里统一改写成接口约定的标准文件名 + const formData = buildChartUploadFormData(picked); + if (hashLookup.status === 'exists') { toast.error(t("user/ChartUploader.MaidataAlreadyExists"), { autoClose: false }); return; @@ -254,12 +244,13 @@ export default function ChartUploader() { } } - const uploadFields = [ - { label: 'maidata.txt', Icon: LuFileText, accept: '.txt' }, - { label: 'bg.png / bg.jpg', Icon: LuImage, accept: 'image/png,image/jpeg' }, - { label: 'track.mp3', Icon: LuFileAudio, accept: 'audio/mpeg,.mp3' }, - { label: 'bg.mp4 / pv.mp4', Icon: LuFileVideo, accept: 'video/mp4', hint: t("user/ChartUploader.VideoHint") }, - ]; + const uploadFieldIcons = [LuFileText, LuImage, LuFileAudio, LuFileVideo]; + const uploadFields = CHART_UPLOAD_FILE_RULES.map((rule, index) => ({ + label: rule.label, + Icon: uploadFieldIcons[index], + accept: getChartUploadAccept(index), + hint: index === 3 ? t("user/ChartUploader.VideoHint") : undefined, + })); const hashLookupStatusText: Record = { idle: '', checking: t("user/ChartUploader.MaidataHashChecking"), diff --git a/src/locales/en.json b/src/locales/en.json index 1374820f..9d1b7b61 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -725,7 +725,7 @@ }, "user/ChartUploader": { "ChooseFile": "Choose", - "InvalidFileName": "Invalid file name (case-sensitive). Expected: ", + "InvalidFileFormat": "Unsupported file format. Choose a {{formats}} file.", "MaidataAlreadyExists": "This chart already exists on the site", "MaidataAlreadyExistsWithTitle": "This chart already exists on the site: {{title}}", "MaidataHashChecking": "Checking whether this chart already exists…", diff --git a/src/locales/ja.json b/src/locales/ja.json index 5a55b818..5f09716c 100644 --- a/src/locales/ja.json +++ b/src/locales/ja.json @@ -713,7 +713,7 @@ }, "user/ChartUploader": { "ChooseFile": "選択", - "InvalidFileName": "ファイル名が正しくありません(大文字と小文字を区別)。正しい名前:", + "InvalidFileFormat": "ファイル形式が対応していません。{{formats}} ファイルを選択してください", "MaidataAlreadyExists": "この譜面はすでにサイト上に存在します", "MaidataAlreadyExistsWithTitle": "この譜面はすでにサイト上に存在します:{{title}}", "MaidataHashChecking": "この譜面が既に存在するか確認しています...", diff --git a/src/locales/ko.json b/src/locales/ko.json index 06944a17..9fd5b8ca 100644 --- a/src/locales/ko.json +++ b/src/locales/ko.json @@ -713,7 +713,7 @@ }, "user/ChartUploader": { "ChooseFile": "선택", - "InvalidFileName": "파일 이름이 올바르지 않습니다(대소문자 구분). 올바른 이름: ", + "InvalidFileFormat": "지원하지 않는 파일 형식입니다. {{formats}} 파일을 선택하세요", "MaidataAlreadyExists": "이 채보는 이미 사이트에 존재합니다", "MaidataAlreadyExistsWithTitle": "이 채보는 이미 사이트에 존재합니다: {{title}}", "MaidataHashChecking": "이 채보가 이미 존재하는지 확인하는 중...", diff --git a/src/locales/zh.json b/src/locales/zh.json index 2a4d186c..0c37f92f 100644 --- a/src/locales/zh.json +++ b/src/locales/zh.json @@ -713,7 +713,7 @@ }, "user/ChartUploader": { "ChooseFile": "选择", - "InvalidFileName": "文件名不正确(区分大小写),应为:", + "InvalidFileFormat": "文件格式不正确,请选择 {{formats}} 文件", "MaidataAlreadyExists": "这个谱面已经存在于网站上", "MaidataAlreadyExistsWithTitle": "这个谱面已经存在于网站上:{{title}}", "MaidataHashChecking": "正在查询这个谱面是否已存在...", diff --git a/src/utils/chartUploadValidation.ts b/src/utils/chartUploadValidation.ts index 7ece8ed6..cc5fb63d 100644 --- a/src/utils/chartUploadValidation.ts +++ b/src/utils/chartUploadValidation.ts @@ -1,15 +1,114 @@ -export const CHART_UPLOAD_FILE_NAMES = [ - ['maidata.txt'], - ['bg.png', 'bg.jpg'], - ['track.mp3'], - ['bg.mp4', 'pv.mp4'], -] as const; +/** + * 上传槽位的格式规则。 + * + * 只按扩展名判断格式,不要求用户把文件命名成标准名:手机相册、网盘导出的文件多半叫 + * `IMG_0001.JPG` 之类。真正发给接口时会按扩展名改写成 standardNames 里的标准文件名。 + */ +export interface ChartUploadFileRule { + /** 界面和「没有选中」提示里显示的名字;也是接口侧期望的标准文件名 */ + label: string; + required: boolean; + /** 允许的扩展名:小写、带点 */ + extensions: readonly string[]; + /** 扩展名 → 上报给接口的标准文件名 */ + standardNames: Readonly>; +} + +export const CHART_UPLOAD_FILE_RULES: readonly ChartUploadFileRule[] = [ + { + label: 'maidata.txt', + required: true, + extensions: ['.txt'], + standardNames: { '.txt': 'maidata.txt' }, + }, + { + label: 'bg.png / bg.jpg', + required: true, + extensions: ['.png', '.jpg', '.jpeg'], + standardNames: { '.png': 'bg.png', '.jpg': 'bg.jpg', '.jpeg': 'bg.jpg' }, + }, + { + label: 'track.mp3', + required: true, + extensions: ['.mp3'], + standardNames: { '.mp3': 'track.mp3' }, + }, + { + // 接口两个名字都认;下载 zip 和编辑器里都优先 pv.mp4,这里也统一成 pv.mp4 + label: 'bg.mp4 / pv.mp4', + required: false, + extensions: ['.mp4'], + standardNames: { '.mp4': 'pv.mp4' }, + }, +]; + +/** 改写成标准文件名时一并修正 MIME,避免手机端给空 type 或 application/octet-stream */ +const MIME_BY_EXTENSION: Readonly> = { + '.txt': 'text/plain', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.mp3': 'audio/mpeg', + '.mp4': 'video/mp4', +}; + +/** 取小写扩展名(含点);没有扩展名时返回空串 */ +export function getChartUploadFileExtension(fileName: string): string { + const dot = fileName.lastIndexOf('.'); + return dot >= 0 ? fileName.slice(dot).toLowerCase() : ''; +} + +/** 文件格式是否被该槽位接受;不检查大小和内容 */ +export function isChartUploadFileFormatAccepted(index: number, fileName: string): boolean { + const rule = CHART_UPLOAD_FILE_RULES[index]; + if (!rule) return false; + return rule.extensions.includes(getChartUploadFileExtension(fileName)); +} + +/** + * 该槽位的 `input[accept]`。 + * + * 只用扩展名、不写 MIME:iOS 的 accept 里只要出现 `image/*`(`image/png` 也算), + * 就会先弹「照片图库 / 拍照 / 选择文件」菜单;只写扩展名才会像 maidata.txt 一样 + * 直接打开「文件」App。 + */ +export function getChartUploadAccept(index: number): string { + return CHART_UPLOAD_FILE_RULES[index]?.extensions.join(',') ?? ''; +} + +/** 错误提示里展示的格式列表,如 `.png / .jpg / .jpeg` */ +export function getChartUploadFormatHint(index: number): string { + return CHART_UPLOAD_FILE_RULES[index]?.extensions.join(' / ') ?? ''; +} + +/** + * 把用户选的文件改写成接口约定的标准文件名;格式不对返回 null。 + * + * 名字本来就标准时原样返回,避免无谓地复制 File。 + */ +export function toStandardChartUploadFile(index: number, file: File): File | null { + const rule = CHART_UPLOAD_FILE_RULES[index]; + if (!rule) return null; + + const extension = getChartUploadFileExtension(file.name); + if (!rule.extensions.includes(extension)) return null; + + const standardName = rule.standardNames[extension]; + if (file.name === standardName) return file; -export function isValidChartUploadFileName(index: number, fileName: string): boolean { - const allowedNames = CHART_UPLOAD_FILE_NAMES[index] as readonly string[] | undefined; - return allowedNames?.includes(fileName) ?? false; + return new File([file], standardName, { + type: MIME_BY_EXTENSION[extension] ?? file.type, + lastModified: file.lastModified, + }); } -export function getExpectedChartUploadFileNames(index: number): string { - return CHART_UPLOAD_FILE_NAMES[index]?.join('/') ?? ''; +/** 组装上传用的 FormData:按槽位顺序放入改写后的标准文件,未选的槽位直接跳过 */ +export function buildChartUploadFormData(files: readonly (File | null | undefined)[]): FormData { + const formData = new FormData(); + files.forEach((file, index) => { + if (!file) return; + const standardFile = toStandardChartUploadFile(index, file); + if (standardFile) formData.append('formfiles', standardFile); + }); + return formData; } diff --git a/test/utils/chartUploadValidation.test.ts b/test/utils/chartUploadValidation.test.ts index ba962b3c..a2a71837 100644 --- a/test/utils/chartUploadValidation.test.ts +++ b/test/utils/chartUploadValidation.test.ts @@ -1,23 +1,112 @@ import { describe, expect, it } from 'vitest'; -import { getExpectedChartUploadFileNames, isValidChartUploadFileName } from '@/utils/chartUploadValidation'; +import { + buildChartUploadFormData, + getChartUploadAccept, + getChartUploadFileExtension, + getChartUploadFormatHint, + isChartUploadFileFormatAccepted, + toStandardChartUploadFile, +} from '@/utils/chartUploadValidation'; + +function fileOf(name: string, type = ''): File { + return new File(['content'], name, { type }); +} + +describe('chart upload file format validation', () => { + it.each([ + [0, 'maidata.txt'], [0, 'my-chart.TXT'], + [1, 'bg.png'], [1, 'COVER.PNG'], [1, 'IMG_0001.JPG'], [1, 'photo.jpeg'], + [2, 'track.mp3'], [2, 'My Song.mp3'], + [3, 'pv.mp4'], [3, 'whatever.MP4'], + ])('accepts field %i by extension regardless of the rest of the name: %s', (index, fileName) => { + expect(isChartUploadFileFormatAccepted(index, fileName)).toBe(true); + }); -describe('chart upload file name validation', () => { it.each([ - [0, 'maidata.txt'], [1, 'bg.png'], [1, 'bg.jpg'], [2, 'track.mp3'], [3, 'bg.mp4'], [3, 'pv.mp4'], - ])('accepts the exact allowed name for field %i: %s', (index, fileName) => { - expect(isValidChartUploadFileName(index, fileName)).toBe(true); + [0, 'maidata'], [0, 'maidata.json'], [0, 'maidata.txt.bak'], + [1, 'bg.gif'], [1, 'bg.png.bak'], [1, 'cover.webp'], [1, 'bg'], + [2, 'track.wav'], [2, 'track.ogg'], [2, 'track.mp3.bak'], + [3, 'pv.mov'], [3, 'pv.mp4.bak'], + [9, 'bg.png'], + ])('rejects field %i for unsupported formats: %s', (index, fileName) => { + expect(isChartUploadFileFormatAccepted(index, fileName)).toBe(false); + }); + + it('reads the last extension case-insensitively', () => { + expect(getChartUploadFileExtension('IMG_0001.JPG')).toBe('.jpg'); + expect(getChartUploadFileExtension('archive.tar.gz')).toBe('.gz'); + expect(getChartUploadFileExtension('maidata')).toBe(''); }); + it('uses extension-only accept values so mobile browsers open the file picker', () => { + for (let index = 0; index < 4; index += 1) { + expect(getChartUploadAccept(index)).not.toMatch(/[a-z]+\//); + } + expect(getChartUploadAccept(0)).toBe('.txt'); + expect(getChartUploadAccept(1)).toBe('.png,.jpg,.jpeg'); + expect(getChartUploadAccept(2)).toBe('.mp3'); + expect(getChartUploadAccept(3)).toBe('.mp4'); + }); + + it('formats the accepted extensions for the error message', () => { + expect(getChartUploadFormatHint(1)).toBe('.png / .jpg / .jpeg'); + expect(getChartUploadFormatHint(3)).toBe('.mp4'); + }); +}); + +describe('standard upload file names', () => { it.each([ - [0, 'MAIDATA.TXT'], [0, 'maidata.txt.bak'], [0, ' maidata.txt'], - [1, 'BG.png'], [1, 'bg.jpeg'], [2, 'Track.mp3'], [2, 'track.mp3 '], - [3, 'PV.MP4'], [3, 'video.mp4'], - ])('rejects case differences and partial or extra text for field %i: %s', (index, fileName) => { - expect(isValidChartUploadFileName(index, fileName)).toBe(false); + [0, 'my chart.txt', 'maidata.txt'], + [1, 'cover.png', 'bg.png'], + [1, 'IMG_0001.JPG', 'bg.jpg'], + [1, 'photo.jpeg', 'bg.jpg'], + [2, 'My Song.mp3', 'track.mp3'], + [3, 'whatever.MP4', 'pv.mp4'], + ])('renames field %i file %s to %s', (index, source, expected) => { + const standard = toStandardChartUploadFile(index, fileOf(source)); + expect(standard).not.toBeNull(); + expect(standard!.name).toBe(expected); }); - it('formats every allowed alternative for the error message', () => { - expect(getExpectedChartUploadFileNames(1)).toBe('bg.png/bg.jpg'); - expect(getExpectedChartUploadFileNames(3)).toBe('bg.mp4/pv.mp4'); + it('sets the MIME type from the standard extension', () => { + const standard = toStandardChartUploadFile(1, fileOf('photo.jpeg', 'application/octet-stream')); + expect(standard?.type).toBe('image/jpeg'); + }); + + it('returns an already standard file untouched', () => { + const original = fileOf('bg.png', 'image/png'); + expect(toStandardChartUploadFile(1, original)).toBe(original); + }); + + it('rejects unsupported formats and unknown slots', () => { + expect(toStandardChartUploadFile(1, fileOf('bg.gif'))).toBeNull(); + expect(toStandardChartUploadFile(9, fileOf('bg.png'))).toBeNull(); + }); +}); + +describe('upload form data', () => { + it('appends standard names in slot order and skips empty slots', () => { + const formData = buildChartUploadFormData([ + fileOf('my chart.txt', 'text/plain'), + fileOf('IMG_0001.JPG', 'image/jpeg'), + fileOf('My Song.mp3', 'audio/mpeg'), + null, + ]); + + const files = formData.getAll('formfiles') as File[]; + expect(files.map((file) => file.name)).toEqual(['maidata.txt', 'bg.jpg', 'track.mp3']); + expect(files.map((file) => file.type)).toEqual(['text/plain', 'image/jpeg', 'audio/mpeg']); + }); + + it('keeps the optional video when it is chosen', () => { + const formData = buildChartUploadFormData([ + fileOf('maidata.txt'), + fileOf('bg.png'), + fileOf('track.mp3'), + fileOf('clip.mp4'), + ]); + + expect((formData.getAll('formfiles') as File[]).map((file) => file.name)) + .toEqual(['maidata.txt', 'bg.png', 'track.mp3', 'pv.mp4']); }); }); From b5967bfd2fd008b3b2cab12a335650caa888551f Mon Sep 17 00:00:00 2001 From: LingFeng-bbben Date: Sat, 28 Nov 2026 00:22:40 +0800 Subject: [PATCH 2/3] =?UTF-8?q?feat(space):=20=E4=B8=8A=E4=BC=A0=E7=9A=84?= =?UTF-8?q?=E8=B0=B1=E9=9D=A2=E9=A1=B5=E7=AD=BE=E6=94=AF=E6=8C=81=E6=8E=92?= =?UTF-8?q?=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 和搜索页共用排序选项与 ?sort= 参数;第一屏列表和搜索模式的全量拉取都带排序词,并补一个组件测试。 --- .../2026-11-28-space-uploaded-sort.md | 40 ++++++ src/components/user/UploadedCharts.tsx | 125 +++++++++++------- test/components/user/UploadedCharts.test.tsx | 82 ++++++++++++ 3 files changed, 196 insertions(+), 51 deletions(-) create mode 100644 docs/changelog/2026-11-28-space-uploaded-sort.md create mode 100644 test/components/user/UploadedCharts.test.tsx diff --git a/docs/changelog/2026-11-28-space-uploaded-sort.md b/docs/changelog/2026-11-28-space-uploaded-sort.md new file mode 100644 index 00000000..4e61e1ad --- /dev/null +++ b/docs/changelog/2026-11-28-space-uploaded-sort.md @@ -0,0 +1,40 @@ +# 个人空间「上传的谱面」加排序 + +日期:2026-11-28 +分支:`main` + +## 背景 + +个人空间的「上传的谱面」页签只有页内搜索,没有排序:列表固定在接口默认的「最近活跃」, +搜出结果后也只能按这个顺序看。搜索页和歌单页早就有一排排序选项(活跃 / 热门 / 分数 / +评论 / 播放 / 上传时间),这里缺一组。 + +## 前端改动 + +| 位置 | 改动 | +| --- | --- | +| `src/components/user/UploadedCharts.tsx` | 搜索框右边加 `SortMenu`,和搜索页共用 `SORT_WORDS`、`useSortOptions`、`parseIndexParam`;排序下标写进网址 `?sort=`(默认 0 不落参数)。第一屏 `SongList` 的两个接口页和搜索模式的全量拉取都带上排序词 | +| `test/components/user/UploadedCharts.test.tsx` | 新增组件测试:选中「上传时间」后列表接口变成 `sort=timep`,网址变成 `sort=5` | + +排序参数和搜索词、页签一起放在地址栏里,刷新/分享/浏览器回退都能还原。搜索模式下 +`collectAllPages` 本来就按接口顺序合并,带排序拉回来后前端过滤不会打乱顺序,所以过滤结果 +也是全局排序后的顺序。 + +## 验证 + +- 开发服务器(`pnpm dev`,http://localhost:3000)真实数据,LSP2 的空间: + - 默认「活跃」:`/space?id=LSP2&tab=uploaded`,列表首项 `Doki Doki Forever`; + - 切「上传时间」:网址变为 `...&sort=5`,Network 里两页列表请求都带 `sort=timep`, + 首项变成最新上传的 `一冊のアロー`;切回「活跃」参数消失、顺序恢复; + - 搜索 + 排序:`?q=Doki&sort=5` 下仍显示「找到 1 张谱面 / Doki Doki Forever」, + 全量拉取的第 0–5 页也都带 `sort=timep`; + - 390×844 手机视口:搜索框和排序按钮同一行,排序按钮不挤压输入框。 +- `test/components/user/UploadedCharts.test.tsx` 通过;`pnpm test` 共 61 个文件、 + 490 个用例全部通过;`pnpm lint`、`pnpm i18n:check`、`pnpm build` 通过。 + +## 注意 + +- 默认排序保持接口原来的「最近活跃」,没有把「上传时间」设成默认,行为和搜索页一致。 +- 搜索模式改变排序会重新拉一遍这个用户的全部上传(按新排序分页),期间显示加载态; + 用户上传很多时这一步会比第一屏慢,和原来首次聚焦搜索框的代价一样。 +- 排序菜单只复用现有文案,没有新增 i18n key。 diff --git a/src/components/user/UploadedCharts.tsx b/src/components/user/UploadedCharts.tsx index 37452956..7083d2d4 100644 --- a/src/components/user/UploadedCharts.tsx +++ b/src/components/user/UploadedCharts.tsx @@ -1,7 +1,8 @@ /** - * 个人空间“上传的谱面”:列表上方带页内搜索框。 + * 个人空间“上传的谱面”:列表上方带页内搜索框和排序菜单。 * 后端搜索不能把“上传者”和关键词组合起来,所以第一次聚焦搜索框(或网址里带着搜索词)时 * 把这个用户的全部上传一次拉回来,联想和过滤都在前端做。没有搜索词时仍显示原来的第一屏列表。 + * 排序和搜索页共用一套参数:`?sort=` 是下标、对应 `SORT_WORDS`。 */ import { useId, useMemo, useRef, useState } from 'react'; @@ -16,7 +17,9 @@ import InteractSummaryProvider from '@/components/song/InteractSummaryProvider'; import { API_PAGE_SIZE, apiPagesForView, SONG_GRID_CONTAINER_CLASS } from '@/components/song/songGrid'; import EmptyState from '@/components/ui/EmptyState'; import SectionLoading from '@/components/ui/SectionLoading'; +import SortMenu from '@/components/ui/SortMenu'; import SuggestionListbox, { type SuggestionListboxItem } from '@/components/ui/SuggestionListbox'; +import { SORT_WORDS, parseIndexParam, useSortOptions } from '@/components/search/chartSort'; import { endpoints } from '@/config/api'; import { apiFetcher } from '@/utils/apiClient'; import type { SuggestionKind } from '@/utils/searchSuggestions'; @@ -25,9 +28,11 @@ import type { Song } from '@/types'; /** 网址里保存已提交搜索词的参数名 */ const QUERY_PARAM = 'q'; +/** 网址里保存排序下标;和搜索页的 `sort` 参数一致 */ +const SORT_PARAM = 'sort'; -const fetchAllUploaded = ([, username]: [string, string]) => - collectAllPages((page) => apiFetcher(endpoints.maichart.listSearchAndSort('uploader:' + username, '', page)), API_PAGE_SIZE); +const fetchAllUploaded = ([, username, sortWord]: [string, string, string]) => + collectAllPages((page) => apiFetcher(endpoints.maichart.listSearchAndSort('uploader:' + username, sortWord, page)), API_PAGE_SIZE); export default function UploadedCharts({ username, onDataLoaded }: { username: string; @@ -35,7 +40,10 @@ export default function UploadedCharts({ username, onDataLoaded }: { }) { const { t } = useTranslation(); const [searchParams, setSearchParams] = useSearchParams(); + const sortOptions = useSortOptions(); const committed = (searchParams.get(QUERY_PARAM) ?? '').trim(); + const sortType = parseIndexParam(searchParams.get(SORT_PARAM), SORT_WORDS.length - 1); + const sortWord = SORT_WORDS[sortType]; const [currentValue, setCurrentValue] = useState(committed); const [isFocused, setIsFocused] = useState(false); const [activeIndex, setActiveIndex] = useState(-1); @@ -44,7 +52,7 @@ export default function UploadedCharts({ username, onDataLoaded }: { const inputRef = useRef(null); const listboxId = useId(); - const all = useSWR(wantAll || committed ? ['uploaded-all', username] : null, fetchAllUploaded, { revalidateOnFocus: false }); + const all = useSWR(wantAll || committed ? ['uploaded-all', username, sortWord] : null, fetchAllUploaded, { revalidateOnFocus: false }); const kindLabels: Record = { title: t("home/HomePage.SuggestKindTitle"), @@ -75,6 +83,13 @@ export default function UploadedCharts({ username, onDataLoaded }: { setSearchParams(next, { replace: true, preventScrollReset: true }); }; + /** 和搜索页一样把排序写进网址;默认排序(下标 0)不落参数 */ + const setSort = (value: number) => { + const next = new URLSearchParams(searchParams); + if (value > 0) next.set(SORT_PARAM, String(value)); else next.delete(SORT_PARAM); + setSearchParams(next, { preventScrollReset: true }); + }; + const setValue = (value: string) => { setCurrentValue(value); setActiveIndex(-1); @@ -114,59 +129,67 @@ export default function UploadedCharts({ username, onDataLoaded }: { return ( <> -
-
{/* 原列表一直挂着:它负责告诉页面有没有上传(决定页签是否显示) */} diff --git a/src/components/ui/LoadingSpinner.tsx b/src/components/ui/LoadingSpinner.tsx index e8ff1cbb..d3cb3597 100644 --- a/src/components/ui/LoadingSpinner.tsx +++ b/src/components/ui/LoadingSpinner.tsx @@ -1,8 +1,10 @@ import { useState } from 'react'; interface LoadingSpinnerProps { - className?: string; // Additional classes for the spinner container - size?: number | string; // Size of the spinner (e.g. 24 or "1.5rem") + /** 只放颜色、动画之类的附加类;尺寸请用 `size`(宽高是内联样式,会盖过 w-/h- 工具类) */ + className?: string; + /** 转圈的直径,数字按 px 处理(例如 16 或 "1.5rem") */ + size?: number | string; } /** 转一圈的时长 */ diff --git a/src/components/user/ChartUploader.tsx b/src/components/user/ChartUploader.tsx index 733ef174..ebc7f9f0 100644 --- a/src/components/user/ChartUploader.tsx +++ b/src/components/user/ChartUploader.tsx @@ -320,7 +320,7 @@ export default function ChartUploader() { {hashLookup.status !== 'idle' && (
- {hashLookup.status === 'checking' && } + {hashLookup.status === 'checking' && } {hashLookupStatusText[hashLookup.status]} {hashLookup.status === 'exists' && hashLookup.chart && ( {isUploading ? ( <> - + {t("user/ChartUploader.UploadingPlzWait")} ) : ( diff --git a/src/pages/QRAuthPage.tsx b/src/pages/QRAuthPage.tsx index 04366873..1dcf2933 100644 --- a/src/pages/QRAuthPage.tsx +++ b/src/pages/QRAuthPage.tsx @@ -164,7 +164,7 @@ function PermitLogin({ authId }: { authId: string | null }) { disabled={submitting} className="inline-flex justify-center items-center gap-2 bg-blue-500 hover:bg-blue-400 disabled:opacity-60 mt-6 border-none rounded-xl w-full h-11 font-semibold text-white text-sm transition-colors cursor-pointer disabled:cursor-not-allowed" > - {submitting && } + {submitting && } {t('qrauth/QRAuthPage.Confirm')}