260615_01_FST: First Commit

This commit is contained in:
2026-06-15 09:32:24 +09:00
parent e75c28a7ba
commit 677d678e68
92 changed files with 12081 additions and 233 deletions

0
.env Normal file
View File

5
.env.development Normal file
View File

@@ -0,0 +1,5 @@
NEXT_PUBLIC_ENV=prod
NEXT_PUBLIC_API_BASE=https://test-gwcf-review.kric.com/api
ENV=prod
API_BACK_SERVER=http://127.0.0.1:6105/api/v1

5
.env.local Normal file
View File

@@ -0,0 +1,5 @@
NEXT_PUBLIC_ENV=local
NEXT_PUBLIC_API_BASE=http://localhost:6104/api
ENV=local
API_BACK_SERVER=http://localhost:6105/api/v1

5
.env.production Normal file
View File

@@ -0,0 +1,5 @@
NEXT_PUBLIC_ENV=prod
NEXT_PUBLIC_API_BASE=https://gwcf-review.kric.com/api
ENV=prod
API_BACK_SERVER=http://127.0.0.1:6105/api/v1

View File

@@ -3,7 +3,9 @@
<component name="MaterialThemeProjectNewConfig">
<option name="metadata">
<MTProjectMetadataState>
<option name="userId" value="-fc079f7:19ea484a881:-7f82" />
<option name="migrated" value="true" />
<option name="pristineConfig" value="false" />
<option name="userId" value="-7d165310:19d50f53563:-7ff9" />
</MTProjectMetadataState>
</option>
</component>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -1,26 +0,0 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}

View File

@@ -1,33 +0,0 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">{children}</body>
</html>
);
}

View File

@@ -1,65 +0,0 @@
import Image from "next/image";
export default function Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
}

View File

@@ -13,6 +13,16 @@ const eslintConfig = defineConfig([
"build/**",
"next-env.d.ts",
]),
{
rules: {
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/no-explicit-any": "warn",
"react-hooks/exhaustive-deps": "off",
"react/no-did-mount-set-state": "off",
"react/no-direct-mutation-state": "warn",
"react-hooks/set-state-in-effect":"off",
},
},
]);
export default eslintConfig;

View File

@@ -2,6 +2,8 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
output: "standalone",
reactCompiler: true,
};
export default nextConfig;

