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
83 changes: 83 additions & 0 deletions src/components/chart/RadarPlot.tsx
Original file line number Diff line number Diff line change
@@ -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<Record<RadarAxis | 'fitted_constant', number | null>>;
}

// 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 (
<svg
viewBox="0 0 320 360"
className="block w-full overflow-visible text-white/90"
role="img"
aria-label={`${labels.map((label, i) => `${label}: ${values[i] ?? '—'}`).join(', ')}; ${estiLabel}: ${esti?.toFixed(2) ?? '—'}`}
>
{complete && (
<motion.polygon
initial={reduceMotion ? false : { points: Array(6).fill(`${RADAR_CENTER_X},${RADAR_CENTER_Y}`).join(' ') }}
animate={{ points, fill: color.fill, stroke: color.stroke }}
transition={{ duration: reduceMotion ? 0 : 0.5, ease: [0.215, 0.61, 0.355, 1] }}
fillOpacity={0.7843}
strokeWidth="2"
strokeLinejoin="round"
/>
)}
<image
href={radarBackground}
x={RADAR_CENTER_X - REFERENCE_RADIUS}
y={RADAR_CENTER_Y - REFERENCE_RADIUS}
width={REFERENCE_RADIUS * 2}
height={REFERENCE_RADIUS * 2}
className="invert opacity-85"
/>
{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 (
<g key={axis.key} textAnchor="middle" fill="currentColor" stroke="rgb(0 0 0 / 55%)" strokeWidth="2" paintOrder="stroke" strokeLinejoin="round">
<text x={x} y={y - 2} fontSize="15" fontWeight="600">{labels[i]}</text>
<text x={x} y={y + 14} fontSize="14" className="tabular-nums">{values[i]?.toFixed(0) ?? '—'}</text>
</g>
);
})}
<text x={RADAR_CENTER_X} y={RADAR_CENTER_Y + 4} textAnchor="middle" fontSize="26" fontWeight="600" fill="currentColor" stroke="rgb(0 0 0 / 35%)" strokeWidth="3" paintOrder="stroke" className="tabular-nums">
{esti?.toFixed(2) ?? '—'}
</text>
<text x={RADAR_CENTER_X} y={RADAR_CENTER_Y + 24} textAnchor="middle" fontSize="13" fill="currentColor">{estiLabel}</text>
</svg>
);
}
2 changes: 2 additions & 0 deletions src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';
Expand Down
78 changes: 3 additions & 75 deletions src/components/song/ChartRadar.tsx
Original file line number Diff line number Diff line change
@@ -1,86 +1,14 @@
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;
hash: string;
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 (
<svg
viewBox="0 0 320 360"
className="block w-full overflow-visible text-white/90"
role="img"
aria-label={`${labels.map((label, i) => `${label}: ${values[i] ?? '—'}`).join(', ')}; ${estiLabel}: ${esti?.toFixed(2) ?? '—'}`}
>
{complete && (
<motion.polygon
initial={reduceMotion ? false : { points: Array(6).fill(`${RADAR_CENTER_X},${RADAR_CENTER_Y}`).join(' ') }}
animate={{ points, fill: color.fill, stroke: color.stroke }}
transition={{ duration: reduceMotion ? 0 : 0.5, ease: [0.215, 0.61, 0.355, 1] }}
fillOpacity={0.7843}
strokeWidth="2"
strokeLinejoin="round"
/>
)}
<image
href={radarBackground}
x={RADAR_CENTER_X - REFERENCE_RADIUS}
y={RADAR_CENTER_Y - REFERENCE_RADIUS}
width={REFERENCE_RADIUS * 2}
height={REFERENCE_RADIUS * 2}
className="invert opacity-85"
/>
{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 (
<g key={axis.key} textAnchor="middle" fill="currentColor" stroke="rgb(0 0 0 / 55%)" strokeWidth="2" paintOrder="stroke" strokeLinejoin="round">
<text x={x} y={y - 2} fontSize="15" fontWeight="600">{labels[i]}</text>
<text x={x} y={y + 14} fontSize="14" className="tabular-nums">{values[i]?.toFixed(0) ?? '—'}</text>
</g>
);
})}
<text x={RADAR_CENTER_X} y={RADAR_CENTER_Y + 4} textAnchor="middle" fontSize="26" fontWeight="600" fill="currentColor" stroke="rgb(0 0 0 / 35%)" strokeWidth="3" paintOrder="stroke" className="tabular-nums">
{esti?.toFixed(2) ?? '—'}
</text>
<text x={RADAR_CENTER_X} y={RADAR_CENTER_Y + 24} textAnchor="middle" fontSize="13" fill="currentColor">{estiLabel}</text>
</svg>
);
}

