feat: enhance auction interactions and player statistics UI

This commit is contained in:
dahyeon committed 2026-11-11 20:06:22 +09:00
1 parent 6c582ba3cf
commit be4de61bb7
115 files changed
+13292 -2871

No files matched your search

@@ -0,0 +1,497 @@
import { useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Badge } from "@astryxdesign/core/Badge";
import { Button } from "@astryxdesign/core/Button";
import {
ChatComposer,
ChatMessage,
ChatMessageBubble,
ChatMessageList,
ChatMessageMetadata,
} from "@astryxdesign/core/Chat";
import { StatusDot } from "@astryxdesign/core/StatusDot";
import { ArrowDown, RotateCcw, SendHorizontal } from "lucide-react";
import type { ApiAuctionChatMessage } from "../api/types";
import type { useAuctionSocket } from "../api/useAuctionSocket";
import type { AuctionReactionKind } from '@lolympus/contracts';
import { AuctionReactionPicker } from './AuctionReactionPicker';
import './auction-reactions.css';
import "./auction-chat.css";
type OutgoingMessage = ApiAuctionChatMessage & {
clientMessageId: string;
status: "sending" | "error";
error?: string;
};
type Props = {
messages: ApiAuctionChatMessage[];
connectionStatus: ReturnType<typeof useAuctionSocket>["connectionStatus"];
senderLabel: string;
currentUserId?: string;
isOperator?: boolean;
teams: readonly { captainUserId: string; teamIndex: number }[];
onSend: (
message: string,
clientMessageId: string,
) => Promise<ApiAuctionChatMessage>;
onReact: (kind: AuctionReactionKind) => Promise<void>;
className?: string;
};
const timeFormatter = new Intl.DateTimeFormat("ko-KR", {
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
function resizeInput(input: HTMLTextAreaElement) {
input.style.height = "auto";
const maxHeight = Number.parseFloat(getComputedStyle(input).maxHeight);
input.style.height = `${Math.min(input.scrollHeight, maxHeight)}px`;
}
export function AuctionChatPanel({
messages,
connectionStatus,
senderLabel,
currentUserId,
isOperator,
teams,
onSend,
onReact,
className = "",
}: Props) {
const titleId = useId();
const hintId = useId();
const [draft, setDraft] = useState("");
const [outbox, setOutbox] = useState<OutgoingMessage[]>([]);
const [hasNewMessages, setHasNewMessages] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const pinnedRef = useRef(true);
const lastMessageIdRef = useRef<string | undefined>(undefined);
const anchorRef = useRef<{ id: string; offset: number } | null>(null);
const sendingRef = useRef(new Set<string>());
const [ownRequestIds, setOwnRequestIds] = useState(new Set<string>());
const connected = connectionStatus === "connected";
const canSend = connected && draft.trim().length > 0 && draft.length <= 300;
const status = connected
? "연결됨"
: connectionStatus === "connecting" || connectionStatus === "idle"
? "연결 중"
: "연결 끊김";
const captainTeams = useMemo(
() => new Map(teams.map((team) => [team.captainUserId, team.teamIndex])),
[teams],
);
const ownTeam = currentUserId ? captainTeams.get(currentUserId) : undefined;
const ownRole = isOperator
? "운영진"
: ownTeam !== undefined
? `${ownTeam}팀 팀장`
: undefined;
const confirmedRequests = new Set(
messages.map((message) => message.clientMessageId),
);
const visibleMessages = [
...messages,
...outbox.filter(
(message) => !confirmedRequests.has(message.clientMessageId),
),
].sort((a, b) => Date.parse(a.sentAt) - Date.parse(b.sentAt));
const groups: (ApiAuctionChatMessage | OutgoingMessage)[][] = [];
for (const message of visibleMessages) {
const previousGroup = groups.at(-1);
const previous = previousGroup?.at(-1);
const sameAuthor =
previous &&
(message.userId
? previous.userId === message.userId
: !previous.userId && previous.displayName === message.displayName);
if (
previous &&
sameAuthor &&
previous.senderRole === message.senderRole &&
!("status" in previous) &&
!("status" in message) &&
Date.parse(message.sentAt) - Date.parse(previous.sentAt) < 5 * 60_000 &&
new Date(message.sentAt).toDateString() ===
new Date(previous.sentAt).toDateString()
) {
previousGroup!.push(message);
} else groups.push([message]);
}
function rememberScroll() {
const container = scrollRef.current;
if (!container) return;
pinnedRef.current =
container.scrollHeight - container.scrollTop - container.clientHeight <
40;
if (pinnedRef.current) setHasNewMessages(false);
const top = container.getBoundingClientRect().top;
const anchor = Array.from(
container.querySelectorAll<HTMLElement>("[data-chat-message-id]"),
).find((element) => element.getBoundingClientRect().bottom > top);
anchorRef.current = anchor
? {
id: anchor.dataset.chatMessageId!,
offset: anchor.getBoundingClientRect().top - top,
}
: null;
}
function scrollToLatest() {
const container = scrollRef.current;
if (container) container.scrollTop = container.scrollHeight;
pinnedRef.current = true;
setHasNewMessages(false);
}
// Track actual message IDs, including when the server's 200-message window
// rolls over without changing the list length. Preserve the visible anchor.
const latestId = visibleMessages.at(-1)?.id;
useLayoutEffect(() => {
const container = scrollRef.current;
if (!container) return;
const isNew = latestId !== lastMessageIdRef.current;
lastMessageIdRef.current = latestId;
if (pinnedRef.current) container.scrollTop = container.scrollHeight;
else if (anchorRef.current) {
const anchor = Array.from(
container.querySelectorAll<HTMLElement>("[data-chat-message-id]"),
).find(
(element) => element.dataset.chatMessageId === anchorRef.current?.id,
);
if (anchor)
container.scrollTop +=
anchor.getBoundingClientRect().top -
container.getBoundingClientRect().top -
anchorRef.current.offset;
}
const frame = requestAnimationFrame(() => {
if (pinnedRef.current) setHasNewMessages(false);
else if (isNew) setHasNewMessages(true);
// A broadcast can arrive even if its acknowledgement is lost. Retire
// confirmed drafts now so they cannot reappear after history rolls over.
const confirmed = new Set(
messages.map((message) => message.clientMessageId),
);
setOutbox((current) => {
const remaining = current.filter(
(message) => !confirmed.has(message.clientMessageId),
);
return remaining.length === current.length ? current : remaining;
});
});
return () => cancelAnimationFrame(frame);
}, [messages, outbox, latestId]);
useLayoutEffect(() => {
const input = textareaRef.current;
if (!input) return;
resizeInput(input);
}, [draft]);
useLayoutEffect(() => {
let inputWidth = 0;
let frame = 0;
const observer = new ResizeObserver(() => {
// Defer writes to the next frame: resizing an observed input inside
// the observer callback causes ResizeObserver loop notifications.
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const input = textareaRef.current;
if (input && input.clientWidth !== inputWidth) {
inputWidth = input.clientWidth;
resizeInput(input);
}
const container = scrollRef.current;
if (container && pinnedRef.current)
container.scrollTop = container.scrollHeight;
});
});
if (scrollRef.current) observer.observe(scrollRef.current);
if (contentRef.current) observer.observe(contentRef.current);
if (textareaRef.current) observer.observe(textareaRef.current);
return () => {
observer.disconnect();
cancelAnimationFrame(frame);
};
}, []);
async function deliver(message: OutgoingMessage) {
if (sendingRef.current.has(message.clientMessageId)) return;
sendingRef.current.add(message.clientMessageId);
setOutbox((current) =>
current.map((entry) =>
entry.id === message.id
? { ...entry, status: "sending", error: undefined }
: entry,
),
);
try {
await onSend(message.message, message.clientMessageId);
setOutbox((current) =>
current.filter((entry) => entry.id !== message.id),
);
} catch (error) {
setOutbox((current) =>
current.map((entry) =>
entry.id === message.id
? {
...entry,
status: "error",
error:
error instanceof Error
? error.message
: "전송하지 못했습니다.",
}
: entry,
),
);
} finally {
sendingRef.current.delete(message.clientMessageId);
}
}
function submit(value = draft) {
if (!connected || !value.trim() || value.length > 300) return;
const clientMessageId = crypto.randomUUID();
const message: OutgoingMessage = {
id: clientMessageId,
clientMessageId,
userId: currentUserId,
displayName: senderLabel,
senderRole: isOperator ? "operator" : undefined,
message: value.trim(),
sentAt: new Date().toISOString(),
status: "sending",
};
setOwnRequestIds((current) => new Set([...current, clientMessageId]));
setOutbox((current) => [...current, message]);
setDraft("");
pinnedRef.current = true;
void deliver(message);
textareaRef.current?.focus();
}
return (
<section
className={`auction-chat-panel ${className}`}
aria-labelledby={titleId}
>
<header className="auction-chat-header">
<h2 id={titleId}>경매 채팅</h2>
<span className="auction-chat-connection" role="status">
<StatusDot
variant={connected ? "success" : "neutral"}
label={status}
aria-hidden="true"
/>
{status}
</span>
</header>
<div className="auction-chat-conversation">
<div
className="auction-chat-scroll"
ref={scrollRef}
onScroll={rememberScroll}
tabIndex={0}
aria-label="경매 대화 내역"
>
<ChatMessageList
ref={contentRef}
density="compact"
gap={3}
aria-label="경매 채팅 메시지"
emptyState={
<div className="auction-chat-empty">
아직 대화가 없습니다.
<br />
팀장과 운영진에게 메시지를 남겨 보세요.
</div>
}
>
{groups.map((group) => {
const first = group[0];
const last = group[group.length - 1];
const own = Boolean(
(currentUserId && first.userId === currentUserId) ||
(first.clientMessageId &&
ownRequestIds.has(first.clientMessageId)),
);
const team = first.userId
? captainTeams.get(first.userId)
: undefined;
const role =
first.senderRole === "operator"
? "운영진"
: team !== undefined
? `${team}팀 팀장`
: undefined;
const outgoing = "status" in last ? last : undefined;
return (
<ChatMessage
key={first.id}
sender={own ? "user" : "assistant"}
name={
<span className="auction-chat-author">
<span
className="auction-chat-name"
title={first.displayName}
>
{first.displayName}
</span>
{role && (
<Badge
variant={
first.senderRole === "operator"
? "purple"
: "neutral"
}
label={role}
/>
)}
{own && <span className="auction-chat-self">나</span>}
<time
dateTime={last.sentAt}
title={new Date(last.sentAt).toLocaleString("ko-KR")}
>
{timeFormatter.format(new Date(last.sentAt))}
</time>
</span>
}
metadata={
outgoing && (
<ChatMessageMetadata
timestamp={
<span
className="auction-chat-delivery"
data-failed={outgoing.status === "error"}
>
{outgoing.status === "sending" ? (
<span role="status">전송 중…</span>
) : (
<>
<span role="alert">{outgoing.error}</span>
<Button
label="다시 보내기"
variant="ghost"
size="sm"
isDisabled={!connected}
icon={
<RotateCcw size={14} aria-hidden="true" />
}
onClick={() => void deliver(outgoing)}
/>
</>
)}
</span>
}
/>
)
}
>
{group.map((message, index) => (
<ChatMessageBubble
key={message.id}
data-chat-message-id={message.id}
group={
group.length === 1
? undefined
: index === 0
? "first"
: index === group.length - 1
? "last"
: "middle"
}
>
{message.message}
</ChatMessageBubble>
))}
</ChatMessage>
);
})}
</ChatMessageList>
</div>
{hasNewMessages && (
<div className="auction-chat-new-messages">
<Button
label="새 메시지"
variant="secondary"
size="sm"
icon={<ArrowDown size={14} aria-hidden="true" />}
onClick={scrollToLatest}
/>
</div>
)}
</div>
<div className="auction-chat-compose-area">
<div className="auction-chat-sender">
<span title={senderLabel}>
{ownRole ? `${ownRole} · ` : ""}
{senderLabel}
</span>
{draft.length >= 240 && (
<span
className="auction-chat-count"
data-limit={draft.length === 300}
>
{draft.length}/300
</span>
)}
</div>
<ChatComposer
className="auction-chat-composer"
density="compact"
elevation="none"
value={draft}
onChange={setDraft}
onSubmit={submit}
input={
<textarea
ref={textareaRef}
value={draft}
rows={1}
maxLength={300}
aria-label="경매 채팅 메시지"
aria-describedby={hintId}
placeholder="메시지 입력"
enterKeyHint="send"
onChange={(event) => setDraft(event.target.value)}
onKeyDown={(event) => {
// Product choice: Enter always sends, including during composition.
// Shift+Enter retains the existing newline shortcut.
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
submit(event.currentTarget.value);
}
}}
/>
}
sendActions={<AuctionReactionPicker connected={connected} onReact={onReact} />}
sendButton={
<Button
className="auction-chat-send"
label="메시지 전송"
variant="primary"
size="md"
isIconOnly
isDisabled={!canSend}
onClick={() => submit()}
icon={<SendHorizontal size={18} aria-hidden="true" />}
/>
}
/>
<p className="auction-chat-hint" id={hintId}>
{connected
? "Enter 전송 · Shift+Enter 줄바꿈"
: "연결되면 전송할 수 있습니다. 작성 내용은 유지됩니다."}
</p>
</div>
</section>
);
}
@@ -0,0 +1,59 @@
import type { CSSProperties } from "react";
import { createPortal } from "react-dom";
import {
AUCTION_REACTIONS,
type ActiveAuctionReaction,
} from "../api/auction-reactions";
import "./auction-reactions.css";
function reactionStyle(id: string): CSSProperties {
let hash = 0;
for (const character of id)
hash = (hash * 31 + character.charCodeAt(0)) >>> 0;
return {
"--reaction-left": `${8 + (hash % 78)}%`,
"--reaction-drift": `${(hash % 65) - 32}px`,
"--reaction-tilt": `${(hash % 21) - 10}deg`,
} as CSSProperties;
}
export function AuctionReactionLayer({
reactions,
}: {
reactions: ActiveAuctionReaction[];
}) {
if (typeof document === "undefined") return null;
const latest = reactions.at(-1);
return createPortal(
<>
<div className="auction-reaction-layer" aria-hidden="true">
{reactions.map((reaction) => (
<div
key={reaction.id}
className="auction-floating-reaction"
data-reaction-id={reaction.id}
style={reactionStyle(reaction.id)}
>
<span className="auction-floating-emoji">
{AUCTION_REACTIONS[reaction.kind].emoji}
</span>
<span className="auction-floating-name">
{reaction.displayName}
</span>
</div>
))}
</div>
<span
className="sr-only"
role="status"
aria-live="polite"
aria-atomic="true"
>
{latest
? `${latest.displayName}님의 ${AUCTION_REACTIONS[latest.kind].label} 반응`
: ""}
</span>
</>,
document.body,
);
}
@@ -0,0 +1,109 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Button } from "@astryxdesign/core/Button";
import { Popover } from "@astryxdesign/core/Popover";
import { Smile } from "lucide-react";
import type { AuctionReactionKind } from "@lolympus/contracts";
import { AUCTION_REACTIONS } from "../api/auction-reactions";
export function AuctionReactionPicker({
connected,
onReact,
}: {
connected: boolean;
onReact: (kind: AuctionReactionKind) => Promise<void>;
}) {
const [isOpen, setIsOpen] = useState(false);
const [coolingDown, setCoolingDown] = useState(false);
const [error, setError] = useState<string | null>(null);
const coolingDownRef = useRef(false);
const requestSequence = useRef(0);
useEffect(() => {
if (!coolingDown) return;
const timer = setTimeout(() => {
coolingDownRef.current = false;
setCoolingDown(false);
}, 450);
return () => clearTimeout(timer);
}, [coolingDown]);
const handleReaction = useCallback(
async (kind: AuctionReactionKind) => {
if (!connected || coolingDownRef.current) return;
coolingDownRef.current = true;
const sequence = ++requestSequence.current;
setCoolingDown(true);
setError(null);
try {
await onReact(kind);
} catch (cause) {
if (sequence === requestSequence.current) {
setError(
cause instanceof Error
? cause.message
: "반응을 보내지 못했습니다.",
);
}
}
},
[connected, onReact],
);
return (
<Popover
label="이모지 반응"
closeButtonLabel="반응 선택 닫기"
placement="above"
alignment="end"
width={260}
isOpen={isOpen}
onOpenChange={setIsOpen}
content={
<div className="auction-reaction-picker">
<p className="auction-reaction-picker-title">이모지 반응</p>
<p className="auction-reaction-picker-description">
선택하면 모두에게 보여요
</p>
<div
className="auction-reaction-options"
role="group"
aria-label="반응 선택"
>
{(
Object.entries(AUCTION_REACTIONS) as [
AuctionReactionKind,
{ emoji: string; label: string },
][]
).map(([kind, { emoji, label }]) => (
<Button
key={kind}
label={`${label} 반응 보내기`}
variant="ghost"
size="lg"
isIconOnly
isDisabled={!connected || coolingDown}
className="auction-reaction-option"
onClick={() => void handleReaction(kind)}
icon={<span aria-hidden="true">{emoji}</span>}
/>
))}
</div>
{(!connected || error) && (
<p className="auction-reaction-error" role="status">
{!connected ? "연결되면 반응을 보낼 수 있습니다." : error}
</p>
)}
</div>
}
>
<Button
label="이모지 반응"
variant="ghost"
size="md"
isIconOnly
className="auction-chat-reaction-trigger"
icon={<Smile size={20} aria-hidden="true" />}
/>
</Popover>
);
}
+133 -5
View File
@@ -11,11 +11,77 @@
border-radius: 1.25rem;
}
.lts-hall-player,
.lts-hall-portrait {
.lts-hall-team-name {
position: relative;
width: fit-content;
max-width: 100%;
color: var(--lts-gold);
filter: drop-shadow(0 0.5px 0 color-mix(in srgb, var(--lts-gold) 20%, transparent));
}
@supports (background-clip: text) or (-webkit-background-clip: text) {
.lts-hall-team-name {
background-image:
linear-gradient(
115deg,
transparent calc(50% - 9px),
color-mix(in srgb, var(--color-brand-gold) 45%, transparent) calc(50% - 5px),
color-mix(in srgb, var(--color-brand-gold) 18%, var(--color-palette-white)) 50%,
color-mix(in srgb, var(--color-brand-gold) 45%, transparent) calc(50% + 5px),
transparent calc(50% + 9px)
),
linear-gradient(
175deg,
var(--lts-gold) 0%,
color-mix(in srgb, var(--lts-gold) 45%, var(--color-brand-gold)) 28%,
var(--color-brand-gold) 39%,
color-mix(in srgb, var(--color-brand-gold) 65%, var(--color-palette-white)) 44%,
var(--lts-gold) 53%,
color-mix(in srgb, var(--lts-gold) 70%, var(--color-brand-gold)) 72%,
var(--color-brand-gold) 100%
);
background-size: 250% 100%, 100% 100%;
background-position: 100% 0, 0 0;
background-repeat: no-repeat;
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
}
.lts-hall-team-name::before,
.lts-hall-team-name::after {
content: '';
position: absolute;
pointer-events: none;
width: 7px;
height: 7px;
background: var(--color-brand-gold);
clip-path: polygon(50% 0, 62% 37%, 100% 50%, 62% 63%, 50% 100%, 38% 63%, 0 50%, 38% 37%);
opacity: 0;
transform: scale(0.4) rotate(-15deg);
}
.lts-hall-team-name::before {
top: -3px;
right: 22%;
}
.lts-hall-team-name::after {
top: 45%;
right: -5px;
width: 5px;
height: 5px;
}
.lts-hall-player {
border-radius: 0.75rem;
}
.lts-hall-portrait {
border-radius: 50%;
}
.lts-hall-pixel {
image-rendering: pixelated;
}
@@ -25,9 +91,69 @@
}
@media (prefers-reduced-motion: no-preference) {
.lts-hall[data-intro] .lts-hall-team-name {
animation: lts-hall-gold-shine 4s cubic-bezier(0.4, 0, 0.2, 1) infinite;
}
.lts-hall[data-intro] .lts-hall-team-name::before,
.lts-hall[data-intro] .lts-hall-team-name::after {
animation: lts-hall-gold-sparkle 4s ease-in-out infinite;
}
.lts-hall[data-intro] .lts-hall-team-name::after {
animation-delay: 120ms;
}
.lts-hall:not([data-motion-active]) .lts-hall-team-name,
.lts-hall:not([data-motion-active]) .lts-hall-team-name::before,
.lts-hall:not([data-motion-active]) .lts-hall-team-name::after {
animation-play-state: paused;
}
.lts-hall[data-intro] .lts-hall-portrait img {
animation: lts-hall-reveal 110ms linear
calc(180ms + var(--lts-hall-order) * 48ms) backwards;
animation: lts-hall-reveal 6s linear
calc(180ms + var(--lts-hall-order) * 48ms) infinite backwards;
}
}
@media (forced-colors: active) {
.lts-hall-team-name {
background: none;
color: CanvasText;
filter: none;
}
.lts-hall-team-name::before,
.lts-hall-team-name::after {
display: none;
}
}
@keyframes lts-hall-gold-shine {
0%,
5% {
background-position: 100% 0, 0 0;
}
/* Sweep from 0.2s to 0.85s, then leave the gold finish at rest. */
21.25%,
100% {
background-position: 0 0, 0 0;
}
}
@keyframes lts-hall-gold-sparkle {
0%,
16.25%,
23.25%,
100% {
opacity: 0;
transform: scale(0.4) rotate(-15deg);
}
19.5% {
opacity: 0.9;
transform: scale(1) rotate(15deg);
}
}
@@ -41,7 +167,9 @@
);
}
to {
/* Reveal for 110ms, then stay visible for the rest of the six-second cycle. */
1.833333%,
100% {
clip-path: polygon(
0 0,
calc(100% + var(--lts-hall-slant)) 0,
+53 -7
View File
@@ -7,7 +7,7 @@ import captainCrown from '../assets/captain-crown.svg';
import pixelTrophy from '../assets/pixel-trophy.svg';
import { profileIconUrl } from '../lib/ddragon';
import { positionLabel } from '../lib/league';
import { pageWidthClass } from '../ui/layout';
import { pageWidthClass, Skeleton } from '../ui';
import './HomeHallOfFame.css';
const POSITION_ORDER: MatchPosition[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
@@ -20,11 +20,13 @@ export default function HomeHallOfFame({
const hallOfFame = useHallOfFame();
const sectionRef = useRef<HTMLElement>(null);
const [playIntro, setPlayIntro] = useState(false);
const [isMotionActive, setIsMotionActive] = useState(false);
const isContentReady = introReady && hallOfFame.isSuccess;
useEffect(() => {
const section = sectionRef.current;
if (
!introReady ||
!isContentReady ||
!section ||
typeof IntersectionObserver === 'undefined' ||
window.matchMedia('(prefers-reduced-motion: reduce)').matches
@@ -32,15 +34,23 @@ export default function HomeHallOfFame({
return;
}
let isInView = false;
const updateMotion = () => setIsMotionActive(isInView && !document.hidden);
const observer = new IntersectionObserver(
([entry]) => {
if (entry?.isIntersecting) setPlayIntro(true);
isInView = entry?.isIntersecting ?? false;
if (isInView) setPlayIntro(true);
updateMotion();
},
{ threshold: 0.5 },
);
observer.observe(section);
return () => observer.disconnect();
}, [introReady]);
document.addEventListener('visibilitychange', updateMotion);
return () => {
observer.disconnect();
document.removeEventListener('visibilitychange', updateMotion);
};
}, [isContentReady]);
const featuredMatch = hallOfFame.data?.match;
@@ -50,11 +60,16 @@ export default function HomeHallOfFame({
<section
ref={sectionRef}
aria-label="명예의 전당"
aria-busy={hallOfFame.isPending}
className={`${pageWidthClass()} lts-hall grid gap-8 py-6 md:py-8 lg:grid-cols-[minmax(0,1fr)_20rem]`}
data-intro={playIntro ? '' : undefined}
data-motion-active={isMotionActive ? '' : undefined}
>
{hallOfFame.isPending ? (
<p role="status">명예의 전당을 불러오는 중</p>
<>
<span role="status" className="sr-only">명예의 전당을 불러오는 중</span>
<FeaturedTeamSkeleton />
</>
) : hallOfFame.isError ? (
<p role="status">
명예의 전당을 불러오지 못했습니다.{' '}
@@ -75,6 +90,37 @@ export default function HomeHallOfFame({
);
}
function FeaturedTeamSkeleton() {
return (
<div className="lts-hall-card flex min-w-0 flex-col gap-4 bg-card p-5 sm:flex-row sm:gap-5">
<div className="min-w-0 sm:w-36 sm:shrink-0">
<h2 className="text-sm font-semibold text-content-muted">명예의 전당</h2>
<div className="mt-2">
<Skeleton width="80%" height={30} />
</div>
<div className="mt-1">
<Skeleton width="90%" height={16} index={1} />
</div>
</div>
<div className="h-px bg-line sm:h-auto sm:w-px" aria-hidden="true" />
<div className="grid min-w-0 flex-1 gap-1 sm:grid-cols-5 sm:content-center sm:items-start" aria-hidden="true">
{POSITION_ORDER.map((position, index) => (
<div key={position} className="flex min-w-0 items-center gap-2.5 px-2 py-2 sm:flex-col sm:gap-2 sm:py-3">
<div className="size-10 shrink-0 sm:size-13">
<Skeleton radius="rounded" index={index} />
</div>
<div className="min-w-0 flex-1 space-y-1 sm:w-full sm:flex-none sm:[&>div]:mx-auto">
<Skeleton width={24} height={16} index={index} />
<Skeleton width="80%" height={16} index={index} />
<Skeleton width="50%" height={12} index={index} />
</div>
</div>
))}
</div>
</div>
);
}
function FeaturedTeam({
team,
match,
@@ -96,7 +142,7 @@ function FeaturedTeam({
>
명예의 전당
</span>
<span className="mt-2 block text-2xl leading-tight font-extrabold tracking-tight [overflow-wrap:anywhere]">
<span className="lts-hall-team-name mt-2 block text-2xl leading-tight font-extrabold tracking-tight [overflow-wrap:anywhere]">
{team.name}
</span>
<span className="mt-1 flex items-center gap-1 text-xs font-semibold text-content-muted">
@@ -0,0 +1,59 @@
import { UserRound } from "lucide-react";
import { useDdragonManifest } from "../api/hooks";
import captainCrown from "../assets/captain-crown.svg";
import { profileIconUrl } from "../lib/ddragon";
const AVATAR_SIZE = {
sm: "size-7",
md: "size-10",
} as const;
const CROWN_SIZE = {
sm: "-right-1 -top-1.5 w-4",
md: "-right-1.5 -top-2 w-5",
} as const;
/** The adjacent player name labels the portrait; only the captain role is read. */
export function SummonerAvatar({
profileIconId,
isCaptain = false,
size = "md",
shape = "rounded",
}: {
profileIconId?: number;
isCaptain?: boolean;
size?: keyof typeof AVATAR_SIZE;
shape?: "circle" | "rounded";
}) {
const { data: manifest } = useDdragonManifest();
const icon = profileIconUrl(manifest, profileIconId ?? 0);
return (
<span
className={`relative inline-flex shrink-0 ${AVATAR_SIZE[size]} ${isCaptain ? "z-10" : ""}`}
>
<span
className={`relative grid size-full place-items-center overflow-hidden bg-sunken-strong text-content-muted ring-2 ring-card ${shape === "circle" ? "rounded-full" : "rounded-[0.625rem]"}`}
>
<UserRound className={size === "sm" ? "size-4" : "size-5"} aria-hidden="true" />
<img
key={icon}
src={icon}
alt=""
className="absolute inset-0 size-full object-cover"
loading="lazy"
onError={(event) => {
event.currentTarget.hidden = true;
}}
/>
</span>
{isCaptain && (
<img
src={captainCrown}
alt="팀장"
className={`pointer-events-none absolute z-10 rotate-[14deg] [image-rendering:pixelated] ${CROWN_SIZE[size]}`}
/>
)}
</span>
);
}
+186
View File
@@ -0,0 +1,186 @@
.lts-app-header {
position: sticky;
top: calc(0px - var(--app-header-row-height));
z-index: 50;
flex-shrink: 0;
background: var(--color-background-body);
}
.lts-app-header-inner {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
grid-template-rows: var(--app-header-row-height) minmax(0, 1fr);
height: var(--app-header-height);
align-items: center;
column-gap: 16px;
max-width: 1320px;
margin-inline: auto;
padding-inline: 16px;
border-bottom: 1px solid var(--color-border);
}
.lts-header-brand {
grid-column: 1;
grid-row: 1;
display: flex;
min-width: 0;
width: fit-content;
max-width: 100%;
flex-direction: column;
color: var(--color-text-primary);
}
.lts-header-brand-name {
overflow: hidden;
font-size: 19px;
font-weight: 850;
line-height: 1.1;
letter-spacing: -0.7px;
text-overflow: ellipsis;
white-space: nowrap;
}
.lts-header-brand-tagline {
margin-top: 5px;
color: var(--color-text-secondary);
font-size: 7px;
font-weight: 750;
line-height: 1.1;
letter-spacing: 2.5px;
}
.lts-header-actions {
grid-column: 2;
grid-row: 1;
display: flex;
min-width: 0;
align-items: center;
justify-content: flex-end;
gap: 8px;
}
.lts-header-icon-button {
display: grid;
width: 38px;
height: 38px;
flex-shrink: 0;
place-items: center;
border: 1px solid var(--color-border);
border-radius: 9px;
background: var(--color-background-card);
color: var(--color-text-secondary);
transition: background-color 150ms, color 150ms;
}
.lts-header-theme-toggle {
border-radius: 50%;
}
.lts-header-icon-button:hover {
background: var(--lts-sunken);
color: var(--color-text-primary);
}
.lts-primary-nav {
grid-column: 1 / -1;
grid-row: 2;
display: flex;
height: 100%;
align-items: stretch;
justify-content: center;
gap: clamp(20px, 5vw, 36px);
}
.lts-primary-nav-link {
position: relative;
display: inline-flex;
min-width: 36px;
align-items: center;
justify-content: center;
color: var(--color-text-secondary);
font-size: 13px;
font-weight: 650;
white-space: nowrap;
transition: color 150ms;
}
.lts-primary-nav-link:hover,
.lts-primary-nav-link[aria-current] {
color: var(--color-text-primary);
}
.lts-primary-nav-link[aria-current]::after {
position: absolute;
right: 0;
bottom: -1px;
left: 0;
height: 3px;
border-radius: 3px 3px 0 0;
background: var(--color-brand-coral);
content: "";
}
.lts-app-header :focus-visible {
outline: 2px solid var(--color-win);
outline-offset: 3px;
}
.lts-primary-nav-link:focus-visible {
outline-offset: -2px;
}
.lts-app-shell--without-nav {
--app-header-nav-height: 0px;
}
.lts-app-header--without-nav {
position: static;
}
.lts-app-header--without-nav .lts-app-header-inner {
height: 60px;
grid-template-rows: minmax(0, 1fr);
}
@media (width >= 48rem) {
.lts-app-header-inner {
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
grid-template-rows: minmax(0, 1fr);
column-gap: 24px;
padding-inline: 24px;
}
.lts-header-brand-name {
font-size: 22px;
}
.lts-header-brand-tagline {
margin-top: 6px;
font-size: 8px;
}
.lts-header-actions {
grid-column: 3;
}
.lts-primary-nav {
grid-column: 2;
grid-row: 1;
gap: 36px;
}
.lts-primary-nav-link {
min-width: 0;
font-size: 14px;
}
.lts-app-header--without-nav .lts-app-header-inner {
height: 74px;
}
}
@media (width >= 80rem) {
.lts-app-header-inner {
padding-inline: 40px;
}
}
+227
View File
@@ -0,0 +1,227 @@
.auction-chat-panel {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
overflow: hidden;
color: var(--color-text-primary);
background: var(--color-background-card);
border: 1px solid var(--color-border);
border-radius: var(--radius-container);
}
.auction-chat-panel .auction-chat-header {
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
gap: 12px;
padding: 12px 14px;
border-bottom: 1px solid var(--color-border);
}
.auction-chat-header h2 {
font-size: 14px;
font-weight: 700;
margin: 0;
}
.auction-chat-connection {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: var(--color-text-secondary);
}
.auction-chat-conversation {
position: relative;
display: flex;
flex: 1;
min-height: 0;
}
.auction-chat-scroll {
flex: 1;
min-width: 0;
overflow-y: auto;
overscroll-behavior: contain;
padding: 16px 12px;
scrollbar-gutter: stable;
}
.auction-chat-scroll > .astryx-chat-message-list {
min-height: 100%;
}
.auction-chat-empty {
margin: auto;
padding: 24px 8px;
text-align: center;
font-size: 13px;
line-height: 1.7;
color: var(--color-text-secondary);
}
.auction-chat-author {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 6px;
font-size: 12px;
line-height: 1.5;
}
.auction-chat-name {
max-width: 150px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 600;
}
.auction-chat-author time,
.auction-chat-self {
font-size: 11px;
font-weight: 400;
color: var(--lts-text-subtle);
}
.auction-chat-author .astryx-badge {
font-size: 10px;
padding-inline: 5px;
height: 18px;
}
.auction-chat-panel
.astryx-chat-message[data-sender="user"]
.auction-chat-author {
justify-content: flex-end;
}
.auction-chat-panel .astryx-chat-message-bubble {
padding: 8px 10px;
max-width: 100%;
font-size: 14px;
line-height: 1.6;
white-space: pre-wrap;
overflow-wrap: anywhere;
border-radius: 10px;
}
.auction-chat-panel
.astryx-chat-message[data-sender="assistant"]
.astryx-chat-message-bubble {
background: var(--color-background-muted);
color: var(--color-text-primary);
}
.auction-chat-panel
.astryx-chat-message[data-sender="user"]
.astryx-chat-message-bubble {
background: var(--color-accent-muted);
color: var(--color-text-primary);
}
.auction-chat-panel .astryx-chat-message > div {
max-width: 92%;
min-width: 0;
}
.auction-chat-delivery {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 4px;
font-size: 11px;
line-height: 1.5;
}
.auction-chat-delivery[data-failed="true"] {
color: var(--color-text-error);
}
.auction-chat-new-messages {
position: absolute;
bottom: 10px;
inset-inline: 0;
display: flex;
justify-content: center;
pointer-events: none;
}
.auction-chat-new-messages button {
pointer-events: auto;
box-shadow: 0 2px 8px var(--color-palette-shadow-light);
}
.auction-chat-compose-area {
flex-shrink: 0;
padding: 10px 12px;
border-top: 1px solid var(--color-border);
}
.auction-chat-sender {
display: flex;
justify-content: space-between;
gap: 8px;
margin-bottom: 6px;
color: var(--color-text-secondary);
font-size: 11px;
line-height: 1.5;
}
.auction-chat-sender > span:first-child {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.auction-chat-count {
flex-shrink: 0;
font-variant-numeric: tabular-nums;
}
.auction-chat-count[data-limit="true"] {
color: var(--color-text-error);
}
/* The Astryx composer keeps its focus/disabled shell; its input and footer
slots form one compact row for this sidebar's plain-text editor. */
.auction-chat-panel .auction-chat-composer > div {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: end;
gap: 6px;
padding: 5px;
border-radius: var(--radius-element);
background: var(--color-background-card);
}
.auction-chat-composer textarea {
display: block;
width: 100%;
min-height: 36px;
max-height: calc(4lh + 14px);
resize: none;
border: 0;
border-radius: 4px;
padding: 7px;
background: transparent;
color: var(--color-text-primary);
font: inherit;
font-size: 14px;
line-height: 22px;
outline: none;
}
.auction-chat-composer textarea::placeholder {
color: var(--lts-text-subtle);
}
.auction-chat-panel .auction-chat-send {
width: 36px;
height: 36px;
min-width: 36px;
border-radius: 8px;
}
.auction-chat-panel .auction-chat-send:disabled {
opacity: 1;
background: var(--color-background-muted);
color: var(--color-text-disabled);
cursor: not-allowed;
}
.auction-chat-hint {
margin: 6px 0 0;
color: var(--lts-text-subtle);
font-size: 10px;
line-height: 1.5;
}
@media (pointer: coarse), (max-width: 639px) {
.auction-chat-panel .auction-chat-send {
width: 44px;
height: 44px;
min-width: 44px;
}
.auction-chat-composer textarea {
min-height: 44px;
max-height: calc(4lh + 22px);
padding-block: 11px;
font-size: 16px;
}
}
@@ -0,0 +1,598 @@
import { useId, useState, type KeyboardEvent, type ReactNode } from "react";
import { Link } from "react-router";
import { ArrowUpRight } from "lucide-react";
import { Tooltip } from "@astryxdesign/core/Tooltip";
import type { AuctionPlayerView } from "../../api/mappers";
import type {
ApiRecentMatchView,
ApiTierInfo,
DdragonManifest,
} from "../../api/types";
import { DEFAULT_COMMUNITY_ID } from "../../config";
import {
championDisplayName,
championIconUrl,
profileIconUrl,
} from "../../lib/ddragon";
import { POSITION_ORDER, positionIcon, positionLabel } from "../../lib/league";
import { LANE_LABELS } from "../../lib/riot-history";
import { internalMatchGamePath } from "../../lib/internal-match-routes";
import { RankBadge } from "../RankBadge";
import { formatRankDetail } from "../rankBadgeUtils";
import {
metricLabel,
POSITION_LANES,
selectProfileGames,
summarizeProfileGames,
type PositionFilter,
type ProfileQueue,
} from "./stats";
import { useProfileHistory } from "./useProfileHistory";
import { useProfileManifest } from "./useProfileManifest";
import "./profile.css";
const POSITIONS: PositionFilter[] = ["ALL", ...POSITION_ORDER];
const QUEUES: ProfileQueue[] = ["internal", "solo"];
const queueName = (queue: ProfileQueue) =>
queue === "internal" ? "내전" : "솔로랭크";
const positionName = (position: PositionFilter) =>
position === "ALL" ? "전체" : positionLabel[position];
const dateLabel = (timestamp: number) =>
new Intl.DateTimeFormat("ko-KR", { month: "2-digit", day: "2-digit" })
.format(timestamp)
.replace(/\.$/, "");
type Summary = ReturnType<typeof summarizeProfileGames>;
type Manifest = DdragonManifest | undefined;
function moveTab<T extends string>(
event: KeyboardEvent<HTMLButtonElement>,
values: T[],
current: T,
select: (value: T) => void,
prefix: string,
) {
if (
event.altKey ||
event.ctrlKey ||
event.metaKey ||
!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)
)
return;
event.preventDefault();
const index = values.indexOf(current);
const next =
event.key === "Home"
? values[0]
: event.key === "End"
? values[values.length - 1]
: values[
(index + (event.key === "ArrowRight" ? 1 : -1) + values.length) %
values.length
];
select(next);
document.getElementById(`${prefix}-${next}`)?.focus();
}
function Portrait({
championId,
manifest,
}: {
championId: number;
manifest: Manifest;
}) {
const src = championIconUrl(manifest, championId);
return (
<span className="ap-champion-portrait">
{src && <img src={src} alt="" loading="lazy" />}
</span>
);
}
function ChampionGroup({
summary,
manifest,
}: {
summary: NonNullable<Summary>;
manifest: Manifest;
}) {
return (
<div className="ap-champions">
<h3>최근 챔피언</h3>
<div className="ap-avatar-group" aria-label="최근 사용 챔피언">
{summary.champions.slice(0, 10).map((champion) => {
const name =
championDisplayName(manifest, champion.championId) ??
`챔피언 ${champion.championId}`;
const description = `${name} · ${champion.games}경기 · ${champion.wins}승 ${champion.games - champion.wins}패 · 승률 ${Math.round((champion.wins / champion.games) * 100)}%`;
return (
<Tooltip
content={description}
placement="below"
key={champion.championId}
>
<span
className="ap-avatar"
role="img"
tabIndex={0}
aria-label={description}
>
<Portrait
championId={champion.championId}
manifest={manifest}
/>
</span>
</Tooltip>
);
})}
</div>
</div>
);
}
function Metrics({ summary }: { summary: Summary }) {
return (
<div className="ap-metrics" aria-label="선택한 포지션의 요약">
<div>
<span>승률</span>
<strong>
{summary ? (
<>
{summary.winRate}
<small>%</small>
</>
) : (
"—"
)}
</strong>
<p>
{summary
? `${summary.wins}승 ${summary.losses}패 · ${summary.games}경기`
: "기록 없음"}
</p>
</div>
<div>
<span>KDA</span>
<strong data-perfect={summary?.kda === "Perfect"}>
{summary?.kda ?? "—"}
</strong>
<p>{summary?.averageKda ?? "기록 없음"}</p>
</div>
<div>
<span>평균 킬 관여율</span>
<strong>
{summary?.killParticipation != null ? (
<>
{Math.round(summary.killParticipation)}
<small>%</small>
</>
) : (
"—"
)}
</strong>
<p>팀 처치 참여 비율</p>
</div>
</div>
);
}
function PlayMetrics({
summary,
position,
}: {
summary: NonNullable<Summary>;
position: PositionFilter;
}) {
const values = [
{ key: "cs", label: "분당 CS", value: metricLabel(summary.csPerMinute, 1) },
{
key: "damage",
label: "팀 내 피해량 비중",
value: metricLabel(summary.damageShare, 0, "%"),
},
{
key: "vision",
label: "분당 시야 점수",
value: metricLabel(summary.visionPerMinute, 2),
},
];
if (position === "SUP") values.unshift(values.splice(2, 1)[0]);
return (
<section
className="ap-play-metrics"
aria-label={`${positionName(position)} ${summary.games}경기 평균 플레이 지표`}
>
<dl>
{values.map((metric) => (
<div key={metric.key}>
<dt>{metric.label}</dt>
<dd>{metric.value}</dd>
</div>
))}
</dl>
</section>
);
}
function RecentGames({
games,
queue,
manifest,
historyBackTo,
}: {
games: ApiRecentMatchView[];
queue: ProfileQueue;
manifest: Manifest;
historyBackTo: string;
}) {
return (
<section className="ap-recent">
<div className="ap-section-heading">
<h3>최근 {queueName(queue)}</h3>
<span>{games.length}경기 · 최신순</span>
</div>
<div
className="ap-game-scroll"
tabIndex={0}
role="region"
aria-label={`${queueName(queue)} 최근 ${games.length}경기 목록`}
>
<table>
<thead>
<tr>
<th scope="col">경기</th>
<th scope="col">K / D / A</th>
<th scope="col">CS/분</th>
<th scope="col">킬 관여</th>
</tr>
</thead>
<tbody>
{games.map((game) => {
const name =
championDisplayName(manifest, game.championId) ??
`챔피언 ${game.championId}`;
const result = game.remake
? "다시하기"
: game.win
? "승리"
: "패배";
const content = (
<>
<Portrait championId={game.championId} manifest={manifest} />
<div>
<strong>
<b
data-result={
game.remake ? "remake" : game.win ? "win" : "loss"
}
>
{result}
</b>{" "}
{name}
</strong>
<p>
{dateLabel(game.gameCreation)} ·{" "}
{LANE_LABELS[game.teamPosition] ?? "포지션 미상"} ·{" "}
{Math.floor(game.gameDuration / 60)}분
</p>
</div>
</>
);
const detailPath =
game.internalMatchId && game.gameNumber
? internalMatchGamePath(
DEFAULT_COMMUNITY_ID,
game.internalMatchId,
game.gameNumber,
)
: null;
return (
<tr key={`${game.matchId}-${game.gameNumber ?? ""}`}>
<td>
{detailPath ? (
<Link
to={detailPath}
state={{
backTo: historyBackTo,
backLabel: "경매로 돌아가기",
}}
className="ap-game-identity"
aria-label={`${name} ${result} 내전 상세 보기`}
>
{content}
</Link>
) : (
<div className="ap-game-identity">{content}</div>
)}
</td>
<td>
{game.kills}/{game.deaths}/{game.assists}
</td>
<td>{metricLabel(game.csPerMin, 1)}</td>
<td>{metricLabel(game.killParticipation, 0, "%")}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</section>
);
}
function Masteries({
player,
manifest,
}: {
player: AuctionPlayerView;
manifest: Manifest;
}) {
if (!player.masteries.length) return null;
return (
<div className="ap-masteries">
<span>누적 숙련도</span>
<div className="ap-mastery-icons">
{player.masteries.slice(0, 5).map((champion) => {
const label = `${championDisplayName(manifest, champion.championId) ?? champion.championId} · Lv.${champion.level} · ${(champion.points / 1000).toFixed(0)}K`;
return (
<Tooltip
content={label}
placement="below"
key={champion.championId}
>
<span role="img" aria-label={label} tabIndex={0}>
<Portrait
championId={champion.championId}
manifest={manifest}
/>
</span>
</Tooltip>
);
})}
</div>
<small>포지션 무관</small>
</div>
);
}
export function AuctionPlayerProfile({
player,
peakTier,
historyBackTo,
bidStatus,
}: {
player: AuctionPlayerView;
peakTier?: ApiTierInfo;
historyBackTo: string;
bidStatus?: ReactNode;
}) {
const prefix = useId();
const manifest = useProfileManifest();
// The parent keys this component by player, so a new player starts at their preference.
const [queue, setQueue] = useState<ProfileQueue>("internal");
const [position, setPosition] = useState<PositionFilter>(
player.mainPosition ?? "ALL",
);
const history = useProfileHistory(player.userId, queue, position);
const games = selectProfileGames(history.data?.matches ?? [], position);
const summary = summarizeProfileGames(games);
const preferences = [player.mainPosition, player.subPosition].filter(
(value, index, values) => value && values.indexOf(value) === index,
);
const historyParams = new URLSearchParams({
queueGroup: queue === "internal" ? "internal" : "summoners-rift",
});
if (queue === "solo") historyParams.set("rank", "solo");
const historyHref = `/users/${player.userId}/history?${historyParams}`;
const loading = !history.data && history.isPending;
const unavailable = !history.data && history.isError;
const showAll = () => {
setPosition("ALL");
document.getElementById(`${prefix}-position-ALL`)?.focus();
};
return (
<section
className="auction-player-profile"
aria-label={`${player.summonerName} 선수 정보`}
>
<header className="ap-identity">
<Link
to={`/users/${player.userId}/history`}
state={{ backTo: historyBackTo }}
aria-label={`${player.summonerName} 전체 전적`}
>
<img
className="ap-player-avatar"
src={profileIconUrl(manifest, player.profileIconId)}
alt=""
/>
</Link>
<div className="ap-player-info">
<div className="ap-player-name">
<h2>
<Link
to={`/users/${player.userId}/history`}
state={{ backTo: historyBackTo }}
>
{player.summonerName}
</Link>
</h2>
<span>#{player.tag}</span>
</div>
<div className="ap-rank">
<RankBadge tier={player.tier} />
<span>{formatRankDetail(player.tier)}</span>
<span className="ap-secondary">현재</span>
</div>
<p className="ap-peak">
기록된 최고 <strong>{formatRankDetail(peakTier)}</strong>
</p>
<div className="ap-preferences">
<span>신청 포지션</span>
{preferences.map((preference, index) => (
<span
className="ap-role-chip"
data-primary={index === 0}
key={preference}
>
<img src={positionIcon[preference]} alt="" />
{positionLabel[preference]}
<small>{index + 1}순위</small>
</span>
))}
</div>
</div>
</header>
{bidStatus}
<div className="ap-tabs" role="tablist" aria-label="선수 전적 종류">
{QUEUES.map((value) => (
<button
type="button"
role="tab"
key={value}
id={`${prefix}-queue-${value}`}
aria-selected={queue === value}
aria-controls={`${prefix}-queue-panel`}
tabIndex={queue === value ? 0 : -1}
onClick={() => setQueue(value)}
onKeyDown={(event) =>
moveTab(event, QUEUES, queue, setQueue, `${prefix}-queue`)
}
>
{queueName(value)}
</button>
))}
</div>
<div
className="ap-card-body"
role="tabpanel"
id={`${prefix}-queue-panel`}
aria-labelledby={`${prefix}-queue-${queue}`}
>
<div className="ap-summary-heading">
<h3>최근 {queueName(queue)}</h3>
<Link to={historyHref} state={{ backTo: historyBackTo }}>
전체 전적
<ArrowUpRight size={13} aria-hidden="true" />
</Link>
</div>
<div
className="ap-position-tabs"
role="tablist"
aria-label="플레이 포지션"
>
{POSITIONS.map((value) => {
const count =
history.data?.positionCounts?.[
value === "ALL" ? "ALL" : POSITION_LANES[value]
] ??
(value === position && history.data ? games.length : undefined);
return (
<button
type="button"
role="tab"
id={`${prefix}-position-${value}`}
aria-controls={`${prefix}-position-panel`}
aria-selected={position === value}
aria-label={`${positionName(value)}${count === undefined ? "" : ` ${count}경기`}`}
tabIndex={position === value ? 0 : -1}
key={value}
onClick={() => setPosition(value)}
onKeyDown={(event) =>
moveTab(
event,
POSITIONS,
position,
setPosition,
`${prefix}-position`,
)
}
>
<span>
{value !== "ALL" && <img src={positionIcon[value]} alt="" />}
{positionName(value)}
</span>
<small>{count ?? "—"}</small>
</button>
);
})}
</div>
<div
role="tabpanel"
id={`${prefix}-position-panel`}
aria-labelledby={`${prefix}-position-${position}`}
aria-busy={loading}
>
{loading ? (
<div className="ap-loading" role="status">
<span />
전적을 불러오는 중입니다.
</div>
) : unavailable ? (
<div className="ap-empty" role="alert">
<strong>전적을 불러오지 못했습니다.</strong>
<p>잠시 후 다시 시도해 주세요.</p>
<button type="button" onClick={() => void history.refetch()}>
다시 시도
</button>
</div>
) : (
<>
<p className="ap-sample-context" aria-live="polite">
{position === "ALL" ? "전체 포지션" : positionName(position)}{" "}
최근 {games.length}경기
{games[0] && (
<span>
{dateLabel(games[games.length - 1].gameCreation)} –{" "}
{dateLabel(games[0].gameCreation)}
</span>
)}
</p>
<Metrics summary={summary} />
{summary && (
<>
<ChampionGroup summary={summary} manifest={manifest} />
<PlayMetrics summary={summary} position={position} />
</>
)}
{games.length ? (
<RecentGames
key={`${queue}-${position}`}
games={games}
queue={queue}
manifest={manifest}
historyBackTo={historyBackTo}
/>
) : (
<div className="ap-empty">
<strong>
{positionName(position)} 플레이 기록이 없습니다.
</strong>
<p>포지션별로 최근 20경기까지 집계합니다.</p>
{position !== "ALL" && (
<button type="button" onClick={showAll}>
전체 전적 보기
</button>
)}
</div>
)}
</>
)}
</div>
{queue === "solo" && <Masteries player={player} manifest={manifest} />}
{history.data && (
<p className="ap-data-note">
{history.data.season.label} · 지표는 선택한 경기 기준
{games.some((game) => game.remake) ? " · 다시하기 제외" : ""}
{summary?.games === 1 ? " · 1경기 표본" : ""}
</p>
)}
{history.isError && history.data && (
<p className="ap-data-note" role="status">
전적 갱신이 지연되어 마지막으로 불러온 기록을 표시합니다.
</p>
)}
</div>
</section>
);
}
@@ -0,0 +1,92 @@
# Auction player information — applied v2
Verified 2026-11-11 on the actual auction route:
`http://localhost:5173/match/6a3b94bccb8a54219653f457/auction`.
## Approved source and implementation
The selected reference is `src/design-previews/player-information-v2/Preview.tsx`
and its CSS. Production uses the separate `AuctionPlayerProfile.tsx`, `profile.css`,
and history/statistics helpers; it imports no prototype fixtures.
The identity header, queue tabs, six position tabs, three summary metrics,
overlapping champion avatars, three performance metrics and scrolling game table
follow the approved reference. Container queries adapt the card at its actual
440 px desktop / 311 px mobile widths. The existing auction bid/status rendering,
team cards and chat are preserved.
## Browser results
- Initial player is 붕어베이글. Requested first position is 미드 and the selected
history position starts at 미드. Internal history: seven actual games, 57% wins,
2.96 aggregate KDA, 57% mean kill participation. All portraits loaded.
- Solo overall window has 20 games dated October 30–November 7. The independent
mid window includes the older October 26 game even though it is outside those
overall 20 games. Support independently has 20 games; top/ADC have one each;
jungle has zero. No missing games are invented or padded.
- Remakes remain in the game list; summary performance excludes them and states
that exclusion. The observed overall solo window has 19 completed games plus
one remake, so summary wins/losses differ intentionally from the list count.
- Support puts vision/minute first. Empty jungle shows dashes and an explicit
empty state. Queue/position changes update the sample, metrics and champions
together. No champion-count text or disclosure controls were introduced.
- The table has all 20 rows, a 228 px viewport and sticky headings. End reaches
the final row (scrollTop 565.3 of a 566 px range); changing position resets to 0.
- ArrowRight and Home move selection and focus between position tabs. Internal
game links retain the match/game route and return-to-auction state.
- At 360 px viewport, page scrollWidth is 345 px and card scrollWidth is 311 px:
no horizontal overflow. Desktop 1280 px also has no horizontal overflow.
Browser viewport override was reset; final state is 내전 / 미드.
## Evidence
- Approved source: `src/design-previews/player-information-v2/Preview.tsx`.
- Full mobile card: `C:/Users/park/.codex/visualizations/2026/11/11/01a1c930-2c9b-7531-a709-2ebb87701e9a/player-information-applied/mobile.jpg`.
- Desktop context: same directory, `desktop.jpg`.
- Desktop identity, tabs and metrics: same directory, `auction-player-card.jpg`.
## Data and validation
Both API and web TypeScript checks passed. Targeted ESLint passed. Eleven web
tests (including the five existing prototype tests) and seventeen backend tests
passed. Tests cover filtering before limiting, older position records, legacy
pagination, stalled cursors, independently capped counts, participant-scoped
Mongo predicates, averages, missing metrics and remake exclusion.
The connected staging API predates lane filtering and returns no positionCounts.
The UI therefore uses a cached compatibility collector over its paginated public
history API. It retains only the independent recent-20 windows. Once the new
backend response is deployed, the UI requests the selected position directly.
The new backend code was type/unit tested, not deployed or verified against a
live database in this task (local bootstrap credentials were unavailable).
Current history APIs use their configured season scope, shown below the card.
The staging DDragon manifest endpoint returned HTTP 500. A separate card-only
query obtains champion metadata from Riot's official CDN when that endpoint
fails. Its partial manifest does not replace the application's full manifest
cache used by item/rune views.
## Size and stable-height follow-up
- Desktop inspector width now matches the approved two-column reference:
`(1104 - 24) / 2 = 540px`. The page maximum width increases by the same 100px,
retaining the existing 484px team grid at the maximum desktop layout width.
The four-column layout starts at 1440px with minimum widths for adjacent areas.
- The passed-status footer uses the reference's 12px type and 10px vertical
padding. Before the fixed-height request, the complete internal card matched
the reference's approximately 826px height.
- The history body now reserves 656px on desktop, including the maximum solo
view, ten champion portraits, the mastery row and the 228px match list. It
reserves 720px at container widths up to 480px. Short/empty results retain the
space, and flex layout keeps the data note at the bottom. Overflow remains
available as an accessibility fallback; it is not needed in the tested states.
- Browser measurements: the full desktop card is 877.60px for internal seven
games, empty support, solo loading and solo support twenty games. On mobile,
both twenty games and empty jungle measure 957.55px. History clientHeight and
scrollHeight are equal (656 / 720 respectively); no extra body scroll appears.
- Web TypeScript and AuctionPage/profile ESLint checks passed. This CSS change
adds no new unit tests; verification exercises the real tab interactions.
- During follow-up, another local Vite process replaced port 5173's staging
configuration with development. Live-data verification continued on the
isolated port 5174 staging proxy (`tmp/auction-profile-qa.mjs`, ignored), with a
separate Vite dependency cache. No auction actions were performed.
@@ -0,0 +1,84 @@
import type {
ApiRecentMatchesResponse,
ApiRecentMatchView,
} from "../../api/types";
import {
POSITION_LANES,
RECENT_GAME_LIMIT,
selectProfileGames,
type PositionFilter,
} from "./stats.ts";
/** Compatibility for older APIs: collect independent windows, never filter just the overall twenty. */
export async function collectProfileWindows(
fetchPage: (cursor?: number) => Promise<ApiRecentMatchesResponse>,
) {
const positions: PositionFilter[] = [
"ALL",
"TOP",
"JGL",
"MID",
"ADC",
"SUP",
];
const windows = new Map<PositionFilter, ApiRecentMatchView[]>(
positions.map((position) => [position, []]),
);
const seen = new Set<string>();
let cursor: number | undefined;
let first: ApiRecentMatchesResponse | undefined;
while (true) {
const page = await fetchPage(cursor);
first ??= page;
for (const game of [...page.matches].sort(
(a, b) => b.gameCreation - a.gameCreation,
)) {
const key = `${game.matchId}:${game.gameNumber ?? ""}`;
if (seen.has(key)) continue;
seen.add(key);
for (const position of positions) {
const window = windows.get(position)!;
if (
window.length < RECENT_GAME_LIMIT &&
(position === "ALL" || game.teamPosition === POSITION_LANES[position])
)
window.push(game);
}
}
if (
page.nextCursor === null ||
positions.every(
(position) => windows.get(position)!.length === RECENT_GAME_LIMIT,
)
)
break;
if (
!Number.isFinite(page.nextCursor) ||
(cursor !== undefined && page.nextCursor >= cursor)
)
throw new Error("전적 페이지를 이어 불러오지 못했습니다.");
cursor = page.nextCursor;
}
const uniqueGames = new Map<string, ApiRecentMatchView>();
for (const window of windows.values())
for (const game of window)
uniqueGames.set(`${game.matchId}:${game.gameNumber ?? ""}`, game);
return {
...first,
matches: [...uniqueGames.values()],
positionCounts: Object.fromEntries(
positions.map((position) => [
position === "ALL" ? "ALL" : POSITION_LANES[position],
windows.get(position)!.length,
]),
),
nextCursor: null,
};
}
export function profileWindow(
history: ApiRecentMatchesResponse,
position: PositionFilter,
): ApiRecentMatchesResponse {
return { ...history, matches: selectProfileGames(history.matches, position) };
}
@@ -0,0 +1,653 @@
.auction-player-profile {
container: auction-profile / inline-size;
color: var(--color-text-primary);
font-size: 13px;
line-height: 1.45;
}
.ap-identity {
padding: 20px;
display: flex;
align-items: flex-start;
gap: 16px;
}
.ap-player-avatar {
width: 64px;
height: 64px;
flex-shrink: 0;
object-fit: cover;
border-radius: var(--radius-inner);
}
.ap-player-info {
min-width: 0;
}
.ap-player-name {
display: flex;
align-items: baseline;
gap: 8px;
flex-wrap: wrap;
margin-bottom: 5px;
}
.ap-player-name h2 {
font-size: 20px;
font-weight: 750;
line-height: 1.2;
letter-spacing: -0.02em;
}
.ap-player-name > span,
.ap-secondary {
font-size: 12px;
color: var(--lts-text-subtle);
}
.ap-rank {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.ap-peak {
font-size: 12px;
color: var(--lts-text-subtle);
margin-top: 4px;
}
.ap-peak strong {
font-weight: 500;
color: var(--color-text-primary);
margin-left: 4px;
}
.ap-preferences {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
margin-top: 10px;
}
.ap-preferences > span:first-child {
font-size: 11px;
color: var(--lts-text-subtle);
margin-right: 2px;
}
.ap-role-chip {
border: 1px solid var(--color-border);
border-radius: 7px;
padding: 2px 6px;
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 12px;
}
.ap-role-chip[data-primary="true"] {
color: var(--color-text-accent);
border-color: color-mix(in srgb, var(--color-text-accent) 22%, transparent);
background: color-mix(in srgb, var(--color-text-accent) 4%, transparent);
}
.ap-role-chip img {
width: 13px;
height: 13px;
border-radius: 0;
}
.ap-role-chip small {
font-size: 10px;
opacity: 0.8;
}
.ap-tabs {
display: flex;
border-block: 1px solid var(--color-border);
padding-inline: 12px;
gap: 5px;
}
.ap-tabs button {
position: relative;
padding: 12px 11px;
color: var(--lts-text-subtle);
font-size: 13px;
font-weight: 650;
cursor: pointer;
border-radius: 0;
}
.ap-tabs button[aria-selected="true"] {
color: var(--color-text-accent);
}
.ap-tabs button[aria-selected="true"]::after {
content: "";
position: absolute;
height: 2px;
background: currentColor;
bottom: -1px;
left: 11px;
right: 11px;
}
.ap-tabs button:hover {
color: var(--color-text-primary);
}
.ap-tabs button:focus-visible,
.ap-recent-game:focus-visible,
.ap-summary-heading a:focus-visible {
outline: 2px solid var(--color-text-accent);
outline-offset: -2px;
}
.ap-card-body {
padding: 16px 18px 12px;
}
.ap-summary-heading {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
}
.ap-summary-heading h3 {
font-size: 14px;
font-weight: 700;
}
.ap-summary-heading a {
color: var(--color-text-accent);
display: inline-flex;
align-items: center;
gap: 3px;
font-size: 12px;
}
.ap-champion-portrait {
display: inline-block;
height: 32px;
width: 32px;
flex: 0 0 32px;
overflow: hidden;
border-radius: var(--radius-inner);
background: var(--color-background-muted);
}
.ap-champion-portrait img {
height: 100%;
width: 100%;
object-fit: cover;
transform: scale(1.18);
}
.ap-card-body {
padding: 14px 18px 10px;
/* Reserve the full solo-rank view: 20 games, ten portraits and mastery row. */
height: 656px;
display: flex;
flex-direction: column;
overflow-y: auto;
scrollbar-width: thin;
}
.ap-card-body > * {
flex-shrink: 0;
}
.ap-card-body > [role="tabpanel"] {
flex-grow: 1;
}
.ap-identity {
padding: 18px;
}
.ap-position-tabs {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
gap: 3px;
margin-top: 13px;
border-bottom: 1px solid var(--color-border);
}
.ap-position-tabs button {
display: flex;
align-items: center;
justify-content: center;
gap: 5px;
min-height: 41px;
position: relative;
border-radius: 5px 5px 0 0;
font-size: 12px;
cursor: pointer;
color: var(--lts-text-subtle);
padding: 6px 2px;
}
.ap-position-tabs button > span {
display: flex;
align-items: center;
gap: 3px;
}
.ap-position-tabs img {
width: 12px;
height: 12px;
border-radius: 0;
}
.ap-position-tabs small {
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.ap-position-tabs button[data-empty="true"] {
color: var(--lts-text-subtle);
}
.ap-position-tabs button[aria-selected="true"] {
background: color-mix(in srgb, var(--color-text-accent) 5%, transparent);
color: var(--color-text-accent);
font-weight: 700;
}
.ap-position-tabs button[aria-selected="true"]::after {
content: "";
position: absolute;
left: 7px;
right: 7px;
bottom: -1px;
height: 2px;
background: var(--color-text-accent);
}
.ap-position-tabs button:hover {
background: var(--color-background-muted);
}
.ap-position-tabs button:focus-visible,
.ap-avatar:focus-visible,
.ap-mastery-icons > span:focus-visible {
outline: 2px solid var(--color-text-accent);
outline-offset: 2px;
z-index: 5;
}
.ap-sample-context {
display: flex;
justify-content: space-between;
gap: 6px;
margin-top: 9px;
font-size: 11px;
color: var(--lts-text-subtle);
}
.ap-metrics {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
margin: 13px 0 9px;
}
.ap-metrics > div {
min-width: 0;
padding-inline: 13px;
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 3px 5px;
}
.ap-metrics > div:first-child {
padding-left: 0;
}
.ap-metrics > div:last-child {
padding-right: 0;
}
.ap-metrics > div + div {
border-left: 1px solid var(--color-border);
}
.ap-metrics > div > span {
font-size: 11px;
color: var(--lts-text-subtle);
}
.ap-metrics strong {
display: block;
font-size: 24px;
font-weight: 750;
line-height: 1.25;
font-variant-numeric: tabular-nums;
letter-spacing: -0.03em;
}
.ap-metrics strong[data-perfect="true"] {
font-size: 16px;
line-height: 1.875;
}
.ap-metrics small {
font-size: 14px;
margin-left: 1px;
font-weight: 500;
}
.ap-metrics p {
grid-column: 1 / -1;
font-size: 11px;
color: var(--lts-text-subtle);
white-space: nowrap;
}
.ap-champions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 4px 12px;
min-height: 49px;
padding-block: 6px;
}
.ap-champions h3 {
font-size: 12px;
color: var(--lts-text-subtle);
font-weight: 500;
flex-shrink: 0;
}
.ap-avatar-group {
display: flex;
align-items: center;
padding-left: 10px;
}
.ap-avatar {
display: inline-flex;
position: relative;
border-radius: 50%;
border: 2px solid var(--color-background-card);
margin-left: -10px;
background: var(--color-background-card);
cursor: help;
}
.ap-avatar:hover,
.ap-avatar:focus {
z-index: 4;
}
.ap-avatar .ap-champion-portrait {
width: 30px;
height: 30px;
flex-basis: 30px;
border-radius: 50%;
}
.ap-play-metrics {
padding-block: 9px;
border-block: 1px solid var(--color-border);
margin: 2px 0 14px;
}
.ap-section-heading {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
margin-bottom: 9px;
}
.ap-section-heading h3 {
font-size: 13px;
font-weight: 700;
}
.ap-section-heading > span {
font-size: 11px;
color: var(--lts-text-subtle);
}
.ap-play-metrics dl {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
}
.ap-play-metrics dt {
font-size: 11px;
color: var(--lts-text-subtle);
}
.ap-play-metrics dd {
font-size: 18px;
font-weight: 650;
margin-top: 2px;
font-variant-numeric: tabular-nums;
}
.ap-recent table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.ap-game-scroll {
max-height: 228px;
overflow-y: auto;
overscroll-behavior-y: contain;
scrollbar-width: thin;
scrollbar-color: var(--color-border) transparent;
}
.ap-game-scroll:focus-visible {
outline: 2px solid var(--color-text-accent);
outline-offset: 3px;
}
.ap-recent thead {
position: sticky;
top: 0;
z-index: 1;
background: var(--color-background-card);
}
.ap-recent th {
color: var(--lts-text-subtle);
font-size: 10px;
font-weight: 500;
text-align: right;
padding: 0 0 6px;
}
.ap-recent th:first-child {
width: auto;
text-align: left;
}
.ap-recent th:nth-child(2) {
width: 78px;
}
.ap-recent th:nth-child(3) {
width: 58px;
}
.ap-recent th:nth-child(4) {
width: 62px;
}
.ap-recent td {
text-align: right;
padding: 5px 0;
border-top: 1px solid var(--color-border);
}
.ap-recent td:first-child {
text-align: left;
}
.ap-game-identity {
display: flex;
align-items: center;
gap: 7px;
}
.ap-game-identity > div {
min-width: 0;
}
.ap-game-identity .ap-champion-portrait {
width: 28px;
height: 28px;
flex-basis: 28px;
}
.ap-game-identity strong {
display: block;
font-size: 12px;
line-height: 1.25;
font-weight: 550;
white-space: nowrap;
}
.ap-game-identity b {
font-weight: 700;
}
.ap-game-identity b[data-result="win"] {
color: var(--color-palette-win-text-light);
}
.ap-game-identity b[data-result="loss"] {
color: var(--color-palette-loss-text-light);
}
[data-theme="dark"] .ap-game-identity b[data-result="win"] {
color: var(--color-palette-win-text-dark);
}
[data-theme="dark"] .ap-game-identity b[data-result="loss"] {
color: var(--color-palette-loss-text-dark);
}
.ap-game-identity p {
font-size: 10px;
line-height: 1.2;
color: var(--lts-text-subtle);
white-space: nowrap;
margin-top: 1px;
}
.ap-masteries {
display: flex;
align-items: center;
gap: 10px;
padding-top: 12px;
margin-top: 8px;
border-top: 1px solid var(--color-border);
color: var(--lts-text-subtle);
font-size: 11px;
}
.ap-mastery-icons {
display: flex;
align-items: center;
gap: 5px;
}
.ap-mastery-icons > span {
display: inline-flex;
border-radius: var(--radius-inner);
cursor: help;
}
.ap-masteries .ap-champion-portrait {
width: 22px;
height: 22px;
flex-basis: 22px;
}
.ap-masteries small {
margin-left: auto;
font-size: 10px;
white-space: nowrap;
}
.ap-data-note {
font-size: 10px;
color: var(--lts-text-subtle);
margin-top: 11px;
}
.ap-empty {
padding: 32px 8px 40px;
text-align: center;
}
.ap-empty strong {
font-size: 13px;
font-weight: 600;
}
.ap-empty p {
color: var(--lts-text-subtle);
font-size: 12px;
margin-top: 8px;
}
.ap-empty button {
color: var(--color-text-accent);
font-size: 12px;
border: 1px solid var(--color-border);
border-radius: var(--radius-element);
padding: 8px 12px;
margin-top: 16px;
cursor: pointer;
}
@container auction-profile (max-width: 480px) {
.ap-card-body {
height: 720px;
}
.ap-card-body {
padding-inline: 12px;
}
.ap-position-tabs {
gap: 1px;
}
.ap-position-tabs button {
flex-direction: column;
gap: 2px;
font-size: 11px;
min-height: 48px;
}
.ap-position-tabs img {
width: 11px;
height: 11px;
}
.ap-metrics > div {
padding-inline: 9px;
}
.ap-metrics {
gap: 0;
}
.ap-metrics > div {
display: block;
}
.ap-metrics > div > span {
font-size: 11px;
}
.ap-metrics strong {
font-size: 23px;
}
.ap-metrics p {
font-size: 10px;
margin-top: 2px;
}
.ap-metrics strong[data-perfect="true"] {
font-size: 17px;
}
.ap-champions {
gap: 8px;
}
.ap-champions h3 {
font-size: 11px;
}
.ap-avatar .ap-champion-portrait {
width: 27px;
height: 27px;
flex-basis: 27px;
}
.ap-recent th:nth-child(2) {
width: 58px;
}
.ap-recent th:nth-child(3) {
width: 43px;
}
.ap-recent th:nth-child(4) {
width: 46px;
}
.ap-recent table {
font-size: 11px;
}
.ap-game-identity {
gap: 5px;
}
.ap-game-identity strong {
font-size: 11px;
}
.ap-game-identity p {
font-size: 9px;
}
.ap-masteries {
gap: 7px;
}
}
.ap-identity > a {
flex-shrink: 0;
}
.ap-player-name h2 {
overflow-wrap: anywhere;
}
.ap-player-name a:hover,
.ap-game-identity:hover {
color: var(--color-text-accent);
}
.ap-game-identity:focus-visible,
.ap-identity a:focus-visible {
outline: 2px solid var(--color-text-accent);
outline-offset: 2px;
}
.ap-game-identity strong {
overflow: hidden;
text-overflow: ellipsis;
}
.ap-game-identity b[data-result="remake"] {
color: var(--lts-text-subtle);
}
.ap-loading {
min-height: 360px;
padding-top: 24px;
color: var(--lts-text-subtle);
font-size: 12px;
}
.ap-loading > span {
display: block;
height: 64px;
border-radius: var(--radius-element);
background: var(--color-background-muted);
margin-bottom: 16px;
}
@container auction-profile (max-width: 480px) {
.ap-identity {
padding: 16px;
gap: 11px;
}
.ap-player-avatar {
width: 52px;
height: 52px;
}
.ap-player-name h2 {
font-size: 18px;
}
.ap-preferences > span:first-child {
width: 100%;
}
}
@@ -0,0 +1,113 @@
import type { ApiRecentMatchView, Position, RiotLane } from "../../api/types";
export type ProfileQueue = "internal" | "solo";
export type PositionFilter = "ALL" | Position;
export const RECENT_GAME_LIMIT = 20;
export const POSITION_LANES: Record<Position, RiotLane> = {
TOP: "TOP",
JGL: "JUNGLE",
MID: "MIDDLE",
ADC: "BOTTOM",
SUP: "UTILITY",
};
/** The server filters before limiting. Keep the display window bounded and sorted. */
export function selectProfileGames(
history: ApiRecentMatchView[],
position: PositionFilter,
) {
return history
.filter(
(game) =>
position === "ALL" || game.teamPosition === POSITION_LANES[position],
)
.sort((a, b) => b.gameCreation - a.gameCreation)
.slice(0, RECENT_GAME_LIMIT);
}
const mean = (values: (number | undefined)[]) => {
const known = values.filter(
(value): value is number =>
typeof value === "number" && Number.isFinite(value),
);
return known.length
? known.reduce((sum, value) => sum + value, 0) / known.length
: null;
};
function damageShare(game: ApiRecentMatchView) {
if (game.damageShare !== undefined) return game.damageShare;
// Older responses expose team totals rather than the computed percentage.
const team = game.teams?.find((team) => team.win === game.win);
if (!team?.participants.length) return undefined;
const total = team.participants.reduce(
(sum, participant) => sum + participant.damageDealtToChampions,
0,
);
return total > 0
? (game.damageDealtToChampions / total) * 100
: total === 0
? 0
: undefined;
}
export function summarizeProfileGames(games: ApiRecentMatchView[]) {
// Remakes remain visible in the list but do not distort win rate or performance.
const completed = games.filter((game) => !game.remake);
if (!completed.length) return null;
const kills = completed.reduce((sum, game) => sum + game.kills, 0);
const deaths = completed.reduce((sum, game) => sum + game.deaths, 0);
const assists = completed.reduce((sum, game) => sum + game.assists, 0);
const wins = completed.filter((game) => game.win).length;
const champions = new Map<
number,
{ championId: number; games: number; wins: number }
>();
for (const game of completed) {
const champion = champions.get(game.championId) ?? {
championId: game.championId,
games: 0,
wins: 0,
};
champion.games++;
champion.wins += Number(game.win);
champions.set(game.championId, champion);
}
return {
games: completed.length,
wins,
losses: completed.length - wins,
winRate: Math.round((wins / completed.length) * 100),
kda: deaths
? ((kills + assists) / deaths).toFixed(2)
: kills + assists > 0
? "Perfect"
: "0.00",
averageKda: [kills, deaths, assists]
.map((value) => (value / completed.length).toFixed(1))
.join("/"),
killParticipation: mean(completed.map((game) => game.killParticipation)),
csPerMinute: mean(completed.map((game) => game.csPerMin)),
damageShare: mean(completed.map(damageShare)),
visionPerMinute: mean(
completed.map((game) =>
game.gameDuration > 0 && Number.isFinite(game.visionScore)
? game.visionScore / (game.gameDuration / 60)
: undefined,
),
),
champions: [...champions.values()].sort(
(a, b) => b.games - a.games || b.wins - a.wins,
),
};
}
export function metricLabel(
value: number | null | undefined,
digits = 0,
suffix = "",
) {
return typeof value === "number" && Number.isFinite(value)
? `${value.toFixed(digits)}${suffix}`
: "—";
}
@@ -0,0 +1,79 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import type { ApiRecentMatchesResponse } from "../../api/types";
import { DEFAULT_COMMUNITY_ID } from "../../config";
import { apiFetch } from "../../lib/api";
import {
POSITION_LANES,
RECENT_GAME_LIMIT,
type PositionFilter,
type ProfileQueue,
} from "./stats";
import { collectProfileWindows, profileWindow } from "./history";
export function useProfileHistory(
userId: string,
queue: ProfileQueue,
position: PositionFilter,
) {
const queryClient = useQueryClient();
const legacyKey = [
"auction-player-history-windows",
DEFAULT_COMMUNITY_ID,
userId,
queue,
];
return useQuery({
queryKey: [
"auction-player-history",
DEFAULT_COMMUNITY_ID,
userId,
queue,
position,
],
queryFn: async ({ signal }) => {
const params = new URLSearchParams({
limit: String(RECENT_GAME_LIMIT),
includePositionCounts: "true",
});
if (position !== "ALL") params.set("lane", POSITION_LANES[position]);
if (queue === "solo") {
params.set("queueGroup", "summoners-rift");
params.set("rank", "solo");
}
const resource =
queue === "internal" ? "internal-history" : "recent-matches";
const path = `/communities/${DEFAULT_COMMUNITY_ID}/users/${userId}/${resource}`;
const loadWindows = () =>
queryClient.fetchQuery({
queryKey: legacyKey,
staleTime: 60_000,
retry: false,
queryFn: ({ signal: windowSignal }) =>
collectProfileWindows((cursor) => {
const pageParams = new URLSearchParams(params);
pageParams.delete("lane");
pageParams.delete("includePositionCounts");
pageParams.set("limit", "30");
if (cursor !== undefined)
pageParams.set("cursor", String(cursor));
return apiFetch<ApiRecentMatchesResponse>(
`${path}?${pageParams}`,
{ auth: "none", signal: windowSignal },
);
}),
});
if (queryClient.getQueryData(legacyKey))
return profileWindow(await loadWindows(), position);
const response = await apiFetch<ApiRecentMatchesResponse>(
`${path}?${params}`,
{ auth: "none", signal },
);
return response.positionCounts
? response
: profileWindow(await loadWindows(), position);
},
enabled: Boolean(DEFAULT_COMMUNITY_ID && userId),
staleTime: 60_000,
retry: 1,
});
}
@@ -0,0 +1,52 @@
import { useQuery } from "@tanstack/react-query";
import { useDdragonManifest } from "../../api/hooks";
import type { DdragonManifest } from "../../api/types";
/** Keep player portraits available if the application's manifest endpoint is down. */
export function useProfileManifest() {
const manifest = useDdragonManifest();
const champions = useQuery({
queryKey: ["auction-profile-champion-manifest", "ko_KR"],
enabled: !manifest.data && manifest.failureCount > 0,
staleTime: 24 * 60 * 60 * 1000,
retry: 1,
queryFn: async ({ signal }): Promise<DdragonManifest> => {
const cdn = "https://ddragon.leagueoflegends.com/cdn";
const versionResponse = await fetch(
"https://ddragon.leagueoflegends.com/api/versions.json",
{ signal },
);
if (!versionResponse.ok)
throw new Error("챔피언 버전을 불러오지 못했습니다.");
const versions: string[] = await versionResponse.json();
const version = versions[0];
if (!version || !/^\d+\.\d+\.\d+$/.test(version))
throw new Error("챔피언 버전 정보가 올바르지 않습니다.");
const response = await fetch(
`${cdn}/${version}/data/ko_KR/champion.json`,
{ signal },
);
if (!response.ok) throw new Error("챔피언 정보를 불러오지 못했습니다.");
const payload: {
data: Record<string, { key: string; id: string; name: string }>;
} = await response.json();
// This separate cache supplies only this card's champion and profile portraits.
return {
version,
cdn,
locale: "ko_KR",
fetchedAt: new Date().toISOString(),
champions: Object.fromEntries(
Object.values(payload.data).map((champion) => [
champion.key,
{ key: champion.id, name: champion.name },
]),
),
items: {},
summonerSpells: {},
runesReforged: [],
};
},
});
return manifest.data ?? champions.data;
}
@@ -0,0 +1,132 @@
.auction-reaction-picker-title {
margin: 0;
font-size: 14px;
font-weight: 700;
}
.auction-reaction-picker-description {
margin: 3px 0 12px;
color: var(--color-text-secondary);
font-size: 12px;
}
.auction-reaction-options {
display: grid;
grid-template-columns: repeat(4, minmax(44px, 1fr));
gap: 6px;
}
.auction-reaction-options .auction-reaction-option {
width: 100%;
height: 46px;
border-radius: 10px;
}
.auction-reaction-option span[aria-hidden] {
font-size: 27px;
line-height: 1;
font-family:
"Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
}
.auction-reaction-options .auction-reaction-option:disabled {
opacity: 0.55;
}
.auction-reaction-error {
margin: 10px 0 0;
font-size: 12px;
line-height: 1.5;
color: var(--color-text-secondary);
}
.auction-chat-panel .auction-chat-reaction-trigger {
width: 36px;
height: 36px;
min-width: 36px;
border-radius: 8px;
color: var(--color-text-secondary);
}
.auction-reaction-layer {
position: fixed;
inset: 0;
z-index: 60;
overflow: hidden;
pointer-events: none;
user-select: none;
contain: strict;
}
.auction-floating-reaction {
position: absolute;
bottom: max(20px, env(safe-area-inset-bottom));
left: clamp(54px, var(--reaction-left), calc(100% - 54px));
display: flex;
align-items: center;
flex-direction: column;
gap: 5px;
width: 100px;
margin-left: -50px;
animation: auction-reaction-rise 2.8s cubic-bezier(0.18, 0.6, 0.25, 1) both;
will-change: transform, opacity;
}
.auction-floating-emoji {
font-family:
"Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
font-size: 48px;
line-height: 1.15;
filter: drop-shadow(0 3px 5px #0002);
}
.auction-floating-name {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
border-radius: 999px;
padding: 3px 8px;
background: #22252ee6;
color: #fff;
font-size: 11px;
line-height: 1.5;
}
@keyframes auction-reaction-rise {
0% {
opacity: 0;
transform: translate3d(0, 32px, 0) scale(0.65) rotate(0);
}
12% {
opacity: 1;
}
40% {
transform: translate3d(var(--reaction-drift), -18vh, 0) scale(1.08)
rotate(var(--reaction-tilt));
}
70% {
opacity: 1;
}
100% {
opacity: 0;
transform: translate3d(0, -48vh, 0) scale(0.9) rotate(0);
}
}
@keyframes auction-reaction-fade {
0%,
100% {
opacity: 0;
}
15%,
75% {
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.auction-floating-reaction {
animation: auction-reaction-fade 2.8s linear both;
transform: none;
will-change: opacity;
}
}
@media (pointer: coarse), (max-width: 639px) {
.auction-chat-panel .auction-chat-reaction-trigger {
width: 44px;
height: 44px;
min-width: 44px;
}
.auction-floating-emoji {
font-size: 40px;
}
}
@@ -4,8 +4,6 @@ import type {
MatchId,
TeamId,
} from "@lolympus/contracts";
import { ChevronDown } from "lucide-react";
import { useState } from "react";
import { useLocation } from "react-router";
import {
formatCompetitionHistoryDate,
@@ -73,10 +71,7 @@ export function CompetitionSeriesHistory({
className="inline-flex min-h-11 shrink-0 items-center gap-1 px-2 text-xs font-bold text-content-muted transition-colors hover:bg-base-content/[0.03] hover:text-base-content focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary"
>
{jumpLabel}
<ChevronDown
className="h-4 w-4 text-primary"
aria-hidden="true"
/>
<span aria-hidden="true">↓</span>
</a>
)}
</header>
@@ -121,7 +116,6 @@ export function CompetitionSeriesHistory({
communityId={communityId}
matchId={matchId}
historyPath={historyPath}
currentHash={location.hash}
/>
</li>
))}
@@ -140,18 +134,15 @@ function SeriesHistoryRow({
communityId,
matchId,
historyPath,
currentHash,
}: {
row: CompetitionSeriesHistoryRow;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
communityId: CommunityId;
matchId: MatchId;
historyPath: string;
currentHash: string;
}) {
const detailsId = seriesHistoryDetailsId(row.series.seriesId);
const seriesHash = `#${detailsId}`;
const [expanded, setExpanded] = useState(currentHash === seriesHash);
if (row.games.length === 0) {
return (
@@ -164,19 +155,14 @@ function SeriesHistoryRow({
}
return (
<details
id={detailsId}
className="group scroll-mt-24"
open={expanded}
onToggle={(event) => setExpanded(event.currentTarget.open)}
>
<summary className="list-none cursor-pointer transition-colors hover:bg-base-content/[0.04] active:bg-base-content/[0.06] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary group-open:bg-base-content/[0.025] [&::-webkit-details-marker]:hidden">
<section id={detailsId} className="group scroll-mt-24">
<header>
<SeriesSummary
row={row}
teamById={teamById}
hasGameDetails
/>
</summary>
</header>
<CompetitionGameHistory
games={row.games}
teamById={teamById}
@@ -184,7 +170,7 @@ function SeriesHistoryRow({
matchId={matchId}
historyBackTo={`${historyPath}${seriesHash}`}
/>
</details>
</section>
);
}
@@ -203,10 +189,9 @@ function SeriesSummary({
series.stage.type,
series.stage.roundNumber,
);
const closedRecordLabel = getSeriesHistoryRecordLabel(
const recordLabel = getSeriesHistoryRecordLabel(
series,
row.games.length,
false,
);
const showRecordLabel = hasGameDetails || !isFutureSeries(series);
@@ -228,20 +213,7 @@ function SeriesSummary({
{showRecordLabel && (
<span className="mt-2 flex min-h-6 items-center justify-end text-xs font-bold text-content-muted lg:col-start-3 lg:row-start-1 lg:mt-0">
{hasGameDetails ? (
<>
<span className="group-open:hidden">{closedRecordLabel}</span>
<span className="hidden group-open:inline">
{getSeriesHistoryRecordLabel(series, row.games.length, true)}
</span>
<ChevronDown
className="ml-1 h-4 w-4 text-primary transition-transform group-open:rotate-180 motion-reduce:transition-none"
aria-hidden="true"
/>
</>
) : (
<span>{closedRecordLabel}</span>
)}
<span>{recordLabel}</span>
</span>
)}
</span>
@@ -23,10 +23,6 @@ export function DoubleEliminationMobileBracket({
projection.series.map((series) => [series.seriesId, series]),
);
const nodeById = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const isCurrentRound = (seriesIds: readonly SeriesId[]) => seriesIds.some((seriesId) => {
const status = seriesById.get(seriesId)?.status;
return status === "ready" || status === "in-progress";
});
const sections = [
{
key: "upper",
@@ -77,17 +73,11 @@ export function DoubleEliminationMobileBracket({
</div>
<div className="space-y-2">
{groups.map((group) => (
<details
key={`${group.stage}:${group.roundNumber}`}
open={groups.length === 1 || isCurrentRound(group.seriesIds)}
className="group lts-panel"
>
<summary
className="cursor-pointer px-3 py-3 text-sm font-semibold hover:bg-sunken"
>
<section key={`${group.stage}:${group.roundNumber}`} className="group lts-panel">
<h4 className="px-3 py-3 text-sm font-semibold ">
{group.accessibleLabel}
<span className="ml-2 text-xs font-medium text-content-muted">{group.seriesIds.length}경기</span>
</summary>
</h4>
<div className="space-y-3 border-t border-line p-3">
{group.seriesIds.map((seriesId) => {
const series = seriesById.get(seriesId);
@@ -117,7 +107,7 @@ export function DoubleEliminationMobileBracket({
);
})}
</div>
</details>
</section>
))}
</div>
</section>
@@ -0,0 +1,34 @@
import type { CompetitionTeamView } from "@lolympus/contracts";
import { sortTeamMembersForRoster } from "../../pages/match-team-progress-view";
import { SummonerAvatar } from "../SummonerAvatar";
export function TeamMemberSummary({ team }: { team: CompetitionTeamView }) {
const members = sortTeamMembersForRoster(team.members);
if (members.length === 0) return null;
return (
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1.5">
<span className="flex shrink-0 -space-x-1.5 py-1.5 pr-1" aria-hidden="true">
{members.map((member) => (
<SummonerAvatar
key={member.userId}
profileIconId={member.profileIconId}
isCaptain={member.userId === team.captainUserId}
size="sm"
shape="circle"
/>
))}
</span>
<p className="min-w-0 basis-48 grow text-[13px] leading-5 text-content-muted">
{members.map((member, index) => (
<span key={member.userId}>
{index > 0 && <span aria-hidden="true"> · </span>}
{index > 0 && <span className="sr-only">, </span>}
<span className="inline-block max-w-full align-top [overflow-wrap:anywhere]">{member.displayName}</span>
{member.userId === team.captainUserId && <span className="sr-only"> (팀장)</span>}
</span>
))}
</p>
</div>
);
}
@@ -0,0 +1,32 @@
import type { CompetitionTeamView } from "@lolympus/contracts";
import { Link } from "react-router";
import { positionLabel } from "../../lib/league";
import { sortTeamMembersForRoster } from "../../pages/match-team-progress-view";
import { SummonerAvatar } from "../SummonerAvatar";
export function TeamRoster({ team }: { team: CompetitionTeamView }) {
return (
<ul className="lts-panel divide-y divide-line">
{sortTeamMembersForRoster(team.members).map((member) => (
<li key={member.userId}>
<Link
to={`/users/${member.userId}/history?queueGroup=internal`}
className="group grid min-h-16 grid-cols-[2.5rem_2.5rem_minmax(0,1fr)] items-center gap-3 px-4 py-3 transition-colors hover:bg-sunken focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary sm:px-5"
>
<span className="text-xs font-semibold text-content-muted">
{member.assignedPosition ? positionLabel[member.assignedPosition] : "미정"}
</span>
<SummonerAvatar
profileIconId={member.profileIconId}
isCaptain={member.userId === team.captainUserId}
/>
<span className="min-w-0 text-sm font-bold text-base-content [overflow-wrap:anywhere] group-hover:underline">
{member.displayName}
<span className="sr-only"> 전적 보기</span>
</span>
</Link>
</li>
))}
</ul>
);
}
@@ -9,6 +9,7 @@ import {
type TeamSeriesTone,
} from "../../pages/match-team-progress-view";
import { isSeriesEntryWinner } from "./series-score-card-model";
import { TeamMemberSummary } from "./TeamMemberSummary";
const STATUS_TONE_CLASS: Record<TeamSeriesTone, string> = {
muted: "border-base-content/15 bg-base-200 text-base-content",
@@ -38,7 +39,7 @@ export function TeamSeriesCard({
return (
<article
className={`overflow-hidden border bg-base-100 ${
className={`overflow-hidden rounded-box border bg-base-100 ${
emphasized ? "border-primary/30" : "border-base-content/10"
}`}
aria-labelledby={headingId}
@@ -50,19 +51,19 @@ export function TeamSeriesCard({
: "border-base-content/10 bg-base-200/40"
}`}
>
<div className="min-w-0">
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 self-center">
<h3
id={headingId}
className="break-words text-base font-black text-base-content"
className="break-words text-xs font-bold text-content-muted"
>
{displayLabel}
</h3>
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-content-muted">
<div className="text-xs text-content-muted">
<span>{seriesRuleLabel(series)}</span>
</div>
</div>
<span
className={`shrink-0 border-l-2 px-2 py-1 text-xs font-bold ${STATUS_TONE_CLASS[presentation.tone]}`}
className={`inline-flex shrink-0 items-center rounded-full border px-2 py-1 text-xs font-bold ${STATUS_TONE_CLASS[presentation.tone]}`}
>
{presentation.label}
</span>
@@ -81,31 +82,32 @@ export function TeamSeriesCard({
return (
<li
key={entry.slot}
className={`grid min-h-12 grid-cols-[minmax(0,1fr)_3rem] items-center gap-3 px-4 py-2.5 sm:px-5 ${
isHighlightedTeam ? "bg-base-200/35" : ""
}`}
className="grid grid-cols-[minmax(0,1fr)_2.5rem] items-center gap-3 px-4 py-3 sm:px-5"
>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<span
className={`min-w-0 break-words text-sm ${
isWinner || isHighlightedTeam
? "font-bold text-base-content"
: "text-content-subtle"
}`}
>
<span className="sr-only">{entry.slot} 슬롯: </span>
{teamName}
</span>
{isHighlightedTeam && (
<span className="border border-base-content/15 bg-base-100 px-1.5 py-0.5 text-[11px] font-bold text-base-content">
이 팀
<div className="min-w-0 space-y-1.5">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<span
className={`min-w-0 break-words text-base text-base-content ${
isWinner || isHighlightedTeam
? "font-bold"
: "font-semibold"
}`}
>
<span className="sr-only">{entry.slot} 슬롯: </span>
{teamName}
</span>
)}
{isWinner && (
<span className="border-l-2 border-success bg-success/10 px-1.5 py-0.5 text-[11px] font-bold text-base-content">
승리
</span>
)}
{isHighlightedTeam && (
<span className="inline-flex items-center rounded-full border border-base-content/15 bg-base-100 px-1.5 py-0.5 text-[11px] font-bold text-base-content">
우리 팀
</span>
)}
{isWinner && (
<span className="inline-flex items-center rounded-full border border-success bg-success/10 px-1.5 py-0.5 text-[11px] font-bold text-base-content">
승리
</span>
)}
</div>
{team && <TeamMemberSummary team={team} />}
</div>
<span className="text-right font-mono text-base font-bold tabular-nums text-base-content">
<span className="sr-only">
@@ -129,7 +131,7 @@ export function TeamSeriesCard({
function seriesRuleLabel(series: SeriesProjection): string {
if (series.rule.type === "fixed-games") {
return `${series.rule.gameCount}게임`;
return `총 ${series.rule.gameCount}경기`;
}
return `${series.rule.maxGames}전 ${series.rule.winsRequired}선승`;
}
@@ -99,97 +99,96 @@ export function TeamTournamentCodes({
}
}
const nextAssignment = assignments.find((assignment) => assignment.state !== "used") ?? assignments[0];
const otherAssignments = assignments.filter((assignment) => assignment !== nextAssignment);
function renderAssignment(assignment: TeamTournamentCodeView) {
const slotId = String(assignment.gameSlotId);
const presentation = getTournamentCodePresentation(assignment, now);
const isCopying = copyingSlotId === slotId;
const copied =
feedback?.kind === "success" && feedback.gameSlotId === slotId;
return (
<li
key={slotId}
className="grid gap-3 px-4 py-3 sm:px-5 md:grid-cols-[5.5rem_minmax(0,1fr)_auto] md:items-center"
>
<div>
<p className="text-sm font-bold text-base-content">
{assignment.ordinal}세트
</p>
<p className="mt-0.5 text-xs text-content-muted">
전체 {assignment.displayNumber}경기
</p>
</div>
const slotId = String(assignment.gameSlotId);
const presentation = getTournamentCodePresentation(assignment, now);
const isCopying = copyingSlotId === slotId;
const copied =
feedback?.kind === "success" && feedback.gameSlotId === slotId;
return (
<li
key={slotId}
className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 px-4 py-3 sm:grid-cols-[5.5rem_minmax(0,1fr)_auto] sm:px-5"
>
<div className="col-span-2 flex flex-wrap items-center gap-x-3 gap-y-1 sm:col-span-1 sm:block">
<div>
<p className="text-sm font-bold text-base-content">
{assignment.ordinal}세트
</p>
<p className="mt-0.5 text-xs text-content-muted">
대회 경기 #{assignment.displayNumber}
</p>
</div>
<span
className={`inline-flex items-center rounded-full border px-1.5 py-0.5 text-[11px] font-semibold sm:mt-1.5 ${CODE_TONE_CLASS[presentation.tone]}`}
role="status"
aria-live="polite"
aria-atomic="true"
>
{presentation.label}
</span>
</div>
<div className="min-w-0">
{assignment.code ? (
<AutoSizingCodeField
label={`${seriesLabel} ${assignment.ordinal}세트 토너먼트 코드`}
value={assignment.code}
/>
) : (
<p className="text-sm font-bold text-content-muted">
발급되면 이곳에서 복사할 수 있습니다.
</p>
)}
{assignment.code &&
assignment.state === "reserved" &&
assignment.expiresAt && (
<p className="mt-1 text-xs text-content-muted">
<time dateTime={assignment.expiresAt}>
{getTournamentCodeExpiryLabel(
assignment.expiresAt,
now,
)}
</time>
</p>
<div className="min-w-0">
{assignment.code ? (
<AutoSizingCodeField
label={`${seriesLabel} ${assignment.ordinal}세트 토너먼트 코드`}
value={assignment.code}
/>
) : (
<p className="text-sm font-bold text-content-muted">
발급되면 이곳에서 복사할 수 있습니다.
</p>
)}
{assignment.code &&
assignment.state === "reserved" &&
assignment.expiresAt && (
<p className="mt-1 text-xs text-content-muted">
<time dateTime={assignment.expiresAt}>
{getTournamentCodeExpiryLabel(
assignment.expiresAt,
now,
)}
</div>
</time>
</p>
)}
</div>
<div className="flex flex-wrap items-center gap-2 md:justify-end">
<span
className={`border-l-2 px-2 py-1 text-xs font-bold ${CODE_TONE_CLASS[presentation.tone]}`}
role="status"
aria-live="polite"
aria-atomic="true"
>
{presentation.label}
</span>
{assignment.code && assignment.state === "reserved" && (
<button
type="button"
className="inline-flex min-h-11 items-center justify-center gap-1.5 border border-base-content/20 bg-base-100 px-3 text-sm font-bold text-base-content hover:border-primary/50 hover:bg-primary/5 focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-70"
aria-label={
presentation.canCopy
? getTournamentCodeCopyLabel(assignment, seriesLabel)
: `${seriesLabel} ${assignment.ordinal}세트 토너먼트 코드 만료됨`
}
disabled={!presentation.canCopy || copyingSlotId !== null}
onClick={() => void handleCopy(assignment)}
>
{!presentation.canCopy ? null : isCopying ? (
<LoaderCircle
className="h-4 w-4 animate-spin motion-reduce:animate-none"
aria-hidden="true"
/>
) : copied ? (
<Check className="h-4 w-4" aria-hidden="true" />
) : (
<Copy className="h-4 w-4" aria-hidden="true" />
)}
{!presentation.canCopy
? "복사 불가"
: isCopying
? "복사 중"
: copied
? "복사됨"
: "복사"}
</button>
)}
</div>
</li>
);
<div className="flex min-w-20 justify-end">
{assignment.code && assignment.state === "reserved" && (
<button
type="button"
className="inline-flex min-h-11 min-w-20 items-center justify-center gap-1.5 rounded-field border border-base-content/20 bg-base-100 px-3 text-sm font-bold text-base-content hover:border-primary/50 hover:bg-primary/5 focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-70"
aria-label={
presentation.canCopy
? getTournamentCodeCopyLabel(assignment, seriesLabel)
: `${seriesLabel} ${assignment.ordinal}세트 토너먼트 코드 만료됨`
}
disabled={!presentation.canCopy || copyingSlotId !== null}
onClick={() => void handleCopy(assignment)}
>
{!presentation.canCopy ? null : isCopying ? (
<LoaderCircle
className="h-4 w-4 animate-spin motion-reduce:animate-none"
aria-hidden="true"
/>
) : copied ? (
<Check className="h-4 w-4" aria-hidden="true" />
) : (
<Copy className="h-4 w-4" aria-hidden="true" />
)}
{!presentation.canCopy
? "복사 불가"
: isCopying
? "복사 중"
: copied
? "복사됨"
: "복사"}
</button>
)}
</div>
</li>
);
}
return (
@@ -197,22 +196,13 @@ export function TeamTournamentCodes({
className="border-t border-base-content/10 bg-sunken/50"
aria-label={`${seriesLabel} 토너먼트 코드`}
>
<div className="px-4 pt-3 sm:px-5">
<div className="flex items-center justify-between gap-3 border-b border-line px-4 py-3 sm:px-5">
<h4 className="text-sm font-bold">토너먼트 코드</h4>
<span className="text-xs text-content-muted">{assignments.length}세트</span>
</div>
<ol>
{renderAssignment(nextAssignment)}
<ol className="divide-y divide-line">
{assignments.map(renderAssignment)}
</ol>
{otherAssignments.length > 0 && (
<details className="border-t border-line">
<summary className="cursor-pointer px-4 py-3 text-sm font-semibold hover:bg-sunken sm:px-5">
다른 세트 코드 · {otherAssignments.length}개
</summary>
<ol className="divide-y divide-line border-t border-line">
{otherAssignments.map(renderAssignment)}
</ol>
</details>
)}
{feedback && (
<p
@@ -193,10 +193,9 @@ export function getSeriesHistoryResultLabel(
export function getSeriesHistoryRecordLabel(
series: CompetitionSeriesHistorySeries,
gameCount: number,
expanded: boolean,
): string {
if (gameCount > 0) {
return expanded ? "게임 상세 접기" : `게임 상세 (${gameCount})`;
return `게임 기록 ${gameCount}개`;
}
if (
series.status === "inactive" ||
@@ -0,0 +1,288 @@
import {
ArrowRight,
CalendarDays,
ChevronRight,
Clock3,
Info,
Users,
} from "lucide-react";
import type { SeriesProjection } from "@lolympus/contracts";
import type { ApiInternalMatchCard } from "../../api/types";
import pixelMedal from "../../assets/pixel-medal-first.svg";
import { formatOfficialMatchResult } from "../../lib/internal-stats-presentation";
import {
getSeriesHistoryResultLabel,
shouldDisplaySeriesHistoryScore,
} from "../competition/competition-series-history";
import { StatsLink } from "./StatsShared";
import { statsDate, statsDuration } from "./stats-navigation";
import { statsGroups } from "./stats-model";
function statsFormat(match: ApiInternalMatchCard) {
const result = match.resultPresentation;
if (result?.type !== "official")
return match.teams.length === 2 ? "두 팀 내전" : "내전 기록";
return {
"paired-series": "두 팀 내전",
"double-elimination": "더블 엘리미네이션",
"round-robin": "리그전",
}[result.formatType];
}
function seriesLabel(series: SeriesProjection | undefined) {
if (!series) return "공식 시리즈 정보 없음";
if (series.stage.type === "pair")
return series.rule.type === "first-to"
? `${series.rule.winsRequired}선승 시리즈`
: `${series.rule.gameCount}세트 시리즈`;
return `${{ upper: "승자조", lower: "패자조", "grand-final": "최종 결승", "reset-final": "결승 재경기", "round-robin": "리그" }[series.stage.type]}${series.stage.roundNumber ? ` ${series.stage.roundNumber}라운드` : ""}`;
}
export function StatsEventOverview({ match }: { match: ApiInternalMatchCard }) {
const analyzed = match.games.every(
(g) => g.analysisAvailability !== undefined,
)
? match.games.filter((g) => g.analysisAvailability === "available").length
: "—";
return (
<div className="is-event-overview">
<div className="is-event-meta">
<span>
<CalendarDays size={14} />
<time dateTime={match.scheduledAt}>
{statsDate(match.scheduledAt)}{" "}
{new Intl.DateTimeFormat("ko-KR", {
hour: "2-digit",
minute: "2-digit",
hour12: false,
timeZone: "Asia/Seoul",
}).format(new Date(match.scheduledAt))}
</time>
</span>
<span>
<Users size={14} />
{match.teams.length}팀 ·{" "}
{match.teams.reduce((n, t) => n + t.members.length, 0)}명
</span>
<span>{match.games.length}세트 결과</span>
<span className="is-analysis-count">{analyzed}세트 분석 가능</span>
</div>
<span className="is-champion-label">
<img src={pixelMedal} alt="" className="size-4 shrink-0 [image-rendering:pixelated]" />
<strong>{formatOfficialMatchResult(match.resultPresentation)}</strong>
</span>
</div>
);
}
export function StatsSeries({
match,
gameHref,
}: {
match: ApiInternalMatchCard;
gameHref: (number: number) => string;
}) {
const team = (index: number) =>
match.teams.find((t) => t.teamIndex === index)?.name ?? `${index}팀`;
const officialTeam = (id: string | null) =>
match.teams.find((t) => t.teamId === id)?.name ??
(id ? "팀 미확인" : "상대 미정");
return (
<div className="is-series-grid">
{statsGroups(match).map(({ id, series, games }) => {
const first = games[0],
label = seriesLabel(series);
const [a, b] = series?.entries ?? [];
const score = series && shouldDisplaySeriesHistoryScore(series);
const winner =
series?.status === "completed" && series.outcome.type !== "draw"
? series.outcome.winnerTeamId
: null;
return (
<section className="is-series-group" key={id} aria-label={label}>
<header>
<span>{label}</span>
<span>
{games.length}세트
{series &&
score &&
games.length !== (a?.gameWins ?? 0) + (b?.gameWins ?? 0)
? " · 기간 내 기록"
: ""}
</span>
</header>
<div className="is-matchup">
<strong
className={winner && winner === a?.teamId ? "is-winner" : ""}
>
{a
? officialTeam(a.teamId)
: first
? team(first.blueTeamIndex)
: "팀 미확인"}
</strong>
<span className="is-score">
{score ? (
<>
<b>{a?.gameWins}</b>
<i>:</i>
<b>{b?.gameWins}</b>
</>
) : series ? (
(getSeriesHistoryResultLabel(series) ?? "VS")
) : (
"VS"
)}
</span>
<strong
className={winner && winner === b?.teamId ? "is-winner" : ""}
>
{b
? officialTeam(b.teamId)
: first
? team(first.redTeamIndex)
: "팀 미확인"}
</strong>
</div>
<ul>
{games.map((game) => (
<li key={game.gameNumber}>
<span className="is-set-number">
{game.ordinal ?? game.gameNumber}세트
<small>전체 #{game.gameNumber}</small>
</span>
<span className="is-set-winner">
{game.winnerTeamIndex !== null ? (
<>
<span className="is-win-badge">승</span>
{team(game.winnerTeamIndex)}
</>
) : (
"결과 미확정"
)}
</span>
<span className="is-duration">
<Clock3 size={12} />
{statsDuration(game.gameDuration)}
</span>
<StatsLink
className={`is-analysis-link ${game.analysisAvailability !== "available" ? "is-unavailable" : ""}`}
to={gameHref(game.gameNumber)}
data-return-id={`set-${match.matchId}-${game.gameNumber}`}
aria-label={`${match.title} 전체 ${game.gameNumber}세트 ${game.analysisAvailability === "missing" ? "원본 상태 확인" : "상세 분석"}`}
>
{game.analysisAvailability === "missing"
? "원본 없음"
: game.analysisAvailability === "pending"
? "준비 중"
: "분석"}
{game.analysisAvailability === "missing" ? (
<Info size={12} />
) : (
<ChevronRight size={13} />
)}
</StatsLink>
</li>
))}
</ul>
{games.length === 0 && (
<p className="is-muted">
{series && getSeriesHistoryResultLabel(series)} · 기록된 세트
없음
</p>
)}
</section>
);
})}
</div>
);
}
export function StatsEvent({
match,
eventHref,
gameHref,
}: {
match: ApiInternalMatchCard;
eventHref: string;
gameHref: (number: number) => string;
}) {
return (
<article className="is-event-section" id={`event-${match.matchId}`}>
<header>
<div>
<div className="is-event-kicker">
<span>{statsFormat(match)}</span>
{Boolean(match.series?.length) && (
<span>{match.series!.length}개 시리즈</span>
)}
</div>
<h3>
<StatsLink to={eventHref} data-return-id={`event-${match.matchId}`}>
{match.title}
<ChevronRight size={18} />
</StatsLink>
</h3>
</div>
<StatsLink
className="is-text-link is-event-detail-link"
to={eventHref}
data-return-id={`event-detail-${match.matchId}`}
>
전체 기록
<ArrowRight size={15} />
</StatsLink>
</header>
<StatsEventOverview match={match} />
<StatsSeries match={match} gameHref={gameHref} />
{match.games.length === 0 && (
<p className="is-event-empty is-muted">
기록된 세트가 없습니다. 전체 기록에서 공식 결과를 확인할 수 있습니다.
</p>
)}
</article>
);
}
export function StatsEventJump({
matches,
}: {
matches: ApiInternalMatchCard[];
}) {
return (
<nav className="is-event-jump" aria-label="내전 바로가기">
<div className="is-jump-desktop">
<p>
<CalendarDays size={15} /> 내전 바로가기
</p>
{matches.map((m) => (
<a href={`#event-${m.matchId}`} key={m.matchId}>
<span>{statsDate(m.scheduledAt)}</span>
<strong>{m.title}</strong>
<small>{statsFormat(m)}</small>
</a>
))}
</div>
<label className="is-jump-mobile">
<CalendarDays size={16} />
<span>내전 이동</span>
<select
aria-label="내전 바로가기"
defaultValue=""
onChange={(e) =>
document.getElementById(`event-${e.target.value}`)?.scrollIntoView({
behavior: matchMedia("(prefers-reduced-motion: reduce)").matches
? "instant"
: "smooth",
block: "start",
})
}
>
<option value="" disabled>
날짜로 바로가기
</option>
{matches.map((m) => (
<option key={m.matchId} value={m.matchId}>
{statsDate(m.scheduledAt)} · {m.title}
</option>
))}
</select>
</label>
</nav>
);
}
@@ -0,0 +1,200 @@
import { ArrowDown, ArrowDownUp, ArrowRight, Info } from "lucide-react";
import type {
ApiLeaderboardRow,
DdragonManifest,
RiotLane,
} from "../../api/types";
import { getMainLane } from "../../lib/internal-stats-presentation";
import { profileIconUrl } from "../../lib/ddragon";
import { LANE_LABELS } from "../../lib/riot-history";
import { StatsChampion, StatsLink } from "./StatsShared";
import { STATS_SORTS, type StatsSort } from "./stats-model";
export function StatsLeaderboard({
rows,
minimum,
lane,
sort,
direction,
onSort,
playerHref,
participationHref,
manifest,
}: {
rows: Array<ApiLeaderboardRow & { rank: number }>;
minimum: number;
lane?: RiotLane;
sort: StatsSort;
direction: "asc" | "desc";
onSort: (key: StatsSort) => void;
playerHref: (id: string) => string;
participationHref: (id: string) => string;
manifest?: DdragonManifest;
}) {
const metric = (key: StatsSort, label: string) => (
<th
scope="col"
aria-sort={
sort === key
? direction === "desc"
? "descending"
: "ascending"
: "none"
}
>
<button
className={sort === key ? "is-sorted" : ""}
onClick={() => onSort(key)}
>
{label}
{sort === key ? (
<ArrowDown
size={13}
className={direction === "asc" ? "is-arrow-up" : ""}
/>
) : (
<ArrowDownUp size={12} />
)}
</button>
</th>
);
return (
<>
<p className="is-table-hint">
<ArrowRight size={14} />
옆으로 이동하면 모든 지표를 볼 수 있어요. 선수 이름은 고정됩니다.
</p>
<div
className="is-table-scroll"
role="region"
tabIndex={0}
aria-label="선수 순위표, 좌우 방향키로 지표 이동"
>
<table className="is-leaderboard">
<caption className="sr-only">
{lane ? LANE_LABELS[lane] : "전체 포지션"} · {STATS_SORTS[sort]}{" "}
{direction === "desc" ? "높은" : "낮은"} 순 · 최소 {minimum}판
</caption>
<colgroup>
<col className="is-col-rank" />
<col className="is-col-player" />
<col className="is-col-win" />
<col className="is-col-games" />
<col className="is-col-kda" />
<col className="is-col-champions" />
<col />
<col />
<col />
</colgroup>
<thead>
<tr>
<th scope="col" className="is-sticky-rank">
순위
</th>
<th scope="col" className="is-sticky-player">
선수
</th>
{metric("winRate", "승률")}
{metric("games", "판수")}
{metric("kda", "KDA")}
<th scope="col">주 챔피언</th>
{metric("avgGoldPerMin", "GPM")}
{metric("avgKillParticipation", "킬 관여")}
{metric("avgCsPerMin", "CS/분")}
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr
key={row.userId}
className={row.games < minimum ? "is-under-qualified" : ""}
>
<td className="is-sticky-rank">
<span className="is-rank-number">{row.rank}</span>
</td>
<th scope="row" className="is-sticky-player">
<div className="is-player-identity">
<img
className="is-champion"
src={profileIconUrl(manifest, row.profileIconId)}
alt=""
loading="lazy"
/>
<div>
<StatsLink
to={playerHref(row.userId)}
data-return-id={`player-${row.userId}`}
>
{row.summonerName}
</StatsLink>
<small>
{LANE_LABELS[lane ?? getMainLane(row.byLane) ?? ""] ??
"포지션 미확인"}
<span>·</span>
<StatsLink
to={participationHref(row.userId)}
data-return-id={`participation-${row.userId}`}
>
참가 내전
</StatsLink>
</small>
{row.games < minimum && (
<span className="is-sample-badge">기준 미달</span>
)}
</div>
</div>
</th>
<td>
<strong className={row.winRate >= 50 ? "is-blue" : ""}>
{row.winRate}
<small>%</small>
</strong>
<div className="is-win-track" aria-hidden="true">
<span style={{ width: `${row.winRate}%` }} />
</div>
</td>
<td>
<strong>{row.games}</strong>
<small className="is-win-loss">
{row.wins}승 {row.losses}패
</small>
</td>
<td>
<strong className={row.kda >= 3 ? "is-green" : ""}>
{row.kda.toFixed(2)}
</strong>
</td>
<td>
<div className="is-champion-list">
{row.topChampions.map((c) => (
<span key={c.championId}>
<StatsChampion
id={c.championId}
manifest={manifest}
size="small"
/>
<small>{c.games}</small>
</span>
))}
</div>
</td>
<td>{row.avgGoldPerMin}</td>
<td>{row.avgKillParticipation}%</td>
<td>{row.avgCsPerMin}</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="is-table-footnote">
<Info size={14} />
<p>
KDA는 (킬 + 어시스트) ÷ 데스, GPM은 분당 골드입니다.{" "}
{lane &&
`${LANE_LABELS[lane]}로 플레이한 경기의 모든 지표를 다시 집계합니다. `}
검색해도 전체 순위는 유지됩니다.
</p>
</div>
</>
);
}
@@ -0,0 +1,181 @@
import {
useEffect,
useState,
type ComponentProps,
type ReactNode,
} from "react";
import { Link } from "react-router";
import {
ArrowLeft,
Check,
Copy,
LoaderCircle,
Search,
ShieldAlert,
} from "lucide-react";
import type {
ApiHistorySeason,
DdragonManifest,
RiotLane,
} from "../../api/types";
import { championDisplayName, championIconUrl } from "../../lib/ddragon";
import { LANE_LABELS } from "../../lib/riot-history";
import "./internal-stats.css";
import { STATS_LANES, rememberStatsVisit } from "./stats-navigation";
export function StatsLink(props: ComponentProps<typeof Link>) {
return (
<Link
{...props}
onClick={(event) => {
rememberStatsVisit();
props.onClick?.(event);
}}
/>
);
}
export function StatsBack({
to,
children = "내전 전적으로 돌아가기",
}: {
to: string;
children?: ReactNode;
}) {
return (
<StatsLink className="is-back-link" to={to}>
<ArrowLeft size={16} />
{children}
</StatsLink>
);
}
export function StatsFeedback({
type,
title,
children,
action,
}: {
type: "empty" | "error" | "loading";
title: string;
children?: ReactNode;
action?: ReactNode;
}) {
const Icon =
type === "loading" ? LoaderCircle : type === "error" ? ShieldAlert : Search;
return (
<section
className={`is-feedback is-feedback-${type}`}
role={type === "error" ? "alert" : "status"}
>
<Icon size={26} aria-hidden="true" />
<h2>{title}</h2>
{children && <p>{children}</p>}
{action && <div className="is-feedback-actions">{action}</div>}
</section>
);
}
export function StatsChampion({
id,
manifest,
size = "normal",
}: {
id: number;
manifest?: DdragonManifest;
size?: "small" | "normal" | "large";
}) {
const src = championIconUrl(manifest, id),
name = championDisplayName(manifest, id) ?? "챔피언";
return src ? (
<img
className={`is-champion is-champion-${size}`}
src={src}
alt={name}
title={name}
loading="lazy"
/>
) : (
<span
className={`is-champion is-champion-${size}`}
aria-label="챔피언 이미지 없음"
/>
);
}
export function StatsSeasonControls({
value,
seasons,
onChange,
label,
}: {
value: string;
seasons?: ApiHistorySeason[];
onChange: (value: string) => void;
label?: string;
}) {
const [notice, setNotice] = useState("");
useEffect(() => {
if (!notice) return;
const timer = setTimeout(() => setNotice(""), 3000);
return () => clearTimeout(timer);
}, [notice]);
return (
<div className="is-page-actions">
<button
className="is-icon-button"
aria-label="현재 전적 링크 복사"
onClick={() =>
void navigator.clipboard.writeText(location.href).then(
() => setNotice("현재 조건이 포함된 링크를 복사했습니다."),
() => setNotice("주소 표시줄의 링크를 복사해 주세요."),
)
}
>
{notice ? <Check size={17} /> : <Copy size={17} />}
</button>
<label className="is-season-select">
<span>집계 시즌</span>
<select value={value} onChange={(e) => onChange(e.target.value)}>
<option value="current">현재 시즌</option>
{seasons
?.filter((s) => !["current", "all"].includes(s.id))
.map((s) => (
<option key={s.id} value={s.id}>
{s.label}
</option>
))}
<option value="all">전체 시즌</option>
{!["current", "all"].includes(value) &&
!seasons?.some((s) => s.id === value) && (
<option value={value}>{label ?? value}</option>
)}
</select>
</label>
<div className="is-announcement" role="status">
{notice}
</div>
</div>
);
}
export function StatsLaneSelect({
value,
onChange,
}: {
value?: RiotLane;
onChange: (value: string) => void;
}) {
return (
<label className="is-select">
<span className="sr-only">플레이 포지션</span>
<select
aria-label="플레이 포지션"
value={value ?? ""}
onChange={(e) => onChange(e.target.value)}
>
<option value="">전체 포지션</option>
{STATS_LANES.map((lane) => (
<option key={lane} value={lane}>
{LANE_LABELS[lane]}
</option>
))}
</select>
</label>
);
}
@@ -0,0 +1,140 @@
import { ChevronRight, Trophy } from "lucide-react";
import type {
ApiLeaderHighlight,
ApiTeamInsightsResponse,
} from "../../api/types";
import { StatsLink } from "./StatsShared";
import { statsPeriod } from "./stats-navigation";
export function StatsSummary({
data,
href,
}: {
data: ApiTeamInsightsResponse;
href: (highlight: ApiLeaderHighlight) => string;
}) {
const total = data.totals,
rate = data.sideWinRate.confirmed;
const records = [
{
label: "평균 KDA",
value: data.topKda,
scope: `시즌 최고 · 최소 ${data.minGamesThreshold}판`,
suffix: "",
},
{
label: "누적 킬",
value: data.mostKills,
scope: "시즌 누적",
suffix: "킬",
},
{
label: "분당 골드",
value: data.topTeamGpm,
scope: "단일 경기 최고",
suffix: "",
},
{
label: "평균 킬 관여",
value: data.topKillParticipation,
scope: `시즌 최고 · 최소 ${data.minGamesThreshold}판`,
suffix: "%",
},
{
label: "평균 분당 CS",
value: data.bestFarm,
scope: `시즌 최고 · 최소 ${data.minGamesThreshold}판`,
suffix: "",
},
];
return (
<section className="is-season-summary" aria-label="커뮤니티 전체 시즌 요약">
<div className="is-summary-topline">
<span>
<span className="is-current-dot" />
{data.season.label} 요약
</span>
<span className="is-muted">
커뮤니티 전체 · {statsPeriod(data.season)}
</span>
</div>
<div className="is-summary-metrics">
<div>
<span>진행한 내전</span>
<strong>
{total?.matches ?? "—"}
<small>회</small>
</strong>
</div>
<div>
<span>기록된 세트</span>
<strong>
{total?.games ?? "—"}
<small>판</small>
</strong>
</div>
<div>
<span>참가 선수</span>
<strong>
{total?.players ?? "—"}
<small>명</small>
</strong>
</div>
<div className="is-side-rate">
<span>
진영 승률<small>{rate?.sampleSize ?? 0}세트 기준</small>
</span>
<div>
<strong className="is-blue">
{rate?.sampleSize ? rate.blue : "—"}
<small>%</small>
</strong>
<span>BLUE / RED</span>
<strong className="is-red">
{rate?.sampleSize ? rate.red : "—"}
<small>%</small>
</strong>
</div>
<div className="is-side-track" aria-hidden="true">
<span style={{ width: `${rate?.blue ?? 50}%` }} />
</div>
</div>
</div>
<div className="is-records-heading">
<Trophy size={14} />
<h2>시즌 기록</h2>
<span>
분석 가능한 {total?.analyzedGames ?? "—"}세트 기준 · 검색 조건과 별도
집계
</span>
</div>
<div className="is-records">
{records.map((record) => (
<div className="is-record" key={record.label}>
<p>
{record.label}
<span>{record.scope}</span>
</p>
<div>
<strong>
{record.value?.metric ?? "—"}
<small>{record.suffix}</small>
</strong>
{record.value ? (
<StatsLink
to={href(record.value)}
data-return-id={`record-${record.label}`}
aria-label={`${record.label} ${record.value.summonerName} ${record.value.isSingleGame ? "근거 경기" : "시즌 전적"}`}
>
{record.value.summonerName}
<ChevronRight size={13} />
</StatsLink>
) : (
<span className="is-muted">기록 없음</span>
)}
</div>
</div>
))}
</div>
</section>
);
}
@@ -0,0 +1,50 @@
# 내전 전적 제품 반영 · 2026-11-11
승인된 `src/design-previews/internal-stats` 시안의 정보 구조와 스타일을 실제 라우트와 API에 반영했다. 시안의 fixture는 제품 코드에서 사용하지 않는다. 모든 세트는 표시하며 접기/아코디언을 추가하지 않았다.
## 반영 범위
- 시즌 전체 요약과 5개 기록, 최근 내전/선수 순위의 별도 검색, 날짜·유형·참가 선수 조건, 조건 초기화, 이전 내전 더 보기.
- 공식 `seriesId`와 세트 순번으로 대결을 묶는다. 같은 두 팀의 재대결을 합치거나 누락된 라운드를 추정하지 않는다. 공식 경기 결과와 원본 분석 가능 상태를 구분한다.
- 6개 지표 정렬, 최소 0/5/10/20판, 기준 충족 선수만 보기, 검색 후에도 전체 순위 유지, 모바일 선수 이름 고정과 표 내부 가로 스크롤.
- 개인 전적 라우트, 시즌/포지션/챔피언별 집계와 세트 목록, 참가 내전 및 상세 분석 연결. URL에 조건과 로드한 페이지 수를 보존한다.
- 상세 분석의 기존 타임라인·스코어보드·라인전·룬/빌드는 유지하고 헤더, 선수 링크, 분석 탭 URL, 복귀 경로를 연결했다. 복귀 시 스크롤과 포커스를 복원하며 중첩 경로의 이전 링크는 세션에 보관한다.
- 실패/빈 결과/로딩/원본 없음 상태, 재시도와 복귀 동작, 키보드 탭 이동, 감소된 모션 설정을 지원한다.
## API 계약
기존 공개 읽기 API를 확장했다. 스키마 마이그레이션이나 새 서비스 의존성은 없다.
| 경로 (`/communities/:communityId` 기준) | 변경 |
| --- | --- |
| `/internal-stats/matches` | 내전명·팀명·선수명 검색, 공식 series/팀 ID와 세트 순번·분석 상태 반환. 날짜 범위와 커서 조건을 함께 유지한다. |
| `/internal-stats/leaderboard` | `lane=TOP/JUNGLE/MIDDLE/BOTTOM/UTILITY` 검증, 해당 경기만으로 모든 지표 재집계. lane별 캐시 분리. |
| `/internal-stats/team-insights` | `totals.matches/games/analyzedGames/players`, 단일 경기 기록의 `internalMatchId/gameNumber` 추가. |
| `/users/:userId/internal-history` | 포지션 필터, `playerStats`, `internalMatchTitle`. 챔피언 선택 목록은 선택한 챔피언으로 축소하지 않는다. |
| `/internal-stats/match/:matchId` | 목록과 같은 공식 시리즈 식별자 및 분석 상태 제공. 상세 응답 캐시 버전 9. |
날짜만 받은 경우 한국 시간 00:00:00.000~23:59:59.999로 해석하며 시즌 범위와 교집합을 사용한다. 잘못된 날짜와 역전된 범위는 400이다. 원본이 없는 세트는 공식 결과/세트 수에는 남기고 KDA 등 상세 지표에서는 제외한다. API 응답 캐시의 presentation 버전을 변경해 예전 응답과 분리했다.
## 검증
- 전적 API 8개 suite, 60개 테스트 통과. 새 테스트는 실제 Nest HTTP 라우트에 Supertest 요청을 보내 포지션별 응답과 400을 확인한다. DB/캐시 경계에는 fixture를 사용했다.
- 웹 전체 테스트 186개 통과. 제품용 추가 테스트는 자격 판수 우선 정렬, 원본 배열 불변, 공식 재대결/순번, 검색·시즌 조건을 담은 복귀 URL을 검증한다.
- 웹 TypeScript/변경 범위 ESLint, API TypeScript/변경 범위 ESLint 통과. API build와 웹 staging build 통과. 웹에는 기존 큰 번들 경고가 남는다.
- 기존 개발 서버 데이터를 연결한 브라우저에서 검색 `귤`, KDA 정렬, 순위 1/45 유지, 개인 화면 이동 후 검색·정렬·선수 포커스 복귀를 확인했다.
- 390px 모바일에서 문서 폭 375px=내용 폭 375px(스크롤바 제외), 표 내부 780px 스크롤과 sticky 선수 열 확인. 데스크톱도 문서 가로 넘침 없음.
- 상세 API 실패 시 모바일에 복귀 링크와 재시도 버튼이 표시된다. 변경 중 HMR에서 발생한 hook 순서 경고는 최종 새로고침 뒤 추가 발생하지 않았다.
## 증거와 검증 한계
화면 자료: `C:/Users/park/.codex/visualizations/2026/11/11/01a1c9d5-e028-75a0-8b1b-f70126da1d08/internal-stats-production/`
- `01-desktop-ranking.jpg`: 조건과 포커스 복귀.
- `02-mobile-ranking.jpg`: 고정 선수 열과 가로 스크롤.
- `03-mobile-error.jpg`: 상세 요청 실패에서 복귀/재시도.
- `04-final-desktop.jpg`: 최종 새로고침한 화면.
현재 개발 서버 API는 이번 변경을 배포하지 않은 상태다. 새 `totals`, `series`, `playerStats`와 포지션 집계의 실제 서버 검증은 미완료이며, 화면 자료의 `—`는 새 집계 항목이 없는 응답이다. 상세 분석 요청도 실패하여 실제 데이터 차트의 최종 시각 검증은 배포 후 필요하다. 이 항목들은 fixture HTTP 계약 테스트 통과와 구분한다.
사용자의 최종 지시에 따라 커밋, main 푸시, 배포를 수행하지 않았다. 배포 후에는 시즌 요약 수치, 포지션별 모든 지표, 공식 시리즈·원본 없는 세트, 개인 전적→분석→목록 복귀를 실제 데이터로 확인한다.
final result: local checks passed; staging integration pending deployment
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,54 @@
import type { ApiInternalMatchCard, ApiLeaderboardRow } from "../../api/types";
export const STATS_SORTS = {
games: "참여 경기 수",
winRate: "승률",
kda: "KDA",
avgGoldPerMin: "분당 골드",
avgKillParticipation: "킬 관여율",
avgCsPerMin: "분당 CS",
};
export type StatsSort = keyof typeof STATS_SORTS;
export function parseStatsSort(value: string | null): StatsSort {
return value && Object.hasOwn(STATS_SORTS, value)
? (value as StatsSort)
: "games";
}
export function sortStatsRows(
rows: readonly ApiLeaderboardRow[],
sort: StatsSort,
minimum: number,
direction: "asc" | "desc",
) {
return [...rows]
.sort(
(a, b) =>
Number(b.games >= minimum) - Number(a.games >= minimum) ||
(a[sort] - b[sort]) * (direction === "desc" ? -1 : 1) ||
b.games - a.games ||
a.summonerName.localeCompare(b.summonerName, "ko") ||
a.userId.localeCompare(b.userId),
)
.map((row, i) => ({ ...row, rank: i + 1 }));
}
export function statsGroups(match: ApiInternalMatchCard) {
const series = match.series ?? [];
const known = new Set<string>(series.map((s) => s.seriesId));
return [
...series.map((s) => ({
id: s.seriesId,
series: s,
games: match.games
.filter((g) => g.seriesId === s.seriesId)
.sort(
(a, b) => (a.ordinal ?? a.gameNumber) - (b.ordinal ?? b.gameNumber),
),
})),
...match.games
.filter((g) => !g.seriesId || !known.has(g.seriesId))
.map((g) => ({
id: `game-${g.gameNumber}`,
series: undefined,
games: [g],
})),
];
}
@@ -0,0 +1,137 @@
import { useLayoutEffect, useRef } from "react";
import { useLocation, useSearchParams } from "react-router";
import type { ApiHistorySeason, RiotLane } from "../../api/types";
export const STATS_LANES: RiotLane[] = [
"TOP",
"JUNGLE",
"MIDDLE",
"BOTTOM",
"UTILITY",
];
export function parseStatsLane(value: string | null): RiotLane | undefined {
return STATS_LANES.includes(value as RiotLane)
? (value as RiotLane)
: undefined;
}
export function statsRoot(cid: string) {
return `/communities/${cid}/internal-stats`;
}
export function statsDate(value: string) {
return new Intl.DateTimeFormat("ko-KR", {
month: "numeric",
day: "numeric",
weekday: "short",
timeZone: "Asia/Seoul",
}).format(new Date(value));
}
export function statsDuration(seconds: number) {
return seconds > 0
? `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`
: "시간 미확인";
}
export function statsPeriod(season?: ApiHistorySeason) {
if (!season) return "시즌을 불러오는 중";
const date = (value: string) =>
new Intl.DateTimeFormat("ko-KR", {
year: "numeric",
month: "2-digit",
day: "2-digit",
timeZone: "Asia/Seoul",
}).format(new Date(value));
return season.startedAt
? `${date(season.startedAt)} — ${season.endedAt ? date(season.endedAt) : "현재"}`
: "전체 기록";
}
export function statsTarget(
path: string,
params: URLSearchParams,
returnTo?: string,
) {
const query = new URLSearchParams();
for (const key of ["seasonId", "lane", "championId"]) {
const value = params.get(key);
if (value) query.set(key, value);
}
if (returnTo) {
// Keep the immediate parent in the URL. Its own return link is restored
// from the saved visit, so repeated player/game hops cannot grow the URL.
query.set("returnTo", visitKey(returnTo));
}
return `${path}${query.size ? `?${query}` : ""}`;
}
function visitKey(value: string) {
const url = new URL(value, "https://internal-stats.local");
url.searchParams.delete("returnTo");
return url.pathname + url.search;
}
export function rememberStatsVisit() {
const key = visitKey(location.pathname + location.search);
try {
const previous = JSON.parse(
sessionStorage.getItem(`internal-stats:${key}`) ?? "null",
);
sessionStorage.setItem(
`internal-stats:${key}`,
JSON.stringify({
y: scrollY,
focus: document.activeElement?.getAttribute("data-return-id"),
back:
new URLSearchParams(location.search).get("returnTo") ??
previous?.back,
}),
);
} catch {
/* Storage can be unavailable. */
}
}
export function useStatsRestoration(ready: boolean) {
const location = useLocation();
const previousPath = useRef<string | null>(null);
useLayoutEffect(() => {
if (!ready) return;
const changedPage = previousPath.current !== location.pathname;
previousPath.current = location.pathname;
let saved: { y: number; focus?: string } | null = null;
try {
saved = JSON.parse(
sessionStorage.getItem(
`internal-stats:${visitKey(location.pathname + location.search)}`,
) ?? "null",
);
} catch {
/* Ignore corrupt storage. */
}
const frame = requestAnimationFrame(() => {
if (saved && Number.isFinite(saved.y)) {
window.scrollTo({ top: saved.y, behavior: "instant" });
if (saved.focus)
document
.querySelector<HTMLElement>(
`[data-return-id="${CSS.escape(saved.focus)}"]`,
)
?.focus({ preventScroll: true });
} else if (changedPage) window.scrollTo({ top: 0, behavior: "instant" });
});
return () => cancelAnimationFrame(frame);
}, [location.pathname, location.search, ready]);
}
export function useStatsBack(fallback: string) {
const location = useLocation();
const [params] = useSearchParams();
let savedBack: unknown;
try {
savedBack = JSON.parse(
sessionStorage.getItem(
`internal-stats:${visitKey(location.pathname + location.search)}`,
) ?? "null",
)?.back;
} catch {
/* A direct visit can use the fallback without storage. */
}
const back = params.get("returnTo") ?? location.state?.backTo ?? savedBack;
return typeof back === "string" &&
/^\/(communities|users|match)\//.test(back) &&
!back.includes("\\")
? back
: fallback;
}