부품 데이터·관리 화면

면적 차트 area-chart

날짜별 값을 그리는 SVG 면적 차트. 계열 한두 개(이번 기간·이전 기간 점선), 세로·가로 눈금, 마우스나 좌우 화살표로 그날 값을 보는 툴팁. 폭에 맞춰 다시 그리며 외부 라이브러리를 쓰지 않는다. title 을 주면 제목·합계·범례가 붙은 카드가 된다.

  • 나온 곳 대시보드
  • 차트
  • 그래프
  • 매출 추이
  • SVG
  • 대시보드

설치

shadcn/ui 를 쓰는 Next.js 프로젝트에서 한 줄로 설치됩니다. 파일은 components/bpublish/area-chart.tsx 로 들어오고, 공통 토큰(base)도 같이 설치됩니다. 테마는 테마에서 하나 고릅니다.

npx shadcn@latest add https://www.bpublish.com/r/area-chart.json

레지스트리를 등록했다면 npx shadcn@latest add @bpublish/area-chart · 설치 안내

AI에게 맡기기

Claude Code, Cursor 같은 AI 코딩 도구에 붙여 넣으세요. MCP 서버를 연결해 두면 이름만 말해도 됩니다.

bpublish UI의 면적 차트(area-chart) 부품으로 만들어 줘. 설치: npx shadcn@latest add https://www.bpublish.com/r/area-chart.json · 문서: https://www.bpublish.com/designs/components/area-chart

사용 예시

app/page.tsx
'use client'

import { AreaChart } from '@/components/bpublish/area-chart'

/* 10월 22일 – 11월 20일 하루 매출(만원) */
const current = [434, 401, 469, 493, 425, 477, 443, 452, 454, 539, 476, 480, 456, 481, 456, 478, 498, 553, 459, 464, 454, 471, 466, 580, 534, 484, 467, 478, 489, 533]
const previous = [383, 356, 396, 418, 435, 439, 398, 426, 411, 418, 436, 437, 446, 411, 393, 379, 409, 380, 471, 454, 397, 441, 428, 414, 480, 459, 463, 406, 420, 460]

const labels = current.map((_, i) => {
  const d = new Date(2026, 9, 22 + i)
  return `${d.getMonth() + 1}.${d.getDate()}`
})

export default function Example() {
  return (
    <AreaChart
      title="매출 추이"
      description="10월 22일 – 11월 20일 · 이전 기간과 비교"
      value="1억 4,344만원"
      change={13.3}
      labels={labels}
      series={[
        { label: '이번 기간', values: current.map((v) => v * 1e4) },
        { label: '이전 기간', values: previous.map((v) => v * 1e4), dashed: true },
      ]}
      formatValue={(v) => `${v.toLocaleString('ko-KR')}원`}
    />
  )
}

속성

이름형식기본값설명
labels필수string[]—가로축 이름(날짜). 값 개수와 같게
series필수{ label: string; values: number[]; color?: string; dashed?: boolean }[]—계열 1–2개. 색 기본값 var(--chart-1), 둘째 점선은 var(--chart-5)
heightnumber280차트 높이(px)
formatValue(v: number) => string—툴팁 값 표기. 기본은 천 단위 쉼표
formatAxis(v: number) => string—세로축 눈금 표기. 기본은 1,200만 · 1.2억
labelstring—화면 읽기 프로그램용 차트 설명. 없으면 title
titlestring—주면 카드로 감싸고 제목을 단다
descriptionstring—제목 아래 기간·기준 한 줄
valuestring—제목 아래 큰 숫자(합계)
changenumber—큰 숫자 옆 증감률(%)

원본 코드

설치 명령 없이 그대로 복사해 넣어도 됩니다. React 외의 패키지는 쓰지 않습니다.

components/bpublish/area-chart.tsx
'use client'

/**
 * bpublish UI — 면적 차트. https://www.bpublish.com/designs/components/area-chart
 * 매출 추이처럼 날짜별 값을 그리는 SVG 차트. 계열은 한두 개(이번 기간·이전 기간),
 * 마우스를 올리거나 좌우 화살표로 그날 값을 본다. 폭에 맞춰 다시 그리고 외부 라이브러리를 쓰지 않는다.
 * title 을 주면 제목·합계·범례가 붙은 카드로 감싼다.
 */