export default function ChartRadar({ id, hash, chartLevel }: ChartRadarProps) {
const { t } = useTranslation();
const titleId = useId();
Expand All @@ -104,9 +32,9 @@ export default function ChartRadar({ id, hash, chartLevel }: ChartRadarProps) {
</div>
) : data ? (
<div className="rounded-xl">
<RadarPlot data={data} />
<RadarPlot feature={data.feature} />
</div>
) : null}
</section>
);
}
}
49 changes: 49 additions & 0 deletions src/components/ui/CollapsibleSection.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<section className={className ?? 'mb-12'}>
<h2 className="my-6 sm:my-8 font-semibold text-white text-2xl sm:text-3xl text-center [text-shadow:0_2px_4px_rgb(0_0_0/30%)]">
<button
type="button"
aria-expanded={open}
aria-controls={contentId}
onClick={() => setOpen(value => !value)}
className="group inline-flex flex-wrap justify-center items-center gap-2 hover:text-white/85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-400/70 rounded-lg transition-colors cursor-pointer"
>
<span>{title}</span>
<IoChevronDownOutline
aria-hidden="true"
className={`opacity-70 group-hover:opacity-100 transition-transform duration-200 ${open ? '' : '-rotate-90'}`}
/>
<span className="sr-only">{open ? t('space/SpacePage.Collapse') : t('space/SpacePage.Expand')}</span>
</button>
</h2>
<div
className="relative mx-auto my-8 border-0 w-[70%] h-px"
style={{
background: 'linear-gradient(90deg, transparent 0%, rgb(255 255 255 / 20%) 15%, rgb(255 255 255 / 40%) 30%, rgb(255 255 255 / 60%) 50%, rgb(255 255 255 / 40%) 70%, rgb(255 255 255 / 20%) 85%, transparent 100%)'
}}
/>
{open && <div id={contentId}>{children}</div>}
</section>
);
}
74 changes: 74 additions & 0 deletions src/components/user/BestScores.tsx
Original file line number Diff line number Diff line change
@@ -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<string, string> = {
'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 <p className="py-8 text-center text-white/50 text-sm">{t('space/SpacePage.Best50Empty')}</p>;
}

return (
<ol className="space-y-1.5 m-0 p-0 list-none">
{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 (
<li key={`${chart?.id ?? score.hash}-${score.chartLevel}-${index}`}>
<Link
to={chart?.id ? `/song?id=${chart.id}` : '/song'}
className="flex items-center gap-2 sm:gap-3 bg-white/5 hover:bg-white/10 px-2 sm:px-3 py-1.5 border border-white/8 rounded-lg transition-colors min-w-0"
>
<span className="w-6 shrink-0 text-right text-white/40 text-xs tabular-nums">{index + 1}</span>
{chart?.id && (
<img
src={endpoints.maichart.image(chart.id)}
alt=""
loading="lazy"
// The CDN rejects a localhost referer; the cover needs no referer at all.
referrerPolicy="no-referrer"
className="rounded w-9 h-9 shrink-0 object-cover"
/>
)}
<div className="flex-1 min-w-0">
<p className="m-0 font-medium text-white text-sm truncate">{chart?.title ?? ''}</p>
<p className="m-0 text-white/45 text-xs truncate">
{[chart?.artist, chart?.designer].filter(Boolean).join(' · ')}
</p>
</div>
{difficulty && (
<span className="bg-white/10 px-1.5 py-0.5 rounded shrink-0 font-semibold text-white/80 text-xs">{difficulty}</span>
)}
{comboText && (
<span className={`px-1.5 py-0.5 rounded shrink-0 font-bold text-[0.65rem] leading-none ${COMBO_CLASS[comboText] ?? 'bg-white/10 text-white/80'}`}>
{comboText}
</span>
)}
<span className="shrink-0 font-semibold text-purple-300 text-sm tabular-nums">{score.acc.dx.toFixed(4)}</span>
</Link>
</li>
);
})}
</ol>
);
}
69 changes: 69 additions & 0 deletions src/components/user/UserRating.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="flex flex-col justify-center items-center gap-3 py-10 text-center" aria-live="polite">
<p role="alert" className="text-white/70">{message}</p>
<button
type="button"
disabled={isValidating}
onClick={() => { void mutate().catch(() => {}); }}
className="bg-white/10 hover:bg-white/20 px-4 py-2 rounded-lg disabled:opacity-50"
>
{t('space/SpacePage.Retry')}
</button>
</div>
);
}

if (isLoading) {
return (
<div className="flex justify-center items-center py-12">
<LoadingSpinner size={40} />
</div>
);
}

if (!data || data.chartCount === 0 || data.best.length === 0) {
return <p className="py-8 text-center text-white/50 text-sm">{t('space/SpacePage.RatingEmpty')}</p>;
}

return (
<div className="justify-center items-start gap-5 grid grid-cols-1 lg:grid-cols-[minmax(0,22rem)_minmax(0,1fr)] mx-auto w-full md:w-[92%] lg:w-[86%]">
<section
aria-label={t('space/SpacePage.Rating')}
className="mx-auto w-full max-w-[17rem] sm:max-w-[20rem] lg:max-w-none bg-white/8 shadow-[0_4px_15px_rgb(0_0_0/0.2)] backdrop-blur-[10px] p-3 sm:p-4 border border-white/10 rounded-2xl min-w-0"
>
<RadarPlot feature={data.feature} />
<p className="m-0 text-center text-white/50 text-xs">
{t('space/SpacePage.RatingCharts', { count: data.chartCount })}
</p>
<p className="m-0 mt-2 text-center text-white/40 text-[0.7rem] leading-relaxed">
{t('space/SpacePage.RatingFormula')}
</p>
</section>
<section aria-label={t('space/SpacePage.Best50')} className="min-w-0">
<h3 className="m-0 mb-3 font-bold text-white text-sm">{t('space/SpacePage.Best50')}</h3>
<BestScores scores={data.best} />
</section>
</div>
);
}
Loading
Loading