diff --git a/src/app/(pages)/(main)/dashboard/[waveCd]/[partCd]/page.tsx b/src/app/(pages)/(main)/dashboard/[waveCd]/[partCd]/page.tsx index 6b0f3c1..4c50fef 100644 --- a/src/app/(pages)/(main)/dashboard/[waveCd]/[partCd]/page.tsx +++ b/src/app/(pages)/(main)/dashboard/[waveCd]/[partCd]/page.tsx @@ -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 ( -
- {group.subItem ?

{group.subItem.title}

: null} + if (!hasChartData) return null; - {hasChartData ? ( - ({ name: item.label, data: item.values }))} - height={280} - /> + return ( + ({ + 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

데이터가 없습니다.

; + } + + return ( +
+ + + + {`BASE: ${group.series[0].baseText}`} + 사례수 + {group.categories.map((category) => ( + + {category.label} + + ))} + + + + {group.series.map((series) => ( + + {series.label} + + {series.baseCount !== null ? `(${formatThousands(series.baseCount)})` : "-"} + + {series.values.map((value, index) => ( + + {value === 0 ? "-" : formatDecimal1(value)} + + ))} + + ))} + +
+
+ ); +} + +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 ( +
+
+

{item.title}

+
+ + {item.audience.label} + + +
+
+ + {hasSubItems ? ( +
+
+ {item.resultGroups.map((group, index) => ( + + ))} +
+
) : null} - {group.categories.length ? ( -
- - - - 구분 - {group.categories.map((category) => ( - - {category.label} - - ))} - - - - {group.series.map((series) => ( - - - {series.label} - {series.baseCount !== null ? ( - - ({series.baseText ? `${series.baseText} ` : ""}N={series.baseCount}) - - ) : null} - - {series.values.map((value, index) => ( - - {value} - - ))} - - ))} - -
+ {activeGroup ? ( +
+ + {hiddenCategoryNote ?

{hiddenCategoryNote}

: null} + {showTable ? ( +
+ +
+ ) : null}
- ) : ( -

데이터가 없습니다.

- )} + ) : null} + + {item.comment ?

{item.comment}

: null}
); } @@ -100,20 +225,7 @@ export default function PartDetailPage() { {data.items.map((item) => ( -
-
-

{item.title}

- {item.audience.label} -
- -
- {item.resultGroups.map((group, index) => ( - - ))} -
- - {item.comment ?

{item.comment}

: null} -
+ ))}
); diff --git a/src/app/(pages)/(main)/dashboard/[waveCd]/page.tsx b/src/app/(pages)/(main)/dashboard/[waveCd]/page.tsx index f77fe3a..647bc03 100644 --- a/src/app/(pages)/(main)/dashboard/[waveCd]/page.tsx +++ b/src/app/(pages)/(main)/dashboard/[waveCd]/page.tsx @@ -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) => (
-

{survey.title}

+

{survey.title}

{survey.items.map((item) => (
@@ -70,19 +68,6 @@ export default function WaveOverviewPage() { ))}
) : null} - - {data.files.length ? ( -
- {data.files.map((file) => ( - - ))} -
- ) : null}
); } diff --git a/src/components/app-shell/AppMainLayout.tsx b/src/components/app-shell/AppMainLayout.tsx index 88ce71a..de72128 100644 --- a/src/components/app-shell/AppMainLayout.tsx +++ b/src/components/app-shell/AppMainLayout.tsx @@ -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 ( + + ); +} 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(null); + // ref 대신 state로 들고 있어야 DOM 노드가 붙는 시점(비동기 커밋)을 scroll-spy effect가 놓치지 않는다. + const [mainElement, setMainElement] = useState(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(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('[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(() => { 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 ? ( +
+ {files.map((file) => ( + + ))} +
+ ) : undefined; return ( setMenuOpen((current) => !current)} onNavigate={navigate} /> } - sidebar={hasSidebar ? : undefined} + sidebar={ + hasSidebar ? ( + + ) : undefined + } > {children} diff --git a/src/components/app-shell/AppSidebar.tsx b/src/components/app-shell/AppSidebar.tsx index ca9571c..89622d2 100644 --- a/src/components/app-shell/AppSidebar.tsx +++ b/src/components/app-shell/AppSidebar.tsx @@ -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 ; +export function AppSidebar({ items, isOpen, pathname, footer, onNavigate }: AppSidebarProps) { + return ; } diff --git a/src/components/layout/KriMainLayout.tsx b/src/components/layout/KriMainLayout.tsx index fba869b..77cee27 100644 --- a/src/components/layout/KriMainLayout.tsx +++ b/src/components/layout/KriMainLayout.tsx @@ -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(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 (
{header}
{sidebar} -
+
{children}
+ {showScrollTop ? ( + + ) : null} {sidebar && sidebarOpen ? (