From 7cb873f0a99ddb62ee6d43c9795c6b265caa51d9 Mon Sep 17 00:00:00 2001 From: LingFeng-bbben <51612155+LingFeng-bbben@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:16:43 +0800 Subject: [PATCH] feat: display user b50 --- src/components/chart/RadarPlot.tsx | 83 ++++++++++++++++ src/components/index.ts | 2 + src/components/song/ChartRadar.tsx | 78 +-------------- src/components/ui/CollapsibleSection.tsx | 49 ++++++++++ src/components/user/BestScores.tsx | 74 ++++++++++++++ src/components/user/UserRating.tsx | 69 +++++++++++++ src/config/api.ts | 3 + src/hooks/useUserRating.ts | 55 +++++++++++ src/locales/en.json | 10 ++ src/locales/ja.json | 10 ++ src/locales/ko.json | 10 ++ src/locales/zh.json | 10 ++ src/pages/SpacePage.tsx | 85 +++------------- src/types/radar.ts | 18 ++++ .../components/ui/CollapsibleSection.test.tsx | 60 ++++++++++++ test/components/user/UserRating.test.tsx | 97 +++++++++++++++++++ 16 files changed, 569 insertions(+), 144 deletions(-) create mode 100644 src/components/chart/RadarPlot.tsx create mode 100644 src/components/ui/CollapsibleSection.tsx create mode 100644 src/components/user/BestScores.tsx create mode 100644 src/components/user/UserRating.tsx create mode 100644 src/hooks/useUserRating.ts create mode 100644 test/components/ui/CollapsibleSection.test.tsx create mode 100644 test/components/user/UserRating.test.tsx diff --git a/src/components/chart/RadarPlot.tsx b/src/components/chart/RadarPlot.tsx new file mode 100644 index 0000000..3adb634 --- /dev/null +++ b/src/components/chart/RadarPlot.tsx @@ -0,0 +1,83 @@ +import { useTranslation } from 'react-i18next'; +import { motion, useReducedMotion } from 'framer-motion'; +import { radarAxes } from '@/utils/radar'; +import type { RadarAxis } from '@/types/radar'; +import radarBackground from '@/assets/radar/MajRadarBG.png'; + +export interface RadarPlotProps { + /** Radar feature values by key; a missing or null value is drawn as 0. */ + feature: Partial>; +} + +// 100 reaches the reference hexagon; drawing stops at 200, while labels +// and dominant-axis colors continue to use the original scores. +const RADAR_CENTER_X = 160; +const RADAR_CENTER_Y = 180; +const REFERENCE_RADIUS = 90; +const REFERENCE_SCORE = 100; +const MAX_RENDERED_SCORE = 200; + +/** + * Draws the six-axis Majdata radar with the fitted chart constant in the centre. + * Shared by the chart radar on the song page and the rating radar on the profile page. + */ +export default function RadarPlot({ feature }: RadarPlotProps) { + const { t } = useTranslation(); + const reduceMotion = useReducedMotion(); + // Access by key: JSON dictionary iteration order is not the visual axis order. + const values = radarAxes.map(axis => feature[axis.key]); + const complete = values.every((value): value is number => value !== null && value !== undefined); + const strongest = complete ? values.indexOf(Math.max(...values)) : 0; + const color = radarAxes[strongest]; + const points = values.map((value, i) => { + const angle = (-90 + i * 60) * Math.PI / 180; + const radius = Math.max(0, Math.min(MAX_RENDERED_SCORE, value ?? 0)) / REFERENCE_SCORE * REFERENCE_RADIUS; + return `${RADAR_CENTER_X + Math.cos(angle) * radius},${RADAR_CENTER_Y + Math.sin(angle) * radius}`; + }).join(' '); + const esti = feature.fitted_constant; + const labels = radarAxes.map(axis => t(axis.i18nKey)); + const estiLabel = t('song/ChartRadar.FittedConstant'); + + return ( + `${label}: ${values[i] ?? '—'}`).join(', ')}; ${estiLabel}: ${esti?.toFixed(2) ?? '—'}`} + > + {complete && ( + + )} + + {radarAxes.map((axis, i) => { + const angle = (-90 + i * 60) * Math.PI / 180; + const x = RADAR_CENTER_X + Math.cos(angle) * REFERENCE_RADIUS; + const y = RADAR_CENTER_Y + Math.sin(angle) * REFERENCE_RADIUS; + return ( + + {labels[i]} + {values[i]?.toFixed(0) ?? '—'} + + ); + })} + + {esti?.toFixed(2) ?? '—'} + + {estiLabel} + + ); +} \ No newline at end of file diff --git a/src/components/index.ts b/src/components/index.ts index 2dc4a9f..02e1bff 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -28,6 +28,7 @@ export { default as SongCard } from './song/SongCard'; export { default as Majdata } from './song/Majdata'; export { default as MiniGame } from './song/MiniGame'; export { default as RecentPlayedWidget } from './user/RecentPlayedWidget'; +export { default as UserRating } from './user/UserRating'; // 活动相关组件 export { default as EventBanner } from './event/EventBanner'; @@ -51,6 +52,7 @@ export { default as Tooltip, TooltipProvider } from './ui/Tooltip'; export { default as LazyLoad } from './ui/LazyLoad'; export { default as LoadingSpinner } from './ui/LoadingSpinner'; export { default as TmpRichText } from './ui/TmpRichText'; +export { default as CollapsibleSection } from './ui/CollapsibleSection'; export { default as CollectionCard } from './collection/CollectionCard'; export { default as CollectionModal } from './collection/CollectionModal'; diff --git a/src/components/song/ChartRadar.tsx b/src/components/song/ChartRadar.tsx index 6c838d4..683eb0c 100644 --- a/src/components/song/ChartRadar.tsx +++ b/src/components/song/ChartRadar.tsx @@ -1,10 +1,7 @@ import { useTranslation } from 'react-i18next'; import { useId } from 'react'; -import { motion, useReducedMotion } from 'framer-motion'; import { RadarRequestError, useChartRadar } from '@/hooks/useChartRadar'; -import { radarAxes } from '@/utils/radar'; -import type { ChartRadarResponse } from '@/types/radar'; -import radarBackground from '@/assets/radar/MajRadarBG.png'; +import RadarPlot from '@/components/chart/RadarPlot'; interface ChartRadarProps { id: string; @@ -12,75 +9,6 @@ interface ChartRadarProps { chartLevel: number | undefined; } -// 100 reaches the reference hexagon; drawing stops at 200, while labels -// and dominant-axis colors continue to use the original scores. -const RADAR_CENTER_X = 160; -const RADAR_CENTER_Y = 180; -const REFERENCE_RADIUS = 90; -const REFERENCE_SCORE = 100; -const MAX_RENDERED_SCORE = 200; - -function RadarPlot({ data }: { data: ChartRadarResponse }) { - const { t } = useTranslation(); - const reduceMotion = useReducedMotion(); - // Access by key: JSON dictionary iteration order is not the visual axis order. - const values = radarAxes.map(axis => data.feature[axis.key]); - const complete = values.every((value): value is number => value !== null); - const strongest = complete ? values.indexOf(Math.max(...values)) : 0; - const color = radarAxes[strongest]; - const points = values.map((value, i) => { - const angle = (-90 + i * 60) * Math.PI / 180; - const radius = Math.max(0, Math.min(MAX_RENDERED_SCORE, value ?? 0)) / REFERENCE_SCORE * REFERENCE_RADIUS; - return `${RADAR_CENTER_X + Math.cos(angle) * radius},${RADAR_CENTER_Y + Math.sin(angle) * radius}`; - }).join(' '); - const esti = data.feature.fitted_constant; - const labels = radarAxes.map(axis => t(axis.i18nKey)); - const estiLabel = t('song/ChartRadar.FittedConstant'); - - return ( - `${label}: ${values[i] ?? '—'}`).join(', ')}; ${estiLabel}: ${esti?.toFixed(2) ?? '—'}`} - > - {complete && ( - - )} - - {radarAxes.map((axis, i) => { - const angle = (-90 + i * 60) * Math.PI / 180; - const x = RADAR_CENTER_X + Math.cos(angle) * REFERENCE_RADIUS; - const y = RADAR_CENTER_Y + Math.sin(angle) * REFERENCE_RADIUS; - return ( - - {labels[i]} - {values[i]?.toFixed(0) ?? '—'} - - ); - })} - - {esti?.toFixed(2) ?? '—'} - - {estiLabel} - - ); -} - export default function ChartRadar({ id, hash, chartLevel }: ChartRadarProps) { const { t } = useTranslation(); const titleId = useId(); @@ -104,9 +32,9 @@ export default function ChartRadar({ id, hash, chartLevel }: ChartRadarProps) { ) : data ? (
- +
) : null} ); -} +} \ No newline at end of file diff --git a/src/components/ui/CollapsibleSection.tsx b/src/components/ui/CollapsibleSection.tsx new file mode 100644 index 0000000..5138370 --- /dev/null +++ b/src/components/ui/CollapsibleSection.tsx @@ -0,0 +1,49 @@ +import { useId, useState, type ReactNode } from 'react'; +import { useTranslation } from 'react-i18next'; +import { IoChevronDownOutline } from 'react-icons/io5'; + +interface CollapsibleSectionProps { + /** Section title, also the label of the toggle button. */ + title: string; + children: ReactNode; + /** Whether the section starts expanded; defaults to true. */ + defaultOpen?: boolean; + className?: string; +} + +/** + * A space-page section whose content can be folded away, with the section title and the divider kept visible. + */ +export default function CollapsibleSection({ title, children, defaultOpen = true, className }: CollapsibleSectionProps) { + const { t } = useTranslation(); + const [open, setOpen] = useState(defaultOpen); + const contentId = useId(); + + return ( +
+

+ +

+
+ {open &&
{children}
} +
+ ); +} \ No newline at end of file diff --git a/src/components/user/BestScores.tsx b/src/components/user/BestScores.tsx new file mode 100644 index 0000000..e6b5326 --- /dev/null +++ b/src/components/user/BestScores.tsx @@ -0,0 +1,74 @@ +import { useTranslation } from 'react-i18next'; +import { Link } from 'react-router-dom'; +import { endpoints } from '@/config/api'; +import { getComboState } from '@/utils'; +import type { Score } from '@/types'; + +interface BestScoresProps { + /** The best chart levels of the rating, best first, in the shape of `GET api/account/scores`. */ + scores: Score[]; +} + +const COMBO_CLASS: Record = { + 'AP+': 'bg-gradient-to-r from-amber-400 to-yellow-300 text-black', + 'AP': 'bg-gradient-to-r from-amber-400/80 to-yellow-300/80 text-black', + 'FC+': 'bg-gradient-to-r from-blue-500 to-sky-300 text-white', + 'FC': 'bg-gradient-to-r from-blue-500/80 to-sky-300/80 text-white', +}; + +/** + * The best 50 chart levels of a player, compact enough to sit next to the rating radar. + */ +export default function BestScores({ scores }: BestScoresProps) { + const { t } = useTranslation(); + + if (scores.length === 0) { + return

{t('space/SpacePage.Best50Empty')}

; + } + + return ( +
    + {scores.map((score, index) => { + const chart = score.chartInfo; + const difficulty = chart?.levels?.[score.chartLevel] ?? ''; + const comboState = Number(score.comboState); + const comboText = comboState > 0 ? getComboState(comboState) : ''; + return ( +
  1. + + {index + 1} + {chart?.id && ( + + )} +
    +

    {chart?.title ?? ''}

    +

    + {[chart?.artist, chart?.designer].filter(Boolean).join(' · ')} +

    +
    + {difficulty && ( + {difficulty} + )} + {comboText && ( + + {comboText} + + )} + {score.acc.dx.toFixed(4)} + +
  2. + ); + })} +
+ ); +} \ No newline at end of file diff --git a/src/components/user/UserRating.tsx b/src/components/user/UserRating.tsx new file mode 100644 index 0000000..44923a3 --- /dev/null +++ b/src/components/user/UserRating.tsx @@ -0,0 +1,69 @@ +import { useTranslation } from 'react-i18next'; +import { RatingRequestError, useUserRating } from '@/hooks/useUserRating'; +import RadarPlot from '@/components/chart/RadarPlot'; +import BestScores from '@/components/user/BestScores'; +import LoadingSpinner from '@/components/ui/LoadingSpinner'; + +interface UserRatingProps { + username: string; +} + +/** + * The rating radar of a player and the best 50 chart levels it averages, loaded from the rating endpoint. + */ +export default function UserRating({ username }: UserRatingProps) { + const { t } = useTranslation(); + const { data, error, isLoading, isValidating, mutate } = useUserRating(username); + + if (error) { + const message = error instanceof RatingRequestError && error.status === 404 + ? t('space/SpacePage.UserNotFound') + : t('space/SpacePage.RatingFailed'); + return ( +
+

{message}

+ +
+ ); + } + + if (isLoading) { + return ( +
+ +
+ ); + } + + if (!data || data.chartCount === 0 || data.best.length === 0) { + return

{t('space/SpacePage.RatingEmpty')}

; + } + + return ( +
+
+ +

+ {t('space/SpacePage.RatingCharts', { count: data.chartCount })} +

+

+ {t('space/SpacePage.RatingFormula')} +

+
+
+

{t('space/SpacePage.Best50')}

+ +
+
+ ); +} \ No newline at end of file diff --git a/src/config/api.ts b/src/config/api.ts index 9773251..33ff715 100644 --- a/src/config/api.ts +++ b/src/config/api.ts @@ -15,6 +15,9 @@ export const endpoints = { // POST,按谱面 Id 集合(请求体 songIds)和时间段统计排行(季赛榜) periodLeaderboard: `${apiroot3}/maiscore/leaderboard/period`, // 成绩总和榜;uploader 为空时为全站榜,否则只统计该上传者的谱面 + // 个人 rating 雷达:前 50 个「谱面 + 难度」的加权平均,best 与 account/scores 的元素结构相同 + rating: (username: string) => + `${apiroot3}/maiscore/rating/by-username/${encodeURIComponent(username)}`, scoreSums: (uploader: string, page: number, pageSize: number) => uploader ? `${apiroot3}/maiscore/sum/chart/by-uploader/${encodeURIComponent(uploader)}?page=${page}&pageSize=${pageSize}` diff --git a/src/hooks/useUserRating.ts b/src/hooks/useUserRating.ts new file mode 100644 index 0000000..04b957f --- /dev/null +++ b/src/hooks/useUserRating.ts @@ -0,0 +1,55 @@ +import useSWR from 'swr'; +import { endpoints } from '@/config/api'; +import { radarAxes } from '@/utils/radar'; +import type { RatingRadarResponse } from '@/types/radar'; + +export class RatingRequestError extends Error { + readonly status: number; + + constructor(status: number) { + super(`Rating request failed (${status})`); + this.status = status; + } +} + +const REQUIRED_FEATURES = [...radarAxes.map(axis => axis.key), 'fitted_constant'] as const; + +async function fetchRating([url]: [string, string]): Promise { + const controller = new AbortController(); + // A cold request analyzes the charts that have no radar yet, so allow more than the chart radar timeout. + const timeout = window.setTimeout(() => controller.abort(), 120_000); + try { + const response = await fetch(url, { signal: controller.signal, credentials: 'include' }); + if (!response.ok) throw new RatingRequestError(response.status); + const value = await response.json(); + // An empty feature object is the valid "no chart could be averaged" response. + const feature = value?.feature; + const featureIsValid = feature && typeof feature === 'object' && !Array.isArray(feature) + && (Object.keys(feature).length === 0 + || REQUIRED_FEATURES.every(key => typeof feature[key] === 'number' && Number.isFinite(feature[key]))); + if (!value || !Array.isArray(value.featureOrder) + || !featureIsValid + || !Array.isArray(value.charts) + || !Array.isArray(value.best) + || typeof value.scoreCount !== 'number' + || typeof value.chartCount !== 'number') { + throw new Error('Unexpected rating response'); + } + return value as RatingRadarResponse; + } finally { + window.clearTimeout(timeout); + } +} + +export function useUserRating(username: string | null | undefined) { + return useSWR( + username ? [endpoints.maiscore.rating(username), username] : null, + fetchRating, + { + keepPreviousData: false, + revalidateOnFocus: false, + revalidateOnReconnect: false, + shouldRetryOnError: false, + }, + ); +} \ No newline at end of file diff --git a/src/locales/en.json b/src/locales/en.json index 372ea74..c55e80a 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -467,11 +467,21 @@ }, "space/SpacePage": { "BackToHome": "Back to Home", + "Best50": "Best 50", + "Best50Empty": "No scores yet", + "Collapse": "Collapse", "Comments": "Comments", "Error": "Error", + "Expand": "Expand", "JoinAt": "Joined {{date}}", "NoComments": "No comments yet", + "Rating": "Rating Radar", + "RatingCharts": "{{count}} charts averaged", + "RatingEmpty": "No scores are available for a rating yet", + "RatingFailed": "Failed to load the rating", + "RatingFormula": "B50 takes the top 50 unique levels by \"constant × acc/101\" (over 5 likes, no Utage, acc >= 97) and averages each radar feature weighted by acc/101. The result is for reference only.", "RecentlyPlayedCharts": "Recently Played Charts", + "Retry": "Retry", "SelfIntro": "Self-Intro", "ServerError": "Server Error", "UploadedCharts": "Uploaded Charts", diff --git a/src/locales/ja.json b/src/locales/ja.json index 047713c..6560d03 100644 --- a/src/locales/ja.json +++ b/src/locales/ja.json @@ -457,11 +457,21 @@ }, "space/SpacePage": { "BackToHome": "ホームに戻る", + "Best50": "Best 50", + "Best50Empty": "まだスコアがありません", + "Collapse": "折りたたむ", "Comments": "投稿したコメント", "Error": "エラー", + "Expand": "展開", "JoinAt": "登録日:{{date}}", "NoComments": "まだコメントを投稿していません", + "Rating": "レーティングレーダー", + "RatingCharts": "{{count}} 譜面を平均", + "RatingEmpty": "レーティングに使えるスコアがまだありません", + "RatingFailed": "レーティングの読み込みに失敗しました", + "RatingFormula": "B50 は「定数 × 達成率/101」で上位 50 難度(いいね 5 超・宴譜面除外・達成率 97 以上)を選び、各レーダー値を達成率/101 で加重平均します。この値は参考値です。", "RecentlyPlayedCharts": "最近プレイした譜面", + "Retry": "再試行", "SelfIntro": "自己紹介", "ServerError": "閉店中", "UploadedCharts": "アップロードされた譜面", diff --git a/src/locales/ko.json b/src/locales/ko.json index 8bcbaa7..2d2deae 100644 --- a/src/locales/ko.json +++ b/src/locales/ko.json @@ -457,11 +457,21 @@ }, "space/SpacePage": { "BackToHome": "홈으로 돌아가기", + "Best50": "Best 50", + "Best50Empty": "아직 기록이 없습니다", + "Collapse": "접기", "Comments": "작성한 댓글", "Error": "오류", + "Expand": "펼치기", "JoinAt": "가입일: {{date}}", "NoComments": "아직 작성한 댓글이 없습니다", + "Rating": "레이팅 레이더", + "RatingCharts": "{{count}}개 채보 평균", + "RatingEmpty": "레이팅에 사용할 기록이 아직 없습니다", + "RatingFailed": "레이팅을 불러오지 못했습니다", + "RatingFormula": "B50은 \"상수 × 달성률/101\"로 상위 50개 난이도(좋아요 5 초과, 연주 악보 제외, 달성률 97 이상)를 뽑고, 각 레이더 값을 달성률/101로 가중 평균합니다. 결과는 참고용입니다.", "RecentlyPlayedCharts": "최근 플레이한 채보", + "Retry": "다시 시도", "SelfIntro": "자기소개", "ServerError": "서버 오류", "UploadedCharts": "업로드한 채보", diff --git a/src/locales/zh.json b/src/locales/zh.json index e68ae9a..b7df5f8 100644 --- a/src/locales/zh.json +++ b/src/locales/zh.json @@ -457,11 +457,21 @@ }, "space/SpacePage": { "BackToHome": "返回首页", + "Best50": "Best 50", + "Best50Empty": "还没有成绩", + "Collapse": "收起", "Comments": "发表的评论", "Error": "错误", + "Expand": "展开", "JoinAt": "注册于 {{date}}", "NoComments": "还没有发表过评论", + "Rating": "评分雷达", + "RatingCharts": "{{count}} 张谱面参与计算", + "RatingEmpty": "还没有可用于计算 rating 的成绩", + "RatingFailed": "Rating 加载失败", + "RatingFormula": "B50 按「定数 × 达成率/101」取前 50 个不重复难度(点赞 > 5、非宴谱、acc >=97),各雷达特征再按达成率/101 加权平均。算法仅供参考。", "RecentlyPlayedCharts": "最近游玩的谱面", + "Retry": "重试", "SelfIntro": "自我介绍", "ServerError": "已闭店", "UploadedCharts": "上传的谱面", diff --git a/src/pages/SpacePage.tsx b/src/pages/SpacePage.tsx index c4b4220..9063e2a 100644 --- a/src/pages/SpacePage.tsx +++ b/src/pages/SpacePage.tsx @@ -9,6 +9,8 @@ import { useState } from 'react'; import { Link, useSearchParams } from 'react-router-dom'; import useSWR from 'swr'; import { PageLayout, RecentPlayedWidget, SongList, ScoreCount, LoadingSpinner, CommentListView } from '@/components'; +import CollapsibleSection from '@/components/ui/CollapsibleSection'; +import UserRating from '@/components/user/UserRating'; import { endpoints } from '@/config/api'; import Markdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; @@ -73,70 +75,30 @@ export default function SpacePage() { + {/* Rating radar and its best 50 */} + + + + {/* Recent Activity */} {hasRecentPlayed !== false && ( - -

- {t("space/SpacePage.RecentlyPlayedCharts")} -

-
+ - + )} {/* Uploaded Charts */} {hasUploadedCharts !== false && ( - -

- {t("space/SpacePage.UploadedCharts")} -

-
+ - + )} {/* Comments */} - -

