WorldMarketMap.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. 'use client';
  2. import './world-map.scss';
  3. import { useEffect, useMemo, useRef, useState } from 'react';
  4. import { geoNaturalEarth1, geoPath } from 'd3-geo';
  5. import { feature } from 'topojson-client';
  6. import type { Feature, Geometry } from 'geojson';
  7. import worldTopo from 'world-atlas/countries-110m.json';
  8. import {
  9. EXCHANGE_GEO,
  10. REGION_LABELS,
  11. REGION_ORDER,
  12. moveDir,
  13. formatFlucRate,
  14. formatIndexClose,
  15. type WorldIndexRow,
  16. type MarketRegion,
  17. TV_SYMBOL
  18. } from '@/types/worldIndex';
  19. import TradingViewChart from './TradingViewChart';
  20. // 등거리 대신 d3-geo geoNaturalEarth1(곡면) 투영. 국가별 topojson feature 를 GeoJSON 으로 디코드해
  21. // 육지 path 와 핀 좌표를 "동일 projection" 으로 산출. 팬/줌은 <g> transform 으로 처리(드래그 이동·확대).
  22. // (Wave1 — .claude/plan/global-market-research-pages.md)
  23. const VW = 1000;
  24. const VH = 500;
  25. const MIN_K = 1;
  26. const MAX_K = 6;
  27. const DEFAULT_K = 1.5; // 기본 살짝 확대
  28. const PIN_H = 15; // 핀 막대 높이 — 머리를 지점 위로 띄워 겹침 완화(map-pin)
  29. type GeoFeature = Feature<Geometry>;
  30. type RegionTab = 'major'|MarketRegion;
  31. type View = { x: number; y: number; k: number };
  32. const COUNTRIES: GeoFeature[] = (() => {
  33. const decoded = feature(worldTopo as never, (worldTopo as unknown as { objects: { countries: never } }).objects.countries) as unknown as { features: GeoFeature[] };
  34. return decoded.features.filter((f) => String(f.id) !== '010'); // 남극 제외
  35. })();
  36. const PROJECTION = geoNaturalEarth1().fitSize([VW, VH], { type: 'FeatureCollection', features: COUNTRIES } as never);
  37. const PATH_FN = geoPath(PROJECTION);
  38. const COUNTRY_PATHS: { id: string; d: string }[] = COUNTRIES
  39. .map((f) => ({ id: String(f.id), d: PATH_FN(f as never) ?? '' }))
  40. .filter((c) => c.d.length > 0);
  41. const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
  42. // viewBox 중심 기준으로 k 배 확대한 초기 view
  43. const centeredView = (k: number): View => ({ x: (VW / 2) * (1 - k), y: (VH / 2) * (1 - k), k });
  44. type Props = {
  45. rows: WorldIndexRow[];
  46. };
  47. type Pin = {
  48. row: WorldIndexRow;
  49. label: string;
  50. x: number;
  51. y: number;
  52. dir: 'up'|'down'|'flat';
  53. radius: number;
  54. };
  55. function formatChangeVal(changeVal: number): string {
  56. const sign = changeVal > 0 ? '+' : '';
  57. return `${sign}${changeVal.toLocaleString('ko-KR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  58. }
  59. export default function WorldMarketMap({ rows }: Props)
  60. {
  61. const [region, setRegion] = useState<RegionTab>('major');
  62. const [active, setActive] = useState<string|null>(null);
  63. const [chartRow, setChartRow] = useState<WorldIndexRow|null>(null);
  64. const [view, setView] = useState<View>(() => centeredView(DEFAULT_K));
  65. const [panning, setPanning] = useState(false);
  66. const svgRef = useRef<SVGSVGElement>(null);
  67. const dragRef = useRef<{ px: number; py: number; vx: number; vy: number; moved: boolean }|null>(null);
  68. const suppressClickRef = useRef(false);
  69. // 마우스 휠 확대/축소 (커서 위치 기준). React onWheel 은 passive 라 네이티브 리스너로 등록(preventDefault 필요).
  70. useEffect(() => {
  71. const svg = svgRef.current;
  72. if (!svg) {
  73. return;
  74. }
  75. const onWheel = (e: WheelEvent) => {
  76. e.preventDefault();
  77. const rect = svg.getBoundingClientRect();
  78. if (rect.width === 0) {
  79. return;
  80. }
  81. const cx = (e.clientX - rect.left) * (VW / rect.width);
  82. const cy = (e.clientY - rect.top) * (VH / rect.height);
  83. const factor = e.deltaY < 0 ? 1.12 : 1 / 1.12;
  84. setView((v) => {
  85. const k = clamp(v.k * factor, MIN_K, MAX_K);
  86. return { x: cx - (cx - v.x) * (k / v.k), y: cy - (cy - v.y) * (k / v.k), k };
  87. });
  88. };
  89. svg.addEventListener('wheel', onWheel, { passive: false });
  90. return () => {
  91. svg.removeEventListener('wheel', onWheel);
  92. };
  93. }, []);
  94. // 좌표를 아는 국가만 취급 + 핀 좌표 산출
  95. const pins = useMemo<Pin[]>(() => {
  96. return rows
  97. .map((row) => {
  98. const geo = EXCHANGE_GEO[row.countryCode];
  99. if (!geo) {
  100. return null;
  101. }
  102. const xy = PROJECTION([geo.lng, geo.lat]);
  103. if (!xy) {
  104. return null;
  105. }
  106. const radius = Math.min(8, 4.5 + Math.abs(row.flucRateBp) / 110);
  107. return { row, label: geo.label, x: xy[0], y: xy[1], dir: moveDir(row.flucRateBp), radius };
  108. })
  109. .filter((c): c is Pin => c !== null);
  110. }, [rows]);
  111. // 지역 탭 (데이터 있는 탭만)
  112. const tabs = useMemo<RegionTab[]>(() => {
  113. const counts: Record<RegionTab, number> = { major: 0, asia: 0, europe: 0, america: 0, mideast: 0 };
  114. pins.forEach((p) => {
  115. const geo = EXCHANGE_GEO[p.row.countryCode];
  116. counts[geo.region] += 1;
  117. if (geo.major) {
  118. counts.major += 1;
  119. }
  120. });
  121. return REGION_ORDER.filter((t) => counts[t] > 0);
  122. }, [pins]);
  123. const activeRegion: RegionTab = tabs.includes(region) ? region : (tabs[0] ?? 'major');
  124. const gridRows = useMemo(() => {
  125. return pins
  126. .map((p) => p.row)
  127. .filter((r) => {
  128. const geo = EXCHANGE_GEO[r.countryCode];
  129. return activeRegion === 'major' ? geo.major === true : geo.region === activeRegion;
  130. })
  131. .sort((a, b) => b.flucRateBp - a.flucRateBp);
  132. }, [pins, activeRegion]);
  133. const asOf = useMemo(() => {
  134. return pins.reduce<string|null>((max, c) => (max === null || c.row.tradeDate > max ? c.row.tradeDate : max), null);
  135. }, [pins]);
  136. // 지역 탭 클릭 → 그리드 필터 + 지도를 해당 지역으로 이동/확대
  137. function selectRegion(t: RegionTab)
  138. {
  139. setRegion(t);
  140. if (t === 'major') {
  141. setView(centeredView(DEFAULT_K));
  142. return;
  143. }
  144. const regionPins = pins.filter((p) => EXCHANGE_GEO[p.row.countryCode].region === t);
  145. if (regionPins.length === 0) {
  146. return;
  147. }
  148. const xs = regionPins.map((p) => p.x);
  149. const ys = regionPins.map((p) => p.y);
  150. const cx = (Math.min(...xs) + Math.max(...xs)) / 2;
  151. const cy = (Math.min(...ys) + Math.max(...ys)) / 2;
  152. const spreadX = Math.max(Math.max(...xs) - Math.min(...xs), 70);
  153. const spreadY = Math.max(Math.max(...ys) - Math.min(...ys), 70);
  154. const k = clamp(Math.min(VW / (spreadX * 2.2), VH / (spreadY * 2.2)), 1.6, 4);
  155. setView({ x: VW / 2 - cx * k, y: VH / 2 - cy * k, k });
  156. }
  157. function zoomBy(factor: number)
  158. {
  159. setView((v) => {
  160. const k = clamp(v.k * factor, MIN_K, MAX_K);
  161. const cx = VW / 2;
  162. const cy = VH / 2;
  163. return { x: cx - (cx - v.x) * (k / v.k), y: cy - (cy - v.y) * (k / v.k), k };
  164. });
  165. }
  166. function onPointerDown(e: React.PointerEvent<SVGSVGElement>)
  167. {
  168. if (e.button !== 0) {
  169. return;
  170. }
  171. dragRef.current = { px: e.clientX, py: e.clientY, vx: view.x, vy: view.y, moved: false };
  172. setPanning(true);
  173. }
  174. function onPointerMove(e: React.PointerEvent<SVGSVGElement>)
  175. {
  176. const d = dragRef.current;
  177. if (!d) {
  178. return;
  179. }
  180. const rect = svgRef.current?.getBoundingClientRect();
  181. const factor = rect && rect.width > 0 ? VW / rect.width : 1;
  182. const dx = (e.clientX - d.px) * factor;
  183. const dy = (e.clientY - d.py) * factor;
  184. if (Math.abs(e.clientX - d.px) + Math.abs(e.clientY - d.py) > 3) {
  185. d.moved = true;
  186. }
  187. setView((v) => ({ ...v, x: d.vx + dx, y: d.vy + dy }));
  188. }
  189. function endPan()
  190. {
  191. suppressClickRef.current = dragRef.current?.moved ?? false;
  192. dragRef.current = null;
  193. setPanning(false);
  194. }
  195. function onPinClick(row: WorldIndexRow)
  196. {
  197. if (suppressClickRef.current) {
  198. suppressClickRef.current = false;
  199. return;
  200. }
  201. if (TV_SYMBOL[row.countryCode]) {
  202. setChartRow(row);
  203. }
  204. }
  205. return (
  206. <section className='world-map' aria-label='세계 주요국 증시지수'>
  207. <div className='world-map__head'>
  208. <h2 className='world-map__title'>세계 증시</h2>
  209. <div className='world-map__meta'>
  210. <span className='world-map__legend'>
  211. <i className='world-map__dot world-map__dot--up' aria-hidden='true' />상승
  212. <i className='world-map__dot world-map__dot--down' aria-hidden='true' />하락
  213. </span>
  214. {asOf && <span className='world-map__asof'>전일 마감 기준 {asOf}</span>}
  215. </div>
  216. </div>
  217. <div className='world-map__body'>
  218. <div className='world-map__stage'>
  219. <svg
  220. ref={svgRef}
  221. className={`world-map__svg${panning ? ' is-panning' : ''}`}
  222. viewBox={`0 0 ${VW} ${VH}`}
  223. role='img'
  224. aria-label='세계지도 위 주요국 증시지수 핀 (드래그로 이동, 확대 가능)'
  225. preserveAspectRatio='xMidYMid meet'
  226. onPointerDown={onPointerDown}
  227. onPointerMove={onPointerMove}
  228. onPointerUp={endPan}
  229. onPointerLeave={endPan}
  230. >
  231. <defs>
  232. <radialGradient id='wm-ocean' cx='50%' cy='42%' r='75%'>
  233. <stop offset='0%' stopColor='var(--az-map-ocean-1)' />
  234. <stop offset='100%' stopColor='var(--az-map-ocean-2)' />
  235. </radialGradient>
  236. </defs>
  237. {/* 대양 (고정 배경 — 팬/줌 영향 없음) */}
  238. <rect x='0' y='0' width={VW} height={VH} rx='16' fill='url(#wm-ocean)' />
  239. {/* 팬/줌 그룹 */}
  240. <g transform={`translate(${view.x} ${view.y}) scale(${view.k})`}>
  241. <g className='world-map__land'>
  242. {COUNTRY_PATHS.map((c) => (
  243. <path key={c.id} d={c.d} />
  244. ))}
  245. </g>
  246. <g className='world-map__pins'>
  247. {pins.map((pin) => {
  248. const isActive = pin.row.countryCode === active;
  249. const leftSide = pin.x > VW * 0.72;
  250. const lx = leftSide ? -(pin.radius + 4) : pin.radius + 4;
  251. const anchor = leftSide ? 'end' : 'start';
  252. return (
  253. <g
  254. key={pin.row.countryCode}
  255. className={`world-map__pin world-map__pin--${pin.dir}${isActive ? ' is-active' : ''}`}
  256. transform={`translate(${pin.x} ${pin.y})`}
  257. role='button'
  258. tabIndex={0}
  259. aria-label={`${pin.label} ${pin.row.name} ${formatFlucRate(pin.row.flucRateBp)}`}
  260. onMouseEnter={() => setActive(pin.row.countryCode)}
  261. onMouseLeave={() => setActive((cur) => (cur === pin.row.countryCode ? null : cur))}
  262. onFocus={() => setActive(pin.row.countryCode)}
  263. onBlur={() => setActive((cur) => (cur === pin.row.countryCode ? null : cur))}
  264. onClick={() => onPinClick(pin.row)}
  265. onKeyDown={(e) => { if ((e.key === 'Enter' || e.key === ' ') && TV_SYMBOL[pin.row.countryCode]) { e.preventDefault(); setChartRow(pin.row); } }}
  266. >
  267. {/* map-pin: 지점에서 위로 뻗은 막대 + 머리(원) */}
  268. <line className='world-map__pin-stem' x1='0' y1='0' x2='0' y2={-PIN_H} />
  269. <circle className='world-map__pin-head' cx='0' cy={-PIN_H} r={pin.radius} />
  270. {/* 상시 라벨 — 국가명 + 등락률 (머리 옆) */}
  271. <g className='world-map__label' transform={`translate(${lx} ${-PIN_H})`} textAnchor={anchor}>
  272. <text className='world-map__label-name' y='-2'>{pin.label}</text>
  273. <text className={`world-map__label-rate world-map__label-rate--${pin.dir}`} y='8.5'>{formatFlucRate(pin.row.flucRateBp)}</text>
  274. {isActive && <text className='world-map__label-close' y='18'>{formatIndexClose(pin.row.close)}</text>}
  275. </g>
  276. </g>
  277. );
  278. })}
  279. </g>
  280. </g>
  281. </svg>
  282. {/* 줌 컨트롤 */}
  283. <div className='world-map__zoom'>
  284. <button type='button' className='world-map__zoom-btn' aria-label='확대' onClick={() => zoomBy(1.4)}>+</button>
  285. <button type='button' className='world-map__zoom-btn' aria-label='축소' onClick={() => zoomBy(1 / 1.4)}>−</button>
  286. <button type='button' className='world-map__zoom-btn' aria-label='초기화' title='초기화' onClick={() => setView(centeredView(DEFAULT_K))}>⤢</button>
  287. </div>
  288. </div>
  289. {/* 지수 패널 — 지역 탭 + 데이터 그리드 */}
  290. <div className='world-map__panel'>
  291. <div className='world-map__tabs' role='tablist' aria-label='지역'>
  292. {tabs.map((t) => (
  293. <button
  294. key={t}
  295. type='button'
  296. role='tab'
  297. aria-selected={t === activeRegion}
  298. className={`world-map__tab${t === activeRegion ? ' is-active' : ''}`}
  299. onClick={() => selectRegion(t)}
  300. >
  301. {REGION_LABELS[t]}
  302. </button>
  303. ))}
  304. </div>
  305. <div className='world-map__grid-wrap'>
  306. <table className='world-map__grid'>
  307. <thead>
  308. <tr>
  309. <th scope='col' className='world-map__c-name'>지수명</th>
  310. <th scope='col' className='world-map__c-num'>지수</th>
  311. <th scope='col' className='world-map__c-num'>전일비</th>
  312. <th scope='col' className='world-map__c-num'>등락률</th>
  313. <th scope='col' className='world-map__c-time'>시간</th>
  314. <th scope='col' className='world-map__c-chart'>차트</th>
  315. </tr>
  316. </thead>
  317. <tbody>
  318. {gridRows.map((row) => {
  319. const geo = EXCHANGE_GEO[row.countryCode];
  320. const dir = moveDir(row.flucRateBp);
  321. const isActive = row.countryCode === active;
  322. return (
  323. <tr
  324. key={row.countryCode}
  325. className={`world-map__row${isActive ? ' is-active' : ''}`}
  326. onMouseEnter={() => setActive(row.countryCode)}
  327. onMouseLeave={() => setActive((cur) => (cur === row.countryCode ? null : cur))}
  328. >
  329. <td className='world-map__c-name'>
  330. <span className='world-map__row-country'>{geo.label}</span>
  331. <span className='world-map__row-name'>{row.name}</span>
  332. </td>
  333. <td className='world-map__c-num world-map__c-close'>{formatIndexClose(row.close)}</td>
  334. <td className={`world-map__c-num world-map__c-${dir}`}>{formatChangeVal(row.changeVal)}</td>
  335. <td className={`world-map__c-num world-map__c-${dir}`}>{formatFlucRate(row.flucRateBp)}</td>
  336. <td className='world-map__c-time'>{row.tradeDate}</td>
  337. <td className='world-map__c-chart'>
  338. <button
  339. type='button'
  340. className='world-map__chart-btn'
  341. title={TV_SYMBOL[row.countryCode] ? `${row.name} 차트 보기` : `${geo.label} 위치 보기`}
  342. aria-label={TV_SYMBOL[row.countryCode] ? `${geo.label} ${row.name} 차트 보기` : `${geo.label} ${row.name} 지도에서 보기`}
  343. onClick={() => { if (TV_SYMBOL[row.countryCode]) { setChartRow(row); } else { setActive(row.countryCode); } }}
  344. >
  345. <svg viewBox='0 0 24 24' width='16' height='16' aria-hidden='true'>
  346. <polyline points='3,17 9,11 13,15 21,6' fill='none' stroke='currentColor' strokeWidth='2' strokeLinecap='round' strokeLinejoin='round' />
  347. </svg>
  348. </button>
  349. </td>
  350. </tr>
  351. );
  352. })}
  353. </tbody>
  354. </table>
  355. {gridRows.length === 0 && <div className='world-map__empty'>이 지역 지수 데이터가 없습니다.</div>}
  356. </div>
  357. </div>
  358. </div>
  359. {chartRow && TV_SYMBOL[chartRow.countryCode] && (
  360. <div
  361. className='world-map__modal'
  362. role='dialog'
  363. aria-modal='true'
  364. aria-label={`${EXCHANGE_GEO[chartRow.countryCode]?.label ?? ''} ${chartRow.name} 차트`}
  365. onClick={() => setChartRow(null)}
  366. >
  367. <div className='world-map__modal-panel' onClick={(e) => e.stopPropagation()}>
  368. <div className='world-map__modal-head'>
  369. <span className='world-map__modal-title'>
  370. {EXCHANGE_GEO[chartRow.countryCode]?.label} · {chartRow.name}
  371. </span>
  372. <button type='button' className='world-map__modal-close' aria-label='닫기' onClick={() => setChartRow(null)}>×</button>
  373. </div>
  374. <div className='world-map__modal-body'>
  375. <TradingViewChart symbol={TV_SYMBOL[chartRow.countryCode]} />
  376. </div>
  377. <p className='world-map__modal-note'>실시간 차트 제공 · TradingView</p>
  378. </div>
  379. </div>
  380. )}
  381. </section>
  382. );
  383. }