5729
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,24 +3,45 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"clean:next": "powershell -NoProfile -Command \"Remove-Item -Recurse -Force .next -ErrorAction SilentlyContinue\"",
"dev": "npm run clean:next && next dev -p 6104",
"build": "next build",
"start": "next start",
"start": "next start -p 6104",
"lint": "eslint"
},
"dependencies": {
"@tanstack/react-query": "^5.90.21",
"@tanstack/react-table": "^8.21.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"crypto-js": "^4.2.0",
"echarts": "^6.0.0",
"echarts-for-react": "^3.0.5",
"exceljs": "^4.4.0",
"jotai": "^2.16.2",
"lucide-react": "^0.562.0",
"next": "16.2.7",
"radix-ui": "^1.5.0",
"react": "19.2.4",
"react-dom": "19.2.4"
"react-dom": "19.2.4",
"shadcn": "^4.1.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.5.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@tanstack/react-query-devtools": "^5.91.3",
"@types/crypto-js": "^4.2.2",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"babel-plugin-react-compiler": "1.0.0",
"eslint": "^9",
"eslint-config-next": "16.2.7",
"postcss": "^8.5.6",
"tailwindcss": "^4",
"tw-animate-css": "^1.4.0",
"typescript": "^5"
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -1 +0,0 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

Before

Width:  |  Height:  |  Size: 391 B

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

BIN
public/logo_long.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
public/logo_short.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

Before

Width:  |  Height:  |  Size: 128 B

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

Before

Width:  |  Height:  |  Size: 385 B

View File

@@ -0,0 +1,23 @@
import MainLayout from "@/components/layout/MainLayout";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import {CookieKeys} from "@/store/cookie/cookie-keys";
export default async function MainLayoutWrapper({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const cookieStore = await cookies();
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
if (!accessToken) {
//redirect("/logout");
}
return (
<MainLayout>
{children}
</MainLayout>
);
}

View File

@@ -0,0 +1,9 @@
'use client'
const MonitoringPage = () => {
return (
<div>MonitoringPage</div>
);
}
export default MonitoringPage;

View File

@@ -0,0 +1,31 @@
'use client'
import {useAuth} from "@/hooks/useAuth";
import {useEffect} from "react";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import {useMounted} from "@/hooks/useMounted";
import {MONITORING_USER_ROLE} from "@/config/gwcf.config";
import {useRouter} from "next/navigation";
const MainPage = () => {
const router = useRouter();
const mounted = useMounted();
const { auth, isMonitoring } = useAuth();
useEffect(() => {
if(auth && auth.user){
if(isMonitoring){
router.push("/monitoring");
}
else{
router.push("/performance");
}
}
}, [auth.user])
if (!mounted) return <LoadingOverlay force />;
return null;
}
export default MainPage;

View File

@@ -0,0 +1,9 @@
'use client'
const PerformancePage = () => {
return (
<div>PerformancePage</div>
);
}
export default PerformancePage;

View File

@@ -0,0 +1,9 @@
'use client'
const UserPage = () => {
return (
<div>UserPage</div>
);
}
export default UserPage;

View File

@@ -0,0 +1,134 @@
"use client";
import Image from "next/image";
import {Button} from "@/components/ui/button";
import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {Input} from "@/components/ui/input";
import React, {useEffect, useRef, useState} from "react";
import {useRouter, useSearchParams} from "next/navigation";
import {apiError} from "@/lib/http-util";
import {useLoginMutation} from "@/query/auth";
import {NONE_HTTP_ERROR} from "@/const/common.const";
const LoginPage = () => {
const router = useRouter();
const loginMutation = useLoginMutation();
const [error, setError] = useState<string | null>(null);
const [userId, setUserId] = useState<string>("");
const [userPw, setUserPw] = useState<string>("");
const passwordInputRef = useRef<HTMLInputElement | null>(null);
const seatNumberInputRef = useRef<HTMLInputElement | null>(null);
const tryLogin = async () => {
if (!userId) return alert("아이디를 입력해 주세요");
if (!userPw) return alert("PW를 입력해 주세요");
setError(null);
try {
await loginMutation.mutateAsync({ userId, userPw });
} catch (e) {
const err = apiError(e);
if (err.status === 401 || err.status === 403) setError("아이디 또는 비밀번호를 다시 확인해주세요.");
else if (err.code === NONE_HTTP_ERROR) setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
else setError(`로그인에 실패했습니다. (${err.message})`);
}
}
useEffect(() => {
if (loginMutation.isSuccess) {
router.replace("/");
}
}, [loginMutation.isSuccess, router]);
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
passwordInputRef.current?.focus();
}
};
const handlePwKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
tryLogin();
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gwcf-login-body p-4">
<Card className="w-full max-w-md shadow-xl">
<CardHeader className="space-y-4">
<div className="flex justify-center">
<div className="w-60 h-32 flex items-center justify-center">
<Image
src="/logo_short.png" // public/kri_logo.png
alt="강원문화재단"
width={200} // 원하는 크기로 줄이기
height={200}
className="object-contain"
priority
/>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">ID</label>
<Input
id="id"
name="id"
type="text"
required
placeholder="아이디를 입력하세요"
value={userId}
onChange={(e) => setUserId(e.currentTarget.value)}
onKeyDown={handleIdKeyDown}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Password</label>
<Input
id="password"
name="password"
type="password"
autoComplete="current-password"
required
placeholder="PW를 입력하세요"
value={userPw}
onChange={(e) => setUserPw(e.currentTarget.value)}
onKeyDown={handlePwKeyDown}
ref={passwordInputRef}
/>
</div>
{error && (
<p className="text-sm text-red-500">
{error}
</p>
)}
<Button
type="submit"
className="w-full mt-6 h-11"
disabled={loginMutation.isPending}
onClick={(e) => {
e.preventDefault();
tryLogin();
}}
>
로그인
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
export default LoginPage;

View File

@@ -0,0 +1,20 @@
'use client'
import { useLogoutMutation } from "@/query/auth";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
const LogoutPage = () => {
const router = useRouter();
const logoutMutation = useLogoutMutation();
useEffect(() => {
(async () => {
await logoutMutation.mutateAsync()
router.replace("/login");
})();
}, []);
return null;
};
export default LogoutPage;

View File

@@ -0,0 +1,26 @@
import {NextRequest, NextResponse} from "next/server";
import {createBackApi} from "@/lib/server-api";
import {LoginRequest, LoginResponse} from "@/types/auth";
import {serverEnv} from "@/lib/env.server";
import {errorToResponse} from "@/lib/http-util";
export const POST = async (req: NextRequest) => {
try {
const backApi = await createBackApi();
const body = (await req.json()) as LoginRequest;
const result = await backApi.post<LoginResponse>("/auth/login", body);
const res = NextResponse.json(result.user, { status: 200 });
res.cookies.set("access_token", result.accessToken, {
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: 24 * 60 * 60, // 24시간
});
return res;
} catch (error : unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,36 @@
import {serverEnv} from "@/lib/env.server";
import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {errorToResponse} from "@/lib/http-util";
import {createBackApi} from "@/lib/server-api";
import {CookieKeys} from "@/store/cookie/cookie-keys";
export async function POST(
req: NextRequest,
context: RouteContext
) {
try {
const {slug = []} = await context.params;
const backApi = await createBackApi();
const [userId] = slug;
const url = userId
? `/auth/logout/${encodeURIComponent(userId)}`
: "/auth/logout/";
await backApi.post<boolean>(url);
const res = NextResponse.json({ ok: true });
res.cookies.set(CookieKeys.AuthToken, "", {
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: 0,
});
return res;
} catch (error: unknown) {
return errorToResponse(error);
}
}

821
src/app/globals.css Normal file
View File

@@ -0,0 +1,821 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@custom-variant dark (&:is(.dark *));
/* =============================
Tailwind v4 Theme Tokens
(shadcn/ui + custom tokens)
============================= */
@theme inline {
/* Fonts */
/* Radius scale */
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--radius-2xl: calc(var(--radius) + 8px);
--radius-3xl: calc(var(--radius) + 12px);
--radius-4xl: calc(var(--radius) + 16px);
/* Core semantic colors */
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
/* Status */
--color-success: var(--success);
--color-warning: var(--warning);
--color-info: var(--info);
--color-chart-border: var(--chart-border);
/* Sidebar (shadcn sidebar tokens) */
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
}
/* =============================
Base Tokens
============================= */
@layer base {
:root {
--radius: 0.75rem;
--content-font-size: 14px;
/* =============================
Brand Core
Gangwon Art & Culture Foundation CI
============================= */
/* Neutral / Black scale (CI Cool Gray) */
--gwcf-black-600: #1a1a1a;
--gwcf-black-500: #333333;
--gwcf-black-400: #4d4d4d;
--gwcf-black-300: #706f6f; /* CI Gray RGB 112.111.111 */
--gwcf-black-200: #a0a0a0;
--gwcf-black-150: #b0b0b0;
--gwcf-black-100: #d4d4d4;
/* Surface Gray scale */
--gwcf-gray-600: #d1d2d2;
--gwcf-gray-500: #dcdddd;
--gwcf-gray-400: #e7e6e6;
--gwcf-gray-300: #eceeee;
--gwcf-gray-200: #f3f4f4;
--gwcf-gray-100: #fafafa;
/* Table highlight tokens */
--gwcf-summary: #a8dedd; /* emerald green tint */
--gwcf-default: #d9f2f2; /* light emerald tint */
--gwcf-csi: #ffc000;
--gwcf-direct: #fff2cc;
--gwcf-indirect: #e2f0d9;
/* ── Main Color: Emerald Green (PANTONE 3262C, RGB 53.182.180) ── */
--gwcf-emerald-600: #1e9896;
--gwcf-emerald-500: #28aaa8;
--gwcf-emerald-400: #35b6b4; /* base */
--gwcf-emerald-300: #5ec7c5;
--gwcf-emerald-200: #92d9d8;
--gwcf-emerald-100: #c2ecec;
--gwcf-emerald-50: #e6f8f8;
/* ── Sub Colors ── */
--gwcf-lime: #c8d400; /* PANTONE 382C RGB 200.212.0 */
--gwcf-green: #95c11f; /* PANTONE 375C RGB 149.193.31 */
--gwcf-orange: #f7a800; /* PANTONE 143C RGB 247.168.51 */
--gwcf-pink: #e71b7b; /* PANTONE 213C RGB 231.27.123 */
--gwcf-purple: #561e7a; /* PANTONE 2597C RGB 86.33.122 */
--gwcf-deep-blue: #272154; /* PANTONE 2755C RGB 39.33.84 */
--gwcf-deep-green: #004844; /* PANTONE 3302C RGB 0.72.68 */
/* ── Metallic (nearest RGB equivalent) ── */
--gwcf-gold: #9e8246; /* PANTONE 872C */
--gwcf-silver: #8a8c8e; /* PANTONE 877C */
--gwcf-null: #9a9a9a;
/* =============================
Surface
============================= */
--background: #f7f8f8;
--foreground: #1a1a1a;
--card: #ffffff;
--card-foreground: #1a1a1a;
--popover: #ffffff;
--popover-foreground: #1a1a1a;
/* =============================
Semantic
============================= */
/* primary: GWCF Emerald Green */
--primary: #35b6b4;
--primary-foreground: #ffffff;
/* secondary: GWCF Dark (near-black) */
--secondary: #1a1a1a;
--secondary-foreground: #ffffff;
/* muted: light gray background */
--muted: #f3f4f4;
--muted-foreground: #646464;
/* accent: light emerald tint */
--accent: #e6f8f8; /* gwcf-emerald-50 */
--accent-foreground: #1e9896; /* gwcf-emerald-600 */
/* =============================
Status Colors
============================= */
--success: #1a7f3c;
--warning: #c47d00;
--info: #0072a3;
--destructive: #e03333;
/* =============================
Process Step Status
0 미진행 · 1 진행중 · 2 출발
3 도착 · 10 완료
============================= */
--status-pending: #9a9a9a; /* 0 미진행: 중립 회색 */
--status-pending-bg: #f3f4f4;
--status-pending-fg: #4d4d4d;
--status-inprogress: #f7a800; /* 1 진행중: CI Orange — 활성/주의 */
--status-inprogress-bg: #fff8e6;
--status-inprogress-fg: #a06e00;
--status-departed: #272154; /* 2 출발: CI Deep Blue — 이동 시작 */
--status-departed-bg: #ecedf7;
--status-departed-fg: #272154;
--status-arrived: #35b6b4; /* 3 도착: CI Emerald Green (메인컬러) */
--status-arrived-bg: #e6f8f8;
--status-arrived-fg: #1e9896;
--status-done: #004844; /* 10 완료: CI Deep Green — 최종 완결 */
--status-done-bg: #e0f0ef;
--status-done-fg: #004844;
/* Excel */
--excel: #1d6f42;
--excel-foreground: #ffffff;
/* =============================
Borders / Ring
============================= */
--border: #e5e6e6;
--input: #d1d2d2;
--ring: #35b6b4; /* gwcf-emerald-400 */
/* =============================
Chart Colors
Series:
1 emerald (main)
2 emerald dark
3 emerald light
4 gray/black
5~6 gray scale
7~10 sub colors (lime, orange, pink, purple)
Stack:
1~6 emerald scale
7 dark
8~10 gray scale
============================= */
--chart-1: #35b6b4; /* emerald-400 */
--chart-2: #1e9896; /* emerald-600 */
--chart-3: #92d9d8; /* emerald-200 */
--chart-4: #1a1a1a; /* black */
--chart-5: #d1d2d2; /* gray-600 */
--chart-6: #e5e6e6; /* gray-400 */
--chart-7: #c8d400; /* lime */
--chart-8: #f7a800; /* orange */
--chart-9: #e71b7b; /* pink */
--chart-10: #561e7a; /* purple */
--chart-stack-1: #1e9896; /* emerald-600 */
--chart-stack-2: #28aaa8; /* emerald-500 */
--chart-stack-3: #35b6b4; /* emerald-400 */
--chart-stack-4: #5ec7c5; /* emerald-300 */
--chart-stack-5: #92d9d8; /* emerald-200 */
--chart-stack-6: #e6f8f8; /* emerald-50 */
--chart-stack-7: #1a1a1a; /* black */
--chart-stack-8: #d1d2d2; /* gray-600 */
--chart-stack-9: #e5e6e6; /* gray-400 */
--chart-stack-10: #f3f4f4; /* gray-200 */
--chart-border: #ebebeb;
/* =============================
Sidebar
============================= */
--sidebar: #ffffff;
--sidebar-foreground: #1a1a1a;
--sidebar-primary: #35b6b4;
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #f3f4f4;
--sidebar-accent-foreground: #1a1a1a;
--sidebar-border: #e5e6e6;
--sidebar-ring: #35b6b4;
}
/* =============================
Dark Mode
============================= */
.dark {
/* Surface */
--background: #0f1a1a;
--foreground: #edf6f6;
--card: #162222;
--card-foreground: #edf6f6;
--popover: #162222;
--popover-foreground: #edf6f6;
/* primary */
--primary: #5ec7c5;
--primary-foreground: #0f1a1a;
/* secondary */
--secondary: #a0a0a0;
--secondary-foreground: #1a1a1a;
/* muted */
--muted: #1e2e2e;
--muted-foreground: #a0a0a0;
/* accent */
--accent: #0d3535;
--accent-foreground: #92d9d8; /* emerald-200 */
/* Status */
--success: #28a852;
--warning: #f0a000;
--info: #00a0d4;
--destructive: #e03333;
/* Process Step Status — dark */
--status-pending: #646464;
--status-pending-bg: #1e1e1e;
--status-pending-fg: #a0a0a0;
--status-inprogress: #f7a800;
--status-inprogress-bg: #2e2200;
--status-inprogress-fg: #ffc84a;
--status-departed: #6c6eb0;
--status-departed-bg: #1a1b2e;
--status-departed-fg: #9fa1d6;
--status-arrived: #5ec7c5;
--status-arrived-bg: #0d2e2e;
--status-arrived-fg: #92d9d8;
--status-done: #28aaa8;
--status-done-bg: #0a1f1f;
--status-done-fg: #5ec7c5;
/* Excel */
--excel: #28a852;
--excel-foreground: #ffffff;
/* Borders / Ring */
--border: #1e3030;
--input: #1e3030;
--ring: #35b6b4;
/* Chart */
--chart-1: #5ec7c5; /* emerald-300 */
--chart-2: #35b6b4; /* emerald-400 */
--chart-3: #92d9d8; /* emerald-200 */
--chart-4: #7e7e7e; /* gray */
--chart-5: #c8c8c8;
--chart-6: #4f4f4f;
--chart-7: #c8d400; /* lime */
--chart-8: #f7a800; /* orange */
--chart-9: #e71b7b; /* pink */
--chart-10: #a0a0a0;
--chart-stack-1: #1e9896; /* emerald-600 */
--chart-stack-2: #28aaa8; /* emerald-500 */
--chart-stack-3: #35b6b4; /* emerald-400 */
--chart-stack-4: #5ec7c5; /* emerald-300 */
--chart-stack-5: #92d9d8; /* emerald-200 */
--chart-stack-6: #0d3535; /* dark emerald bg */
--chart-stack-7: #edf6f6;
--chart-stack-8: #a0a0a0;
--chart-stack-9: #646464;
--chart-stack-10: #3c3c3c;
--chart-border: #1e3030;
/* Sidebar */
--sidebar: #162222;
--sidebar-foreground: #edf6f6;
--sidebar-primary: #35b6b4;
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #0d3535;
--sidebar-accent-foreground: #edf6f6;
--sidebar-border: #1e3030;
--sidebar-ring: #35b6b4;
}
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
/* =============================
Convenience Classes
(project compatibility)
============================= */
* { border-color: var(--border); }
/* Token based bg/text */
.bg-white-hover { background-color: #fff; }
.bg-white-hover:hover {
background-color: var(--primary);
color: #fff;
}
.bg-background { background-color: var(--background); }
.bg-card { background-color: var(--card); }
.bg-primary { background-color: var(--primary); }
.bg-secondary { background-color: var(--secondary); }
.bg-accent { background-color: var(--accent); }
.bg-muted { background-color: var(--muted); }
.bg-success { background-color: var(--success); }
.bg-warning { background-color: var(--warning); }
.bg-info { background-color: var(--info); }
.bg-destructive { background-color: var(--destructive); }
.bg-excel { background-color: var(--excel); }
.text-foreground { color: var(--foreground); }
.text-primary { color: var(--primary); }
.text-secondary { color: var(--secondary); }
.text-secondary-hover { color: var(--secondary); }
.text-secondary-hover:hover { color: var(--primary) !important; }
.text-primary-foreground { color: var(--primary-foreground); }
.text-muted-foreground { color: var(--muted-foreground); }
.text-success { color: var(--success); }
.text-warning { color: var(--warning); }
.text-info { color: var(--info); }
.text-destructive { color: var(--destructive); }
.text-excel { color: var(--excel); }
.text-excel-foreground { color: var(--excel-foreground); }
.border-border { border-color: var(--border); }
.text-zero { color: var(--gwcf-black-150) !important; }
.text-null { color: var(--gwcf-null) !important; }
/* GWCF neutral scale */
.bg-black-600 { background-color: var(--gwcf-black-600) !important; }
.bg-black-500 { background-color: var(--gwcf-black-500) !important; }
.bg-black-400 { background-color: var(--gwcf-black-400) !important; }
.bg-black-300 { background-color: var(--gwcf-black-300) !important; }
.bg-black-200 { background-color: var(--gwcf-black-200) !important; }
.bg-black-100 { background-color: var(--gwcf-black-100) !important; }
.bg-gray-600 { background-color: var(--gwcf-gray-600) !important; }
.bg-gray-500 { background-color: var(--gwcf-gray-500) !important; }
.bg-gray-400 { background-color: var(--gwcf-gray-400) !important; }
.bg-gray-300 { background-color: var(--gwcf-gray-300) !important; }
.bg-gray-200 { background-color: var(--gwcf-gray-200) !important; }
.bg-gray-100 { background-color: var(--gwcf-gray-100) !important; }
.border-gray-600 { border-color: var(--gwcf-gray-600) !important; }
.border-gray-500 { border-color: var(--gwcf-gray-500) !important; }
.border-gray-400 { border-color: var(--gwcf-gray-400) !important; }
.border-gray-300 { border-color: var(--gwcf-gray-300) !important; }
.border-gray-200 { border-color: var(--gwcf-gray-200) !important; }
.border-gray-100 { border-color: var(--gwcf-gray-100) !important; }
.border-black-600 { border-color: var(--gwcf-black-600) !important; }
.border-black-500 { border-color: var(--gwcf-black-500) !important; }
.border-black-400 { border-color: var(--gwcf-black-400) !important; }
.border-black-300 { border-color: var(--gwcf-black-300) !important; }
.border-black-200 { border-color: var(--gwcf-black-200) !important; }
.border-black-100 { border-color: var(--gwcf-black-100) !important; }
/* GWCF Emerald scale */
.bg-emerald-600 { background-color: var(--gwcf-emerald-600) !important; }
.bg-emerald-500 { background-color: var(--gwcf-emerald-500) !important; }
.bg-emerald-400 { background-color: var(--gwcf-emerald-400) !important; }
.bg-emerald-300 { background-color: var(--gwcf-emerald-300) !important; }
.bg-emerald-200 { background-color: var(--gwcf-emerald-200) !important; }
.bg-emerald-100 { background-color: var(--gwcf-emerald-100) !important; }
.bg-emerald-50 { background-color: var(--gwcf-emerald-50) !important; }
/* GWCF Sub Colors */
.bg-lime { background-color: var(--gwcf-lime) !important; }
.bg-gwcf-green { background-color: var(--gwcf-green) !important; }
.bg-orange { background-color: var(--gwcf-orange) !important; }
.bg-pink { background-color: var(--gwcf-pink) !important; }
.bg-purple { background-color: var(--gwcf-purple) !important; }
.bg-deep-blue { background-color: var(--gwcf-deep-blue) !important; }
.bg-deep-green { background-color: var(--gwcf-deep-green) !important; }
.bg-gold { background-color: var(--gwcf-gold) !important; }
.bg-silver { background-color: var(--gwcf-silver) !important; }
.bg-summary { background-color: var(--gwcf-summary) !important; }
.bg-default { background-color: var(--gwcf-default) !important; }
.bg-csi { background-color: var(--gwcf-csi) !important; }
.bg-direct { background-color: var(--gwcf-direct) !important; }
.bg-indirect { background-color: var(--gwcf-indirect) !important; }
.bg-null { background-color: var(--gwcf-null) !important; }
/* =============================
Process Step Status Utilities
0 미진행 · 1 진행중 · 2 출발 · 3 도착 · 10 완료
============================= */
.bg-status-pending { background-color: var(--status-pending-bg) !important; }
.bg-status-inprogress { background-color: var(--status-inprogress-bg) !important; }
.bg-status-departed { background-color: var(--status-departed-bg) !important; }
.bg-status-arrived { background-color: var(--status-arrived-bg) !important; }
.bg-status-done { background-color: var(--status-done-bg) !important; }
.text-status-pending { color: var(--status-pending-fg) !important; }
.text-status-inprogress { color: var(--status-inprogress-fg) !important; }
.text-status-departed { color: var(--status-departed-fg) !important; }
.text-status-arrived { color: var(--status-arrived-fg) !important; }
.text-status-done { color: var(--status-done-fg) !important; }
.border-status-pending { border-color: var(--status-pending) !important; }
.border-status-inprogress { border-color: var(--status-inprogress) !important; }
.border-status-departed { border-color: var(--status-departed) !important; }
.border-status-arrived { border-color: var(--status-arrived) !important; }
.border-status-done { border-color: var(--status-done) !important; }
/* =============================
Content Text Size Utilities
============================= */
.content-text-xs { font-size: calc(var(--content-font-size) * 0.75); }
.content-text-sm { font-size: calc(var(--content-font-size) * 0.875); }
.content-text-base { font-size: calc(var(--content-font-size) * 1); }
.content-text-lg { font-size: calc(var(--content-font-size) * 1.125); }
.content-text-xl { font-size: calc(var(--content-font-size) * 1.25); }
.content-text-2xl { font-size: calc(var(--content-font-size) * 1.5); }
.content-text-3xl { font-size: calc(var(--content-font-size) * 1.875); }
.content-text-4xl { font-size: calc(var(--content-font-size) * 2.25); }
@layer utilities {
.placeholder-content-text-xs::placeholder { font-size: calc(var(--content-font-size) * 0.75); }
.placeholder-content-text-sm::placeholder { font-size: calc(var(--content-font-size) * 0.875); }
.placeholder-content-text-base::placeholder { font-size: calc(var(--content-font-size) * 1); }
.placeholder-content-text-lg::placeholder { font-size: calc(var(--content-font-size) * 1.125); }
.placeholder-content-text-xl::placeholder { font-size: calc(var(--content-font-size) * 1.25); }
.placeholder-content-text-2xl::placeholder { font-size: calc(var(--content-font-size) * 1.5); }
.placeholder-content-text-3xl::placeholder { font-size: calc(var(--content-font-size) * 1.875); }
.placeholder-content-text-4xl::placeholder { font-size: calc(var(--content-font-size) * 2.25); }
.bg-gwcf-login-body {
background-color: var(--background);
background-image: linear-gradient(
135deg,
color-mix(in srgb, var(--gwcf-emerald-600) 20%, transparent) 0%,
var(--background) 30%,
var(--background) 70%,
color-mix(in srgb, var(--gwcf-emerald-600) 20%, transparent) 100%
);
}
.app-header {
background: #ffffff;
border-bottom: 1px solid rgba(35, 31, 32, 0.08);
box-shadow: 0 4px 14px rgba(35, 31, 32, 0.08);
}
.app-sidebar {
background: #ffffff;
border-right: 1px solid rgba(35, 31, 32, 0.08);
box-shadow: 4px 0 14px rgba(35, 31, 32, 0.06);
}
.text-header-color { color: var(--gwcf-black-300); }
.text-header-primary {
color: var(--gwcf-emerald-400);
font-weight: 800;
position: relative;
padding-bottom: 4px;
}
.text-header-primary::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 3px;
background: linear-gradient(90deg, var(--gwcf-emerald-400) 0%, #ffffff 100%);
border-radius: 2px 2px 0 0;
}
.text-header-secondary-hover {
color: #4f4f4f;
transition: all 0.3s ease;
cursor: pointer;
}
.text-header-secondary-hover:hover {
color: var(--gwcf-black-600) !important;
font-weight: 800;
}
.bg-gwcf-main-body {
background-color: var(--background);
background-image: linear-gradient(
135deg,
color-mix(in srgb, var(--gwcf-emerald-600) 5%, transparent) 0%,
var(--background) 30%,
var(--background) 70%,
color-mix(in srgb, var(--gwcf-emerald-600) 5%, transparent) 100%
);
}
}
/* =============================
GWCF Components
(Table / Category Card)
============================= */
@layer components {
.gwcf-table {
width: 100%;
min-width: 980px;
border-collapse: collapse;
table-layout: fixed;
border: 0px !important;
border-bottom: 1px solid var(--gwcf-black-600) !important;
background-color: #fff;
}
.gwcf-table tbody,
.gwcf-table tr {
background-color: #fff;
}
.gwcf-table th,
.gwcf-table td {
border: 1px solid var(--gwcf-black-600) !important;
background-color: inherit;
padding: 6px 12px;
font-size: 13px;
line-height: 1.15;
text-align: center;
word-wrap: break-word;
word-break: auto-phrase;
}
.gwcf-table tbody th,
.gwcf-table tbody td {
padding: 6px 12px;
}
.gwcf-table thead tr.gwcf-table__chart-row > th,
.gwcf-table thead tr.gwcf-table__chart-row > td {
border: 0 !important;
}
.gwcf-table thead tr.gwcf-table__after-chart-row > th,
.gwcf-table thead tr.gwcf-table__after-chart-row > td {
border-top: 1px solid var(--gwcf-black-600) !important;
}
.gwcf-table thead tr.gwcf-table__after-chart-row > th.gwcf-table-border-none,
.gwcf-table thead tr.gwcf-table__after-chart-row > td.gwcf-table-border-none {
border: 0 !important;
}
.gwcf-table thead th.gwcf-table-border-none,
.gwcf-table thead td.gwcf-table-border-none {
border: 0 !important;
background: transparent !important;
}
.gwcf-table thead th.gwcf-table-blank-head,
.gwcf-table thead td.gwcf-table-blank-head {
background: var(--background) !important;
border-top: 1px solid var(--background) !important;
border-left: 1px solid var(--background) !important;
}
.gwcf-table tbody th.gwcf-table-border-none,
.gwcf-table tbody td.gwcf-table-border-none {
border: 0 !important;
}
.gwcf-table thead tr.gwcf-table__group th,
.gwcf-table thead tr.gwcf-table__group th {
background-color: var(--gwcf-gray-400);
color: var(--gwcf-black-600);
font-weight: 700;
}
.gwcf-table thead tr.gwcf-table__subhead th,
.gwcf-table thead tr.gwcf-table__subhead th {
background-color: var(--gwcf-default);
color: var(--gwcf-black-600);
font-weight: 700;
}
.gwcf-table tbody th.gwcf-table__rowhead {
text-align: left;
font-weight: 700;
color: var(--foreground);
background-color: inherit;
word-wrap: break-word;
word-break: auto-phrase;
}
.gwcf-table tbody td.gwcf-table__section-row {
padding: 7px 12px;
color: var(--gwcf-black-600);
}
.gwcf-detail-table {
--gwcf-detail-table-head-height: 56px;
}
.gwcf-detail-rank-table {
--gwcf-detail-table-row-height: 56px;
min-width: 285px !important;
}
.gwcf-detail-table thead tr,
.gwcf-detail-table thead th {
height: var(--gwcf-detail-table-head-height);
}
.gwcf-detail-table tbody th,
.gwcf-detail-table tbody td {
vertical-align: middle;
height: var(--gwcf-detail-table-row-height);
}
.gwcf-detail-comment-table tbody td {
vertical-align: top;
}
.gwcf-detail-comment-table tbody td.gwcf-detail-importance-cell {
vertical-align: middle !important;
}
.gwcf-detail-importance-content {
display: flex;
min-height: 96px;
align-items: center;
justify-content: center;
}
.gwcf-num-pos {
color: var(--destructive);
}
.gwcf-num-neg {
color: #1d4ed8;
}
.gwcf-tab-content {
position: relative;
background: #fff;
border: 2px solid var(--gwcf-gray-300) !important;
border-radius: 0px 10px 10px 10px;
padding: 18px;
box-shadow: 0 6px 14px rgba(0, 0, 0, 0.25);
display: flex;
flex-direction: column;
min-height: 0;
}
.gwcf-category-card {
position: relative;
background: #fff;
border: 2px solid var(--gwcf-gray-300) !important;
border-radius: 10px;
padding: 18px;
box-shadow: 0 6px 14px rgba(0, 0, 0, 0.25);
}
.gwcf-category-card__label {
position: absolute;
top: -16px;
left: 16px;
background: var(--gwcf-black-600);
color: #fff;
padding: 6px 16px;
border-radius: 9999px;
font-weight: 800;
font-size: 13px;
letter-spacing: -0.02em;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.18);
}
.gwcf-category-card__slot {
height: 240px;
width: 100%;
}
.dark .gwcf-category-card {
background: var(--card);
border-color: var(--gwcf-gray-600) !important;
}
/* =============================
Process Step Status Badge
usage: <span class="gwcf-status-badge gwcf-status-badge--arrived">도착</span>
============================= */
.gwcf-status-badge {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 2px 10px;
border-radius: 9999px;
font-size: 12px;
font-weight: 700;
letter-spacing: -0.01em;
border: 1px solid transparent;
white-space: nowrap;
}
/* 0 미진행 */
.gwcf-status-badge--pending {
background-color: var(--status-pending-bg);
color: var(--status-pending-fg);
border-color: var(--status-pending);
}
/* 1 진행중 */
.gwcf-status-badge--inprogress {
background-color: var(--status-inprogress-bg);
color: var(--status-inprogress-fg);
border-color: var(--status-inprogress);
}
/* 2 출발 */
.gwcf-status-badge--departed {
background-color: var(--status-departed-bg);
color: var(--status-departed-fg);
border-color: var(--status-departed);
}
/* 3 도착 */
.gwcf-status-badge--arrived {
background-color: var(--status-arrived-bg);
color: var(--status-arrived-fg);
border-color: var(--status-arrived);
}
/* 10 완료 */
.gwcf-status-badge--done {
background-color: var(--status-done-bg);
color: var(--status-done-fg);
border-color: var(--status-done);
}
}

34
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,34 @@
import type { Metadata } from "next";
import { Noto_Sans_KR } from "next/font/google";
import "./globals.css";
import {Toaster} from "sonner";
import {AppProvider} from "@/components/providers/AppProvider";
const notoSansKr = Noto_Sans_KR({
weight: "variable",
display: "swap",
preload: false,
});
export const metadata: Metadata = {
title: "화재보험협회 대시보드",
description: "화재보험협회 CX 대시보드",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html
lang="ko"
className={`${notoSansKr.className} h-full antialiased`}
>
<body className="min-h-full flex flex-col">
<AppProvider>{children}</AppProvider>
<Toaster />
</body>
</html>
);
}

View File

@@ -0,0 +1,237 @@
'use client'
import * as React from 'react'
import { cn } from '@/lib/utils'
import {MultiSelect, MultiSelectRef} from '@/components/ui/multi-select'
import type { MultiSelectOption } from '@/components/ui/multi-select'
type BaseProps<T> = {
items: T[]
searchable?: boolean
searchMode?: "filter" | "inputOnly";
defaultSearchValue?: string;
onSearchValueChange?: (value: string) => void;
placeholder?: string
widthClassName?: string
heightClassName?: string
spanClassName?: string
badgeClassName?: string
className?: string
getValue?: (item: T) => string
getLabel?: (item: T) => string
/** ✅ 옵션: 원본 item을 option.info에 실어둘지 */
withInfo?: boolean
}
type KriMultiSelectProps<T = unknown> = BaseProps<T> & {
value: string[]
onChange: (value: string[]) => void
maxCount?: number
maxSelected?: number
hideSelectAll?: boolean
/** ✅ withInfo=true일 때만 의미 있게 쓰면 됨 */
onItemsChange?: (items: T[]) => void
onOptionsChange?: (options: MultiSelectOption<T>[]) => void
}
export function KriMultiSelect<T = unknown>({
items,
value,
onChange,
searchable = true,
searchMode = "filter",
defaultSearchValue = "",
onSearchValueChange,
maxCount = 1,
maxSelected,
hideSelectAll = false,
placeholder = 'Select options',
widthClassName,
heightClassName,
spanClassName = "content-text-lg",
badgeClassName = "content-text-lg",
className,
getValue,
getLabel,
withInfo = false,
onItemsChange,
onOptionsChange,
}: KriMultiSelectProps<T>) {
const msRef = React.useRef<MultiSelectRef>(null);
const extractValue = React.useCallback(
(item: T) => (getValue ? getValue(item) : String(item)),
[getValue]
)
const extractLabel = React.useCallback(
(item: T) => (getLabel ? getLabel(item) : String(item)),
[getLabel]
)
const options = React.useMemo<MultiSelectOption<T>[]>(() => {
return items.map((item) => ({
value: extractValue(item),
label: extractLabel(item),
...(withInfo ? { info: item } : {}), // ✅ 필요할 때만 info를 실음
}))
}, [items, extractValue, extractLabel, withInfo])
return (
<div className={cn(widthClassName, heightClassName, "flex-none overflow-hidden")}>
<MultiSelect<T>
ref={msRef}
options={options}
defaultValue={value}
onValueChange={onChange}
onOptionChange={onOptionsChange}
onInfoChange={onItemsChange}
maxSelected={maxSelected}
placeholder={placeholder}
className={cn("bg-white content-text-lg", className)}
spanClassName={spanClassName}
badgeClassName={badgeClassName}
searchable={searchable}
searchMode={searchMode}
defaultSearchValue={defaultSearchValue}
onSearchValueChange={onSearchValueChange}
maxCount={maxCount}
hideSelectAll={hideSelectAll}
autoSize
singleLine
resetOnDefaultValueChange
deduplicateOptions
/>
</div>
)
}
type KriSingleSelectProps<T = unknown> = BaseProps<T> & {
value: string
onChange: (value: string) => void
onItemChange?: (item: T | null) => void
onOptionChange?: (option: MultiSelectOption<T> | null) => void
preventDeselect?: boolean;
hideOptionCheck?: boolean;
useClear?: boolean
clearLabel?: string
clearValue?: string
showSelectedTooltip?: boolean
}
export function KriSingleSelect<T = unknown>({
items,
value,
onChange,
searchable = true,
searchMode = "filter",
defaultSearchValue = "",
onSearchValueChange,
placeholder = 'Select an option',
heightClassName,
widthClassName,
spanClassName = "content-text-lg",
badgeClassName = "content-text-lg",
className,
getValue,
getLabel,
withInfo = false,
onItemChange,
onOptionChange,
preventDeselect = false,
hideOptionCheck = false,
showSelectedTooltip = false,
useClear = false,
clearLabel = "선택 해제",
clearValue = "__CLEAR__",
}: KriSingleSelectProps<T>) {
const msRef = React.useRef<MultiSelectRef>(null);
const extractValue = React.useCallback(
(item: T) => (getValue ? getValue(item) : String(item)),
[getValue]
)
const extractLabel = React.useCallback(
(item: T) => (getLabel ? getLabel(item) : String(item)),
[getLabel]
)
const options = React.useMemo<MultiSelectOption<T>[]>(() => {
const special: MultiSelectOption<T>[] = [];
if (useClear) special.push({ value: clearValue, label: clearLabel });
const normal = items.map((item) => ({
value: extractValue(item),
label: extractLabel(item),
...(withInfo ? { info: item } : {}),
}));
return [...special, ...normal]
}, [items, extractValue, extractLabel, withInfo, useClear, clearLabel, clearValue])
const defaultValue = React.useMemo(() => (value ? [value] : []), [value])
const tooltipText = React.useMemo(() => {
if (!showSelectedTooltip) return undefined;
if (!value || !value) return undefined;
if (useClear && value === clearValue) return undefined;
const label = options.find(o => o.value === value)?.label;
return label ?? value; // options에 없으면 value라도 표시
}, [showSelectedTooltip, value, options, useClear, clearValue]);
return (
<div className={cn(widthClassName, heightClassName, "flex-none overflow-hidden")}>
<MultiSelect<T>
ref={msRef}
options={options}
defaultValue={defaultValue}
onValueChange={(next) => {
const v = next[0] ?? ""
if (v === clearValue) {
msRef.current?.clear();
onChange("")
onOptionChange?.(null)
onItemChange?.(null)
return
}
onChange(v)
}}
onOptionChange={(opts) => {
const opt = opts[0] ?? null
const item = withInfo ? ((opt as any)?.info ?? null) : null
onOptionChange?.(opt)
onItemChange?.(item)
}}
selectionMode="single"
maxCount={1}
maxSelected={1}
placeholder={placeholder}
className={cn("bg-white content-text-lg", className)}
spanClassName={spanClassName}
badgeClassName={badgeClassName}
searchable={searchable}
searchMode={searchMode}
defaultSearchValue={defaultSearchValue}
onSearchValueChange={onSearchValueChange}
preventDeselect={preventDeselect}
hideOptionCheck={hideOptionCheck}
hideSelectAll
autoSize
singleLine
closeOnSelect
resetOnDefaultValueChange
deduplicateOptions
/>
</div>
)
}

View File

@@ -0,0 +1,95 @@
'use client'
import type { CSSProperties } from 'react'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { cn } from '@/lib/utils'
export type KriSelectItem = {
value: string
label: string
}
type KriSelectProps<T> = {
items: T[]
value: string
onChange?: (value: string) => void
onChangeOption?: (option: T) => void
placeholder?: string
className?: string
heightClassName?: string
triggerTextClassName?: string
contentClassName?: string
itemClassName?: string
getValue?: (item: T) => string
getLabel?: (item: T) => string
useAll?: boolean
}
const HEIGHT_CLASS_VALUE: Record<string, CSSProperties['height']> = {
'h-6': '1.5rem',
'h-7': '1.75rem',
'h-8': '2rem',
'h-9': '2.25rem',
'h-10': '2.5rem',
}
export function KriSelect<T>({
items,
value,
onChange,
onChangeOption,
placeholder,
className,
heightClassName,
triggerTextClassName = 'content-text-lg',
contentClassName,
itemClassName,
getValue,
getLabel,
useAll = true,
}: Readonly<KriSelectProps<T>>) {
const extractValue = (item: T) => (getValue ? getValue(item) : String(item))
const extractLabel = (item: T) => (getLabel ? getLabel(item) : String(item))
const triggerStyle: CSSProperties | undefined = heightClassName
? { height: HEIGHT_CLASS_VALUE[heightClassName] ?? undefined }
: undefined
return (
<Select
value={value}
onValueChange={(v) => {
onChange?.(v)
const selected = items.find((item) => extractValue(item) === v)
if (selected) {
onChangeOption?.(selected)
}
}}
>
<SelectTrigger
className={cn('w-fit whitespace-nowrap bg-white', triggerTextClassName, heightClassName, className)}
style={triggerStyle}
aria-label={placeholder ?? 'select'}
>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent className={contentClassName}>
{useAll ? (
<SelectItem key="ALL" value="ALL" className={itemClassName}>
전체
</SelectItem>
) : null}
{items.map((item, idx) => {
const v = extractValue(item)
const label = extractLabel(item)
return (
<SelectItem key={v ?? idx} value={v} className={itemClassName}>
{label}
</SelectItem>
)
})}
</SelectContent>
</Select>
)
}

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-600/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

@@ -0,0 +1,19 @@
"use client";
import {useIsFetching} from "@tanstack/react-query";
import {useLoading} from "@/hooks/useLoading";
import {useEffect} from "react";
const ReactQueryLoadingSync = () => {
const fetching = useIsFetching();
const { showLoading, hideLoading } = useLoading();
useEffect(() => {
if (fetching > 0) showLoading();
else hideLoading();
}, [fetching, showLoading, hideLoading]);
return null;
};
export default ReactQueryLoadingSync;

View File

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

View File

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

View File

@@ -0,0 +1,385 @@
'use client'
import { useEffect, useState } from 'react'
import {
ChevronsLeftIcon,
ChevronLeftIcon,
ChevronRightIcon,
ChevronsRightIcon,
ArrowUp,
ArrowDown,
ArrowUpDown
} from 'lucide-react'
import type { PaginationState, SortingState, RowSelectionState } from '@tanstack/react-table'
import {
flexRender,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable
} from '@tanstack/react-table'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from '@/components/ui/pagination'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { usePagination } from './hooks/usePagination'
import { DataTableProps, DataTableColumn } from './DataTable.type'
import { cn } from '@/lib/utils'
import {usePreventClickOnDrag} from "@/components/data-table/hooks/usePreventClickOnDrag";
export function DataTable<TData>({
columns,
data,
getRowId,
highlightRowIds,
isClient = true,
pageCount: serverPageCount,
totalCount: serverTotalCount,
onPaginationChange: onServerPaginationChange,
onSortingChange: onServerSortingChange,
selectMode = 'none',
onRowClick,
onRowSelectionChange,
defaultPageSize = 10,
pageSizeOptions = [5, 10, 25, 50],
paginationItemsToDisplay = 5
}: Readonly<DataTableProps<TData>>) {
// Pagination state
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: defaultPageSize
})
// Sorting state
const [sorting, setSorting] = useState<SortingState>([])
// Row selection state
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
const drag = usePreventClickOnDrag(6);
const isNotSelection = !['none', 'click-event'].includes(selectMode);
// 서버 페이지네이션일 때 부모에게 알림
useEffect(() => {
if (!isClient && onServerPaginationChange) {
onServerPaginationChange(pagination)
}
}, [pagination, isClient, onServerPaginationChange])
// 서버 정렬일 때 부모에게 알림
useEffect(() => {
if (!isClient && onServerSortingChange) {
onServerSortingChange(sorting)
}
}, [sorting, isClient, onServerSortingChange])
// Row selection 변경 시 부모에게 알림
useEffect(() => {
if (isNotSelection && onRowSelectionChange) {
const selectedRows = table
.getSelectedRowModel()
.rows.map(row => row.original)
onRowSelectionChange(selectedRows)
}
}, [rowSelection, selectMode])
// selectMode에 따라 select column 추가
const enhancedColumns: DataTableColumn<TData, any>[] = [
...(isNotSelection
? [
{
id: 'select',
header: ({ table }) =>
selectMode === 'multi' ? (
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && 'indeterminate')
}
onCheckedChange={value => table.toggleAllPageRowsSelected(!!value)}
aria-label='KriSelect all'
/>
) : null,
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={value => {
if (selectMode === 'single') {
// single mode: 다른 것 모두 해제
table.resetRowSelection()
}
row.toggleSelected(!!value)
}}
aria-label='KriSelect row'
onClick={e => e.stopPropagation()} // row 클릭 이벤트 전파 방지
/>
),
size: 28,
enableSorting: false
} as DataTableColumn<TData, any>
]
: []),
...columns
]
// Row 클릭 핸들러
const handleRowClick = (row: any) => {
switch (selectMode) {
case 'none':
return
case 'click-event':
if (!onRowClick) return
onRowClick(row.original)
return
case 'single':
table.resetRowSelection()
row.toggleSelected(true)
return
default: // 'multi' 등
row.toggleSelected(!row.getIsSelected())
return
}
}
const table = useReactTable({
data,
columns: enhancedColumns,
pageCount: isClient ? undefined : serverPageCount,
state: {
sorting,
pagination,
rowSelection
},
enableRowSelection: isNotSelection,
onRowSelectionChange: setRowSelection,
onSortingChange: setSorting,
onPaginationChange: setPagination,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined,
manualPagination: !isClient,
manualSorting: !isClient,
enableSortingRemoval: false,
...(getRowId && { getRowId }), //있으면만 적용
})
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
currentPage: table.getState().pagination.pageIndex + 1,
totalPages: table.getPageCount(),
paginationItemsToDisplay
})
const totalCount = isClient ? data.length : (serverTotalCount || 0)
return (
<div className='w-full space-y-4'>
<div className='rounded-md border'>
<Table>
<TableHeader>
{table.getHeaderGroups().map(headerGroup => (
<TableRow key={headerGroup.id} className='hover:bg-transparent'>
{headerGroup.headers.map(header => {
const column = header.column
const canSort = column.getCanSort()
const sorted = column.getIsSorted() as false | 'asc' | 'desc'
const headerContent = header.isPlaceholder
? null
: flexRender(column.columnDef.header, header.getContext())
return (
<TableHead
key={header.id}
className={cn(
'content-text-lg font-semibold text-gray-900',
column.id === 'actions' && 'w-[140px] text-center'
)}
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
>
{header.isPlaceholder ? null : canSort ? (
<Button
type='button'
variant='ghost'
className='px-0 font-semibold content-text-lg flex items-center gap-1'
onClick={column.getToggleSortingHandler()}
>
<span>{headerContent}</span>
{sorted === 'asc' && <ArrowUp className='w-3 h-3' />}
{sorted === 'desc' && <ArrowDown className='w-3 h-3' />}
{!sorted && <ArrowUpDown className='w-3 h-3 text-muted-foreground' />}
</Button>
) : (
headerContent
)}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map(row => {
const shouldHighlight = highlightRowIds && highlightRowIds.includes(row.id)
return (
<TableRow
key={row.id}
data-state={row.getIsSelected() && 'selected'}
onPointerDown={drag.onPointerDown}
onPointerMove={drag.onPointerMove}
onPointerUp={drag.onPointerUp}
onPointerCancel={drag.onPointerCancel}
onClick={drag.wrapClick(() => handleRowClick(row))}
className={cn(
'content-text-base',
'[&>td]:py-0 [&>td]:px-2',
selectMode !== 'none' && 'cursor-pointer',
'data-[state=selected]:bg-slate-100 data-[state=selected]:font-semibold',
shouldHighlight && 'bg-emerald-50',
)}
>
{row.getVisibleCells().map(cell => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
)})
) : (
<TableRow>
<TableCell colSpan={enhancedColumns.length} className='h-24 text-center'>
데이터가 없습니다.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className='flex items-center justify-between gap-3 max-sm:flex-col p-2 pt-0'>
<p className='text-muted-foreground flex-1 text-sm whitespace-nowrap' aria-live='polite'>
Page <span className='text-foreground'>{table.getState().pagination.pageIndex + 1}</span> of{' '}
<span className='text-foreground'>{table.getPageCount()}</span>
{!isClient && totalCount > 0 && (
<span className='ml-2'>
(총 <span className='text-foreground'>{totalCount}</span>건)
</span>
)}
</p>
<div className='grow'>
<Pagination>
<PaginationContent>
<PaginationItem>
<Button
size='icon'
variant='outline'
className='disabled:pointer-events-none disabled:opacity-50'
onClick={() => table.firstPage()}
disabled={!table.getCanPreviousPage()}
aria-label='Go to first page'
>
<ChevronsLeftIcon aria-hidden='true' />
</Button>
</PaginationItem>
<PaginationItem>
<Button
size='icon'
variant='outline'
className='disabled:pointer-events-none disabled:opacity-50'
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
aria-label='Go to previous page'
>
<ChevronLeftIcon aria-hidden='true' />
</Button>
</PaginationItem>
{showLeftEllipsis && (
<PaginationItem>
<PaginationEllipsis />
</PaginationItem>
)}
{pages.map(page => {
const isActive = page === table.getState().pagination.pageIndex + 1
return (
<PaginationItem key={page}>
<Button
size='icon'
variant={isActive ? 'default' : 'ghost'}
onClick={() => table.setPageIndex(page - 1)}
aria-current={isActive ? 'page' : undefined}
>
{page}
</Button>
</PaginationItem>
)
})}
{showRightEllipsis && (
<PaginationItem>
<PaginationEllipsis />
</PaginationItem>
)}
<PaginationItem>
<Button
size='icon'
variant='outline'
className='disabled:pointer-events-none disabled:opacity-50'
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
aria-label='Go to next page'
>
<ChevronRightIcon aria-hidden='true' />
</Button>
</PaginationItem>
<PaginationItem>
<Button
size='icon'
variant='outline'
className='disabled:pointer-events-none disabled:opacity-50'
onClick={() => table.lastPage()}
disabled={!table.getCanNextPage()}
aria-label='Go to last page'
>
<ChevronsRightIcon aria-hidden='true' />
</Button>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
<div className='flex flex-1 justify-end'>
<Select
value={table.getState().pagination.pageSize.toString()}
onValueChange={value => {
table.setPageSize(Number(value))
}}
>
<SelectTrigger id='results-per-page' className='w-fit whitespace-nowrap' aria-label='Results per page'>
<SelectValue placeholder='페이지당 개수' />
</SelectTrigger>
<SelectContent>
{pageSizeOptions.map(size => (
<SelectItem key={size} value={size.toString()}>
{size} / page
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,47 @@
import { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table'
export type SelectMode = 'none' | 'click-event' | 'single' | 'multi'
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue> & {
enableSorting?: boolean // 정렬 가능 여부 (기본값: false)
}
export interface ServerPaginationParams {
pageIndex: number
pageSize: number
sorting?: SortingState
}
export interface ServerPaginationResponse<TData> {
data: TData[]
totalCount: number
pageCount: number
}
export interface DataTableProps<TData> {
// 필수 props
columns: DataTableColumn<TData, any>[]
data: TData[]
getRowId?: (row: TData, index: number) => string //id 지정
highlightRowIds?: string[]
// 페이지네이션 모드
isClient?: boolean // true: 클라이언트, false: 서버 (기본값: true)
// 서버 페이지네이션 (isClient=false일 때 필요)
pageCount?: number
totalCount?: number
onPaginationChange?: (pagination: PaginationState) => void
onSortingChange?: (sorting: SortingState) => void
// 선택 모드
selectMode?: SelectMode // 'none' | 'click-event' | 'single' | 'multi' (기본값: 'none')
onRowClick?: (selectedRows: TData) => void
onRowSelectionChange?: (selectedRows: TData[]) => void
// 페이지네이션 설정
defaultPageSize?: number
pageSizeOptions?: number[]
// 기타 설정
paginationItemsToDisplay?: number
}

View File

@@ -0,0 +1,38 @@
import { useMemo } from 'react'
interface UsePaginationProps {
currentPage: number
totalPages: number
paginationItemsToDisplay?: number
}
export function usePagination({
currentPage,
totalPages,
paginationItemsToDisplay = 5
}: UsePaginationProps) {
const { pages, showLeftEllipsis, showRightEllipsis } = useMemo(() => {
const halfDisplay = Math.floor(paginationItemsToDisplay / 2)
let startPage = Math.max(1, currentPage - halfDisplay)
let endPage = Math.min(totalPages, currentPage + halfDisplay)
if (currentPage <= halfDisplay) {
endPage = Math.min(paginationItemsToDisplay, totalPages)
}
if (currentPage > totalPages - halfDisplay) {
startPage = Math.max(1, totalPages - paginationItemsToDisplay + 1)
}
const pages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i)
return {
pages,
showLeftEllipsis: startPage > 1,
showRightEllipsis: endPage < totalPages
}
}, [currentPage, totalPages, paginationItemsToDisplay])
return { pages, showLeftEllipsis, showRightEllipsis }
}

View File

@@ -0,0 +1,48 @@
import * as React from "react";
export const usePreventClickOnDrag = (thresholdPx = 6) => {
const s = React.useRef({ x: 0, y: 0, dragging: false });
const onPointerDown = React.useCallback((e: React.PointerEvent) => {
// 좌클릭만
if (e.button !== 0) return;
s.current.x = e.clientX;
s.current.y = e.clientY;
s.current.dragging = false;
}, []);
const onPointerMove = React.useCallback(
(e: React.PointerEvent) => {
// 누르고 있을 때만
if (e.buttons === 0) return;
const dx = e.clientX - s.current.x;
const dy = e.clientY - s.current.y;
if (dx * dx + dy * dy >= thresholdPx * thresholdPx) {
s.current.dragging = true;
}
},
[thresholdPx]
);
const onPointerUp = React.useCallback(() => {
// click은 pointerup 다음에 발생하므로 "다음 tick"에 false로 복구
setTimeout(() => {
s.current.dragging = false;
}, 0);
}, []);
const wrapClick =
(fn: () => void) =>
(e: React.MouseEvent) => {
if (s.current.dragging) {
e.preventDefault();
e.stopPropagation();
return;
}
fn();
};
return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp, wrapClick };
}

View File

@@ -0,0 +1,90 @@
"use client";
import {Button} from "@/components/ui/button";
import {LogOut} from "lucide-react";
import Image from "next/image";
import {TOP_MENUS} from "@/config/menu.data";
import type {LoginUser} from "@/types/auth";
import {SITE_TITLE} from "@/config/gwcf.config";
interface HeaderProps {
userInfo: LoginUser | undefined;
isMonitoring: boolean;
activeTopId: string;
onNavigate: (path: string) => void;
}
export const Header = ({
userInfo,
isMonitoring,
activeTopId,
onNavigate,
}: HeaderProps) => {
return (
<header className="bg-white border-b border-gray-200 sticky top-0 z-40">
<div className="relative flex items-center justify-between px-4 h-16">
<div className="relative z-10 flex items-center gap-4">
{/* 로고 */}
<div className="flex items-center gap-2 cursor-pointer">
<div className="flex items-center gap-2 cursor-pointer justify-center w-16 sm:w-40">
<Image
src="/logo_short.png"
alt="강원문화재단 logo"
width={60}
height={100}
className="object-contain sm:hidden"
onClick={() => onNavigate("/")}
priority
/>
<Image
src="/logo_long.png"
alt="강원문화재단 logo"
width={150}
height={100}
className="hidden object-contain sm:block"
onClick={() => onNavigate("/")}
priority
/>
</div>
</div>
{/* 상단 메뉴 */}
{
!isMonitoring && (
<nav className="flex items-center gap-1">
{TOP_MENUS.map((m) => (
<Button
key={m.id}
variant={activeTopId === m.id ? "default" : "ghost"}
onClick={() => onNavigate(m.path)}
>
{m.label}
</Button>
))}
</nav>
)
}
</div>
<div
className="pointer-events-none absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 hidden sm:inline">
<h1 className="font-bold content-text-2xl text-header-color text-center whitespace-nowrap">{SITE_TITLE}</h1>
</div>
{/* 우측 컨트롤 */}
<div className="relative z-10 flex items-center gap-4">
<span
className="content-text-base text-header-color font-bold">
{userInfo?.userName || "박준성7957"}
</span>
<Button
variant="ghost"
size="sm"
className="gap-2 sm:bg-primary sm:text-primary-foreground sm:hover:bg-primary/90"
>
<LogOut className="w-4 h-4"/>
<span className="hidden sm:inline">로그아웃</span>
</Button>
</div>
</div>
</header>
);
};

View File

@@ -0,0 +1,61 @@
"use client";
import {ReactNode, useEffect, useState} from "react";
import { usePathname, useRouter } from "next/navigation";
import { Header } from "@/components/layout/Header";
import {TOP_MENUS} from "@/config/menu.data";
import {useAuth} from "@/hooks/useAuth";
import type {LoginUser} from "@/types/auth";
import {useMounted} from "@/hooks/useMounted";
type MainLayoutProps = {
children: ReactNode;
};
const MainLayout = ({ children }: MainLayoutProps) => {
const router = useRouter();
const pathname = usePathname();
const activeTop = TOP_MENUS.find((m) => m.match?.(pathname)) ?? TOP_MENUS[0];
const { auth, isMonitoring } = useAuth();
const mounted = useMounted();
const [userInfo, setUserInfo] = useState<LoginUser|undefined>(undefined);
useEffect(() => {
if (!mounted) return;
if(auth.user){
setUserInfo(auth.user);
}
else{
//router.replace("/logout");
}
}, [auth.user, mounted, router])
const movePage = (path: string) => {
router.push(path);
};
return (
<div
className="bg-gray-50 flex flex-col min-h-screen"
>
{/* 헤더 - 고정 폰트 크기 */}
<Header
isMonitoring={isMonitoring}
userInfo={userInfo}
activeTopId={activeTop.id}
onNavigate={movePage}
/>
{/* 본문 */}
<div className="flex flex-1 min-h-0">
{/* 메인 콘텐츠만 가변 폰트 크기 적용 */}
<main className="flex-1 p-4">
{children}
</main>
</div>
</div>
);
};
export default MainLayout;

View File

@@ -0,0 +1,33 @@
'use client'
import { Provider as JotaiProvider } from "jotai";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import ReactQueryLoadingSync from "@/components/common/ReactQueryLoadingSync";
import {useState} from "react";
import {QueryClient} from "@tanstack/query-core";
import { QueryClientProvider } from "@tanstack/react-query";
export function AppProvider({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: 1,
},
},
})
);
return (
<JotaiProvider>
<QueryClientProvider client={queryClient}>
<ReactQueryLoadingSync />
<LoadingOverlay />
{children}
</QueryClientProvider>
</JotaiProvider>
);
}

View File

@@ -0,0 +1,48 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
link: "text-primary underline-offset-4 [a&]:hover:underline",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant = "default",
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span"
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

View File

@@ -0,0 +1,64 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"cursor-pointer inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@@ -0,0 +1,32 @@
"use client"
import * as React from "react"
import { CheckIcon } from "lucide-react"
import { Checkbox as CheckboxPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View File

@@ -0,0 +1,184 @@
"use client"
import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { SearchIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
function Command({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className
)}
{...props}
/>
)
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
className,
showCloseButton = true,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn("overflow-hidden p-0", className)}
showCloseButton={showCloseButton}
>
<Command className="**:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
)
}
function CommandList({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className
)}
{...props}
/>
)
}
function CommandEmpty({
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
)
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className
)}
{...props}
/>
)
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("-mx-1 h-px bg-border", className)}
{...props}
/>
)
}
function CommandItem({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
)}
{...props}
/>
)
}
function CommandShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="command-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

