diff --git a/apps/api/src/modules/riot/riot-ddragon.service.spec.ts b/apps/api/src/modules/riot/riot-ddragon.service.spec.ts new file mode 100644 index 00000000..4539bd96 --- /dev/null +++ b/apps/api/src/modules/riot/riot-ddragon.service.spec.ts @@ -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; +} + +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: + '공격력 10', + 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: + '공격력 10', + 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, + ); + }); +}); diff --git a/apps/api/src/modules/riot/riot-ddragon.service.ts b/apps/api/src/modules/riot/riot-ddragon.service.ts index f5c7e83b..c4ff9d8a 100644 --- a/apps/api/src/modules/riot/riot-ddragon.service.ts +++ b/apps/api/src/modules/riot/riot-ddragon.service.ts @@ -5,7 +5,7 @@ const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com'; const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`; const DEFAULT_LOCALE = 'ko_KR'; const CACHE_TTL_SECONDS = 24 * 60 * 60; -const CACHE_VERSION = 'v3'; +const CACHE_VERSION = 'v4'; const FETCH_TIMEOUT_MS = 10_000; export interface DdragonChampionEntry { @@ -29,6 +29,18 @@ export interface DdragonRuneStyleEntry extends 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 { version: string; cdn: string; @@ -36,6 +48,7 @@ export interface DdragonManifest { champions: Record; summonerSpells: Record; runesReforged: DdragonRuneStyleEntry[]; + items: Record; fetchedAt: string; } @@ -70,6 +83,22 @@ interface RuneStyleDataEntry extends 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; +} + @Injectable() export class RiotDdragonService { private readonly logger = new Logger(RiotDdragonService.name); @@ -102,10 +131,11 @@ export class RiotDdragonService { private async buildManifest(locale: string): Promise { 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.fetchSummonerSpellMap(version, locale), this.fetchRuneStyles(version, locale), + this.fetchItemMap(version, locale), ]); return { version, @@ -114,6 +144,7 @@ export class RiotDdragonService { champions, summonerSpells, runesReforged, + items, fetchedAt: new Date().toISOString(), }; } @@ -200,6 +231,38 @@ export class RiotDdragonService { })); } + private async fetchItemMap( + version: string, + locale: string, + ): Promise> { + const url = `${DDRAGON_CDN}/${version}/data/${locale}/item.json`; + const payload = await this.fetchJson(url); + if (!payload || typeof payload !== 'object' || !payload.data) { + throw new Error(`ddragon item.json response is malformed (${url}).`); + } + + const map: Record = {}; + 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(url: string): Promise { const controller = new AbortController(); 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 { return `ddragon:manifest:${CACHE_VERSION}:${locale}`; } diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index e9db3dcb..219271dc 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -495,6 +495,18 @@ export interface DdragonRuneStyleEntry extends 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 { version: string; cdn: string; @@ -502,6 +514,7 @@ export interface DdragonManifest { champions: Record; summonerSpells: Record; runesReforged: DdragonRuneStyleEntry[]; + items: Record; fetchedAt: string; } diff --git a/apps/web/src/components/ItemTooltip.tsx b/apps/web/src/components/ItemTooltip.tsx new file mode 100644 index 00000000..bb20b888 --- /dev/null +++ b/apps/web/src/components/ItemTooltip.tsx @@ -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(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 ( + setOpen(false)} + onFocus={() => hasItem && setOpen(true)} + onMouseEnter={() => hasItem && setOpen(true)} + onMouseLeave={() => setOpen(false)} + > + + {hasItem && open ? ( + + ) : null} + + ); +} + +function ItemTooltipPortal({ + id, + anchorRef, + itemId, + manifest, +}: { + id: string; + anchorRef: RefObject; + itemId: number; + manifest: DdragonManifest | null | undefined; +}) { + const [position, setPosition] = useState(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( + , + 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 ( +
+
+ {item?.name ?? `아이템 ${itemId}`} +
+ {item?.plaintext ? ( +
{item.plaintext}
+ ) : null} + {descriptionHtml ? ( +
+ ) : ( +
+ 아이템 상세 정보를 불러오는 중입니다. +
+ )} + {item?.gold.total ? ( +
+ 가격: + {item.gold.total}{" "} + + ({item.gold.base || item.gold.total}) + +
+ ) : null} +
+ ); +} + +function clamp(value: number, min: number, max: number) { + if (max < min) return min; + return Math.min(Math.max(value, min), max); +} diff --git a/apps/web/src/lib/ddragon.ts b/apps/web/src/lib/ddragon.ts index 923d15f8..86756197 100644 --- a/apps/web/src/lib/ddragon.ts +++ b/apps/web/src/lib/ddragon.ts @@ -2,6 +2,25 @@ import type { DdragonManifest } from '../api/types'; const FALLBACK_VERSION = '15.24.1'; const FALLBACK_CDN = 'https://ddragon.leagueoflegends.com/cdn'; +const DDRAGON_DESCRIPTION_TAG_CLASSES: Record = { + 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) { return manifest?.cdn ?? FALLBACK_CDN; @@ -42,6 +61,34 @@ export function itemIconUrl( 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(/<br\s*\/?>/gi, '
') + .replace(/<(\/?)([a-zA-Z][a-zA-Z0-9]*)(?:\s[\s\S]*?)?>/g, (_match, closing, tag) => { + const normalizedTag = String(tag); + const className = DDRAGON_DESCRIPTION_TAG_CLASSES[normalizedTag]; + if (!className) return ''; + return closing ? '' : ``; + }) + .replace(/<\/?[a-zA-Z][\s\S]*?>/g, ''); +} + export function summonerSpellIconUrl( manifest: DdragonManifest | null | undefined, spellId: number, @@ -76,3 +123,12 @@ export function runeIconUrl( ) { return runeKeystoneIconUrl(manifest, runeId); } + +function escapeHtml(value: string) { + return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} diff --git a/apps/web/src/pages/InternalMatchDetailPage.tsx b/apps/web/src/pages/InternalMatchDetailPage.tsx index b23f2c63..51b86198 100644 --- a/apps/web/src/pages/InternalMatchDetailPage.tsx +++ b/apps/web/src/pages/InternalMatchDetailPage.tsx @@ -5,7 +5,6 @@ import { DEFAULT_COMMUNITY_ID } from "../config"; import { championDisplayName, championIconUrl, - itemIconUrl, } from "../lib/ddragon"; import { sideShortLabel, @@ -14,6 +13,7 @@ import { } from "../lib/league"; import { internalMatchGamePath } from "../lib/internal-match-routes"; import { LANE_LABELS } from "../lib/riot-history"; +import { ItemIcon } from "../components/ItemTooltip"; function formatDateTime(value: string | number) { return new Intl.DateTimeFormat("ko-KR", { @@ -72,19 +72,16 @@ function ItemStrip({ }) { return (
- {[...items, trinket].map((itemId, index) => { - const icon = itemIconUrl(manifest, itemId); - return ( - - {icon ? ( - - ) : null} - - ); - })} + {[...items, trinket].map((itemId, index) => ( + + ))}
); } diff --git a/apps/web/src/pages/MatchGameDetailPage.tsx b/apps/web/src/pages/MatchGameDetailPage.tsx index 56805d60..e626ac7a 100644 --- a/apps/web/src/pages/MatchGameDetailPage.tsx +++ b/apps/web/src/pages/MatchGameDetailPage.tsx @@ -17,7 +17,6 @@ import { DEFAULT_COMMUNITY_ID } from "../config"; import { championDisplayName, championIconUrl, - itemIconUrl, runeIconUrl, runeKeystoneIconUrl, runeStyleIconUrl, @@ -33,6 +32,7 @@ import { internalMatchGamePath, } from "../lib/internal-match-routes"; import { LANE_LABELS } from "../lib/riot-history"; +import { ItemIcon } from "../components/ItemTooltip"; type MatchGameDetail = ApiInternalMatchDetailResponse["games"][number]; type MatchGameTeam = MatchGameDetail["teams"][number]; @@ -382,19 +382,16 @@ function ItemStrip({ return (
- {itemIds.map((itemId, index) => { - const icon = itemIconUrl(manifest, itemId); - return ( - - {icon ? ( - - ) : null} - - ); - })} + {itemIds.map((itemId, index) => ( + + ))}
); } diff --git a/apps/web/src/pages/UserHistoryPage.tsx b/apps/web/src/pages/UserHistoryPage.tsx index 79193797..6f44a71c 100644 --- a/apps/web/src/pages/UserHistoryPage.tsx +++ b/apps/web/src/pages/UserHistoryPage.tsx @@ -29,7 +29,6 @@ import { ApiError } from "../lib/api"; import { championDisplayName, championIconUrl, - itemIconUrl, profileIconUrl, runeKeystoneIconUrl, runeStyleIconUrl, @@ -43,6 +42,7 @@ import { RANK_FILTER_TABS, } from "../lib/riot-history"; import { ResponsiveTierLabel } from "../components/RankBadge"; +import { ItemIcon } from "../components/ItemTooltip"; // recharts가 무거워 메인 번들에서 분리한다 (전적 페이지에서만 로드). const TierHistoryChart = lazy(() => import("../components/TierHistoryChart")); @@ -344,24 +344,16 @@ function ItemGrid({ return (
- {slots.map((itemId, index) => { - const url = itemIconUrl(manifest, itemId); - return ( -
- {url ? ( - - ) : null} -
- ); - })} + {slots.map((itemId, index) => ( + + ))}
); }