import * as React from 'react'

export type AreaChartSeries = {
  label: string
  values: number[]
  /** 기본: 첫 계열 var(--chart-1), 둘째 계열은 점선이면 var(--chart-5) 아니면 var(--chart-2) */
  color?: string
  /** 점선으로 그리고 면을 채우지 않는다. 비교 기간에 쓴다 */
  dashed?: boolean
}

export type AreaChartProps = {
  /** 가로축 이름(날짜). 값 개수와 같아야 한다 */
  labels: string[]
  series: AreaChartSeries[]
  /** 차트 높이(px) */
  height?: number
  /** 툴팁의 값 표기 */
  formatValue?: (v: number) => string
  /** 세로축 눈금 표기 */
  formatAxis?: (v: number) => string
  /** 화면 읽기 프로그램이 읽을 설명. 없으면 title */
  label?: string
  /** 주면 카드로 감싸고 머리에 제목을 단다 */
  title?: string
  description?: string
  /** 제목 아래 큰 숫자(합계 등) */
  value?: string
  /** 큰 숫자 옆 증감률(%) */
  change?: number
  className?: string
}

const cx = (...v: Array<string | false | null | undefined>) => v.filter(Boolean).join(' ')
const n0 = new Intl.NumberFormat('ko-KR', { maximumFractionDigits: 0 })
const n1 = new Intl.NumberFormat('ko-KR', { maximumFractionDigits: 1 })
const plain = (v: number) => n0.format(v)
/** 1,200만 · 1.2억 처럼 좁은 자리에 맞춘 눈금 */
const compact = (v: number) => (v >= 1e8 ? `${n1.format(v / 1e8)}억` : v >= 1e4 ? `${n0.format(v / 1e4)}만` : n0.format(v))

const colorOf = (s: AreaChartSeries, i: number) => s.color ?? (i === 0 ? 'var(--chart-1)' : s.dashed ? 'var(--chart-5)' : 'var(--chart-2)')

export function AreaChart({ title, description, value, change, series, className, ...chart }: AreaChartProps) {
  if (!title) return <Plot series={series} className={className} {...chart} />
  return (
    <section className={cx('flex flex-col rounded-lg border border-border bg-card text-card-foreground', className)}>
      <header className="flex items-start justify-between gap-4 px-5 pt-5">
        <div className="min-w-0">
          <h2 className="text-sm font-semibold tracking-tight">{title}</h2>
          {description ? <p className="mt-1 text-[13px] leading-5 text-muted-foreground">{description}</p> : null}
        </div>
        {series.length > 1 ? (
          <ul className="hidden shrink-0 items-center gap-4 sm:flex">
            {series.map((s, i) => (
              <li key={s.label} className="flex items-center gap-1.5 text-xs text-muted-foreground">
                <svg aria-hidden viewBox="0 0 14 2" className="h-0.5 w-3.5">
                  <line x1="0" x2="14" y1="1" y2="1" stroke={colorOf(s, i)} strokeWidth="2" strokeDasharray={s.dashed ? '3.5 2.5' : undefined} />
                </svg>
                {s.label}
              </li>
            ))}
          </ul>
        ) : null}
      </header>
      {value ? (
        <div className="flex items-baseline gap-2.5 px-5 pt-4">
          <p className="text-[28px] leading-none font-semibold tracking-tight tabular-nums">{value}</p>
          {change !== undefined ? <Delta value={change} /> : null}
        </div>
      ) : null}
      <div className="mt-auto px-3 pt-4 pb-3">
        <Plot series={series} {...chart} label={chart.label ?? title} />
      </div>
    </section>
  )
}