View File

@@ -0,0 +1,158 @@
"use client"
import * as React from "react"
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Input }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,127 @@
import * as React from "react"
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { buttonVariants, type Button } from "@/components/ui/button"
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
role="navigation"
aria-label="pagination"
data-slot="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
)
}
function PaginationContent({
className,
...props
}: React.ComponentProps<"ul">) {
return (
<ul
data-slot="pagination-content"
className={cn("flex flex-row items-center gap-1", className)}
{...props}
/>
)
}
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
return <li data-slot="pagination-item" {...props} />
}
type PaginationLinkProps = {
isActive?: boolean
} & Pick<React.ComponentProps<typeof Button>, "size"> &
React.ComponentProps<"a">
function PaginationLink({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) {
return (
<a
aria-current={isActive ? "page" : undefined}
data-slot="pagination-link"
data-active={isActive}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className
)}
{...props}
/>
)
}
function PaginationPrevious({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
{...props}
>
<ChevronLeftIcon />
<span className="hidden sm:block">Previous</span>
</PaginationLink>
)
}
function PaginationNext({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
{...props}
>
<span className="hidden sm:block">Next</span>
<ChevronRightIcon />
</PaginationLink>
)
}
function PaginationEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
aria-hidden
data-slot="pagination-ellipsis"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontalIcon className="size-4" />
<span className="sr-only">More pages</span>
</span>
)
}
export {
Pagination,
PaginationContent,
PaginationLink,
PaginationItem,
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
}

