260129_01_ENH: 카테고리 파트 layout 및 route 구조 변경

This commit is contained in:
2026-01-29 13:42:42 +09:00
parent d48decab52
commit 4b40c43962
34 changed files with 508 additions and 309 deletions

View File

@@ -0,0 +1,17 @@
"use client";
import { useAtomValue } from "jotai";
import { loadingAtom } from "@/store/jotai/loading";
export function LoadingOverlay({ force = false }: { force?: boolean }) {
const isLoading = useAtomValue(loadingAtom);
if (!force && !isLoading) return null;
return (
<div className="fixed inset-0 z-[9999] bg-black/70 flex items-center justify-center">
{/* 심플 로딩 인디케이터 */}
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
</div>
);
}

View File

@@ -6,14 +6,7 @@ import { ChevronRight } from "lucide-react";
import { useMemo } from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
const PRODUCTS = [
{ value: "냉장고", label: "냉장고" },
{ value: "세탁기", label: "세탁기" },
{ value: "식기세척기", label: "식기세척기" },
{ value: "건조기", label: "건조기" },
{ value: "에어컨", label: "에어컨" },
] as const;
import {ProductsFilterItem} from "@/types/lg";
export type CategoryTypeValue = {
label: string;
@@ -27,13 +20,13 @@ export type CategoryFilterValue = {
};
type CategoryFilterProps = {
filterItems: ProductsFilterItem,
value: CategoryFilterValue;
onChange: (next: CategoryFilterValue) => void;
className?: string;
};
const CategoryFilter = ({ value, onChange, className }: CategoryFilterProps) => {
const CategoryFilter = ({ filterItems, value, onChange, className }: CategoryFilterProps) => {
const currentTargetItem = useMemo(() => {
return categoryTarget.find((item) => item.type === value.type.value);
}, [value.type]);
@@ -46,8 +39,8 @@ const CategoryFilter = ({ value, onChange, className }: CategoryFilterProps) =>
const next: CategoryFilterValue = { ...value, [key]: v } as CategoryFilterValue;
if (key === "type") {
const nextItem = categoryTarget.find((item) => item.type === v);
if (key === "type" && typeof v === "object" && v.value !== value.type.value) {
const nextItem = categoryTarget.find((item) => item.type === v.value);
const firstTarget = nextItem?.children?.[0]?.target;
if (firstTarget) next.target = firstTarget;
}
@@ -66,17 +59,17 @@ const CategoryFilter = ({ value, onChange, className }: CategoryFilterProps) =>
<div className="min-w-0 flex-1 overflow-x-auto px-2 py-2">
<div className="flex w-max items-center gap-1 whitespace-nowrap">
{PRODUCTS.map((p) => {
const active = value.product === p.value;
{filterItems.items.map((p) => {
const active = value.product === p;
return (
<Button
key={p.value}
key={p}
type="button"
variant={active ? "default" : "secondary"}
onClick={() => handlePick("product", p.value)}
onClick={() => handlePick("product", p)}
className="h-6 shrink-0 rounded-sm px-3 text-sm font-semibold content-text-sm"
>
{p.label}
{p}
</Button>
);
})}

View File

@@ -1,11 +1,11 @@
"use client";
import {ReactNode, useState} from "react";
import {ReactNode, useEffect, useMemo, useState} from "react";
import { usePathname, useRouter } from "next/navigation";
import {cn} from "@/lib/utils";
import {SelectedMap} from "@/types/common";
import {topMenus, totalSubMenus, categorySubMenus} from "@/config/menu.data";
import {categoryTarget, totalFilters} from "@/config/filter.data";
import {categoryTarget, TARGET_SLUG, totalFilters} from "@/config/filter.data";
import {CategoryTargetData, CategoryTargetType} from "@/config/filter.types";
import Header from "./Header";
import SubMenu from "./SubMenu";
@@ -13,6 +13,9 @@ import TotalFilter from "./TotalFilter";
import CategoryFilter, {CategoryFilterValue} from "./CategoryFilter";
import ExcelDownloadButton from "./ExcelDownloadButton";
import {LayoutFilterProvider} from "./LayoutFilterContext";
import {PRODUCTS_FILTER_ITEM} from "@/const/lgConst";
import {ProductsFilterItem} from "@/types/lg";
import {useLoading} from "@/hooks/useLoading";
type MainLayoutProps = {
children: ReactNode;
@@ -28,43 +31,79 @@ const buildDefaultTotalValue = (): SelectedMap => {
return init;
};
export const buildDefaultCategoryValue = (): CategoryFilterValue => {
export const buildDefaultCategoryValue = (categoryFilterItems: ProductsFilterItem): CategoryFilterValue => {
const initProduct = categoryFilterItems.items[0];
const initType = {label:"보유", value:CategoryTargetType.PENETRATION}
const firstTarget = categoryTarget.find((x) => x.type === initType.value)?.children?.[0]?.target;
const initTarget = firstTarget ?? CategoryTargetData.PROFILE;
return {
product: "냉장고",
product: initProduct,
type: initType,
target: firstTarget ?? CategoryTargetData.PROFILE,
target: initTarget,
};
};
const MainLayout = ({ children }: MainLayoutProps) => {
const router = useRouter();
const pathname = usePathname();
const { withLoadingAsync } = useLoading();
const isTotal = pathname.startsWith("/total");
const activeTop = topMenus.find((m) => m.match?.(pathname)) ?? topMenus[0];
const subMenus = isTotal ? totalSubMenus : categorySubMenus;
const activeSub = subMenus.find((m) => m.path.startsWith(pathname)) ?? subMenus[0];
const activeSub = subMenus.find((m) => pathname.startsWith(m.path)) ?? subMenus[0];
const [isTotalFilterOpen, setIsTotalFilterOpen] = useState(true);
const [isCategoryFilterOpen, setIsCategoryFilterOpen] = useState(true);
const isFilterOpen = isTotal ? isTotalFilterOpen : isCategoryFilterOpen;
const categoryFilterItems = PRODUCTS_FILTER_ITEM.find((m) => pathname.match?.(m.path)) ?? PRODUCTS_FILTER_ITEM[0];
const [totalValue, setTotalValue] = useState<SelectedMap>(() => buildDefaultTotalValue());
const [categoryValue, setCategoryValue] = useState<CategoryFilterValue>(() => buildDefaultCategoryValue());
const [categoryValue, setCategoryValue] = useState<CategoryFilterValue>(() => buildDefaultCategoryValue(categoryFilterItems));
const movePage = (path: string) => {
router.push(path);
};
const moveCategoryPage = (path: string) => {
const slug = TARGET_SLUG[categoryValue.target] ?? "profile";
const nextPath = `${path}/${slug}`;
if (pathname !== nextPath) {
router.push(nextPath);
}
}
const toggleFilter = () => {
if (isTotal) setIsTotalFilterOpen((v) => !v);
else setIsCategoryFilterOpen((v) => !v);
};
useEffect(() => {
/*
withLoadingAsync(async () => {
setCategoryValue(prev => ({...prev, product: categoryFilterItems.items[0]}))
});
*/
setCategoryValue(prev => ({...prev, product: categoryFilterItems.items[0]}))
}, [categoryFilterItems]);
useEffect(() => {
if (isTotal) return;
const base = activeSub?.path; // "/category/ha-kitchen"
if (!base) return;
const slug = TARGET_SLUG[categoryValue.target] ?? "profile";
const nextPath = `${base}/${slug}`;
if (pathname !== nextPath) {
router.replace(nextPath);
}
}, [isTotal, categoryValue.target, activeSub?.path, pathname, router]);
return (
<div className="min-h-screen flex flex-col bg-transparent">
<LayoutFilterProvider
@@ -82,7 +121,7 @@ const MainLayout = ({ children }: MainLayoutProps) => {
<SubMenu
subMenu={subMenus}
activeSubId={activeSub.id}
onNavigate={movePage}
onNavigate={isTotal? movePage : moveCategoryPage}
/>
<div className="flex-1 min-h-0 flex flex-col pr-4">
<div className="bg-card lg-tab-content flex-1 min-h-0">
@@ -106,7 +145,7 @@ const MainLayout = ({ children }: MainLayoutProps) => {
{isTotal ? (
<TotalFilter filters={totalFilters} value={totalValue} onChange={setTotalValue} />
) : (
<CategoryFilter value={categoryValue} onChange={setCategoryValue} />
<CategoryFilter filterItems={categoryFilterItems} value={categoryValue} onChange={setCategoryValue} />
)}
</div>
)}

View File

@@ -0,0 +1,10 @@
const SectionTitle = ({title}:{title:string}) => {
return (
<div className="mb-2 font-semibold flex items-center gap-2">
<span className="w-3 h-3 bg-primary" />
{title}
</div>
);
}
export default SectionTitle;

View File

@@ -3,6 +3,7 @@
import React, { useMemo } from "react";
import { cn } from "@/lib/utils";
import type { DataColumn, SignStyle } from "../types";
import SectionTitle from "../SectionTitle";
type MergedChartCell<T> = {
/** 차트를 삽입할 컬럼 key(해당 컬럼 td는 startRow에서만 렌더되고 rowSpan 적용) */
@@ -143,10 +144,7 @@ export default function LeftChartTable<T extends Record<string, unknown>>({
return (
<div className={cn("w-full", wrapperClassName)}>
{title && (
<div className="mb-2 font-semibold flex items-center gap-2">
<span className="w-3 h-3 bg-primary"></span>
{title}
</div>
<SectionTitle title={title} />
)}
<div className="overflow-x-auto">

View File

@@ -3,6 +3,7 @@
import React, { useMemo } from "react";
import { cn } from "@/lib/utils";
import type { ChartData, SignStyle, TopChartTableRow } from "../types";
import SectionTitle from "../SectionTitle";
type BaseProps = {
title?: string;
@@ -135,10 +136,7 @@ export default function TopChartTable(props: TopChartTableProps) {
return (
<div className={cn("w-full", wrapperClassName)}>
{title && (
<div className="mb-2 font-semibold flex items-center gap-2">
<span className="w-3 h-3 bg-primary"></span>
{title}
</div>
<SectionTitle title={title} />
)}
<div className="overflow-x-auto">

View File

@@ -14,6 +14,8 @@ export { default as GaugeTable } from "./table/GaugeTable";
export { default as TopChartTable } from "./combo/TopChartTable";
export { default as LeftChartTable } from "./combo/LeftChartTable";
export { default as GaugeCardTable } from "./combo/GaugeCardTable";
export { default as CategoryByData } from "./combo/CategoryByData"
export { default as CategoryByData } from "./sub-page/CategoryByData"
export { default as CardDefault } from "./card/Card";
export { default as SectionTitle } from "./SectionTitle";

View File

@@ -0,0 +1,85 @@
import GaugeCardTable from "../combo/GaugeCardTable";
import {GaugeColumn} from "@/components/lge-dashboard";
import {useMemo} from "react";
import {apiLifeStageByProduct} from "@/config/sample.data";
import {LifeStageRow} from "@/types/lg";
const LifeStageDiv = () => {
const norm = (s: string) => s.replace(/\s+/g, "").toLowerCase();
const asNum = (v: unknown): number | null => typeof v === "number" && Number.isFinite(v) ? v : null;
const LIFE_STAGE_COLUMNS: GaugeColumn<LifeStageRow>[] = [
{ key: "item", header: "", rowHead: true, renderLabel: (r) => r.item },
{ key: "total", header: "전체", max: 100, align: "left", cellType:"number"},
{ key: "single", header: "미혼", max: 100 , align: "left"},
{ key: "noKids", header: "무자녀", group: "기혼", max: 100 , align: "left"},
{ key: "preschoolKids", header: "미취학", group: "기혼", max: 100 , align: "left"},
{ key: "schoolKids", header: "취학자녀", group: "기혼", max: 100 , align: "left"},
{ key: "adultKids", header: "성인자녀", group: "기혼", max: 100 , align: "left"},
{ key: "independentSenior", header: "독립\n시니어", max: 100 , align: "left"},
];
const LIFE_STAGE_GROUPS = [
{ title: "대형가전 군", items: ["냉장고", "세탁기", "건조기", "에어컨", "TV", "김치 냉장고", "식기세척기", "의류 관리기"] },
{ title: "소형가전 군", items: ["청소기", "공기 청정기", "정수기"] },
{ title: "신가전 군", items: ["로봇 청소기", "음식물처리기"] },
] as const;
const lifeStageRowsByGroup = useMemo(() => {
const pick = (label: string) => apiLifeStageByProduct.find((r) => norm(r.rowLabel) === norm(label));
return LIFE_STAGE_GROUPS.map((g) => {
const rows: LifeStageRow[] = g.items.map((label) => {
const r = pick(label);
return {
item: label,
total: asNum((r as any)?.total), // 서버에 all이 없으면 null로 남음
single: asNum((r as any)?.single),
noKids: asNum((r as any)?.noKids),
preschoolKids: asNum((r as any)?.preschoolKids),
schoolKids: asNum((r as any)?.schoolKids),
adultKids: asNum((r as any)?.adultKids),
independentSenior: asNum((r as any)?.independentSenior),
};
});
return { title: g.title, rows };
});
}, []);
return (
<div className="mt-6">
<div className="flex justify-end gap-6 text-xs text-muted-foreground mb-2">
<div className="flex items-center gap-2">
<span className="inline-block h-4 w-8 border bg-gray-200 border-gray-300"/>
<span>제품 보유율</span>
</div>
<div className="flex items-center gap-2">
<span
className="inline-block h-4 w-8 border border-gray-300"
style={{ backgroundColor: "hsl(var(--lg-pink-300) / 0.4)" }}
/>
<span>시장 기회공간</span>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
{lifeStageRowsByGroup.map((g) => (
<GaugeCardTable
key={g.title}
title={g.title}
columns={LIFE_STAGE_COLUMNS}
rows={g.rows}
/>
))}
</div>
</div>
);
}
export default LifeStageDiv;

View File

@@ -142,7 +142,7 @@ const GaugeTable = <T extends Record<string, unknown>>({
v === null
? undefined
: `linear-gradient(to right, ${fill} ${pct}%, ${track} 0%)`;
console.log(cellBg);
if (cellType === "number") {
return (
<td

View File

@@ -2,127 +2,6 @@ import type React from "react";
export type NewNumber = number | null | undefined;
export const PRODUCT_KEY_MAP = {
washingMachine: "세탁기",
refrigerator: "냉장고",
airConditioner: "에어컨",
tv: "TV",
microwave: "전자 레인지",
vacuumCleaner: "청소기",
laptop: "노트북",
kimchiRefrigerator: "김치 냉장고",
airFryer: "에어 프라이어",
tablet: "태블릿",
waterPurifier: "정수기",
monitor: "모니터",
airPurifier: "공기 청정기",
dryer: "건조기",
electricRange: "전기 레인지",
humidifier: "가습기",
dehumidifier: "제습기",
oven: "오븐",
robotVacuum: "로봇 청소기",
dishwasher: "식기 세척기",
massageChair: "안마 의자",
clothingCareSystem: "의류 관리기",
foodWasteDisposer: "음식물처리기",
projector: "빔프로젝터",
comboAirCareProduct: "복합 에어케어 제품",
ventilationSystem: "환기 시스템",
wineCellar: "와인 셀러",
premiumBathroomVentFan: "프리미엄 욕실 환풍기",
shoeCareSystem: "신발 관리기",
} as const;
export const BANNER_KEY_MAP = {
// 라이프 스테이지
single: "미혼",
noKids: "무자녀",
preschoolKids: "미취학",
schoolKids: "취학자녀",
adultKids: "성인자녀",
independentSenior: "독립시니어",
// 가구원수
hh1: "1인 가구",
hh2: "2인 가구",
hh3: "3인 가구",
hh4Plus: "4인 이상 가구",
// 연령
age20s: "20대",
age30s: "30대",
age40s: "40대",
age50s: "50대",
age60s: "60대",
// 점유형태
ownerOccupied: "자가",
jeonse: "전세",
depositAndMonthly: "전+월세 (보증금有)",
monthlyNoDeposit: "월세 (보증금無)",
otherTenure: "기타",
// 주거형태
apartment: "아파트",
house: "주택",
officetel: "오피스텔",
villa: "(연립)빌라",
studio: "원룸",
otherHousingType: "기타",
// 평형
under19Pyeong: "19평 이하",
pyeong20s: "20평형 대",
pyeong30s: "30평형 대",
pyeong40s: "40평형 대",
pyeong50Plus: "50평형 대 이상",
// 권역
regionCapital: "서울, 인천, 경기도",
regionGyeongnamBusanUlsan: "경남, 부산, 울산",
regionGyeongbukDaegu: "경북, 대구",
regionJeollaGwangju: "전라도, 광주",
regionChungcheongDaejeonSejong: "충청, 대전, 세종",
regionGangwonJeju: "강원, 제주",
// 소득
incomeUnder299: "299만원 이하",
income300to599: "300~599만원 이하",
income600to899: "600~899만원 이하",
income900Plus: "900만원 이상",
} as const;
export type ProductKey = keyof typeof PRODUCT_KEY_MAP;
export type BannerKey = keyof typeof BANNER_KEY_MAP;
export type ServerBaseRow = {
year: number;
rowLabel: string;
total: number;
};
// { year, rowLabel, total, ...category }
export type ServerProductRow = ServerBaseRow & Partial<Record<ProductKey, number>>;
// { year, rowLabel, total, ...banner }
// (배너는 기본 41개 키 + 차트별 추가 키가 생길 수 있으니 확장 허용)
export type ServerBannerRow = ServerBaseRow &
Partial<Record<BannerKey, number>> & {
[k: string]: number | string;
};
export type LifeStageRow = Record<string, unknown> & {
item: string;
total: number | null;
single: number | null;
noKids: number | null;
preschoolKids: number | null;
schoolKids: number | null;
adultKids: number | null;
independentSenior: number | null;
};
export type ChartSeries = {
/** legend에 노출될 이름 */
name: string;

View File

@@ -0,0 +1,11 @@
import { Provider as JotaiProvider } from "jotai";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
export function AppProvider({ children }: { children: React.ReactNode }) {
return (
<JotaiProvider>
<LoadingOverlay />
{children}
</JotaiProvider>
);
}