function Delta({ value }: { value: number }) {
  const up = value >= 0
  return (
    <span
      className={cx(
        'inline-flex h-5 items-center gap-0.5 rounded-md px-1.5 text-xs font-semibold tabular-nums',
        up
          ? 'bg-[color-mix(in_oklab,var(--success,var(--foreground))_12%,transparent)] text-[color-mix(in_oklab,var(--success,var(--foreground))_85%,var(--foreground))]'
          : 'bg-destructive/10 text-destructive',
      )}
    >
      <svg aria-hidden viewBox="0 0 12 12" className={cx('size-3', !up && 'rotate-180')}>
        <path d="M6 2.5 9.5 7h-7L6 2.5Z" fill="currentColor" />
      </svg>
      {Math.abs(value).toFixed(1)}%<span className="sr-only">{up ? ' 증가' : ' 감소'}</span>
    </span>
  )
}

/* ── 차트 본체 ──────────────────────────────────────────────────── */

function Plot({
  labels,
  series,
  height = 280,
  formatValue = plain,
  formatAxis = compact,
  label,
  className,
}: Omit<AreaChartProps, 'title' | 'description' | 'value' | 'change'>) {
  const ref = React.useRef<HTMLDivElement>(null)
  const [width, setWidth] = React.useState(0)
  const [active, setActive] = React.useState<number | null>(null)

  React.useLayoutEffect(() => {
    const el = ref.current
    if (!el) return
    setWidth(el.getBoundingClientRect().width)
    const ro = new ResizeObserver(([e]) => setWidth(e.contentRect.width))
    ro.observe(el)
    return () => ro.disconnect()
  }, [])

  const n = labels.length
  const pad = { top: 12, right: 8, bottom: 28, left: 52 }
  const iw = Math.max(0, width - pad.left - pad.right)
  const ih = height - pad.top - pad.bottom
  const max = niceMax(Math.max(0, ...series.flatMap((s) => s.values)) * 1.04)
  const x = (i: number) => pad.left + (n <= 1 ? iw / 2 : (i / (n - 1)) * iw)
  const y = (v: number) => pad.top + ih - (v / max) * ih
  const ticks = [0, 0.25, 0.5, 0.75, 1].map((f) => f * max)
  /* 날짜 글자 하나가 차지하는 폭(약 56px)보다 촘촘하게 놓지 않는다 */
  const every = Math.max(1, Math.ceil(n / Math.max(2, Math.min(6, Math.floor(iw / 56)))))
  const xTicks = labels.map((_, i) => i).filter((i) => (n - 1 - i) % every === 0)

  const pick = (clientX: number, el: Element) => {
    const r = el.getBoundingClientRect()
    const i = Math.round(((clientX - r.left - pad.left) / (iw || 1)) * (n - 1))
    setActive(Math.max(0, Math.min(n - 1, i)))
  }
  const onKey = (e: React.KeyboardEvent) => {
    if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return
    e.preventDefault()
    setActive((a) => Math.max(0, Math.min(n - 1, (a ?? n - 1) + (e.key === 'ArrowRight' ? 1 : -1))))
  }
  const tipLeft = active === null ? 0 : Math.min(Math.max(x(active), pad.left + 80), width - 88)

  return (
    <div ref={ref} className={cx('relative w-full min-w-0 select-none', className)} style={{ height }}>
      {width > 0 ? (
        <svg
          role="img"
          aria-label={label}
          tabIndex={0}
          width={width}
          height={height}
          className="absolute inset-0 block rounded-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
          onPointerMove={(e) => pick(e.clientX, e.currentTarget)}
          onPointerLeave={() => setActive(null)}
          onKeyDown={onKey}
          onBlur={() => setActive(null)}
        >
          {ticks.map((t) => (
            <g key={t}>
              <line x1={pad.left} x2={width - pad.right} y1={y(t)} y2={y(t)} stroke="var(--border)" strokeDasharray={t === 0 ? undefined : '3 4'} />
              <text x={pad.left - 10} y={y(t)} dy="0.32em" textAnchor="end" className="fill-muted-foreground text-[11px] tabular-nums">
                {formatAxis(t)}
              </text>
            </g>
          ))}

          {xTicks.map((i) => (
            <text
              key={i}
              x={x(i)}
              y={height - 8}
              textAnchor={i === n - 1 ? 'end' : i === 0 ? 'start' : 'middle'}
              className="fill-muted-foreground text-[11px] tabular-nums"
            >
              {labels[i]}
            </text>
          ))}

          {series.map((s, si) => {
            const color = colorOf(s, si)
            const line = monotone(s.values.map((v, i) => [x(i), y(v)] as const))
            return (
              <g key={s.label}>
                {s.dashed ? null : <path d={`${line}L${x(n - 1)},${y(0)}L${x(0)},${y(0)}Z`} fill={color} fillOpacity={0.09} />}
                <path
                  d={line}
                  fill="none"
                  stroke={color}
                  strokeWidth={s.dashed ? 1.5 : 2}
                  strokeDasharray={s.dashed ? '4 4' : undefined}
                  strokeLinejoin="round"
                  strokeLinecap="round"
                />
              </g>
            )
          })}

          {active !== null ? (
            <g>
              <line x1={x(active)} x2={x(active)} y1={pad.top} y2={pad.top + ih} stroke="var(--foreground)" strokeOpacity={0.18} />
              {series.map((s, si) => (
                <circle key={s.label} cx={x(active)} cy={y(s.values[active])} r={4} fill="var(--card)" stroke={colorOf(s, si)} strokeWidth={2} />
              ))}
            </g>
          ) : null}
        </svg>
      ) : null}

      {active !== null ? (
        <div
          aria-live="polite"
          className="pointer-events-none absolute top-1 z-10 min-w-40 -translate-x-1/2 rounded-lg border border-border bg-popover px-3 py-2.5 text-popover-foreground shadow-lg"
          style={{ left: tipLeft }}
        >
          <p className="text-xs font-medium text-muted-foreground tabular-nums">{labels[active]}</p>
          <ul className="mt-1.5 space-y-1">
            {series.map((s, si) => (
              <li key={s.label} className="flex items-center justify-between gap-4 text-[13px]">
                <span className="flex items-center gap-1.5 text-muted-foreground">
                  <span aria-hidden className="size-2 rounded-sm" style={{ backgroundColor: colorOf(s, si) }} />
                  {s.label}
                </span>
                <span className="font-semibold tabular-nums">{formatValue(s.values[active])}</span>
              </li>
            ))}
          </ul>
        </div>
      ) : null}
    </div>
  )
}