View File

@@ -0,0 +1,89 @@
"use client"
import * as React from "react"
import { Popover as PopoverPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="popover-header"
className={cn("flex flex-col gap-1 text-sm", className)}
{...props}
/>
)
}
function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {
return (
<div
data-slot="popover-title"
className={cn("font-medium", className)}
{...props}
/>
)
}
function PopoverDescription({
className,
...props
}: React.ComponentProps<"p">) {
return (
<p
data-slot="popover-description"
className={cn("text-muted-foreground", className)}
{...props}
/>
)
}
export {
Popover,
PopoverTrigger,
PopoverContent,
PopoverAnchor,
PopoverHeader,
PopoverTitle,
PopoverDescription,
}

View File

@@ -0,0 +1,190 @@
"use client"
import * as React from "react"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { Select as SelectPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "item-aligned",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span
data-slot="select-item-indicator"
className="absolute right-2 flex size-3.5 items-center justify-center"
>
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

@@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import { Separator as SeparatorPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

116
src/components/ui/table.tsx Normal file
View File

@@ -0,0 +1,116 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

13
src/config/gwcf.config.ts Normal file
View File

@@ -0,0 +1,13 @@
export const SITE_TITLE = "강원 문화예술 지원 사업 모니터링 및 종합평가";
export const TOP_MENU_KEY_MAP: Record<string, string> = {
"performance-list":"사업정보",
"user-list":"계정관리",
}
export const TOP_MENU_PATH_MAP: Record<string, string> = {
"performance-list":"/performance",
"user-list":"/user",
}
export const MONITORING_USER_ROLE = 9003;

17
src/config/menu.data.ts Normal file
View File

@@ -0,0 +1,17 @@
import {TopMenuItem} from "@/config/menu.type";
import {TOP_MENU_KEY_MAP, TOP_MENU_PATH_MAP} from "@/config/gwcf.config";
export const TOP_MENUS: TopMenuItem[] = Object.entries(TOP_MENU_KEY_MAP).map(
([key, value]) => {
const path = `/${TOP_MENU_PATH_MAP[key].replace(/^\/+/, "")}`;
return {
id: key,
label: value,
path,
match: (pathname: string) => pathname === path,
};
}
);

6
src/config/menu.type.ts Normal file
View File

@@ -0,0 +1,6 @@
export type TopMenuItem = {
id: string;
label: string;
path: string;
match?: (pathname: string) => boolean;
};

View File

@@ -0,0 +1,3 @@
export const UNKNOWN_HTTP_ERROR = 'UNKNOWN_HTTP_ERROR';
export const NONE_HTTP_ERROR = 'NONE_HTTP_ERROR';
export const VIEW_DECIMAL_POINT = 0;

44
src/hooks/useAuth.ts Normal file
View File

@@ -0,0 +1,44 @@
"use client";
import { useCallback } from "react";
import { useAtom } from "jotai";
import { authStateAtom, type AuthState } from "@/store/jotai/auth";
import type { LoginUser } from "@/types/auth";
import {MONITORING_USER_ROLE} from "@/config/gwcf.config";
export const useAuth = () => {
const [auth, setAuth] = useAtom(authStateAtom);
// 로그인 성공 후 LoginResponse 를 바로 넣어줄 수 있게
const setFromLoginResponse = useCallback(
(res: LoginUser) => {
setAuth({
user: res
});
},
[setAuth],
);
const updateAuth = useCallback(
(next: AuthState | ((prev: AuthState) => AuthState)) => {
setAuth(next);
},
[setAuth],
);
const isMonitoring = auth.user?.userRole === MONITORING_USER_ROLE;
const logout = useCallback(() => {
setAuth({
user: null,
});
}, [setAuth]);
return {
auth,
isMonitoring,
setAuth: updateAuth,
setFromLoginResponse,
logout,
};
}

View File

@@ -0,0 +1,12 @@
import { useEffect, useState } from "react";
export function useDebouncedValue<T>(value: T, delayMs = 1200) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const t = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(t);
}, [value, delayMs]);
return debounced;
}

