feat(home+search): KOSPI/KOSDAQ 인덱스 카드 + 검색결과 미니 sparkline

- Sparkline 컴포넌트를 PriceHero 내부에서 web/components/Sparkline.tsx 로 분리·재사용
- /api/markets/indices: macro_daily 의 kospi/kosdaq N일 시계열 + 최신값/전일대비
- 홈 IndicesPanel: 두 인덱스 카드(현재값/등락/우측 sparkline)
- /api/symbols/search?with_sparkline=true: 결과 한 번에 최근 30 종가 batch 조회
- SearchBox 결과 행에 mini sparkline + 현재가/등락률 인라인 표시

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
claude-owner
2026-05-28 14:46:13 +09:00
parent 66a28cc7ca
commit ae4f07d675
8 changed files with 330 additions and 71 deletions

View File

@@ -1,3 +1,4 @@
import { IndicesPanel } from "../components/IndicesPanel";
import { MarketsOverview } from "../components/MarketsOverview";
import { SearchBox } from "../components/SearchBox";
import { SeedTiles } from "../components/SeedTiles";
@@ -16,7 +17,11 @@ export default function HomePage() {
<SearchBox autoFocus />
</div>
<div className="mt-10">
<div className="mt-8">
<IndicesPanel />
</div>
<div className="mt-8">
<SeedTiles />
</div>

View File

@@ -0,0 +1,90 @@
"use client";
// 홈 상단에 KOSPI / KOSDAQ 인덱스 두 칸. 우측엔 mini sparkline.
// macro_daily 가 아직 비어 있으면 안내 카드 한 줄.
import { useEffect, useState } from "react";
import { api, type IndicesResponse, type IndexSeries } from "../lib/api";
import { Sparkline } from "./Sparkline";
export function IndicesPanel() {
const [data, setData] = useState<IndicesResponse | null>(null);
const [err, setErr] = useState<string | null>(null);
useEffect(() => {
let alive = true;
api
.indices(60)
.then((r) => {
if (alive) setData(r);
})
.catch((e) => {
if (alive) setErr(e instanceof Error ? e.message : String(e));
});
return () => {
alive = false;
};
}, []);
if (err)
return (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/30 p-4 text-xs text-zinc-500">
: {err}
</div>
);
if (!data)
return (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/30 p-4 text-xs text-zinc-500">
</div>
);
const allEmpty = data.indices.every((s) => s.points.length === 0);
if (allEmpty)
return (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/30 p-4 text-xs text-zinc-500">
. macro_daily .
</div>
);
return (
<div className="grid gap-3 md:grid-cols-2">
{data.indices.map((s) => (
<IndexCard key={s.key} s={s} />
))}
</div>
);
}
function IndexCard({ s }: { s: IndexSeries }) {
const pct = s.pct_change;
const tone =
pct == null || pct === 0
? "text-zinc-400"
: pct > 0
? "text-rose-400"
: "text-sky-400";
const stroke = pct != null && pct < 0 ? "#3b82f6" : "#ef4444";
const values = s.points.map((p) => p.value);
return (
<div className="flex items-center justify-between gap-3 rounded-lg border border-zinc-800 bg-zinc-900/40 p-3">
<div className="min-w-0">
<div className="text-xs text-zinc-500">{s.name}</div>
<div className="mt-0.5 text-xl font-semibold tabular-nums text-zinc-50">
{s.latest != null
? s.latest.toLocaleString(undefined, { maximumFractionDigits: 2 })
: "—"}
</div>
<div className={`mt-0.5 text-xs tabular-nums ${tone}`}>
{pct != null
? `${pct >= 0 ? "+" : ""}${pct.toFixed(2)}%`
: "—"}
</div>
</div>
{values.length >= 2 && (
<Sparkline values={values} stroke={stroke} width={120} height={40} />
)}
</div>
);
}

View File

@@ -4,6 +4,8 @@
// 표시: 종목명 / (코드·시장) / 현재가 / 전일대비 + 우측에 sparkline.
// 한국 거래소 관행대로 상승=빨강, 하락=파랑.
import { Sparkline } from "./Sparkline";
type Props = {
name: string;
code: string;
@@ -59,38 +61,3 @@ export function PriceHero({ name, code, market, current, prev, asOf, series }: P
</div>
);
}
// 가벼운 SVG sparkline. lightweight-charts 인스턴스를 또 만들 필요 없음.
function Sparkline({ values, stroke }: { values: number[]; stroke: string }) {
const W = 140;
const H = 44;
const min = Math.min(...values);
const max = Math.max(...values);
const span = max - min || 1;
const stepX = W / (values.length - 1);
const points = values
.map((v, i) => {
const x = (i * stepX).toFixed(1);
const y = (H - ((v - min) / span) * H).toFixed(1);
return `${x},${y}`;
})
.join(" ");
return (
<svg
width={W}
height={H}
viewBox={`0 0 ${W} ${H}`}
className="shrink-0 opacity-80"
aria-hidden
>
<polyline
points={points}
fill="none"
stroke={stroke}
strokeWidth={1.5}
strokeLinejoin="round"
strokeLinecap="round"
/>
</svg>
);
}

View File

@@ -3,6 +3,7 @@
import Link from "next/link";
import { useEffect, useState } from "react";
import { api, type Symbol } from "../lib/api";
import { Sparkline } from "./Sparkline";
export function SearchBox({ autoFocus = false }: { autoFocus?: boolean }) {
const [q, setQ] = useState("");
@@ -22,7 +23,8 @@ export function SearchBox({ autoFocus = false }: { autoFocus?: boolean }) {
setErr(null);
const handle = setTimeout(async () => {
try {
const r = await api.search(term, seedOnly, 15);
// with_sparkline=true: 백엔드가 최근 30 종가 + close + pct_change 동봉.
const r = await api.search(term, seedOnly, 15, true);
setItems(r.items);
} catch (e) {
setErr(e instanceof Error ? e.message : String(e));
@@ -63,31 +65,61 @@ export function SearchBox({ autoFocus = false }: { autoFocus?: boolean }) {
{items.length > 0 && (
<ul className="mt-2 divide-y divide-zinc-800 rounded-md border border-zinc-800 bg-zinc-900/40">
{items.map((it) => (
<li key={it.code}>
<Link
href={`/${it.code}`}
className="flex items-center justify-between px-4 py-3 text-sm hover:bg-zinc-800/70"
>
<div>
<div className="font-medium text-zinc-100">
{it.name}
{it.is_seed && (
<span className="ml-2 rounded-full bg-emerald-900/60 px-2 py-0.5 text-[10px] font-semibold text-emerald-300">
SEED
</span>
)}
</div>
<div className="text-xs text-zinc-500">
{it.code} · {it.market}
{it.sector ? ` · ${it.sector}` : ""}
</div>
</div>
<span className="text-zinc-500"></span>
</Link>
</li>
<SearchRow key={it.code} it={it} />
))}
</ul>
)}
</div>
);
}
function SearchRow({ it }: { it: Symbol }) {
const pct = it.pct_change ?? null;
const tone =
pct == null || pct === 0
? "text-zinc-400"
: pct > 0
? "text-rose-400"
: "text-sky-400";
const stroke = pct != null && pct < 0 ? "#3b82f6" : "#ef4444";
const series = it.sparkline ?? [];
return (
<li>
<Link
href={`/${it.code}`}
className="flex items-center justify-between gap-3 px-4 py-3 text-sm hover:bg-zinc-800/70"
>
<div className="min-w-0">
<div className="font-medium text-zinc-100">
{it.name}
{it.is_seed && (
<span className="ml-2 rounded-full bg-emerald-900/60 px-2 py-0.5 text-[10px] font-semibold text-emerald-300">
SEED
</span>
)}
</div>
<div className="text-xs text-zinc-500">
{it.code} · {it.market}
{it.sector ? ` · ${it.sector}` : ""}
</div>
</div>
<div className="flex shrink-0 items-center gap-3">
{series.length >= 2 && (
<Sparkline values={series} stroke={stroke} width={80} height={28} />
)}
<div className="text-right tabular-nums">
<div className="text-xs text-zinc-100">
{it.close != null
? it.close.toLocaleString(undefined, { maximumFractionDigits: 0 })
: "—"}
</div>
<div className={`text-[11px] ${tone}`}>
{pct != null ? `${pct >= 0 ? "+" : ""}${pct.toFixed(2)}%` : ""}
</div>
</div>
</div>
</Link>
</li>
);
}

View File

@@ -0,0 +1,49 @@
// 가벼운 SVG sparkline. lightweight-charts 인스턴스를 또 만들 필요 없음.
// 종가 시계열을 받아 polyline 으로 그린다. 색상은 호출부에서 결정 (KR 관행: 상승=빨강, 하락=파랑).
type Props = {
values: number[];
stroke: string;
width?: number;
height?: number;
className?: string;
};
export function Sparkline({
values,
stroke,
width = 140,
height = 44,
className,
}: Props) {
if (values.length < 2) return null;
const min = Math.min(...values);
const max = Math.max(...values);
const span = max - min || 1;
const stepX = width / (values.length - 1);
const points = values
.map((v, i) => {
const x = (i * stepX).toFixed(1);
const y = (height - ((v - min) / span) * height).toFixed(1);
return `${x},${y}`;
})
.join(" ");
return (
<svg
width={width}
height={height}
viewBox={`0 0 ${width} ${height}`}
className={`shrink-0 opacity-80 ${className ?? ""}`}
aria-hidden
>
<polyline
points={points}
fill="none"
stroke={stroke}
strokeWidth={1.5}
strokeLinejoin="round"
strokeLinecap="round"
/>
</svg>
);
}

View File

@@ -33,6 +33,10 @@ export type Symbol = {
market: string;
sector: string | null;
is_seed: boolean;
// with_sparkline=true 일 때만 채워짐.
sparkline?: number[];
close?: number | null;
pct_change?: number | null;
};
export type SymbolSearch = {
@@ -205,6 +209,22 @@ export type ThemeDetailResponse = {
items: Mover[];
};
export type IndexPoint = { date: string; value: number };
export type IndexSeries = {
key: "kospi" | "kosdaq";
name: string;
points: IndexPoint[];
latest: number | null;
prev: number | null;
pct_change: number | null;
};
export type IndicesResponse = {
days: number;
indices: IndexSeries[];
};
async function getJson<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
...init,
@@ -222,9 +242,9 @@ async function getJson<T>(path: string, init?: RequestInit): Promise<T> {
}
export const api = {
search: (q: string, seedOnly = false, limit = 20) =>
search: (q: string, seedOnly = false, limit = 20, withSparkline = false) =>
getJson<SymbolSearch>(
`/api/symbols/search?q=${encodeURIComponent(q)}&limit=${limit}&seed_only=${seedOnly}`,
`/api/symbols/search?q=${encodeURIComponent(q)}&limit=${limit}&seed_only=${seedOnly}&with_sparkline=${withSparkline}`,
),
getSymbol: (code: string) => getJson<Symbol>(`/api/symbols/${encodeURIComponent(code)}`),
getChart: (code: string, days = 180, interval: ChartInterval = "1d") =>
@@ -258,6 +278,7 @@ export const api = {
getJson<RelatedResponse>(
`/api/markets/related/${encodeURIComponent(code)}?limit=${limit}`,
),
indices: (days = 60) => getJson<IndicesResponse>(`/api/markets/indices?days=${days}`),
themesIndex: () => getJson<ThemesIndexResponse>(`/api/themes`),
themeDetail: (slug: string, limit = 30) =>
getJson<ThemeDetailResponse>(