260818_01_ENH: 1차 완성

This commit is contained in:
2026-08-18 12:30:43 +09:00
parent 7c9da4517c
commit 041fe90081
10 changed files with 397 additions and 93 deletions

View File

@@ -1,69 +1,194 @@
"use client";
import { ChevronDown } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { useEffect } from "react";
import { useEffect, useState } 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 { cn } from "@/lib/utils";
import { 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";
import type { ResultGroup } from "@/types/wave";
import type { Item, ResultGroup } from "@/types/wave";
function ResultGroupBlock({ group }: { group: ResultGroup }) {
// audience.type이 SURVEY인 문항의 대표 색상은 실제 응답에 포함된 series[].color를 그대로 사용한다.
// surveyCd/label 기준으로 색상을 별도 매핑하지 않는다.
function findAudienceColor(item: Item): string | undefined {
for (const group of item.resultGroups) {
const withColor = group.series.find((series) => series.color);
if (withColor) return withColor.color;
}
return undefined;
}
function seriesLegendName(label: string, baseCount: number | null) {
return baseCount === null ? label : `${label} (N=${formatThousands(baseCount)})`;
}
// 차트에서 숨겨진(chartVisible=false) 카테고리를 각주로 만든다. 값이 0인 항목은 무시한다.
// 시리즈(설문)가 하나뿐이면 "※ 기타 0.9%, 모름·무응답 2.3%"처럼 시리즈명을 생략하고,
// 여러 개면 "※ 기타 : 일반국민 0.9%, 전문가 3.8% | 모름·무응답 : 일반국민 2.5%"처럼 구분해서 표기한다.
function buildHiddenCategoryNote(group: ResultGroup): string | null {
const isSingleSeries = group.series.length === 1;
const parts = group.categories
.map((category, index) => {
if (category.chartVisible) return null;
const entries = group.series
.map((series) => ({ label: series.label, value: series.values[index] }))
.filter((entry) => entry.value !== 0);
if (!entries.length) return null;
if (isSingleSeries) {
return `${category.label} ${formatDecimal1(entries[0].value)}%`;
}
const valueText = entries.map((entry) => `${entry.label} ${formatDecimal1(entry.value)}%`).join(", ");
return `${category.label} : ${valueText}`;
})
.filter((part): part is string => part !== null);
if (!parts.length) return null;
return `※ ${parts.join(isSingleSeries ? ", " : " | ")}`;
}
function ResultGroupChart({ group }: { group: ResultGroup }) {
const chartData = toChartData(group.categories, group.series);
const hasChartData = chartData.categories.length > 0 && chartData.series.length > 0;
return (
<div className="space-y-3">
{group.subItem ? <p className="text-sm font-medium">{group.subItem.title}</p> : null}
if (!hasChartData) return null;
{hasChartData ? (
<KriBarChart
categories={chartData.categories}
series={chartData.series.map((item) => ({ name: item.label, data: item.values }))}
height={280}
/>
return (
<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),
},
},
}))}
legend={{ left: 0, top: 0, textStyle: { fontSize: CHART_FONT_SIZE } }}
grid={{ top: 55, right: 25, bottom: 5, left: 0, containLabel: true }}
xAxis={{ axisLabel: { fontSize: CHART_FONT_SIZE, interval: 0 } }}
yAxis={{ min: 0, max: 100, interval: 25, axisLabel: { fontSize: CHART_FONT_SIZE } }}
barMaxWidth={CHART_BAR_MAX_WIDTH}
height={CHART_HEIGHT}
/>
);
}
function ResultGroupTable({ group }: { group: ResultGroup }) {
if (!group.categories.length) {
return <p className="text-sm text-muted-foreground">데이터가 없습니다.</p>;
}
return (
<div className="overflow-x-auto rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="border">{`BASE: ${group.series[0].baseText}`}</TableHead>
<TableHead className="border">사례수</TableHead>
{group.categories.map((category) => (
<TableHead key={category.label} className="text-center border">
{category.label}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{group.series.map((series) => (
<TableRow key={series.surveyCd}>
<TableCell className="font-medium whitespace-normal border">{series.label}</TableCell>
<TableCell className="border">
{series.baseCount !== null ? `(${formatThousands(series.baseCount)})` : "-"}
</TableCell>
{series.values.map((value, index) => (
<TableCell key={group.categories[index]?.label ?? index} className="text-right border">
{value === 0 ? "-" : formatDecimal1(value)}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
);
}
function ItemCard({ item }: { item: Item }) {
const [showTable, setShowTable] = useState(false);
const [activeGroupIndex, setActiveGroupIndex] = useState(0);
const hasSubItems = item.resultGroups.some((group) => group.subItem !== null);
const activeGroup = item.resultGroups[activeGroupIndex] ?? item.resultGroups[0];
const hiddenCategoryNote = activeGroup ? buildHiddenCategoryNote(activeGroup) : null;
return (
<div id={`item-${item.partItemCd}`} className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="font-medium">{item.title}</p>
<div className="flex items-center gap-2">
<Badge
className={cn(
"rounded-md px-3 py-1.5 text-sm font-semibold text-white",
item.audience.type === "COMMON" && "bg-slate-500",
)}
style={item.audience.type === "COMMON" ? undefined : { backgroundColor: findAudienceColor(item) }}
>
{item.audience.label}
</Badge>
<Button type="button" variant="outline" size="sm" onClick={() => setShowTable((current) => !current)}>
통계표 보기
<ChevronDown className={cn("size-4 transition-transform", showTable && "rotate-180")} />
</Button>
</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>
))}
</div>
</div>
) : null}
{group.categories.length ? (
<div className="overflow-x-auto rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>구분</TableHead>
{group.categories.map((category) => (
<TableHead key={category.label} className="text-right">
{category.label}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{group.series.map((series) => (
<TableRow key={series.surveyCd}>
<TableCell className="font-medium whitespace-normal">
{series.label}
{series.baseCount !== null ? (
<span className="ml-1 text-xs text-muted-foreground">
({series.baseText ? `${series.baseText} ` : ""}N={series.baseCount})
</span>
) : null}
</TableCell>
{series.values.map((value, index) => (
<TableCell key={group.categories[index]?.label ?? index} className="text-right">
{value}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
{activeGroup ? (
<div className="mt-4">
<ResultGroupChart group={activeGroup} />
{hiddenCategoryNote ? <p className="mt-1 text-xs text-muted-foreground">{hiddenCategoryNote}</p> : null}
{showTable ? (
<div className="mt-6">
<ResultGroupTable group={activeGroup} />
</div>
) : null}
</div>
) : (
<p className="text-sm text-muted-foreground">데이터가 없습니다.</p>
)}
) : null}
{item.comment ? <p className="mt-4 text-xs text-muted-foreground">{item.comment}</p> : null}
</div>
);
}
@@ -100,20 +225,7 @@ export default function PartDetailPage() {
<AppPageTitle title={data.title} />
{data.items.map((item) => (
<div key={item.partItemCd} id={`item-${item.partItemCd}`} className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="font-medium">{item.title}</p>
<Badge variant={item.audience.type === "COMMON" ? "secondary" : "outline"}>{item.audience.label}</Badge>
</div>
<div className="mt-4 space-y-6">
{item.resultGroups.map((group, index) => (
<ResultGroupBlock key={group.subItem?.partItemSubCd ?? index} group={group} />
))}
</div>
{item.comment ? <p className="mt-4 text-xs text-muted-foreground">{item.comment}</p> : null}
</div>
<ItemCard key={item.partItemCd} item={item} />
))}
</div>
);

View File

@@ -1,12 +1,9 @@
"use client";
import { FileDown } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { useEffect } from "react";
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
import { Button } from "@/components/ui/button";
import { isSessionInvalid, resolveApiErrorMessage } from "@/lib/api-error-message";
import { toFileDownloadUrl } from "@/lib/file-download";
import { useWaveDetailQuery } from "@/query/waves";
export default function WaveOverviewPage() {
@@ -55,9 +52,10 @@ export default function WaveOverviewPage() {
{data.surveys.map((survey) => (
<div
key={survey.surveyCd}
className="rounded-lg border-2 border-brand-blue/30 bg-card p-6 text-card-foreground shadow-sm"
className="rounded-lg border-2 bg-card p-6 text-card-foreground shadow-sm"
style={{ borderColor: survey.color }}
>
<p className="font-semibold text-brand-blue-dark">{survey.title}</p>
<p className="font-semibold" style={{ color: survey.color }}>{survey.title}</p>
<dl className="mt-3 space-y-2">
{survey.items.map((item) => (
<div key={item.title} className="flex gap-3 text-sm">
@@ -70,19 +68,6 @@ export default function WaveOverviewPage() {
))}
</div>
) : null}
{data.files.length ? (
<div className="flex flex-wrap gap-2">
{data.files.map((file) => (
<Button key={file.fileIdx} variant="outline" asChild>
<a href={toFileDownloadUrl(file.downloadUrl)} target="_blank" rel="noreferrer">
<FileDown className="size-4" />
{file.title} ({file.type})
</a>
</Button>
))}
</div>
) : null}
</div>
);
}

View File

@@ -1,13 +1,47 @@
"use client";
import { FileDown } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { usePathname, useParams, useRouter } from "next/navigation";
import { toast } from "sonner";
import { KriMainLayout } from "@/components/layout/KriMainLayout";
import type { KriNavigationItem } from "@/components/layout/types";
import { Button } from "@/components/ui/button";
import { AppHeader } from "./AppHeader";
import { AppSidebar } from "./AppSidebar";
import { useAuth } from "@/hooks/useAuth";
import { SCROLL_SPY_BOTTOM_TOLERANCE, SCROLL_SPY_THRESHOLD_DOWN, SCROLL_SPY_THRESHOLD_UP } from "@/const/epolicy-dash.const";
import { downloadFile, toFileDownloadUrl } from "@/lib/file-download";
import { useWaveDetailQuery, useWavesQuery } from "@/query/waves";
import type { FileDownload } from "@/types/wave";
function SidebarDownloadButton({ file }: { file: FileDownload }) {
const [isDownloading, setIsDownloading] = useState(false);
const handleClick = async () => {
setIsDownloading(true);
try {
await downloadFile(toFileDownloadUrl(file.downloadUrl), file.fileName);
} catch {
toast.error(`${file.title} 다운로드에 실패했습니다.`);
} finally {
setIsDownloading(false);
}
};
return (
<Button
type="button"
variant="outline"
className="w-full justify-start"
disabled={isDownloading}
onClick={() => void handleClick()}
>
<FileDown className="size-4" />
<span className="truncate">{isDownloading ? "다운로드 중..." : file.title}</span>
</Button>
);
}
function scrollToHash(hash: string) {
requestAnimationFrame(() => {
@@ -30,12 +64,92 @@ export function AppMainLayout({ children }: { children: React.ReactNode }) {
const { auth } = useAuth();
const [menuOpen, setMenuOpen] = useState(true);
const pendingHashRef = useRef<string | null>(null);
// ref 대신 state로 들고 있어야 DOM 노드가 붙는 시점(비동기 커밋)을 scroll-spy effect가 놓치지 않는다.
const [mainElement, setMainElement] = useState<HTMLElement | null>(null);
const isAuthenticated = Boolean(auth.user);
const waveCd = toNumberOrUndefined(params?.waveCd);
const { data: waves } = useWavesQuery(isAuthenticated);
const { data: waveDetail, isError: waveDetailError } = useWaveDetailQuery(waveCd, isAuthenticated);
// 좌측 사이드바의 part_item 하위 항목을 스크롤 위치에 따라 active 처리한다(scroll-spy).
// 컨테이너 상단 30% 밴드 안에 들어온 항목 중 가장 위쪽 항목을 active로 본다.
// 롤백 필요 시 이 effect와 activeItemId 관련 부분만 제거하면 이전 동작(하이라이트 없음)으로 돌아간다.
const [activeItemId, setActiveItemId] = useState<string | null>(null);
useEffect(() => {
if (!mainElement) return;
// IntersectionObserver의 콜백 entries는 "현재 보이는 모든 요소"가 아니라
// "직전 대비 교차 상태가 바뀐 요소"만 담기 때문에, 그 안에서 "가장 위"를 고르는 방식은
// 실제 화면 위치와 어긋날 수 있었다. 대신 스크롤마다 모든 문항의 위치를 직접 계산한다.
// 스크롤 방향에 따라 기준선을 다르게 둔다(히스테리시스): 아래로 내릴 때는 넉넉하게,
// 위로 올릴 때는 타이트하게 둬서 이미 거의 지나간 카드가 계속 active로 남는 걸 줄인다.
let targets: HTMLElement[] = [];
let lastTargetCount = -1;
let lastScrollTop = mainElement.scrollTop;
let ticking = false;
const computeActive = () => {
ticking = false;
if (!targets.length) return;
// 본문 스크롤이 바닥 근처면 마지막 문항을 active로 본다.
// 마지막 문항이 짧으면 상단 기준선까지 끝내 못 올라올 수 있어서 별도로 처리한다.
const atBottom = mainElement.scrollHeight - mainElement.scrollTop - mainElement.clientHeight <= SCROLL_SPY_BOTTOM_TOLERANCE;
if (atBottom) {
setActiveItemId(targets[targets.length - 1].id);
return;
}
const scrollTop = mainElement.scrollTop;
const scrollingDown = scrollTop >= lastScrollTop;
lastScrollTop = scrollTop;
const threshold = scrollingDown ? SCROLL_SPY_THRESHOLD_DOWN : SCROLL_SPY_THRESHOLD_UP;
const containerTop = mainElement.getBoundingClientRect().top;
let current = targets[0];
for (const target of targets) {
const offset = target.getBoundingClientRect().top - containerTop;
if (offset <= threshold) current = target;
else break;
}
setActiveItemId(current.id);
};
const onScroll = () => {
if (ticking) return;
ticking = true;
requestAnimationFrame(computeActive);
};
// Part 상세 데이터(usePartDetailQuery)는 이 컴포넌트가 아니라 하위 페이지에서 비동기로 로딩된다.
// 로딩이 늦어 문항 카드가 아직 DOM에 없을 때 최초 계산을 시도하면 그대로 끝나버리므로,
// MutationObserver로 카드가 나중에 생기거나 개수가 바뀔 때마다 다시 계산한다.
const setup = () => {
const found = Array.from(mainElement.querySelectorAll<HTMLElement>('[id^="item-"]'));
if (found.length === lastTargetCount) return;
lastTargetCount = found.length;
targets = found;
computeActive();
};
setup();
mainElement.addEventListener("scroll", onScroll, { passive: true });
const mutationObserver = new MutationObserver(setup);
mutationObserver.observe(mainElement, { childList: true, subtree: true });
return () => {
mutationObserver.disconnect();
mainElement.removeEventListener("scroll", onScroll);
};
}, [pathname, waveDetail, mainElement]);
// auth.user는 localStorage에서 즉시 채워져 서버(SSR)와 클라이언트 첫 렌더가 달라진다.
// 화면에 실제로 렌더링되는 값은 마운트 이후에만 반영해 하이드레이션 불일치를 막는다.
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
useEffect(() => {
if (!isAuthenticated) router.replace("/logout");
}, [isAuthenticated, router]);
@@ -57,8 +171,9 @@ export function AppMainLayout({ children }: { children: React.ReactNode }) {
const sideMenus = useMemo<KriNavigationItem[]>(() => {
if (!waveCd || waveDetailError || !waveDetail) return [];
const activePartItemCd = activeItemId?.startsWith("item-") ? activeItemId.slice("item-".length) : undefined;
return [
{ id: "overview", label: "조사 개요", path: `/dashboard/${waveCd}` },
{ id: "overview", label: "조사 개요", path: `/dashboard/${waveCd}`, match: (path: string) => path === `/dashboard/${waveCd}` },
...waveDetail.parts.map((part) => ({
id: String(part.partCd),
label: part.title,
@@ -67,10 +182,12 @@ export function AppMainLayout({ children }: { children: React.ReactNode }) {
id: `${part.partCd}-${item.partItemCd}`,
label: item.title,
path: `/dashboard/${waveCd}/${part.partCd}#item-${item.partItemCd}`,
match: (path: string) =>
path === `/dashboard/${waveCd}/${part.partCd}` && activePartItemCd === String(item.partItemCd),
})),
})),
];
}, [waveCd, waveDetail, waveDetailError]);
}, [waveCd, waveDetail, waveDetailError, activeItemId]);
const activeMenuId = useMemo(() => topMenus.find((item) => item.match?.(pathname))?.id, [topMenus, pathname]);
@@ -101,9 +218,18 @@ export function AppMainLayout({ children }: { children: React.ReactNode }) {
}, [pathname]);
const hasSidebar = sideMenus.length > 0;
const files = waveDetail?.files ?? [];
const sidebarFooter = files.length ? (
<div className="space-y-2">
{files.map((file) => (
<SidebarDownloadButton key={file.fileIdx} file={file} />
))}
</div>
) : undefined;
return (
<KriMainLayout
mainRef={setMainElement}
sidebarOpen={hasSidebar && menuOpen}
onSidebarOpenChange={setMenuOpen}
header={
@@ -112,12 +238,16 @@ export function AppMainLayout({ children }: { children: React.ReactNode }) {
showMenuButton={hasSidebar}
activeMenuId={activeMenuId}
topMenus={topMenus}
user={auth.user}
user={mounted ? auth.user : null}
onToggleMenu={() => setMenuOpen((current) => !current)}
onNavigate={navigate}
/>
}
sidebar={hasSidebar ? <AppSidebar items={sideMenus} isOpen={menuOpen} pathname={pathname} onNavigate={navigate} /> : undefined}
sidebar={
hasSidebar ? (
<AppSidebar items={sideMenus} isOpen={menuOpen} pathname={pathname} footer={sidebarFooter} onNavigate={navigate} />
) : undefined
}
>
{children}
</KriMainLayout>

View File

@@ -1,5 +1,6 @@
"use client";
import type { ReactNode } from "react";
import { KriSidebar } from "@/components/layout/KriSidebar";
import type { KriNavigationItem } from "@/components/layout/types";
@@ -7,9 +8,10 @@ interface AppSidebarProps {
items: KriNavigationItem[];
isOpen: boolean;
pathname: string;
footer?: ReactNode;
onNavigate: (path: string) => void;
}
export function AppSidebar({ items, isOpen, pathname, onNavigate }: AppSidebarProps) {
return <KriSidebar items={items} isOpen={isOpen} pathname={pathname} onNavigate={onNavigate} />;
export function AppSidebar({ items, isOpen, pathname, footer, onNavigate }: AppSidebarProps) {
return <KriSidebar items={items} isOpen={isOpen} pathname={pathname} footer={footer} onNavigate={onNavigate} />;
}

View File

@@ -1,6 +1,7 @@
'use client'
import type { CSSProperties, ReactNode } from 'react'
import { ArrowUp } from 'lucide-react'
import { useEffect, useState, type CSSProperties, type ReactNode } from 'react'
import { cn } from '@/lib/utils'
export interface KriMainLayoutProps {
@@ -14,6 +15,8 @@ export interface KriMainLayoutProps {
bodyClassName?: string
mainClassName?: string
mainStyle?: CSSProperties
/** 소비 측에서 본문 스크롤 컨테이너 DOM에 직접 접근해야 할 때(예: scroll-spy) 전달하는 콜백. */
mainRef?: (node: HTMLElement | null) => void
}
export function KriMainLayout({
@@ -27,16 +30,43 @@ export function KriMainLayout({
bodyClassName,
mainClassName,
mainStyle,
mainRef: externalMainRef,
}: KriMainLayoutProps) {
const [mainEl, setMainEl] = useState<HTMLElement | null>(null)
const [showScrollTop, setShowScrollTop] = useState(false)
// 소비 측이 전달한 콜백으로 DOM 노드를 전달하는 건 렌더 중이 아닌 effect에서 처리한다.
useEffect(() => {
externalMainRef?.(mainEl)
}, [mainEl, externalMainRef])
useEffect(() => {
if (!mainEl) return
const onScroll = () => setShowScrollTop(mainEl.scrollTop > 300)
mainEl.addEventListener('scroll', onScroll, { passive: true })
return () => mainEl.removeEventListener('scroll', onScroll)
}, [mainEl])
return (
<div className={cn('flex flex-col bg-muted/30', fullHeight && 'h-screen', className)}>
{header}
<div className={cn('flex min-h-0 flex-1 overflow-hidden', bodyClassName)}>
{sidebar}
<main className={cn('min-w-0 flex-1 overflow-y-auto p-4 lg:p-6', mainClassName)} style={mainStyle}>
<main ref={setMainEl} className={cn('min-w-0 flex-1 overflow-y-auto p-4 lg:p-6', mainClassName)} style={mainStyle}>
{children}
</main>
</div>
{showScrollTop ? (
<button
type="button"
aria-label="맨 위로"
onClick={() => mainEl?.scrollTo({ top: 0, behavior: 'smooth' })}
className="fixed right-6 bottom-6 z-30 flex size-11 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-colors hover:bg-primary/90 cursor-pointer"
>
<ArrowUp className="size-5" />
</button>
) : null}
{sidebar && sidebarOpen ? (
<button
type="button"

View File

@@ -10,6 +10,7 @@ export interface KriSidebarProps {
isOpen: boolean
pathname?: string
header?: React.ReactNode
footer?: React.ReactNode
onNavigate?: (path: string, item: KriNavigationItem) => void
className?: string
contentClassName?: string
@@ -26,6 +27,7 @@ export function KriSidebar({
isOpen,
pathname = '',
header,
footer,
onNavigate,
className,
contentClassName,
@@ -33,12 +35,12 @@ export function KriSidebar({
return (
<aside
className={cn(
'fixed top-20 left-0 z-30 h-[calc(100vh-5rem)] overflow-y-auto border-r bg-background transition-all duration-300 lg:static lg:top-0 lg:h-full lg:translate-x-0',
'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',
className,
)}
>
<div className={cn('h-full space-y-4 overflow-y-auto p-4', contentClassName)}>
<div className={cn('min-h-0 flex-1 space-y-4 overflow-y-auto p-4', contentClassName)}>
{header}
<nav className="space-y-1">
{items.map((item) => {
@@ -54,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-words',
'h-auto w-full justify-start rounded-md py-2 text-left whitespace-normal break-keep break-words',
active &&
'border-l-2 border-primary bg-primary/10 text-primary font-medium hover:bg-primary/15 hover:text-primary',
)}
@@ -75,7 +77,7 @@ export function KriSidebar({
type="button"
variant={active ? 'secondary' : 'ghost'}
className={cn(
'h-auto w-full justify-start gap-1.5 rounded-md px-3 py-2 text-left whitespace-normal break-words',
'h-auto w-full justify-start gap-1.5 rounded-md px-3 py-2 text-left whitespace-normal break-keep break-words',
active &&
'border-l-2 border-primary bg-primary/10 text-primary font-medium hover:bg-primary/15 hover:text-primary',
)}
@@ -99,7 +101,7 @@ export function KriSidebar({
type="button"
variant={childActive ? 'secondary' : 'ghost'}
className={cn(
'h-auto w-full justify-start rounded-md py-2 text-left whitespace-normal break-words',
'h-auto w-full justify-start rounded-md py-2 text-left whitespace-normal break-keep break-words',
childActive &&
'border-l-2 border-primary bg-primary/10 text-primary font-medium hover:bg-primary/15 hover:text-primary',
)}
@@ -118,6 +120,7 @@ export function KriSidebar({
})}
</nav>
</div>
{footer ? <div className="shrink-0 border-t p-4">{footer}</div> : null}
</aside>
)
}

View File

@@ -0,0 +1,11 @@
// 좌측 사이드바 문항 scroll-spy 판정 기준선(px). AppMainLayout.tsx에서 사용.
// 스크롤 방향에 따라 다른 값을 써서(히스테리시스) 경계에서 active가 튀는 걸 줄인다.
export const SCROLL_SPY_THRESHOLD_DOWN = 340;
export const SCROLL_SPY_THRESHOLD_UP = 410;
// 본문 스크롤이 바닥에서 이 값(px) 이내면 마지막 문항을 강제로 active 처리한다.
export const SCROLL_SPY_BOTTOM_TOLERANCE = 8;
// Part 상세 차트 렌더링 설정. dashboard/[waveCd]/[partCd]/page.tsx에서 사용.
export const CHART_FONT_SIZE = 14;
export const CHART_BAR_MAX_WIDTH = 100;
export const CHART_HEIGHT = 320;

View File

@@ -3,3 +3,20 @@ import { clientEnv } from "@/lib/env.client";
export function toFileDownloadUrl(downloadUrl: string): string {
return `${clientEnv.FILE_ORIGIN}${downloadUrl}`;
}
// 백엔드가 Content-Disposition: attachment를 내려주지 않아 PDF 등은 새 탭에 그냥 열려버린다.
// blob으로 받아 강제 다운로드시킨다 (파일 서버는 CORS를 허용하고 있어 동작함).
export async function downloadFile(url: string, fileName: string): Promise<void> {
const response = await fetch(url);
if (!response.ok) throw new Error(`파일을 내려받지 못했습니다. (HTTP ${response.status})`);
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = objectUrl;
anchor.download = fileName;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
URL.revokeObjectURL(objectUrl);
}

11
src/lib/format.ts Normal file
View File

@@ -0,0 +1,11 @@
export function round1(value: number): number {
return Math.round(value * 10) / 10;
}
export function formatDecimal1(value: number): string {
return value.toFixed(1);
}
export function formatThousands(value: number): string {
return value.toLocaleString("ko-KR");
}

View File

@@ -18,7 +18,9 @@ export interface SubItem {
export interface Series {
baseCount: number | null;
/** DB에 저장된 원문 그대로. baseCount와 조합해 생성되는 값이 아니다 (예: "전국 만 18세 이상 성인 남녀"). */
baseText: string | null;
color: string;
label: string;
surveyCd: number;
values: number[];
@@ -73,6 +75,7 @@ export interface SurveyItem {
export interface Survey {
alias: string;
color: string;
items: SurveyItem[];
surveyCd: number;
title: string;