54
src/hooks/useDialog.ts Normal file
View File

@@ -0,0 +1,54 @@
import { useAtom } from 'jotai'
import {DialogId, openDialogIdsAtom} from "@/store/jotai/dialog";
export function useDialog() {
const [openDialogIds, setOpenDialogIds] = useAtom(openDialogIdsAtom)
/**
* 다이얼로그 열기
* @param dialogId 다이얼로그를 구분할 ID
* @param onlyThis true 이면 기존 다이얼로그 전부 닫고 이 것만 연다.
* false 이면 기존 배열에 추가한다.
*/
const showDialog = (dialogId: DialogId, onlyThis: boolean = true) => {
setOpenDialogIds(prev => {
if (onlyThis) {
// 이 다이얼로그만 열기
return [dialogId]
}
// 이미 열려 있으면 그대로
if (prev.includes(dialogId)) {
return prev
}
// 여러 개 동시에 열기 허용
return [...prev, dialogId]
})
}
/**
* 다이얼로그 닫기
*/
const hideDialog = (dialogId: DialogId) => {
setOpenDialogIds(prev => prev.filter(id => id !== dialogId))
}
/**
* 다이얼로그 열려있는지 여부
*/
const isDialogOpen = (dialogId: DialogId) => openDialogIds.includes(dialogId)
/**
* 모든 다이얼로그 닫기 (있으면 편하니까 같이 제공)
*/
const hideAll = () => setOpenDialogIds([])
return {
openDialogIds,
isDialogOpen,
showDialog,
hideDialog,
hideAll,
}
}

