WorldMarketMap.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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; // 기본: 전체 세계지도 표시 (확대는 휠/드래그/지역탭)
  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. // 확대(k↑)하면 핀 간격이 벌어져 겹침이 풀리므로 더 많은 라벨이 나타난다. (핀 머리/막대는 항상 표시)
  138. const labeledSet = useMemo(() => {
  139. const ordered = [...pins].sort((a, b) => Math.abs(b.row.flucRateBp) - Math.abs(a.row.flucRateBp));
  140. const placed: { x1: number; y1: number; x2: number; y2: number }[] = [];
  141. const show = new Set<string>();
  142. for (const pin of ordered) {
  143. const sx = view.x + pin.x * view.k;
  144. const sy = view.y + pin.y * view.k;
  145. if (sx < -24 || sx > VW + 24 || sy < -24 || sy > VH + 24) {
  146. continue;
  147. }
  148. const hy = sy - PIN_H;
  149. const left = sx > VW * 0.72;
  150. const w = Math.max(pin.label.length * 11.5, 46) + 6;
  151. const x1 = left ? sx - (pin.radius + 4) - w : sx + (pin.radius + 4);
  152. const box = { x1, y1: hy - 13, x2: x1 + w, y2: hy + 12 };
  153. const hit = placed.some((p) => !(box.x2 < p.x1 || box.x1 > p.x2 || box.y2 < p.y1 || box.y1 > p.y2));
  154. if (!hit) {
  155. placed.push(box);
  156. show.add(pin.row.countryCode);
  157. }
  158. }
  159. return show;
  160. }, [pins, view]);
  161. // 지역 탭 클릭 → 그리드 필터 + 지도를 해당 지역으로 이동/확대
  162. function selectRegion(t: RegionTab)
  163. {
  164. setRegion(t);
  165. if (t === 'major') {
  166. setView(centeredView(DEFAULT_K));
  167. return;
  168. }
  169. const regionPins = pins.filter((p) => EXCHANGE_GEO[p.row.countryCode].region === t);
  170. if (regionPins.length === 0) {
  171. return;
  172. }
  173. const xs = regionPins.map((p) => p.x);
  174. const ys = regionPins.map((p) => p.y);
  175. const cx = (Math.min(...xs) + Math.max(...xs)) / 2;
  176. const cy = (Math.min(...ys) + Math.max(...ys)) / 2;
  177. const spreadX = Math.max(Math.max(...xs) - Math.min(...xs), 70);
  178. const spreadY = Math.max(Math.max(...ys) - Math.min(...ys), 70);
  179. const k = clamp(Math.min(VW / (spreadX * 2.2), VH / (spreadY * 2.2)), 1.6, 4);
  180. setView({ x: VW / 2 - cx * k, y: VH / 2 - cy * k, k });
  181. }
  182. function zoomBy(factor: number)
  183. {
  184. setView((v) => {
  185. const k = clamp(v.k * factor, MIN_K, MAX_K);
  186. const cx = VW / 2;
  187. const cy = VH / 2;
  188. return { x: cx - (cx - v.x) * (k / v.k), y: cy - (cy - v.y) * (k / v.k), k };
  189. });
  190. }
  191. function onPointerDown(e: React.PointerEvent<SVGSVGElement>)
  192. {
  193. if (e.button !== 0) {
  194. return;
  195. }
  196. dragRef.current = { px: e.clientX, py: e.clientY, vx: view.x, vy: view.y, moved: false };
  197. setPanning(true);
  198. }
  199. function onPointerMove(e: React.PointerEvent<SVGSVGElement>)
  200. {
  201. const d = dragRef.current;
  202. if (!d) {
  203. return;
  204. }
  205. const rect = svgRef.current?.getBoundingClientRect();
  206. const factor = rect && rect.width > 0 ? VW / rect.width : 1;
  207. const dx = (e.clientX - d.px) * factor;
  208. const dy = (e.clientY - d.py) * factor;
  209. if (Math.abs(e.clientX - d.px) + Math.abs(e.clientY - d.py) > 3) {
  210. d.moved = true;
  211. }
  212. setView((v) => ({ ...v, x: d.vx + dx, y: d.vy + dy }));
  213. }
  214. function endPan()
  215. {
  216. suppressClickRef.current = dragRef.current?.moved ?? false;
  217. dragRef.current = null;
  218. setPanning(false);
  219. }
  220. function onPinClick(row: WorldIndexRow)
  221. {
  222. if (suppressClickRef.current) {
  223. suppressClickRef.current = false;
  224. return;
  225. }
  226. if (TV_SYMBOL[row.countryCode]) {
  227. setChartRow(row);
  228. }
  229. }
  230. return (
  231. <section className='world-map' aria-label='세계 주요국 증시지수'>
  232. <div className='world-map__head'>
  233. <h2 className='world-map__title'>세계 증시</h2>
  234. <div className='world-map__meta'>
  235. <span className='world-map__legend'>
  236. <i className='world-map__dot world-map__dot--up' aria-hidden='true' />상승
  237. <i className='world-map__dot world-map__dot--down' aria-hidden='true' />하락
  238. </span>
  239. {asOf && <span className='world-map__asof'>전일 마감 기준 {asOf}</span>}
  240. </div>
  241. </div>
  242. <div className='world-map__body'>
  243. <div className='world-map__stage'>
  244. <svg
  245. ref={svgRef}
  246. className={`world-map__svg${panning ? ' is-panning' : ''}`}
  247. viewBox={`0 0 ${VW} ${VH}`}
  248. role='img'
  249. aria-label='세계지도 위 주요국 증시지수 핀 (드래그로 이동, 확대 가능)'
  250. preserveAspectRatio='xMidYMid meet'
  251. onPointerDown={onPointerDown}
  252. onPointerMove={onPointerMove}
  253. onPointerUp={endPan}
  254. onPointerLeave={endPan}
  255. >
  256. <defs>
  257. <radialGradient id='wm-ocean' cx='50%' cy='42%' r='75%'>
  258. <stop offset='0%' stopColor='var(--az-map-ocean-1)' />
  259. <stop offset='100%' stopColor='var(--az-map-ocean-2)' />
  260. </radialGradient>
  261. </defs>
  262. {/* 대양 (고정 배경 — 팬/줌 영향 없음) */}
  263. <rect x='0' y='0' width={VW} height={VH} rx='16' fill='url(#wm-ocean)' />
  264. {/* 팬/줌 그룹 — 육지만. 핀/라벨은 변환 밖에서 화면좌표로 그려 확대 시 크기 고정 + 라벨 겹침 회피 */}
  265. <g transform={`translate(${view.x} ${view.y}) scale(${view.k})`}>
  266. <g className='world-map__land'>
  267. {COUNTRY_PATHS.map((c, i) => (
  268. <path key={i} d={c.d} />
  269. ))}
  270. </g>
  271. </g>
  272. <g className='world-map__pins'>
  273. {pins.map((pin) => {
  274. const sx = view.x + pin.x * view.k;
  275. const sy = view.y + pin.y * view.k;
  276. if (sx < -24 || sx > VW + 24 || sy < -24 || sy > VH + 24) {
  277. return null;
  278. }
  279. const isActive = pin.row.countryCode === active;
  280. const showLabel = isActive || labeledSet.has(pin.row.countryCode);
  281. const leftSide = sx > VW * 0.72;
  282. const lx = leftSide ? -(pin.radius + 4) : pin.radius + 4;
  283. const anchor = leftSide ? 'end' : 'start';
  284. return (
  285. <g
  286. key={pin.row.countryCode}
  287. className={`world-map__pin world-map__pin--${pin.dir}${isActive ? ' is-active' : ''}`}
  288. transform={`translate(${sx.toFixed(1)} ${sy.toFixed(1)})`}
  289. role='button'
  290. tabIndex={0}
  291. aria-label={`${pin.label} ${pin.row.name} ${formatFlucRate(pin.row.flucRateBp)}`}
  292. onMouseEnter={() => setActive(pin.row.countryCode)}
  293. onMouseLeave={() => setActive((cur) => (cur === pin.row.countryCode ? null : cur))}
  294. onFocus={() => setActive(pin.row.countryCode)}
  295. onBlur={() => setActive((cur) => (cur === pin.row.countryCode ? null : cur))}
  296. onClick={() => onPinClick(pin.row)}
  297. onKeyDown={(e) => { if ((e.key === 'Enter' || e.key === ' ') && TV_SYMBOL[pin.row.countryCode]) { e.preventDefault(); setChartRow(pin.row); } }}
  298. >
  299. {/* map-pin: 지점에서 위로 뻗은 막대 + 머리(원) */}
  300. <line className='world-map__pin-stem' x1='0' y1='0' x2='0' y2={-PIN_H} />
  301. <circle className='world-map__pin-head' cx='0' cy={-PIN_H} r={pin.radius} />
  302. {/* 라벨 — 겹치지 않는 것만(활성 핀은 항상). 국가명 + 등락률 */}
  303. {showLabel && (
  304. <g className='world-map__label' transform={`translate(${lx} ${-PIN_H})`} textAnchor={anchor}>
  305. <text className='world-map__label-name' y='-2'>{pin.label}</text>
  306. <text className={`world-map__label-rate world-map__label-rate--${pin.dir}`} y='8.5'>{formatFlucRate(pin.row.flucRateBp)}</text>
  307. {isActive && <text className='world-map__label-close' y='18'>{formatIndexClose(pin.row.close)}</text>}
  308. </g>
  309. )}
  310. </g>
  311. );
  312. })}
  313. </g>
  314. </svg>
  315. {/* 줌 컨트롤 */}
  316. <div className='world-map__zoom'>
  317. <button type='button' className='world-map__zoom-btn' aria-label='확대' onClick={() => zoomBy(1.4)}>+</button>
  318. <button type='button' className='world-map__zoom-btn' aria-label='축소' onClick={() => zoomBy(1 / 1.4)}>−</button>
  319. <button type='button' className='world-map__zoom-btn' aria-label='초기화' title='초기화' onClick={() => setView(centeredView(DEFAULT_K))}>⤢</button>
  320. </div>
  321. </div>
  322. {/* 지수 패널 — 지역 탭 + 데이터 그리드 */}
  323. <div className='world-map__panel'>
  324. <div className='world-map__tabs' role='tablist' aria-label='지역'>
  325. {tabs.map((t) => (
  326. <button
  327. key={t}
  328. type='button'
  329. role='tab'
  330. aria-selected={t === activeRegion}
  331. className={`world-map__tab${t === activeRegion ? ' is-active' : ''}`}
  332. onClick={() => selectRegion(t)}
  333. >
  334. {REGION_LABELS[t]}
  335. </button>
  336. ))}
  337. </div>
  338. <div className='world-map__grid-wrap'>
  339. <table className='world-map__grid'>
  340. <thead>
  341. <tr>
  342. <th scope='col' className='world-map__c-name'>지수명</th>
  343. <th scope='col' className='world-map__c-num'>지수</th>
  344. <th scope='col' className='world-map__c-num'>전일비</th>
  345. <th scope='col' className='world-map__c-num'>등락률</th>
  346. <th scope='col' className='world-map__c-time'>시간</th>
  347. </tr>
  348. </thead>
  349. <tbody>
  350. {gridRows.map((row) => {
  351. const geo = EXCHANGE_GEO[row.countryCode];
  352. const dir = moveDir(row.flucRateBp);
  353. const isActive = row.countryCode === active;
  354. return (
  355. <tr
  356. key={row.countryCode}
  357. className={`world-map__row${isActive ? ' is-active' : ''}`}
  358. tabIndex={0}
  359. aria-label={TV_SYMBOL[row.countryCode] ? `${geo.label} ${row.name} 차트 보기` : `${geo.label} ${row.name} 지도에서 보기`}
  360. onMouseEnter={() => setActive(row.countryCode)}
  361. onMouseLeave={() => setActive((cur) => (cur === row.countryCode ? null : cur))}
  362. onClick={() => { if (TV_SYMBOL[row.countryCode]) { setChartRow(row); } else { setActive(row.countryCode); } }}
  363. onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); if (TV_SYMBOL[row.countryCode]) { setChartRow(row); } else { setActive(row.countryCode); } } }}
  364. >
  365. <td className='world-map__c-name'>
  366. <span className='world-map__row-country'>{geo.label}</span>
  367. <span className='world-map__row-name'>{row.name}</span>
  368. </td>
  369. <td className='world-map__c-num world-map__c-close'>{formatIndexClose(row.close)}</td>
  370. <td className={`world-map__c-num world-map__c-${dir}`}>{formatChangeVal(row.changeVal)}</td>
  371. <td className={`world-map__c-num world-map__c-${dir}`}>{formatFlucRate(row.flucRateBp)}</td>
  372. <td className='world-map__c-time'>{row.tradeDate}</td>
  373. </tr>
  374. );
  375. })}
  376. </tbody>
  377. </table>
  378. {gridRows.length === 0 && <div className='world-map__empty'>이 지역 지수 데이터가 없습니다.</div>}
  379. </div>
  380. </div>
  381. </div>
  382. {chartRow && TV_SYMBOL[chartRow.countryCode] && (
  383. <div
  384. className='world-map__modal'
  385. role='dialog'
  386. aria-modal='true'
  387. aria-label={`${EXCHANGE_GEO[chartRow.countryCode]?.label ?? ''} ${chartRow.name} 차트`}
  388. onClick={() => setChartRow(null)}
  389. >
  390. <div className='world-map__modal-panel' onClick={(e) => e.stopPropagation()}>
  391. <div className='world-map__modal-head'>
  392. <span className='world-map__modal-title'>
  393. {EXCHANGE_GEO[chartRow.countryCode]?.label} · {chartRow.name}
  394. </span>
  395. <button type='button' className='world-map__modal-close' aria-label='닫기' onClick={() => setChartRow(null)}>×</button>
  396. </div>
  397. <div className='world-map__modal-body'>
  398. <TradingViewChart symbol={TV_SYMBOL[chartRow.countryCode]} />
  399. </div>
  400. <p className='world-map__modal-note'>실시간 차트 제공 · TradingView</p>
  401. </div>
  402. </div>
  403. )}
  404. </section>
  405. );
  406. }