Files
Aislo/ui_template/ui_template_elements_chart.ts
T
eomsangdonandClaude Opus 5 41cfab22e9 refactor(ui_template): 공통 컴포넌트 700줄 초과 분리 — 차트·기본 스타일
917줄 한 파일을 넷으로 나눔 (동작 불변, 순수 이동).
- `ui_template_elements.ts` 363줄 — 버튼·입력·선택·카드·태그·토스트·확인창·셸
- `ui_template_elements_styles.ts` 369줄 — `injectBaseStyles()` 와 규칙 문자열
- `ui_template_elements_chart.ts` 185줄 — 공통 라인 차트
- `ui_template_elements_base.ts` 33줄 — 요소 생성 헬퍼 `el` (셋이 함께 써 순환 방지)

본체가 `export *` 로 다시 내보내 호출부의 import 경로는 불변.

검증: 분리 전 `export` 25개 전부 유지(+`el` 공개 1개 추가), `tsc --noEmit` 통과,
tmp/tests 378 passed

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 11:19:04 +09:00

186 lines
7.0 KiB
TypeScript

/* =============================================================================
* ui_template_elements_chart.ts
* 공통 라인 차트 — 대시보드 리소스 그래프에 쓰는 SVG 꺾은선.
*
* `ui_template_elements.ts` 가 700줄을 넘어 떼어냈다(2026-09-04). 본체가 그대로
* 다시 내보내므로 호출부의 import 경로는 바뀌지 않는다.
* ========================================================================== */
import { el } from "./ui_template_elements_base";
export interface LineChartSeries {
/** 범례에 표시할 이름 (i18n 결과 문자열) */
name: string;
/** y 값 배열 (x는 인덱스 순서, null은 결측으로 선 끊김) */
values: (number | null)[];
/** 선 색상 클래스 접미사: 0~3 (theme.css의 --color-chart-N 참조) */
colorIndex?: 0 | 1 | 2 | 3;
}
export interface LineChartOptions {
series: LineChartSeries[];
/** x축 라벨 (values와 같은 길이 권장, 일부만 자동 선택 표기) */
xLabels?: string[];
/** y축 최대값 (기본: 100 = 퍼센트) */
yMax?: number;
/** y축 단위 접미사 (기본: "%") */
yUnit?: string;
/** 접근성 설명 */
ariaLabel?: string;
/** 커스텀 가상 가로폭 (기본: CHART_W = 640) */
width?: number;
/** 커스텀 가상 세로폭 (기본: CHART_H = 200) */
height?: number;
}
const CHART_W = 640;
const CHART_H = 200;
const CHART_PAD = { top: 12, right: 12, bottom: 26, left: 36 };
const X_TICK_STEP = 3; // x축 라벨 표기 간격 (3개마다 1개 표시)
/** 유효 점들을 Catmull-Rom → 3차 베지어로 변환한 스플라인 path 데이터를 만든다. */
function splinePath(points: { x: number; y: number }[]): string {
if (points.length === 0) return "";
if (points.length === 1) return `M${points[0].x},${points[0].y}`;
let d = `M${points[0].x.toFixed(1)},${points[0].y.toFixed(1)}`;
for (let i = 0; i < points.length - 1; i += 1) {
const p0 = points[i - 1] ?? points[i];
const p1 = points[i];
const p2 = points[i + 1];
const p3 = points[i + 2] ?? p2;
// Catmull-Rom (tension 1/6) → cubic Bézier 제어점
const c1x = p1.x + (p2.x - p0.x) / 6;
const c1y = p1.y + (p2.y - p0.y) / 6;
const c2x = p2.x - (p3.x - p1.x) / 6;
const c2y = p2.y - (p3.y - p1.y) / 6;
d +=
` C${c1x.toFixed(1)},${c1y.toFixed(1)} ` +
`${c2x.toFixed(1)},${c2y.toFixed(1)} ` +
`${p2.x.toFixed(1)},${p2.y.toFixed(1)}`;
}
return d;
}
/** 시계열 스플라인 차트를 반환. 데이터가 없으면 안내 문구를 담은 빈 상태를 반환. */
export function createLineChart(opts: LineChartOptions): HTMLDivElement {
const w = opts.width ?? CHART_W;
const h = opts.height ?? CHART_H;
const yMax = opts.yMax ?? 100;
const yUnit = opts.yUnit ?? "%";
const wrap = el("div", { className: "ui-chart" });
const pointCount = Math.max(0, ...opts.series.map((s) => s.values.length));
if (pointCount < 2) {
wrap.append(el("div", { className: "ui-chart__empty", text: "—" }));
wrap.setAttribute("data-empty", "true");
return wrap;
}
const plotW = w - CHART_PAD.left - CHART_PAD.right;
const plotH = h - CHART_PAD.top - CHART_PAD.bottom;
const xAt = (i: number) => CHART_PAD.left + (plotW * i) / (pointCount - 1);
const yAt = (v: number) => CHART_PAD.top + plotH * (1 - Math.min(v, yMax) / yMax);
const svgNs = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNs, "svg");
svg.setAttribute("class", "ui-chart__svg");
svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
svg.setAttribute("role", "img");
svg.setAttribute("width", "100%");
svg.setAttribute("height", "100%");
svg.setAttribute("preserveAspectRatio", "none");
if (opts.ariaLabel) svg.setAttribute("aria-label", opts.ariaLabel);
// y축 그리드 + 라벨 (0, 25, 50, 75, 100%)
for (let g = 0; g <= 4; g += 1) {
const v = (yMax / 4) * g;
const y = yAt(v);
const line = document.createElementNS(svgNs, "line");
line.setAttribute("class", "ui-chart__grid");
line.setAttribute("x1", String(CHART_PAD.left));
line.setAttribute("x2", String(w - CHART_PAD.right));
line.setAttribute("y1", String(y));
line.setAttribute("y2", String(y));
svg.append(line);
const tick = document.createElementNS(svgNs, "text");
tick.setAttribute("class", "ui-chart__tick");
tick.setAttribute("x", String(CHART_PAD.left - 6));
tick.setAttribute("y", String(y + 4));
tick.setAttribute("text-anchor", "end");
tick.textContent = `${Math.round(v)}${yUnit}`;
svg.append(tick);
}
// x축 라벨 (데이터 포인트 개수만큼, X_TICK_STEP 간격으로 표기) + 수직 점선 그리드
if (opts.xLabels && opts.xLabels.length > 0) {
const labels = opts.xLabels;
const baseY = CHART_PAD.top + plotH;
for (let idx = 0; idx < pointCount; idx += X_TICK_STEP) {
const label = labels[idx];
const x = xAt(idx);
if (label !== undefined && label !== "") {
// 수직 점선 그리드
const vline = document.createElementNS(svgNs, "line");
vline.setAttribute("class", "ui-chart__grid ui-chart__grid--vertical");
vline.setAttribute("x1", String(x));
vline.setAttribute("x2", String(x));
vline.setAttribute("y1", String(CHART_PAD.top));
vline.setAttribute("y2", String(baseY));
svg.append(vline);
// x축 라벨
const tick = document.createElementNS(svgNs, "text");
tick.setAttribute("class", "ui-chart__tick ui-chart__tick--x");
tick.setAttribute("x", String(x));
tick.setAttribute("y", String(baseY + 16));
tick.setAttribute("text-anchor", "middle");
tick.textContent = label;
svg.append(tick);
}
}
}
// 시리즈별 스플라인 (null 구간은 연속 세그먼트로 나눠 각각 곡선 처리)
for (const s of opts.series) {
let segment: { x: number; y: number }[] = [];
let d = "";
const flush = () => {
if (segment.length > 0) d += `${splinePath(segment)} `;
segment = [];
};
s.values.forEach((v, i) => {
if (v === null || v === undefined) {
flush();
return;
}
segment.push({ x: xAt(i), y: yAt(v) });
});
flush();
const path = document.createElementNS(svgNs, "path");
path.setAttribute("class", `ui-chart__line ui-chart__line--c${s.colorIndex ?? 0}`);
path.setAttribute("d", d.trim());
svg.append(path);
}
// 범례 (그래프 영역 우상단 오버레이)
const legend = el("div", { className: "ui-chart__legend" });
opts.series.forEach((s) => {
legend.append(
el("span", {
className: `ui-chart__legend-item ui-chart__legend-item--c${s.colorIndex ?? 0}`,
text: s.name,
}),
);
});
const plot = el("div", { className: "ui-chart__plot" });
plot.append(svg, legend);
wrap.append(plot);
return wrap;
}
/* =============================================================================
* 8. 기본 컴포넌트 스타일 주입 (injectBaseStyles)
* theme.css 변수만 참조. 앱 진입 시 1회 호출.
* ========================================================================== */