View File

@@ -0,0 +1,24 @@
"use client";
import { useCallback } from "react";
import { useAtom } from "jotai";
import { layoutSelectedMenuAtom } from "@/store/jotai/layout";
export const useLayoutSelectedMenu = () => {
const [selectedMenusByTopMenu, setSelectedMenusByTopMenu] = useAtom(layoutSelectedMenuAtom);
const selectMenu = useCallback(
(topMenuId: string, menuId: string) => {
setSelectedMenusByTopMenu((prev) => ({
...prev,
[topMenuId]: menuId,
}));
},
[setSelectedMenusByTopMenu],
);
return {
selectedMenusByTopMenu,
selectMenu,
};
};

56
src/hooks/useLoading.ts Normal file
View File

@@ -0,0 +1,56 @@
"use client";
import { useAtom } from "jotai";
import { useCallback } from "react";
import { loadingAtom } from "@/store/jotai/loading";
export const useLoading = () => {
const [isLoading, setIsLoading] = useAtom(loadingAtom);
const showLoading = useCallback(() => {
setIsLoading(true);
}, [setIsLoading]);
const hideLoading = useCallback(() => {
setIsLoading(false);
}, [setIsLoading]);
/**
* 비동기 함수 호출 시 편하게 쓸 수 있는 래퍼
*
* 예)
* const { withLoading } = useLoading();
* await withLoading(() => apiCall());
*/
const withLoadingAsync = useCallback(
async <T,>(fn: () => Promise<T>): Promise<T> => {
showLoading();
try {
return await fn();
} finally {
hideLoading();
}
},
[showLoading, hideLoading],
);
const withLoading = useCallback(
<T,>(fn: () => T): T => {
showLoading();
try {
return fn();
} finally {
hideLoading();
}
},
[showLoading, hideLoading],
);
return {
isLoading,
showLoading,
hideLoading,
withLoading,
withLoadingAsync,
} as const;
}

7
src/hooks/useMounted.ts Normal file
View File

@@ -0,0 +1,7 @@
import { useEffect, useState } from "react";
export const useMounted = () => {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
return mounted;
};

22
src/hooks/useResize.ts Normal file
View File

@@ -0,0 +1,22 @@
import { useEffect, useState } from "react";
export const useResizeKey = (debounceMs = 150) => {
const [key, setKey] = useState(0);
useEffect(() => {
let t: number | undefined;
const onResize = () => {
window.clearTimeout(t);
t = window.setTimeout(() => setKey((k) => k + 1), debounceMs);
};
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
window.clearTimeout(t);
};
}, [debounceMs]);
return key;
}

49
src/hooks/useStorage.ts Normal file
View File

@@ -0,0 +1,49 @@
"use client";
import {
setLocalStorage,
getLocalStorage,
removeLocalStorage,
setSessionStorage,
getSessionStorage,
removeSessionStorage,
} from "@/store/storage/secure-storage";
import { StorageKey, StorageType } from "@/store/storage/storage-keys";
/**
* 사용법:
* const { set, get, remove } = useStorage(StorageKeys.SeatNumber);
*/
export const useStorage = <T>(key: StorageKey) => {
const storageType = StorageType[key]; // "local" | "session"
const set = (value: T): void => {
if (storageType === "session") {
setSessionStorage(key, value);
} else {
setLocalStorage(key, value);
}
};
const get = (): T => {
if (storageType === "session") {
return getSessionStorage(key);
} else {
return getLocalStorage(key);
}
};
const remove = (): void => {
if (storageType === "session") {
removeSessionStorage(key);
} else {
removeLocalStorage(key);
}
};
return {
set,
get,
remove,
} as const;
};

15
src/lib/env.client.ts Normal file
View File

@@ -0,0 +1,15 @@
const required = <K extends keyof typeof RAW_PUBLIC_ENV>(name: K) => {
const v = RAW_PUBLIC_ENV[name];
if (!v) throw new Error(`Missing env: ${name}`);
return v;
};
const RAW_PUBLIC_ENV = {
NEXT_PUBLIC_ENV: process.env.NEXT_PUBLIC_ENV,
NEXT_PUBLIC_API_BASE: process.env.NEXT_PUBLIC_API_BASE,
} as const;
export const clientEnv = {
ENV: required("NEXT_PUBLIC_ENV"),
API_BASE: required("NEXT_PUBLIC_API_BASE"),
};

10
src/lib/env.server.ts Normal file
View File

@@ -0,0 +1,10 @@
const required = (name: string) => {
const v = process.env[name];
if (!v) throw new Error(`Missing env: ${name}`);
return v;
};
export const serverEnv = {
ENV: required("ENV"),
API_BACK_SERVER: required("API_BACK_SERVER"),
};

0
src/lib/gwcf-util.ts Normal file
View File

307
src/lib/http-client.ts Normal file
View File

@@ -0,0 +1,307 @@
import { clientEnv } from "@/lib/env.client";
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
export class HttpError extends Error {
public readonly status: number;
public readonly data: unknown;
public readonly url: string;
private readonly headerMap: Record<string, string>;
constructor(status: number, data: unknown, url: string, headers?: Headers) {
super(`HTTP ${status}`);
this.name = "HttpError";
this.status = status;
this.data = data;
this.url = url;
this.headerMap =
headers && typeof headers.entries === "function"
? Object.fromEntries(headers.entries())
: {};
}
get headers(): Record<string, string> {
return this.headerMap;
}
get traceId(): string | undefined {
return this.headerMap["x-trace-id"] ?? this.headerMap["x-request-id"];
}
}
export type QueryValue = string | string[] | undefined;
export type Query = Record<string, QueryValue>;
export type PathParams = Record<string, string | number | boolean>;
export type NextFetchOptions = {
revalidate?: number;
tags?: string[];
};
export type RequestOptions = {
method?: HttpMethod;
pathParams?: PathParams;
query?: Query;
json?: unknown;
rawBody?: string;
form?: FormData;
headers?: Record<string, string>;
timeoutMs?: number;
suppressAlert?: boolean;
onAuthError?: () => void;
autoLogoutOnAuthError?: boolean;
expectText?: boolean;
expectBinary?: boolean;
cache?: RequestCache; // "force-cache" | "no-store" | ...
next?: NextFetchOptions; // Next 서버 fetch 확장 옵션
};
export type HttpClientOptions = {
getToken?: () => string | null;
defaultTimeoutMs?: number;
defaultHeaders?: Record<string, string>;
setErrorMessage?: (status: number, serverMsg?: string) => string;
};
const replacePathParams = (path: string, params?: PathParams): string => {
if (!params) return path;
let out = path;
for (const [k, v] of Object.entries(params)) {
const ph = `:${k}`;
if (out.includes(ph)) out = out.replace(ph, encodeURIComponent(String(v)));
}
return out;
};
const appendQuery = (u: URL, query?: Query): void => {
if (!query) return;
for (const [k, v] of Object.entries(query)) {
if (Array.isArray(v)) v.forEach((it) => u.searchParams.append(k, it));
else if (v !== undefined) u.searchParams.set(k, v);
}
};
const buildHeaders = (base: Record<string, string>, extra?: Record<string, string>): Headers => {
const h = new Headers(base);
if (extra) for (const [k, v] of Object.entries(extra)) h.set(k, v);
return h;
};
const isAbortError = (err: unknown): boolean => {
if (!err || typeof err !== "object") return false;
const e = err as { name?: unknown; code?: unknown; message?: unknown };
return (
e.name === "AbortError" || // browser fetch abort
e.code === "ABORT_ERR" || // some runtimes
(typeof e.message === "string" && e.message.toLowerCase().includes("aborted"))
);
};
const isJsonContentType = (ctype: string) => {
const ct = (ctype ?? "").toLowerCase()
return ct.includes("application/json") || ct.includes("+json")
}
export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => {
const {
getToken,
defaultTimeoutMs = 60_000,
defaultHeaders = { "content-type": "application/json" },
setErrorMessage,
} = opts;
const request = async <T = unknown>(path: string, options: RequestOptions = {}): Promise<T> => {
const replaced = replacePathParams(path, options.pathParams);
let url: URL;
if (/^https?:\/\//i.test(replaced)) {
url = new URL(replaced);
} else if (replaced.startsWith("/")) {
const base = new URL(baseURL);
const joinedPath = `${base.pathname.replace(/\/+$/, "")}/${replaced.replace(/^\/+/, "")}`;
url = new URL(base.toString());
url.pathname = joinedPath;
} else {
url = new URL(replaced, new URL(baseURL));
}
appendQuery(url, options.query);
const base: Record<string, string> = { ...defaultHeaders };
const token = getToken?.();
if (token) base["authorization"] = `Bearer ${token}`;
const headers = buildHeaders(base, options.headers);
let body: BodyInit | undefined;
if (options.form) {
headers.delete("content-type");
body = options.form;
} else if (options.rawBody !== undefined) {
if (!headers.has("content-type")) headers.set("content-type", "text/plain;charset=utf-8");
body = options.rawBody;
} else if (options.json !== undefined) {
if (!headers.has("content-type")) headers.set("content-type", "application/json");
body = typeof options.json === "string" ? options.json : JSON.stringify(options.json);
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs);
const isServer = typeof window === "undefined";
const cacheMode: RequestCache = options.cache ?? (isServer && options.next ? "force-cache" : "no-store");
const nextOpt = isServer ? options.next : undefined;
try {
const res = await fetch(url.toString(), {
method: options.method ?? (body ? "POST" : "GET"),
headers,
body,
cache: cacheMode,
...(nextOpt ? ({ next: nextOpt } as any) : {}),
signal: controller.signal,
});
if (options.expectBinary) {
if (!res.ok) {
const rawText = await res.text().catch(() => "");
const ctype = res.headers.get("content-type") ?? ""
const isJson = isJsonContentType(ctype)
let parsedError: unknown;
if (isJson && rawText) {
try {
parsedError = JSON.parse(rawText);
} catch {
parsedError = rawText;
}
} else {
parsedError = rawText || null;
}
const autoLogout = options.autoLogoutOnAuthError ?? true;
const suppressAlert = options.suppressAlert ?? true;
if (res.status === 401) options.onAuthError?.();
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
try {
window.dispatchEvent(new CustomEvent("auth:expired"));
} catch {}
throw new HttpError(res.status, parsedError, url.toString(), res.headers);
}
if (!suppressAlert && typeof window !== "undefined") {
const serverMsg =
typeof parsedError === "object" && parsedError !== null && "message" in parsedError
? String((parsedError as { message?: unknown }).message ?? "")
: typeof parsedError === "string"
? parsedError
: undefined;
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
alert(`[${res.status}] ${msg}`);
}
throw new HttpError(res.status, parsedError, url.toString(), res.headers);
}
const buffer = await res.arrayBuffer();
return buffer as T;
}
const ctype = res.headers.get("content-type") ?? "";
const isJson = isJsonContentType(ctype)
const rawText = await res.text().catch(() => "");
const parsed: unknown = options.expectText
? rawText
: isJson
? rawText
? JSON.parse(rawText)
: null
: rawText;
if (!res.ok) {
const autoLogout = options.autoLogoutOnAuthError ?? true;
const suppressAlert = options.suppressAlert ?? true;
if (res.status === 401) options.onAuthError?.();
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
try {
window.dispatchEvent(new CustomEvent("auth:expired"));
} catch {}
throw new HttpError(res.status, parsed, url.toString(), res.headers);
}
if (!suppressAlert && typeof window !== "undefined") {
const serverMsg =
typeof parsed === "object" && parsed !== null && "message" in parsed
? String((parsed as { message?: unknown }).message ?? "")
: typeof parsed === "string"
? parsed
: undefined;
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
alert(`[${res.status}] ${msg}`);
}
throw new HttpError(res.status, parsed, url.toString(), res.headers);
}
return parsed as T;
} catch (err: unknown) {
if (isAbortError(err)) {
throw new HttpError(
408,
{ message: "요청 시간이 초과되었습니다.", timeoutMs: options.timeoutMs ?? defaultTimeoutMs },
url.toString()
);
}
let code: string | undefined;
if (typeof err === "object" && err !== null) {
const anyErr = err as { cause?: unknown; code?: unknown };
if (anyErr.cause && typeof anyErr.cause === "object") {
const cause = anyErr.cause as { code?: unknown };
if (typeof cause.code === "string") code = cause.code;
}
if (!code && typeof anyErr.code === "string") code = anyErr.code;
}
if (code === "ECONNREFUSED") {
throw new HttpError(404, { message: "백엔드 서버를 찾을 수 없습니다." }, url.toString());
}
throw err;
} finally {
clearTimeout(timer);
}
};
const get = <T = unknown>(path: string, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "GET" });
const post = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "POST", json });
const put = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PUT", json });
const patch = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PATCH", json });
const del = <T = unknown>(path: string, o?: Omit<RequestOptions, "method">) =>
request<T>(path, { ...o, method: "DELETE" });
const postForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "POST", form });
const putForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PUT", form });
return { request, get, post, put, patch, del, postForm, putForm };
};
export const nextApi = createHttpClient(clientEnv.API_BASE);

