리뷰어 093ac86 지적 처리:
- 종목 페이지 단축키 핸들러 (←/→/S) 에 modal 가드 추가.
`document.querySelector('[role="dialog"][aria-modal="true"]')` 가 매치되면
return — ShortcutsHelp 같은 모달이 열린 상태에서 close 버튼이 포커스를
잡고 있어도 페이지 단축키가 뒤에서 동작하지 않도록.
- StockChart 의 F 단축키에도 동일한 modal 가드 — 동일 문제 (모달 위에서
F 가 차트 전체화면 토글) 차단.
신규 슬라이스 — 차트 수평선 그리기 도구:
- `web/lib/lines.ts` — `hlines:<code>` 키 localStorage. id 단위 add/remove/clear,
최대 10 개, 같은 가격 중복 추가 방지(부동소수 4 자리 비교), crypto.randomUUID
폴백 포함.
- StockChart 툴바: `─ 수평선 (N/10)` 버튼 — hover 가격 또는 마지막 봉 종가에
추가. 한도 도달 / 가격 없음이면 disabled.
- 추가된 라인은 chips 형태로 toolbar 아래 한 줄에 표시 — 각각 ✕ 로 제거,
`전체 해제` 버튼 별도.
- H 키 단축키 — modifier/editable/modal 가드 일관 적용. 가격은 ref 로 들고
있어 keydown effect 가 재구독되지 않음.
- 차트엔 `createPriceLine` 으로 zinc-400 solid 라인 (목표/손절의 점선과 톤
분리). 종목 전환 시 자동 reload.
- ShortcutsHelp 에 H 단축키 등록.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
270 lines
10 KiB
TypeScript
270 lines
10 KiB
TypeScript
"use client";
|
|
|
|
import Link from "next/link";
|
|
import { useEffect, useMemo, useState } from "react";
|
|
import { AlertsPanel } from "../../components/AlertsPanel";
|
|
import { CompositeScoreCard } from "../../components/CompositeScoreCard";
|
|
import { DisclosuresPanel } from "../../components/DisclosuresPanel";
|
|
import { InvestmentNote } from "../../components/InvestmentNote";
|
|
import { InvestorCumulative } from "../../components/InvestorCumulative";
|
|
import { MetricsPanel } from "../../components/MetricsPanel";
|
|
import { PeerComparePanel } from "../../components/PeerComparePanel";
|
|
import { NewsList } from "../../components/NewsList";
|
|
import { OrderbookPanel } from "../../components/OrderbookPanel";
|
|
import { PeriodReturns } from "../../components/PeriodReturns";
|
|
import { PeriodTabs, periodNeighbor, periodSpec, type Period } from "../../components/PeriodTabs";
|
|
import { PredictionPanel } from "../../components/PredictionPanel";
|
|
import { PriceHero } from "../../components/PriceHero";
|
|
import { PriceTargets } from "../../components/PriceTargets";
|
|
import { RelatedStocks } from "../../components/RelatedStocks";
|
|
import { ShareButton } from "../../components/ShareButton";
|
|
import { StarButton } from "../../components/StarButton";
|
|
import { StockChart } from "../../components/StockChart";
|
|
import { SymbolSidebar } from "../../components/SymbolSidebar";
|
|
import { TradingValuePanel } from "../../components/TradingValuePanel";
|
|
import { api, type ChartPayload, type LatestPredictionResponse } from "../../lib/api";
|
|
import { recent } from "../../lib/recent";
|
|
import { readTargets, type Targets } from "../../lib/targets";
|
|
import { watchlist } from "../../lib/watchlist";
|
|
import { markRecorded, wasRecordedToday } from "../../lib/views";
|
|
|
|
export default function CodePage({ params }: { params: { code: string } }) {
|
|
const { code } = params;
|
|
const [chart, setChart] = useState<ChartPayload | null>(null);
|
|
const [prediction, setPrediction] = useState<LatestPredictionResponse | null>(null);
|
|
const [err, setErr] = useState<string | null>(null);
|
|
const [period, setPeriod] = useState<Period>("3M");
|
|
const [viewsToday, setViewsToday] = useState<number | null>(null);
|
|
const [targets, setTargets] = useState<Targets>({});
|
|
|
|
const spec = periodSpec(period);
|
|
const isIntraday = spec.interval === "10m";
|
|
|
|
// 종목 페이지 방문 시 최근 본 종목에 push.
|
|
useEffect(() => {
|
|
recent.push(code);
|
|
}, [code]);
|
|
|
|
// 조회 카운터.
|
|
// - 같은 (code, KST today) 는 localStorage 마크로 dedupe → POST 1회.
|
|
// - dedupe 실패 (스토리지 잠금 등) 해도 GET 으로 today_views 는 조회.
|
|
// - POST 응답이 today_views 를 주므로 별도 GET 안 해도 됨 (한 라운드트립으로 끝).
|
|
// - 이미 봤던 종목이면 GET 만.
|
|
useEffect(() => {
|
|
let alive = true;
|
|
const apply = (n: number) => {
|
|
if (alive) setViewsToday(n);
|
|
};
|
|
if (!wasRecordedToday(code)) {
|
|
api.recordView(code)
|
|
.then((r) => {
|
|
// POST 성공 후에만 mark — 실패 시 다음 방문에 다시 시도 가능.
|
|
markRecorded(code);
|
|
apply(r.today_views);
|
|
})
|
|
.catch(() => {
|
|
// POST 실패 시 GET 한 번 시도 (혹시 다른 사용자 카운트라도 보여줌).
|
|
api.views(code).then((r) => apply(r.today_views)).catch(() => {});
|
|
});
|
|
} else {
|
|
api.views(code).then((r) => apply(r.today_views)).catch(() => {});
|
|
}
|
|
return () => {
|
|
alive = false;
|
|
};
|
|
}, [code]);
|
|
|
|
// 저장된 목표가/손절가 — 마운트 + 종목 전환 시 localStorage 에서 로드.
|
|
useEffect(() => {
|
|
setTargets(readTargets(code));
|
|
}, [code]);
|
|
|
|
// 종목 페이지 키보드 단축키:
|
|
// ←/→ : 기간 탭 이전/다음 (양끝 clamp — wrap 안 함, 사용자가 끝 인지)
|
|
// S : 관심종목 토글
|
|
// 입력 필드(검색창, 메모 등) 포커스 시 무시 — 텍스트 편집 방해 금지.
|
|
// modifier(Ctrl/Cmd/Alt) 가 눌리면 브라우저/OS 단축키 양보.
|
|
useEffect(() => {
|
|
if (typeof window === "undefined") return;
|
|
const isEditableTarget = (t: EventTarget | null): boolean => {
|
|
if (!(t instanceof HTMLElement)) return false;
|
|
const tag = t.tagName;
|
|
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return true;
|
|
if (t.isContentEditable) return true;
|
|
return false;
|
|
};
|
|
const onKey = (e: KeyboardEvent) => {
|
|
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
|
if (isEditableTarget(e.target)) return;
|
|
// 모달/대화상자가 열려 있으면 뒤의 페이지 단축키를 가로채지 않음.
|
|
// ShortcutsHelp 처럼 close 버튼이 포커스 잡혀 있어도 editable 가드는 통과되므로,
|
|
// 페이지 단축키가 뒤에서 작동하는 것을 막기 위해 aria-modal 으로 추가 확인.
|
|
if (document.querySelector('[role="dialog"][aria-modal="true"]')) return;
|
|
if (e.key === "ArrowLeft") {
|
|
e.preventDefault();
|
|
setPeriod((cur) => periodNeighbor(cur, -1));
|
|
} else if (e.key === "ArrowRight") {
|
|
e.preventDefault();
|
|
setPeriod((cur) => periodNeighbor(cur, 1));
|
|
} else if (e.key === "s" || e.key === "S") {
|
|
e.preventDefault();
|
|
watchlist.toggle(code);
|
|
}
|
|
};
|
|
window.addEventListener("keydown", onKey);
|
|
return () => window.removeEventListener("keydown", onKey);
|
|
}, [code]);
|
|
|
|
useEffect(() => {
|
|
let alive = true;
|
|
setErr(null);
|
|
setChart(null);
|
|
|
|
const load = () => {
|
|
api
|
|
.getChart(code, spec.days, spec.interval)
|
|
.then((c) => {
|
|
if (alive) setChart(c);
|
|
})
|
|
.catch((e) => {
|
|
if (alive) setErr(e instanceof Error ? e.message : String(e));
|
|
});
|
|
};
|
|
load();
|
|
|
|
// 1일(10분봉) 모드만 60s 폴링 — 백엔드가 10분 내면 DB 만 읽음.
|
|
if (isIntraday) {
|
|
const h = window.setInterval(load, 60_000);
|
|
return () => {
|
|
alive = false;
|
|
window.clearInterval(h);
|
|
};
|
|
}
|
|
return () => {
|
|
alive = false;
|
|
};
|
|
}, [code, spec.days, spec.interval, isIntraday]);
|
|
|
|
useEffect(() => {
|
|
let alive = true;
|
|
api
|
|
.latestPrediction(code)
|
|
.then((r) => {
|
|
if (alive && r.found) setPrediction(r);
|
|
})
|
|
.catch(() => {
|
|
// 예측 이력 없음 — 무시
|
|
});
|
|
return () => {
|
|
alive = false;
|
|
};
|
|
}, [code]);
|
|
|
|
// 현재가/전일가 + 헤더 sparkline 시리즈 — ohlcv 끝부분에서 산출.
|
|
const { current, prev, asOf, sparkSeries } = useMemo(() => {
|
|
if (!chart || !chart.ohlcv.length)
|
|
return { current: null, prev: null, asOf: null, sparkSeries: [] as number[] };
|
|
const valid = chart.ohlcv.filter((p) => p.close != null);
|
|
if (!valid.length)
|
|
return { current: null, prev: null, asOf: null, sparkSeries: [] as number[] };
|
|
const last = valid[valid.length - 1];
|
|
const prevPt = valid.length >= 2 ? valid[valid.length - 2] : null;
|
|
// 최근 30개 종가 (없으면 가용 전체).
|
|
const recent = valid.slice(-30).map((p) => p.close as number);
|
|
return {
|
|
current: last.close,
|
|
prev: prevPt?.close ?? null,
|
|
asOf: last.date,
|
|
sparkSeries: recent,
|
|
};
|
|
}, [chart]);
|
|
|
|
return (
|
|
<main className="mx-auto max-w-5xl px-6 py-8">
|
|
<div className="mb-4 flex items-center justify-between gap-3">
|
|
<div className="flex items-center gap-3">
|
|
<Link href="/" className="text-xs text-zinc-500 hover:text-zinc-300">
|
|
← 검색
|
|
</Link>
|
|
<Link
|
|
href="/watchlist"
|
|
className="text-xs text-zinc-500 hover:text-zinc-300"
|
|
>
|
|
관심종목
|
|
</Link>
|
|
</div>
|
|
<div className="flex items-center gap-3">
|
|
<Link
|
|
href={`/compare?codes=${code}`}
|
|
className="rounded-md border border-zinc-700 px-2 py-0.5 text-[11px] text-zinc-400 hover:border-zinc-500 hover:text-zinc-200"
|
|
title="이 종목으로 비교 시작"
|
|
>
|
|
⇄ 비교
|
|
</Link>
|
|
<ShareButton code={code} name={chart?.name} />
|
|
<StarButton code={code} name={chart?.name} />
|
|
<PeriodTabs value={period} onChange={(id) => setPeriod(id)} />
|
|
</div>
|
|
</div>
|
|
|
|
{err && <div className="mb-4 text-sm text-red-400">차트 로딩 실패: {err}</div>}
|
|
|
|
{chart && (
|
|
<>
|
|
<PriceHero
|
|
name={chart.name}
|
|
code={chart.code}
|
|
market={chart.market}
|
|
current={current}
|
|
prev={prev}
|
|
asOf={asOf}
|
|
series={sparkSeries}
|
|
viewsToday={viewsToday}
|
|
/>
|
|
<div className="grid gap-6 lg:grid-cols-[1fr_280px]">
|
|
<div>
|
|
<StockChart chart={chart} prediction={prediction} targets={targets} />
|
|
{isIntraday && chart.intraday_status && (
|
|
<div className="mt-2 text-right text-[11px] text-zinc-500">
|
|
실시간 10분봉 · 60초 갱신 · [{chart.intraday_status}]
|
|
</div>
|
|
)}
|
|
<div className="mt-6">
|
|
<PredictionPanel code={code} initial={prediction} onResult={setPrediction} />
|
|
</div>
|
|
</div>
|
|
<div className="space-y-4">
|
|
<SymbolSidebar code={code} />
|
|
<OrderbookPanel code={code} />
|
|
<PriceTargets code={code} current={current} onChange={setTargets} />
|
|
<AlertsPanel code={code} name={chart?.name} current={current} />
|
|
<InvestmentNote code={code} />
|
|
<RelatedStocks code={code} />
|
|
</div>
|
|
</div>
|
|
<div className="mt-6">
|
|
<CompositeScoreCard chart={chart} />
|
|
</div>
|
|
<div className="mt-6">
|
|
<PeriodReturns ohlcv={chart.ohlcv} />
|
|
</div>
|
|
<div className="mt-6">
|
|
<PeerComparePanel code={code} />
|
|
</div>
|
|
<div className="mt-6 grid gap-6 md:grid-cols-2">
|
|
<TradingValuePanel data={chart.trading_value} />
|
|
<InvestorCumulative data={chart.trading_value} />
|
|
</div>
|
|
<div className="mt-6">
|
|
<MetricsPanel code={code} />
|
|
</div>
|
|
<div className="mt-6 grid gap-6 md:grid-cols-2">
|
|
<NewsList code={code} />
|
|
<DisclosuresPanel code={code} />
|
|
</div>
|
|
</>
|
|
)}
|
|
</main>
|
|
);
|
|
}
|