/** 눈금이 떨어지는 보기 좋은 최댓값 */
function niceMax(max: number, ticks = 4) {
  if (max <= 0) return 1
  const mag = 10 ** Math.floor(Math.log10(max / ticks))
  const step = [1, 2, 2.5, 5, 10].map((s) => s * mag).find((s) => s * ticks >= max) ?? 10 * mag
  return step * ticks
}

/** 값의 오르내림을 넘어서지 않는 부드러운 곡선 (Fritsch–Carlson) */
function monotone(pts: ReadonlyArray<readonly [number, number]>) {
  const n = pts.length
  if (n < 2) return n ? `M${pts[0][0]},${pts[0][1]}` : ''
  const dx: number[] = []
  const m: number[] = []
  for (let i = 0; i < n - 1; i++) {
    dx[i] = pts[i + 1][0] - pts[i][0]
    m[i] = (pts[i + 1][1] - pts[i][1]) / (dx[i] || 1)
  }
  const t: number[] = [m[0]]
  for (let i = 1; i < n - 1; i++) {
    t[i] = m[i - 1] * m[i] <= 0 ? 0 : (3 * (dx[i - 1] + dx[i])) / ((2 * dx[i] + dx[i - 1]) / m[i - 1] + (dx[i] + 2 * dx[i - 1]) / m[i])
  }
  t[n - 1] = m[n - 2]
  let d = `M${pts[0][0]},${pts[0][1]}`
  for (let i = 0; i < n - 1; i++) {
    const h = dx[i] / 3
    d += `C${pts[i][0] + h},${pts[i][1] + t[i] * h} ${pts[i + 1][0] - h},${pts[i + 1][1] - t[i + 1] * h} ${pts[i + 1][0]},${pts[i + 1][1]}`
  }
  return d
}