52
src/lib/http-util.ts Normal file
View File

@@ -0,0 +1,52 @@
import {NextResponse} from "next/server";
import {HttpError} from "@/lib/http-client";
import {clientEnv} from "@/lib/env.client";
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "../const/common.const";
export type ApiError = {
status: number
code: string
message: string
}
export const errorToResponse = (error: unknown) => {
if (error instanceof HttpError) {
const payload = error.data ?? { message: "서버에서 오류 응답을 받았습니다." }
return NextResponse.json(payload, { status: error.status })
}
return NextResponse.json(
{ message: "서버 내부 오류가 발생했습니다." },
{ status: 500 }
)
}
const isDev = clientEnv.ENV !== "prod"
export const apiError = (e: unknown): ApiError => {
if (e instanceof HttpError) {
const d = e.data as any
const code = typeof d?.code === "string" ? d.code : UNKNOWN_HTTP_ERROR
const message =
(typeof d?.detail === "string" && d.detail) ||
(typeof d?.message === "string" && d.message) ||
(typeof d?.errMessage === "string" && d.errMessage) ||
(typeof d === "string" && d) ||
`HTTP ${e.status}`
if (isDev) {
console.groupCollapsed(
`[API ERROR] ${e.status}${code ? ` / ${code}` : ""}`
)
console.log("url:", e.url)
if (e.traceId) console.log("traceId:", e.traceId)
console.log("raw data:", d)
console.groupEnd()
}
return { status: e.status, code, message }
}
if (isDev) console.error("[NON-HTTP ERROR]", e)
return { status: 500, code: NONE_HTTP_ERROR, message: "저장에 실패했습니다." }
}

223
src/lib/security.ts Normal file
View File