- {t("space/SpacePage.Comments")} -

-
+
- +
{/* Who Loves To Play */} {hasUploadedCharts === true && ( - -

- {t("space/SpacePage.WhoLovesToPlay")} -

-
+ - + )} ); @@ -253,4 +200,4 @@ function Introduction({ username }: { username: string }) { )}
); -} +} \ No newline at end of file diff --git a/src/types/radar.ts b/src/types/radar.ts index 1f4c150..df98ad5 100644 --- a/src/types/radar.ts +++ b/src/types/radar.ts @@ -4,3 +4,21 @@ export interface ChartRadarResponse { featureOrder: string[]; feature: Record; } + +import type { Score } from './score'; + +/** GET /api/maiscore/rating/by-username/{username} 的响应。 */ +export interface RatingRadarResponse { + /** 七个特征名,顺序与 feature 的插入顺序一致。 */ + featureOrder: string[]; + /** 各特征按 DX 达成率/101 加权后的平均值;没有可计算数据时为空对象。 */ + feature: Record; + /** 实际参与平均的谱面 Id,按参与顺序;同一谱面的不同难度会出现多次。 */ + charts: string[]; + /** 同一批「谱面 + 难度」的成绩,结构与 GET api/account/scores 的元素相同。 */ + best: Score[]; + /** 参与的前 50 个「谱面 + 难度」数。 */ + scoreCount: number; + /** 实际参与平均的谱面数,雷达分析失败时小于 scoreCount。 */ + chartCount: number; +} \ No newline at end of file diff --git a/test/components/ui/CollapsibleSection.test.tsx b/test/components/ui/CollapsibleSection.test.tsx new file mode 100644 index 0000000..29f5d2b --- /dev/null +++ b/test/components/ui/CollapsibleSection.test.tsx @@ -0,0 +1,60 @@ +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import CollapsibleSection from '@/components/ui/CollapsibleSection'; + +(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +describe('collapsible section', () => { + let container: HTMLDivElement; + let root: Root; + + beforeEach(() => { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + }); + + afterEach(() => { + act(() => root.unmount()); + container.remove(); + }); + + async function render(defaultOpen?: boolean) { + await act(async () => root.render( + +

section content

+
, + )); + } + + it('starts expanded and folds the content away on click', async () => { + await render(); + const button = container.querySelector('button')!; + expect(button.getAttribute('aria-expanded')).toBe('true'); + expect(container.textContent).toContain('section content'); + + await act(async () => button.click()); + + expect(button.getAttribute('aria-expanded')).toBe('false'); + expect(container.textContent).not.toContain('section content'); + expect(container.textContent).toContain('最近游玩的谱面'); + }); + + it('unfolds again on the second click', async () => { + await render(); + const button = container.querySelector('button')!; + await act(async () => button.click()); + await act(async () => button.click()); + + expect(button.getAttribute('aria-expanded')).toBe('true'); + expect(container.textContent).toContain('section content'); + }); + + it('can start collapsed', async () => { + await render(false); + + expect(container.querySelector('button')!.getAttribute('aria-expanded')).toBe('false'); + expect(container.textContent).not.toContain('section content'); + }); +}); \ No newline at end of file diff --git a/test/components/user/UserRating.test.tsx b/test/components/user/UserRating.test.tsx new file mode 100644 index 0000000..a9ebebc --- /dev/null +++ b/test/components/user/UserRating.test.tsx @@ -0,0 +1,97 @@ +import { act, type ReactNode } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { MemoryRouter } from 'react-router-dom'; +import { SWRConfig } from 'swr'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import UserRating from '@/components/user/UserRating'; + +(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const featureOrder = ['note', 'peak', 'sweep', 'slide_tricky', 'slide_sequence', 'jack', 'fitted_constant']; + +function rating() { + return { + featureOrder, + feature: { note: 100.2, peak: 90.1, sweep: 80.3, slide_tricky: 70.4, slide_sequence: 60.5, jack: 50.6, fitted_constant: 13.5 }, + charts: ['chart-a'], + best: [{ + acc: { dx: 100.5123, classic: 99.1 }, + dxScore: 1200, + comboState: 2, + chartLevel: 4, + hash: 'chart-hash', + levelHash: 'a'.repeat(64), + chartInfo: { + id: 'chart-a', title: 'Song A', artist: 'Artist A', designer: 'Designer A', description: '', + levels: ['', '', '', '', '14+', '', ''], uploader: 'uploader', timestamp: '2026-01-01', + hash: 'chart-hash', tags: [], publicTags: [], + }, + timestamp: '2026-01-01T00:00:00Z', + }], + scoreCount: 1, + chartCount: 1, + }; +} + +const jsonResponse = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status }); + +describe('rating on the profile page', () => { + let container: HTMLDivElement; + let root: Root; + let fetchMock: ReturnType>; + let cache: Map; + + beforeEach(() => { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + cache = new Map(); + fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + }); + + afterEach(() => { + act(() => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); + }); + + async function render(children: ReactNode = ) { + await act(async () => root.render( + cache }}> + {children} + , + )); + } + + it('draws the radar and lists the averaged chart levels', async () => { + fetchMock.mockResolvedValue(jsonResponse(rating())); + await render(); + + expect(fetchMock).toHaveBeenCalledWith('/api3/api/maiscore/rating/by-username/bbben', expect.anything()); + expect(container.querySelector('svg')?.textContent).toContain('拟合定数'); + expect(container.textContent).toContain('1 张谱面参与计算'); + expect(container.textContent).toContain('Best 50'); + expect(container.textContent).toContain('Song A'); + expect(container.textContent).toContain('14+'); + expect(container.textContent).toContain('100.5123'); + }); + + it('shows an empty notice when no chart could be averaged', async () => { + fetchMock.mockResolvedValue(jsonResponse({ ...rating(), feature: {}, charts: [], best: [], scoreCount: 0, chartCount: 0 })); + await render(); + + expect(container.textContent).toContain('还没有可用于计算 rating 的成绩'); + }); + + it('reports a failed rating and retries on demand', async () => { + fetchMock.mockResolvedValue(jsonResponse({}, 500)); + await render(); + + expect(container.textContent).toContain('Rating 加载失败'); + const retry = Array.from(container.querySelectorAll('button')).find(button => button.textContent === '重试')!; + fetchMock.mockResolvedValue(jsonResponse(rating())); + await act(async () => retry.click()); + expect(container.textContent).toContain('Song A'); + }); +}); \ No newline at end of file