501 lines
16 KiB
TypeScript
501 lines
16 KiB
TypeScript
import "./header.css";
|
|
|
|
import { useEffect, useCallback, useState, useRef } from "react";
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import { Minus, Plus } from "lucide-react";
|
|
import { images } from "@common/assets";
|
|
import type { AuthService, TokenManager } from "@common/auth";
|
|
import { getRemainingMs } from "@common/auth";
|
|
import { getConfig } from "@common/config";
|
|
import { getAuthLoginRedirectUrl, isAtLoginRedirectUrl } from "@common/network";
|
|
import { ENDPOINT } from "../../config";
|
|
import { setCookie, getCookie } from "../../lib";
|
|
import { useSessionExtendConfirm } from "../../lib/use-session-extend-confirm";
|
|
import {
|
|
getPopupInfo,
|
|
getUserPopupList,
|
|
getSiteInfo,
|
|
getUserInfo,
|
|
type Popup,
|
|
getSiteList,
|
|
type SiteListResponse,
|
|
} from "../../api";
|
|
import { Button } from "../button";
|
|
import { Skeleton } from "../skeleton";
|
|
import { SidebarTrigger } from "../sidebar";
|
|
import { Popover, PopoverContent, PopoverTrigger } from "../popover";
|
|
import { SearchForm } from "./search-form";
|
|
import { NoticePopover } from "./notice-popover";
|
|
import { ScrollArea, ScrollBar } from "../scroll-area";
|
|
|
|
const appConfig = getConfig();
|
|
const userId = getCookie(appConfig.AUTH_USER_ID ?? "");
|
|
const isLoggedIn = !!userId;
|
|
|
|
function getRootDomain(hostname: string): string {
|
|
if (hostname === "localhost" || /^\d+\.\d+\.\d+\.\d+$/.test(hostname)) {
|
|
return hostname;
|
|
}
|
|
|
|
if (hostname.includes("hasuon.or.kr")) {
|
|
return ".hasuon.or.kr";
|
|
}
|
|
|
|
const parts = hostname.split(".");
|
|
if (parts.length >= 2) {
|
|
return `.${parts.slice(-2).join(".")}`;
|
|
}
|
|
|
|
return hostname;
|
|
}
|
|
|
|
function clearClientCookies(tokenManager?: TokenManager) {
|
|
const actualHost = window.location.hostname;
|
|
const domain = getRootDomain(actualHost);
|
|
|
|
const cookiesToDelete = [
|
|
appConfig.AUTH_USER_ID,
|
|
appConfig.REFRESH_TOKEN,
|
|
appConfig.ACCESS_TOKEN,
|
|
appConfig.CLAIM_NAME,
|
|
"site-id-key",
|
|
"site-theme-key",
|
|
].filter(Boolean);
|
|
|
|
cookiesToDelete.forEach((cookieName) => {
|
|
if (!cookieName) return;
|
|
|
|
tokenManager?.removeToken(cookieName);
|
|
|
|
if (domain !== "localhost") {
|
|
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${domain}`;
|
|
}
|
|
|
|
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
|
|
|
|
if (window.location.protocol === "https:") {
|
|
if (domain !== "localhost") {
|
|
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${domain}; secure`;
|
|
}
|
|
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; secure`;
|
|
}
|
|
});
|
|
}
|
|
|
|
async function legacyLogout(tokenManager?: TokenManager) {
|
|
try {
|
|
const response = await fetch("/api/auth/logout", {
|
|
method: "POST",
|
|
credentials: "include",
|
|
});
|
|
|
|
if (!response.ok) {
|
|
console.error("Logout API failed");
|
|
}
|
|
} catch (error) {
|
|
console.error("Logout error:", error);
|
|
} finally {
|
|
clearClientCookies(tokenManager);
|
|
window.location.href = "/auth/login";
|
|
}
|
|
}
|
|
|
|
function formatRemainingMs(remainingMs: number | null): string {
|
|
if (remainingMs === null) return "-";
|
|
if (remainingMs <= 0) return "만료됨";
|
|
|
|
const totalSeconds = Math.floor(remainingMs / 1000);
|
|
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
const seconds = totalSeconds % 60;
|
|
|
|
return `${minutes}분 ${seconds}초`;
|
|
}
|
|
|
|
function useTokenRemainingMs(enabled: boolean): number | null {
|
|
const [remainingMs, setRemainingMs] = useState<number | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (!enabled) {
|
|
setRemainingMs(null);
|
|
return;
|
|
}
|
|
|
|
const update = () => {
|
|
const token = getCookie(appConfig.CLAIM_NAME ?? "");
|
|
setRemainingMs(token ? getRemainingMs(token, 0) : 0);
|
|
};
|
|
|
|
update();
|
|
const id = setInterval(update, 1000);
|
|
return () => clearInterval(id);
|
|
}, [enabled]);
|
|
|
|
return remainingMs;
|
|
}
|
|
|
|
export function Header({
|
|
authService,
|
|
tokenManager,
|
|
viewOnly,
|
|
}: {
|
|
authService?: AuthService;
|
|
/** @deprecated authService를 사용하세요. */
|
|
tokenManager?: TokenManager;
|
|
viewOnly?: boolean;
|
|
}) {
|
|
const [mounted, setMounted] = useState(false);
|
|
const [logoWidth, setLogoWidth] = useState(0);
|
|
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
|
const logoRef = useRef<HTMLImageElement>(null);
|
|
const siteId = getCookie("site-id-key") ?? "";
|
|
|
|
const remainingMs = useTokenRemainingMs(mounted && isLoggedIn && !viewOnly);
|
|
|
|
useEffect(() => {
|
|
if (
|
|
!mounted ||
|
|
!isLoggedIn ||
|
|
viewOnly ||
|
|
!authService ||
|
|
remainingMs === null ||
|
|
remainingMs > 0
|
|
) {
|
|
return;
|
|
}
|
|
|
|
void authService.logout();
|
|
}, [mounted, viewOnly, authService, remainingMs]);
|
|
|
|
useSessionExtendConfirm({
|
|
enabled:
|
|
mounted &&
|
|
isLoggedIn &&
|
|
!viewOnly &&
|
|
!!authService &&
|
|
!isAtLoginRedirectUrl(getAuthLoginRedirectUrl()),
|
|
getAccessToken: () => getCookie(appConfig.CLAIM_NAME ?? ""),
|
|
silentRefresh: authService?.silentRefresh ?? (async () => {}),
|
|
declineSessionExtend: authService?.declineSessionExtend ?? (() => {}),
|
|
onTimeout: () => {
|
|
handleLogout();
|
|
},
|
|
});
|
|
|
|
const { data: userInfo } = useQuery({
|
|
queryKey: [ENDPOINT.USER_SERVICE.USERS],
|
|
queryFn: () => getUserInfo(),
|
|
enabled: isLoggedIn && !viewOnly,
|
|
});
|
|
|
|
const { data: siteInfo } = useQuery({
|
|
queryKey: [ENDPOINT.CMS_SERVICE.SITES, siteId],
|
|
queryFn: () => getSiteInfo(siteId),
|
|
select: (data) => {
|
|
if (data.siteSkn) {
|
|
const siteSkin = data.siteSkn.toLowerCase();
|
|
setCookie("site-theme-key", siteSkin);
|
|
document.documentElement.setAttribute("data-theme", siteSkin);
|
|
}
|
|
return data;
|
|
},
|
|
enabled: !viewOnly,
|
|
});
|
|
|
|
const { data: userPopupList } = useQuery({
|
|
queryKey: [ENDPOINT.CMS_SERVICE.POPUPS],
|
|
queryFn: () => getUserPopupList(),
|
|
enabled: isLoggedIn && !viewOnly,
|
|
});
|
|
|
|
const { data: userSiteList } = useQuery<SiteListResponse>({
|
|
queryKey: [ENDPOINT.CMS_SERVICE.SITE_LIST],
|
|
queryFn: () => getSiteList(),
|
|
enabled: isLoggedIn && !viewOnly,
|
|
});
|
|
const handleLogout = () => {
|
|
if (authService) {
|
|
void authService.logout();
|
|
return;
|
|
}
|
|
|
|
void legacyLogout(tokenManager);
|
|
};
|
|
|
|
const openPopup = useCallback(async (popup: Popup) => {
|
|
try {
|
|
const cookieName = `cs-popup-hide-for-day-${popup.popupSn}`;
|
|
const hasCookie = getCookie(cookieName);
|
|
if (hasCookie) return;
|
|
|
|
const response = await getPopupInfo(popup.popupSn);
|
|
if (!response) return;
|
|
|
|
const width = response.popupWdth || 400;
|
|
const height = response.popupHgt || 300;
|
|
const left = (response.popupHrzntltyPstn || 0) + window.screenX;
|
|
const top = (response.popupVtclPstn || 0) + window.screenY;
|
|
|
|
const popupWindow = window.open(
|
|
`/view/popup/${popup.popupSn}`,
|
|
"",
|
|
`width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes,status=no,location=no,menubar=no`,
|
|
);
|
|
|
|
if (popupWindow) {
|
|
popupWindow.focus();
|
|
}
|
|
} catch (error) {
|
|
console.error(`Failed to open popup ${popup.popupSn}:`, error);
|
|
}
|
|
}, []);
|
|
|
|
const getLogoImage = () => {
|
|
const siteThemeKey = getCookie("site-theme-key");
|
|
if (siteThemeKey === "blue" || siteThemeKey === "green")
|
|
return images.logoWhite;
|
|
return images.logo;
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (!userPopupList?.length) return;
|
|
|
|
const timer = setTimeout(() => {
|
|
userPopupList.forEach((popup) => {
|
|
openPopup(popup);
|
|
});
|
|
}, 500);
|
|
|
|
return () => clearTimeout(timer);
|
|
}, [userPopupList, openPopup]);
|
|
|
|
useEffect(() => {
|
|
setMounted(true);
|
|
|
|
// 브라우저 푸시 알림 권한 정중히 요청
|
|
if (typeof window !== "undefined" && "Notification" in window) {
|
|
if (Notification.permission === "default") {
|
|
Notification.requestPermission().catch((err) => {
|
|
console.error("Notification permission request failed", err);
|
|
});
|
|
}
|
|
}
|
|
}, []);
|
|
|
|
return (
|
|
<header
|
|
id="gnb"
|
|
tabIndex={-1}
|
|
className="sticky top-0 z-30 box-border flex h-[6rem] w-full flex-col items-center justify-between border-b border-solid border-border bg-background sm:flex-row"
|
|
>
|
|
<div className="flex w-full items-center justify-between px-2 sm:w-auto sm:justify-start sm:px-4 md:px-6">
|
|
<div className="flex items-center gap-2 sm:gap-4">
|
|
<SidebarTrigger className="size-12 !bg-transparent p-2 hover:!bg-accent [&>svg]:!size-full [&>svg]:text-foreground" />
|
|
<h1 className="flex flex-col items-center gap-2">
|
|
{mounted ? (
|
|
<img
|
|
ref={logoRef}
|
|
src={getLogoImage()}
|
|
className="h-[3rem]"
|
|
alt="logo"
|
|
onLoad={() => {
|
|
if (logoRef.current) {
|
|
setLogoWidth(logoRef.current.offsetWidth);
|
|
}
|
|
}}
|
|
/>
|
|
) : (
|
|
<Skeleton className="h-[3rem] w-[15rem]" />
|
|
)}
|
|
<span
|
|
className="text-[1.2rem] font-semibold text-foreground"
|
|
style={{
|
|
letterSpacing:
|
|
logoWidth > 0
|
|
? `${(logoWidth - 120) / (siteInfo?.siteNm?.length || 1)}px`
|
|
: "0.05em",
|
|
}}
|
|
>
|
|
{siteInfo?.siteNm}
|
|
</span>
|
|
</h1>
|
|
</div>
|
|
{/* 모바일에서 오른쪽 요소들 */}
|
|
<div className="flex items-center gap-1 sm:hidden">
|
|
{/* 모바일 메뉴 토글 버튼 */}
|
|
{mounted && (
|
|
<Button
|
|
onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
|
|
className="m-0 flex h-[3rem] items-center !bg-background px-3 py-0 text-label"
|
|
>
|
|
<i
|
|
className={`diveicon ${isMobileMenuOpen ? "di-menu-close-fill" : "di-menu-open-fill"} static text-4xl`}
|
|
/>
|
|
</Button>
|
|
)}
|
|
{mounted && isLoggedIn && (
|
|
<Popover>
|
|
<PopoverTrigger asChild>
|
|
<Button className="group m-0 flex h-[3rem] items-center !bg-background px-2 py-0 text-label">
|
|
<i className="diveicon di-account-circle static translate-y-0.5 pr-2 text-3xl" />
|
|
<span className="xs:inline hidden text-xs">
|
|
{userInfo?.userName}
|
|
</span>
|
|
<i className="diveicon di-chevron-down static p-0 transition-transform group-data-[state=open]:rotate-180" />
|
|
</Button>
|
|
</PopoverTrigger>
|
|
<PopoverContent align="end" className="w-48 border-border p-1.5">
|
|
<UserMenuContent
|
|
remainingMs={remainingMs}
|
|
onLogout={handleLogout}
|
|
/>
|
|
</PopoverContent>
|
|
</Popover>
|
|
)}
|
|
</div>
|
|
</div>
|
|
{/* 모바일에서 네비게이션 (토글 시 표시) */}
|
|
{isMobileMenuOpen && (
|
|
<div className="w-full border-t border-border bg-background py-2 sm:hidden">
|
|
{mounted &&
|
|
userSiteList?.content &&
|
|
userSiteList.content.length > 0 && (
|
|
<nav className="flex flex-col items-center gap-2 px-4">
|
|
{userSiteList.content.map((site) => (
|
|
<a
|
|
key={site.siteId}
|
|
href={siteId === site.siteId ? "#" : site.dmnAddr}
|
|
className="w-full py-2 text-center text-xl font-medium text-foreground transition-colors hover:text-primary"
|
|
target={siteId === site.siteId ? "_self" : "_blank"}
|
|
rel="noopener noreferrer"
|
|
onClick={() => setIsMobileMenuOpen(false)}
|
|
>
|
|
{site.siteNm}
|
|
</a>
|
|
))}
|
|
</nav>
|
|
)}
|
|
</div>
|
|
)}
|
|
{/* 데스크톱에서 중간 네비게이션 */}
|
|
<ScrollArea className="hidden max-w-[calc(100vw-60rem)] flex-1 items-center justify-center px-2 py-4 sm:flex">
|
|
{mounted &&
|
|
userSiteList?.content &&
|
|
userSiteList.content.length > 0 && (
|
|
<nav className="flex w-full flex-nowrap items-center justify-start gap-3 overflow-x-auto whitespace-nowrap md:gap-6">
|
|
{userSiteList.content.map((site) => (
|
|
<a
|
|
key={site.siteId}
|
|
href={siteId === site.siteId ? "#" : site.dmnAddr}
|
|
className="header-nav-link whitespace-nowrap text-sm font-medium text-foreground transition-colors hover:text-primary md:text-lg lg:text-2xl"
|
|
target={siteId === site.siteId ? "_self" : "_blank"}
|
|
rel="noopener noreferrer"
|
|
>
|
|
{site.siteNm}
|
|
</a>
|
|
))}
|
|
</nav>
|
|
)}
|
|
<ScrollBar orientation="horizontal" />
|
|
</ScrollArea>
|
|
{/* 데스크톱에서 오른쪽 요소들 */}
|
|
<div className="hidden items-center gap-2 px-2 sm:flex md:px-4">
|
|
<SearchForm />
|
|
<ScreenZoomControls />
|
|
{mounted ? (
|
|
isLoggedIn && (
|
|
<Popover>
|
|
<PopoverTrigger asChild>
|
|
<Button className="group m-0 flex h-[3rem] items-center !bg-background px-2 py-0 text-label md:px-4">
|
|
<i className="diveicon di-account-circle static translate-y-0.5 pr-1 text-2xl md:pr-2 md:text-3xl" />
|
|
<span className="hidden text-sm md:inline md:text-base">
|
|
{userInfo?.userName}
|
|
</span>
|
|
<i className="diveicon di-chevron-down static p-0 transition-transform group-data-[state=open]:rotate-180" />
|
|
</Button>
|
|
</PopoverTrigger>
|
|
<PopoverContent align="end" className="w-48 border-border p-1.5">
|
|
<UserMenuContent
|
|
remainingMs={remainingMs}
|
|
onLogout={handleLogout}
|
|
/>
|
|
</PopoverContent>
|
|
</Popover>
|
|
)
|
|
) : (
|
|
<Skeleton className="mx-4 h-[3rem] w-[15rem]" />
|
|
)}
|
|
</div>
|
|
</header>
|
|
);
|
|
}
|
|
|
|
function ScreenZoomControls() {
|
|
const [scale, setScale] = useState(1);
|
|
|
|
const updateScale = (nextScale: number) => {
|
|
const boundedScale = Math.min(2, Math.max(0.5, nextScale));
|
|
document.body.style.zoom = String(boundedScale);
|
|
setScale(boundedScale);
|
|
};
|
|
|
|
return (
|
|
<div className="flex items-center gap-1" aria-label="화면 크기 조절">
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
className="size-[2.8rem] !bg-background p-2 text-foreground hover:!bg-accent"
|
|
aria-label="화면 축소"
|
|
title="화면 축소"
|
|
disabled={scale <= 0.5}
|
|
onClick={() => updateScale(Number((scale - 0.1).toFixed(1)))}
|
|
>
|
|
<Minus />
|
|
</Button>
|
|
<span className="min-w-12 text-center text-sm" aria-live="polite">
|
|
{Math.round(scale * 100)}%
|
|
</span>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
className="size-[2.8rem] !bg-background p-2 text-foreground hover:!bg-accent"
|
|
aria-label="화면 확대"
|
|
title="화면 확대"
|
|
disabled={scale >= 2}
|
|
onClick={() => updateScale(Number((scale + 0.1).toFixed(1)))}
|
|
>
|
|
<Plus />
|
|
</Button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function UserMenuContent({
|
|
remainingMs,
|
|
onLogout,
|
|
}: {
|
|
remainingMs: number | null;
|
|
onLogout: () => void;
|
|
}) {
|
|
return (
|
|
<ul>
|
|
<li className="rounded-sm px-3 py-2 text-sm text-muted-foreground">
|
|
<span className="block text-sm">로그인 만료까지</span>
|
|
<span className="block text-lg font-medium text-foreground">
|
|
{formatRemainingMs(remainingMs)}
|
|
</span>
|
|
</li>
|
|
<li className="cursor-pointer rounded-sm px-3 py-2 text-xl hover:bg-accent">
|
|
<NoticePopover />
|
|
</li>
|
|
<li
|
|
onClick={onLogout}
|
|
className="cursor-pointer rounded-sm px-3 py-2 text-xl hover:bg-accent"
|
|
>
|
|
로그아웃
|
|
</li>
|
|
</ul>
|
|
);
|
|
}
|