Files
lg-cxdash-front/src/components/layout/MainLayout.tsx

243 lines
9.2 KiB
TypeScript

"use client";
import {ReactNode, useEffect, useMemo, useRef, useState} from "react";
import {usePathname, useRouter} from "next/navigation";
import {cn} from "@/lib/utils";
import {SelectedMap} from "@/types/common";
import {topMenus, totalSubMenus, categorySubMenus} from "@/const/menu.const";
import {categoryTarget, totalFilters} from "@/const/filter.const";
import {CategoryTargetData, CategoryTargetType} from "@/types/filter.types";
import Header from "./Header";
import SubMenu from "./SubMenu";
import TotalFilter from "./TotalFilter";
import CategoryFilter, {CategoryFilterValue} from "./CategoryFilter";
import ExcelDownloadButton from "./ExcelDownloadButton";
import {LayoutFilterProvider} from "./LayoutFilterContext";
import {LAST_YEAR} from "@/const/lg-common.const";
import {PRODUCTS_FILTER_ITEM} from "@/const/lg-product.const";
import {ProductsFilterItem} from "@/types/lg.types";
import {ArrowUp, Filter} from "lucide-react";
import {Button} from "@/components/ui/button";
type MainLayoutProps = {
children: ReactNode;
};
const buildDefaultTotalValue = (): SelectedMap => {
const init: SelectedMap = {};
totalFilters.forEach((f) => {
// "전체"가 있으면 그 value, 없으면 첫 번째 값
const all = f.children.find((c) => c.label === "전체");
init[f.variable] = all?.value ?? f.children[0]?.value ?? "";
});
return init;
};
const buildDefaultCategoryValue = (categoryFilterItems: ProductsFilterItem): CategoryFilterValue => {
const initProduct = categoryFilterItems.items[0];
const initType = {label:"보유", value:CategoryTargetType.PENETRATION}
const firstTarget = categoryTarget.find((x) => x.type.includes(initType.value))?.children[0];
const initTarget = firstTarget ?? { value: CategoryTargetData.PROFILE, label: "Profile"};
return {
year: LAST_YEAR,
product: initProduct,
type: initType,
target: initTarget,
};
};
const buildTotalPartDescription = (pathname:string) => {
switch(pathname) {
case "/total/penetration":
return "■ 보급률: 전체 소비자 중, 조사 년도에 해당 제품을 <strong>보유하고 있는 비율</strong>";
case "/total/lg-penetration":
return "■ 보급률: 전체 소비자 중, 조사 년도에 LG 제품을 <strong>보유하고 있는 비율</strong>";
case "/total/purchase":
return "■ 구매율: 전체 소비자 중, 조사 년도에 해당 제품을 <strong>구매한 비율</strong>";
case "/total/lg-purchase":
return "■ 구매율: 전체 소비자 중, 조사 년도에 LG 제품을 <strong>구매한 비율</strong>";
default:
return "";
}
}
const MainLayout = ({ children }: MainLayoutProps) => {
const router = useRouter();
const pathname = usePathname();
const scrollRef = useRef<HTMLDivElement | null>(null);
const [showScrollTop, setShowScrollTop] = useState(false);
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) => 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 totalPartDescription = buildTotalPartDescription(pathname);
const [totalValue, setTotalValue] = useState<SelectedMap>(() => buildDefaultTotalValue());
const [categoryValue, setCategoryValue] = useState<CategoryFilterValue>(() => buildDefaultCategoryValue(categoryFilterItems));
const prevIsTotalRef = useRef<boolean>(isTotal);
const movePage = (path: string) => {
router.push(path);
};
const toggleFilter = () => {
if (isTotal) setIsTotalFilterOpen((v) => !v);
else setIsCategoryFilterOpen((v) => !v);
};
const onScrollContent = () => {
const el = scrollRef.current;
if (!el) return;
setShowScrollTop(el.scrollTop > 120);
};
const scrollToTop = () => {
scrollRef.current?.scrollTo({ top: 0, behavior: "smooth" });
};
const isDefaultTotalFilter = useMemo(() => {
if(!isTotal) return false;
return Object.values(totalValue).every(value => value === "0");
},[isTotal, totalValue])
const setDefaletTotalFilter = () => {
if(isTotal && !isDefaultTotalFilter){
setTotalValue(prev =>
Object.fromEntries(
Object.keys(prev).map(key => [key, "0"])
)
);
}
}
useEffect(() => {
const prevIsTotal = prevIsTotalRef.current;
// 1) category -> total : 아무것도 안 함 (여기서 setCategoryValue 하면 1번 더 렌더됨)
if (isTotal) {
prevIsTotalRef.current = isTotal;
return;
}
// 2) total -> category : 들어오는 순간에만 초기화
if (prevIsTotal) {
setCategoryValue(buildDefaultCategoryValue(categoryFilterItems));
prevIsTotalRef.current = isTotal;
return;
}
// 3) category 내부 이동(카테고리 path 바뀜 등) : product만 동기화
const nextProduct = categoryFilterItems.items[0];
setCategoryValue((prev) => {
if (prev.product === nextProduct) return prev;
return { ...prev, product: nextProduct };
});
prevIsTotalRef.current = isTotal;
}, [isTotal, categoryFilterItems]);
return (
<div className="h-screen flex flex-col bg-transparent overflow-hidden">
<LayoutFilterProvider
value={isTotal? { isTotal: true, filterValue: totalValue } : { isTotal: false, filterValue: categoryValue }}
>
<Header
activeTopId={activeTop.id}
onNavigate={movePage}
/>
<div className="flex-1 min-h-0 flex flex-col bg-lg-main-body p-1 pl-6">
<SubMenu
subMenu={subMenus}
activeSubId={activeSub.id}
onNavigate={movePage}
/>
<div className="flex-1 min-h-0 flex flex-col pr-4">
<div className="bg-card lg-tab-content flex-1 min-h-0 flex flex-col overflow-hidden">
<div className="shrink-0 flex items-center justify-between px-2 py-1">
<div className="flex">
<button
type="button"
onClick={toggleFilter}
className={cn(
"inline-flex items-center gap-2 font-semibold text-gray-900 content-text-sm cursor-pointer",
"select-none"
)}
>
<Filter className="h-4 w-4 fill-[hsl(var(--lg-gray-500))] stroke-[hsl(var(--lg-gray-500))]" />
필터 <span className="text-sm leading-none mb-1">{isFilterOpen ? "▲" : "▼"}</span>
</button>
{isTotal && (
<>
<Button
variant={isDefaultTotalFilter ? "secondary" : "default"}
onClick={setDefaletTotalFilter}
className="h-6 rounded-sm px-3 ml-3 text-sm font-semibold content-text-sm"
>
초기화
</Button>
<div className={"ml-5 content-text-sm"} dangerouslySetInnerHTML={{__html: totalPartDescription}}>
</div>
</>
)}
</div>
<ExcelDownloadButton/>
</div>
{isFilterOpen && (
<div className="shrink-0">
{isTotal ? (
<TotalFilter filters={totalFilters} value={totalValue} onChange={setTotalValue} />
) : (
<CategoryFilter filterItems={categoryFilterItems} value={categoryValue} onChange={setCategoryValue} />
)}
</div>
)}
<div className="relative flex-1 min-h-0">
<div
ref={scrollRef}
onScroll={onScrollContent}
className="h-full overflow-auto"
>
<div className="p-3 pb-8">
{children}
</div>
</div>
{showScrollTop && (
<button
type="button"
onClick={scrollToTop}
aria-label="위로 가기"
className={cn(
"absolute -bottom-2 right-4 z-20",
"h-8 w-8 rounded-full",
"bg-gray-900/80 text-white hover:bg-primary",
"flex items-center justify-center"
)}
>
<ArrowUp className="h-5 w-5" />
</button>
)}
</div>
</div>
</div>
</div>
</LayoutFilterProvider>
</div>
);
}
export default MainLayout;