feat: add item tooltips to match history

This commit is contained in:
dahyeon committed 2026-06-26 23:07:06 -07:00
1 parent 38c2d1f1b4
commit 68afaf0cb8
8 files changed
+477 -49

No files matched your search

@@ -0,0 +1,102 @@
import { RedisService } from '../global/redis/redis.service';
import { RiotDdragonService } from './riot-ddragon.service';
function jsonResponse(payload: unknown): Response {
return {
ok: true,
json: jest.fn().mockResolvedValue(payload),
} as unknown as Response;
}
function makeRedisService() {
return {
getJson: jest.fn().mockResolvedValue(null),
setJson: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<RedisService>;
}
describe('RiotDdragonService', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('includes localized item metadata in the manifest', async () => {
const fetchMock = jest.fn(async (url: string) => {
if (url.endsWith('/api/versions.json')) {
return jsonResponse(['15.24.1']);
}
if (url.endsWith('/champion.json')) {
return jsonResponse({
data: {
Aatrox: { key: '266', id: 'Aatrox', name: '아트록스' },
},
});
}
if (url.endsWith('/summoner.json')) {
return jsonResponse({
data: {
SummonerFlash: { key: '4', id: 'SummonerFlash', name: '점멸' },
},
});
}
if (url.endsWith('/runesReforged.json')) {
return jsonResponse([]);
}
if (url.endsWith('/item.json')) {
return jsonResponse({
data: {
'1055': {
name: '도란의 검',
description:
'<mainText><stats>공격력 <attention>10</attention></stats></mainText>',
plaintext: '공격력과 체력을 올려줍니다.',
gold: {
base: 450,
total: 450,
sell: 180,
purchasable: true,
},
},
},
});
}
throw new Error(`Unexpected URL: ${url}`);
});
jest.spyOn(global, 'fetch').mockImplementation(fetchMock as typeof fetch);
const redis = makeRedisService();
const service = new RiotDdragonService(redis);
await expect(service.getManifest('ko_KR')).resolves.toMatchObject({
version: '15.24.1',
locale: 'ko_KR',
items: {
'1055': {
name: '도란의 검',
description:
'<mainText><stats>공격력 <attention>10</attention></stats></mainText>',
plaintext: '공격력과 체력을 올려줍니다.',
gold: {
base: 450,
total: 450,
sell: 180,
purchasable: true,
},
},
},
});
expect(fetchMock).toHaveBeenCalledWith(
expect.stringContaining('/15.24.1/data/ko_KR/item.json'),
expect.any(Object),
);
expect(redis.setJson).toHaveBeenCalledWith(
'ddragon:manifest:v4:ko_KR',
expect.objectContaining({
items: expect.objectContaining({
'1055': expect.objectContaining({ name: '도란의 검' }),
}),
}),
86_400,
);
});
});
@@ -5,7 +5,7 @@ const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com';
const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`; const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`;
const DEFAULT_LOCALE = 'ko_KR'; const DEFAULT_LOCALE = 'ko_KR';
const CACHE_TTL_SECONDS = 24 * 60 * 60; const CACHE_TTL_SECONDS = 24 * 60 * 60;
const CACHE_VERSION = 'v3'; const CACHE_VERSION = 'v4';
const FETCH_TIMEOUT_MS = 10_000; const FETCH_TIMEOUT_MS = 10_000;
export interface DdragonChampionEntry { export interface DdragonChampionEntry {
@@ -29,6 +29,18 @@ export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
slots: Array<{ runes: DdragonRuneEntry[] }>; slots: Array<{ runes: DdragonRuneEntry[] }>;
} }
export interface DdragonItemEntry {
name: string;
description: string;
plaintext: string;
gold: {
base: number;
total: number;
sell: number;
purchasable: boolean;
};
}
export interface DdragonManifest { export interface DdragonManifest {
version: string; version: string;
cdn: string; cdn: string;
@@ -36,6 +48,7 @@ export interface DdragonManifest {
champions: Record<string, DdragonChampionEntry>; champions: Record<string, DdragonChampionEntry>;
summonerSpells: Record<string, DdragonSummonerSpellEntry>; summonerSpells: Record<string, DdragonSummonerSpellEntry>;
runesReforged: DdragonRuneStyleEntry[]; runesReforged: DdragonRuneStyleEntry[];
items: Record<string, DdragonItemEntry>;
fetchedAt: string; fetchedAt: string;
} }
@@ -70,6 +83,22 @@ interface RuneStyleDataEntry extends RuneDataEntry {
slots?: Array<{ runes?: RuneDataEntry[] }>; slots?: Array<{ runes?: RuneDataEntry[] }>;
} }
interface ItemDataEntry {
name?: string;
description?: string;
plaintext?: string;
gold?: {
base?: number;
total?: number;
sell?: number;
purchasable?: boolean;
};
}
interface ItemDataResponse {
data: Record<string, ItemDataEntry>;
}
@Injectable() @Injectable()
export class RiotDdragonService { export class RiotDdragonService {
private readonly logger = new Logger(RiotDdragonService.name); private readonly logger = new Logger(RiotDdragonService.name);
@@ -102,10 +131,11 @@ export class RiotDdragonService {
private async buildManifest(locale: string): Promise<DdragonManifest> { private async buildManifest(locale: string): Promise<DdragonManifest> {
const version = await this.fetchLatestVersion(); const version = await this.fetchLatestVersion();
const [champions, summonerSpells, runesReforged] = await Promise.all([ const [champions, summonerSpells, runesReforged, items] = await Promise.all([
this.fetchChampionMap(version, locale), this.fetchChampionMap(version, locale),
this.fetchSummonerSpellMap(version, locale), this.fetchSummonerSpellMap(version, locale),
this.fetchRuneStyles(version, locale), this.fetchRuneStyles(version, locale),
this.fetchItemMap(version, locale),
]); ]);
return { return {
version, version,
@@ -114,6 +144,7 @@ export class RiotDdragonService {
champions, champions,
summonerSpells, summonerSpells,
runesReforged, runesReforged,
items,
fetchedAt: new Date().toISOString(), fetchedAt: new Date().toISOString(),
}; };
} }
@@ -200,6 +231,38 @@ export class RiotDdragonService {
})); }));
} }
private async fetchItemMap(
version: string,
locale: string,
): Promise<Record<string, DdragonItemEntry>> {
const url = `${DDRAGON_CDN}/${version}/data/${locale}/item.json`;
const payload = await this.fetchJson<ItemDataResponse>(url);
if (!payload || typeof payload !== 'object' || !payload.data) {
throw new Error(`ddragon item.json response is malformed (${url}).`);
}
const map: Record<string, DdragonItemEntry> = {};
for (const [itemId, entry] of Object.entries(payload.data)) {
if (!/^\d+$/.test(itemId) || typeof entry?.name !== 'string') {
continue;
}
map[itemId] = {
name: entry.name,
description:
typeof entry.description === 'string' ? entry.description : '',
plaintext: typeof entry.plaintext === 'string' ? entry.plaintext : '',
gold: {
base: numberOrZero(entry.gold?.base),
total: numberOrZero(entry.gold?.total),
sell: numberOrZero(entry.gold?.sell),
purchasable: entry.gold?.purchasable ?? false,
},
};
}
return map;
}
private async fetchJson<T>(url: string): Promise<T> { private async fetchJson<T>(url: string): Promise<T> {
const controller = new AbortController(); const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
@@ -245,6 +308,10 @@ function isRuneEntry(value: unknown): value is RuneDataEntry {
); );
} }
function numberOrZero(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
}
function manifestCacheKey(locale: string): string { function manifestCacheKey(locale: string): string {
return `ddragon:manifest:${CACHE_VERSION}:${locale}`; return `ddragon:manifest:${CACHE_VERSION}:${locale}`;
} }
+13
View File
@@ -495,6 +495,18 @@ export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
slots: Array<{ runes: DdragonRuneEntry[] }>; slots: Array<{ runes: DdragonRuneEntry[] }>;
} }
export interface DdragonItemEntry {
name: string;
description: string;
plaintext: string;
gold: {
base: number;
total: number;
sell: number;
purchasable: boolean;
};
}
export interface DdragonManifest { export interface DdragonManifest {
version: string; version: string;
cdn: string; cdn: string;
@@ -502,6 +514,7 @@ export interface DdragonManifest {
champions: Record<string, DdragonChampionEntry>; champions: Record<string, DdragonChampionEntry>;
summonerSpells: Record<string, DdragonSummonerSpellEntry>; summonerSpells: Record<string, DdragonSummonerSpellEntry>;
runesReforged: DdragonRuneStyleEntry[]; runesReforged: DdragonRuneStyleEntry[];
items: Record<string, DdragonItemEntry>;
fetchedAt: string; fetchedAt: string;
} }
+204
View File
@@ -0,0 +1,204 @@
import type { CSSProperties, RefObject } from "react";
import { useEffect, useId, useRef, useState } from "react";
import { createPortal } from "react-dom";
import type { DdragonManifest } from "../api/types";
import {
itemDetails,
itemDisplayName,
itemIconUrl,
safeDdragonDescriptionHtml,
} from "../lib/ddragon";
type TooltipPosition = {
left: number;
top: number;
width: number;
placement: "top" | "bottom";
};
type ItemIconProps = {
itemId: number;
manifest: DdragonManifest | null | undefined;
className?: string;
imageClassName?: string;
trinket?: boolean;
};
const VIEWPORT_MARGIN = 8;
const TOOLTIP_GAP = 8;
const TOOLTIP_WIDTH = 320;
export function ItemIcon({
itemId,
manifest,
className = "h-6 w-6",
imageClassName = "scale-[1.18]",
trinket = false,
}: ItemIconProps) {
const anchorRef = useRef<HTMLSpanElement>(null);
const tooltipId = useId();
const [open, setOpen] = useState(false);
const icon = itemIconUrl(manifest, itemId);
const hasItem = itemId > 0;
const itemName = itemDisplayName(manifest, itemId) ?? `아이템 ${itemId}`;
const slotTone = trinket
? "border-primary/25 bg-base-content/[0.04]"
: "border-base-content/5 bg-base-content/8";
return (
<span
ref={anchorRef}
className={`relative inline-flex shrink-0 ${className}`}
role={hasItem ? "img" : undefined}
tabIndex={hasItem ? 0 : undefined}
aria-label={hasItem ? itemName : "빈 아이템 슬롯"}
aria-describedby={hasItem && open ? tooltipId : undefined}
onBlur={() => setOpen(false)}
onFocus={() => hasItem && setOpen(true)}
onMouseEnter={() => hasItem && setOpen(true)}
onMouseLeave={() => setOpen(false)}
>
<span
className={`block h-full w-full overflow-hidden border ${slotTone}`}
aria-hidden="true"
>
{icon ? (
<img
src={icon}
alt=""
className={`h-full w-full object-cover ${imageClassName}`}
loading="lazy"
/>
) : null}
</span>
{hasItem && open ? (
<ItemTooltipPortal
id={tooltipId}
anchorRef={anchorRef}
itemId={itemId}
manifest={manifest}
/>
) : null}
</span>
);
}
function ItemTooltipPortal({
id,
anchorRef,
itemId,
manifest,
}: {
id: string;
anchorRef: RefObject<HTMLElement | null>;
itemId: number;
manifest: DdragonManifest | null | undefined;
}) {
const [position, setPosition] = useState<TooltipPosition | null>(null);
useEffect(() => {
function updatePosition() {
const anchor = anchorRef.current;
if (!anchor) return;
const rect = anchor.getBoundingClientRect();
const width = Math.min(
TOOLTIP_WIDTH,
window.innerWidth - VIEWPORT_MARGIN * 2,
);
const left = clamp(
rect.left + rect.width / 2 - width / 2,
VIEWPORT_MARGIN,
window.innerWidth - width - VIEWPORT_MARGIN,
);
const placement = rect.top > 260 ? "top" : "bottom";
setPosition({
left,
top:
placement === "top"
? rect.top - TOOLTIP_GAP
: rect.bottom + TOOLTIP_GAP,
width,
placement,
});
}
updatePosition();
window.addEventListener("resize", updatePosition);
window.addEventListener("scroll", updatePosition, true);
return () => {
window.removeEventListener("resize", updatePosition);
window.removeEventListener("scroll", updatePosition, true);
};
}, [anchorRef]);
if (typeof document === "undefined" || !position) return null;
const style: CSSProperties = {
left: position.left,
top: position.top,
width: position.width,
transform:
position.placement === "top" ? "translateY(-100%)" : undefined,
};
return createPortal(
<div
id={id}
role="tooltip"
style={style}
className="pointer-events-none fixed z-[1000] border border-base-content/20 bg-black px-3 py-3 text-xs leading-relaxed text-white shadow-2xl"
>
<ItemTooltipContent itemId={itemId} manifest={manifest} />
</div>,
document.body,
);
}
function ItemTooltipContent({
itemId,
manifest,
}: {
itemId: number;
manifest: DdragonManifest | null | undefined;
}) {
const item = itemDetails(manifest, itemId);
const descriptionHtml = item?.description
? safeDdragonDescriptionHtml(item.description)
: "";
return (
<div className="space-y-2">
<div className="font-black text-[#f0d878]">
{item?.name ?? `아이템 ${itemId}`}
</div>
{item?.plaintext ? (
<div className="font-bold text-white">{item.plaintext}</div>
) : null}
{descriptionHtml ? (
<div
className="space-y-1 text-white/80 [&_br]:block [&_br]:content-['']"
dangerouslySetInnerHTML={{ __html: descriptionHtml }}
/>
) : (
<div className="text-white/55">
아이템 상세 정보를 불러오는 중입니다.
</div>
)}
{item?.gold.total ? (
<div className="border-t border-white/10 pt-2 font-bold text-white">
가격:
<span className="text-[#f0d878]">{item.gold.total}</span>{" "}
<span className="text-[#f0d878]">
({item.gold.base || item.gold.total})
</span>
</div>
) : null}
</div>
);
}
function clamp(value: number, min: number, max: number) {
if (max < min) return min;
return Math.min(Math.max(value, min), max);
}
+56
View File
@@ -2,6 +2,25 @@ import type { DdragonManifest } from '../api/types';
const FALLBACK_VERSION = '15.24.1'; const FALLBACK_VERSION = '15.24.1';
const FALLBACK_CDN = 'https://ddragon.leagueoflegends.com/cdn'; const FALLBACK_CDN = 'https://ddragon.leagueoflegends.com/cdn';
const DDRAGON_DESCRIPTION_TAG_CLASSES: Record<string, string> = {
active: 'text-[#f0d878] font-semibold',
attention: 'text-[#f0d878] font-semibold',
flavorText: 'text-white/45 italic',
healing: 'text-emerald-300 font-semibold',
keywordMajor: 'text-[#f0d878] font-semibold',
keywordName: 'text-[#f0d878] font-semibold',
keywordStealth: 'text-violet-300 font-semibold',
mainText: 'text-white/80',
ornnBonus: 'text-[#f0d878] font-semibold',
passive: 'text-[#f0d878] font-semibold',
rarityGeneric: 'text-white/55',
rarityLegendary: 'text-[#f0d878] font-semibold',
rarityMythic: 'text-violet-300 font-semibold',
rules: 'text-white/45',
shield: 'text-sky-300 font-semibold',
stats: 'text-sky-200',
status: 'text-sky-300 font-semibold',
};
function cdn(manifest: DdragonManifest | null | undefined) { function cdn(manifest: DdragonManifest | null | undefined) {
return manifest?.cdn ?? FALLBACK_CDN; return manifest?.cdn ?? FALLBACK_CDN;
@@ -42,6 +61,34 @@ export function itemIconUrl(
return `${cdn(manifest)}/${version(manifest)}/img/item/${itemId}.png`; return `${cdn(manifest)}/${version(manifest)}/img/item/${itemId}.png`;
} }
export function itemDetails(
manifest: DdragonManifest | null | undefined,
itemId: number,
) {
if (!itemId) return null;
return manifest?.items?.[String(itemId)] ?? null;
}
export function itemDisplayName(
manifest: DdragonManifest | null | undefined,
itemId: number,
) {
return itemDetails(manifest, itemId)?.name ?? null;
}
export function safeDdragonDescriptionHtml(description: string) {
const escaped = escapeHtml(description);
return escaped
.replace(/&lt;br\s*\/?&gt;/gi, '<br />')
.replace(/&lt;(\/?)([a-zA-Z][a-zA-Z0-9]*)(?:\s[\s\S]*?)?&gt;/g, (_match, closing, tag) => {
const normalizedTag = String(tag);
const className = DDRAGON_DESCRIPTION_TAG_CLASSES[normalizedTag];
if (!className) return '';
return closing ? '</span>' : `<span class="${className}">`;
})
.replace(/&lt;\/?[a-zA-Z][\s\S]*?&gt;/g, '');
}
export function summonerSpellIconUrl( export function summonerSpellIconUrl(
manifest: DdragonManifest | null | undefined, manifest: DdragonManifest | null | undefined,
spellId: number, spellId: number,
@@ -76,3 +123,12 @@ export function runeIconUrl(
) { ) {
return runeKeystoneIconUrl(manifest, runeId); return runeKeystoneIconUrl(manifest, runeId);
} }
function escapeHtml(value: string) {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
+11 -14
View File
@@ -5,7 +5,6 @@ import { DEFAULT_COMMUNITY_ID } from "../config";
import { import {
championDisplayName, championDisplayName,
championIconUrl, championIconUrl,
itemIconUrl,
} from "../lib/ddragon"; } from "../lib/ddragon";
import { import {
sideShortLabel, sideShortLabel,
@@ -14,6 +13,7 @@ import {
} from "../lib/league"; } from "../lib/league";
import { internalMatchGamePath } from "../lib/internal-match-routes"; import { internalMatchGamePath } from "../lib/internal-match-routes";
import { LANE_LABELS } from "../lib/riot-history"; import { LANE_LABELS } from "../lib/riot-history";
import { ItemIcon } from "../components/ItemTooltip";
function formatDateTime(value: string | number) { function formatDateTime(value: string | number) {
return new Intl.DateTimeFormat("ko-KR", { return new Intl.DateTimeFormat("ko-KR", {
@@ -72,19 +72,16 @@ function ItemStrip({
}) { }) {
return ( return (
<div className="flex flex-wrap gap-1"> <div className="flex flex-wrap gap-1">
{[...items, trinket].map((itemId, index) => { {[...items, trinket].map((itemId, index) => (
const icon = itemIconUrl(manifest, itemId); <ItemIcon
return ( key={`${itemId}-${index}`}
<span itemId={itemId}
key={`${itemId}-${index}`} manifest={manifest}
className="w-5 h-5 bg-base-content/10 border border-base-content/5 overflow-hidden" trinket={index === items.length}
> className="h-5 w-5"
{icon ? ( imageClassName=""
<img src={icon} alt="" className="w-full h-full object-cover" /> />
) : null} ))}
</span>
);
})}
</div> </div>
); );
} }
+11 -14
View File
@@ -17,7 +17,6 @@ import { DEFAULT_COMMUNITY_ID } from "../config";
import { import {
championDisplayName, championDisplayName,
championIconUrl, championIconUrl,
itemIconUrl,
runeIconUrl, runeIconUrl,
runeKeystoneIconUrl, runeKeystoneIconUrl,
runeStyleIconUrl, runeStyleIconUrl,
@@ -33,6 +32,7 @@ import {
internalMatchGamePath, internalMatchGamePath,
} from "../lib/internal-match-routes"; } from "../lib/internal-match-routes";
import { LANE_LABELS } from "../lib/riot-history"; import { LANE_LABELS } from "../lib/riot-history";
import { ItemIcon } from "../components/ItemTooltip";
type MatchGameDetail = ApiInternalMatchDetailResponse["games"][number]; type MatchGameDetail = ApiInternalMatchDetailResponse["games"][number];
type MatchGameTeam = MatchGameDetail["teams"][number]; type MatchGameTeam = MatchGameDetail["teams"][number];
@@ -382,19 +382,16 @@ function ItemStrip({
return ( return (
<div className="grid grid-cols-7 gap-0.5"> <div className="grid grid-cols-7 gap-0.5">
{itemIds.map((itemId, index) => { {itemIds.map((itemId, index) => (
const icon = itemIconUrl(manifest, itemId); <ItemIcon
return ( key={`${itemId}-${index}`}
<span itemId={itemId}
key={`${itemId}-${index}`} manifest={manifest}
className="h-8 w-8 overflow-hidden border border-base-content/5 bg-base-content/10" trinket={index === 6}
> className="h-8 w-8"
{icon ? ( imageClassName=""
<img src={icon} alt="" className="h-full w-full object-cover" /> />
) : null} ))}
</span>
);
})}
</div> </div>
); );
} }
+11 -19
View File
@@ -29,7 +29,6 @@ import { ApiError } from "../lib/api";
import { import {
championDisplayName, championDisplayName,
championIconUrl, championIconUrl,
itemIconUrl,
profileIconUrl, profileIconUrl,
runeKeystoneIconUrl, runeKeystoneIconUrl,
runeStyleIconUrl, runeStyleIconUrl,
@@ -43,6 +42,7 @@ import {
RANK_FILTER_TABS, RANK_FILTER_TABS,
} from "../lib/riot-history"; } from "../lib/riot-history";
import { ResponsiveTierLabel } from "../components/RankBadge"; import { ResponsiveTierLabel } from "../components/RankBadge";
import { ItemIcon } from "../components/ItemTooltip";
// recharts가 무거워 메인 번들에서 분리한다 (전적 페이지에서만 로드). // recharts가 무거워 메인 번들에서 분리한다 (전적 페이지에서만 로드).
const TierHistoryChart = lazy(() => import("../components/TierHistoryChart")); const TierHistoryChart = lazy(() => import("../components/TierHistoryChart"));
@@ -344,24 +344,16 @@ function ItemGrid({
return ( return (
<div className={`grid gap-1 ${layoutClass}`}> <div className={`grid gap-1 ${layoutClass}`}>
{slots.map((itemId, index) => { {slots.map((itemId, index) => (
const url = itemIconUrl(manifest, itemId); <ItemIcon
return ( key={`${itemKey}-item-${index}`}
<div itemId={itemId}
key={`${itemKey}-item-${index}`} manifest={manifest}
className="w-5 h-5 bg-base-content/8 overflow-hidden border border-base-content/5" trinket={index === 6}
> className="h-5 w-5"
{url ? ( imageClassName=""
<img />
src={url} ))}
alt=""
className="w-full h-full object-cover"
loading="lazy"
/>
) : null}
</div>
);
})}
</div> </div>
); );
} }