260825_01_ENH: 차트 문항별 색상지정 및 차트 하이라이트 모드 적용, 문항별 제목과 범례 사이에 문항 텍스트 삽입, gap 추가

This commit is contained in:
2026-08-25 14:48:49 +09:00
parent 1d20055f7d
commit 75385bd452
5 changed files with 220 additions and 39 deletions

View File

@@ -3,14 +3,22 @@
import { ChevronDown } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import type { CSSProperties } from "react";
import { KriBarChart } from "@/components/chart";
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { CHART_BAR_MAX_WIDTH, CHART_FONT_SIZE, CHART_HEIGHT } from "@/const/epolicy-dash.const";
import {
CHART_BAR_MAX_WIDTH,
CHART_FONT_SIZE,
CHART_GAP_MARKER_BG_COLOR,
CHART_GAP_MARKER_TEXT_COLOR,
CHART_HEIGHT,
SUBITEM_NEGATIVE_COLOR,
} from "@/const/epolicy-dash.const";
import { cn } from "@/lib/utils";
import { toChartData } from "@/lib/chart-utils";
import { getGapPoints, getHighlightedIndexes, toChartData } from "@/lib/chart-utils";
import { formatDecimal1, formatThousands, round1 } from "@/lib/format";
import { isSessionInvalid, resolveApiErrorMessage } from "@/lib/api-error-message";
import { usePartDetailQuery } from "@/query/waves";
@@ -26,6 +34,17 @@ function findAudienceColor(item: Item): string | undefined {
return undefined;
}
// 서브 탭 hover 배경처럼 색상에 알파를 입힌 은은한 톤이 필요한 곳에서 사용한다.
function hexToRgba(hex: string, alpha: number): string {
const normalized = hex.replace("#", "");
const isShorthand = normalized.length === 3;
const r = parseInt(isShorthand ? normalized[0] + normalized[0] : normalized.slice(0, 2), 16);
const g = parseInt(isShorthand ? normalized[1] + normalized[1] : normalized.slice(2, 4), 16);
const b = parseInt(isShorthand ? normalized[2] + normalized[2] : normalized.slice(4, 6), 16);
if ([r, g, b].some((channel) => Number.isNaN(channel))) return hex;
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}
function seriesLegendName(label: string, baseCount: number | null) {
return baseCount === null ? label : `${label} (N=${formatThousands(baseCount)})`;
}
@@ -118,19 +137,59 @@ function ResultGroupChart({ group }: { group: ResultGroup }) {
<div ref={chartWrapperRef}>
<KriBarChart
categories={chartData.categories}
series={chartData.series.map((item) => ({
name: seriesLegendName(item.label, item.baseCount),
data: item.values.map(round1),
color: item.color,
option: {
label: {
show: true,
position: "top",
fontSize: CHART_FONT_SIZE,
formatter: (params: { value: number }) => formatDecimal1(params.value),
series={chartData.series.map((item) => {
const highlightedIndexes = item.chartHighlightMode ? getHighlightedIndexes(group.categories, item) : [];
const gapPoints = getGapPoints(group.categories, item);
return {
name: seriesLegendName(item.label, item.baseCount),
data: item.values.map((value, index) =>
highlightedIndexes.includes(index) && item.chartHighlightColor
? { value: round1(value), itemStyle: { color: item.chartHighlightColor } }
: round1(value),
),
color: item.color,
option: {
label: {
show: true,
position: "top",
fontSize: CHART_FONT_SIZE,
formatter: (params: { value: number }) => formatDecimal1(params.value),
},
...(gapPoints.length
? {
markPoint: {
// 점 마커 없이, 라운딩된 사각형 배경을 가진 라벨 자체를 도형처럼 사용한다.
symbol: "circle",
symbolSize: 0,
label: {
show: true,
position: "top",
// 막대 자체의 값 라벨(position:"top")과 겹치지 않도록 그 위로 띄운다.
distance: 15,
color: CHART_GAP_MARKER_TEXT_COLOR,
backgroundColor: CHART_GAP_MARKER_BG_COLOR,
borderRadius: 20,
padding: [10, 10, 7, 10],
fontWeight: "bold",
fontSize: CHART_FONT_SIZE,
formatter: ({ value }: { value: number }) =>
`${value >= 0 ? "▲" : "▼"} ${formatDecimal1(Math.abs(value))}%p`,
},
// ALL: 현재 막대 바로 위. LAST_VISIBLE: 직전 막대와의 중간 지점(두 막대 사이)에 표시한다.
data: gapPoints.map(({ index, previousIndex, value, previousValue, gap }) => ({
coord:
item.chartGapMode === "LAST_VISIBLE"
? [(index + previousIndex) / 2, Math.max(value, previousValue)]
: [index, value],
value: gap,
})),
},
}
: {}),
},
},
}))}
};
})}
legend={{ left: 0, top: 0, textStyle: { fontSize: CHART_FONT_SIZE } }}
grid={{ top: 55, right: 25, bottom: 5, left: 0, containLabel: true }}
xAxis={{
@@ -195,6 +254,8 @@ function ItemCard({ item }: { item: Item }) {
const hasSubItems = item.resultGroups.some((group) => group.subItem !== null);
const activeGroup = item.resultGroups[activeGroupIndex] ?? item.resultGroups[0];
const hiddenCategoryNote = activeGroup ? buildHiddenCategoryNote(activeGroup) : null;
// subItem 코멘트가 있으면 그것을 우선 표시하고, 없으면 문항 공통 코멘트로 대체한다.
const activeComment = activeGroup?.subItem?.partItemSubComment || item.comment || null;
return (
<div id={`item-${item.partItemCd}`} className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
@@ -217,22 +278,46 @@ function ItemCard({ item }: { item: Item }) {
</div>
</div>
{hasSubItems ? (
<div className="mt-4 flex justify-end">
<div className="inline-flex rounded-md border p-1">
{item.resultGroups.map((group, index) => (
<Button
key={group.subItem?.partItemSubCd ?? index}
type="button"
size="sm"
variant={index === activeGroupIndex ? "default" : "ghost"}
className="rounded-sm"
onClick={() => setActiveGroupIndex(index)}
>
{group.subItem?.title}
</Button>
))}
{hasSubItems || activeComment ? (
<div className="mt-4 flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1">
{activeComment ? <p className="text-xs text-muted-foreground">{activeComment}</p> : null}
</div>
{hasSubItems ? (
<div className="inline-flex shrink-0 rounded-md border p-1">
{item.resultGroups.map((group, index) => {
const isActive = index === activeGroupIndex;
const isNegativeSubItem = group.subItem?.partItemSubCd === 2;
return (
<Button
key={group.subItem?.partItemSubCd ?? index}
type="button"
size="sm"
variant={isActive ? "default" : "ghost"}
className={cn(
"rounded-sm",
isNegativeSubItem &&
!isActive &&
"hover:bg-[var(--negative-hover-bg)] hover:text-[var(--negative-hover-text)]",
)}
style={
isNegativeSubItem
? ({
...(isActive ? { backgroundColor: SUBITEM_NEGATIVE_COLOR, color: "#fff" } : {}),
["--negative-hover-bg" as string]: hexToRgba(SUBITEM_NEGATIVE_COLOR, 0.12),
["--negative-hover-text" as string]: SUBITEM_NEGATIVE_COLOR,
} as CSSProperties)
: undefined
}
onClick={() => setActiveGroupIndex(index)}
>
{group.subItem?.title}
</Button>
);
})}
</div>
) : null}
</div>
) : null}
@@ -247,8 +332,6 @@ function ItemCard({ item }: { item: Item }) {
) : null}
</div>
) : null}
{item.comment ? <p className="mt-4 text-xs text-muted-foreground">{item.comment}</p> : null}
</div>
);
}
@@ -281,7 +364,7 @@ export default function PartDetailPage() {
}
return (
<div className="space-y-6">
<div className="space-y-6 px-50">
<AppPageTitle title={data.title} />
{data.items.map((item) => (

View File

@@ -36,7 +36,7 @@ export function KriSidebar({
<aside
className={cn(
'fixed top-20 left-0 z-30 flex h-[calc(100vh-5rem)] flex-col overflow-hidden border-r bg-background transition-all duration-300 lg:static lg:top-0 lg:h-full lg:translate-x-0',
isOpen ? 'w-80 translate-x-0' : 'w-80 -translate-x-full lg:w-0 lg:border-r-0',
isOpen ? 'w-130 translate-x-0' : 'w-130 -translate-x-full lg:w-0 lg:border-r-0',
className,
)}
>
@@ -56,7 +56,7 @@ export function KriSidebar({
type="button"
variant={active ? 'secondary' : 'ghost'}
className={cn(
'h-auto w-full justify-start rounded-md py-2 text-left whitespace-normal break-keep break-words',
'h-auto w-full justify-start rounded-md py-2 text-left whitespace-normal break-keep wrap-break-words',
active &&
'border-l-2 border-primary bg-primary/10 text-primary font-medium hover:bg-primary/15 hover:text-primary',
)}

View File

@@ -6,6 +6,15 @@ export const SCROLL_SPY_THRESHOLD_UP = 410;
export const SCROLL_SPY_BOTTOM_TOLERANCE = 8;
// Part 상세 차트 렌더링 설정. dashboard/[waveCd]/[partCd]/page.tsx에서 사용.
export const CHART_FONT_SIZE = 14;
export const CHART_FONT_SIZE = 16;
export const CHART_BAR_MAX_WIDTH = 100;
export const CHART_HEIGHT = 320;
// 서브 문항 탭(예: "감소 이유")의 부정적 의미 강조색. series.color는 surveyCd 구성에 따라 값이 들쭉날쭉해서
// (예: 전문가만 있는 응답군은 색이 달라짐) 탭 색상 기준으로 쓸 수 없어, primary(브랜드 블루)와 동일한 채도로
// 고정한 별도 색상을 쓴다.
export const SUBITEM_NEGATIVE_COLOR = "#F0475A";
// Gap markPoint(전분기 대비 증감) 배지 색상. 특정 시리즈 색과 섞이지 않도록 중립적인 회색조를 쓴다.
export const CHART_GAP_MARKER_BG_COLOR = "#E5E7EB";
export const CHART_GAP_MARKER_TEXT_COLOR = "#000000";

View File

@@ -1,4 +1,5 @@
import type { Category } from "@/types/wave";
import { round1 } from "@/lib/format";
import type { Category, Series } from "@/types/wave";
export function toChartData<T extends { values: number[] }>(categories: Category[], series: T[]) {
const visibleIndexes = categories
@@ -13,3 +14,80 @@ export function toChartData<T extends { values: number[] }>(categories: Category
})),
};
}
// chartVisible=true인 카테고리만 대상으로, 강조할 데이터 포인트의 인덱스를 계산한다.
// 반환되는 인덱스는 toChartData가 만든 필터링된(visible) 카테고리/값 배열 기준이다.
export function getHighlightedIndexes(
categories: Category[],
series: Pick<Series, "chartHighlightMode" | "chartHighlightValue" | "values">,
): number[] {
const visibleCategories = categories.filter((category) => category.chartVisible);
switch (series.chartHighlightMode) {
case "MAX_VALUE": {
const visibleValues = toChartData(categories, [series]).series[0].values;
if (!visibleValues.length) return [];
const maxValue = Math.max(...visibleValues);
const index = visibleValues.indexOf(maxValue);
return index >= 0 ? [index] : [];
}
case "LAST_VISIBLE": {
if (!visibleCategories.length) return [];
const maxOrder = Math.max(...visibleCategories.map((category) => category.order));
const index = visibleCategories.findIndex((category) => category.order === maxOrder);
return index >= 0 ? [index] : [];
}
case "SPECIFIED": {
const orders = (series.chartHighlightValue ?? "")
.split(",")
.map((value) => Number(value.trim()))
.filter((value) => !Number.isNaN(value));
if (!orders.length) return [];
return visibleCategories
.map((category, index) => (orders.includes(category.order) ? index : -1))
.filter((index) => index >= 0);
}
default:
return [];
}
}
export type GapPoint = {
// index/previousIndex는 toChartData가 만든 필터링된(visible) 카테고리/값 배열 기준 인덱스다.
// ALL은 index 위치(현재 막대 위)에, LAST_VISIBLE은 index와 previousIndex의 중간(두 막대 사이)에 표시한다.
index: number;
previousIndex: number;
value: number;
previousValue: number;
gap: number;
};
// 같은 Series 안에서, chartVisible=true인 항목을 category.order 오름차순으로 정렬한 뒤
// 인접한 값끼리의 차이(현재 - 직전)를 계산한다. 값은 차트에 표시되는 값(round1)과 맞춘다.
// NONE 또는 알 수 없는 값은 방어적으로 NONE과 동일하게 처리한다(Gap 없음).
export function getGapPoints(
categories: Category[],
series: Pick<Series, "chartGapMode" | "values">,
): GapPoint[] {
if (series.chartGapMode !== "ALL" && series.chartGapMode !== "LAST_VISIBLE") return [];
const visiblePoints = categories
.map((category, index) => ({ category, value: round1(series.values[index]) }))
.filter((point) => point.category.chartVisible)
.sort((a, b) => a.category.order - b.category.order);
if (visiblePoints.length < 2) return [];
const gapPoints = visiblePoints.slice(1).map((current, index) => {
const previous = visiblePoints[index];
return {
index: index + 1,
previousIndex: index,
value: current.value,
previousValue: previous.value,
gap: round1(current.value - previous.value),
};
});
return series.chartGapMode === "LAST_VISIBLE" ? gapPoints.slice(-1) : gapPoints;
}

View File

@@ -13,13 +13,27 @@ export interface Category {
export interface SubItem {
partItemSubCd: number;
partItemSubComment: string | null;
title: string;
}
export type ChartType = "BAR";
export type ChartHighlightMode = "MAX_VALUE" | "LAST_VISIBLE" | "SPECIFIED";
/** Backend가 설정 없음/DB 값 오류 시에도 항상 "NONE"으로 채워서 내려준다. */
export type ChartGapMode = "NONE" | "ALL" | "LAST_VISIBLE";
export interface Series {
baseCount: number | null;
/** DB에 저장된 원문 그대로. baseCount와 조합해 생성되는 값이 아니다 (예: "전국 만 18세 이상 성인 남녀"). */
baseText: string | null;
chartGapMode: ChartGapMode;
chartHighlightColor: string | null;
chartHighlightMode: ChartHighlightMode | null;
/** chartHighlightMode가 "SPECIFIED"일 때 강조할 category.order 목록 (쉼표 구분 문자열, 예: "1,3,5"). */
chartHighlightValue: string | null;
chartType: ChartType;
color: string;
label: string;
surveyCd: number;
@@ -32,11 +46,8 @@ export interface ResultGroup {
subItem: SubItem | null;
}
export type ChartType = "BAR";
export interface Item {
audience: Audience;
chartType: ChartType;
comment: string;
order: number;
partItemCd: number;