@@ -0,0 +1,223 @@
import CryptoJS from "crypto-js";
const KEY = CryptoJS.enc.Utf8.parse("kr!-Kfp@-fr0nT-CrypT0-Key-STR!!!");
const IV = CryptoJS.enc.Utf8.parse("kr!-Kfp@Dash-IV!");
const VALID_AES_KEY_BYTES = [16, 24, 32];
const AES_IV_BYTES = 16;
const validateAesConfig = () => {
const validKey = VALID_AES_KEY_BYTES.includes(KEY.sigBytes);
const validIv = IV.sigBytes === AES_IV_BYTES;
if (validKey && validIv) return;
const message = [
"AES 설정이 올바르지 않습니다.",
`KEY: ${KEY.sigBytes} bytes (허용: ${VALID_AES_KEY_BYTES.join(", ")})`,
`IV: ${IV.sigBytes} bytes (필수: ${AES_IV_BYTES})`,
].join("\n");
if (typeof window !== "undefined" && process.env.NEXT_PUBLIC_ENV === "local") {
const w = window as Window & { __kfpaCryptoConfigAlerted?: boolean };
if (!w.__kfpaCryptoConfigAlerted) {
w.__kfpaCryptoConfigAlerted = true;
alert(message);
}
}
};
validateAesConfig();
export type WordArray = CryptoJS.lib.WordArray;
export class Security {
public static encryptBase64UrlObject(input: unknown): string {
const data = JSON.stringify(input);
return this.encryptBase64Url(data);
}
public static decryptBase64UrlObject(input: string): unknown {
const data = this.decryptBase64Url(input);
return JSON.parse(data);
}
public static encryptBase64Object(input: unknown): string {
const data = JSON.stringify(input);
return this.encryptBase64(data);
}
public static decryptBase64Object(input: string): unknown {
const data = this.decryptBase64(input);
return JSON.parse(data);
}
public static encryptBase64Url(input: string): string {
const data = this.decodeUtf8(input);
const params = this.encrypt(data);
return this.encodeBase64Url(params);
}
public static decryptBase64Url(input: string): string {
const data = this.decodeBase64Url(input);
const decryptedData = this.decrypt(data);
return this.encodeUtf8(decryptedData);
}
public static encryptBase64(input: string): string {
const data = this.decodeUtf8(input);
const params = this.encrypt(data);
return this.encodeBase64(params);
}
public static decryptBase64(input: string): string {
try {
const data = this.decodeBase64(input);
const decryptedData = this.decrypt(data);
return this.encodeUtf8(decryptedData);
} catch (error) {
console.error("SecurityFunction.decryptBase64 오류:", {
input: input?.substring(0, 50) + "...", // 처음 50자만 로그
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
}
public static encrypt(input: WordArray): WordArray {
const params = CryptoJS.AES.encrypt(input, KEY, {
iv: IV,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
});
return params.ciphertext;
}
public static decrypt(input: WordArray): WordArray {
const params = CryptoJS.lib.CipherParams.create({
ciphertext: input,
});
return CryptoJS.AES.decrypt(params, KEY, {
iv: IV,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
});
}
public static convertUint8ArrayToWordArray(input: Uint8Array): WordArray {
const words: number[] = [];
let i = 0;
while (i < input.length) {
const word =
(input[i++] << 24) |
(input[i++] << 16) |
(input[i++] << 8) |
input[i++];
words.push(word);
}
return CryptoJS.lib.WordArray.create(words, words.length * 4);
}
public static convertWordArrayToUint8Array(input: WordArray): Uint8Array {
const array = new Uint8Array(input.words.length << 2);
for (let i = 0, j = 0; i < input.words.length; i++) {
const word = input.words[i];
array[j++] = word >> 24;
array[j++] = (word >> 16) & 0xff;
array[j++] = (word >> 8) & 0xff;
array[j++] = word & 0xff;
}
return array;
}
public static computeHmacSha256Hex(input: WordArray, key: WordArray): string {
return this.encodeHex(this.computeHmacSha256(input, key));
}
public static computeHmacSha256(input: WordArray, key: WordArray): WordArray {
return CryptoJS.HmacSHA256(input, key);
}
public static computeSha256Hex(input: WordArray): string {
return this.encodeHex(this.computeSha256(input));
}
public static computeSha256(input: WordArray): WordArray {
return CryptoJS.SHA256(input);
}
private static convertToSpecialChars(base64: string): string {
return Array.from(base64)
.map((char) => char.charCodeAt(0).toString(2).padStart(16, "0"))
.map((binary) => binary.replace(/0/g, "\u200b").replace(/1/g, "\u200c"))
.join("ㅤ");
}
private static convertFromSpecialChars(input: string): string {
return input
.split("ㅤ")
.map((bin) => bin.replace(/\u200b/g, "0").replace(/\u200c/g, "1"))
.map((binary) => String.fromCharCode(parseInt(binary, 2)))
.join("");
}
public static encodeBase64UrlUtf8(input: string): string {
return this.encodeBase64Url(this.decodeUtf8(input));
}
public static decodeBase64UrlUtf8(input: string): string {
return this.encodeUtf8(this.decodeBase64Url(input));
}
public static encodeBase64Url(input: WordArray): string {
return CryptoJS.enc.Base64url.stringify(input);
}
public static decodeBase64Url(input: string): WordArray {
if (this.hasSpecialChars(input)) {
const base64url = this.convertFromSpecialChars(input);
return CryptoJS.enc.Base64url.parse(base64url);
}
return CryptoJS.enc.Base64url.parse(input);
}
public static encodeBase64Utf8(input: string): string {
return this.encodeBase64(this.decodeUtf8(input));
}
public static decodeBase64Utf8(input: string): string {
return this.encodeUtf8(this.decodeBase64(input));
}
public static encodeBase64(input: WordArray): string {
return CryptoJS.enc.Base64.stringify(input);
}
public static decodeBase64(input: string): WordArray {
if (this.hasSpecialChars(input)) {
const base64 = this.convertFromSpecialChars(input);
return CryptoJS.enc.Base64.parse(base64);
}
return CryptoJS.enc.Base64.parse(input);
}
private static hasSpecialChars(input: string): boolean {
return input.includes("\u200b") || input.includes("\u200c");
}
public static encodeHex(input: WordArray): string {
return CryptoJS.enc.Hex.stringify(input);
}
public static decodeHex(input: string): WordArray {
return CryptoJS.enc.Hex.parse(input);
}
public static encodeUtf8(input: WordArray): string {
return CryptoJS.enc.Utf8.stringify(input);
}
public static decodeUtf8(input: string): WordArray {
return CryptoJS.enc.Utf8.parse(input);
}
}

20
src/lib/server-api.ts Normal file
View File

@@ -0,0 +1,20 @@
import { cookies } from "next/headers";
import { createHttpClient } from "@/lib/http-client";
import { serverEnv } from "@/lib/env.server";
const createServerApi = async (rootUrl: string, defaultHeaders?: Record<string, string>) => {
const cookieStore = await cookies();
const accessToken = cookieStore.get("access_token")?.value ?? null;
return createHttpClient(rootUrl, {
getToken: () => accessToken, // 이미 위에서 읽은 값만 참조
defaultHeaders: {
"content-type": "application/json",
...(defaultHeaders ?? {}),
},
});
};
export const createBackApi = () => {
return createServerApi(serverEnv.API_BACK_SERVER);
}

62
src/lib/utils.ts Normal file
View File

@@ -0,0 +1,62 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import {VIEW_DECIMAL_POINT} from "@/const/common.const";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export const formatKoreanBaseDate = (date = new Date()) => {
const year = String(date.getFullYear()).slice(-2);
return `${year}년 ${date.getMonth() + 1}월 ${date.getDate()}일 기준`;
};
/**
* 다양한 형식의 값을 숫자로 파싱합니다.
* - 쉼표, 퍼센트, 유니코드 마이너스 자동 처리
* - null/undefined/빈문자열/"−" 등은 null 반환
* - 유한하지 않은 숫자는 null 반환
*/
export function parseNumber(
value: unknown,
options?: {
allowComma?: boolean; // 기본값: true
allowPercent?: boolean; // 기본값: true
allowMinus?: boolean; // 기본값: true (유니코드 마이너스 포함)
}
): number | null {
const { allowComma = true, allowPercent = true, allowMinus = true } = options ?? {};
if (value === null || value === undefined) return null;
if (typeof value === "number") {
return Number.isFinite(value) ? value : null;
}
if (typeof value === "string") {
let s = value.trim();
if (s === "" || s === "-" || s === "−") return null;
s = s.replaceAll("(", "");
s = s.replaceAll(")", "");
if (allowComma) s = s.replaceAll(",", "");
if (allowPercent) s = s.replaceAll("%", "");
if (allowMinus) s = s.replaceAll("−", "-"); // 유니코드 마이너스 -> ASCII 마이너스
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
return null;
}
export const roundNumber = (num: number|null, decimalPoint?: number) => {
if(num == null) return null;
decimalPoint ??= VIEW_DECIMAL_POINT;
const factor = 10 ** decimalPoint;
return Math.round(num * factor) / factor;
};

41
src/query/auth.ts Normal file
View File

@@ -0,0 +1,41 @@
"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { nextApi } from "@/lib/http-client";
import { useAuth } from "@/hooks/useAuth";
import type { LoginUser } from "@/types/auth";
export const useLoginMutation = () => {
const { setFromLoginResponse } = useAuth();
return useMutation({
mutationFn: async (v: { userId: string; userPw: string;}) => {
return nextApi.post<LoginUser>("/login", { userId: v.userId, userPw: v.userPw }, { autoLogoutOnAuthError: false });
},
onSuccess: (data, v) => {
setFromLoginResponse(data);
},
});
}
export const useLogoutMutation = () => {
const qc = useQueryClient();
const { auth, logout } = useAuth();
return useMutation({
mutationFn: async () => {
const userId = auth.user?.userId ?? "";
try {
if (userId){
await nextApi.post(`/logout/${userId}`, null, { autoLogoutOnAuthError: false });
}
} catch (e) {
console.error(e);
}
},
onSettled: () => {
logout();
qc.clear(); // 다음 사용자/세션에 서버상태 남지 않게
},
});
}

View File

@@ -0,0 +1,105 @@
"use client";
import type { CookieKey } from "./cookie-keys";
export type CookieSetOptions = {
days?: number; // 만료일: 기본 365일
path?: string; // 기본 "/"
secure?: boolean;
sameSite?: "Lax" | "Strict" | "None";
};
function isBrowser() {
return typeof document !== "undefined";
}
function buildCookieString(
key: CookieKey,
value: string,
options: CookieSetOptions = {},
): string {
const {
days = 365,
path = "/",
secure = false,
sameSite = "Lax",
} = options;
let cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
// 만료일
if (Number.isFinite(days)) {
const expires = new Date();
expires.setDate(expires.getDate() + days);
cookie += `; Expires=${expires.toUTCString()}`;
}
if (path) {
cookie += `; Path=${path}`;
}
if (secure) {
cookie += "; Secure";
}
if (sameSite) {
cookie += `; SameSite=${sameSite}`;
}
return cookie;
}
export const cookieStore = {
/**
* 문자열 값 가져오기 (없으면 null)
*/
get(key: CookieKey): string | null {
if (!isBrowser()) return null;
try {
const name = encodeURIComponent(key) + "=";
const cookies = document.cookie ? document.cookie.split("; ") : [];
for (const c of cookies) {
if (c.startsWith(name)) {
const value = c.substring(name.length);
return decodeURIComponent(value);
}
}
return null;
} catch {
return null;
}
},
/**
* 문자열 값 저장
*/
set(key: CookieKey, value: string, options?: CookieSetOptions) {
if (!isBrowser()) return;
try {
const cookie = buildCookieString(key, value, options);
document.cookie = cookie;
} catch {
// 쿠키 설정 실패는 조용히 무시
}
},
/**
* 쿠키 삭제
*/
remove(key: CookieKey, options?: Omit<CookieSetOptions, "days">) {
if (!isBrowser()) return;
try {
document.cookie = buildCookieString(key, "", {
...(options ?? {}),
days: -1, // 과거로 설정해서 삭제
});
} catch {
// 무시
}
},
};

View File

@@ -0,0 +1,6 @@
export const CookieKeys = {
AuthToken: "kri_authToken",
// 필요하면 여기 계속 추가 (예: Theme: "kri_theme", ...)
} as const;
export type CookieKey = (typeof CookieKeys)[keyof typeof CookieKeys];

20
src/store/jotai/auth.ts Normal file
View File

@@ -0,0 +1,20 @@
"use client";
import { createLocalStorageAtom } from "@/store/jotai/utils";
import { StorageKeys } from "@/store/storage/storage-keys";
import type { LoginUser } from "@/types/auth";
export type AuthState = {
user: LoginUser | null;
};
const initialAuthState: AuthState = {
user: null,
};
/**
* AES 암호화된 localStorage 기반 로그인 상태 Atom
*/
export const authStateAtom = createLocalStorageAtom<AuthState>(
StorageKeys.AuthState,
initialAuthState,
);

View File

@@ -0,0 +1,9 @@
import { atom } from 'jotai'
// 사용할 수 있는 DialogId를 타입으로 고정
// Dialog추가 할 때만다 추가하기
export type DialogId =
| 'loginDialog'
// 현재 열려 있는 다이얼로그 ID 리스트
export const openDialogIdsAtom = atom<DialogId[]>([])

11
src/store/jotai/layout.ts Normal file
View File

@@ -0,0 +1,11 @@
"use client";
import { createLocalStorageAtom } from "@/store/jotai/utils";
import { StorageKeys } from "@/store/storage/storage-keys";
export type LayoutSelectedMenuState = Record<string, string>;
export const layoutSelectedMenuAtom = createLocalStorageAtom<LayoutSelectedMenuState>(
StorageKeys.LayoutSelectedMenu,
{},
);

View File

@@ -0,0 +1,8 @@
"use client";
import { atom } from "jotai";
/**
* 전역 로딩 상태
*/
export const loadingAtom = atom(false);

108
src/store/jotai/utils.ts Normal file
View File

@@ -0,0 +1,108 @@
"use client";
import { atom, type PrimitiveAtom } from "jotai";
import {
setLocalStorage,
getLocalStorage,
removeLocalStorage,
setSessionStorage,
getSessionStorage,
removeSessionStorage
} from "@/store/storage/secure-storage";
import {StorageKey} from "@/store/storage/storage-keys";
const loadInitialState = <T>(storageType: "local"|"session", key: StorageKey, initialValue: T): T => {
if (typeof window === "undefined") {
// SSR 시에는 그냥 기본값 사용
return initialValue;
}
const stored = storageType == "local" ? getLocalStorage(key) : getSessionStorage(key);
if (stored && typeof stored === "object") {
return stored as T;
}
return initialValue;
}
/**
* localStorage(AES 암호화) + Jotai 연동용 Atom 생성기
* - initialValue: SSR 시/최초 렌더 시 기본값
* - 마운트 후 localStorage에서 실제 값 읽어와서 덮어씀
*/
export const createLocalStorageAtom = <T>(
key: StorageKey,
initialValue: T,
) => {
const realInitialValue = loadInitialState("local", key, initialValue);
const baseAtom: PrimitiveAtom<T> = atom<T>(realInitialValue);
// 하이드레이션(저장소 주입)과 사용자 set 경합 방지용 플래그
let wasOverridden = false; // 마운트 이후 사용자가 값을 쓴 적이 있는지
const persistentAtom = atom(
(get) => get(baseAtom),
(get, set, update: T | ((prev: T) => T)) => {
const prev = get(baseAtom);
const next =
typeof update === "function"
? (update as (prev: T) => T)(prev)
: update;
// 메모리 상태 갱신
set(baseAtom, next);
// 사용자 쓰기 발생 표시 (하이드레이션이 도착해도 무시하도록)
wasOverridden = true;
if (next === null || (next as unknown) === undefined) {
// 암호화 localStorage 및 캐시 제거
removeLocalStorage(key);
} else {
// 동기 API로 캐시를 먼저 기록하고 암호화 저장은 백그라운드 처리
setLocalStorage(key, next);
}
},
);
return persistentAtom;
}
/**
* sessionStorage + Jotai 연동용 Atom 생성기
* - 탭 단위로 유지, 탭/브라우저 닫히면 삭제
* - 새로고침 시 유지
*/
export const createSessionStorageAtom = <T>(
key: StorageKey,
initialValue: T,
) => {
const realInitialValue = loadInitialState("session", key, initialValue);
const baseAtom: PrimitiveAtom<T> = atom<T>(realInitialValue);
const persistentAtom = atom(
(get) => get(baseAtom),
(get, set, update: T | ((prev: T) => T)) => {
const prev = get(baseAtom);
const next =
typeof update === "function"
? (update as (prev: T) => T)(prev)
: update;
set(baseAtom, next);
if (typeof window === "undefined") return;
try {
if (next === null || (next as unknown) === undefined) {
removeSessionStorage(key)
} else {
setSessionStorage(key, next);
}
} catch {
// sessionStorage 에러는 조용히 무시
}
},
);
return persistentAtom;
}

View File

@@ -0,0 +1,94 @@
import { Security } from "@/lib/security";
import { clientEnv } from "@/lib/env.client";
type StorageValue = any;
const parseStorageValue = (value: string): StorageValue => {
if (!value || value.trim() === "") {
return null;
}
const rawValue = clientEnv.ENV === "prod" ? Security.decryptBase64(value) : value;
if (!rawValue || rawValue.trim() === "") {
return null;
}
return JSON.parse(rawValue);
};
const stringifyStorageValue = (value: StorageValue): string => {
const rawValue = JSON.stringify(value);
return clientEnv.ENV === "prod" ? Security.encryptBase64(rawValue) : rawValue;
};
export const setLocalStorage = (key: string, value: StorageValue): void => {
try {
localStorage.setItem(key, stringifyStorageValue(value));
} catch {}
};
export const getLocalStorage = (key: string): StorageValue => {
try {
const value = localStorage.getItem(key);
if (value === null || value === "") {
return null;
}
try {
return parseStorageValue(value);
} catch {
try {
return JSON.parse(value);
} catch {
localStorage.removeItem(key);
return null;
}
}
} catch {
return null;
}
};
export const removeLocalStorage = (key: string): void => {
localStorage.removeItem(key);
};
export const clearLocalStorage = (): void => {
localStorage.clear();
};
export const setSessionStorage = (key: string, value: StorageValue): void => {
try {
sessionStorage.setItem(key, stringifyStorageValue(value));
} catch {}
};
export const getSessionStorage = (key: string): StorageValue => {
try {
const value = sessionStorage.getItem(key);
if (value === null || value === "") {
return null;
}
try {
return parseStorageValue(value);
} catch {
try {
return JSON.parse(value);
} catch {
sessionStorage.removeItem(key);
return null;
}
}
} catch {
return null;
}
};
export const removeSessionStorage = (key: string): void => {
sessionStorage.removeItem(key);
};
export const clearSessionStorage = (): void => {
sessionStorage.clear();
};

View File

@@ -0,0 +1,15 @@
export const StorageKeys = {
AuthState: "kfpa:authState",
LayoutSelectedMenu: "kfpa:layoutSelectedMenu",
//CategoriFilter: "kri:categoryFilter",
//SidebarCollapsed: "kri:sidebarCollapsed",
// 필요하면 여기 계속 추가
} as const;
export const StorageType: Record<StorageKey, "local" | "session"> = {
[StorageKeys.AuthState]: "local",
[StorageKeys.LayoutSelectedMenu]: "local",
//[StorageKeys.CategoriFilter]: "local",
};
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];

18
src/types/auth.ts Normal file
View File

@@ -0,0 +1,18 @@
export type LoginRequest = {
userId: string;
userPw: string;
};
export type LoginResponse = {
accessToken: string;
user: LoginUser;
};
export type LoginUser = {
userId: string;
userName: string;
userCmpn: string;
userTeam: string;
userRole: number;
userDetail: Record<string, string>;
};

28
src/types/common.ts Normal file
View File

@@ -0,0 +1,28 @@
export type DataVerification = {
success: boolean;
fieldName : string;
errMessage: string;
}
export type RouteContext = { params: Promise<{ slug?: string[] }> };
export type PageRequest = {
pageIndex: number;
pageSize: number;
sortBy: string;
sortDir: "asc" | "desc";
}
export type PageResponse<T> = {
content: T[];
totalElements: number;
totalPages: number;
pageIndex: number;
pageSize: number;
numberOfElements: number;
first: boolean;
last: boolean;
empty: boolean;
}
export type SelectedMap = Record<string, string>;

0
src/types/gwcf.ts Normal file
View File

View File

@@ -19,7 +19,7 @@
}
],
"paths": {
"@/*": ["./*"]
"@/*": ["./src/*"]
}
},
"include": [